id stringlengths 14 16 | text stringlengths 31 2.73k | source stringlengths 56 166 |
|---|---|---|
24c3d8478057-0 | .rst
.pdf
API References
API References#
All of LangChain’s reference documentation, in one place.
Full documentation on all methods, classes, and APIs in LangChain.
Prompts
Utilities
Chains
Agents
previous
Integrations
next
Utilities
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/reference.html |
8bd147c90de8-0 | .md
.pdf
Deployments
Contents
Streamlit
Gradio (on Hugging Face)
Beam
Vercel
SteamShip
Langchain-serve
BentoML
Deployments#
So you’ve made a really cool chain - now what? How do you deploy it and make it easily sharable with the world?
This section covers several options for that.
Note that these are meant as quick deployment options for prototypes and demos, and not for production systems.
If you are looking for help with deployment of a production system, please contact us directly.
What follows is a list of template GitHub repositories aimed that are intended to be
very easy to fork and modify to use your chain.
This is far from an exhaustive list of options, and we are EXTREMELY open to contributions here.
Streamlit#
This repo serves as a template for how to deploy a LangChain with Streamlit.
It implements a chatbot interface.
It also contains instructions for how to deploy this app on the Streamlit platform.
Gradio (on Hugging Face)#
This repo serves as a template for how deploy a LangChain with Gradio.
It implements a chatbot interface, with a “Bring-Your-Own-Token” approach (nice for not wracking up big bills).
It also contains instructions for how to deploy this app on the Hugging Face platform.
This is heavily influenced by James Weaver’s excellent examples.
Beam#
This repo serves as a template for how deploy a LangChain with Beam.
It implements a Question Answering app and contains instructions for deploying the app as a serverless REST API.
Vercel#
A minimal example on how to run LangChain on Vercel using Flask.
SteamShip#
This repository contains LangChain adapters for Steamship, enabling LangChain developers to rapidly deploy their apps on Steamship. | https://langchain-cn.readthedocs.io/en/latest/deployments.html |
8bd147c90de8-1 | This includes: production ready endpoints, horizontal scaling across dependencies, persistant storage of app state, multi-tenancy support, etc.
Langchain-serve#
This repository allows users to serve local chains and agents as RESTful, gRPC, or Websocket APIs thanks to Jina. Deploy your chains & agents with ease and enjoy independent scaling, serverless and autoscaling APIs, as well as a Streamlit playground on Jina AI Cloud.
BentoML#
This repository provides an example of how to deploy a LangChain application with BentoML. BentoML is a framework that enables the containerization of machine learning applications as standard OCI images. BentoML also allows for the automatic generation of OpenAPI and gRPC endpoints. With BentoML, you can integrate models from all popular ML frameworks and deploy them as microservices running on the most optimal hardware and scaling independently.
previous
LangChain Gallery
next
Tracing
Contents
Streamlit
Gradio (on Hugging Face)
Beam
Vercel
SteamShip
Langchain-serve
BentoML
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/deployments.html |
fe9bdd36e5c4-0 | .rst
.pdf
LangChain Ecosystem
LangChain Ecosystem#
Guides for how other companies/products can be used with LangChain
AI21 Labs
Aim
Apify
AtlasDB
Banana
CerebriumAI
Chroma
ClearML Integration
Cohere
Comet
Databerry
DeepInfra
Deep Lake
ForefrontAI
Google Search Wrapper
Google Serper Wrapper
GooseAI
GPT4All
Graphsignal
Hazy Research
Helicone
Hugging Face
Jina
Llama.cpp
Milvus
Modal
NLPCloud
OpenAI
OpenSearch
Petals
PGVector
Pinecone
PromptLayer
Qdrant
Replicate
Runhouse
RWKV-4
SearxNG Search API
SerpAPI
StochasticAI
Unstructured
Weights & Biases
Weaviate
Wolfram Alpha Wrapper
Writer
Zilliz
previous
Agents
next
AI21 Labs
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/ecosystem.html |
e295932341ec-0 | Index
_
| A
| B
| C
| D
| E
| F
| G
| H
| I
| J
| K
| L
| M
| N
| O
| P
| Q
| R
| S
| T
| U
| V
| W
| Z
_
__call__() (langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
A | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-1 | (langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
A
aadd_documents() (langchain.vectorstores.VectorStore method)
aadd_texts() (langchain.vectorstores.VectorStore method)
aapply() (langchain.chains.LLMChain method)
aapply_and_parse() (langchain.chains.LLMChain method)
add() (langchain.docstore.InMemoryDocstore method)
add_documents() (langchain.vectorstores.VectorStore method)
add_embeddings() (langchain.vectorstores.FAISS method)
add_example() (langchain.prompts.example_selector.LengthBasedExampleSelector method)
(langchain.prompts.example_selector.SemanticSimilarityExampleSelector method)
add_texts() (langchain.vectorstores.AtlasDB method)
(langchain.vectorstores.Chroma method)
(langchain.vectorstores.DeepLake method)
(langchain.vectorstores.ElasticVectorSearch method)
(langchain.vectorstores.FAISS method)
(langchain.vectorstores.Milvus method)
(langchain.vectorstores.OpenSearchVectorSearch method)
(langchain.vectorstores.Pinecone method)
(langchain.vectorstores.Qdrant method)
(langchain.vectorstores.VectorStore method)
(langchain.vectorstores.Weaviate method)
afrom_documents() (langchain.vectorstores.VectorStore class method)
afrom_texts() (langchain.vectorstores.VectorStore class method)
agenerate() (langchain.chains.LLMChain method)
(langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-2 | (langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
agenerate_prompt() (langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-3 | (langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
agent (langchain.agents.AgentExecutor attribute)
(langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute)
AgentType (class in langchain.agents)
ai_prefix (langchain.agents.ConversationalAgent attribute)
aiosession (langchain.serpapi.SerpAPIWrapper attribute)
(langchain.utilities.searx_search.SearxSearchWrapper attribute)
aleph_alpha_api_key (langchain.llms.AlephAlpha attribute)
allowed_tools (langchain.agents.Agent attribute)
(langchain.agents.ReActTextWorldAgent attribute)
(langchain.agents.ZeroShotAgent attribute)
amax_marginal_relevance_search() (langchain.vectorstores.VectorStore method)
amax_marginal_relevance_search_by_vector() (langchain.vectorstores.VectorStore method)
answers (langchain.utilities.searx_search.SearxResults property)
api_answer_chain (langchain.chains.APIChain attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-4 | api_answer_chain (langchain.chains.APIChain attribute)
api_docs (langchain.chains.APIChain attribute)
api_operation (langchain.chains.OpenAPIEndpointChain attribute)
api_request_chain (langchain.chains.APIChain attribute)
(langchain.chains.OpenAPIEndpointChain attribute)
api_response_chain (langchain.chains.OpenAPIEndpointChain attribute)
api_url (langchain.llms.StochasticAI attribute)
aplan() (langchain.agents.Agent method)
(langchain.agents.BaseMultiActionAgent method)
(langchain.agents.BaseSingleActionAgent method)
(langchain.agents.LLMSingleActionAgent method)
apply() (langchain.chains.LLMChain method)
apply_and_parse() (langchain.chains.LLMChain method)
apredict() (langchain.chains.LLMChain method)
apredict_and_parse() (langchain.chains.LLMChain method)
aprep_prompts() (langchain.chains.LLMChain method)
are_all_true_prompt (langchain.chains.LLMSummarizationCheckerChain attribute)
aresults() (langchain.utilities.searx_search.SearxSearchWrapper method)
arun() (langchain.serpapi.SerpAPIWrapper method)
(langchain.utilities.searx_search.SearxSearchWrapper method)
as_retriever() (langchain.vectorstores.VectorStore method)
asimilarity_search() (langchain.vectorstores.VectorStore method)
asimilarity_search_by_vector() (langchain.vectorstores.VectorStore method)
AtlasDB (class in langchain.vectorstores)
B
bad_words (langchain.llms.NLPCloud attribute)
base_embeddings (langchain.chains.HypotheticalDocumentEmbedder attribute)
base_url (langchain.llms.AI21 attribute)
(langchain.llms.ForefrontAI attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-5 | (langchain.llms.ForefrontAI attribute)
(langchain.llms.Writer attribute)
batch_size (langchain.llms.AzureOpenAI attribute)
beam_search_diversity_rate (langchain.llms.Writer attribute)
beam_width (langchain.llms.Writer attribute)
best_of (langchain.llms.AlephAlpha attribute)
(langchain.llms.AzureOpenAI attribute)
C
callback_manager (langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute)
categories (langchain.utilities.searx_search.SearxSearchWrapper attribute)
chain (langchain.chains.ConstitutionalChain attribute)
chains (langchain.chains.SequentialChain attribute)
(langchain.chains.SimpleSequentialChain attribute)
CharacterTextSplitter (class in langchain.text_splitter)
CHAT_CONVERSATIONAL_REACT_DESCRIPTION (langchain.agents.AgentType attribute)
CHAT_ZERO_SHOT_REACT_DESCRIPTION (langchain.agents.AgentType attribute)
CHAT_ZERO_SHOT_REACT_DESCRIPTION_V2 (langchain.agents.AgentType attribute)
check_assertions_prompt (langchain.chains.LLMCheckerChain attribute)
(langchain.chains.LLMSummarizationCheckerChain attribute)
Chroma (class in langchain.vectorstores)
CHUNK_LEN (langchain.llms.RWKV attribute)
chunk_size (langchain.embeddings.OpenAIEmbeddings attribute)
client (langchain.llms.Petals attribute)
combine_docs_chain (langchain.chains.AnalyzeDocumentChain attribute)
combine_documents_chain (langchain.chains.MapReduceChain attribute)
combine_embeddings() (langchain.chains.HypotheticalDocumentEmbedder method)
completion_bias_exclusion_first_token_only (langchain.llms.AlephAlpha attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-6 | completion_bias_exclusion_first_token_only (langchain.llms.AlephAlpha attribute)
compress_to_size (langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding attribute)
constitutional_principles (langchain.chains.ConstitutionalChain attribute)
construct() (langchain.llms.AI21 class method)
(langchain.llms.AlephAlpha class method)
(langchain.llms.Anthropic class method)
(langchain.llms.AzureOpenAI class method)
(langchain.llms.Banana class method)
(langchain.llms.CerebriumAI class method)
(langchain.llms.Cohere class method)
(langchain.llms.DeepInfra class method)
(langchain.llms.ForefrontAI class method)
(langchain.llms.GooseAI class method)
(langchain.llms.GPT4All class method)
(langchain.llms.HuggingFaceEndpoint class method)
(langchain.llms.HuggingFaceHub class method)
(langchain.llms.HuggingFacePipeline class method)
(langchain.llms.LlamaCpp class method)
(langchain.llms.Modal class method)
(langchain.llms.NLPCloud class method)
(langchain.llms.OpenAI class method)
(langchain.llms.OpenAIChat class method)
(langchain.llms.Petals class method)
(langchain.llms.PromptLayerOpenAI class method)
(langchain.llms.PromptLayerOpenAIChat class method)
(langchain.llms.Replicate class method)
(langchain.llms.RWKV class method)
(langchain.llms.SagemakerEndpoint class method)
(langchain.llms.SelfHostedHuggingFaceLLM class method)
(langchain.llms.SelfHostedPipeline class method)
(langchain.llms.StochasticAI class method)
(langchain.llms.Writer class method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-7 | (langchain.llms.StochasticAI class method)
(langchain.llms.Writer class method)
content_handler (langchain.embeddings.SagemakerEndpointEmbeddings attribute)
(langchain.llms.SagemakerEndpoint attribute)
CONTENT_KEY (langchain.vectorstores.Qdrant attribute)
contextual_control_threshold (langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding attribute)
(langchain.llms.AlephAlpha attribute)
control_log_additive (langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding attribute)
(langchain.llms.AlephAlpha attribute)
CONVERSATIONAL_REACT_DESCRIPTION (langchain.agents.AgentType attribute)
copy() (langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-8 | (langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
coroutine (langchain.agents.Tool attribute)
countPenalty (langchain.llms.AI21 attribute)
create_assertions_prompt (langchain.chains.LLMSummarizationCheckerChain attribute)
create_csv_agent() (in module langchain.agents)
create_documents() (langchain.text_splitter.TextSplitter method)
create_draft_answer_prompt (langchain.chains.LLMCheckerChain attribute)
create_index() (langchain.vectorstores.AtlasDB method)
create_json_agent() (in module langchain.agents)
create_llm_result() (langchain.llms.AzureOpenAI method)
(langchain.llms.OpenAI method)
(langchain.llms.PromptLayerOpenAI method)
create_openapi_agent() (in module langchain.agents)
create_outputs() (langchain.chains.LLMChain method)
create_pandas_dataframe_agent() (in module langchain.agents)
create_prompt() (langchain.agents.Agent class method)
(langchain.agents.ConversationalAgent class method)
(langchain.agents.ConversationalChatAgent class method)
(langchain.agents.ReActTextWorldAgent class method)
(langchain.agents.ZeroShotAgent class method)
create_sql_agent() (in module langchain.agents)
create_vectorstore_agent() (in module langchain.agents)
create_vectorstore_router_agent() (in module langchain.agents)
credentials_profile_name (langchain.embeddings.SagemakerEndpointEmbeddings attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-9 | credentials_profile_name (langchain.embeddings.SagemakerEndpointEmbeddings attribute)
(langchain.llms.SagemakerEndpoint attribute)
critique_chain (langchain.chains.ConstitutionalChain attribute)
D
database (langchain.chains.SQLDatabaseChain attribute)
decider_chain (langchain.chains.SQLDatabaseSequentialChain attribute)
DeepLake (class in langchain.vectorstores)
delete() (langchain.vectorstores.DeepLake method)
delete_collection() (langchain.vectorstores.Chroma method)
delete_dataset() (langchain.vectorstores.DeepLake method)
deployment_name (langchain.llms.AzureOpenAI attribute)
description (langchain.agents.Tool attribute)
deserialize_json_input() (langchain.chains.OpenAPIEndpointChain method)
device (langchain.llms.SelfHostedHuggingFaceLLM attribute)
dict() (langchain.agents.BaseMultiActionAgent method)
(langchain.agents.BaseSingleActionAgent method)
(langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-10 | (langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
(langchain.prompts.BasePromptTemplate method)
(langchain.prompts.FewShotPromptTemplate method)
(langchain.prompts.FewShotPromptWithTemplates method)
do_sample (langchain.llms.NLPCloud attribute)
(langchain.llms.Petals attribute)
E
early_stopping (langchain.llms.NLPCloud attribute)
early_stopping_method (langchain.agents.AgentExecutor attribute)
(langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute)
echo (langchain.llms.AlephAlpha attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
ElasticVectorSearch (class in langchain.vectorstores)
embed_documents() (langchain.chains.HypotheticalDocumentEmbedder method)
(langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding method)
(langchain.embeddings.AlephAlphaSymmetricSemanticEmbedding method)
(langchain.embeddings.CohereEmbeddings method)
(langchain.embeddings.FakeEmbeddings method)
(langchain.embeddings.HuggingFaceEmbeddings method)
(langchain.embeddings.HuggingFaceHubEmbeddings method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-11 | (langchain.embeddings.HuggingFaceHubEmbeddings method)
(langchain.embeddings.HuggingFaceInstructEmbeddings method)
(langchain.embeddings.LlamaCppEmbeddings method)
(langchain.embeddings.OpenAIEmbeddings method)
(langchain.embeddings.SagemakerEndpointEmbeddings method)
(langchain.embeddings.SelfHostedEmbeddings method)
(langchain.embeddings.SelfHostedHuggingFaceInstructEmbeddings method)
(langchain.embeddings.TensorflowHubEmbeddings method)
embed_instruction (langchain.embeddings.HuggingFaceInstructEmbeddings attribute)
(langchain.embeddings.SelfHostedHuggingFaceInstructEmbeddings attribute)
embed_query() (langchain.chains.HypotheticalDocumentEmbedder method)
(langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding method)
(langchain.embeddings.AlephAlphaSymmetricSemanticEmbedding method)
(langchain.embeddings.CohereEmbeddings method)
(langchain.embeddings.FakeEmbeddings method)
(langchain.embeddings.HuggingFaceEmbeddings method)
(langchain.embeddings.HuggingFaceHubEmbeddings method)
(langchain.embeddings.HuggingFaceInstructEmbeddings method)
(langchain.embeddings.LlamaCppEmbeddings method)
(langchain.embeddings.OpenAIEmbeddings method)
(langchain.embeddings.SagemakerEndpointEmbeddings method)
(langchain.embeddings.SelfHostedEmbeddings method)
(langchain.embeddings.SelfHostedHuggingFaceInstructEmbeddings method)
(langchain.embeddings.TensorflowHubEmbeddings method)
embedding (langchain.llms.GPT4All attribute)
endpoint_kwargs (langchain.embeddings.SagemakerEndpointEmbeddings attribute)
(langchain.llms.SagemakerEndpoint attribute)
endpoint_name (langchain.embeddings.SagemakerEndpointEmbeddings attribute)
(langchain.llms.SagemakerEndpoint attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-12 | (langchain.llms.SagemakerEndpoint attribute)
endpoint_url (langchain.llms.CerebriumAI attribute)
(langchain.llms.ForefrontAI attribute)
(langchain.llms.HuggingFaceEndpoint attribute)
(langchain.llms.Modal attribute)
engines (langchain.utilities.searx_search.SearxSearchWrapper attribute)
entity_extraction_chain (langchain.chains.GraphQAChain attribute)
error (langchain.chains.OpenAIModerationChain attribute)
example_keys (langchain.prompts.example_selector.SemanticSimilarityExampleSelector attribute)
example_prompt (langchain.prompts.example_selector.LengthBasedExampleSelector attribute)
(langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
example_selector (langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
example_separator (langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
examples (langchain.prompts.example_selector.LengthBasedExampleSelector attribute)
(langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
F
f16_kv (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
FAISS (class in langchain.vectorstores)
fetch_k (langchain.prompts.example_selector.MaxMarginalRelevanceExampleSelector attribute)
finish_tool_name (langchain.agents.Agent property)
(langchain.agents.ConversationalAgent property)
format() (langchain.prompts.BaseChatPromptTemplate method)
(langchain.prompts.BasePromptTemplate method)
(langchain.prompts.ChatPromptTemplate method)
(langchain.prompts.FewShotPromptTemplate method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-13 | (langchain.prompts.FewShotPromptTemplate method)
(langchain.prompts.FewShotPromptWithTemplates method)
(langchain.prompts.PromptTemplate method)
format_messages() (langchain.prompts.BaseChatPromptTemplate method)
(langchain.prompts.ChatPromptTemplate method)
(langchain.prompts.MessagesPlaceholder method)
format_prompt() (langchain.prompts.BaseChatPromptTemplate method)
(langchain.prompts.BasePromptTemplate method)
(langchain.prompts.StringPromptTemplate method)
frequency_penalty (langchain.llms.AlephAlpha attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.Cohere attribute)
(langchain.llms.GooseAI attribute)
frequencyPenalty (langchain.llms.AI21 attribute)
from_agent_and_tools() (langchain.agents.AgentExecutor class method)
from_api_operation() (langchain.chains.OpenAPIEndpointChain class method)
from_chains() (langchain.agents.MRKLChain class method)
from_colored_object_prompt() (langchain.chains.PALChain class method)
from_documents() (langchain.vectorstores.AtlasDB class method)
(langchain.vectorstores.Chroma class method)
(langchain.vectorstores.VectorStore class method)
from_embeddings() (langchain.vectorstores.FAISS class method)
from_examples() (langchain.prompts.example_selector.MaxMarginalRelevanceExampleSelector class method)
(langchain.prompts.example_selector.SemanticSimilarityExampleSelector class method)
(langchain.prompts.PromptTemplate class method)
from_existing_index() (langchain.vectorstores.Pinecone class method)
from_file() (langchain.prompts.PromptTemplate class method)
from_huggingface_tokenizer() (langchain.text_splitter.TextSplitter class method)
from_llm() (langchain.chains.ChatVectorDBChain class method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-14 | from_llm() (langchain.chains.ChatVectorDBChain class method)
(langchain.chains.ConstitutionalChain class method)
(langchain.chains.ConversationalRetrievalChain class method)
(langchain.chains.GraphQAChain class method)
(langchain.chains.HypotheticalDocumentEmbedder class method)
(langchain.chains.QAGenerationChain class method)
(langchain.chains.SQLDatabaseSequentialChain class method)
from_llm_and_api_docs() (langchain.chains.APIChain class method)
from_llm_and_tools() (langchain.agents.Agent class method)
(langchain.agents.BaseSingleActionAgent class method)
(langchain.agents.ConversationalAgent class method)
(langchain.agents.ConversationalChatAgent class method)
(langchain.agents.ZeroShotAgent class method)
from_math_prompt() (langchain.chains.PALChain class method)
from_model_id() (langchain.llms.HuggingFacePipeline class method)
from_params() (langchain.chains.MapReduceChain class method)
from_pipeline() (langchain.llms.SelfHostedHuggingFaceLLM class method)
(langchain.llms.SelfHostedPipeline class method)
from_string() (langchain.chains.LLMChain class method)
from_template() (langchain.prompts.PromptTemplate class method)
from_texts() (langchain.vectorstores.AtlasDB class method)
(langchain.vectorstores.Chroma class method)
(langchain.vectorstores.DeepLake class method)
(langchain.vectorstores.ElasticVectorSearch class method)
(langchain.vectorstores.FAISS class method)
(langchain.vectorstores.Milvus class method)
(langchain.vectorstores.OpenSearchVectorSearch class method)
(langchain.vectorstores.Pinecone class method)
(langchain.vectorstores.Qdrant class method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-15 | (langchain.vectorstores.Qdrant class method)
(langchain.vectorstores.VectorStore class method)
(langchain.vectorstores.Weaviate class method)
from_tiktoken_encoder() (langchain.text_splitter.TextSplitter class method)
from_url_and_method() (langchain.chains.OpenAPIEndpointChain class method)
func (langchain.agents.Tool attribute)
G
generate() (langchain.chains.LLMChain method)
(langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-16 | (langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
generate_prompt() (langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
get_all_tool_names() (in module langchain.agents)
get_allowed_tools() (langchain.agents.Agent method)
(langchain.agents.BaseMultiActionAgent method)
(langchain.agents.BaseSingleActionAgent method)
get_answer_expr (langchain.chains.PALChain attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-17 | get_answer_expr (langchain.chains.PALChain attribute)
get_full_inputs() (langchain.agents.Agent method)
get_num_tokens() (langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
get_num_tokens_from_messages() (langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-18 | (langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
get_params() (langchain.serpapi.SerpAPIWrapper method)
get_principles() (langchain.chains.ConstitutionalChain class method)
get_sub_prompts() (langchain.llms.AzureOpenAI method)
(langchain.llms.OpenAI method)
(langchain.llms.PromptLayerOpenAI method)
get_text_length (langchain.prompts.example_selector.LengthBasedExampleSelector attribute)
globals (langchain.python.PythonREPL attribute)
graph (langchain.chains.GraphQAChain attribute)
H | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-19 | graph (langchain.chains.GraphQAChain attribute)
H
hardware (langchain.embeddings.SelfHostedHuggingFaceEmbeddings attribute)
(langchain.llms.SelfHostedHuggingFaceLLM attribute)
(langchain.llms.SelfHostedPipeline attribute)
headers (langchain.utilities.searx_search.SearxSearchWrapper attribute)
hosting (langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding attribute)
I
inference_fn (langchain.embeddings.SelfHostedEmbeddings attribute)
(langchain.embeddings.SelfHostedHuggingFaceEmbeddings attribute)
(langchain.llms.SelfHostedHuggingFaceLLM attribute)
(langchain.llms.SelfHostedPipeline attribute)
inference_kwargs (langchain.embeddings.SelfHostedEmbeddings attribute)
initialize_agent() (in module langchain.agents)
InMemoryDocstore (class in langchain.docstore)
input_key (langchain.chains.QAGenerationChain attribute)
input_keys (langchain.chains.ConstitutionalChain property)
(langchain.chains.ConversationChain property)
(langchain.chains.HypotheticalDocumentEmbedder property)
(langchain.chains.QAGenerationChain property)
(langchain.prompts.example_selector.SemanticSimilarityExampleSelector attribute)
input_variables (langchain.chains.SequentialChain attribute)
(langchain.chains.TransformChain attribute)
(langchain.prompts.BasePromptTemplate attribute)
(langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
(langchain.prompts.MessagesPlaceholder property)
(langchain.prompts.PromptTemplate attribute)
J
json() (langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-20 | (langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
K
k (langchain.chains.QAGenerationChain attribute)
(langchain.chains.VectorDBQA attribute)
(langchain.chains.VectorDBQAWithSourcesChain attribute)
(langchain.llms.Cohere attribute)
(langchain.prompts.example_selector.SemanticSimilarityExampleSelector attribute)
(langchain.utilities.searx_search.SearxSearchWrapper attribute)
L
langchain.agents
module
langchain.chains
module
langchain.docstore
module | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-21 | langchain.chains
module
langchain.docstore
module
langchain.embeddings
module
langchain.llms
module
langchain.prompts
module
langchain.prompts.example_selector
module
langchain.python
module
langchain.serpapi
module
langchain.text_splitter
module
langchain.utilities.searx_search
module
langchain.vectorstores
module
last_n_tokens_size (langchain.llms.LlamaCpp attribute)
LatexTextSplitter (class in langchain.text_splitter)
length (langchain.llms.ForefrontAI attribute)
(langchain.llms.Writer attribute)
length_no_input (langchain.llms.NLPCloud attribute)
length_penalty (langchain.llms.NLPCloud attribute)
length_pentaly (langchain.llms.Writer attribute)
list_assertions_prompt (langchain.chains.LLMCheckerChain attribute)
llm (langchain.chains.LLMBashChain attribute)
(langchain.chains.LLMChain attribute)
(langchain.chains.LLMCheckerChain attribute)
(langchain.chains.LLMMathChain attribute)
(langchain.chains.LLMSummarizationCheckerChain attribute)
(langchain.chains.PALChain attribute)
(langchain.chains.SQLDatabaseChain attribute)
llm_chain (langchain.agents.Agent attribute)
(langchain.agents.LLMSingleActionAgent attribute)
(langchain.agents.ReActTextWorldAgent attribute)
(langchain.agents.ZeroShotAgent attribute)
(langchain.chains.HypotheticalDocumentEmbedder attribute)
(langchain.chains.LLMRequestsChain attribute)
(langchain.chains.QAGenerationChain attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-22 | (langchain.chains.QAGenerationChain attribute)
llm_prefix (langchain.agents.Agent property)
(langchain.agents.ConversationalAgent property)
(langchain.agents.ConversationalChatAgent property)
(langchain.agents.ZeroShotAgent property)
load_agent() (in module langchain.agents)
load_chain() (in module langchain.chains)
load_fn_kwargs (langchain.embeddings.SelfHostedHuggingFaceEmbeddings attribute)
(langchain.llms.SelfHostedHuggingFaceLLM attribute)
(langchain.llms.SelfHostedPipeline attribute)
load_local() (langchain.vectorstores.FAISS class method)
load_prompt() (in module langchain.prompts)
load_tools() (in module langchain.agents)
locals (langchain.python.PythonREPL attribute)
log_probs (langchain.llms.AlephAlpha attribute)
logit_bias (langchain.llms.AlephAlpha attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.GooseAI attribute)
logitBias (langchain.llms.AI21 attribute)
logits_all (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
logprobs (langchain.llms.LlamaCpp attribute)
(langchain.llms.Writer attribute)
lookup_tool() (langchain.agents.AgentExecutor method)
M
MarkdownTextSplitter (class in langchain.text_splitter)
max_checks (langchain.chains.LLMSummarizationCheckerChain attribute)
max_execution_time (langchain.agents.AgentExecutor attribute)
(langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-23 | (langchain.agents.SelfAskWithSearchChain attribute)
max_iterations (langchain.agents.AgentExecutor attribute)
(langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute)
max_length (langchain.llms.NLPCloud attribute)
(langchain.llms.Petals attribute)
(langchain.prompts.example_selector.LengthBasedExampleSelector attribute)
max_marginal_relevance_search() (langchain.vectorstores.Chroma method)
(langchain.vectorstores.DeepLake method)
(langchain.vectorstores.FAISS method)
(langchain.vectorstores.Milvus method)
(langchain.vectorstores.Qdrant method)
(langchain.vectorstores.VectorStore method)
max_marginal_relevance_search_by_vector() (langchain.vectorstores.Chroma method)
(langchain.vectorstores.DeepLake method)
(langchain.vectorstores.FAISS method)
(langchain.vectorstores.VectorStore method)
max_new_tokens (langchain.llms.Petals attribute)
max_retries (langchain.embeddings.OpenAIEmbeddings attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.OpenAIChat attribute)
(langchain.llms.PromptLayerOpenAIChat attribute)
max_tokens (langchain.llms.AzureOpenAI attribute)
(langchain.llms.Cohere attribute)
(langchain.llms.GooseAI attribute)
(langchain.llms.LlamaCpp attribute)
max_tokens_for_prompt() (langchain.llms.AzureOpenAI method)
(langchain.llms.OpenAI method)
(langchain.llms.PromptLayerOpenAI method)
max_tokens_limit (langchain.chains.ConversationalRetrievalChain attribute)
(langchain.chains.RetrievalQAWithSourcesChain attribute)
(langchain.chains.VectorDBQAWithSourcesChain attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-24 | (langchain.chains.VectorDBQAWithSourcesChain attribute)
max_tokens_per_generation (langchain.llms.RWKV attribute)
max_tokens_to_sample (langchain.llms.Anthropic attribute)
maximum_tokens (langchain.llms.AlephAlpha attribute)
maxTokens (langchain.llms.AI21 attribute)
memory (langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute)
(langchain.chains.ConversationChain attribute)
merge_from() (langchain.vectorstores.FAISS method)
METADATA_KEY (langchain.vectorstores.Qdrant attribute)
Milvus (class in langchain.vectorstores)
min_length (langchain.llms.NLPCloud attribute)
min_tokens (langchain.llms.GooseAI attribute)
minimum_tokens (langchain.llms.AlephAlpha attribute)
minTokens (langchain.llms.AI21 attribute)
model (langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding attribute)
(langchain.embeddings.CohereEmbeddings attribute)
(langchain.llms.AI21 attribute)
(langchain.llms.AlephAlpha attribute)
(langchain.llms.Anthropic attribute)
(langchain.llms.Cohere attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.RWKV attribute)
model_id (langchain.embeddings.SelfHostedHuggingFaceEmbeddings attribute)
(langchain.embeddings.SelfHostedHuggingFaceInstructEmbeddings attribute)
(langchain.llms.HuggingFacePipeline attribute)
(langchain.llms.SelfHostedHuggingFaceLLM attribute)
(langchain.llms.Writer attribute)
model_key (langchain.llms.Banana attribute)
model_kwargs (langchain.embeddings.HuggingFaceHubEmbeddings attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-25 | model_kwargs (langchain.embeddings.HuggingFaceHubEmbeddings attribute)
(langchain.embeddings.SagemakerEndpointEmbeddings attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.Banana attribute)
(langchain.llms.CerebriumAI attribute)
(langchain.llms.GooseAI attribute)
(langchain.llms.HuggingFaceEndpoint attribute)
(langchain.llms.HuggingFaceHub attribute)
(langchain.llms.HuggingFacePipeline attribute)
(langchain.llms.Modal attribute)
(langchain.llms.OpenAIChat attribute)
(langchain.llms.Petals attribute)
(langchain.llms.PromptLayerOpenAIChat attribute)
(langchain.llms.SagemakerEndpoint attribute)
(langchain.llms.SelfHostedHuggingFaceLLM attribute)
(langchain.llms.StochasticAI attribute)
model_load_fn (langchain.embeddings.SelfHostedHuggingFaceEmbeddings attribute)
(langchain.llms.SelfHostedHuggingFaceLLM attribute)
(langchain.llms.SelfHostedPipeline attribute)
model_name (langchain.chains.OpenAIModerationChain attribute)
(langchain.embeddings.HuggingFaceEmbeddings attribute)
(langchain.embeddings.HuggingFaceInstructEmbeddings attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.GooseAI attribute)
(langchain.llms.NLPCloud attribute)
(langchain.llms.OpenAIChat attribute)
(langchain.llms.Petals attribute)
(langchain.llms.PromptLayerOpenAIChat attribute)
model_path (langchain.llms.LlamaCpp attribute)
model_reqs (langchain.embeddings.SelfHostedHuggingFaceEmbeddings attribute)
(langchain.embeddings.SelfHostedHuggingFaceInstructEmbeddings attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-26 | (langchain.embeddings.SelfHostedHuggingFaceInstructEmbeddings attribute)
(langchain.llms.SelfHostedHuggingFaceLLM attribute)
(langchain.llms.SelfHostedPipeline attribute)
model_url (langchain.embeddings.TensorflowHubEmbeddings attribute)
modelname_to_contextsize() (langchain.llms.AzureOpenAI method)
(langchain.llms.OpenAI method)
(langchain.llms.PromptLayerOpenAI method)
module
langchain.agents
langchain.chains
langchain.docstore
langchain.embeddings
langchain.llms
langchain.prompts
langchain.prompts.example_selector
langchain.python
langchain.serpapi
langchain.text_splitter
langchain.utilities.searx_search
langchain.vectorstores
N
n (langchain.llms.AlephAlpha attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.GooseAI attribute)
n_batch (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
n_ctx (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
n_parts (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
n_predict (langchain.llms.GPT4All attribute)
n_threads (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
NLTKTextSplitter (class in langchain.text_splitter)
normalize (langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-27 | normalize (langchain.embeddings.AlephAlphaAsymmetricSemanticEmbedding attribute)
num_beams (langchain.llms.NLPCloud attribute)
num_return_sequences (langchain.llms.NLPCloud attribute)
numResults (langchain.llms.AI21 attribute)
O
observation_prefix (langchain.agents.Agent property)
(langchain.agents.ConversationalAgent property)
(langchain.agents.ConversationalChatAgent property)
(langchain.agents.ZeroShotAgent property)
openai_api_key (langchain.chains.OpenAIModerationChain attribute)
openai_organization (langchain.chains.OpenAIModerationChain attribute)
OpenSearchVectorSearch (class in langchain.vectorstores)
output_key (langchain.chains.QAGenerationChain attribute)
output_keys (langchain.chains.ConstitutionalChain property)
(langchain.chains.HypotheticalDocumentEmbedder property)
(langchain.chains.QAGenerationChain property)
output_parser (langchain.agents.ConversationalChatAgent attribute)
(langchain.agents.LLMSingleActionAgent attribute)
(langchain.prompts.BasePromptTemplate attribute)
output_variables (langchain.chains.TransformChain attribute)
P
p (langchain.llms.Cohere attribute)
param_mapping (langchain.chains.OpenAPIEndpointChain attribute)
params (langchain.serpapi.SerpAPIWrapper attribute)
(langchain.utilities.searx_search.SearxSearchWrapper attribute)
parse() (langchain.agents.AgentOutputParser method)
partial() (langchain.prompts.BasePromptTemplate method)
(langchain.prompts.ChatPromptTemplate method)
penalty_alpha_frequency (langchain.llms.RWKV attribute)
penalty_alpha_presence (langchain.llms.RWKV attribute)
penalty_bias (langchain.llms.AlephAlpha attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-28 | penalty_bias (langchain.llms.AlephAlpha attribute)
penalty_exceptions (langchain.llms.AlephAlpha attribute)
penalty_exceptions_include_stop_sequences (langchain.llms.AlephAlpha attribute)
persist() (langchain.vectorstores.Chroma method)
(langchain.vectorstores.DeepLake method)
Pinecone (class in langchain.vectorstores)
plan() (langchain.agents.Agent method)
(langchain.agents.BaseMultiActionAgent method)
(langchain.agents.BaseSingleActionAgent method)
(langchain.agents.LLMSingleActionAgent method)
predict() (langchain.chains.LLMChain method)
predict_and_parse() (langchain.chains.LLMChain method)
prefix (langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
prefix_messages (langchain.llms.OpenAIChat attribute)
(langchain.llms.PromptLayerOpenAIChat attribute)
prep_prompts() (langchain.chains.LLMChain method)
prep_streaming_params() (langchain.llms.AzureOpenAI method)
(langchain.llms.OpenAI method)
(langchain.llms.PromptLayerOpenAI method)
presence_penalty (langchain.llms.AlephAlpha attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.Cohere attribute)
(langchain.llms.GooseAI attribute)
presencePenalty (langchain.llms.AI21 attribute)
Prompt (in module langchain.prompts)
prompt (langchain.chains.ConversationChain attribute)
(langchain.chains.LLMBashChain attribute)
(langchain.chains.LLMChain attribute)
(langchain.chains.LLMMathChain attribute)
(langchain.chains.PALChain attribute)
(langchain.chains.SQLDatabaseChain attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-29 | (langchain.chains.PALChain attribute)
(langchain.chains.SQLDatabaseChain attribute)
python_globals (langchain.chains.PALChain attribute)
python_locals (langchain.chains.PALChain attribute)
PythonCodeTextSplitter (class in langchain.text_splitter)
Q
qa_chain (langchain.chains.GraphQAChain attribute)
Qdrant (class in langchain.vectorstores)
query_instruction (langchain.embeddings.HuggingFaceInstructEmbeddings attribute)
(langchain.embeddings.SelfHostedHuggingFaceInstructEmbeddings attribute)
query_suffix (langchain.utilities.searx_search.SearxSearchWrapper attribute)
R
random_seed (langchain.llms.Writer attribute)
raw_completion (langchain.llms.AlephAlpha attribute)
REACT_DOCSTORE (langchain.agents.AgentType attribute)
RecursiveCharacterTextSplitter (class in langchain.text_splitter)
reduce_k_below_max_tokens (langchain.chains.RetrievalQAWithSourcesChain attribute)
(langchain.chains.VectorDBQAWithSourcesChain attribute)
region_name (langchain.embeddings.SagemakerEndpointEmbeddings attribute)
(langchain.llms.SagemakerEndpoint attribute)
remove_end_sequence (langchain.llms.NLPCloud attribute)
remove_input (langchain.llms.NLPCloud attribute)
repeat_last_n (langchain.llms.GPT4All attribute)
repeat_penalty (langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
repetition_penalties_include_completion (langchain.llms.AlephAlpha attribute)
repetition_penalties_include_prompt (langchain.llms.AlephAlpha attribute)
repetition_penalty (langchain.llms.ForefrontAI attribute)
(langchain.llms.NLPCloud attribute)
(langchain.llms.Writer attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-30 | (langchain.llms.NLPCloud attribute)
(langchain.llms.Writer attribute)
repo_id (langchain.embeddings.HuggingFaceHubEmbeddings attribute)
(langchain.llms.HuggingFaceHub attribute)
request_timeout (langchain.llms.AzureOpenAI attribute)
requests (langchain.chains.OpenAPIEndpointChain attribute)
requests_wrapper (langchain.chains.APIChain attribute)
(langchain.chains.LLMRequestsChain attribute)
results() (langchain.serpapi.SerpAPIWrapper method)
(langchain.utilities.searx_search.SearxSearchWrapper method)
retriever (langchain.chains.ConversationalRetrievalChain attribute)
(langchain.chains.RetrievalQA attribute)
(langchain.chains.RetrievalQAWithSourcesChain attribute)
return_all (langchain.chains.SequentialChain attribute)
return_direct (langchain.chains.SQLDatabaseChain attribute)
return_intermediate_steps (langchain.agents.AgentExecutor attribute)
(langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute)
(langchain.chains.OpenAPIEndpointChain attribute)
(langchain.chains.PALChain attribute)
(langchain.chains.SQLDatabaseChain attribute)
(langchain.chains.SQLDatabaseSequentialChain attribute)
return_stopped_response() (langchain.agents.Agent method)
(langchain.agents.BaseMultiActionAgent method)
(langchain.agents.BaseSingleActionAgent method)
return_values (langchain.agents.Agent property)
(langchain.agents.BaseMultiActionAgent property)
(langchain.agents.BaseSingleActionAgent property)
revised_answer_prompt (langchain.chains.LLMCheckerChain attribute)
revised_summary_prompt (langchain.chains.LLMSummarizationCheckerChain attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-31 | revised_summary_prompt (langchain.chains.LLMSummarizationCheckerChain attribute)
revision_chain (langchain.chains.ConstitutionalChain attribute)
run() (langchain.python.PythonREPL method)
(langchain.serpapi.SerpAPIWrapper method)
(langchain.utilities.searx_search.SearxSearchWrapper method)
rwkv_verbose (langchain.llms.RWKV attribute)
S
save() (langchain.agents.AgentExecutor method)
(langchain.agents.BaseMultiActionAgent method)
(langchain.agents.BaseSingleActionAgent method)
(langchain.llms.AI21 method)
(langchain.llms.AlephAlpha method)
(langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.Banana method)
(langchain.llms.CerebriumAI method)
(langchain.llms.Cohere method)
(langchain.llms.DeepInfra method)
(langchain.llms.ForefrontAI method)
(langchain.llms.GooseAI method)
(langchain.llms.GPT4All method)
(langchain.llms.HuggingFaceEndpoint method)
(langchain.llms.HuggingFaceHub method)
(langchain.llms.HuggingFacePipeline method)
(langchain.llms.LlamaCpp method)
(langchain.llms.Modal method)
(langchain.llms.NLPCloud method)
(langchain.llms.OpenAI method)
(langchain.llms.OpenAIChat method)
(langchain.llms.Petals method)
(langchain.llms.PromptLayerOpenAI method)
(langchain.llms.PromptLayerOpenAIChat method)
(langchain.llms.Replicate method)
(langchain.llms.RWKV method)
(langchain.llms.SagemakerEndpoint method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-32 | (langchain.llms.SagemakerEndpoint method)
(langchain.llms.SelfHostedHuggingFaceLLM method)
(langchain.llms.SelfHostedPipeline method)
(langchain.llms.StochasticAI method)
(langchain.llms.Writer method)
(langchain.prompts.BasePromptTemplate method)
(langchain.prompts.ChatPromptTemplate method)
save_agent() (langchain.agents.AgentExecutor method)
save_local() (langchain.vectorstores.FAISS method)
search() (langchain.docstore.InMemoryDocstore method)
(langchain.docstore.Wikipedia method)
(langchain.vectorstores.DeepLake method)
search_kwargs (langchain.chains.ChatVectorDBChain attribute)
(langchain.chains.VectorDBQA attribute)
(langchain.chains.VectorDBQAWithSourcesChain attribute)
search_type (langchain.chains.VectorDBQA attribute)
searx_host (langchain.utilities.searx_search.SearxSearchWrapper attribute)
SearxResults (class in langchain.utilities.searx_search)
seed (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
select_examples() (langchain.prompts.example_selector.LengthBasedExampleSelector method)
(langchain.prompts.example_selector.MaxMarginalRelevanceExampleSelector method)
(langchain.prompts.example_selector.SemanticSimilarityExampleSelector method)
SELF_ASK_WITH_SEARCH (langchain.agents.AgentType attribute)
serpapi_api_key (langchain.serpapi.SerpAPIWrapper attribute)
similarity_search() (langchain.vectorstores.AtlasDB method)
(langchain.vectorstores.Chroma method)
(langchain.vectorstores.DeepLake method)
(langchain.vectorstores.ElasticVectorSearch method)
(langchain.vectorstores.FAISS method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-33 | (langchain.vectorstores.FAISS method)
(langchain.vectorstores.Milvus method)
(langchain.vectorstores.OpenSearchVectorSearch method)
(langchain.vectorstores.Pinecone method)
(langchain.vectorstores.Qdrant method)
(langchain.vectorstores.VectorStore method)
(langchain.vectorstores.Weaviate method)
similarity_search_by_vector() (langchain.vectorstores.Chroma method)
(langchain.vectorstores.DeepLake method)
(langchain.vectorstores.FAISS method)
(langchain.vectorstores.VectorStore method)
(langchain.vectorstores.Weaviate method)
similarity_search_with_score() (langchain.vectorstores.Chroma method)
(langchain.vectorstores.DeepLake method)
(langchain.vectorstores.FAISS method)
(langchain.vectorstores.Milvus method)
(langchain.vectorstores.Pinecone method)
(langchain.vectorstores.Qdrant method)
similarity_search_with_score_by_vector() (langchain.vectorstores.FAISS method)
SpacyTextSplitter (class in langchain.text_splitter)
split_documents() (langchain.text_splitter.TextSplitter method)
split_text() (langchain.text_splitter.CharacterTextSplitter method)
(langchain.text_splitter.NLTKTextSplitter method)
(langchain.text_splitter.RecursiveCharacterTextSplitter method)
(langchain.text_splitter.SpacyTextSplitter method)
(langchain.text_splitter.TextSplitter method)
(langchain.text_splitter.TokenTextSplitter method)
sql_chain (langchain.chains.SQLDatabaseSequentialChain attribute)
stop (langchain.agents.LLMSingleActionAgent attribute)
(langchain.chains.PALChain attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
(langchain.llms.Writer attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-34 | (langchain.llms.LlamaCpp attribute)
(langchain.llms.Writer attribute)
stop_sequences (langchain.llms.AlephAlpha attribute)
strategy (langchain.llms.RWKV attribute)
stream() (langchain.llms.Anthropic method)
(langchain.llms.AzureOpenAI method)
(langchain.llms.OpenAI method)
(langchain.llms.PromptLayerOpenAI method)
streaming (langchain.llms.Anthropic attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.OpenAIChat attribute)
(langchain.llms.PromptLayerOpenAIChat attribute)
strip_outputs (langchain.chains.SimpleSequentialChain attribute)
suffix (langchain.llms.LlamaCpp attribute)
(langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
T
task (langchain.embeddings.HuggingFaceHubEmbeddings attribute)
(langchain.llms.HuggingFaceEndpoint attribute)
(langchain.llms.HuggingFaceHub attribute)
(langchain.llms.SelfHostedHuggingFaceLLM attribute)
temp (langchain.llms.GPT4All attribute)
temperature (langchain.llms.AI21 attribute)
(langchain.llms.AlephAlpha attribute)
(langchain.llms.Anthropic attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.Cohere attribute)
(langchain.llms.ForefrontAI attribute)
(langchain.llms.GooseAI attribute)
(langchain.llms.LlamaCpp attribute)
(langchain.llms.NLPCloud attribute)
(langchain.llms.Petals attribute)
(langchain.llms.RWKV attribute)
(langchain.llms.Writer attribute)
template (langchain.prompts.PromptTemplate attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-35 | (langchain.llms.Writer attribute)
template (langchain.prompts.PromptTemplate attribute)
template_format (langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
(langchain.prompts.PromptTemplate attribute)
text_length (langchain.chains.LLMRequestsChain attribute)
text_splitter (langchain.chains.AnalyzeDocumentChain attribute)
(langchain.chains.MapReduceChain attribute)
(langchain.chains.QAGenerationChain attribute)
TextSplitter (class in langchain.text_splitter)
tokenizer (langchain.llms.Petals attribute)
tokens (langchain.llms.AlephAlpha attribute)
tokens_path (langchain.llms.RWKV attribute)
tokens_to_generate (langchain.llms.Writer attribute)
TokenTextSplitter (class in langchain.text_splitter)
tool() (in module langchain.agents)
tool_run_logging_kwargs() (langchain.agents.Agent method)
(langchain.agents.BaseMultiActionAgent method)
(langchain.agents.BaseSingleActionAgent method)
(langchain.agents.LLMSingleActionAgent method)
tools (langchain.agents.AgentExecutor attribute)
(langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute)
top_k (langchain.chains.SQLDatabaseChain attribute)
(langchain.llms.AlephAlpha attribute)
(langchain.llms.Anthropic attribute)
(langchain.llms.ForefrontAI attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
(langchain.llms.NLPCloud attribute)
(langchain.llms.Petals attribute)
(langchain.llms.Writer attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-36 | (langchain.llms.Petals attribute)
(langchain.llms.Writer attribute)
top_k_docs_for_context (langchain.chains.ChatVectorDBChain attribute)
top_p (langchain.llms.AlephAlpha attribute)
(langchain.llms.Anthropic attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.ForefrontAI attribute)
(langchain.llms.GooseAI attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
(langchain.llms.NLPCloud attribute)
(langchain.llms.Petals attribute)
(langchain.llms.RWKV attribute)
(langchain.llms.Writer attribute)
topP (langchain.llms.AI21 attribute)
transform (langchain.chains.TransformChain attribute)
truncate (langchain.embeddings.CohereEmbeddings attribute)
(langchain.llms.Cohere attribute)
U
unsecure (langchain.utilities.searx_search.SearxSearchWrapper attribute)
update_forward_refs() (langchain.llms.AI21 class method)
(langchain.llms.AlephAlpha class method)
(langchain.llms.Anthropic class method)
(langchain.llms.AzureOpenAI class method)
(langchain.llms.Banana class method)
(langchain.llms.CerebriumAI class method)
(langchain.llms.Cohere class method)
(langchain.llms.DeepInfra class method)
(langchain.llms.ForefrontAI class method)
(langchain.llms.GooseAI class method)
(langchain.llms.GPT4All class method)
(langchain.llms.HuggingFaceEndpoint class method)
(langchain.llms.HuggingFaceHub class method)
(langchain.llms.HuggingFacePipeline class method)
(langchain.llms.LlamaCpp class method) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-37 | (langchain.llms.LlamaCpp class method)
(langchain.llms.Modal class method)
(langchain.llms.NLPCloud class method)
(langchain.llms.OpenAI class method)
(langchain.llms.OpenAIChat class method)
(langchain.llms.Petals class method)
(langchain.llms.PromptLayerOpenAI class method)
(langchain.llms.PromptLayerOpenAIChat class method)
(langchain.llms.Replicate class method)
(langchain.llms.RWKV class method)
(langchain.llms.SagemakerEndpoint class method)
(langchain.llms.SelfHostedHuggingFaceLLM class method)
(langchain.llms.SelfHostedPipeline class method)
(langchain.llms.StochasticAI class method)
(langchain.llms.Writer class method)
use_mlock (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
use_multiplicative_presence_penalty (langchain.llms.AlephAlpha attribute)
V
validate_template (langchain.prompts.FewShotPromptTemplate attribute)
(langchain.prompts.FewShotPromptWithTemplates attribute)
(langchain.prompts.PromptTemplate attribute)
VectorStore (class in langchain.vectorstores)
vectorstore (langchain.chains.ChatVectorDBChain attribute)
(langchain.chains.VectorDBQA attribute)
(langchain.chains.VectorDBQAWithSourcesChain attribute)
(langchain.prompts.example_selector.SemanticSimilarityExampleSelector attribute)
verbose (langchain.agents.MRKLChain attribute)
(langchain.agents.ReActChain attribute)
(langchain.agents.SelfAskWithSearchChain attribute)
(langchain.llms.AzureOpenAI attribute)
(langchain.llms.OpenAI attribute)
(langchain.llms.OpenAIChat attribute) | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
e295932341ec-38 | (langchain.llms.OpenAI attribute)
(langchain.llms.OpenAIChat attribute)
vocab_only (langchain.embeddings.LlamaCppEmbeddings attribute)
(langchain.llms.GPT4All attribute)
(langchain.llms.LlamaCpp attribute)
W
Weaviate (class in langchain.vectorstores)
Wikipedia (class in langchain.docstore)
Z
ZERO_SHOT_REACT_DESCRIPTION (langchain.agents.AgentType attribute)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/genindex.html |
3a6f498be63a-0 | .rst
.pdf
Welcome to LangChain
Contents
Getting Started
Modules
Use Cases
Reference Docs
LangChain Ecosystem
Additional Resources
Welcome to LangChain#
LangChain is a framework for developing applications powered by language models. We believe that the most powerful and differentiated applications will not only call out to a language model via an API, but will also:
Be data-aware: connect a language model to other sources of data
Be agentic: allow a language model to interact with its environment
The LangChain framework is designed with the above principles in mind.
This is the Python specific portion of the documentation. For a purely conceptual guide to LangChain, see here. For the JavaScript documentation, see here.
Getting Started#
Checkout the below guide for a walkthrough of how to get started using LangChain to create an Language Model application.
Getting Started Documentation
Modules#
There are several main modules that LangChain provides support for.
For each module we provide some examples to get started, how-to guides, reference docs, and conceptual guides.
These modules are, in increasing order of complexity:
Models: The various model types and model integrations LangChain supports.
Prompts: This includes prompt management, prompt optimization, and prompt serialization.
Memory: Memory is the concept of persisting state between calls of a chain/agent. LangChain provides a standard interface for memory, a collection of memory implementations, and examples of chains/agents that use memory.
Indexes: Language models are often more powerful when combined with your own text data - this module covers best practices for doing exactly that.
Chains: Chains go beyond just a single LLM call, and are sequences of calls (whether to an LLM or a different utility). LangChain provides a standard interface for chains, lots of integrations with other tools, and end-to-end chains for common applications. | https://langchain-cn.readthedocs.io/en/latest/index.html |
3a6f498be63a-1 | Agents: Agents involve an LLM making decisions about which Actions to take, taking that Action, seeing an Observation, and repeating that until done. LangChain provides a standard interface for agents, a selection of agents to choose from, and examples of end to end agents.
Use Cases#
The above modules can be used in a variety of ways. LangChain also provides guidance and assistance in this. Below are some of the common use cases LangChain supports.
Personal Assistants: The main LangChain use case. Personal assistants need to take actions, remember interactions, and have knowledge about your data.
Question Answering: The second big LangChain use case. Answering questions over specific documents, only utilizing the information in those documents to construct an answer.
Chatbots: Since language models are good at producing text, that makes them ideal for creating chatbots.
Querying Tabular Data: If you want to understand how to use LLMs to query data that is stored in a tabular format (csvs, SQL, dataframes, etc) you should read this page.
Code Understanding: If you want to understand how to use LLMs to query source code from github, you should read this page.
Interacting with APIs: Enabling LLMs to interact with APIs is extremely powerful in order to give them more up-to-date information and allow them to take actions.
Extraction: Extract structured information from text.
Summarization: Summarizing longer documents into shorter, more condensed chunks of information. A type of Data Augmented Generation.
Evaluation: Generative models are notoriously hard to evaluate with traditional metrics. One new way of evaluating them is using language models themselves to do the evaluation. LangChain provides some prompts/chains for assisting in this.
Reference Docs# | https://langchain-cn.readthedocs.io/en/latest/index.html |
3a6f498be63a-2 | Reference Docs#
All of LangChain’s reference documentation, in one place. Full documentation on all methods, classes, installation methods, and integration setups for LangChain.
Reference Documentation
LangChain Ecosystem#
Guides for how other companies/products can be used with LangChain
LangChain Ecosystem
Additional Resources#
Additional collection of resources we think may be useful as you develop your application!
LangChainHub: The LangChainHub is a place to share and explore other prompts, chains, and agents.
Glossary: A glossary of all related terms, papers, methods, etc. Whether implemented in LangChain or not!
Gallery: A collection of our favorite projects that use LangChain. Useful for finding inspiration or seeing how things were done in other applications.
Deployments: A collection of instructions, code snippets, and template repositories for deploying LangChain apps.
Tracing: A guide on using tracing in LangChain to visualize the execution of chains and agents.
Model Laboratory: Experimenting with different prompts, models, and chains is a big part of developing the best possible application. The ModelLaboratory makes it easy to do so.
Discord: Join us on our Discord to discuss all things LangChain!
Production Support: As you move your LangChains into production, we’d love to offer more comprehensive support. Please fill out this form and we’ll set up a dedicated support Slack channel.
next
入门指南
Contents
Getting Started
Modules
Use Cases
Reference Docs
LangChain Ecosystem
Additional Resources
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/index.html |
6d517c60f283-0 | .md
.pdf
Tracing
Contents
Tracing Walkthrough
Changing Sessions
Tracing#
By enabling tracing in your LangChain runs, you’ll be able to more effectively visualize, step through, and debug your chains and agents.
First, you should install tracing and set up your environment properly.
You can use either a locally hosted version of this (uses Docker) or a cloud hosted version (in closed alpha).
If you’re interested in using the hosted platform, please fill out the form here.
Locally Hosted Setup
Cloud Hosted Setup
Tracing Walkthrough#
When you first access the UI, you should see a page with your tracing sessions.
An initial one “default” should already be created for you.
A session is just a way to group traces together.
If you click on a session, it will take you to a page with no recorded traces that says “No Runs.”
You can create a new session with the new session form.
If we click on the default session, we can see that to start we have no traces stored.
If we now start running chains and agents with tracing enabled, we will see data show up here.
To do so, we can run this notebook as an example.
After running it, we will see an initial trace show up.
From here we can explore the trace at a high level by clicking on the arrow to show nested runs.
We can keep on clicking further and further down to explore deeper and deeper.
We can also click on the “Explore” button of the top level run to dive even deeper.
Here, we can see the inputs and outputs in full, as well as all the nested traces.
We can keep on exploring each of these nested traces in more detail.
For example, here is the lowest level trace with the exact inputs/outputs to the LLM.
Changing Sessions# | https://langchain-cn.readthedocs.io/en/latest/tracing.html |
6d517c60f283-1 | Changing Sessions#
To initially record traces to a session other than "default", you can set the LANGCHAIN_SESSION environment variable to the name of the session you want to record to:
import os
os.environ["LANGCHAIN_HANDLER"] = "langchain"
os.environ["LANGCHAIN_SESSION"] = "my_session" # Make sure this session actually exists. You can create a new session in the UI.
To switch sessions mid-script or mid-notebook, do NOT set the LANGCHAIN_SESSION environment variable. Instead: langchain.set_tracing_callback_manager(session_name="my_session")
previous
Deployments
Contents
Tracing Walkthrough
Changing Sessions
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/tracing.html |
9fe0ebb2729f-0 | .md
.pdf
Glossary
Contents
Chain of Thought Prompting
Action Plan Generation
ReAct Prompting
Self-ask
Prompt Chaining
Memetic Proxy
Self Consistency
Inception
MemPrompt
Glossary#
This is a collection of terminology commonly used when developing LLM applications.
It contains reference to external papers or sources where the concept was first introduced,
as well as to places in LangChain where the concept is used.
Chain of Thought Prompting#
A prompting technique used to encourage the model to generate a series of intermediate reasoning steps.
A less formal way to induce this behavior is to include “Let’s think step-by-step” in the prompt.
Resources:
Chain-of-Thought Paper
Step-by-Step Paper
Action Plan Generation#
A prompt usage that uses a language model to generate actions to take.
The results of these actions can then be fed back into the language model to generate a subsequent action.
Resources:
WebGPT Paper
SayCan Paper
ReAct Prompting#
A prompting technique that combines Chain-of-Thought prompting with action plan generation.
This induces the to model to think about what action to take, then take it.
Resources:
Paper
LangChain Example
Self-ask#
A prompting method that builds on top of chain-of-thought prompting.
In this method, the model explicitly asks itself follow-up questions, which are then answered by an external search engine.
Resources:
Paper
LangChain Example
Prompt Chaining#
Combining multiple LLM calls together, with the output of one-step being the input to the next.
Resources:
PromptChainer Paper
Language Model Cascades
ICE Primer Book
Socratic Models
Memetic Proxy# | https://langchain-cn.readthedocs.io/en/latest/glossary.html |
9fe0ebb2729f-1 | Language Model Cascades
ICE Primer Book
Socratic Models
Memetic Proxy#
Encouraging the LLM to respond in a certain way framing the discussion in a context that the model knows of and that will result in that type of response. For example, as a conversation between a student and a teacher.
Resources:
Paper
Self Consistency#
A decoding strategy that samples a diverse set of reasoning paths and then selects the most consistent answer.
Is most effective when combined with Chain-of-thought prompting.
Resources:
Paper
Inception#
Also called “First Person Instruction”.
Encouraging the model to think a certain way by including the start of the model’s response in the prompt.
Resources:
Example
MemPrompt#
MemPrompt maintains a memory of errors and user feedback, and uses them to prevent repetition of mistakes.
Resources:
Paper
previous
Zilliz
next
LangChain Gallery
Contents
Chain of Thought Prompting
Action Plan Generation
ReAct Prompting
Self-ask
Prompt Chaining
Memetic Proxy
Self Consistency
Inception
MemPrompt
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/glossary.html |
fdf355d85b0f-0 | .rst
.pdf
LangChain Gallery
Contents
Open Source
Misc. Colab Notebooks
Proprietary
LangChain Gallery#
Lots of people have built some pretty awesome stuff with LangChain.
This is a collection of our favorites.
If you see any other demos that you think we should highlight, be sure to let us know!
Open Source#
HowDoI.ai
This is an experiment in building a large-language-model-backed chatbot. It can hold a conversation, remember previous comments/questions,
and answer all types of queries (history, web search, movie data, weather, news, and more).
YouTube Transcription QA with Sources
An end-to-end example of doing question answering on YouTube transcripts, returning the timestamps as sources to legitimize the answer.
QA Slack Bot
This application is a Slack Bot that uses Langchain and OpenAI’s GPT3 language model to provide domain specific answers. You provide the documents.
ThoughtSource
A central, open resource and community around data and tools related to chain-of-thought reasoning in large language models.
LLM Strategy
This Python package adds a decorator llm_strategy that connects to an LLM (such as OpenAI’s GPT-3) and uses the LLM to “implement” abstract methods in interface classes. It does this by forwarding requests to the LLM and converting the responses back to Python data using Python’s @dataclasses.
Zero-Shot Corporate Lobbyist
A notebook showing how to use GPT to help with the work of a corporate lobbyist.
Dagster Documentation ChatBot
A jupyter notebook demonstrating how you could create a semantic search engine on documents in one of your Google Folders
Google Folder Semantic Search
Build a GitHub support bot with GPT3, LangChain, and Python.
Talk With Wind
Record sounds of anything (birds, wind, fire, train station) and chat with it. | https://langchain-cn.readthedocs.io/en/latest/gallery.html |
fdf355d85b0f-1 | Record sounds of anything (birds, wind, fire, train station) and chat with it.
ChatGPT LangChain
This simple application demonstrates a conversational agent implemented with OpenAI GPT-3.5 and LangChain. When necessary, it leverages tools for complex math, searching the internet, and accessing news and weather.
GPT Math Techniques
A Hugging Face spaces project showing off the benefits of using PAL for math problems.
GPT Political Compass
Measure the political compass of GPT.
Notion Database Question-Answering Bot
Open source GitHub project shows how to use LangChain to create a chatbot that can answer questions about an arbitrary Notion database.
LlamaIndex
LlamaIndex (formerly GPT Index) is a project consisting of a set of data structures that are created using GPT-3 and can be traversed using GPT-3 in order to answer queries.
Grover’s Algorithm
Leveraging Qiskit, OpenAI and LangChain to demonstrate Grover’s algorithm
QNimGPT
A chat UI to play Nim, where a player can select an opponent, either a quantum computer or an AI
ReAct TextWorld
Leveraging the ReActTextWorldAgent to play TextWorld with an LLM!
Fact Checker
This repo is a simple demonstration of using LangChain to do fact-checking with prompt chaining.
DocsGPT
Answer questions about the documentation of any project
Misc. Colab Notebooks#
Wolfram Alpha in Conversational Agent
Give ChatGPT a WolframAlpha neural implant
Tool Updates in Agents
Agent improvements (6th Jan 2023)
Conversational Agent with Tools (Langchain AGI)
Langchain AGI (23rd Dec 2022)
Proprietary#
Daimon
A chat-based AI personal assistant with long-term memory about you. | https://langchain-cn.readthedocs.io/en/latest/gallery.html |
fdf355d85b0f-2 | Daimon
A chat-based AI personal assistant with long-term memory about you.
AI Assisted SQL Query Generator
An app to write SQL using natural language, and execute against real DB.
Clerkie
Stack Tracing QA Bot to help debug complex stack tracing (especially the ones that go multi-function/file deep).
Sales Email Writer
By Raza Habib, this demo utilizes LangChain + SerpAPI + HumanLoop to write sales emails. Give it a company name and a person, this application will use Google Search (via SerpAPI) to get more information on the company and the person, and then write them a sales message.
Question-Answering on a Web Browser
By Zahid Khawaja, this demo utilizes question answering to answer questions about a given website. A followup added this for YouTube videos, and then another followup added it for Wikipedia.
Mynd
A journaling app for self-care that uses AI to uncover insights and patterns over time.
previous
Glossary
next
Deployments
Contents
Open Source
Misc. Colab Notebooks
Proprietary
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/gallery.html |
b9c54b4254ad-0 | Search
Error
Please activate JavaScript to enable the search functionality.
Ctrl+K
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/search.html |
edcf8f136f78-0 | .ipynb
.pdf
Model Comparison
Model Comparison#
Constructing your language model application will likely involved choosing between many different options of prompts, models, and even chains to use. When doing so, you will want to compare these different options on different inputs in an easy, flexible, and intuitive way.
LangChain provides the concept of a ModelLaboratory to test out and try different models.
from langchain import LLMChain, OpenAI, Cohere, HuggingFaceHub, PromptTemplate
from langchain.model_laboratory import ModelLaboratory
llms = [
OpenAI(temperature=0),
Cohere(model="command-xlarge-20221108", max_tokens=20, temperature=0),
HuggingFaceHub(repo_id="google/flan-t5-xl", model_kwargs={"temperature":1})
]
model_lab = ModelLaboratory.from_llms(llms)
model_lab.compare("What color is a flamingo?")
Input:
What color is a flamingo?
OpenAI
Params: {'model': 'text-davinci-002', 'temperature': 0.0, 'max_tokens': 256, 'top_p': 1, 'frequency_penalty': 0, 'presence_penalty': 0, 'n': 1, 'best_of': 1}
Flamingos are pink.
Cohere
Params: {'model': 'command-xlarge-20221108', 'max_tokens': 20, 'temperature': 0.0, 'k': 0, 'p': 1, 'frequency_penalty': 0, 'presence_penalty': 0}
Pink
HuggingFaceHub
Params: {'repo_id': 'google/flan-t5-xl', 'temperature': 1}
pink | https://langchain-cn.readthedocs.io/en/latest/model_laboratory.html |
edcf8f136f78-1 | pink
prompt = PromptTemplate(template="What is the capital of {state}?", input_variables=["state"])
model_lab_with_prompt = ModelLaboratory.from_llms(llms, prompt=prompt)
model_lab_with_prompt.compare("New York")
Input:
New York
OpenAI
Params: {'model': 'text-davinci-002', 'temperature': 0.0, 'max_tokens': 256, 'top_p': 1, 'frequency_penalty': 0, 'presence_penalty': 0, 'n': 1, 'best_of': 1}
The capital of New York is Albany.
Cohere
Params: {'model': 'command-xlarge-20221108', 'max_tokens': 20, 'temperature': 0.0, 'k': 0, 'p': 1, 'frequency_penalty': 0, 'presence_penalty': 0}
The capital of New York is Albany.
HuggingFaceHub
Params: {'repo_id': 'google/flan-t5-xl', 'temperature': 1}
st john s
from langchain import SelfAskWithSearchChain, SerpAPIWrapper
open_ai_llm = OpenAI(temperature=0)
search = SerpAPIWrapper()
self_ask_with_search_openai = SelfAskWithSearchChain(llm=open_ai_llm, search_chain=search, verbose=True)
cohere_llm = Cohere(temperature=0, model="command-xlarge-20221108")
search = SerpAPIWrapper()
self_ask_with_search_cohere = SelfAskWithSearchChain(llm=cohere_llm, search_chain=search, verbose=True)
chains = [self_ask_with_search_openai, self_ask_with_search_cohere]
names = [str(open_ai_llm), str(cohere_llm)] | https://langchain-cn.readthedocs.io/en/latest/model_laboratory.html |
edcf8f136f78-2 | names = [str(open_ai_llm), str(cohere_llm)]
model_lab = ModelLaboratory(chains, names=names)
model_lab.compare("What is the hometown of the reigning men's U.S. Open champion?")
Input:
What is the hometown of the reigning men's U.S. Open champion?
OpenAI
Params: {'model': 'text-davinci-002', 'temperature': 0.0, 'max_tokens': 256, 'top_p': 1, 'frequency_penalty': 0, 'presence_penalty': 0, 'n': 1, 'best_of': 1}
> Entering new chain...
What is the hometown of the reigning men's U.S. Open champion?
Are follow up questions needed here: Yes.
Follow up: Who is the reigning men's U.S. Open champion?
Intermediate answer: Carlos Alcaraz.
Follow up: Where is Carlos Alcaraz from?
Intermediate answer: El Palmar, Spain.
So the final answer is: El Palmar, Spain
> Finished chain.
So the final answer is: El Palmar, Spain
Cohere
Params: {'model': 'command-xlarge-20221108', 'max_tokens': 256, 'temperature': 0.0, 'k': 0, 'p': 1, 'frequency_penalty': 0, 'presence_penalty': 0}
> Entering new chain...
What is the hometown of the reigning men's U.S. Open champion?
Are follow up questions needed here: Yes.
Follow up: Who is the reigning men's U.S. Open champion?
Intermediate answer: Carlos Alcaraz.
So the final answer is:
Carlos Alcaraz
> Finished chain.
So the final answer is:
Carlos Alcaraz
By Harrison Chase | https://langchain-cn.readthedocs.io/en/latest/model_laboratory.html |
edcf8f136f78-3 | So the final answer is:
Carlos Alcaraz
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/model_laboratory.html |
7647b6b0cca7-0 | .md
.pdf
入门指南
Contents
安装
环境设置
构建语言模型应用程序:LLMs
构建语言模型类应用程序:聊天模型
入门指南#
本教程将为您快速介绍如何使用LangChain构建端到端的语言模型应用程序。
安装#
请使用以下命令安装LangChain:
pip install langchain
# or
conda install langchain -c conda-forge
环境设置#
通常使用LangChain需要将其与一个或多个模型提供者、数据存储、API等进行集成。
在本示例中,我们将使用OpenAI的API,因此我们首先需要安装其SDK:
pip install openai
接下来我们需要在终端中设置环境变量。
export OPENAI_API_KEY="..."
是的,没错。您可以在 Jupyter 笔记本或 Python 脚本中设置环境变量。以下是设置环境变量的代码示例:
import os
os.environ["OPENAI_API_KEY"] = "..."
构建语言模型应用程序:LLMs#
现在我们已经安装了 LangChain 并设置好了环境,可以开始构建我们的语言模型应用程序了。
LangChain 提供了许多模块,可以用来构建语言模型应用程序。这些模块可以组合使用,创建更复杂的应用程序,或者单独用于简单的应用程序。
LLMs: 从语言模型获取预测结果 | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-1 | LLMs: 从语言模型获取预测结果
LangChain 最基本的构建块是在某些输入上调用 LLM。让我们通过一个简单的示例来演示如何实现这一点。为此,假设我们正在构建一个服务,根据公司的产品生成公司名称。
为了实现这一点,我们首先需要导入 LLM 包,例如OpenAI。
from langchain.llms import OpenAI
接下来,我们可以使用任何参数来初始化LLM。在这个例子中,我们希望输出结果更随机一些,因此我们将使用较高的temperature(这也是OpenAI的API参数,温度代表了分子平均随机运动的快慢,因此借用温度来表示随机性)值来初始化。
llm = OpenAI(temperature=0.9)
现在我们可以调用它了!
text = "请用中文给生产彩色袜子的公司起个好名字。"
print(llm(text))
色活靓履
有关如何在 LangChain 中使用 LLMs 的更多详细信息,请参见 LLM 入门指南.
Prompt Templates (提示模板): 为语言模型管理提示 | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-2 | Prompt Templates (提示模板): 为语言模型管理提示
调用 LLM 是我们开始的第一步。但通常在应用中使用 LLM 时,您不会直接将用户输入发送到 LLM 中。您可能会按照业务场景需要,简化用户的输入。然后按适合当前场景的模式,对输入进行修饰和调整后再发送到 LLM 中。
例如,在先前的示例中,我们传递的文本是硬编码以要求为制造彩色袜子的公司命名。在这个想象中的服务中,我们希望做的是只获取描述公司的用户输入,然后使用这些信息格式化提示。
这在 LangChain 中非常容易!
首先,让我们定义提示模板:
from langchain.prompts import PromptTemplate
prompt = PromptTemplate(
input_variables=["product"],
template="请用中文给生产{product}的公司起个好名字",
)
现在让我们看看它的工作原理!我们可以调用 .format 方法来格式化它。
print(prompt.format(product="彩色袜子"))
请用中文给生产彩色袜子的公司起个好名字
想要了解更多详细信息,请参阅提示模板的入门指南。
Chains(链):在多步流程中将 LLM(语言模型)和 Prompt Templates (提示模板)结合起来。 | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-3 | 到目前为止,我们已经单独使用了 PromptTemplate 和 LLM 这些基础组件。他们不仅可以单独使用,还可以“链接”在一起组合使用。
在 LangChain 中,“链”由“链接”组成,“链接”可以是像 LLM 这样的基础组件或其他链。
例如:LLMChain 就是最核心的“链”类型,由 PromptTemplate 和 LLM 组成。
扩展之前的例子,我们可以构造一个 LLMChain,它接受用户输入,使用 PromptTemplate 进行格式化,并将格式化的响应传递给 LLM。
from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
input_variables=["product"],
template="请用中文给生产{product}的公司起个好名字",
)
现在我们可以创建一个非常简单的链,该链将接受用户输入,然后用 PromptTemplate(提示模版)进行格式化,最后将其发送给 LLM(语言模型):
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
现在我们可以运行该链,只需指定产品即可获得我们期望的结果!
chain.run("彩色袜子")
# -> '\n\n彩色星足!' | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-4 | # -> '\n\n彩色星足!'
第一个链成功执行了! - 一个 LLM 链。虽然这只是一种较简单的链,但理解它的工作原理会为您使用更复杂的链打下良好的基础。
要了解更多详情,请查看链的入门指南。
Agents(代理):根据用户输入动态调用链
到目前为止,我们所讨论的链都是按照预定顺序运行的。
而代理不再是这样:它们使用 LLM 确定要采取的操作以及其顺序。一个操作可以是使用工具并观察其输出,或将结果返回给用户。
如果使用得当,代理可以非常强大。在本教程中,我们将通过最简单的、最高级别的 API,向您展示如何轻松地使用代理。
为了加载代理,您应该理解以下概念:
工具: 执行特定任务的函数。这可以是诸如 Google 搜索、数据库查找、Python REPL、其他链之类的工具。目前工具的接口是一个期望输入为字符串并输出字符串的函数。
LLM: 驱动代理的语言模型。注意:这里指代理通过语言模型自己判断选择使用哪些工具 | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-5 | 代理: 通过引用代理类的名字字符串,指定要使用的代理。本篇介绍专注于最简单的、最高级别的 API,所以仅涵盖使用标准支持的代理类。如果要实现自定义代理,请参阅自定义代理的文档(即将推出)。
代理: 有关支持的代理及其规格列表,请参考 here.
工具: 有关预定义工具及其规格列表,请参见 here.
接下来这个例子需要安装 SerpAPI Python 包。
pip install google-search-results
然后设置环境变量。
import os
os.environ["SERPAPI_API_KEY"] = "..."
现在我们可以开始了!
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
# 首先,让我们加载我们将用来控制代理的语言模型。
llm = OpenAI(temperature=0)
# 接下来,让我们加载一些要使用的工具。请注意,“llm-math”工具使用LLM,因此我们需要传递LLM。
tools = load_tools(["serpapi", "llm-math"], llm=llm)
# 最后,让我们使用这些工具、语言模型和我们想要使用的代理类型来初始化一个代理。
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-6 | # 现在让我们来测试一下吧!
agent.run("What was the high temperature in SF yesterday in Fahrenheit? What is that number raised to the .023 power?")
> Entering new AgentExecutor chain...
I need to find the temperature first, then use the calculator to raise it to the .023 power.
Action: Search
Action Input: "High temperature in SF yesterday"
Observation: San Francisco Temperature Yesterday. Maximum temperature yesterday: 57 °F (at 1:56 pm) Minimum temperature yesterday: 49 °F (at 1:56 am) Average temperature ...
Thought: I now have the temperature, so I can use the calculator to raise it to the .023 power.
Action: Calculator
Action Input: 57^.023
Observation: Answer: 1.0974509573251117
Thought: I now know the final answer
Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.
> Finished chain.
Memory(记忆):将状态添加到链和代理中。 | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-7 | Memory(记忆):将状态添加到链和代理中。
到目前为止,我们所讨论的所有链和代理都是无状态的。但通常情况下,您可能希望链或代理具有某种“记忆”概念,以便它可以记住有关其先前交互的信息。这种情况最清晰和简单的例子是设计聊天机器人 - 您希望它记住以前的消息,以便它可以利用上下文进行更好的对话。这将是一种“短期记忆”。在更复杂的方面,您可以想象链/代理随着时间的推移记住关键信息 - 这将是一种“长期记忆”。有关后者的更具体的想法,请参见 论文.
LangChain 提供了几个专门为此目的创建的链。本笔记本演示了使用其中一条链(ConversationChain)和两种不同类型的记忆的方法。
默认情况下,ConversationChain 具有一种简单的记忆类型,它记住了所有先前的输入/输出,并将它们添加到传递的上下文中。让我们看一下如何使用这个链(将verbose=True,以便我们可以看到提示)。
from langchain import OpenAI, ConversationChain
llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, verbose=True) | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-8 | conversation = ConversationChain(llm=llm, verbose=True)
conversation.predict(input="Hi there!")
> Entering new chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI:
> Finished chain.
' Hello! How are you today?'
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
> Entering new chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI: Hello! How are you today?
Human: I'm doing well! Just having a conversation with an AI.
AI:
> Finished chain.
" That's great! What would you like to talk about?"
构建语言模型类应用程序:聊天模型#
同样地,您可以使用聊天模型而不是 LLM。聊天模型是语言模型的一种变体。虽然聊天模型在底层使用语言模型,但它们公开的界面有点不同:它们不是公开一个“文本输入,文本输出”的 API,而是公开一个“聊天信息”是输入和输出的接口。 | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-9 | 聊天模型 API 还比较新,因此我们仍在摸索正确的抽象化方法。
在聊天模型中获取消
您可以通过向聊天模型传递一个或多个消息来获得聊天回复。响应将是一个消息。目前在 LangChain 中支持的消息类型有 AIMessage、HumanMessage、SystemMessage 和 ChatMessage,其中 ChatMessage 接受一个任意角色参数。大多数情况下,您只需要处理 HumanMessage、AIMessage 和 SystemMessage 即可
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
chat = ChatOpenAI(temperature=0)
您可以通过传入单个消息来获取回复
chat([HumanMessage(content="翻译句子从英文到中文. I love programming.")])
# -> AIMessage(content="我喜欢编程。", additional_kwargs={})
您还可以针对 OpenAI 的 GPT-3.5 Turbo 和 GPT-4 模型传入多个消息。
messages = [
SystemMessage(content="你是我的英文翻译中文助理"),
HumanMessage(content="翻译句子从英文到中文. I love programming.")
]
chat(messages)
# -> AIMessage(content="我喜欢编程。", additional_kwargs={})
您可以进一步采用 “generate” 函数生成多组消息的完成度建议。这将返回一个带有额外 “message” 参数的 “LLMResult”。
batch_messages = [ | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-10 | batch_messages = [
[
SystemMessage(content="你是我的英文翻译中文助理"),
HumanMessage(content="翻译句子从英文到中文. I love programming.")
],
[
SystemMessage(content="你是我的英文翻译中文助理"),
HumanMessage(content="翻译句子从英文到中文. I love artificial intelligence.")
],
]
result = chat.generate(batch_messages)
result
# -> LLMResult(generations=[[ChatGeneration(text='我喜欢编程。', generation_info=None, message=AIMessage(content='我喜欢编程。', additional_kwargs={}))], [ChatGeneration(text='我喜爱人工智能。', generation_info=None, message=AIMessage(content='我喜爱人工智能。', additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 95, 'completion_tokens': 19, 'total_tokens': 114}, 'model_name': 'gpt-3.5-turbo'})
您可以从这个 “LLMResult” 中恢复令牌使用情况等信息。
result.llm_output['token_usage']
# -> {'prompt_tokens': 95, 'completion_tokens': 19, 'total_tokens': 114}
Chat Prompt Templates(聊天提示模版) | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-11 | Chat Prompt Templates(聊天提示模版)
类似于 LLM 模型,您可以使用 “MessagePromptTemplate” 模板来进行 templating。您可以构建一个 ChatPromptTemplate,从一个或多个 MessagePromptTemplate 构建。您可以使用 ChatPromptTemplate 的 format_prompt - 这将返回一个 PromptValue,您可以将其转换为字符串或 Message 对象,这取决于您是否想将格式化的值用作 llm 或 chat 模型的输入。
为了方便起见,模板上公开了一个 “from_template” 方法。如果您使用此模板,它会是这样的:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
chat = ChatOpenAI(temperature=0)
template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
# get a chat completion from the formatted messages
chat(chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages())
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})
在Chain(链)中使用聊天模型
上面讨论的 LLMChain 也可以与聊天模型一起使用:
from langchain.chat_models import ChatOpenAI
from langchain import LLMChain
from langchain.prompts.chat import (
ChatPromptTemplate, | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-12 | from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
chat = ChatOpenAI(temperature=0)
template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
chain = LLMChain(llm=chat, prompt=chat_prompt)
chain.run(input_language="English", output_language="French", text="I love programming.")
# -> "J'aime programmer."
在Agents(代理)中使用聊天模型
也可以将代理与聊天模型一起使用,您可以使用 AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION 作为代理类型进行初始化。
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI
# 首先,让我们加载我们将用来控制代理的语言模型。
chat = ChatOpenAI(temperature=0)
# 接下来,让我们加载一些工具来使用。请注意,llm-math 工具使用 LLM,因此我们需要将其传递给它。
llm = OpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math"], llm=llm) | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-13 | # 最后,让我们使用这些工具、语言模型和我们想要使用的代理类型来初始化一个代理。
agent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
# 现在让我们测试一下!
agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
> Entering new AgentExecutor chain...
Thought: I need to use a search engine to find Olivia Wilde's boyfriend and a calculator to raise his age to the 0.23 power.
Action:
{
"action": "Search",
"action_input": "Olivia Wilde boyfriend"
}
Observation: Sudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.
Thought:I need to use a search engine to find Harry Styles' current age.
Action:
{
"action": "Search",
"action_input": "Harry Styles age"
}
Observation: 29 years
Thought:Now I need to calculate 29 raised to the 0.23 power.
Action:
{
"action": "Calculator",
"action_input": "29^0.23"
}
Observation: Answer: 2.169459462491557
Thought:I now know the final answer.
Final Answer: 2.169459462491557
> Finished chain.
'2.169459462491557' | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-14 | > Finished chain.
'2.169459462491557'
Memory(记忆): 为 Chain(链)与 Agents(代理)添加状态
可以在使用聊天模型初始化的链和代理中使用记忆。与针对语言模型的记忆不同的是,我们可以将之前的所有消息作为唯一的记忆对象保留,而不试图将其压缩为一个字符串。
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template("下面是人类和人工智能之间的友好对话。人工智能很健谈,提供了许多来自上下文的具体细节。如果人工智能不知道回答一个问题,它会诚实地说出自己不知道。"),
MessagesPlaceholder(variable_name="history"),
HumanMessagePromptTemplate.from_template("{input}")
])
llm = ChatOpenAI(temperature=0)
memory = ConversationBufferMemory(return_messages=True)
conversation = ConversationChain(memory=memory, prompt=prompt, llm=llm)
conversation.predict(input="Hi there!")
# -> 'Hello! How can I assist you today?'
conversation.predict(input="I'm doing well! Just having a conversation with an AI.") | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-15 | conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
# -> "That sounds like fun! I'm happy to chat with you. Is there anything specific you'd like to talk about?"
conversation.predict(input="Tell me about yourself.")
# -> "Sure! I am an AI language model created by OpenAI. I was trained on a large dataset of text from the internet, which allows me to understand and generate human-like language. I can answer questions, provide information, and even have conversations like this one. Is there anything else you'd like to know about me?"
previous
Welcome to LangChain
next
Models(模型)
Contents
安装
环境设置
构建语言模型应用程序:LLMs
构建语言模型类应用程序:聊天模型
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
5396f0be47bb-0 | Source code for langchain.python
"""Mock Python REPL."""
import sys
from io import StringIO
from typing import Dict, Optional
from pydantic import BaseModel, Field
[docs]class PythonREPL(BaseModel):
"""Simulates a standalone Python REPL."""
globals: Optional[Dict] = Field(default_factory=dict, alias="_globals")
locals: Optional[Dict] = Field(default_factory=dict, alias="_locals")
[docs] def run(self, command: str) -> str:
"""Run command with own globals/locals and returns anything printed."""
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
try:
exec(command, self.globals, self.locals)
sys.stdout = old_stdout
output = mystdout.getvalue()
except Exception as e:
sys.stdout = old_stdout
output = str(e)
return output
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/python.html |
337471756051-0 | Source code for langchain.text_splitter
"""Functionality for splitting text."""
from __future__ import annotations
import copy
import logging
from abc import ABC, abstractmethod
from typing import (
AbstractSet,
Any,
Callable,
Collection,
Iterable,
List,
Literal,
Optional,
Union,
)
from langchain.docstore.document import Document
logger = logging.getLogger()
[docs]class TextSplitter(ABC):
"""Interface for splitting text into chunks."""
def __init__(
self,
chunk_size: int = 4000,
chunk_overlap: int = 200,
length_function: Callable[[str], int] = len,
):
"""Create a new TextSplitter."""
if chunk_overlap > chunk_size:
raise ValueError(
f"Got a larger chunk overlap ({chunk_overlap}) than chunk size "
f"({chunk_size}), should be smaller."
)
self._chunk_size = chunk_size
self._chunk_overlap = chunk_overlap
self._length_function = length_function
[docs] @abstractmethod
def split_text(self, text: str) -> List[str]:
"""Split text into multiple components."""
[docs] def create_documents(
self, texts: List[str], metadatas: Optional[List[dict]] = None
) -> List[Document]:
"""Create documents from a list of texts."""
_metadatas = metadatas or [{}] * len(texts)
documents = []
for i, text in enumerate(texts):
for chunk in self.split_text(text):
new_doc = Document(
page_content=chunk, metadata=copy.deepcopy(_metadatas[i])
) | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
337471756051-1 | page_content=chunk, metadata=copy.deepcopy(_metadatas[i])
)
documents.append(new_doc)
return documents
[docs] def split_documents(self, documents: List[Document]) -> List[Document]:
"""Split documents."""
texts = [doc.page_content for doc in documents]
metadatas = [doc.metadata for doc in documents]
return self.create_documents(texts, metadatas)
def _join_docs(self, docs: List[str], separator: str) -> Optional[str]:
text = separator.join(docs)
text = text.strip()
if text == "":
return None
else:
return text
def _merge_splits(self, splits: Iterable[str], separator: str) -> List[str]:
# We now want to combine these smaller pieces into medium size
# chunks to send to the LLM.
separator_len = self._length_function(separator)
docs = []
current_doc: List[str] = []
total = 0
for d in splits:
_len = self._length_function(d)
if (
total + _len + (separator_len if len(current_doc) > 0 else 0)
> self._chunk_size
):
if total > self._chunk_size:
logger.warning(
f"Created a chunk of size {total}, "
f"which is longer than the specified {self._chunk_size}"
)
if len(current_doc) > 0:
doc = self._join_docs(current_doc, separator)
if doc is not None:
docs.append(doc)
# Keep on popping if:
# - we have a larger chunk than in the chunk overlap | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
337471756051-2 | # - we have a larger chunk than in the chunk overlap
# - or if we still have any chunks and the length is long
while total > self._chunk_overlap or (
total + _len + (separator_len if len(current_doc) > 0 else 0)
> self._chunk_size
and total > 0
):
total -= self._length_function(current_doc[0]) + (
separator_len if len(current_doc) > 1 else 0
)
current_doc = current_doc[1:]
current_doc.append(d)
total += _len + (separator_len if len(current_doc) > 1 else 0)
doc = self._join_docs(current_doc, separator)
if doc is not None:
docs.append(doc)
return docs
[docs] @classmethod
def from_huggingface_tokenizer(cls, tokenizer: Any, **kwargs: Any) -> TextSplitter:
"""Text splitter that uses HuggingFace tokenizer to count length."""
try:
from transformers import PreTrainedTokenizerBase
if not isinstance(tokenizer, PreTrainedTokenizerBase):
raise ValueError(
"Tokenizer received was not an instance of PreTrainedTokenizerBase"
)
def _huggingface_tokenizer_length(text: str) -> int:
return len(tokenizer.encode(text))
except ImportError:
raise ValueError(
"Could not import transformers python package. "
"Please install it with `pip install transformers`."
)
return cls(length_function=_huggingface_tokenizer_length, **kwargs)
[docs] @classmethod
def from_tiktoken_encoder(
cls,
encoding_name: str = "gpt2", | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
337471756051-3 | cls,
encoding_name: str = "gpt2",
allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
disallowed_special: Union[Literal["all"], Collection[str]] = "all",
**kwargs: Any,
) -> TextSplitter:
"""Text splitter that uses tiktoken encoder to count length."""
try:
import tiktoken
except ImportError:
raise ValueError(
"Could not import tiktoken python package. "
"This is needed in order to calculate max_tokens_for_prompt. "
"Please install it with `pip install tiktoken`."
)
# create a GPT-3 encoder instance
enc = tiktoken.get_encoding(encoding_name)
def _tiktoken_encoder(text: str, **kwargs: Any) -> int:
return len(
enc.encode(
text,
allowed_special=allowed_special,
disallowed_special=disallowed_special,
**kwargs,
)
)
return cls(length_function=_tiktoken_encoder, **kwargs)
[docs]class CharacterTextSplitter(TextSplitter):
"""Implementation of splitting text that looks at characters."""
def __init__(self, separator: str = "\n\n", **kwargs: Any):
"""Create a new TextSplitter."""
super().__init__(**kwargs)
self._separator = separator
[docs] def split_text(self, text: str) -> List[str]:
"""Split incoming text and return chunks."""
# First we naively split the large input into a bunch of smaller ones.
if self._separator:
splits = text.split(self._separator)
else:
splits = list(text) | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
337471756051-4 | else:
splits = list(text)
return self._merge_splits(splits, self._separator)
[docs]class TokenTextSplitter(TextSplitter):
"""Implementation of splitting text that looks at tokens."""
def __init__(
self,
encoding_name: str = "gpt2",
allowed_special: Union[Literal["all"], AbstractSet[str]] = set(),
disallowed_special: Union[Literal["all"], Collection[str]] = "all",
**kwargs: Any,
):
"""Create a new TextSplitter."""
super().__init__(**kwargs)
try:
import tiktoken
except ImportError:
raise ValueError(
"Could not import tiktoken python package. "
"This is needed in order to for TokenTextSplitter. "
"Please install it with `pip install tiktoken`."
)
# create a GPT-3 encoder instance
self._tokenizer = tiktoken.get_encoding(encoding_name)
self._allowed_special = allowed_special
self._disallowed_special = disallowed_special
[docs] def split_text(self, text: str) -> List[str]:
"""Split incoming text and return chunks."""
splits = []
input_ids = self._tokenizer.encode(
text,
allowed_special=self._allowed_special,
disallowed_special=self._disallowed_special,
)
start_idx = 0
cur_idx = min(start_idx + self._chunk_size, len(input_ids))
chunk_ids = input_ids[start_idx:cur_idx]
while start_idx < len(input_ids):
splits.append(self._tokenizer.decode(chunk_ids))
start_idx += self._chunk_size - self._chunk_overlap | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
337471756051-5 | start_idx += self._chunk_size - self._chunk_overlap
cur_idx = min(start_idx + self._chunk_size, len(input_ids))
chunk_ids = input_ids[start_idx:cur_idx]
return splits
[docs]class RecursiveCharacterTextSplitter(TextSplitter):
"""Implementation of splitting text that looks at characters.
Recursively tries to split by different characters to find one
that works.
"""
def __init__(self, separators: Optional[List[str]] = None, **kwargs: Any):
"""Create a new TextSplitter."""
super().__init__(**kwargs)
self._separators = separators or ["\n\n", "\n", " ", ""]
[docs] def split_text(self, text: str) -> List[str]:
"""Split incoming text and return chunks."""
final_chunks = []
# Get appropriate separator to use
separator = self._separators[-1]
for _s in self._separators:
if _s == "":
separator = _s
break
if _s in text:
separator = _s
break
# Now that we have the separator, split the text
if separator:
splits = text.split(separator)
else:
splits = list(text)
# Now go merging things, recursively splitting longer texts.
_good_splits = []
for s in splits:
if self._length_function(s) < self._chunk_size:
_good_splits.append(s)
else:
if _good_splits:
merged_text = self._merge_splits(_good_splits, separator)
final_chunks.extend(merged_text)
_good_splits = []
other_info = self.split_text(s) | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
337471756051-6 | _good_splits = []
other_info = self.split_text(s)
final_chunks.extend(other_info)
if _good_splits:
merged_text = self._merge_splits(_good_splits, separator)
final_chunks.extend(merged_text)
return final_chunks
[docs]class NLTKTextSplitter(TextSplitter):
"""Implementation of splitting text that looks at sentences using NLTK."""
def __init__(self, separator: str = "\n\n", **kwargs: Any):
"""Initialize the NLTK splitter."""
super().__init__(**kwargs)
try:
from nltk.tokenize import sent_tokenize
self._tokenizer = sent_tokenize
except ImportError:
raise ImportError(
"NLTK is not installed, please install it with `pip install nltk`."
)
self._separator = separator
[docs] def split_text(self, text: str) -> List[str]:
"""Split incoming text and return chunks."""
# First we naively split the large input into a bunch of smaller ones.
splits = self._tokenizer(text)
return self._merge_splits(splits, self._separator)
[docs]class SpacyTextSplitter(TextSplitter):
"""Implementation of splitting text that looks at sentences using Spacy."""
def __init__(
self, separator: str = "\n\n", pipeline: str = "en_core_web_sm", **kwargs: Any
):
"""Initialize the spacy text splitter."""
super().__init__(**kwargs)
try:
import spacy
except ImportError:
raise ImportError(
"Spacy is not installed, please install it with `pip install spacy`."
)
self._tokenizer = spacy.load(pipeline) | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
337471756051-7 | )
self._tokenizer = spacy.load(pipeline)
self._separator = separator
[docs] def split_text(self, text: str) -> List[str]:
"""Split incoming text and return chunks."""
splits = (str(s) for s in self._tokenizer(text).sents)
return self._merge_splits(splits, self._separator)
[docs]class MarkdownTextSplitter(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Markdown-formatted headings."""
def __init__(self, **kwargs: Any):
"""Initialize a MarkdownTextSplitter."""
separators = [
# First, try to split along Markdown headings (starting with level 2)
"\n## ",
"\n### ",
"\n#### ",
"\n##### ",
"\n###### ",
# Note the alternative syntax for headings (below) is not handled here
# Heading level 2
# ---------------
# End of code block
"```\n\n",
# Horizontal lines
"\n\n***\n\n",
"\n\n---\n\n",
"\n\n___\n\n",
# Note that this splitter doesn't handle horizontal lines defined
# by *three or more* of ***, ---, or ___, but this is not handled
"\n\n",
"\n",
" ",
"",
]
super().__init__(separators=separators, **kwargs)
[docs]class LatexTextSplitter(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Latex-formatted layout elements."""
def __init__(self, **kwargs: Any):
"""Initialize a LatexTextSplitter.""" | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
337471756051-8 | """Initialize a LatexTextSplitter."""
separators = [
# First, try to split along Latex sections
"\n\\chapter{",
"\n\\section{",
"\n\\subsection{",
"\n\\subsubsection{",
# Now split by environments
"\n\\begin{enumerate}",
"\n\\begin{itemize}",
"\n\\begin{description}",
"\n\\begin{list}",
"\n\\begin{quote}",
"\n\\begin{quotation}",
"\n\\begin{verse}",
"\n\\begin{verbatim}",
## Now split by math environments
"\n\\begin{align}",
"$$",
"$",
# Now split by the normal type of lines
" ",
"",
]
super().__init__(separators=separators, **kwargs)
[docs]class PythonCodeTextSplitter(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Python syntax."""
def __init__(self, **kwargs: Any):
"""Initialize a MarkdownTextSplitter."""
separators = [
# First, try to split along class definitions
"\nclass ",
"\ndef ",
"\n\tdef ",
# Now split by the normal type of lines
"\n\n",
"\n",
" ",
"",
]
super().__init__(separators=separators, **kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/text_splitter.html |
49ea2802adfe-0 | Source code for langchain.llms.huggingface_hub
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_env
DEFAULT_REPO_ID = "gpt2"
VALID_TASKS = ("text2text-generation", "text-generation")
[docs]class HuggingFaceHub(LLM):
"""Wrapper around HuggingFaceHub models.
To use, you should have the ``huggingface_hub`` python package installed, and the
environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass
it as a named parameter to the constructor.
Only supports `text-generation` and `text2text-generation` for now.
Example:
.. code-block:: python
from langchain.llms import HuggingFaceHub
hf = HuggingFaceHub(repo_id="gpt2", huggingfacehub_api_token="my-api-key")
"""
client: Any #: :meta private:
repo_id: str = DEFAULT_REPO_ID
"""Model name to use."""
task: Optional[str] = None
"""Task to call the model with. Should be a task that returns `generated_text`."""
model_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model."""
huggingfacehub_api_token: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict: | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_hub.html |
49ea2802adfe-1 | @root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
try:
from huggingface_hub.inference_api import InferenceApi
repo_id = values["repo_id"]
client = InferenceApi(
repo_id=repo_id,
token=huggingfacehub_api_token,
task=values.get("task"),
)
if client.task not in VALID_TASKS:
raise ValueError(
f"Got invalid task {client.task}, "
f"currently only {VALID_TASKS} are supported"
)
values["client"] = client
except ImportError:
raise ValueError(
"Could not import huggingface_hub python package. "
"Please install it with `pip install huggingface_hub`."
)
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"repo_id": self.repo_id, "task": self.task},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "huggingface_hub"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_hub.html |
49ea2802adfe-2 | Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = hf("Tell me a joke.")
"""
_model_kwargs = self.model_kwargs or {}
response = self.client(inputs=prompt, params=_model_kwargs)
if "error" in response:
raise ValueError(f"Error raised by inference API: {response['error']}")
if self.client.task == "text-generation":
# Text generation return includes the starter text.
text = response[0]["generated_text"][len(prompt) :]
elif self.client.task == "text2text-generation":
text = response[0]["generated_text"]
else:
raise ValueError(
f"Got invalid task {self.client.task}, "
f"currently only {VALID_TASKS} are supported"
)
if stop is not None:
# This is a bit hacky, but I can't figure out a better way to enforce
# stop tokens when making calls to huggingface_hub.
text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_hub.html |
adb328573c57-0 | Source code for langchain.llms.replicate
"""Wrapper around Replicate API."""
import logging
from typing import Any, Dict, List, Mapping, Optional
from pydantic import Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.utils import get_from_dict_or_env
logger = logging.getLogger(__name__)
[docs]class Replicate(LLM):
"""Wrapper around Replicate models.
To use, you should have the ``replicate`` python package installed,
and the environment variable ``REPLICATE_API_TOKEN`` set with your API token.
You can find your token here: https://replicate.com/account
The model param is required, but any other model parameters can also
be passed in with the format input={model_param: value, ...}
Example:
.. code-block:: python
from langchain.llms import Replicate
replicate = Replicate(model="stability-ai/stable-diffusion: \
27b93a2413e7f36cd83da926f365628\
0b2931564ff050bf9575f1fdf9bcd7478",
input={"image_dimensions": "512x512"})
"""
model: str
input: Dict[str, Any] = Field(default_factory=dict)
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
replicate_api_token: Optional[str] = None
class Config:
"""Configuration for this pydantic config."""
extra = Extra.forbid
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in.""" | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/replicate.html |
adb328573c57-1 | """Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if field_name in extra:
raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
replicate_api_token = get_from_dict_or_env(
values, "REPLICATE_API_TOKEN", "REPLICATE_API_TOKEN"
)
values["replicate_api_token"] = replicate_api_token
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of model."""
return "replicate"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call to replicate endpoint."""
try:
import replicate as replicate_python
except ImportError:
raise ValueError(
"Could not import replicate python package. "
"Please install it with `pip install replicate`."
)
# get the model and version | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/replicate.html |
adb328573c57-2 | )
# get the model and version
model_str, version_str = self.model.split(":")
model = replicate_python.models.get(model_str)
version = model.versions.get(version_str)
# sort through the openapi schema to get the name of the first input
input_properties = sorted(
version.openapi_schema["components"]["schemas"]["Input"][
"properties"
].items(),
key=lambda item: item[1].get("x-order", 0),
)
first_input_name = input_properties[0][0]
inputs = {first_input_name: prompt, **self.input}
outputs = replicate_python.run(self.model, input={**inputs})
return outputs[0]
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/replicate.html |
c0a2f6d2c75f-0 | Source code for langchain.llms.stochasticai
"""Wrapper around StochasticAI APIs."""
import logging
import time
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, Field, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_env
logger = logging.getLogger(__name__)
[docs]class StochasticAI(LLM):
"""Wrapper around StochasticAI large language models.
To use, you should have the environment variable ``STOCHASTICAI_API_KEY``
set with your API key.
Example:
.. code-block:: python
from langchain.llms import StochasticAI
stochasticai = StochasticAI(api_url="")
"""
api_url: str = ""
"""Model name to use."""
model_kwargs: Dict[str, Any] = Field(default_factory=dict)
"""Holds any model parameters valid for `create` call not
explicitly specified."""
stochasticai_api_key: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator(pre=True)
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
"""Build extra kwargs from additional params that were passed in."""
all_required_field_names = {field.alias for field in cls.__fields__.values()}
extra = values.get("model_kwargs", {})
for field_name in list(values):
if field_name not in all_required_field_names:
if field_name in extra:
raise ValueError(f"Found {field_name} supplied twice.")
logger.warning( | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/stochasticai.html |
c0a2f6d2c75f-1 | raise ValueError(f"Found {field_name} supplied twice.")
logger.warning(
f"""{field_name} was transfered to model_kwargs.
Please confirm that {field_name} is what you intended."""
)
extra[field_name] = values.pop(field_name)
values["model_kwargs"] = extra
return values
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment."""
stochasticai_api_key = get_from_dict_or_env(
values, "stochasticai_api_key", "STOCHASTICAI_API_KEY"
)
values["stochasticai_api_key"] = stochasticai_api_key
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {
**{"endpoint_url": self.api_url},
**{"model_kwargs": self.model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "stochasticai"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to StochasticAI's complete endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = StochasticAI("Tell me a joke.")
"""
params = self.model_kwargs or {}
response_post = requests.post(
url=self.api_url,
json={"prompt": prompt, "params": params},
headers={ | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/stochasticai.html |
c0a2f6d2c75f-2 | json={"prompt": prompt, "params": params},
headers={
"apiKey": f"{self.stochasticai_api_key}",
"Accept": "application/json",
"Content-Type": "application/json",
},
)
response_post.raise_for_status()
response_post_json = response_post.json()
completed = False
while not completed:
response_get = requests.get(
url=response_post_json["data"]["responseUrl"],
headers={
"apiKey": f"{self.stochasticai_api_key}",
"Accept": "application/json",
"Content-Type": "application/json",
},
)
response_get.raise_for_status()
response_get_json = response_get.json()["data"]
text = response_get_json.get("completion")
completed = text is not None
time.sleep(0.5)
text = text[0]
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/stochasticai.html |
682875d88386-0 | Source code for langchain.llms.forefrontai
"""Wrapper around ForefrontAI APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_env
[docs]class ForefrontAI(LLM):
"""Wrapper around ForefrontAI large language models.
To use, you should have the environment variable ``FOREFRONTAI_API_KEY``
set with your API key.
Example:
.. code-block:: python
from langchain.llms import ForefrontAI
forefrontai = ForefrontAI(endpoint_url="")
"""
endpoint_url: str = ""
"""Model name to use."""
temperature: float = 0.7
"""What sampling temperature to use."""
length: int = 256
"""The maximum number of tokens to generate in the completion."""
top_p: float = 1.0
"""Total probability mass of tokens to consider at each step."""
top_k: int = 40
"""The number of highest probability vocabulary tokens to
keep for top-k-filtering."""
repetition_penalty: int = 1
"""Penalizes repeated tokens according to frequency."""
forefrontai_api_key: Optional[str] = None
base_url: Optional[str] = None
"""Base url to use, if None decides based on model name."""
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment.""" | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/forefrontai.html |
682875d88386-1 | """Validate that api key exists in environment."""
forefrontai_api_key = get_from_dict_or_env(
values, "forefrontai_api_key", "FOREFRONTAI_API_KEY"
)
values["forefrontai_api_key"] = forefrontai_api_key
return values
@property
def _default_params(self) -> Mapping[str, Any]:
"""Get the default parameters for calling ForefrontAI API."""
return {
"temperature": self.temperature,
"length": self.length,
"top_p": self.top_p,
"top_k": self.top_k,
"repetition_penalty": self.repetition_penalty,
}
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {**{"endpoint_url": self.endpoint_url}, **self._default_params}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "forefrontai"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to ForefrontAI's complete endpoint.
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = ForefrontAI("Tell me a joke.")
"""
response = requests.post(
url=self.endpoint_url,
headers={
"Authorization": f"Bearer {self.forefrontai_api_key}",
"Content-Type": "application/json",
},
json={"text": prompt, **self._default_params}, | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/forefrontai.html |
682875d88386-2 | },
json={"text": prompt, **self._default_params},
)
response_json = response.json()
text = response_json["result"][0]["completion"]
if stop is not None:
# I believe this is required since the stop tokens
# are not enforced by the model parameters
text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/forefrontai.html |
772218bb2d35-0 | Source code for langchain.llms.huggingface_endpoint
"""Wrapper around HuggingFace APIs."""
from typing import Any, Dict, List, Mapping, Optional
import requests
from pydantic import Extra, root_validator
from langchain.llms.base import LLM
from langchain.llms.utils import enforce_stop_tokens
from langchain.utils import get_from_dict_or_env
VALID_TASKS = ("text2text-generation", "text-generation")
[docs]class HuggingFaceEndpoint(LLM):
"""Wrapper around HuggingFaceHub Inference Endpoints.
To use, you should have the ``huggingface_hub`` python package installed, and the
environment variable ``HUGGINGFACEHUB_API_TOKEN`` set with your API token, or pass
it as a named parameter to the constructor.
Only supports `text-generation` and `text2text-generation` for now.
Example:
.. code-block:: python
from langchain.llms import HuggingFaceEndpoint
endpoint_url = (
"https://abcdefghijklmnop.us-east-1.aws.endpoints.huggingface.cloud"
)
hf = HuggingFaceEndpoint(
endpoint_url=endpoint_url,
huggingfacehub_api_token="my-api-key"
)
"""
endpoint_url: str = ""
"""Endpoint URL to use."""
task: Optional[str] = None
"""Task to call the model with. Should be a task that returns `generated_text`."""
model_kwargs: Optional[dict] = None
"""Key word arguments to pass to the model."""
huggingfacehub_api_token: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator() | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
772218bb2d35-1 | extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key and python package exists in environment."""
huggingfacehub_api_token = get_from_dict_or_env(
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
)
try:
from huggingface_hub.hf_api import HfApi
try:
HfApi(
endpoint="https://huggingface.co", # Can be a Private Hub endpoint.
token=huggingfacehub_api_token,
).whoami()
except Exception as e:
raise ValueError(
"Could not authenticate with huggingface_hub. "
"Please check your API token."
) from e
except ImportError:
raise ValueError(
"Could not import huggingface_hub python package. "
"Please install it with `pip install huggingface_hub`."
)
return values
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
_model_kwargs = self.model_kwargs or {}
return {
**{"endpoint_url": self.endpoint_url, "task": self.task},
**{"model_kwargs": _model_kwargs},
}
@property
def _llm_type(self) -> str:
"""Return type of llm."""
return "huggingface_endpoint"
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
"""Call out to HuggingFace Hub's inference endpoint.
Args:
prompt: The prompt to pass into the model. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
772218bb2d35-2 | Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
Returns:
The string generated by the model.
Example:
.. code-block:: python
response = hf("Tell me a joke.")
"""
_model_kwargs = self.model_kwargs or {}
# payload samples
parameter_payload = {"inputs": prompt, "parameters": _model_kwargs}
# HTTP headers for authorization
headers = {
"Authorization": f"Bearer {self.huggingfacehub_api_token}",
"Content-Type": "application/json",
}
# send request
try:
response = requests.post(
self.endpoint_url, headers=headers, json=parameter_payload
)
except requests.exceptions.RequestException as e: # This is the correct syntax
raise ValueError(f"Error raised by inference endpoint: {e}")
generated_text = response.json()
if "error" in generated_text:
raise ValueError(
f"Error raised by inference API: {generated_text['error']}"
)
if self.task == "text-generation":
# Text generation return includes the starter text.
text = generated_text[0]["generated_text"][len(prompt) :]
elif self.task == "text2text-generation":
text = generated_text[0]["generated_text"]
else:
raise ValueError(
f"Got invalid task {self.task}, "
f"currently only {VALID_TASKS} are supported"
)
if stop is not None:
# This is a bit hacky, but I can't figure out a better way to enforce
# stop tokens when making calls to huggingface_hub. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
772218bb2d35-3 | # stop tokens when making calls to huggingface_hub.
text = enforce_stop_tokens(text, stop)
return text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/_modules/langchain/llms/huggingface_endpoint.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.