id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
9c3e20eb52bd-0 | .ipynb
.pdf
Pandas Dataframe Agent
Pandas Dataframe Agent#
This notebook shows how to use agents to interact with a pandas dataframe. It is mostly optimized for question answering.
NOTE: this agent calls the Python agent under the hood, which executes LLM generated Python code - this can be bad if the LLM generated Pyt... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html |
9c3e20eb52bd-1 | > Finished chain.
'30 people have more than 3 siblings.'
agent.run("whats the square root of the average age?")
> Entering new AgentExecutor chain...
Thought: I need to calculate the average age first
Action: python_repl_ast
Action Input: df['Age'].mean()
Observation: 29.69911764705882
Thought: I can now calculate the ... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html |
deaa0209a33d-0 | .ipynb
.pdf
PowerBI Dataset Agent
Contents
Some notes
Initialization
Example: describing a table
Example: simple query on a table
Example: running queries
Example: add your own few-shot prompts
PowerBI Dataset Agent#
This notebook showcases an agent designed to interact with a Power BI Dataset. The agent is designed ... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/powerbi.html |
deaa0209a33d-1 | from azure.identity import DefaultAzureCredential
fast_llm = AzureOpenAI(temperature=0.5, max_tokens=1000, deployment_name="gpt-35-turbo", verbose=True)
smart_llm = AzureOpenAI(temperature=0, max_tokens=100, deployment_name="gpt-4", verbose=True)
toolkit = PowerBIToolkit(
powerbi=PowerBIDataset(dataset_id="<dataset... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/powerbi.html |
deaa0209a33d-2 | ----
Question: How many rows are in the table revenue where year is not empty?
DAX: EVALUATE ROW("Number of rows", COUNTROWS(FILTER(revenue_details, revenue_details[year] <> "")))
----
Question: What was the average of value in revenue in dollars?
DAX: EVALUATE ROW("Average", AVERAGE(revenue_details[dollar_value]))
---... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/powerbi.html |
4501e6aecb55-0 | .ipynb
.pdf
Jira
Jira#
This notebook goes over how to use the Jira tool.
The Jira tool allows agents to interact with a given Jira instance, performing actions such as searching for issues and creating issues, the tool wraps the atlassian-python-api library, for more see: https://atlassian-python-api.readthedocs.io/jir... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/jira.html |
4501e6aecb55-1 | verbose=True
)
agent.run("make a new issue in project PW to remind me to make more fried rice")
> Entering new AgentExecutor chain...
I need to create an issue in project PW
Action: Create Issue
Action Input: {"summary": "Make more fried rice", "description": "Reminder to make more fried rice", "issuetype": {"name": "... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/jira.html |
0144290d9949-0 | .ipynb
.pdf
JSON Agent
Contents
Initialization
Example: getting the required POST parameters for a request
JSON Agent#
This notebook showcases an agent designed to interact with large JSON/dict objects. This is useful when you want to answer questions about a JSON blob that’s too large to fit in the context window of... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
0144290d9949-1 | verbose=True
)
Example: getting the required POST parameters for a request#
json_agent_executor.run("What are the required parameters in the request body to the /completions endpoint?")
> Entering new AgentExecutor chain...
Action: json_spec_list_keys
Action Input: data
Observation: ['openapi', 'info', 'servers', 'tags... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
0144290d9949-2 | Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]
Observation: ['post']
Thought: I should look at the post key to see what parameters are required
Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]
Observation: ['operationId', 'tags', 'summary', 'requestBody', 'respons... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
0144290d9949-3 | Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]
Observation: ['schema']
Thought: I should look at the schema key to see what parameters are required
Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]["requestBody"... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
0144290d9949-4 | Observation: ['model']
Thought: I now know the final answer
Final Answer: The required parameters in the request body to the /completions endpoint are 'model'.
> Finished chain.
"The required parameters in the request body to the /completions endpoint are 'model'."
previous
Jira
next
OpenAPI agents
Contents
Initial... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
aa76cc27cf85-0 | .ipynb
.pdf
OpenAPI agents
Contents
1st example: hierarchical planning agent
To start, let’s collect some OpenAPI specs.
How big is this spec?
Let’s see some examples!
Try another API.
2nd example: “json explorer” agent
OpenAPI agents#
We can construct agents to consume arbitrary APIs, here APIs conformant to the Ope... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-1 | !mv api-docs klarna_openapi.yaml
!wget https://raw.githubusercontent.com/APIs-guru/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yaml
!mv openapi.yaml spotify_openapi.yaml
--2023-03-31 15:45:56-- https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml
Resolving raw.githubusercontent.com (ra... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-2 | HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/json]
Saving to: ‘api-docs’
api-docs [ <=> ] 1.87K --.-KB/s in 0s
2023-03-31 15:45:57 (261 MB/s) - ‘api-docs’ saved [1916]
--2023-03-31 15:45:57-- https://raw.githubusercontent.com/APIs-guru/openap... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-3 | with open("klarna_openapi.yaml") as f:
raw_klarna_api_spec = yaml.load(f, Loader=yaml.Loader)
klarna_api_spec = reduce_openapi_spec(raw_klarna_api_spec)
with open("spotify_openapi.yaml") as f:
raw_spotify_api_spec = yaml.load(f, Loader=yaml.Loader)
spotify_api_spec = reduce_openapi_spec(raw_spotify_api_spec)
We... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-4 | def construct_spotify_auth_headers(raw_spec: dict):
scopes = list(raw_spec['components']['securitySchemes']['oauth_2_0']['flows']['authorizationCode']['scopes'].keys())
access_token = util.prompt_for_user_token(scope=','.join(scopes))
return {
'Authorization': f'Bearer {access_token}'
}
# Get AP... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-5 | llm = OpenAI(model_name="gpt-4", temperature=0.0)
/Users/jeremywelborn/src/langchain/langchain/llms/openai.py:169: UserWarning: You are trying to use a chat model. This way of initializing it is no longer supported. Instead, please use: `from langchain.chat_models import ChatOpenAI`
warnings.warn(
/Users/jeremywelbor... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-6 | 5. POST /playlists/{playlist_id}/tracks to add the first song from "Kind of Blue" to the "Machine Blues" playlist
Thought:I have the plan, now I need to execute the API calls.
Action: api_controller
Action Input: 1. GET /search to search for the album "Kind of Blue"
2. GET /albums/{id}/tracks to get the tracks from the... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-7 | Thought:Action: requests_get
Action Input: {"url": "https://api.spotify.com/v1/me", "output_instructions": "Extract the id of the current user"}
Observation: 22rhrz4m4kvpxlsb5hezokzwi
Thought:Action: requests_post
Action Input: {"url": "https://api.spotify.com/v1/users/22rhrz4m4kvpxlsb5hezokzwi/playlists", "data": {"na... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-8 | > Finished chain.
Observation: The first song from the "Kind of Blue" album has been added to the "Machine Blues" playlist.
Thought:I am finished executing the plan and have created the playlist with the first song from Kind of Blue.
Final Answer: I have created a playlist called "Machine Blues" with the first song fro... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-9 | > Entering new AgentExecutor chain...
Action: requests_get
Action Input: {"url": "https://api.spotify.com/v1/me", "output_instructions": "Extract the user's id and username"}
Observation: ID: 22rhrz4m4kvpxlsb5hezokzwi, Username: Jeremy Welborn
Thought:Action: requests_get
Action Input: {"url": "https://api.spotify.com/... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-10 | Observation: acoustic, afrobeat, alt-rock, alternative, ambient, anime, black-metal, bluegrass, blues, bossanova, brazil, breakbeat, british, cantopop, chicago-house, children, chill, classical, club, comedy, country, dance, dancehall, death-metal, deep-house, detroit-techno, disco, disney, drum-and-bass, dub, dubstep,... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-11 | Action: requests_get
Action Input: {"url": "https://api.spotify.com/v1/recommendations?seed_genres=blues", "output_instructions": "Extract the list of recommended tracks with their ids and names"}
Observation: [
{
id: '03lXHmokj9qsXspNsPoirR',
name: 'Get Away Jordan'
}
]
Thought:I am finished executing the ... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-12 | }
openai_requests_wrapper=RequestsWrapper(headers=headers)
# Meta!
llm = OpenAI(model_name="gpt-4", temperature=0.25)
openai_agent = planner.create_openapi_agent(openai_api_spec, openai_requests_wrapper, llm)
user_query = "generate a short piece of advice"
openai_agent.run(user_query)
> Entering new AgentExecutor chain... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-13 | Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-001, ada, babbage-code-search-text, babbage-similarity, whisper-1, code-search-babbage-text-001, text-curie-001, code-search-babbage-code-001, text-ada-001, text-embedding-ada... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-14 | Observation: "you must provide a model parameter"
Thought:!! Could not _extract_tool_and_input from "I cannot finish executing the plan without knowing how to provide the model parameter correctly." in _get_next_action
I cannot finish executing the plan without knowing how to provide the model parameter correctly.
> Fi... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-15 | Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada
Thought:Action: requests_post
Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"model": "davinci", "prompt": "Give me a short piece of adv... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-16 | 3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice
Thought:I have an updated plan, now I need to execute the API calls.
Action: api_controller
Action Input: 1. GET /models to retrieve the list of available models
2. Choose a suitable mod... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-17 | > Finished chain.
Observation: Some basic advice for improving communication skills would be to make sure to listen.
Thought:I am finished executing the plan and have the information the user asked for.
Final Answer: A short piece of advice for improving communication skills is to make sure to listen.
> Finished chain.... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-18 | openapi_agent_executor = create_openapi_agent(
llm=OpenAI(temperature=0),
toolkit=openapi_toolkit,
verbose=True
)
openapi_agent_executor.run("Make a post request to openai /completions. The prompt should be 'tell me a joke.'")
> Entering new AgentExecutor chain...
Action: json_explorer
Action Input: What is... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-19 | Thought: I should find the path for the /completions endpoint.
Action: json_explorer
Action Input: What is the path for the /completions endpoint?
> Entering new AgentExecutor chain...
Action: json_spec_list_keys
Action Input: data
Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta']
... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-20 | Thought: I now know the path for the /completions endpoint
Final Answer: The path for the /completions endpoint is data["paths"][2]
> Finished chain.
Observation: The path for the /completions endpoint is data["paths"][2]
Thought: I should find the required parameters for the POST request.
Action: json_explorer
Action ... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-21 | Action Input: data["paths"]
Observation: ['/engines', '/engines/{engine_id}', '/completions', '/chat/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/audio/transcriptions', '/audio/translations', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-22 | Observation: ['operationId', 'tags', 'summary', 'requestBody', 'responses', 'x-oaiMeta']
Thought: I should look at the requestBody key to see what parameters are required
Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]["requestBody"]
Observation: ['required', 'content']
Thought: I should... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-23 | Action: json_spec_list_keys
Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"]
Observation: ValueError('Value at path `data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"]` is not a dict, get the value dire... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-24 | Observation: ['model']
Thought: I now know the final answer
Final Answer: The required parameters for a POST request to the /completions endpoint are 'model'.
> Finished chain.
Observation: The required parameters for a POST request to the /completions endpoint are 'model'.
Thought: I now know the parameters needed to ... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-25 | Thought: I now know the final answer.
Final Answer: The response of the POST request is {"id":"cmpl-70Ivzip3dazrIXU8DSVJGzFJj2rdv","object":"text_completion","created":1680307139,"model":"davinci","choices":[{"text":" with mummy not there”\n\nYou dig deep and come up with,","index":0,"logprobs":null,"finish_reason":"le... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
aa76cc27cf85-26 | How big is this spec?
Let’s see some examples!
Try another API.
2nd example: “json explorer” agent
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
006f7d6e5f9f-0 | .ipynb
.pdf
Vectorstore Agent
Contents
Create the Vectorstores
Initialize Toolkit and Agent
Examples
Multiple Vectorstores
Examples
Vectorstore Agent#
This notebook showcases an agent designed to retrieve information from one or more vectorstores, either with or without sources.
Create the Vectorstores#
from langchai... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
006f7d6e5f9f-1 | ruff_store = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff")
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
Initialize Toolkit and Agent#
First, we’ll create an agent with a single vectorstore.
from langchain.agents.agent_toolkits import (
c... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
006f7d6e5f9f-2 | > Finished chain.
"Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address? List the source.")
> Entering new AgentExecutor chain..... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
006f7d6e5f9f-3 | Multiple Vectorstores#
We can also easily use this initialize an agent with multiple vectorstores and use the agent to route between them. To do this. This agent is optimized for routing, so it is a different toolkit and initializer.
from langchain.agents.agent_toolkits import (
create_vectorstore_router_agent,
... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
006f7d6e5f9f-4 | > Finished chain.
"Biden said that Ketanji Brown Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
agent_executor.run("What tool does ruff use to run over Jupyter Notebooks?")
> Entering new AgentExecutor chain...
I need to find out what tool ruff uses to... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
006f7d6e5f9f-5 | Action: ruff
Action Input: What tool does ruff use to run over Jupyter Notebooks?
Observation: Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.ipynb
Thought: I need to fin... | /content/https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
0ff6bd4137b6-0 | .rst
.pdf
Prompt Templates
Prompt Templates#
Note
Conceptual Guide
Language models take text as input - that text is commonly referred to as a prompt.
Typically this is not simply a hardcoded string but rather a combination of a template, some examples, and user input.
LangChain provides several classes and functions t... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates.html |
5360c080166a-0 | .rst
.pdf
Output Parsers
Output Parsers#
Note
Conceptual Guide
Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in.
Output parsers are classes that help structure language model responses. There are two main methods an out... | /content/https://python.langchain.com/en/latest/modules/prompts/output_parsers.html |
f454ffbfd101-0 | .ipynb
.pdf
Chat Prompt Template
Chat Prompt Template#
Chat Models takes a list of chat messages as input - this list commonly referred to as a prompt.
Typically this is not simply a hardcoded list of messages but rather a combination of a template, some examples, and user input.
LangChain provides several classes and ... | /content/https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html |
f454ffbfd101-1 | chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
# get a chat completion from the formatted messages
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages()
[SystemMessage(content='You are a helpful assistant th... | /content/https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html |
14b9d2cfa9f1-0 | .rst
.pdf
Example Selectors
Example Selectors#
Note
Conceptual Guide
If you have a large number of examples, you may need to select which ones to include in the prompt. The ExampleSelector is the class responsible for doing so.
The base interface is defined as below:
class BaseExampleSelector(ABC):
"""Interface for... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors.html |
e8f6df4103b1-0 | .rst
.pdf
How-To Guides
How-To Guides#
If you’re new to the library, you may want to start with the Quickstart.
The user guide here shows more advanced workflows and how to use the library in different ways.
Connecting to a Feature Store
How to create a custom prompt template
How to create a prompt template that uses f... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/how_to_guides.html |
eb6a72b64af0-0 | .md
.pdf
Getting Started
Contents
What is a prompt template?
Create a prompt template
Template formats
Validate template
Serialize prompt template
Pass few shot examples to a prompt template
Select examples for a prompt template
Getting Started#
In this tutorial, we will learn about:
what a prompt template is, and wh... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
eb6a72b64af0-1 | from langchain import PromptTemplate
# An example prompt with no input variables
no_input_prompt = PromptTemplate(input_variables=[], template="Tell me a joke.")
no_input_prompt.format()
# -> "Tell me a joke."
# An example prompt with one input variable
one_input_prompt = PromptTemplate(input_variables=["adjective"], t... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
eb6a72b64af0-2 | # -> Tell me a funny joke about chickens.
You can create custom prompt templates that format the prompt in any way you want. For more information, see Custom Prompt Templates.
Template formats#
By default, PromptTemplate will treat the provided template as a Python f-string. You can specify other template format throug... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
eb6a72b64af0-3 | validate_template=False) # No error
Serialize prompt template#
You can save your PromptTemplate into a file in your local filesystem. langchain will automatically infer the file format through the file extension name. Currently, langchain supports saving template to YAML and JSON file.
prompt_template.save("awesome_pro... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
eb6a72b64af0-4 | from langchain import PromptTemplate, FewShotPromptTemplate
# First, create the list of few shot examples.
examples = [
{"word": "happy", "antonym": "sad"},
{"word": "tall", "antonym": "short"},
]
# Next, we specify the template to format the examples we have provided.
# We use the `PromptTemplate` class for th... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
eb6a72b64af0-5 | input_variables=["input"],
# The example_separator is the string we will use to join the prefix, examples, and suffix together with.
example_separator="\n\n",
)
# We can now generate a prompt using the `format` method.
print(few_shot_prompt.format(input="big"))
# -> Give the antonym of every input
# ->
# -> Wo... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
eb6a72b64af0-6 | {"word": "tall", "antonym": "short"},
{"word": "energetic", "antonym": "lethargic"},
{"word": "sunny", "antonym": "gloomy"},
{"word": "windy", "antonym": "calm"},
]
# We'll use the `LengthBasedExampleSelector` to select the examples.
example_selector = LengthBasedExampleSelector(
# These are the example... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
eb6a72b64af0-7 | # ->
# -> Word: happy
# -> Antonym: sad
# ->
# -> Word: tall
# -> Antonym: short
# ->
# -> Word: energetic
# -> Antonym: lethargic
# ->
# -> Word: sunny
# -> Antonym: gloomy
# ->
# -> Word: windy
# -> Antonym: calm
# ->
# -> Word: big
# -> Antonym:
In contrast, if we provide a very long input, the LengthBasedExampleSel... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
2e13cc6c0d0e-0 | .ipynb
.pdf
Connecting to a Feature Store
Contents
Feast
Load Feast Store
Prompts
Use in a chain
Connecting to a Feature Store#
Feature stores are a concept from traditional machine learning that make sure data fed into models is up-to-date and relevant. For more on this, see here.
This concept is extremely relevant ... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
2e13cc6c0d0e-1 | Prompts#
Here we will set up a custom FeastPromptTemplate. This prompt template will take in a driver id, look up their stats, and format those stats into a prompt.
Note that the input to this prompt template is just driver_id, since that is the only user defined piece (all other variables are looked up inside the prom... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
2e13cc6c0d0e-2 | kwargs["acc_rate"] = feature_vector["acc_rate"][0]
kwargs["avg_daily_trips"] = feature_vector["avg_daily_trips"][0]
return prompt.format(**kwargs)
prompt_template = FeastPromptTemplate(input_variables=["driver_id"])
print(prompt_template.format(driver_id=1001))
Given the driver's up to date stats, write... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
2e13cc6c0d0e-3 | previous
How-To Guides
next
How to create a custom prompt template
Contents
Feast
Load Feast Store
Prompts
Use in a chain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/connecting_to_a_feature_store.html |
7b89d5172964-0 | .ipynb
.pdf
How to create a custom prompt template
Contents
Why are custom prompt templates needed?
Creating a Custom Prompt Template
Use the custom prompt template
How to create a custom prompt template#
Let’s suppose we want the LLM to generate English language explanations of a function given its name. To achieve ... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
7b89d5172964-1 | import inspect
def get_source_code(function_name):
# Get the source code of the function
return inspect.getsource(function_name)
Next, we’ll create a custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function.
from langchain.prompt... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
7b89d5172964-2 | fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])
# Generate a prompt for the function "get_source_code"
prompt = fn_explainer.format(function_name=get_source_code)
print(prompt)
Given the function name and source code, generate an English language explanation of the function.
... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/custom_prompt_template.html |
9486f5162824-0 | .ipynb
.pdf
How to serialize prompts
Contents
PromptTemplate
Loading from YAML
Loading from JSON
Loading Template from a File
FewShotPromptTemplate
Examples
Loading from YAML
Loading from JSON
Examples in the Config
Example Prompt from a File
How to serialize prompts#
It is often preferrable to store prompts not as p... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
9486f5162824-1 | Loading from YAML#
This shows an example of loading a PromptTemplate from YAML.
!cat simple_prompt.yaml
_type: prompt
input_variables:
["adjective", "content"]
template:
Tell me a {adjective} joke about {content}.
prompt = load_prompt("simple_prompt.yaml")
print(prompt.format(adjective="funny", content="chicke... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
9486f5162824-2 | print(prompt.format(adjective="funny", content="chickens"))
Tell me a funny joke about chickens.
FewShotPromptTemplate#
This section covers examples for loading few shot prompt templates.
Examples#
This shows an example of what examples stored as json might look like.
!cat examples.json
[
{"input": "happy", "output... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
9486f5162824-3 | !cat few_shot_prompt_yaml_examples.yaml
_type: few_shot
input_variables:
["adjective"]
prefix:
Write antonyms for the following words.
example_prompt:
_type: prompt
input_variables:
["input", "output"]
template:
"Input: {input}\nOutput: {output}"
examples:
examples.yaml
suffix:
... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
9486f5162824-4 | print(prompt.format(adjective="funny"))
Write antonyms for the following words.
Input: happy
Output: sad
Input: tall
Output: short
Input: funny
Output:
Examples in the Config#
This shows an example of referencing the examples directly in the config.
!cat few_shot_prompt_examples_in.json
{
"_type": "few_shot",
"... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
9486f5162824-5 | !cat example_prompt.json
{
"_type": "prompt",
"input_variables": ["input", "output"],
"template": "Input: {input}\nOutput: {output}"
}
!cat few_shot_prompt_example_prompt.json
{
"_type": "few_shot",
"input_variables": ["adjective"],
"prefix": "Write antonyms for the following words.",
"exa... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/prompt_serialization.html |
205a63fa1c3a-0 | .ipynb
.pdf
How to work with partial Prompt Templates
Contents
Partial With Strings
Partial With Functions
How to work with partial Prompt Templates#
A prompt template is a class with a .format method which takes in a key-value map and returns a string (a prompt) to pass to the language model. Like other methods, it ... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html |
205a63fa1c3a-1 | partial_prompt = prompt.partial(foo="foo");
print(partial_prompt.format(bar="baz"))
foobaz
You can also just initialize the prompt with the partialed variables.
prompt = PromptTemplate(template="{foo}{bar}", input_variables=["bar"], partial_variables={"foo": "foo"})
print(prompt.format(bar="baz"))
foobaz
Partial With F... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html |
205a63fa1c3a-2 | Tell me a funny joke about the day 02/27/2023, 22:15:16
You can also just initialize the prompt with the partialed variables, which often makes more sense in this workflow.
prompt = PromptTemplate(
template="Tell me a {adjective} joke about the day {date}",
input_variables=["adjective"],
partial_variables=... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/partial.html |
be828d92e133-0 | .ipynb
.pdf
How to create a prompt template that uses few shot examples
Contents
Use Case
Using an example set
Create the example set
Create a formatter for the few shot examples
Feed examples and formatter to FewShotPromptTemplate
Using an example selector
Feed examples into ExampleSelector
Feed example selector int... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
be828d92e133-1 | Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
"""
},
{
"question": "When was the founder of craigslist born?",
"answer":
"""
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was fou... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
be828d92e133-2 | """
}
]
Create a formatter for the few shot examples#
Configure a formatter that will format the few shot examples into a string. This formatter should be a PromptTemplate object.
example_prompt = PromptTemplate(input_variables=["question", "answer"], template="Question: {question}\n{answer}")
print(example_prompt.fo... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
be828d92e133-3 | Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
Question: When was the founder of craigslist born?
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
be828d92e133-4 | Using an example selector#
Feed examples into ExampleSelector#
We will reuse the example set and the formatter from the previous section. However, instead of feeding the examples directly into the FewShotPromptTemplate object, we will feed them into an ExampleSelector object.
In this tutorial, we will use the SemanticS... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
be828d92e133-5 | for example in selected_examples:
print("\n")
for k, v in example.items():
print(f"{k}: {v}")
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
Examples most similar to the input: Who was the father of Mary Ball Washington?
question: Who was the maternal... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
be828d92e133-6 | So the final answer is: Joseph Ball
Question: Who was the father of Mary Ball Washington?
previous
How to create a custom prompt template
next
How to work with partial Prompt Templates
Contents
Use Case
Using an example set
Create the example set
Create a formatter for the few shot examples
Feed examples and format... | /content/https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
618d270c273d-0 | .ipynb
.pdf
NGram Overlap ExampleSelector
NGram Overlap ExampleSelector#
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive.
The selector allows for a th... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
618d270c273d-1 | {"input": "windy", "output": "calm"},
]
# These are examples of a fictional translation task.
examples = [
{"input": "See Spot run.", "output": "Ver correr a Spot."},
{"input": "My dog barks.", "output": "Mi perro ladra."},
{"input": "Spot can run.", "output": "Spot puede correr."},
]
example_prompt = Promp... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
618d270c273d-2 | example_selector=example_selector,
example_prompt=example_prompt,
prefix="Give the Spanish translation of every input",
suffix="Input: {sentence}\nOutput:",
input_variables=["sentence"],
)
# An example input with large ngram overlap with "Spot can run."
# and no overlap with "My dog barks."
print(dynam... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
618d270c273d-3 | # excludes examples with no ngram overlaps with input.
# Since "My dog barks." has no ngram overlaps with "Spot can run fast."
# it is excluded.
example_selector.threshold=0.0
print(dynamic_prompt.format(sentence="Spot can run fast."))
Give the Spanish translation of every input
Input: Spot can run.
Output: Spot puede ... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
df056c3ef142-0 | .ipynb
.pdf
LengthBased ExampleSelector
LengthBased ExampleSelector#
This ExampleSelector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while ... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
df056c3ef142-1 | example_prompt=example_prompt,
# This is the maximum length that the formatted examples should be.
# Length is measured by the get_text_length function below.
max_length=25,
# This is the function used to get the length of a string, which is used
# to determine which examples to include. It is comm... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
df056c3ef142-2 | Give the antonym of every input
Input: happy
Output: sad
Input: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else
Output:
# You can add an example to an example selector as well.
new_example = {"input": "big", "output": "small"}
dynamic_prompt.example_sele... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
306242fe63f7-0 | .ipynb
.pdf
Similarity ExampleSelector
Similarity ExampleSelector#
The SemanticSimilarityExampleSelector selects examples based on which examples are most similar to the inputs. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs.
from langchain.prompts.exam... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html |
306242fe63f7-1 | OpenAIEmbeddings(),
# This is the VectorStore class that is used to store the embeddings and do a similarity search over.
Chroma,
# This is the number of examples to produce.
k=1
)
similar_prompt = FewShotPromptTemplate(
# We provide an ExampleSelector instead of examples.
example_selector=exa... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html |
306242fe63f7-2 | Input: happy
Output: sad
Input: joyful
Output:
previous
NGram Overlap ExampleSelector
next
Output Parsers
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html |
651f9011458f-0 | .md
.pdf
How to create a custom example selector
Contents
Implement custom example selector
Use custom example selector
How to create a custom example selector#
In this tutorial, we’ll create a custom example selector that selects every alternate example from a given list of examples.
An ExampleSelector must implemen... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html |
651f9011458f-1 | Use custom example selector#
examples = [
{"foo": "1"},
{"foo": "2"},
{"foo": "3"}
]
# Initialize example selector.
example_selector = CustomExampleSelector(examples)
# Select examples
example_selector.select_examples({"foo": "foo"})
# -> array([{'foo': '2'}, {'foo': '3'}], dtype=object)
# Add new example t... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html |
ca7e32f91fd9-0 | .ipynb
.pdf
Maximal Marginal Relevance ExampleSelector
Maximal Marginal Relevance ExampleSelector#
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddin... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html |
ca7e32f91fd9-1 | # This is the list of examples available to select from.
examples,
# This is the embedding class used to produce embeddings which are used to measure semantic similarity.
OpenAIEmbeddings(),
# This is the VectorStore class that is used to store the embeddings and do a similarity search over.
FAISS... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html |
ca7e32f91fd9-2 | )
similar_prompt.example_selector.k = 2
print(similar_prompt.format(adjective="worried"))
Give the antonym of every input
Input: happy
Output: sad
Input: windy
Output: calm
Input: worried
Output:
previous
LengthBased ExampleSelector
next
NGram Overlap ExampleSelector
By Harrison Chase
© Copyright 2023, Harri... | /content/https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html |
c0701b800427-0 | .ipynb
.pdf
Output Parsers
Output Parsers#
Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in.
Output parsers are classes that help structure language model responses. There are two main methods an output parser must impl... | /content/https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html |
c0701b800427-1 | from typing import List
model_name = 'text-davinci-003'
temperature = 0.0
model = OpenAI(model_name=model_name, temperature=temperature)
# Define your desired data structure.
class Joke(BaseModel):
setup: str = Field(description="question to set up a joke")
punchline: str = Field(description="answer to resolve ... | /content/https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html |
c0701b800427-2 | Output Parsers
next
CommaSeparatedListOutputParser
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/prompts/output_parsers/getting_started.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.