id stringlengths 14 16 | text stringlengths 45 2.73k | source stringlengths 49 114 |
|---|---|---|
ed22b7d46209-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_iterations.html |
284572d69fdc-0 | .ipynb
.pdf
How to use a timeout for the agent
How to use a timeout for the agent#
This notebook walks through how to cap an agent executor after a certain amount of time. This can be useful for safeguarding against long running agent runs.
from langchain.agents import load_tools
from langchain.agents import initialize... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_time_limit.html |
284572d69fdc-1 | Final Answer: foo
> Finished chain.
'foo'
Now let’s try it again with the max_execution_time=1 keyword argument. It now stops nicely after 1 second (only one iteration usually)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, max_execution_time=1)
agent.run(adversarial_pro... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_time_limit.html |
de553f7a77d9-0 | .ipynb
.pdf
How to add SharedMemory to an Agent and its Tools
How to add SharedMemory to an Agent and its Tools#
This notebook goes over adding memory to both of an Agent and its tools. Before going through this notebook, please walk through the following notebooks, as this will build on top of both of them:
Adding mem... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-1 | Tool(
name = "Summary",
func=summry_chain.run,
description="useful for when you summarize a conversation. The input to this tool should be a string, representing who will read this summary."
)
]
prefix = """Have a conversation with a human, answering the following questions as best you can. ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-2 | Action: Search
Action Input: "ChatGPT"
Observation: Nov 30, 2022 ... We've trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer ... ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-3 | Thought: I now know the final answer.
Final Answer: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capab... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-4 | Action Input: Who developed ChatGPT
Observation: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large ... Feb 15, 2023 ... Who owns Chat GPT? Chat GPT is owned and developed by AI research and deployment company, OpenAI. Th... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-5 | Thought: I now know the final answer
Final Answer: ChatGPT was developed by OpenAI.
> Finished chain.
'ChatGPT was developed by OpenAI.'
agent_chain.run(input="Thanks. Summarize the conversation, for my daughter 5 years old.")
> Entering new AgentExecutor chain...
Thought: I need to simplify the conversation for a 5 ye... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-6 | print(agent_chain.memory.buffer)
Human: What is ChatGPT?
AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is a... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-7 | Tool(
name = "Summary",
func=summry_chain.run,
description="useful for when you summarize a conversation. The input to this tool should be a string, representing who will read this summary."
)
]
prefix = """Have a conversation with a human, answering the following questions as best you can. ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-8 | Action: Search
Action Input: "ChatGPT"
Observation: Nov 30, 2022 ... We've trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer ... ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-9 | Thought: I now know the final answer.
Final Answer: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capab... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-10 | Action Input: Who developed ChatGPT
Observation: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large ... Feb 15, 2023 ... Who owns Chat GPT? Chat GPT is owned and developed by AI research and deployment company, OpenAI. Th... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-11 | Thought: I now know the final answer
Final Answer: ChatGPT was developed by OpenAI.
> Finished chain.
'ChatGPT was developed by OpenAI.'
agent_chain.run(input="Thanks. Summarize the conversation, for my daughter 5 years old.")
> Entering new AgentExecutor chain...
Thought: I need to simplify the conversation for a 5 ye... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
de553f7a77d9-12 | print(agent_chain.memory.buffer)
Human: What is ChatGPT?
AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is a... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
82df7fe22edf-0 | .ipynb
.pdf
CSV Agent
CSV Agent#
This notebook shows how to use agents to interact with a csv. It is mostly optimized for question answering.
NOTE: this agent calls the Pandas DataFrame agent under the hood, which in turn calls the Python agent, which executes LLM generated Python code - this can be bad if the LLM gene... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/csv.html |
82df7fe22edf-1 | 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:
Thought: I can now calculate th... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/csv.html |
a01e328e7d36-0 | .ipynb
.pdf
Jira
Jira#
This notebook goes over how to use the Jira tool.
The Jira tool allows agents to interact with a given Jira instance, performing actions such as searching for issues and creating issues, the tool wraps the atlassian-python-api library, for more see: https://atlassian-python-api.readthedocs.io/jir... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/jira.html |
a01e328e7d36-1 | 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 descriptio... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/jira.html |
9d0988c10224-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... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
9d0988c10224-1 | 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', '/... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
9d0988c10224-2 | 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"... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
9d0988c10224-3 | Initialization
Example: getting the required POST parameters for a request
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/json.html |
6937542f9831-0 | .ipynb
.pdf
OpenAPI agents
Contents
1st example: hierarchical planning agent
To start, let’s collect some OpenAPI specs.
How big is this spec?
Let’s see some examples!
Try another API.
2nd example: “json explorer” agent
OpenAPI agents#
We can construct agents to consume arbitrary APIs, here APIs conformant to the Ope... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-1 | !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.githubusercont... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-2 | --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)|18... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-3 | 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 variabl... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-4 | from langchain.agents.agent_toolkits.openapi import planner
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_mo... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-5 | 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 creat... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-6 | 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:/... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-7 | 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 /recommen... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-8 | 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,... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-9 | 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:... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-10 | > 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:... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-11 | 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"
Thought:!! Cou... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-12 | Observation: babbage, davinci, text-davinci-edit-001, babbage-code-search-code, text-similarity-babbage-001, code-davinci-edit-001, text-davinci-edit-001, ada
Thought:Action: requests_post
Action Input: {"url": "https://api.openai.com/v1/completions", "data": {"model": "davinci", "prompt": "Give me a short piece of adv... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-13 | 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 AgentE... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-14 | 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 compr... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-15 | 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 In... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-16 | 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', '... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-17 | 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', '... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-18 | 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"... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-19 | > 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... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
6937542f9831-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... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi.html |
f4be42fda280-0 | .ipynb
.pdf
Natural Language APIs
Contents
First, import dependencies and load the LLM
Next, load the Natural Language API Toolkits
Create the Agent
Using Auth + Adding more Endpoints
Thank you!
Natural Language APIs#
Natural Language API Toolkits (NLAToolkits) permit LangChain Agents to efficiently plan and combine ... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html |
f4be42fda280-1 | Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.
Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.
Create the Agent#
# Slightly twe... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html |
f4be42fda280-2 | Action: Open_AI_Klarna_product_Api.productsUsingGET
Action Input: Italian clothes
Observation: The API response contains two products from the Alé brand in Italian Blue. The first is the Alé Colour Block Short Sleeve Jersey Men - Italian Blue, which costs $86.49, and the second is the Alé Dolid Flash Jersey Men - Itali... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html |
f4be42fda280-3 | llm,
"https://spoonacular.com/application/frontend/downloads/spoonacular-openapi-3.json",
requests=requests,
max_text_length=1800, # If you want to truncate the response text
)
Attempting to load an OpenAPI 3.0.0 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for be... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html |
f4be42fda280-4 | Unsupported APIPropertyLocation "header" for parameter Accept. Valid values are ['path', 'query'] Ignoring optional parameter
Unsupported APIPropertyLocation "header" for parameter Content-Type. Valid values are ['path', 'query'] Ignoring optional parameter
Unsupported APIPropertyLocation "header" for parameter Accept.... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html |
f4be42fda280-5 | Action: spoonacular_API.searchRecipes
Action Input: Italian
Observation: The API response contains 10 Italian recipes, including Turkey Tomato Cheese Pizza, Broccolini Quinoa Pilaf, Bruschetta Style Pork & Pasta, Salmon Quinoa Risotto, Italian Tuna Pasta, Roasted Brussels Sprouts With Garlic, Asparagus Lemon Risotto, I... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html |
f4be42fda280-6 | > Finished chain.
'To present for your Italian language class, you could wear an Italian Gold Sparkle Perfectina Necklace - Gold, an Italian Design Miami Cuban Link Chain Necklace - Gold, or an Italian Gold Miami Cuban Link Chain Necklace - Gold. For a recipe, you could make Turkey Tomato Cheese Pizza, Broccolini Quino... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/openapi_nla.html |
85f14717819c-0 | .ipynb
.pdf
Pandas Dataframe Agent
Pandas Dataframe Agent#
This notebook shows how to use agents to interact with a pandas dataframe. It is mostly optimized for question answering.
NOTE: this agent calls the Python agent under the hood, which executes LLM generated Python code - this can be bad if the LLM generated Pyt... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html |
85f14717819c-1 | 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: im... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/pandas.html |
75c6fed557f4-0 | .ipynb
.pdf
Python Agent
Contents
Fibonacci Example
Training neural net
Python Agent#
This notebook showcases an agent designed to write and execute python code to answer a question.
from langchain.agents.agent_toolkits import create_python_agent
from langchain.tools.python.tool import PythonREPLTool
from langchain.p... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/python.html |
75c6fed557f4-1 | I need to write a neural network in PyTorch and train it on the given data.
Action: Python REPL
Action Input:
import torch
# Define the model
model = torch.nn.Sequential(
torch.nn.Linear(1, 1)
)
# Define the loss
loss_fn = torch.nn.MSELoss()
# Define the optimizer
optimizer = torch.optim.SGD(model.parameters(), lr... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/python.html |
75c6fed557f4-2 | Thought: I now know the final answer
Final Answer: The prediction for x = 5 is 10.0.
> Finished chain.
'The prediction for x = 5 is 10.0.'
previous
Pandas Dataframe Agent
next
SQL Database Agent
Contents
Fibonacci Example
Training neural net
By Harrison Chase
© Copyright 2023, Harrison Chase.
La... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/python.html |
74c478bd82d0-0 | .ipynb
.pdf
SQL Database Agent
Contents
Initialization
Example: describing a table
Example: describing a table, recovering from an error
Example: running queries
Recovering from an error
SQL Database Agent#
This notebook showcases an agent designed to interact with a sql databases. The agent builds off of SQLDatabase... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-1 | Action: schema_sql_db
Action Input: "PlaylistTrack"
Observation:
CREATE TABLE "PlaylistTrack" (
"PlaylistId" INTEGER NOT NULL,
"TrackId" INTEGER NOT NULL,
PRIMARY KEY ("PlaylistId", "TrackId"),
FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"),
FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId"... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-2 | Thought: The table is called PlaylistTrack
Action: schema_sql_db
Action Input: "PlaylistTrack"
Observation:
CREATE TABLE "PlaylistTrack" (
"PlaylistId" INTEGER NOT NULL,
"TrackId" INTEGER NOT NULL,
PRIMARY KEY ("PlaylistId", "TrackId"),
FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"),
FOREIGN KEY("Playl... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-3 | "Address" NVARCHAR(70),
"City" NVARCHAR(40),
"State" NVARCHAR(40),
"Country" NVARCHAR(40),
"PostalCode" NVARCHAR(10),
"Phone" NVARCHAR(24),
"Fax" NVARCHAR(24),
"Email" NVARCHAR(60) NOT NULL,
"SupportRepId" INTEGER,
PRIMARY KEY ("CustomerId"),
FOREIGN KEY("SupportRepId") REFERENCES "Employee" ("Emplo... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-4 | "BillingCity" NVARCHAR(40),
"BillingState" NVARCHAR(40),
"BillingCountry" NVARCHAR(40),
"BillingPostalCode" NVARCHAR(10),
"Total" NUMERIC(10, 2) NOT NULL,
PRIMARY KEY ("InvoiceId"),
FOREIGN KEY("CustomerId") REFERENCES "Customer" ("CustomerId")
)
SELECT * FROM 'Invoice' LIMIT 3;
InvoiceId CustomerId Invoice... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-5 | Observation: [('USA', 523.0600000000003), ('Canada', 303.9599999999999), ('France', 195.09999999999994), ('Brazil', 190.09999999999997), ('Germany', 156.48), ('United Kingdom', 112.85999999999999), ('Czech Republic', 90.24000000000001), ('Portugal', 77.23999999999998), ('India', 75.25999999999999), ('Chile', 46.62)]
Th... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-6 | "TrackId" INTEGER NOT NULL,
PRIMARY KEY ("PlaylistId", "TrackId"),
FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"),
FOREIGN KEY("PlaylistId") REFERENCES "Playlist" ("PlaylistId")
)
SELECT * FROM 'PlaylistTrack' LIMIT 3;
PlaylistId TrackId
1 3402
1 3389
1 3390
Thought: I can use a SELECT statement to get the... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-7 | Thought: I now know the final answer.
Final Answer: The total number of tracks in each playlist are: '90’s Music' (1477), 'Brazilian Music' (39), 'Classical' (75), 'Classical 101 - Deep Cuts' (25), 'Classical 101 - Next Steps' (25), 'Classical 101 - The Basics' (25), 'Grunge' (15), 'Heavy Metal Classic' (26), 'Music' (... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-8 | CREATE TABLE "Artist" (
"ArtistId" INTEGER NOT NULL,
"Name" NVARCHAR(120),
PRIMARY KEY ("ArtistId")
)
SELECT * FROM 'Artist' LIMIT 3;
ArtistId Name
1 AC/DC
2 Accept
3 Aerosmith
CREATE TABLE "Track" (
"TrackId" INTEGER NOT NULL,
"Name" NVARCHAR(200) NOT NULL,
"AlbumId" INTEGER,
"MediaTypeId" INTEGER NOT NULL... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-9 | "InvoiceId" INTEGER NOT NULL,
"TrackId" INTEGER NOT NULL,
"UnitPrice" NUMERIC(10, 2) NOT NULL,
"Quantity" INTEGER NOT NULL,
PRIMARY KEY ("InvoiceLineId"),
FOREIGN KEY("TrackId") REFERENCES "Track" ("TrackId"),
FOREIGN KEY("InvoiceId") REFERENCES "Invoice" ("InvoiceId")
)
SELECT * FROM 'InvoiceLine' LIMIT 3;... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
74c478bd82d0-10 | Thought: I should double check my query before executing it.
Action: query_checker_sql_db
Action Input: SELECT Artist.Name, SUM(InvoiceLine.Quantity) AS TotalQuantity FROM Artist INNER JOIN Track ON Artist.ArtistId = Track.ArtistId INNER JOIN InvoiceLine ON Track.TrackId = InvoiceLine.TrackId GROUP BY Artist.Name ORDER... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/sql_database.html |
6de67dd578b2-0 | .ipynb
.pdf
Vectorstore Agent
Contents
Create the Vectorstores
Initialize Toolkit and Agent
Examples
Multiple Vectorstores
Examples
Vectorstore Agent#
This notebook showcases an agent designed to retrieve information from one or more vectorstores, either with or without sources.
Create the Vectorstores#
from langchai... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
6de67dd578b2-1 | )
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,
ve... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
6de67dd578b2-2 | 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", "s... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
6de67dd578b2-3 | 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... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
6de67dd578b2-4 | 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... | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
6de67dd578b2-5 | 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 21, 2023. | https://python.langchain.com/en/latest/modules/agents/toolkits/examples/vectorstore.html |
f22e46d0980d-0 | .ipynb
.pdf
Defining Custom Tools
Contents
Completely New Tools
Tool dataclass
Subclassing the BaseTool class
Using the tool decorator
Modify existing tools
Defining the priorities among Tools
Using tools to return directly
Multi-argument tools
Defining Custom Tools#
When constructing your own agent, you will need to... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-1 | tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to answer questions about current events"
),
]
# You can also define an args_schema to provide more information about inputs
from pydantic import BaseModel, Field
class CalculatorInput(BaseModel):
... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-2 | Final Answer: 3.991298452658078
> Finished chain.
'3.991298452658078'
Subclassing the BaseTool class#
class CustomSearchTool(BaseTool):
name = "Search"
description = "useful for when you need to answer questions about current events"
def _run(self, query: str) -> str:
"""Use the tool."""
ret... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-3 | Action: Calculator
Action Input: 25^(0.43)
> Entering new LLMMathChain chain...
25^(0.43)```text
25**(0.43)
```
...numexpr.evaluate("25**(0.43)")...
Answer: 3.991298452658078
> Finished chain.
Answer: 3.991298452658078I now know the final answer
Final Answer: 3.991298452658078
> Finished chain.
'3.991298452658078'
Usin... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-4 | """Searches the API for the query."""
return "Results"
search_api
Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class 'pydantic.main.SearchApi'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-5 | agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
> Entering new AgentExecutor chain...
I need to find out Leo DiCaprio's girlfriend's name and her age.
Action: Google Search
Action Input: "Leo DiCaprio girlfriend"I draw the lime at going to get a Mohawk, though." DiCaprio... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-6 | from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.llms import OpenAI
from langchain import LLMMathChain, SerpAPIWrapper
search = SerpAPIWrapper()
tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-7 | tools = [
Tool(
name="Calculator",
func=llm_math_chain.run,
description="useful for when you need to answer questions about math",
return_direct=True
)
]
llm = OpenAI(temperature=0)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
ag... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-8 | matches = re.findall(pattern, action_input)
if not matches:
raise ValueError(f"Could not parse action input: `{action_input}`")
# Create a dictionary with the parsed arguments and their values
parsed_input = {}
for arg, value in matches:
if value == "None... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
f22e46d0980d-9 | llm = OpenAI(temperature=0)
agent = initialize_agent([custom_search], llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, agent_kwargs={"output_parser": CustomOutputParser()})
agent.run("Search for me and tell me whatever it says")
> Entering new AgentExecutor chain...
I need to use a search function to fi... | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html |
6620f2dc5f3d-0 | .md
.pdf
Getting Started
Contents
List of Tools
Getting Started#
Tools are functions that agents can use to interact with the world.
These tools can be generic utilities (e.g. search), other chains, or even other agents.
Currently, tools can be loaded with the following snippet:
from langchain.agents import load_tool... | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html |
6620f2dc5f3d-1 | Requires LLM: No
wolfram-alpha
Tool Name: Wolfram Alpha
Tool Description: A wolfram alpha search engine. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query.
Notes: Calls the Wolfram Alpha API and then parses results.
Requires ... | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html |
6620f2dc5f3d-2 | Requires LLM: Yes
open-meteo-api
Tool Name: Open Meteo API
Tool Description: Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the Open Meteo API (https://api.open-meteo.com/), ... | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html |
6620f2dc5f3d-3 | For more information on this, see this page
searx-search
Tool Name: Search
Tool Description: A wrapper around SearxNG meta search engine. Input should be a search query.
Notes: SearxNG is easy to deploy self-hosted. It is a good privacy friendly alternative to Google Search. Uses the SearxNG API.
Requires LLM: No
Extra... | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html |
6620f2dc5f3d-4 | Notes: A connection to the OpenWeatherMap API (https://api.openweathermap.org), specifically the /data/2.5/weather endpoint.
Requires LLM: No
Extra Parameters: openweathermap_api_key (your API key to access this endpoint)
previous
Tools
next
Defining Custom Tools
Contents
List of Tools
By Harrison Chase
... | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html |
d14aa3f307d3-0 | .ipynb
.pdf
Multi-Input Tools
Multi-Input Tools#
This notebook shows how to use a tool that requires multiple inputs with an agent.
The difficulty in doing so comes from the fact that an agent decides its next step from a language model, which outputs a string. So if that step requires multiple inputs, they need to be ... | https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html |
d14aa3f307d3-1 | )
]
mrkl = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
mrkl.run("What is 3 times 4")
> Entering new AgentExecutor chain...
I need to multiply two numbers
Action: Multiplier
Action Input: 3,4
Observation: 12
Thought: I now know the final answer
Final Answer: 3 times 4 is 12
>... | https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html |
2aafe06fe7c1-0 | .ipynb
.pdf
Tool Input Schema
Tool Input Schema#
By default, tools infer the argument schema by inspecting the function signature. For more strict requirements, custom input schema can be specified, along with custom validation logic.
from typing import Any, Dict
from langchain.agents import AgentType, initialize_agent... | https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html |
2aafe06fe7c1-1 | answer = agent.run("What's the main title on langchain.com?")
print(answer)
The main title of langchain.com is "LANG CHAIN 🦜️🔗 Official Home Page"
agent.run("What's the main title on google.com?")
---------------------------------------------------------------------------
ValidationError Tra... | https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html |
2aafe06fe7c1-2 | 112 try:
--> 113 outputs = self._call(inputs)
114 except (KeyboardInterrupt, Exception) as e:
115 self.callback_manager.on_chain_error(e, verbose=self.verbose)
File ~/code/lc/lckg/langchain/agents/agent.py:792, in AgentExecutor._call(self, inputs)
790 # We now enter the agent loop (until it returns ... | https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html |
2aafe06fe7c1-3 | 103 tool_input: Union[str, Dict],
(...)
107 **kwargs: Any,
108 ) -> str:
109 """Run the tool."""
--> 110 run_input = self._parse_input(tool_input)
111 if not self.verbose and verbose is not None:
112 verbose_ = verbose
File ~/code/lc/lckg/langchain/tools/base.py:71, in... | https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html |
b84468082cf8-0 | .ipynb
.pdf
Apify
Apify#
This notebook shows how to use the Apify integration for LangChain.
Apify is a cloud platform for web scraping and data extraction,
which provides an ecosystem of more than a thousand
ready-made apps called Actors for various web scraping, crawling, and data extraction use cases.
For example, y... | https://python.langchain.com/en/latest/modules/agents/tools/examples/apify.html |
b84468082cf8-1 | loader = apify.call_actor(
actor_id="apify/website-content-crawler",
run_input={"startUrls": [{"url": "https://python.langchain.com/en/latest/"}]},
dataset_mapping_function=lambda item: Document(
page_content=item["text"] or "", metadata={"source": item["url"]}
),
)
Initialize the vector index f... | https://python.langchain.com/en/latest/modules/agents/tools/examples/apify.html |
9bc7da9b378d-0 | .ipynb
.pdf
Arxiv API
Arxiv API#
This notebook goes over how to use the arxiv component.
First, you need to install arxiv python package.
!pip install arxiv
from langchain.utilities import ArxivAPIWrapper
arxiv = ArxivAPIWrapper()
docs = arxiv.run("1605.08386")
docs
'Published: 2016-05-26\nTitle: Heat-bath random walks... | https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html |
9bc7da9b378d-1 | docs = arxiv.run("Caprice Stanley")
docs
'Published: 2017-10-10\nTitle: On Mixing Behavior of a Family of Random Walks Determined by a Linear Recurrence\nAuthors: Caprice Stanley, Seth Sullivant\nSummary: We study random walks on the integers mod $G_n$ that are determined by an\ninteger sequence $\\{ G_n \\}_{n \\geq 1... | https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html |
9bc7da9b378d-2 | docs = arxiv.run("1605.08386WWW")
docs
'No good Arxiv Result was found'
previous
Apify
next
Bash
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/agents/tools/examples/arxiv.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.