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 ... | 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 d... | 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 enj... | 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
H... | 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.llm... | 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.InMemory... | 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 met... | 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 met... | 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.OpenAPIEndp... | 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
call... | 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 cl... | 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.AlephAlphaAsy... | 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)
countPenalt... | 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... | 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.SelfHostedHugg... | 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)
... | 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 (langcha... | 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(... | 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 clas... | 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... | 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)
(l... | 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... | 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)
(langcha... | 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.embeddi... | 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.Hu... | 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_s... | 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)
lo... | 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... | 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)
(langch... | 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 attri... | 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.Ope... | 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 ... | 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)... | 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 lan... | 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.... | 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.... | 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.ag... | 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_ve... | 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)
stre... | 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... | 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... | 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... | 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... | 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 ... | 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... | 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... | 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... | 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 actual... | 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 whe... | 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 Consiste... | 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... | 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 Mat... | 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
... | 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... | 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'... | 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_tok... | 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
接下来我们需要在终端中设... | 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)
现在... | 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 = Pro... | 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 ... | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-4 | # -> '\n\n彩色星足!'
第一个链成功执行了! - 一个 LLM 链。虽然这只是一种较简单的链,但理解它的工作原理会为您使用更复杂的链打下良好的基础。
要了解更多详情,请查看链的入门指南。
Agents(代理):根据用户输入动态调用链
到目前为止,我们所讨论的链都是按照预定顺序运行的。
而代理不再是这样:它们使用 LLM 确定要采取的操作以及其顺序。一个操作可以是使用工具并观察其输出,或将结果返回给用户。
如果使用得当,代理可以非常强大。在本教程中,我们将通过最简单的、最高级别的 API,向您展示如何轻松地使用代理。
为了加载代理,您应该理解以下概念:
工具: 执行特定任务的函数。这可以是诸如 Google 搜索、数据库查找... | 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_to... | 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 ... | https://langchain-cn.readthedocs.io/en/latest/getting_started/getting_started.html |
7647b6b0cca7-7 | Memory(记忆):将状态添加到链和代理中。
到目前为止,我们所讨论的所有链和代理都是无状态的。但通常情况下,您可能希望链或代理具有某种“记忆”概念,以便它可以记住有关其先前交互的信息。这种情况最清晰和简单的例子是设计聊天机器人 - 您希望它记住以前的消息,以便它可以利用上下文进行更好的对话。这将是一种“短期记忆”。在更复杂的方面,您可以想象链/代理随着时间的推移记住关键信息 - 这将是一种“长期记忆”。有关后者的更具体的想法,请参见 论文.
LangChain 提供了几个专门为此目的创建的链。本笔记本演示了使用其中一条链(ConversationChain)和两种不同类型的记忆的方法。
默认情况下,ConversationCha... | 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 ans... | 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 (
AIMes... | 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)
... | 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” 方法。如果您使用此模板,它会是这样的:
... | 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... | 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 searc... | 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.... | 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 ... | 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")... | 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,
)
f... | 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]
... | 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
... | 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."""
tr... | 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"... | 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 character... | 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(TextSplit... | 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)
[doc... | 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}",
... | 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... | 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:
... | 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.")
"""
_mod... | 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__)
[d... | 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 ... | 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(
... | 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
... | 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)
... | 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 = resp... | 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... | 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, ... | 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
... | 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... | 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"
)
... | 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.")
"""
_mod... | 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.