id stringlengths 14 16 | text stringlengths 31 2.73k | source stringlengths 49 114 |
|---|---|---|
89c8ad128972-0 | .ipynb
.pdf
Cohere
Cohere#
This example goes over how to use LangChain to interact with Cohere models
from langchain.llms import Cohere
from langchain import PromptTemplate, LLMChain
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["ques... | https://python.langchain.com/en/latest/modules/models/llms/integrations/cohere.html |
89c8ad128972-1 | llm_chain.run(question)
" Let's start with the year that Justin Beiber was born. You know that he was born in 1994. We have to go back one year. 1993.\n\n1993 was the year that the Dallas Cowboys won the Super Bowl. They won over the Buffalo Bills in Super Bowl 26.\n\nNow, let's do it backwards. According to our inform... | https://python.langchain.com/en/latest/modules/models/llms/integrations/cohere.html |
1a0579176fb4-0 | .ipynb
.pdf
Replicate
Contents
Setup
Calling a model
Chaining Calls
Replicate#
This example goes over how to use LangChain to interact with Replicate models
import os
from langchain.llms import Replicate
from langchain import PromptTemplate, LLMChain
os.environ["REPLICATE_API_TOKEN"] = "YOUR REPLICATE API TOKEN"
Setu... | https://python.langchain.com/en/latest/modules/models/llms/integrations/replicate.html |
1a0579176fb4-1 | prompt = """
Answer the following yes/no question by reasoning step by step.
Can a dog drive a car?
"""
llm(prompt)
'The legal driving age of dogs is 2. Cars are designed for humans to drive. Therefore, the final answer is yes.'
We can call any replicate model using this syntax. For example, we can call stable diffusi... | https://python.langchain.com/en/latest/modules/models/llms/integrations/replicate.html |
1a0579176fb4-2 | text2image = Replicate(model="stability-ai/stable-diffusion:db21e45d3f7023abc2a46ee38a23973f6dce16bb082a930b0c49861f96d1e5bf")
First prompt in the chain
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
chain = LLMChain(llm=llm, prompt=pr... | https://python.langchain.com/en/latest/modules/models/llms/integrations/replicate.html |
1a0579176fb4-3 | > Finished chain.
https://replicate.delivery/pbxt/BedAP1PPBwXFfkmeD7xDygXO4BcvApp1uvWOwUdHM4tcQfvCB/out-0.png
response = requests.get("https://replicate.delivery/pbxt/eq6foRJngThCAEBqse3nL3Km2MBfLnWQNd0Hy2SQRo2LuprCB/out-0.png")
img = Image.open(BytesIO(response.content))
img
previous
PromptLayer OpenAI
next
SageMakerE... | https://python.langchain.com/en/latest/modules/models/llms/integrations/replicate.html |
1d312c66675f-0 | .ipynb
.pdf
Anthropic
Anthropic#
This example goes over how to use LangChain to interact with Anthropic models
from langchain.llms import Anthropic
from langchain import PromptTemplate, LLMChain
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_vari... | https://python.langchain.com/en/latest/modules/models/llms/integrations/anthropic_example.html |
fa2a4447561e-0 | .ipynb
.pdf
GooseAI LLM Example
Contents
Install openai
Imports
Set the Environment API Key
Create the GooseAI instance
Create a Prompt Template
Initiate the LLMChain
Run the LLMChain
GooseAI LLM Example#
This notebook goes over how to use Langchain with GooseAI.
Install openai#
The openai package is required to use ... | https://python.langchain.com/en/latest/modules/models/llms/integrations/gooseai_example.html |
fa2a4447561e-1 | Initiate the LLMChain
Run the LLMChain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 06, 2023. | https://python.langchain.com/en/latest/modules/models/llms/integrations/gooseai_example.html |
0ee587f76e07-0 | .ipynb
.pdf
AI21
AI21#
This example goes over how to use LangChain to interact with AI21 models
from langchain.llms import AI21
from langchain import PromptTemplate, LLMChain
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
... | https://python.langchain.com/en/latest/modules/models/llms/integrations/ai21.html |
03d2cd35283c-0 | .ipynb
.pdf
OpenAI
OpenAI#
This example goes over how to use LangChain to interact with OpenAI models
from langchain.llms import OpenAI
from langchain import PromptTemplate, LLMChain
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["ques... | https://python.langchain.com/en/latest/modules/models/llms/integrations/openai.html |
721ad6e4cb12-0 | .ipynb
.pdf
Banana
Banana#
This example goes over how to use LangChain to interact with Banana models
import os
from langchain.llms import Banana
from langchain import PromptTemplate, LLMChain
os.environ["BANANA_API_KEY"] = "YOUR_API_KEY"
template = """Question: {question}
Answer: Let's think step by step."""
prompt = ... | https://python.langchain.com/en/latest/modules/models/llms/integrations/banana.html |
7f5da1bbc4af-0 | .ipynb
.pdf
Self-Hosted Models via Runhouse
Self-Hosted Models via Runhouse#
This example goes over how to use LangChain and Runhouse to interact with models hosted on your own GPU, or on-demand GPUs on AWS, GCP, AWS, or Lambda.
For more information, see Runhouse or the Runhouse docs.
from langchain.llms import SelfHos... | https://python.langchain.com/en/latest/modules/models/llms/integrations/self_hosted_examples.html |
7f5da1bbc4af-1 | INFO | 2023-02-17 05:42:24,016 | Time to send message: 0.48 seconds
"\n\nLet's say we're talking sports teams who won the Super Bowl in the year Justin Beiber"
You can also load more custom models through the SelfHostedHuggingFaceLLM interface:
llm = SelfHostedHuggingFaceLLM(
model_id="google/flan-t5-small",
ta... | https://python.langchain.com/en/latest/modules/models/llms/integrations/self_hosted_examples.html |
7f5da1bbc4af-2 | INFO | 2023-02-17 05:42:59,522 | Time to send message: 0.3 seconds
'john w. bush'
You can send your pipeline directly over the wire to your model, but this will only work for small models (<2 Gb), and will be pretty slow:
pipeline = load_pipeline()
llm = SelfHostedPipeline.from_pipeline(
pipeline=pipeline, hardware... | https://python.langchain.com/en/latest/modules/models/llms/integrations/self_hosted_examples.html |
3d6a48287cab-0 | .ipynb
.pdf
Hugging Face Hub
Hugging Face Hub#
This example showcases how to connect to the Hugging Face Hub.
from langchain import PromptTemplate, HuggingFaceHub, LLMChain
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
ll... | https://python.langchain.com/en/latest/modules/models/llms/integrations/huggingface_hub.html |
55e297592a5c-0 | .ipynb
.pdf
SageMakerEndpoint
SageMakerEndpoint#
This notebooks goes over how to use an LLM hosted on a SageMaker endpoint.
!pip3 install langchain boto3
from langchain.docstore.document import Document
example_doc_1 = """
Peter and Elizabeth took a taxi to attend the night party in the city. While in the party, Elizab... | https://python.langchain.com/en/latest/modules/models/llms/integrations/sagemaker.html |
55e297592a5c-1 | return response_json[0]["generated_text"]
content_handler = ContentHandler()
chain = load_qa_chain(
llm=SagemakerEndpoint(
endpoint_name="endpoint-name",
credentials_profile_name="credentials-profile-name",
region_name="us-west-2",
model_kwargs={"temperature":1e-10},
conte... | https://python.langchain.com/en/latest/modules/models/llms/integrations/sagemaker.html |
7f4b6ec11271-0 | .ipynb
.pdf
DeepInfra LLM Example
Contents
Imports
Set the Environment API Key
Create the DeepInfra instance
Create a Prompt Template
Initiate the LLMChain
Run the LLMChain
DeepInfra LLM Example#
This notebook goes over how to use Langchain with DeepInfra.
Imports#
import os
from langchain.llms import DeepInfra
from ... | https://python.langchain.com/en/latest/modules/models/llms/integrations/deepinfra_example.html |
7f4b6ec11271-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 06, 2023. | https://python.langchain.com/en/latest/modules/models/llms/integrations/deepinfra_example.html |
d1871ca7af52-0 | .ipynb
.pdf
Azure OpenAI LLM Example
Contents
API configuration
Deployments
Azure OpenAI LLM Example#
This notebook goes over how to use Langchain with Azure OpenAI.
The Azure OpenAI API is compatible with OpenAI’s API. The openai Python package makes it easy to use both OpenAI and Azure OpenAI. You can call Azure ... | https://python.langchain.com/en/latest/modules/models/llms/integrations/azure_openai_example.html |
d1871ca7af52-1 | import openai
response = openai.Completion.create(
engine="text-davinci-002-prod",
prompt="This is a test",
max_tokens=5
)
# Import Azure OpenAI
from langchain.llms import AzureOpenAI
# Create an instance of Azure OpenAI
# Replace the deployment name with your own
llm = AzureOpenAI(deployment_name="text-dav... | https://python.langchain.com/en/latest/modules/models/llms/integrations/azure_openai_example.html |
835be58d9aa3-0 | .ipynb
.pdf
Aleph Alpha
Aleph Alpha#
This example goes over how to use LangChain to interact with Aleph Alpha models
from langchain.llms import AlephAlpha
from langchain import PromptTemplate, LLMChain
template = """Q: {question}
A:"""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm = Aleph... | https://python.langchain.com/en/latest/modules/models/llms/integrations/aleph_alpha.html |
e026a881747d-0 | .ipynb
.pdf
Petals LLM Example
Contents
Install petals
Imports
Set the Environment API Key
Create the Petals instance
Create a Prompt Template
Initiate the LLMChain
Run the LLMChain
Petals LLM Example#
This notebook goes over how to use Langchain with Petals.
Install petals#
The petals package is required to use the ... | https://python.langchain.com/en/latest/modules/models/llms/integrations/petals_example.html |
e026a881747d-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 06, 2023. | https://python.langchain.com/en/latest/modules/models/llms/integrations/petals_example.html |
1d78b3c8b85a-0 | .ipynb
.pdf
CerebriumAI LLM Example
Contents
Install cerebrium
Imports
Set the Environment API Key
Create the CerebriumAI instance
Create a Prompt Template
Initiate the LLMChain
Run the LLMChain
CerebriumAI LLM Example#
This notebook goes over how to use Langchain with CerebriumAI.
Install cerebrium#
The cerebrium pa... | https://python.langchain.com/en/latest/modules/models/llms/integrations/cerebriumai_example.html |
1d78b3c8b85a-1 | llm_chain.run(question)
previous
Banana
next
Cohere
Contents
Install cerebrium
Imports
Set the Environment API Key
Create the CerebriumAI instance
Create a Prompt Template
Initiate the LLMChain
Run the LLMChain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 06, 2023. | https://python.langchain.com/en/latest/modules/models/llms/integrations/cerebriumai_example.html |
0ca8787bcc77-0 | .ipynb
.pdf
Writer
Writer#
This example goes over how to use LangChain to interact with Writer models
from langchain.llms import Writer
from langchain import PromptTemplate, LLMChain
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["ques... | https://python.langchain.com/en/latest/modules/models/llms/integrations/writer.html |
5d0acb72f4a9-0 | .ipynb
.pdf
PromptLayer OpenAI
Contents
Install PromptLayer
Imports
Set the Environment API Key
Use the PromptLayerOpenAI LLM like normal
Using PromptLayer Track
PromptLayer OpenAI#
This example showcases how to connect to PromptLayer to start recording your OpenAI requests.
Install PromptLayer#
The promptlayer packa... | https://python.langchain.com/en/latest/modules/models/llms/integrations/promptlayer_openai.html |
5d0acb72f4a9-1 | for res in llm_results.generations:
pl_request_id = res[0].generation_info["pl_request_id"]
promptlayer.track.score(request_id=pl_request_id, score=100)
Using this allows you to track the performance of your model in the PromptLayer dashboard. If you are using a prompt template, you can attach a template to a r... | https://python.langchain.com/en/latest/modules/models/llms/integrations/promptlayer_openai.html |
c6e0a21ec688-0 | .rst
.pdf
How-To Guides
How-To Guides#
The examples here all address certain “how-to” guides for working with chat models.
How to use few shot examples
How to stream responses
previous
Getting Started
next
How to use few shot examples
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated ... | https://python.langchain.com/en/latest/modules/models/chat/how_to_guides.html |
879c2d611bc7-0 | .rst
.pdf
Integrations
Integrations#
The examples here all highlight how to integrate with different chat models.
Azure
OpenAI
PromptLayer ChatOpenAI
previous
How to stream responses
next
Azure
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 06, 2023. | https://python.langchain.com/en/latest/modules/models/chat/integrations.html |
b64925539272-0 | .ipynb
.pdf
Getting Started
Contents
PromptTemplates
LLMChain
Streaming
Getting Started#
This notebook covers how to get started with chat models. The interface is based around messages rather than raw text.
from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate, LLMChain
from langchain.pro... | https://python.langchain.com/en/latest/modules/models/chat/getting_started.html |
b64925539272-1 | [
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="Translate this sentence from English to French. I love programming.")
],
[
SystemMessage(content="You are a helpful assistant that translates English to French."),
Hum... | https://python.langchain.com/en/latest/modules/models/chat/getting_started.html |
b64925539272-2 | 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 mes... | https://python.langchain.com/en/latest/modules/models/chat/getting_started.html |
b64925539272-3 | A taste that's sure to excite
Chorus:
Sparkling water, oh so fine
A drink that's always on my mind
With every sip, I feel alive
Sparkling water, you're my vibe
Verse 2:
No sugar, no calories, just pure bliss
A drink that's hard to resist
It's the perfect way to quench my thirst
A drink that always comes first
Chorus:
S... | https://python.langchain.com/en/latest/modules/models/chat/getting_started.html |
2eb8e77a830c-0 | .ipynb
.pdf
How to stream responses
How to stream responses#
This notebook goes over how to use streaming with a chat model.
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
HumanMessage,
)
from langchain.callbacks.base import CallbackManager
from langchain.callbacks.streaming_stdout impo... | https://python.langchain.com/en/latest/modules/models/chat/examples/streaming.html |
2eb8e77a830c-1 | Sparkling
previous
How to use few shot examples
next
Integrations
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 06, 2023. | https://python.langchain.com/en/latest/modules/models/chat/examples/streaming.html |
d0e1ee151a0b-0 | .ipynb
.pdf
How to use few shot examples
Contents
Alternating Human/AI messages
System Messages
How to use few shot examples#
This notebook covers how to use few shot examples in chat models.
There does not appear to be solid consensus on how best to do few shot prompting. As a result, we are not solidifying any abst... | https://python.langchain.com/en/latest/modules/models/chat/examples/few_shot_examples.html |
d0e1ee151a0b-1 | template="You are a helpful assistant that translates english to pirate."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
example_human = SystemMessagePromptTemplate.from_template("Hi", additional_kwargs={"name": "example_user"})
example_ai = SystemMessagePromptTemplate.from_template("Argh m... | https://python.langchain.com/en/latest/modules/models/chat/examples/few_shot_examples.html |
0054dae88331-0 | .ipynb
.pdf
Azure
Azure#
This notebook goes over how to connect to an Azure hosted OpenAI endpoint
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage
BASE_URL = "https://${TODO}.openai.azure.com"
API_KEY = "..."
DEPLOYMENT_NAME = "chat"
model = AzureChatOpenAI(
openai_api_ba... | https://python.langchain.com/en/latest/modules/models/chat/integrations/azure_chat_openai.html |
4f04b9079ab3-0 | .ipynb
.pdf
OpenAI
OpenAI#
This notebook covers how to get started with OpenAI chat models.
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema impo... | https://python.langchain.com/en/latest/modules/models/chat/integrations/openai.html |
4f04b9079ab3-1 | AIMessage(content="J'adore la programmation.", additional_kwargs={})
previous
Azure
next
PromptLayer ChatOpenAI
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 06, 2023. | https://python.langchain.com/en/latest/modules/models/chat/integrations/openai.html |
9167090e5f61-0 | .ipynb
.pdf
PromptLayer ChatOpenAI
Contents
Install PromptLayer
Imports
Set the Environment API Key
Use the PromptLayerOpenAI LLM like normal
Using PromptLayer Track
PromptLayer ChatOpenAI#
This example showcases how to connect to PromptLayer to start recording your ChatOpenAI requests.
Install PromptLayer#
The promp... | https://python.langchain.com/en/latest/modules/models/chat/integrations/promptlayer_chatopenai.html |
9167090e5f61-1 | chat = PromptLayerChatOpenAI(return_pl_id=True)
chat_results = chat.generate([[HumanMessage(content="I am a cat and I want")]])
for res in chat_results.generations:
pl_request_id = res[0].generation_info["pl_request_id"]
promptlayer.track.score(request_id=pl_request_id, score=100)
Using this allows you to track... | https://python.langchain.com/en/latest/modules/models/chat/integrations/promptlayer_chatopenai.html |
63df8f46d2e8-0 | .ipynb
.pdf
Hugging Face Hub
Hugging Face Hub#
Let’s load the Hugging Face Embedding class.
from langchain.embeddings import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
previous
F... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/huggingfacehub.html |
99f724511090-0 | .ipynb
.pdf
SageMaker Endpoint Embeddings
SageMaker Endpoint Embeddings#
Let’s load the SageMaker Endpoints Embeddings class. The class can be used if you host, e.g. your own Hugging Face model on SageMaker.
For instrucstions on how to do this, please see here
!pip3 install langchain boto3
from typing import Dict
from ... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/sagemaker-endpoint.html |
d49ce0f118e1-0 | .ipynb
.pdf
AzureOpenAI
AzureOpenAI#
Let’s load the OpenAI Embedding class with environment variables set to indicate to use Azure endpoints.
# set the environment variables needed for openai package to know to reach out to azure
import os
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https:/... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/azureopenai.html |
95e27a70185a-0 | .ipynb
.pdf
Llama-cpp
Llama-cpp#
This notebook goes over how to use Llama-cpp embeddings within LangChain
!pip install llama-cpp-python
from langchain.embeddings import LlamaCppEmbeddings
llama = LlamaCppEmbeddings(model_path="/path/to/model/ggml-model-q4_0.bin")
text = "This is a test document."
query_result = llama.e... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/llamacpp.html |
504f609a9dc1-0 | .ipynb
.pdf
Cohere
Cohere#
Let’s load the Cohere Embedding class.
from langchain.embeddings import CohereEmbeddings
embeddings = CohereEmbeddings(cohere_api_key=cohere_api_key)
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
previous
AzureOpe... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/cohere.html |
7d5e7aecd1a2-0 | .ipynb
.pdf
Fake Embeddings
Fake Embeddings#
LangChain also provides a fake embedding class. You can use this to test your pipelines.
from langchain.embeddings import FakeEmbeddings
embeddings = FakeEmbeddings(size=1352)
query_result = embeddings.embed_query("foo")
doc_results = embeddings.embed_documents(["foo"])
prev... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/fake.html |
c5d373f6a2f1-0 | .ipynb
.pdf
OpenAI
OpenAI#
Let’s load the OpenAI Embedding class.
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
Let’s load the OpenAI Embedding class with fir... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/openai.html |
1bba8e014240-0 | .ipynb
.pdf
Self Hosted Embeddings
Self Hosted Embeddings#
Let’s load the SelfHostedEmbeddings, SelfHostedHuggingFaceEmbeddings, and SelfHostedHuggingFaceInstructEmbeddings classes.
from langchain.embeddings import (
SelfHostedEmbeddings,
SelfHostedHuggingFaceEmbeddings,
SelfHostedHuggingFaceInstructEmbeddi... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/self-hosted.html |
1bba8e014240-1 | tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
return pipeline("feature-extraction", model=model, tokenizer=tokenizer)
def inference_fn(pipeline, prompt):
# Return last hidden state of the model
if isinstance(prompt, list):
return [emb[... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/self-hosted.html |
5e676a6f934d-0 | .ipynb
.pdf
Aleph Alpha
Contents
Asymmetric
Symmetric
Aleph Alpha#
There are two possible ways to use Aleph Alpha’s semantic embeddings. If you have texts with a dissimilar structure (e.g. a Document and a Query) you would want to use asymmetric embeddings. Conversely, for texts with comparable structures, symmetric ... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/aleph_alpha.html |
e410066be08a-0 | .ipynb
.pdf
Jina
Jina#
Let’s load the Jina Embedding class.
from langchain.embeddings import JinaEmbeddings
embeddings = JinaEmbeddings(jina_auth_token=jina_auth_token, model_name="ViT-B-32::openai")
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([t... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/jina.html |
6343ccb96fd8-0 | .ipynb
.pdf
TensorflowHub
TensorflowHub#
Let’s load the TensorflowHub Embedding class.
from langchain.embeddings import TensorflowHubEmbeddings
embeddings = TensorflowHubEmbeddings()
2023-01-30 23:53:01.652176: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neu... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/tensorflowhub.html |
cdcd88695684-0 | .ipynb
.pdf
InstructEmbeddings
InstructEmbeddings#
Let’s load the HuggingFace instruct Embeddings class.
from langchain.embeddings import HuggingFaceInstructEmbeddings
embeddings = HuggingFaceInstructEmbeddings(
query_instruction="Represent the query for retrieval: "
)
load INSTRUCTOR_Transformer
max_seq_length 51... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/instruct_embeddings.html |
d4a84f9990a7-0 | .rst
.pdf
How-To Guides
How-To Guides#
A chain is made up of links, which can be either primitives or other chains.
Primitives can be either prompts, models, arbitrary functions, or other chains.
The examples here are broken up into three sections:
Generic Functionality
Covers both generic chains (that are useful in a ... | https://python.langchain.com/en/latest/modules/chains/how_to_guides.html |
70299e850881-0 | .ipynb
.pdf
Getting Started
Contents
Why do we need chains?
Query an LLM with the LLMChain
Combine chains with the SequentialChain
Create a custom chain with the Chain class
Getting Started#
In this tutorial, we will learn about creating simple chains in LangChain. We will learn how to create a chain, add components ... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
70299e850881-1 | print(chain.run("colorful socks"))
Rainbow Socks Co.
You can use a chat model in an LLMChain as well:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
)
human_message_prompt = HumanMessagePromptTemplate(
prompt=PromptTempla... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
70299e850881-2 | template="Write a catchphrase for the following company: {company_name}",
)
chain_two = LLMChain(llm=llm, prompt=second_prompt)
Now we can combine the two LLMChains, so that we can create a company name and a catchphrase in a single step.
from langchain.chains import SimpleSequentialChain
overall_chain = SimpleSequenti... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
70299e850881-3 | return list(all_input_vars)
@property
def output_keys(self) -> List[str]:
return ['concat_output']
def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:
output_1 = self.chain_1.run(inputs)
output_2 = self.chain_2.run(inputs)
return {'concat_output': output_1 + output_2}
... | https://python.langchain.com/en/latest/modules/chains/getting_started.html |
a6e232491019-0 | .ipynb
.pdf
Question Answering with Sources
Contents
Prepare Data
Quickstart
The stuff Chain
The map_reduce Chain
The refine Chain
The map-rerank Chain
Question Answering with Sources#
This notebook walks through how to use LangChain for question answering with sources over a list of documents. It covers four differe... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-1 | from langchain.chains.qa_with_sources import load_qa_with_sources_chain
from langchain.llms import OpenAI
Quickstart#
If you just want to get started as quickly as possible, this is the recommended way to do it:
chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type="stuff")
query = "What did the presiden... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-2 | PROMPT = PromptTemplate(template=template, input_variables=["summaries", "question"])
chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type="stuff", prompt=PROMPT)
query = "What did the president say about Justice Breyer"
chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'out... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-3 | ' None',
' None',
' None'],
'output_text': ' The president thanked Justice Breyer for his service.\nSOURCES: 30-pl'}
Custom Prompts
You can also use your own prompts with this chain. In this example, we will respond in Italian.
question_prompt_template = """Use the following portion of a long document to see if an... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-4 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'intermediate_steps': ["\nStasera vorrei onorare qualcuno che ha dedicato la sua vita a servire questo paese: il giustizia Stephen Breyer - un veterano dell'esercito, uno studioso costituzionale e un giustizia in uscita della Corte Suprema d... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-5 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output_text': "\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked him for his service and praised his c... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-6 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'intermediate_steps': ['\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service.... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-7 | '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-8 | '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-9 | 'output_text': '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal publi... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-10 | "answer the question (in Italian)"
"If you do update it, please update the sources as well. "
"If the context isn't useful, return the original answer."
)
refine_prompt = PromptTemplate(
input_variables=["question", "existing_answer", "context_str"],
template=refine_template,
)
question_template = (
... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-11 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-12 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-13 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sottolineato l'impor... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-14 | 'output_text': "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese, ha onorato la sua carriera e ha contribuito a costruire un consenso. Ha ricevuto un ampio sostegno, dall'Ordine Fraterno della Polizia a ex giudici nominati da democratici e repubblicani. Inoltre, ha sotto... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-15 | 'score': '100'},
{'answer': ' This document does not answer the question', 'score': '0'},
{'answer': ' This document does not answer the question', 'score': '0'},
{'answer': ' This document does not answer the question', 'score': '0'}]
Custom Prompts
You can also use your own prompts with this chain. In this example... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
a6e232491019-16 | result
{'source': 30,
'intermediate_steps': [{'answer': ' Il presidente ha detto che Justice Breyer ha dedicato la sua vita a servire questo paese e ha onorato la sua carriera.',
'score': '100'},
{'answer': ' Il presidente non ha detto nulla sulla Giustizia Breyer.',
'score': '100'},
{'answer': ' Non so.', '... | https://python.langchain.com/en/latest/modules/chains/index_examples/qa_with_sources.html |
6c5c4a2786d3-0 | .ipynb
.pdf
Retrieval Question/Answering
Contents
Chain Type
Custom Prompts
Return Source Documents
Retrieval Question/Answering#
This example showcases question answering over an index.
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter imp... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
6c5c4a2786d3-1 | There are two ways to load different chain types. First, you can specify the chain type argument in the from_chain_type method. This allows you to pass in the name of the chain type you want to use. For example, in the below we change the chain type to map_reduce.
qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_ty... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
6c5c4a2786d3-2 | query = "What did the president say about Ketanji Brown Jackson"
qa.run(query)
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also s... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
6c5c4a2786d3-3 | Return Source Documents#
Additionally, we can return the source documents used to answer the question by specifying an optional parameter when constructing the chain.
qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=docsearch.as_retriever(), return_source_documents=True)
query = "What did th... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
6c5c4a2786d3-4 | Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
6c5c4a2786d3-5 | Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
6c5c4a2786d3-6 | Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \n\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \n\nThat ends on my watch. \n\nMedicare is going to set higher standards ... | https://python.langchain.com/en/latest/modules/chains/index_examples/vector_db_qa.html |
0784b6c64abc-0 | .ipynb
.pdf
Question Answering
Contents
Prepare Data
Quickstart
The stuff Chain
The map_reduce Chain
The refine Chain
The map-rerank Chain
Question Answering#
This notebook walks through how to use LangChain for question answering over a list of documents. It covers four different types of chains: stuff, map_reduce, ... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-1 | chain.run(input_documents=docs, question=query)
' The president said that he was honoring Justice Breyer for his service to the country and that he was a Constitutional scholar, Army veteran, and retiring Justice of the United States Supreme Court.'
If you want more control and understanding over what is happening, ple... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-2 | The map_reduce Chain#
This sections shows results of using the map_reduce Chain to do question answering.
chain = load_qa_chain(OpenAI(temperature=0), chain_type="map_reduce")
query = "What did the president say about Justice Breyer"
chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-3 | template=question_prompt_template, input_variables=["context", "question"]
)
combine_prompt_template = """Given the following extracted parts of a long document and a question, create a final answer italian.
If you don't know the answer, just say that you don't know. Don't try to make up an answer.
QUESTION: {question... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-4 | '\nNella mia amministrazione, i guardiani sono stati accolti di nuovo. Stiamo andando dietro ai criminali che hanno rubato miliardi di dollari di aiuti di emergenza destinati alle piccole imprese e a milioni di americani. E stasera, annuncio che il Dipartimento di Giustizia nominerà un procuratore capo per la frode pan... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-5 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output_text': '\n\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his commitment to protecti... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-6 | '\n\nThe president said that he wanted to honor Justice Breyer for his dedication to serving the country, his legacy of excellence, and his commitment to advancing liberty and justice, as well as for his commitment to protecting the rights of LGBTQ+ Americans and his support for the bipartisan Equality Act. He also men... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-7 | input_variables=["question", "existing_answer", "context_str"],
template=refine_prompt_template,
)
initial_qa_template = (
"Context information is below. \n"
"---------------------\n"
"{context_str}"
"\n---------------------\n"
"Given the context information and not prior knowledge, "
"answe... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-8 | "\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto livel... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-9 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto liv... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-10 | "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvocato di alto liv... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-11 | 'output_text': "\n\nIl presidente ha detto che Justice Breyer ha dedicato la sua vita al servizio di questo paese e ha onorato la sua carriera. Ha anche detto che la sua nomina di Circuit Court of Appeals Judge Ketanji Brown Jackson continuerà il suo eccezionale lascito. Ha sottolineato che la sua esperienza come avvoc... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
0784b6c64abc-12 | 'score': '100'},
{'answer': " The president said that Justice Breyer is a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that since she's been nominated, she's received a broad range of support from the Fraterna... | https://python.langchain.com/en/latest/modules/chains/index_examples/question_answering.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.