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 Python code is harmful. Use cautiously. from langchain.agents import create_pandas_dataframe_agent from langchain.llms import OpenAI import pandas as pd df = pd.read_csv('titanic.csv') agent = create_pandas_dataframe_agent(OpenAI(temperature=0), df, verbose=True) agent.run("how many rows are there?") > Entering new AgentExecutor chain... Thought: I need to count the number of rows Action: python_repl_ast Action Input: len(df) Observation: 891 Thought: I now know the final answer Final Answer: There are 891 rows in the dataframe. > Finished chain. 'There are 891 rows in the dataframe.' agent.run("how many people have more than 3 sibligngs") > Entering new AgentExecutor chain... Thought: I need to count the number of people with more than 3 siblings Action: python_repl_ast Action Input: df[df['SibSp'] > 3].shape[0] Observation: 30 Thought: I now know the final answer Final Answer: 30 people have more than 3 siblings. > Finished chain. '30 people have more than 3 siblings.'
/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 square root Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: name 'math' is not defined Thought: I need to import the math library Action: python_repl_ast Action Input: import math Observation: None Thought: I can now calculate the square root Action: python_repl_ast Action Input: math.sqrt(df['Age'].mean()) Observation: 5.449689683556195 Thought: I now know the final answer Final Answer: 5.449689683556195 > Finished chain. '5.449689683556195' previous Natural Language APIs next PowerBI Dataset 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/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 to answer more general questions about a dataset, as well as recover from errors. Note that, as this agent is in active development, all answers might not be correct. It runs against the executequery endpoint, which does not allow deletes. Some notes# It relies on authentication with the azure.identity package, which can be installed with pip install azure-identity. Alternatively you can create the powerbi dataset with a token as a string without supplying the credentials. You can also supply a username to impersonate for use with datasets that have RLS enabled. The toolkit uses a LLM to create the query from the question, the agent uses the LLM for the overall execution. Testing was done mostly with a text-davinci-003 model, codex models did not seem to perform ver well. Initialization# from langchain.agents.agent_toolkits import create_pbi_agent from langchain.agents.agent_toolkits import PowerBIToolkit from langchain.utilities.powerbi import PowerBIDataset from langchain.llms.openai import AzureOpenAI from langchain.agents import AgentExecutor from azure.identity import DefaultAzureCredential
/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_id>", table_names=['table1', 'table2'], credential=DefaultAzureCredential()), llm=smart_llm ) agent_executor = create_pbi_agent( llm=fast_llm, toolkit=toolkit, verbose=True, ) Example: describing a table# agent_executor.run("Describe table1") Example: simple query on a table# In this example, the agent actually figures out the correct query to get a row count of the table. agent_executor.run("How many records are in table1?") Example: running queries# agent_executor.run("How many records are there by dimension1 in table2?") agent_executor.run("What unique values are there for dimensions2 in table2") Example: add your own few-shot prompts# #fictional example few_shots = """ Question: How many rows are in the table revenue? DAX: EVALUATE ROW("Number of rows", COUNTROWS(revenue_details)) ----
/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])) ---- """ toolkit = PowerBIToolkit( powerbi=PowerBIDataset(dataset_id="<dataset_id>", table_names=['table1', 'table2'], credential=DefaultAzureCredential()), llm=smart_llm, examples=few_shots, ) agent_executor = create_pbi_agent( llm=fast_llm, toolkit=toolkit, verbose=True, ) agent_executor.run("What was the maximum of value in revenue in dollars in 2022?") previous Pandas Dataframe Agent next Python 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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/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/jira.html To use this tool, you must first set as environment variables: JIRA_API_TOKEN JIRA_USERNAME JIRA_INSTANCE_URL %pip install atlassian-python-api import os from langchain.agents import AgentType from langchain.agents import initialize_agent from langchain.agents.agent_toolkits.jira.toolkit import JiraToolkit from langchain.llms import OpenAI from langchain.utilities.jira import JiraAPIWrapper os.environ["JIRA_API_TOKEN"] = "abc" os.environ["JIRA_USERNAME"] = "123" os.environ["JIRA_INSTANCE_URL"] = "https://jira.atlassian.com" os.environ["OPENAI_API_KEY"] = "xyz" llm = OpenAI(temperature=0) jira = JiraAPIWrapper() toolkit = JiraToolkit.from_jira_api_wrapper(jira) agent = initialize_agent( toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True )
/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": "Task"}, "priority": {"name": "Low"}, "project": {"key": "PW"}} Observation: None Thought: I now know the final answer Final Answer: A new issue has been created in project PW with the summary "Make more fried rice" and description "Reminder to make more fried rice". > Finished chain. 'A new issue has been created in project PW with the summary "Make more fried rice" and description "Reminder to make more fried rice".' previous CSV Agent next JSON 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/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 an LLM. The agent is able to iteratively explore the blob to find what it needs to answer the user’s question. In the below example, we are using the OpenAPI spec for the OpenAI API, which you can find here. We will use the JSON agent to answer some questions about the API spec. Initialization# import os import yaml from langchain.agents import ( create_json_agent, AgentExecutor ) from langchain.agents.agent_toolkits import JsonToolkit from langchain.chains import LLMChain from langchain.llms.openai import OpenAI from langchain.requests import TextRequestsWrapper from langchain.tools.json.tool import JsonSpec with open("openai_openapi.yml") as f: data = yaml.load(f, Loader=yaml.FullLoader) json_spec = JsonSpec(dict_=data, max_value_length=4000) json_toolkit = JsonToolkit(spec=json_spec) json_agent_executor = create_json_agent( llm=OpenAI(temperature=0), toolkit=json_toolkit, verbose=True ) Example: getting the required POST parameters for a request#
/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', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"] Observation: ['/engines', '/engines/{engine_id}', '/completions', '/edits', '/images/generations', '/images/edits', '/images/variations', '/embeddings', '/engines/{engine_id}/search', '/files', '/files/{file_id}', '/files/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I should look at the /completions endpoint to see what parameters are required
/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', '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 look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["required"] Observation: True Thought: I should look at the content key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"] Observation: ['application/json'] Thought: I should look at the application/json key to see what parameters are required Action: json_spec_list_keys
/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"]["application/json"]["schema"] Observation: ['$ref'] Thought: I should look at the $ref key to see what parameters are required Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: #/components/schemas/CreateCompletionRequest Thought: I should look at the CreateCompletionRequest schema to see what parameters are required Action: json_spec_list_keys Action Input: data["components"]["schemas"]["CreateCompletionRequest"] Observation: ['type', 'properties', 'required'] Thought: I should look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["components"]["schemas"]["CreateCompletionRequest"]["required"] Observation: ['model'] Thought: I now know the final answer
/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 Initialization Example: getting the required POST parameters for a request By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/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 OpenAPI/Swagger specification. 1st example: hierarchical planning agent# In this example, we’ll consider an approach called hierarchical planning, common in robotics and appearing in recent works for LLMs X robotics. We’ll see it’s a viable approach to start working with a massive API spec AND to assist with user queries that require multiple steps against the API. The idea is simple: to get coherent agent behavior over long sequences behavior & to save on tokens, we’ll separate concerns: a “planner” will be responsible for what endpoints to call and a “controller” will be responsible for how to call them. In the initial implementation, the planner is an LLM chain that has the name and a short description for each endpoint in context. The controller is an LLM agent that is instantiated with documentation for only the endpoints for a particular plan. There’s a lot left to get this working very robustly :) To start, let’s collect some OpenAPI specs.# import os, yaml !wget https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml !mv openapi.yaml openai_openapi.yaml !wget https://www.klarna.com/us/shopping/public/openai/v0/api-docs
/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 (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 122995 (120K) [text/plain] Saving to: ‘openapi.yaml’ openapi.yaml 100%[===================>] 120.11K --.-KB/s in 0.01s 2023-03-31 15:45:56 (10.4 MB/s) - ‘openapi.yaml’ saved [122995/122995] --2023-03-31 15:45:57-- https://www.klarna.com/us/shopping/public/openai/v0/api-docs Resolving www.klarna.com (www.klarna.com)... 52.84.150.34, 52.84.150.46, 52.84.150.61, ... Connecting to www.klarna.com (www.klarna.com)|52.84.150.34|:443... connected.
/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/openapi-directory/main/APIs/spotify.com/1.0.0/openapi.yaml Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.110.133, 185.199.109.133, 185.199.111.133, ... Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.110.133|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 286747 (280K) [text/plain] Saving to: ‘openapi.yaml’ openapi.yaml 100%[===================>] 280.03K --.-KB/s in 0.02s 2023-03-31 15:45:58 (13.3 MB/s) - ‘openapi.yaml’ saved [286747/286747] from langchain.agents.agent_toolkits.openapi.spec import reduce_openapi_spec with open("openai_openapi.yaml") as f: raw_openai_api_spec = yaml.load(f, Loader=yaml.Loader) openai_api_spec = reduce_openapi_spec(raw_openai_api_spec)
/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’ll work with the Spotify API as one of the examples of a somewhat complex API. There’s a bit of auth-related setup to do if you want to replicate this. You’ll have to set up an application in the Spotify developer console, documented here, to get credentials: CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI. To get an access tokens (and keep them fresh), you can implement the oauth flows, or you can use spotipy. If you’ve set your Spotify creedentials as environment variables SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET, and SPOTIPY_REDIRECT_URI, you can use the helper functions below: import spotipy.util as util from langchain.requests import RequestsWrapper def construct_spotify_auth_headers(raw_spec: dict):
/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 API credentials. headers = construct_spotify_auth_headers(raw_spotify_api_spec) requests_wrapper = RequestsWrapper(headers=headers) How big is this spec?# endpoints = [ (route, operation) for route, operations in raw_spotify_api_spec["paths"].items() for operation in operations if operation in ["get", "post"] ] len(endpoints) 63 import tiktoken enc = tiktoken.encoding_for_model('text-davinci-003') def count_tokens(s): return len(enc.encode(s)) count_tokens(yaml.dump(raw_spotify_api_spec)) 80326 Let’s see some examples!# Starting with GPT-4. (Some robustness iterations under way for GPT-3 family.) from langchain.llms.openai import OpenAI from langchain.agents.agent_toolkits.openapi import planner llm = OpenAI(model_name="gpt-4", temperature=0.0)
/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/jeremywelborn/src/langchain/langchain/llms/openai.py:608: 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( spotify_agent = planner.create_openapi_agent(spotify_api_spec, requests_wrapper, llm) user_query = "make me a playlist with the first song from kind of blue. call it machine blues." spotify_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to create a playlist with the first song from Kind of Blue and name it Machine Blues Observation: 1. GET /search to search for the album "Kind of Blue" 2. GET /albums/{id}/tracks to get the tracks from the "Kind of Blue" album 3. GET /me to get the current user's information 4. POST /users/{user_id}/playlists to create a new playlist named "Machine Blues" for the current user
/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 "Kind of Blue" album 3. GET /me to get the current user's information 4. POST /users/{user_id}/playlists to create a new playlist named "Machine Blues" for the current user 5. POST /playlists/{playlist_id}/tracks to add the first song from "Kind of Blue" to the "Machine Blues" playlist > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/search?q=Kind%20of%20Blue&type=album", "output_instructions": "Extract the id of the first album in the search results"} Observation: 1weenld61qoidwYuZ1GESA Thought:Action: requests_get Action Input: {"url": "https://api.spotify.com/v1/albums/1weenld61qoidwYuZ1GESA/tracks", "output_instructions": "Extract the id of the first track in the album"} Observation: 7q3kkfAVpmcZ8g6JUThi3o Thought:Action: requests_get
/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": {"name": "Machine Blues"}, "output_instructions": "Extract the id of the created playlist"} Observation: 7lzoEi44WOISnFYlrAIqyX Thought:Action: requests_post Action Input: {"url": "https://api.spotify.com/v1/playlists/7lzoEi44WOISnFYlrAIqyX/tracks", "data": {"uris": ["spotify:track:7q3kkfAVpmcZ8g6JUThi3o"]}, "output_instructions": "Confirm that the track was added to the playlist"} Observation: The track was added to the playlist, confirmed by the snapshot_id: MiwxODMxNTMxZTFlNzg3ZWFlZmMxYTlmYWQyMDFiYzUwNDEwMTAwZmE1. Thought:I am finished executing the plan. Final Answer: The first song from the "Kind of Blue" album has been added to the "Machine Blues" playlist. > Finished chain.
/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 from the "Kind of Blue" album. > Finished chain. 'I have created a playlist called "Machine Blues" with the first song from the "Kind of Blue" album.' user_query = "give me a song I'd like, make it blues-ey" spotify_agent.run(user_query) > Entering new AgentExecutor chain... Action: api_planner Action Input: I need to find the right API calls to get a blues song recommendation for the user Observation: 1. GET /me to get the current user's information 2. GET /recommendations/available-genre-seeds to retrieve a list of available genres 3. GET /recommendations with the seed_genre parameter set to "blues" to get a blues song recommendation for the user Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /me to get the current user's information 2. GET /recommendations/available-genre-seeds to retrieve a list of available genres 3. GET /recommendations with the seed_genre parameter set to "blues" to get a blues song recommendation for the user > Entering new AgentExecutor chain... Action: requests_get
/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/v1/recommendations/available-genre-seeds", "output_instructions": "Extract the list of available genres"}
/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, edm, electro, electronic, emo, folk, forro, french, funk, garage, german, gospel, goth, grindcore, groove, grunge, guitar, happy, hard-rock, hardcore, hardstyle, heavy-metal, hip-hop, holidays, honky-tonk, house, idm, indian, indie, indie-pop, industrial, iranian, j-dance, j-idol, j-pop, j-rock, jazz, k-pop, kids, latin, latino, malay, mandopop, metal, metal-misc, metalcore, minimal-techno, movies, mpb, new-age, new-release, opera, pagode, party, philippines- Thought: Retrying langchain.llms.openai.completion_with_retry.<locals>._completion_with_retry in 4.0 seconds as it raised RateLimitError: That model is currently overloaded with other requests. You can retry your request, or contact us through our help center at help.openai.com if the error persists. (Please include the request ID 2167437a0072228238f3c0c5b3882764 in your message.). Action: requests_get
/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 plan. Final Answer: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. > Finished chain. Observation: The recommended blues song for user Jeremy Welborn (ID: 22rhrz4m4kvpxlsb5hezokzwi) is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. Thought:I am finished executing the plan and have the information the user asked for. Final Answer: The recommended blues song for you is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR. > Finished chain. 'The recommended blues song for you is "Get Away Jordan" with the track ID: 03lXHmokj9qsXspNsPoirR.' Try another API.# headers = { "Authorization": f"Bearer {os.getenv('OPENAI_API_KEY')}" }
/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... Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice Observation: 1. GET /engines to retrieve the list of available engines 2. POST /completions with the selected engine and a prompt for generating a short piece of advice Thought:I have the plan, now I need to execute the API calls. Action: api_controller Action Input: 1. GET /engines to retrieve the list of available engines 2. POST /completions with the selected engine and a prompt for generating a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/engines", "output_instructions": "Extract the ids of the engines"}
/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-002, text-similarity-ada-001, curie-instruct-beta, ada-code-search-code, ada-similarity, text-davinci-003, code-search-ada-text-001, text-search-ada-query-001, davinci-search-document, ada-code-search-text, text-search-ada-doc-001, davinci-instruct-beta, text-similarity-curie-001, code-search-ada-code-001 Thought:I will use the "davinci" engine to generate a short piece of advice. Action: requests_post Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"engine": "davinci", "prompt": "Give me a short piece of advice on how to be more productive."}, "output_instructions": "Extract the text from the first choice"} Observation: "you must provide a model parameter"
/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. > Finished chain. Observation: I need more information on how to provide the model parameter correctly in the POST request to generate a short piece of advice. Thought:I need to adjust my plan to include the model parameter in the POST request. Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice, including the model parameter in the POST request Observation: 1. GET /models to retrieve the list of available models 2. Choose a suitable model from the list 3. POST /completions with the chosen model as a parameter 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 model from the list 3. POST /completions with the chosen model as a parameter to generate a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/models", "output_instructions": "Extract the ids of the available models"}
/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 advice on how to improve communication skills."}, "output_instructions": "Extract the text from the first choice"} Observation: "I'd like to broaden my horizon.\n\nI was trying to" Thought:I cannot finish executing the plan without knowing some other information. Final Answer: The generated text is not a piece of advice on improving communication skills. I would need to retry the API call with a different prompt or model to get a more relevant response. > Finished chain. Observation: The generated text is not a piece of advice on improving communication skills. I would need to retry the API call with a different prompt or model to get a more relevant response. Thought:I need to adjust my plan to include a more specific prompt for generating a short piece of advice on improving communication skills. Action: api_planner Action Input: I need to find the right API calls to generate a short piece of advice on improving communication skills, including the model parameter in the POST request Observation: 1. GET /models to retrieve the list of available models 2. Choose a suitable model for generating text (e.g., text-davinci-002)
/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 model for generating text (e.g., text-davinci-002) 3. POST /completions with the chosen model and a prompt related to improving communication skills to generate a short piece of advice > Entering new AgentExecutor chain... Action: requests_get Action Input: {"url": "https://api.openai.com/v1/models", "output_instructions": "Extract the names of the models"} 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": "text-davinci-002", "prompt": "Give a short piece of advice on how to improve communication skills"}, "output_instructions": "Extract the text from the first choice"} Observation: "Some basic advice for improving communication skills would be to make sure to listen" Thought:I am finished executing the plan. Final Answer: Some basic advice for improving communication skills would be to make sure to listen. > Finished chain.
/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. 'A short piece of advice for improving communication skills is to make sure to listen.' Takes awhile to get there! 2nd example: “json explorer” agent# Here’s an agent that’s not particularly practical, but neat! The agent has access to 2 toolkits. One comprises tools to interact with json: one tool to list the keys of a json object and another tool to get the value for a given key. The other toolkit comprises requests wrappers to send GET and POST requests. This agent consumes a lot calls to the language model, but does a surprisingly decent job. from langchain.agents import create_openapi_agent from langchain.agents.agent_toolkits import OpenAPIToolkit from langchain.llms.openai import OpenAI from langchain.requests import TextRequestsWrapper from langchain.tools.json.tool import JsonSpec with open("openai_openapi.yaml") as f: data = yaml.load(f, Loader=yaml.FullLoader) json_spec=JsonSpec(dict_=data, max_value_length=4000) openapi_toolkit = OpenAPIToolkit.from_llm(OpenAI(temperature=0), json_spec, openai_requests_wrapper, verbose=True)
/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 the base url for the API? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the servers key to see what the base url is Action: json_spec_list_keys Action Input: data["servers"][0] Observation: ValueError('Value at path `data["servers"][0]` is not a dict, get the value directly.') Thought: I should get the value of the servers key Action: json_spec_get_value Action Input: data["servers"][0] Observation: {'url': 'https://api.openai.com/v1'} Thought: I now know the base url for the API Final Answer: The base url for the API is https://api.openai.com/v1 > Finished chain. Observation: The base url for the API is https://api.openai.com/v1 Thought: I should find the path for the /completions endpoint.
/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'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys 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/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations']
/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 Input: What are the required parameters for a POST request to the /completions endpoint? > Entering new AgentExecutor chain... Action: json_spec_list_keys Action Input: data Observation: ['openapi', 'info', 'servers', 'tags', 'paths', 'components', 'x-oaiMeta'] Thought: I should look at the paths key to see what endpoints exist Action: json_spec_list_keys Action Input: data["paths"]
/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/{file_id}/content', '/answers', '/classifications', '/fine-tunes', '/fine-tunes/{fine_tune_id}', '/fine-tunes/{fine_tune_id}/cancel', '/fine-tunes/{fine_tune_id}/events', '/models', '/models/{model}', '/moderations'] Thought: I should look at the /completions endpoint to see what parameters are required 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"]
/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 look at the content key to see what parameters are required Action: json_spec_list_keys Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"] Observation: ['application/json'] Thought: I should look at the application/json key to see what parameters are required 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"]["application/json"]["schema"] Observation: ['$ref'] Thought: I should look at the $ref key to see what parameters are required Action: json_spec_list_keys
/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 directly.') Thought: I should look at the $ref key to get the value directly Action: json_spec_get_value Action Input: data["paths"]["/completions"]["post"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] Observation: #/components/schemas/CreateCompletionRequest Thought: I should look at the CreateCompletionRequest schema to see what parameters are required Action: json_spec_list_keys Action Input: data["components"]["schemas"]["CreateCompletionRequest"] Observation: ['type', 'properties', 'required'] Thought: I should look at the required key to see what parameters are required Action: json_spec_get_value Action Input: data["components"]["schemas"]["CreateCompletionRequest"]["required"] Observation: ['model'] Thought: I now know the final answer
/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 make the request. Action: requests_post Action Input: { "url": "https://api.openai.com/v1/completions", "data": { "model": "davinci", "prompt": "tell me a joke" } } Observation: {"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":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} Thought: I now know the final answer.
/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":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}} > Finished chain. '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":"length"}],"usage":{"prompt_tokens":4,"completion_tokens":16,"total_tokens":20}}' previous JSON Agent next Natural Language APIs 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.
/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 langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain import OpenAI, VectorDBQA llm = OpenAI(temperature=0) from langchain.document_loaders import TextLoader loader = TextLoader('../../../state_of_the_union.txt') documents = loader.load() text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) embeddings = OpenAIEmbeddings() state_of_union_store = Chroma.from_documents(texts, embeddings, collection_name="state-of-union") Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. from langchain.document_loaders import WebBaseLoader loader = WebBaseLoader("https://beta.ruff.rs/docs/faq/") docs = loader.load() ruff_texts = text_splitter.split_documents(docs)
/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 ( create_vectorstore_agent, VectorStoreToolkit, VectorStoreInfo, ) vectorstore_info = VectorStoreInfo( name="state_of_union_address", description="the most recent state of the Union adress", vectorstore=state_of_union_store ) toolkit = VectorStoreToolkit(vectorstore_info=vectorstore_info) agent_executor = create_vectorstore_agent( llm=llm, toolkit=toolkit, verbose=True ) Examples# agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address?") > Entering new AgentExecutor chain... I need to find the answer in the state of the union address Action: state_of_union_address Action Input: What did biden say about ketanji brown jackson Observation: 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. Thought: I now know the final answer Final Answer: 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. > Finished chain.
/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... I need to use the state_of_union_address_with_sources tool to answer this question. Action: state_of_union_address_with_sources Action Input: What did biden say about ketanji brown jackson Observation: {"answer": " Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence.\n", "sources": "../../state_of_the_union.txt"} Thought: I now know the final answer Final Answer: Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt > Finished chain. "Biden said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to the United States Supreme Court, and that she is one of the nation's top legal minds who will continue Justice Breyer's legacy of excellence. Sources: ../../state_of_the_union.txt"
/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, VectorStoreRouterToolkit, VectorStoreInfo, ) ruff_vectorstore_info = VectorStoreInfo( name="ruff", description="Information about the Ruff python linting library", vectorstore=ruff_store ) router_toolkit = VectorStoreRouterToolkit( vectorstores=[vectorstore_info, ruff_vectorstore_info], llm=llm ) agent_executor = create_vectorstore_router_agent( llm=llm, toolkit=router_toolkit, verbose=True ) Examples# agent_executor.run("What did biden say about ketanji brown jackson is the state of the union address?") > Entering new AgentExecutor chain... I need to use the state_of_union_address tool to answer this question. Action: state_of_union_address Action Input: What did biden say about ketanji brown jackson Observation: 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. Thought: I now know the final answer Final Answer: 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. > Finished chain.
/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 run over Jupyter Notebooks 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 now know the final answer Final Answer: 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 > Finished chain. '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' agent_executor.run("What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?") > Entering new AgentExecutor chain... I need to find out what tool ruff uses and if the president mentioned it in the state of the union.
/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 find out if the president mentioned nbQA in the state of the union. Action: state_of_union_address Action Input: Did the president mention nbQA in the state of the union? Observation: No, the president did not mention nbQA in the state of the union. Thought: I now know the final answer. Final Answer: No, the president did not mention nbQA in the state of the union. > Finished chain. 'No, the president did not mention nbQA in the state of the union.' previous SQL Database Agent next Agent Executors Contents Create the Vectorstores Initialize Toolkit and Agent Examples Multiple Vectorstores Examples By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/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 to make constructing and working with prompts easy. The following sections of documentation are provided: Getting Started: An overview of all the functionality LangChain provides for working with and constructing prompts. How-To Guides: A collection of how-to guides. These highlight how to accomplish various objectives with our prompt class. Reference: API reference documentation for all prompt classes. previous Prompts next Getting Started By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/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 output parser must implement: get_format_instructions() -> str: A method which returns a string containing instructions for how the output of a language model should be formatted. parse(str) -> Any: A method which takes in a string (assumed to be the response from a language model) and parses it into some structure. And then one optional one: parse_with_prompt(str) -> Any: A method which takes in a string (assumed to be the response from a language model) and a prompt (assumed to the prompt that generated such a response) and parses it into some structure. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so. To start, we recommend familiarizing yourself with the Getting Started section Output Parsers After that, we provide deep dives on all the different types of output parsers. CommaSeparatedListOutputParser OutputFixingParser PydanticOutputParser RetryOutputParser Structured Output Parser previous Similarity 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/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 functions to make constructing and working with prompts easy. from langchain.prompts import ( ChatPromptTemplate, PromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplate, ) from langchain.schema import ( AIMessage, HumanMessage, SystemMessage ) You can make use of templating by using a MessagePromptTemplate. You can build a ChatPromptTemplate from one or more MessagePromptTemplates. You can use ChatPromptTemplate’s format_prompt – this returns a PromptValue, which you can convert to a string or Message object, depending on whether you want to use the formatted value as input to an llm or chat model. For convenience, there is a from_template method exposed on the template. If you were to use this template, this is what it would look like: template="You are a helpful assistant that translates {input_language} to {output_language}." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_template="{text}" human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
/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 that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})] If you wanted to construct the MessagePromptTemplate more directly, you could create a PromptTemplate outside and then pass it in, eg: prompt=PromptTemplate( template="You are a helpful assistant that translates {input_language} to {output_language}.", input_variables=["input_language", "output_language"], ) system_message_prompt = SystemMessagePromptTemplate(prompt=prompt) previous Output Parsers next Example Selectors By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/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 selecting examples to include in prompts.""" @abstractmethod def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on the inputs.""" The only method it needs to expose is a select_examples method. This takes in the input variables and then returns a list of examples. It is up to each specific implementation as to how those examples are selected. Let’s take a look at some below. See below for a list of example selectors. How to create a custom example selector LengthBased ExampleSelector Maximal Marginal Relevance ExampleSelector NGram Overlap ExampleSelector Similarity ExampleSelector previous Chat Prompt Template next How to create a custom example selector By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/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 few shot examples How to work with partial Prompt Templates How to serialize prompts previous Getting Started next Connecting to a Feature Store By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/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 why it is needed, how to create a prompt template, how to pass few shot examples to a prompt template, how to select examples for a prompt template. What is a prompt template?# A prompt template refers to a reproducible way to generate a prompt. It contains a text string (“the template”), that can take in a set of parameters from the end user and generate a prompt. The prompt template may contain: instructions to the language model, a set of few shot examples to help the language model generate a better response, a question to the language model. The following code snippet contains an example of a prompt template: from langchain import PromptTemplate template = """ I want you to act as a naming consultant for new companies. What is a good name for a company that makes {product}? """ prompt = PromptTemplate( input_variables=["product"], template=template, ) prompt.format(product="colorful socks") # -> I want you to act as a naming consultant for new companies. # -> What is a good name for a company that makes colorful socks? Create a prompt template# You can create simple hardcoded prompts using the PromptTemplate class. Prompt templates can take any number of input variables, and can be formatted to generate a prompt. from langchain import PromptTemplate # An example prompt with no input variables
/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"], template="Tell me a {adjective} joke.") one_input_prompt.format(adjective="funny") # -> "Tell me a funny joke." # An example prompt with multiple input variables multiple_input_prompt = PromptTemplate( input_variables=["adjective", "content"], template="Tell me a {adjective} joke about {content}." ) multiple_input_prompt.format(adjective="funny", content="chickens") # -> "Tell me a funny joke about chickens." If you do not wish to specify input_variables manually, you can also create a PromptTemplate using from_template class method. langchain will automatically infer the input_variables based on the template passed. template = "Tell me a {adjective} joke about {content}." prompt_template = PromptTemplate.from_template(template) prompt_template.input_variables # -> ['adjective', 'content'] prompt_template.format(adjective="funny", content="chickens") # -> Tell me a funny joke about chickens.
/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 through template_format argument: # Make sure jinja2 is installed before running this jinja2_template = "Tell me a {{ adjective }} joke about {{ content }}" prompt_template = PromptTemplate.from_template(template=jinja2_template, template_format="jinja2") prompt_template.format(adjective="funny", content="chickens") # -> Tell me a funny joke about chickens. Currently, PromptTemplate only supports jinja2 and f-string templating format. If there is any other templating format that you would like to use, feel free to open an issue in the Github page. Validate template# By default, PromptTemplate will validate the template string by checking whether the input_variables match the variables defined in template. You can disable this behavior by setting validate_template to False template = "I am learning langchain because {reason}." prompt_template = PromptTemplate(template=template, input_variables=["reason", "foo"]) # ValueError due to extra variables prompt_template = PromptTemplate(template=template, input_variables=["reason", "foo"], validate_template=False) # No error Serialize prompt template#
/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_prompt.json") # Save to JSON file from langchain.prompts import load_prompt loaded_prompt = load_prompt("awesome_prompt.json") assert prompt_template == loaded_prompt langchain also supports loading prompt template from LangChainHub, which contains a collection of useful prompts you can use in your project. You can read more about LangChainHub and the prompts available with it here. from langchain.prompts import load_prompt prompt = load_prompt("lc://prompts/conversation/prompt.json") prompt.format(history="", input="What is 1 + 1?") You can learn more about serializing prompt template in How to serialize prompts. Pass few shot examples to a prompt template# Few shot examples are a set of examples that can be used to help the language model generate a better response. To generate a prompt with few shot examples, you can use the FewShotPromptTemplate. This class takes in a PromptTemplate and a list of few shot examples. It then formats the prompt template with the few shot examples. In this example, we’ll create a prompt to generate word antonyms. from langchain import PromptTemplate, FewShotPromptTemplate
/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 this. example_formatter_template = """ Word: {word} Antonym: {antonym}\n """ example_prompt = PromptTemplate( input_variables=["word", "antonym"], template=example_formatter_template, ) # Finally, we create the `FewShotPromptTemplate` object. few_shot_prompt = FewShotPromptTemplate( # These are the examples we want to insert into the prompt. examples=examples, # This is how we want to format the examples when we insert them into the prompt. example_prompt=example_prompt, # The prefix is some text that goes before the examples in the prompt. # Usually, this consists of intructions. prefix="Give the antonym of every input", # The suffix is some text that goes after the examples in the prompt. # Usually, this is where the user input will go suffix="Word: {input}\nAntonym:", # The input variables are the variables that the overall prompt expects. input_variables=["input"],
/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 # -> # -> Word: happy # -> Antonym: sad # -> # -> Word: tall # -> Antonym: short # -> # -> Word: big # -> Antonym: Select examples for a prompt template# If you have a large number of examples, you can use the ExampleSelector to select a subset of examples that will be most informative for the Language Model. This will help you generate a prompt that is more likely to generate a good response. Below, we’ll use the LengthBasedExampleSelector, which selects examples based on the length of the input. 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 for shorter inputs it will select more. We’ll continue with the example from the previous section, but this time we’ll use the LengthBasedExampleSelector to select the examples. from langchain.prompts.example_selector import LengthBasedExampleSelector # These are a lot of examples of a pretend task of creating antonyms. examples = [ {"word": "happy", "antonym": "sad"}, {"word": "tall", "antonym": "short"},
/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 examples is has available to choose from. examples=examples, # This is the PromptTemplate being used to format the examples. 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, ) # We can now use the `example_selector` to create a `FewShotPromptTemplate`. dynamic_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Word: {input}\nAntonym:", input_variables=["input"], example_separator="\n\n", ) # We can now generate a prompt using the `format` method. print(dynamic_prompt.format(input="big")) # -> Give the antonym of every input # -> # -> Word: happy # -> Antonym: sad
/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 LengthBasedExampleSelector will select fewer examples to include in the prompt. long_string = "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else" print(dynamic_prompt.format(input=long_string)) # -> Give the antonym of every input # -> Word: happy # -> Antonym: sad # -> # -> Word: big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else # -> Antonym: LangChain comes with a few example selectors that you can use. For more details on how to use them, see Example Selectors. You can create custom example selectors that select examples based on any criteria you want. For more details on how to do this, see Creating a custom example selector. previous Prompt Templates next How-To Guides 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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 26, 2023.
/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 when considering putting LLM applications in production. In order to personalize LLM applications, you may want to combine LLMs with up-to-date information about particular users. Feature stores can be a great way to keep that data fresh, and LangChain provides an easy way to combine that data with LLMs. In this notebook we will show how to connect prompt templates to feature stores. The basic idea is to call a feature store from inside a prompt template to retrieve values that are then formatted into the prompt. Feast# To start, we will use the popular open source feature store framework Feast. This assumes you have already run the steps in the README around getting started. We will build of off that example in getting started, and create and LLMChain to write a note to a specific driver regarding their up-to-date statistics. Load Feast Store# Again, this should be set up according to the instructions in the Feast README from feast import FeatureStore # You may need to update the path depending on where you stored it feast_repo_path = "../../../../../my_feature_repo/feature_repo/" store = FeatureStore(repo_path=feast_repo_path) Prompts#
/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 prompt template). from langchain.prompts import PromptTemplate, StringPromptTemplate template = """Given the driver's up to date stats, write them note relaying those stats to them. If they have a conversation rate above .5, give them a compliment. Otherwise, make a silly joke about chickens at the end to make them feel better Here are the drivers stats: Conversation rate: {conv_rate} Acceptance rate: {acc_rate} Average Daily Trips: {avg_daily_trips} Your response:""" prompt = PromptTemplate.from_template(template) class FeastPromptTemplate(StringPromptTemplate): def format(self, **kwargs) -> str: driver_id = kwargs.pop("driver_id") feature_vector = store.get_online_features( features=[ 'driver_hourly_stats:conv_rate', 'driver_hourly_stats:acc_rate', 'driver_hourly_stats:avg_daily_trips' ], entity_rows=[{"driver_id": 1001}] ).to_dict() kwargs["conv_rate"] = feature_vector["conv_rate"][0]
/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 them note relaying those stats to them. If they have a conversation rate above .5, give them a compliment. Otherwise, make a silly joke about chickens at the end to make them feel better Here are the drivers stats: Conversation rate: 0.4745151400566101 Acceptance rate: 0.055561766028404236 Average Daily Trips: 936 Your response: Use in a chain# We can now use this in a chain, successfully creating a chain that achieves personalization backed by a feature store from langchain.chat_models import ChatOpenAI from langchain.chains import LLMChain chain = LLMChain(llm=ChatOpenAI(), prompt=prompt_template) chain.run(1001) "Hi there! I wanted to update you on your current stats. Your acceptance rate is 0.055561766028404236 and your average daily trips are 936. While your conversation rate is currently 0.4745151400566101, I have no doubt that with a little extra effort, you'll be able to exceed that .5 mark! Keep up the great work! And remember, even chickens can't always cross the road, but they still give it their best shot." previous
/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 this task, we will 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. Why are custom prompt templates needed?# LangChain provides a set of default prompt templates that can be used to generate prompts for a variety of tasks. However, there may be cases where the default prompt templates do not meet your needs. For example, you may want to create a prompt template with specific dynamic instructions for your language model. In such cases, you can create a custom prompt template. Take a look at the current set of default prompt templates here. Creating a Custom Prompt Template# There are essentially two distinct prompt templates available - string prompt templates and chat prompt templates. String prompt templates provides a simple prompt in string format, while chat prompt templates produces a more structured prompt to be used with a chat API. In this guide, we will create a custom prompt using a string prompt template. To create a custom string prompt template, there are two requirements: It has an input_variables attribute that exposes what input variables the prompt template expects. It exposes a format method that takes in keyword arguments corresponding to the expected input_variables and returns the formatted prompt. We will create a custom prompt template that takes in the function name as input and formats the prompt to provide the source code of the function. To achieve this, let’s first create a function that will return the source code of a function given its name.
/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.prompts import StringPromptTemplate from pydantic import BaseModel, validator class FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel): """ 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. """ @validator("input_variables") def validate_input_variables(cls, v): """ Validate that the input variables are correct. """ if len(v) != 1 or "function_name" not in v: raise ValueError("function_name must be the only input_variable.") return v def format(self, **kwargs) -> str: # Get the source code of the function source_code = get_source_code(kwargs["function_name"]) # Generate the prompt to be sent to the language model prompt = f""" Given the function name and source code, generate an English language explanation of the function. Function Name: {kwargs["function_name"].__name__} Source Code: {source_code} Explanation: """ return prompt def _prompt_type(self): return "function-explainer" Use the custom prompt template# Now that we have created a custom prompt template, we can use it to generate prompts for our task.
/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. Function Name: get_source_code Source Code: def get_source_code(function_name): # Get the source code of the function return inspect.getsource(function_name) Explanation: previous Connecting to a Feature Store next How to create a prompt template that uses few shot examples Contents Why are custom prompt templates needed? Creating a Custom Prompt Template Use the custom prompt template 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/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 python code but as files. This can make it easy to share, store, and version prompts. This notebook covers how to do that in LangChain, walking through all the different types of prompts and the different serialization options. At a high level, the following design principles are applied to serialization: Both JSON and YAML are supported. We want to support serialization methods that are human readable on disk, and YAML and JSON are two of the most popular methods for that. Note that this rule applies to prompts. For other assets, like Examples, different serialization methods may be supported. We support specifying everything in one file, or storing different components (templates, examples, etc) in different files and referencing them. For some cases, storing everything in file makes the most sense, but for others it is preferrable to split up some of the assets (long templates, large examples, reusable components). LangChain supports both. There is also a single entry point to load prompts from disk, making it easy to load any type of prompt. # All prompts are loaded through the `load_prompt` function. from langchain.prompts import load_prompt PromptTemplate# This section covers examples for loading a PromptTemplate. Loading from YAML#
/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="chickens")) Tell me a funny joke about chickens. Loading from JSON# This shows an example of loading a PromptTemplate from JSON. !cat simple_prompt.json { "_type": "prompt", "input_variables": ["adjective", "content"], "template": "Tell me a {adjective} joke about {content}." } prompt = load_prompt("simple_prompt.json") print(prompt.format(adjective="funny", content="chickens")) Tell me a funny joke about chickens. Loading Template from a File# This shows an example of storing the template in a separate file and then referencing it in the config. Notice that the key changes from template to template_path. !cat simple_template.txt Tell me a {adjective} joke about {content}. !cat simple_prompt_with_template_file.json { "_type": "prompt", "input_variables": ["adjective", "content"], "template_path": "simple_template.txt" } prompt = load_prompt("simple_prompt_with_template_file.json")
/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": "sad"}, {"input": "tall", "output": "short"} ] And here is what the same examples stored as yaml might look like. !cat examples.yaml - input: happy output: sad - input: tall output: short Loading from YAML# This shows an example of loading a few shot example from YAML. !cat few_shot_prompt.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.json suffix: "Input: {adjective}\nOutput:" prompt = load_prompt("few_shot_prompt.yaml") print(prompt.format(adjective="funny")) Write antonyms for the following words. Input: happy Output: sad Input: tall Output: short Input: funny Output: The same would work if you loaded examples from the yaml file. !cat few_shot_prompt_yaml_examples.yaml
/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: "Input: {adjective}\nOutput:" prompt = load_prompt("few_shot_prompt_yaml_examples.yaml") print(prompt.format(adjective="funny")) Write antonyms for the following words. Input: happy Output: sad Input: tall Output: short Input: funny Output: Loading from JSON# This shows an example of loading a few shot example from JSON. !cat few_shot_prompt.json { "_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.json", "suffix": "Input: {adjective}\nOutput:" } prompt = load_prompt("few_shot_prompt.json")
/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", "input_variables": ["adjective"], "prefix": "Write antonyms for the following words.", "example_prompt": { "_type": "prompt", "input_variables": ["input", "output"], "template": "Input: {input}\nOutput: {output}" }, "examples": [ {"input": "happy", "output": "sad"}, {"input": "tall", "output": "short"} ], "suffix": "Input: {adjective}\nOutput:" } prompt = load_prompt("few_shot_prompt_examples_in.json") print(prompt.format(adjective="funny")) Write antonyms for the following words. Input: happy Output: sad Input: tall Output: short Input: funny Output: Example Prompt from a File# This shows an example of loading the PromptTemplate that is used to format the examples from a separate file. Note that the key changes from example_prompt to example_prompt_path.
/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.", "example_prompt_path": "example_prompt.json", "examples": "examples.json", "suffix": "Input: {adjective}\nOutput:" } prompt = load_prompt("few_shot_prompt_example_prompt.json") print(prompt.format(adjective="funny")) Write antonyms for the following words. Input: happy Output: sad Input: tall Output: short Input: funny Output: previous How to work with partial Prompt Templates next 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 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/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 can make sense to “partial” a prompt template - eg pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values. LangChain supports this in two ways: we allow for partially formatted prompts (1) with string values, (2) with functions that return string values. These two different ways support different use cases. In the documentation below we go over the motivations for both use cases as well as how to do it in LangChain. Partial With Strings# One common use case for wanting to partial a prompt template is if you get some of the variables before others. For example, suppose you have a prompt template that requires two variables, foo and baz. If you get the foo value early on in the chain, but the baz value later, it can be annoying to wait until you have both variables in the same place to pass them to the prompt template. Instead, you can partial the prompt template with the foo value, and then pass the partialed prompt template along and just use that. Below is an example of doing this: from langchain.prompts import PromptTemplate prompt = PromptTemplate(template="{foo}{bar}", input_variables=["foo", "bar"]) partial_prompt = prompt.partial(foo="foo");
/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 Functions# The other common use is to partial with a function. The use case for this is when you have a variable you know that you always want to fetch in a common way. A prime example of this is with date or time. Imagine you have a prompt which you always want to have the current date. You can’t hard code it in the prompt, and passing it along with the other input variables is a bit annoying. In this case, it’s very handy to be able to partial the prompt with a function that always returns the current date. from datetime import datetime def _get_datetime(): now = datetime.now() return now.strftime("%m/%d/%Y, %H:%M:%S") prompt = PromptTemplate( template="Tell me a {adjective} joke about the day {date}", input_variables=["adjective", "date"] ); partial_prompt = prompt.partial(date=_get_datetime) print(partial_prompt.format(adjective="funny")) Tell me a funny joke about the day 02/27/2023, 22:15:16
/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={"date": _get_datetime} ); print(prompt.format(adjective="funny")) Tell me a funny joke about the day 02/27/2023, 22:15:16 previous How to create a prompt template that uses few shot examples next How to serialize prompts Contents Partial With Strings Partial With Functions 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/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 into FewShotPromptTemplate How to create a prompt template that uses few shot examples# In this tutorial, we’ll learn how to create a prompt template that uses few shot examples. We’ll use the FewShotPromptTemplate class to create a prompt template that uses few shot examples. This class either takes in a set of examples, or an ExampleSelector object. In this tutorial, we’ll go over both options. Use Case# In this tutorial, we’ll configure few shot examples for self-ask with search. Using an example set# Create the example set# To get started, create a list of few shot examples. Each example should be a dictionary with the keys being the input variables and the values being the values for those input variables. from langchain.prompts.few_shot import FewShotPromptTemplate from langchain.prompts.prompt import PromptTemplate examples = [ { "question": "Who lived longer, Muhammad Ali or Alan Turing?", "answer": """ Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died? Intermediate answer: Alan Turing was 41 years old when he died.
/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 founded by Craig Newmark. Follow up: When was Craig Newmark born? Intermediate answer: Craig Newmark was born on December 6, 1952. So the final answer is: December 6, 1952 """ }, { "question": "Who was the maternal grandfather of George Washington?", "answer": """ Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball """ }, { "question": "Are both the directors of Jaws and Casino Royale from the same country?", "answer": """ Are follow up questions needed here: Yes. Follow up: Who is the director of Jaws? Intermediate Answer: The director of Jaws is Steven Spielberg. Follow up: Where is Steven Spielberg from? Intermediate Answer: The United States. Follow up: Who is the director of Casino Royale? Intermediate Answer: The director of Casino Royale is Martin Campbell. Follow up: Where is Martin Campbell from? Intermediate Answer: New Zealand. So the final answer is: No """ } ] Create a formatter for the few shot examples#
/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.format(**examples[0])) Question: Who lived longer, Muhammad Ali or Alan Turing? Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. 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 Feed examples and formatter to FewShotPromptTemplate# Finally, create a FewShotPromptTemplate object. This object takes in the few shot examples and the formatter for the few shot examples. prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"] ) print(prompt.format(input="Who was the father of Mary Ball Washington?")) Question: Who lived longer, Muhammad Ali or Alan Turing? Are follow up questions needed here: Yes. Follow up: How old was Muhammad Ali when he died? Intermediate answer: Muhammad Ali was 74 years old when he died. Follow up: How old was Alan Turing when he died?
/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 was founded by Craig Newmark. Follow up: When was Craig Newmark born? Intermediate answer: Craig Newmark was born on December 6, 1952. So the final answer is: December 6, 1952 Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball Question: Are both the directors of Jaws and Casino Royale from the same country? Are follow up questions needed here: Yes. Follow up: Who is the director of Jaws? Intermediate Answer: The director of Jaws is Steven Spielberg. Follow up: Where is Steven Spielberg from? Intermediate Answer: The United States. Follow up: Who is the director of Casino Royale? Intermediate Answer: The director of Casino Royale is Martin Campbell. Follow up: Where is Martin Campbell from? Intermediate Answer: New Zealand. So the final answer is: No Question: Who was the father of Mary Ball Washington? Using an example selector# Feed examples into ExampleSelector#
/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 SemanticSimilarityExampleSelector class. This class selects few shot examples based on their similarity to the input. It uses an embedding model to compute the similarity between the input and the few shot examples, as well as a vector store to perform the nearest neighbor search. from langchain.prompts.example_selector import SemanticSimilarityExampleSelector from langchain.vectorstores import Chroma from langchain.embeddings import OpenAIEmbeddings example_selector = SemanticSimilarityExampleSelector.from_examples( # 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. Chroma, # This is the number of examples to produce. k=1 ) # Select the most similar example to the input. question = "Who was the father of Mary Ball Washington?" selected_examples = example_selector.select_examples({"question": question}) print(f"Examples most similar to the input: {question}") for example in selected_examples: print("\n")
/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 grandfather of George Washington? answer: Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball Feed example selector into FewShotPromptTemplate# Finally, create a FewShotPromptTemplate object. This object takes in the example selector and the formatter for the few shot examples. prompt = FewShotPromptTemplate( example_selector=example_selector, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"] ) print(prompt.format(input="Who was the father of Mary Ball Washington?")) Question: Who was the maternal grandfather of George Washington? Are follow up questions needed here: Yes. Follow up: Who was the mother of George Washington? Intermediate answer: The mother of George Washington was Mary Ball Washington. Follow up: Who was the father of Mary Ball Washington? Intermediate answer: The father of Mary Ball Washington was Joseph Ball. So the final answer is: Joseph Ball Question: Who was the father of Mary Ball Washington? previous
/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 formatter to FewShotPromptTemplate Using an example selector Feed examples into ExampleSelector Feed example selector into FewShotPromptTemplate 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/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 threshold score to be set. Examples with an ngram overlap score less than or equal to the threshold are excluded. The threshold is set to -1.0, by default, so will not exclude any examples, only reorder them. Setting the threshold to 0.0 will exclude examples that have no ngram overlaps with the input. from langchain.prompts import PromptTemplate from langchain.prompts.example_selector.ngram_overlap import NGramOverlapExampleSelector from langchain.prompts import FewShotPromptTemplate, PromptTemplate example_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}", ) # These are a lot of examples of a pretend task of creating antonyms. examples = [ {"input": "happy", "output": "sad"}, {"input": "tall", "output": "short"}, {"input": "energetic", "output": "lethargic"}, {"input": "sunny", "output": "gloomy"},
/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 = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}", ) example_selector = NGramOverlapExampleSelector( # These are the examples it has available to choose from. examples=examples, # This is the PromptTemplate being used to format the examples. example_prompt=example_prompt, # This is the threshold, at which selector stops. # It is set to -1.0 by default. threshold=-1.0, # For negative threshold: # Selector sorts examples by ngram overlap score, and excludes none. # For threshold greater than 1.0: # Selector excludes all examples, and returns an empty list. # For threshold equal to 0.0: # Selector sorts examples by ngram overlap score, # and excludes those with no ngram overlap with input. ) dynamic_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector,
/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(dynamic_prompt.format(sentence="Spot can run fast.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: See Spot run. Output: Ver correr a Spot. Input: My dog barks. Output: Mi perro ladra. Input: Spot can run fast. Output: # You can add examples to NGramOverlapExampleSelector as well. new_example = {"input": "Spot plays fetch.", "output": "Spot juega a buscar."} example_selector.add_example(new_example) print(dynamic_prompt.format(sentence="Spot can run fast.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: See Spot run. Output: Ver correr a Spot. Input: Spot plays fetch. Output: Spot juega a buscar. Input: My dog barks. Output: Mi perro ladra. Input: Spot can run fast. Output: # You can set a threshold at which examples are excluded. # For example, setting threshold equal to 0.0 # excludes examples with no ngram overlaps with input.
/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 correr. Input: See Spot run. Output: Ver correr a Spot. Input: Spot plays fetch. Output: Spot juega a buscar. Input: Spot can run fast. Output: # Setting small nonzero threshold example_selector.threshold=0.09 print(dynamic_prompt.format(sentence="Spot can play fetch.")) Give the Spanish translation of every input Input: Spot can run. Output: Spot puede correr. Input: Spot plays fetch. Output: Spot juega a buscar. Input: Spot can play fetch. Output: # Setting threshold greater than 1.0 example_selector.threshold=1.0+1e-9 print(dynamic_prompt.format(sentence="Spot can play fetch.")) Give the Spanish translation of every input Input: Spot can play fetch. Output: previous Maximal Marginal Relevance ExampleSelector next Similarity ExampleSelector 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/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 for shorter inputs it will select more. from langchain.prompts import PromptTemplate from langchain.prompts import FewShotPromptTemplate from langchain.prompts.example_selector import LengthBasedExampleSelector # These are a lot of examples of a pretend task of creating antonyms. examples = [ {"input": "happy", "output": "sad"}, {"input": "tall", "output": "short"}, {"input": "energetic", "output": "lethargic"}, {"input": "sunny", "output": "gloomy"}, {"input": "windy", "output": "calm"}, ] example_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}", ) example_selector = LengthBasedExampleSelector( # These are the examples it has available to choose from. examples=examples, # This is the PromptTemplate being used to format the examples. example_prompt=example_prompt,
/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 commented out because # it is provided as a default value if none is specified. # get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x)) ) dynamic_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Input: {adjective}\nOutput:", input_variables=["adjective"], ) # An example with small input, so it selects all examples. print(dynamic_prompt.format(adjective="big")) Give the antonym of every input Input: happy Output: sad Input: tall Output: short Input: energetic Output: lethargic Input: sunny Output: gloomy Input: windy Output: calm Input: big Output: # An example with long input, so it selects only one example. long_string = "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else" print(dynamic_prompt.format(adjective=long_string)) Give the antonym of every input
/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_selector.add_example(new_example) print(dynamic_prompt.format(adjective="enthusiastic")) Give the antonym of every input Input: happy Output: sad Input: tall Output: short Input: energetic Output: lethargic Input: sunny Output: gloomy Input: windy Output: calm Input: big Output: small Input: enthusiastic Output: previous How to create a custom example selector next Maximal Marginal Relevance ExampleSelector 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/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.example_selector import SemanticSimilarityExampleSelector from langchain.vectorstores import Chroma from langchain.embeddings import OpenAIEmbeddings from langchain.prompts import FewShotPromptTemplate, PromptTemplate example_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}", ) # These are a lot of examples of a pretend task of creating antonyms. examples = [ {"input": "happy", "output": "sad"}, {"input": "tall", "output": "short"}, {"input": "energetic", "output": "lethargic"}, {"input": "sunny", "output": "gloomy"}, {"input": "windy", "output": "calm"}, ] example_selector = SemanticSimilarityExampleSelector.from_examples( # 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(),
/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=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Input: {adjective}\nOutput:", input_variables=["adjective"], ) Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient. # Input is a feeling, so should select the happy/sad example print(similar_prompt.format(adjective="worried")) Give the antonym of every input Input: happy Output: sad Input: worried Output: # Input is a measurement, so should select the tall/short example print(similar_prompt.format(adjective="fat")) Give the antonym of every input Input: happy Output: sad Input: fat Output: # You can add new examples to the SemanticSimilarityExampleSelector as well similar_prompt.example_selector.add_example({"input": "enthusiastic", "output": "apathetic"}) print(similar_prompt.format(adjective="joyful")) Give the antonym of every input Input: happy Output: sad Input: joyful Output: previous
/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 implement two methods: An add_example method which takes in an example and adds it into the ExampleSelector A select_examples method which takes in input variables (which are meant to be user input) and returns a list of examples to use in the few shot prompt. Let’s implement a custom ExampleSelector that just selects two examples at random. Note Take a look at the current set of example selector implementations supported in LangChain here. Implement custom example selector# from langchain.prompts.example_selector.base import BaseExampleSelector from typing import Dict, List import numpy as np class CustomExampleSelector(BaseExampleSelector): def __init__(self, examples: List[Dict[str, str]]): self.examples = examples def add_example(self, example: Dict[str, str]) -> None: """Add new example to store for a key.""" self.examples.append(example) def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on the inputs.""" return np.random.choice(self.examples, size=2, replace=False) Use custom example selector# examples = [
/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 to the set of examples example_selector.add_example({"foo": "4"}) example_selector.examples # -> [{'foo': '1'}, {'foo': '2'}, {'foo': '3'}, {'foo': '4'}] # Select examples example_selector.select_examples({"foo": "foo"}) # -> array([{'foo': '1'}, {'foo': '4'}], dtype=object) previous Example Selectors next LengthBased ExampleSelector Contents Implement custom example selector Use custom example selector 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/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 embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples. from langchain.prompts.example_selector import MaxMarginalRelevanceExampleSelector from langchain.vectorstores import FAISS from langchain.embeddings import OpenAIEmbeddings from langchain.prompts import FewShotPromptTemplate, PromptTemplate example_prompt = PromptTemplate( input_variables=["input", "output"], template="Input: {input}\nOutput: {output}", ) # These are a lot of examples of a pretend task of creating antonyms. examples = [ {"input": "happy", "output": "sad"}, {"input": "tall", "output": "short"}, {"input": "energetic", "output": "lethargic"}, {"input": "sunny", "output": "gloomy"}, {"input": "windy", "output": "calm"}, ] example_selector = MaxMarginalRelevanceExampleSelector.from_examples(
/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, # This is the number of examples to produce. k=2 ) mmr_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Input: {adjective}\nOutput:", input_variables=["adjective"], ) # Input is a feeling, so should select the happy/sad example as the first one print(mmr_prompt.format(adjective="worried")) Give the antonym of every input Input: happy Output: sad Input: windy Output: calm Input: worried Output: # Let's compare this to what we would just get if we went solely off of similarity similar_prompt = FewShotPromptTemplate( # We provide an ExampleSelector instead of examples. example_selector=example_selector, example_prompt=example_prompt, prefix="Give the antonym of every input", suffix="Input: {adjective}\nOutput:", input_variables=["adjective"], ) similar_prompt.example_selector.k = 2
/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, Harrison Chase. Last updated on Apr 26, 2023.
/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 implement: get_format_instructions() -> str: A method which returns a string containing instructions for how the output of a language model should be formatted. parse(str) -> Any: A method which takes in a string (assumed to be the response from a language model) and parses it into some structure. And then one optional one: parse_with_prompt(str, PromptValue) -> Any: A method which takes in a string (assumed to be the response from a language model) and a prompt (assumed to the prompt that generated such a response) and parses it into some structure. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so. Below we go over the main type of output parser, the PydanticOutputParser. See the examples folder for other options. from langchain.prompts import PromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate from langchain.llms import OpenAI from langchain.chat_models import ChatOpenAI from langchain.output_parsers import PydanticOutputParser from pydantic import BaseModel, Field, validator from typing import List model_name = 'text-davinci-003' temperature = 0.0
/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 the joke") # You can add custom validation logic easily with Pydantic. @validator('setup') def question_ends_with_question_mark(cls, field): if field[-1] != '?': raise ValueError("Badly formed question!") return field # Set up a parser + inject instructions into the prompt template. parser = PydanticOutputParser(pydantic_object=Joke) prompt = PromptTemplate( template="Answer the user query.\n{format_instructions}\n{query}\n", input_variables=["query"], partial_variables={"format_instructions": parser.get_format_instructions()} ) # And a query intented to prompt a language model to populate the data structure. joke_query = "Tell me a joke." _input = prompt.format_prompt(query=joke_query) output = model(_input.to_string()) parser.parse(output) Joke(setup='Why did the chicken cross the road?', punchline='To get to the other side!') previous Output Parsers next CommaSeparatedListOutputParser By Harrison Chase
/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