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']
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"]


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']
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"]
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: 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
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
Final Answer: The required parameters for a POST request to the /completions endpoint are 'model'.
> Finished chain.


> 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.
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.


> 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
Pandas Dataframe Agent
 Contents

OpenAPI agents
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
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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.python import PythonREPL
from langchain.llms.openai import OpenAI
agent_executor = create_python_agent(
    llm=OpenAI(temperature=0, max_tokens=1000),
    tool=PythonREPLTool(),
    verbose=True
)
Fibonacci Example#
This example was created by John Wiseman.
agent_executor.run("What is the 10th fibonacci number?")
> Entering new AgentExecutor chain...
 I need to calculate the 10th fibonacci number
Action: Python REPL
Action Input: def fibonacci(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)
Observation:
Thought: I need to call the function with 10 as the argument
Action: Python REPL
Action Input: fibonacci(10)
Observation:
Thought: I now know the final answer
Final Answer: 55
> Finished chain.
'55'
Training neural net#
This example was created by Samee Ur Rehman.
agent_executor.run("""Understand, write a single neuron neural network in PyTorch.
Take synthetic data for y=2x. Train for 1000 epochs and print every 100 epochs.
Return prediction for x = 5""")
> Entering new AgentExecutor chain...
 I need to write a neural network in PyTorch and train it on the given data.


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=0.01)
# Define the data
x_data = torch.tensor([[1.0], [2.0], [3.0], [4.0]])
y_data = torch.tensor([[2.0], [4.0], [6.0], [8.0]])
# Train the model
for epoch in range(1000):
    # Forward pass
    y_pred = model(x_data)
    # Compute and print loss
    loss = loss_fn(y_pred, y_data)
    if (epoch+1) % 100 == 0:
        print(f'Epoch {epoch+1}: loss = {loss.item():.4f}')
    # Zero the gradients
    optimizer.zero_grad()
    # Backward pass
    loss.backward()
    # Update the weights
    optimizer.step()
Observation: Epoch 100: loss = 0.0013
Epoch 200: loss = 0.0007
Epoch 300: loss = 0.0004
Epoch 400: loss = 0.0002
Epoch 500: loss = 0.0001
Epoch 600: loss = 0.0001
Epoch 700: loss = 0.0000
Epoch 800: loss = 0.0000
Epoch 900: loss = 0.0000
Epoch 1000: loss = 0.0000
Thought: I now know the final answer


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.

  Last updated on Apr 06, 2023.


.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 generated Python code is harmful. Use cautiously.
from langchain.agents import create_csv_agent
from langchain.llms import OpenAI
agent = create_csv_agent(OpenAI(temperature=0), 'titanic.csv', 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.'
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


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
Toolkits
next
JSON Agent
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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 parsed from that. Therefore, the currently supported way to do this is to write a smaller wrapper function that parses a string into multiple inputs.
For a concrete example, let’s work on giving an agent access to a multiplication function, which takes as input two integers. In order to use this, we will tell the agent to generate the “Action Input” as a comma-separated list of length two. We will then write a thin wrapper that takes a string, splits it into two around a comma, and passes both parsed sides as integers to the multiplication function.
from langchain.llms import OpenAI
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
Here is the multiplication function, as well as a wrapper to parse a string as input.
def multiplier(a, b):
    return a * b
def parsing_multiplier(string):
    a, b = string.split(",")
    return multiplier(int(a), int(b))
llm = OpenAI(temperature=0)
tools = [
    Tool(
        name = "Multiplier",
        func=parsing_multiplier,
        description="useful for when you need to multiply two numbers together. The input to this tool should be a comma separated list of numbers of length two, representing the two numbers you want to multiply together. For example, `1,2` would be the input if you wanted to multiply 1 by 2."
    )
]


)
]
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
> Finished chain.
'3 times 4 is 12'
previous
Defining Custom Tools
next
Apify
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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_tools
tool_names = [...]
tools = load_tools(tool_names)
Some tools (e.g. chains, agents) may require a base LLM to use to initialize them.
In that case, you can pass in an LLM as well:
from langchain.agents import load_tools
tool_names = [...]
llm = ...
tools = load_tools(tool_names, llm=llm)
Below is a list of all supported tools and relevant information:
Tool Name: The name the LLM refers to the tool by.
Tool Description: The description of the tool that is passed to the LLM.
Notes: Notes about the tool that are NOT passed to the LLM.
Requires LLM: Whether this tool requires an LLM to be initialized.
(Optional) Extra Parameters: What extra parameters are required to initialize this tool.
List of Tools#
python_repl
Tool Name: Python REPL
Tool Description: A Python shell. Use this to execute python commands. Input should be a valid python command. If you expect output it should be printed out.
Notes: Maintains state.
Requires LLM: No
serpapi
Tool Name: Search
Tool Description: A search engine. Useful for when you need to answer questions about current events. Input should be a search query.
Notes: Calls the Serp API and then parses results.
Requires LLM: No
wolfram-alpha
Tool Name: Wolfram Alpha


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 LLM: No
Extra Parameters: wolfram_alpha_appid: The Wolfram Alpha app id.
requests
Tool Name: Requests
Tool Description: A portal to the internet. Use this when you need to get specific content from a site. Input should be a specific url, and the output will be all the text on that page.
Notes: Uses the Python requests module.
Requires LLM: No
terminal
Tool Name: Terminal
Tool Description: Executes commands in a terminal. Input should be valid commands, and the output will be any output from running that command.
Notes: Executes commands with subprocess.
Requires LLM: No
pal-math
Tool Name: PAL-MATH
Tool Description: A language model that is excellent at solving complex word math problems. Input should be a fully worded hard word math problem.
Notes: Based on this paper.
Requires LLM: Yes
pal-colored-objects
Tool Name: PAL-COLOR-OBJ
Tool Description: A language model that is wonderful at reasoning about position and the color attributes of objects. Input should be a fully worded hard reasoning problem. Make sure to include all information about the objects AND the final question you want to answer.
Notes: Based on this paper.
Requires LLM: Yes
llm-math
Tool Name: Calculator
Tool Description: Useful for when you need to answer questions about math.
Notes: An instance of the LLMMath chain.
Requires LLM: Yes
open-meteo-api
Tool Name: Open Meteo API


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/), specifically the /v1/forecast endpoint.
Requires LLM: Yes
news-api
Tool Name: News API
Tool Description: Use this when you want to get information about the top headlines of current news stories. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the News API (https://newsapi.org), specifically the /v2/top-headlines endpoint.
Requires LLM: Yes
Extra Parameters: news_api_key (your API key to access this endpoint)
tmdb-api
Tool Name: TMDB API
Tool Description: Useful for when you want to get information from The Movie Database. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the TMDB API (https://api.themoviedb.org/3), specifically the /search/movie endpoint.
Requires LLM: Yes
Extra Parameters: tmdb_bearer_token (your Bearer Token to access this endpoint - note that this is different from the API key)
google-search
Tool Name: Search
Tool Description: A wrapper around Google Search. Useful for when you need to answer questions about current events. Input should be a search query.
Notes: Uses the Google Custom Search API
Requires LLM: No
Extra Parameters: google_api_key, google_cse_id
For more information on this, see this page
searx-search
Tool Name: Search


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 Parameters: searx_host
google-serper
Tool Name: Search
Tool Description: A low-cost Google Search API. Useful for when you need to answer questions about current events. Input should be a search query.
Notes: Calls the serper.dev Google Search API and then parses results.
Requires LLM: No
Extra Parameters: serper_api_key
For more information on this, see this page
wikipedia
Tool Name: Wikipedia
Tool Description: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, historical events, or other subjects. Input should be a search query.
Notes: Uses the wikipedia Python package to call the MediaWiki API and then parses results.
Requires LLM: No
Extra Parameters: top_k_results
podcast-api
Tool Name: Podcast API
Tool Description: Use the Listen Notes Podcast API to search all podcasts or episodes. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the Listen Notes Podcast API (https://www.PodcastAPI.com), specifically the /search/ endpoint.
Requires LLM: Yes
Extra Parameters: listen_api_key (your api key to access this endpoint)
openweathermap-api
Tool Name: OpenWeatherMap
Tool Description: A wrapper around OpenWeatherMap API. Useful for fetching current weather information for a specified location. Input should be a location string (e.g. ‘London,GB’).


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

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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
Defining Custom Tools#
When constructing your own agent, you will need to provide it with a list of Tools that it can use. Besides the actual function that is called, the Tool consists of several components:
name (str), is required
description (str), is optional
return_direct (bool), defaults to False
The function that should be called when the tool is selected should take as input a single string and return a single string.
There are two ways to define a tool, we will cover both in the example below.
# Import things that are needed generically
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.tools import BaseTool
from langchain.llms import OpenAI
from langchain import LLMMathChain, SerpAPIWrapper
Initialize the LLM to use for the agent.
llm = OpenAI(temperature=0)
Completely New Tools#
First, we show how to create completely new tools from scratch.
There are two ways to do this: either by using the Tool dataclass, or by subclassing the BaseTool class.
Tool dataclass#
# Load the tool configs that are needed.
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events"
    ),
    Tool(
        name="Calculator",
        func=llm_math_chain.run,


Tool(
        name="Calculator",
        func=llm_math_chain.run,
        description="useful for when you need to answer questions about math"
    )
]
# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
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 who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Camila Morrone
Thought: I now need to calculate her age raised to the 0.43 power
Action: Calculator
Action Input: 22^0.43
> Entering new LLMMathChain chain...
22^0.43
```python
import math
print(math.pow(22, 0.43))
```
Answer: 3.777824273683966
> Finished chain.
Observation: Answer: 3.777824273683966
Thought: I now know the final answer
Final Answer: Camila Morrone's age raised to the 0.43 power is 3.777824273683966.
> Finished chain.
"Camila Morrone's age raised to the 0.43 power is 3.777824273683966."
Subclassing the BaseTool class#
class CustomSearchTool(BaseTool):
    name = "Search"
    description = "useful for when you need to answer questions about current events"


description = "useful for when you need to answer questions about current events"
    def _run(self, query: str) -> str:
        """Use the tool."""
        return search.run(query)

    async def _arun(self, query: str) -> str:
        """Use the tool asynchronously."""
        raise NotImplementedError("BingSearchRun does not support async")

class CustomCalculatorTool(BaseTool):
    name = "Calculator"
    description = "useful for when you need to answer questions about math"
    def _run(self, query: str) -> str:
        """Use the tool."""
        return llm_math_chain.run(query)

    async def _arun(self, query: str) -> str:
        """Use the tool asynchronously."""
        raise NotImplementedError("BingSearchRun does not support async")
tools = [CustomSearchTool(), CustomCalculatorTool()]
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
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 who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Camila Morrone
Thought: I now need to calculate her age raised to the 0.43 power
Action: Calculator
Action Input: 22^0.43
> Entering new LLMMathChain chain...
22^0.43
```python
import math
print(math.pow(22, 0.43))
```
Answer: 3.777824273683966
> Finished chain.


```
Answer: 3.777824273683966
> Finished chain.
Observation: Answer: 3.777824273683966
Thought: I now know the final answer
Final Answer: Camila Morrone's age raised to the 0.43 power is 3.777824273683966.
> Finished chain.
"Camila Morrone's age raised to the 0.43 power is 3.777824273683966."
Using the tool decorator#
To make it easier to define custom tools, a @tool decorator is provided. This decorator can be used to quickly create a Tool from a simple function. The decorator uses the function name as the tool name by default, but this can be overridden by passing a string as the first argument. Additionally, the decorator will use the function’s docstring as the tool’s description.
from langchain.agents import tool
@tool
def search_api(query: str) -> str:
    """Searches the API for the query."""
    return "Results"
search_api
Tool(name='search_api', description='search_api(query: str) -> str - Searches the API for the query.', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1184e0cd0>, func=<function search_api at 0x1635f8700>, coroutine=None)
You can also provide arguments like the tool name and whether to return directly.
@tool("search", return_direct=True)
def search_api(query: str) -> str:
    """Searches the API for the query."""
    return "Results"
search_api


"""Searches the API for the query."""
    return "Results"
search_api
Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x1184e0cd0>, func=<function search_api at 0x1635f8670>, coroutine=None)
Modify existing tools#
Now, we show how to load existing tools and just modify them. In the example below, we do something really simple and change the Search tool to have the name Google Search.
from langchain.agents import load_tools
tools = load_tools(["serpapi", "llm-math"], llm=llm)
tools[0].name = "Google Search"
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
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 who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Google Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Camila Morrone
Thought: I need to find out Camila Morrone's age
Action: Google Search
Action Input: "Camila Morrone age"
Observation: 25 years
Thought: I need to calculate 25 raised to the 0.43 power
Action: Calculator
Action Input: 25^0.43
Observation: Answer: 3.991298452658078
Thought: I now know the final answer


Thought: I now know the final answer
Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.
> Finished chain.
"Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078."
Defining the priorities among Tools#
When you made a Custom tool, you may want the Agent to use the custom tool more than normal tools.
For example, you made a custom tool, which gets information on music from your database. When a user wants information on songs, You want the Agent to use  the custom tool more than the normal Search tool. But the Agent might prioritize a normal Search tool.
This can be accomplished by adding a statement such as Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?' to the description.
An example is below.
# Import things that are needed generically
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 answer questions about current events"
    ),
    Tool(
        name="Music Search",
        func=lambda x: "'All I Want For Christmas Is You' by Mariah Carey.", #Mock Function


description="A Music search engine. Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?'",
    )
]
agent = initialize_agent(tools, OpenAI(temperature=0), agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("what is the most famous song of christmas")
> Entering new AgentExecutor chain...
 I should use a music search engine to find the answer
Action: Music Search
Action Input: most famous song of christmas
Observation: 'All I Want For Christmas Is You' by Mariah Carey.
Thought: I now know the final answer
Final Answer: 'All I Want For Christmas Is You' by Mariah Carey.
> Finished chain.
"'All I Want For Christmas Is You' by Mariah Carey."
Using tools to return directly#
Often, it can be desirable to have a tool output returned directly to the user, if it’s called. You can do this easily with LangChain by setting the return_direct flag for a tool to be True.
llm_math_chain = LLMMathChain(llm=llm)
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)
agent.run("whats 2**.12")
> Entering new AgentExecutor chain...
 I need to calculate this
Action: Calculator
Action Input: 2**.12
Observation: Answer: 1.2599210498948732


Observation: Answer: 1.2599210498948732
> Finished chain.
'Answer: 1.2599210498948732'
previous
Getting Started
next
Multi-Input 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
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Search Tools
 Contents
Google Serper API Wrapper
SerpAPI
GoogleSearchAPIWrapper
SearxNG Meta Search Engine
Search Tools#
This notebook shows off usage of various search tools.
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI
llm = OpenAI(temperature=0)
Google Serper API Wrapper#
First, let’s try to use the Google Serper API tool.
tools = load_tools(["google-serper"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What is the weather in Pomfret?")
> Entering new AgentExecutor chain...
 I should look up the current weather conditions.
Action: Search
Action Input: "weather in Pomfret"
Observation: 37°F
Thought: I now know the current temperature in Pomfret.
Final Answer: The current temperature in Pomfret is 37°F.
> Finished chain.
'The current temperature in Pomfret is 37°F.'
SerpAPI#
Now, let’s use the SerpAPI tool.
tools = load_tools(["serpapi"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What is the weather in Pomfret?")
> Entering new AgentExecutor chain...
 I need to find out what the current weather is in Pomfret.
Action: Search
Action Input: "weather in Pomfret"


Action: Search
Action Input: "weather in Pomfret"
Observation: Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 ...
Thought: I now know the current weather in Pomfret.
Final Answer: Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 mph.
> Finished chain.
'Partly cloudy skies during the morning hours will give way to cloudy skies with light rain and snow developing in the afternoon. High 42F. Winds WNW at 10 to 15 mph.'
GoogleSearchAPIWrapper#
Now, let’s use the official Google Search API Wrapper.
tools = load_tools(["google-search"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What is the weather in Pomfret?")
> Entering new AgentExecutor chain...
 I should look up the current weather conditions.
Action: Google Search
Action Input: "weather in Pomfret"


Action: Google Search
Action Input: "weather in Pomfret"
Observation: Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%. Pomfret, CT Weather Forecast, with current conditions, wind, air quality, and what to expect for the next 3 days. Hourly Weather-Pomfret, CT. As of 12:52 am EST. Special Weather Statement +2 ... Hazardous Weather Conditions. Special Weather Statement ... Pomfret CT. Tonight ... National Digital Forecast Database Maximum Temperature Forecast. Pomfret Center Weather Forecasts. Weather Underground provides local & long-range weather forecasts, weatherreports, maps & tropical weather conditions for ... Pomfret, CT 12 hour by hour weather forecast includes precipitation, temperatures, sky conditions, rain chance, dew-point, relative humidity, wind direction ... North Pomfret Weather Forecasts. Weather Underground provides local & long-range weather forecasts, weatherreports, maps & tropical weather conditions for ... Today's Weather - Pomfret, CT. Dec 31, 2022 4:00 PM. Putnam MS. --. Weather forecast icon. Feels like --. Hi --. Lo --. Pomfret, CT temperature trend for the next 14 Days. Find daytime highs and nighttime lows from TheWeatherNetwork.com. Pomfret, MD Weather Forecast Date: 332 PM EST Wed Dec 28 2022. The area/counties/county of: Charles, including the cites of: St. Charles and Waldorf.
Thought: I now know the current weather conditions in Pomfret.
Final Answer: Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%.


> Finished AgentExecutor chain.
'Showers early becoming a steady light rain later in the day. Near record high temperatures. High around 60F. Winds SW at 10 to 15 mph. Chance of rain 60%.'
SearxNG Meta Search Engine#
Here we will be using a self hosted SearxNG meta search engine.
tools = load_tools(["searx-search"], searx_host="http://localhost:8888", llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What is the weather in Pomfret")
> Entering new AgentExecutor chain...
 I should look up the current weather
Action: SearX Search
Action Input: "weather in Pomfret"
Observation: Mainly cloudy with snow showers around in the morning. High around 40F. Winds NNW at 5 to 10 mph. Chance of snow 40%. Snow accumulations less than one inch.
10 Day Weather - Pomfret, MD As of 1:37 pm EST Today 49°/ 41° 52% Mon 27 | Day 49° 52% SE 14 mph Cloudy with occasional rain showers. High 49F. Winds SE at 10 to 20 mph. Chance of rain 50%....
10 Day Weather - Pomfret, VT As of 3:51 am EST Special Weather Statement Today 39°/ 32° 37% Wed 01 | Day 39° 37% NE 4 mph Cloudy with snow showers developing for the afternoon. High 39F....


Pomfret, CT ; Current Weather. 1:06 AM. 35°F · RealFeel® 32° ; TODAY'S WEATHER FORECAST. 3/3. 44°Hi. RealFeel® 50° ; TONIGHT'S WEATHER FORECAST. 3/3. 32°Lo.
Pomfret, MD Forecast Today Hourly Daily Morning 41° 1% Afternoon 43° 0% Evening 35° 3% Overnight 34° 2% Don't Miss Finally, Here’s Why We Get More Colds and Flu When It’s Cold Coast-To-Coast...
Pomfret, MD Weather Forecast | AccuWeather Current Weather 5:35 PM 35° F RealFeel® 36° RealFeel Shade™ 36° Air Quality Excellent Wind E 3 mph Wind Gusts 5 mph Cloudy More Details WinterCast...
Pomfret, VT Weather Forecast | AccuWeather Current Weather 11:21 AM 23° F RealFeel® 27° RealFeel Shade™ 25° Air Quality Fair Wind ESE 3 mph Wind Gusts 7 mph Cloudy More Details WinterCast...
Pomfret Center, CT Weather Forecast | AccuWeather Daily Current Weather 6:50 PM 39° F RealFeel® 36° Air Quality Fair Wind NW 6 mph Wind Gusts 16 mph Mostly clear More Details WinterCast...
12:00 pm · Feels Like36° · WindN 5 mph · Humidity43% · UV Index3 of 10 · Cloud Cover65% · Rain Amount0 in ...
Pomfret Center, CT Weather Conditions | Weather Underground star Popular Cities San Francisco, CA 49 °F Clear Manhattan, NY 37 °F Fair Schiller Park, IL (60176) warning39 °F Mostly Cloudy...


Thought: I now know the final answer
Final Answer: The current weather in Pomfret is mainly cloudy with snow showers around in the morning. The temperature is around 40F with winds NNW at 5 to 10 mph. Chance of snow is 40%.
> Finished chain.
'The current weather in Pomfret is mainly cloudy with snow showers around in the morning. The temperature is around 40F with winds NNW at 5 to 10 mph. Chance of snow is 40%.'
previous
Requests
next
SearxNG Search API
 Contents

Google Serper API Wrapper
SerpAPI
GoogleSearchAPIWrapper
SearxNG Meta Search Engine
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.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, you can use it to extract Google Search results, Instagram and Facebook profiles, products from Amazon or Shopify, Google Maps reviews, etc. etc.
In this example, we’ll use the Website Content Crawler Actor,
which can deeply crawl websites such as documentation, knowledge bases, help centers, or blogs,
and extract text content from the web pages. Then we feed the documents into a vector index and answer questions from it.
First, import ApifyWrapper into your source code:
from langchain.document_loaders.base import Document
from langchain.indexes import VectorstoreIndexCreator
from langchain.utilities import ApifyWrapper
Initialize it using your Apify API token and for the purpose of this example, also with your OpenAI API key:
import os
os.environ["OPENAI_API_KEY"] = "Your OpenAI API key"
os.environ["APIFY_API_TOKEN"] = "Your Apify API token"
apify = ApifyWrapper()
Then run the Actor, wait for it to finish, and fetch its results from the Apify dataset into a LangChain document loader.
Note that if you already have some results in an Apify dataset, you can load them directly using ApifyDatasetLoader, as shown in this notebook. In that notebook, you’ll also find the explanation of the dataset_mapping_function, which is used to map fields from the Apify dataset records to LangChain Document fields.
loader = apify.call_actor(
    actor_id="apify/website-content-crawler",


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 from the crawled documents:
index = VectorstoreIndexCreator().from_loaders([loader])
And finally, query the vector index:
query = "What is LangChain?"
result = index.query_with_sources(query)
print(result["answer"])
print(result["sources"])
 LangChain is a standard interface through which you can interact with a variety of large language models (LLMs). It provides modules that can be used to build language model applications, and it also provides chains and agents with memory capabilities.
https://python.langchain.com/en/latest/modules/models/llms.html, https://python.langchain.com/en/latest/getting_started/getting_started.html
previous
Multi-Input Tools
next
Bash
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Bash
Bash#
It can often be useful to have an LLM generate bash commands, and then run them. A common use case for this is letting the LLM interact with your local file system. We provide an easy util to execute bash commands.
from langchain.utilities import BashProcess
bash = BashProcess()
print(bash.run("ls"))
bash.ipynb
google_search.ipynb
python.ipynb
requests.ipynb
serpapi.ipynb
previous
Apify
next
Bing Search
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Zapier Natural Language Actions API
 Contents
Zapier Natural Language Actions API
Example with Agent
Example with SimpleSequentialChain
Zapier Natural Language Actions API#
Full docs here: https://nla.zapier.com/api/v1/docs
Zapier Natural Language Actions gives you access to the 5k+ apps, 20k+ actions on Zapier’s platform through a natural language API interface.
NLA supports apps like Gmail, Salesforce, Trello, Slack, Asana, HubSpot, Google Sheets, Microsoft Teams, and thousands more apps: https://zapier.com/apps
Zapier NLA handles ALL the underlying API auth and translation from natural language –> underlying API call –> return simplified output for LLMs. The key idea is you, or your users, expose a set of actions via an oauth-like setup window, which you can then query and execute via a REST API.
NLA offers both API Key and OAuth for signing NLA API requests.
Server-side (API Key): for quickly getting started, testing, and production scenarios where LangChain will only use actions exposed in the developer’s Zapier account (and will use the developer’s connected accounts on Zapier.com)
User-facing (Oauth): for production scenarios where you are deploying an end-user facing application and LangChain needs access to end-user’s exposed actions and connected accounts on Zapier.com
This quick start will focus on the server-side use case for brevity. Review full docs or reach out to nla@zapier.com for user-facing oauth developer support.
This example goes over how to use the Zapier integration with a SimpleSequentialChain, then an Agent.
In code, below:
%load_ext autoreload
%autoreload 2
import os
# get from https://platform.openai.com/


%autoreload 2
import os
# get from https://platform.openai.com/
os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "")
# get from https://nla.zapier.com/demo/provider/debug (under User Information, after logging in):
os.environ["ZAPIER_NLA_API_KEY"] = os.environ.get("ZAPIER_NLA_API_KEY", "")
Example with Agent#
Zapier tools can be used with an agent. See the example below.
from langchain.llms import OpenAI
from langchain.agents import initialize_agent
from langchain.agents.agent_toolkits import ZapierToolkit
from langchain.agents import AgentType
from langchain.utilities.zapier import ZapierNLAWrapper
## step 0. expose gmail 'find email' and slack 'send channel message' actions
# first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all fields "Have AI guess"
# in an oauth scenario, you'd get your own <provider> id (instead of 'demo') which you route your users through first
llm = OpenAI(temperature=0)
zapier = ZapierNLAWrapper()
toolkit = ZapierToolkit.from_zapier_nla_wrapper(zapier)
agent = initialize_agent(toolkit.get_tools(), llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("Summarize the last email I received regarding Silicon Valley Bank. Send the summary to the #test-zapier channel in slack.")
> Entering new AgentExecutor chain...
 I need to find the email and summarize it.
Action: Gmail: Find Email
Action Input: Find the latest email from Silicon Valley Bank


Action: Gmail: Find Email
Action Input: Find the latest email from Silicon Valley Bank
Observation: {"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "sreply@svb.com", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & have an ask for clients & partners as we rebuild. Tim Mayopoulos <https://eml.svb.com/NjEwLUtBSy0yNjYAAAGKgoxUeBCLAyF_NxON97X4rKEaNBLG", "reply_to__email": "sreply@svb.com", "subject": "Meet the new CEO Tim Mayopoulos", "date": "Tue, 14 Mar 2023 23:42:29 -0500 (CDT)", "message_url": "https://mail.google.com/mail/u/0/#inbox/186e393b13cfdf0a", "attachment_count": "0", "to__emails": "ankush@langchain.dev", "message_id": "186e393b13cfdf0a", "labels": "IMPORTANT, CATEGORY_UPDATES, INBOX"}
Thought: I need to summarize the email and send it to the #test-zapier channel in Slack.
Action: Slack: Send Channel Message
Action Input: Send a slack message to the #test-zapier channel with the text "Silicon Valley Bank has announced that Tim Mayopoulos is the new CEO. FDIC is fully insuring all deposits and they have an ask for clients and partners as they rebuild."


Observation: {"message__text": "Silicon Valley Bank has announced that Tim Mayopoulos is the new CEO. FDIC is fully insuring all deposits and they have an ask for clients and partners as they rebuild.", "message__permalink": "https://langchain.slack.com/archives/C04TSGU0RA7/p1678859932375259", "channel": "C04TSGU0RA7", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:58:52Z", "message__bot_profile__icons__image_36": "https://avatars.slack-edge.com/2022-08-02/3888649620612_f864dc1bb794cf7d82b0_36.png", "message__blocks[]block_id": "kdZZ", "message__blocks[]elements[]type": "['rich_text_section']"}
Thought: I now know the final answer.
Final Answer: I have sent a summary of the last email from Silicon Valley Bank to the #test-zapier channel in Slack.
> Finished chain.
'I have sent a summary of the last email from Silicon Valley Bank to the #test-zapier channel in Slack.'
Example with SimpleSequentialChain#
If you need more explicit control, use a chain, like below.
from langchain.llms import OpenAI
from langchain.chains import LLMChain, TransformChain, SimpleSequentialChain
from langchain.prompts import PromptTemplate
from langchain.tools.zapier.tool import ZapierNLARunAction


from langchain.tools.zapier.tool import ZapierNLARunAction
from langchain.utilities.zapier import ZapierNLAWrapper
## step 0. expose gmail 'find email' and slack 'send direct message' actions
# first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all fields "Have AI guess"
# in an oauth scenario, you'd get your own <provider> id (instead of 'demo') which you route your users through first
actions = ZapierNLAWrapper().list()
## step 1. gmail find email
GMAIL_SEARCH_INSTRUCTIONS = "Grab the latest email from Silicon Valley Bank"
def nla_gmail(inputs):
    action = next((a for a in actions if a["description"].startswith("Gmail: Find Email")), None)
    return {"email_data": ZapierNLARunAction(action_id=action["id"], zapier_description=action["description"], params_schema=action["params"]).run(inputs["instructions"])}
gmail_chain = TransformChain(input_variables=["instructions"], output_variables=["email_data"], transform=nla_gmail)
## step 2. generate draft reply
template = """You are an assisstant who drafts replies to an incoming email. Output draft reply in plain text (not JSON).
Incoming email:
{email_data}
Draft email reply:"""
prompt_template = PromptTemplate(input_variables=["email_data"], template=template)
reply_chain = LLMChain(llm=OpenAI(temperature=.7), prompt=prompt_template)
## step 3. send draft reply via a slack direct message
SLACK_HANDLE = "@Ankush Gola"
def nla_slack(inputs):


SLACK_HANDLE = "@Ankush Gola"
def nla_slack(inputs):
    action = next((a for a in actions if a["description"].startswith("Slack: Send Direct Message")), None)
    instructions = f'Send this to {SLACK_HANDLE} in Slack: {inputs["draft_reply"]}'
    return {"slack_data": ZapierNLARunAction(action_id=action["id"], zapier_description=action["description"], params_schema=action["params"]).run(instructions)}
slack_chain = TransformChain(input_variables=["draft_reply"], output_variables=["slack_data"], transform=nla_slack)
## finally, execute
overall_chain = SimpleSequentialChain(chains=[gmail_chain, reply_chain, slack_chain], verbose=True)
overall_chain.run(GMAIL_SEARCH_INSTRUCTIONS)
> Entering new SimpleSequentialChain chain...


overall_chain.run(GMAIL_SEARCH_INSTRUCTIONS)
> Entering new SimpleSequentialChain chain...
{"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "sreply@svb.com", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & have an ask for clients & partners as we rebuild. Tim Mayopoulos <https://eml.svb.com/NjEwLUtBSy0yNjYAAAGKgoxUeBCLAyF_NxON97X4rKEaNBLG", "reply_to__email": "sreply@svb.com", "subject": "Meet the new CEO Tim Mayopoulos", "date": "Tue, 14 Mar 2023 23:42:29 -0500 (CDT)", "message_url": "https://mail.google.com/mail/u/0/#inbox/186e393b13cfdf0a", "attachment_count": "0", "to__emails": "ankush@langchain.dev", "message_id": "186e393b13cfdf0a", "labels": "IMPORTANT, CATEGORY_UPDATES, INBOX"}
Dear Silicon Valley Bridge Bank,
Thank you for your email and the update regarding your new CEO Tim Mayopoulos. We appreciate your dedication to keeping your clients and partners informed and we look forward to continuing our relationship with you.
Best regards,
[Your Name]


Best regards,
[Your Name]
{"message__text": "Dear Silicon Valley Bridge Bank, \n\nThank you for your email and the update regarding your new CEO Tim Mayopoulos. We appreciate your dedication to keeping your clients and partners informed and we look forward to continuing our relationship with you. \n\nBest regards, \n[Your Name]", "message__permalink": "https://langchain.slack.com/archives/D04TKF5BBHU/p1678859968241629", "channel": "D04TKF5BBHU", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:59:28Z", "message__blocks[]block_id": "p7i", "message__blocks[]elements[]elements[]type": "[['text']]", "message__blocks[]elements[]type": "['rich_text_section']"}
> Finished chain.


> Finished chain.
'{"message__text": "Dear Silicon Valley Bridge Bank, \\n\\nThank you for your email and the update regarding your new CEO Tim Mayopoulos. We appreciate your dedication to keeping your clients and partners informed and we look forward to continuing our relationship with you. \\n\\nBest regards, \\n[Your Name]", "message__permalink": "https://langchain.slack.com/archives/D04TKF5BBHU/p1678859968241629", "channel": "D04TKF5BBHU", "message__bot_profile__name": "Zapier", "message__team": "T04F8K3FZB5", "message__bot_id": "B04TRV4R74K", "message__bot_profile__deleted": "false", "message__bot_profile__app_id": "A024R9PQM", "ts_time": "2023-03-15T05:59:28Z", "message__blocks[]block_id": "p7i", "message__blocks[]elements[]elements[]type": "[[\'text\']]", "message__blocks[]elements[]type": "[\'rich_text_section\']"}'
previous
Wolfram Alpha
next
Agents
 Contents

Zapier Natural Language Actions API
Example with Agent
Example with SimpleSequentialChain
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
SearxNG Search API
 Contents
Custom Parameters
Obtaining results with metadata
SearxNG Search API#
This notebook goes over how to use a self hosted SearxNG search API to search the web.
You can check this link for more informations about Searx API parameters.
import pprint
from langchain.utilities import SearxSearchWrapper
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888")
For some engines, if a direct answer is available the warpper will print the answer instead of the full list of search results. You can use the results method of the wrapper if you want to obtain all the results.
search.run("What is the capital of France")
'Paris is the capital of France, the largest country of Europe with 550 000 km2 (65 millions inhabitants). Paris has 2.234 million inhabitants end 2011. She is the core of Ile de France region (12 million people).'
Custom Parameters#
SearxNG supports up to 139 search engines. You can also customize the Searx wrapper with arbitrary named parameters that will be passed to the Searx search API . In the below example we will making a more interesting use of custom search parameters from searx search api.
In this example we will be using the engines parameters to query wikipedia
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888", k=5) # k is for max number of items
search.run("large language model ", engines=['wiki'])


search.run("large language model ", engines=['wiki'])
'Large language models (LLMs) represent a major advancement in AI, with the promise of transforming domains through learned knowledge. LLM sizes have been increasing 10X every year for the last few years, and as these models grow in complexity and size, so do their capabilities.\n\nGPT-3 can translate language, write essays, generate computer code, and more — all with limited to no supervision. In July 2020, OpenAI unveiled GPT-3, a language model that was easily the largest known at the time. Put simply, GPT-3 is trained to predict the next word in a sentence, much like how a text message autocomplete feature works.\n\nA large language model, or LLM, is a deep learning algorithm that can recognize, summarize, translate, predict and generate text and other content based on knowledge gained from massive datasets. Large language models are among the most successful applications of transformer models.\n\nAll of today’s well-known language models—e.g., GPT-3 from OpenAI, PaLM or LaMDA from Google, Galactica or OPT from Meta, Megatron-Turing from Nvidia/Microsoft, Jurassic-1 from AI21 Labs—are...\n\nLarge language models (LLMs) such as GPT-3are increasingly being used to generate text. These tools should be used with care, since they can generate content that is biased, non-verifiable, constitutes original research, or violates copyrights.'
Passing other Searx parameters for searx like language
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888", k=1)
search.run("deep learning", language='es', engines=['wiki'])


search.run("deep learning", language='es', engines=['wiki'])
'Aprendizaje profundo (en inglés, deep learning) es un conjunto de algoritmos de aprendizaje automático (en inglés, machine learning) que intenta modelar abstracciones de alto nivel en datos usando arquitecturas computacionales que admiten transformaciones no lineales múltiples e iterativas de datos expresados en forma matricial o tensorial. 1'
Obtaining results with metadata#
In this example we will be looking for scientific paper using the categories parameter and limiting the results to a time_range (not all engines support the time range option).
We also would like to obtain the results in a structured way including metadata. For this we will be using the results method of the wrapper.
search = SearxSearchWrapper(searx_host="http://127.0.0.1:8888")
results = search.results("Large Language Model prompt", num_results=5, categories='science', time_range='year')
pprint.pp(results)
[{'snippet': '… on natural language instructions, large language models (… the '
             'prompt used to steer the model, and most effective prompts … to '
             'prompt engineering, we propose Automatic Prompt …',
  'title': 'Large language models are human-level prompt engineers',
  'link': 'https://arxiv.org/abs/2211.01910',
  'engines': ['google scholar'],
  'category': 'science'},
 {'snippet': '… Large language models (LLMs) have introduced new possibilities '
             'for prototyping with AI [18]. Pre-trained on a large amount of '
             'text data, models … language instructions called prompts. …',
  'title': 'Promptchainer: Chaining large language model prompts through '


'title': 'Promptchainer: Chaining large language model prompts through '
           'visual programming',
  'link': 'https://dl.acm.org/doi/abs/10.1145/3491101.3519729',
  'engines': ['google scholar'],
  'category': 'science'},
 {'snippet': '… can introspect the large prompt model. We derive the view '
             'ϕ0(X) and the model h0 from T01. However, instead of fully '
             'fine-tuning T0 during co-training, we focus on soft prompt '
             'tuning, …',
  'title': 'Co-training improves prompt-based learning for large language '
           'models',
  'link': 'https://proceedings.mlr.press/v162/lang22a.html',
  'engines': ['google scholar'],
  'category': 'science'},
 {'snippet': '… With the success of large language models (LLMs) of code and '
             'their use as … prompt design process become important. In this '
             'work, we propose a framework called Repo-Level Prompt …',
  'title': 'Repository-level prompt generation for large language models of '
           'code',
  'link': 'https://arxiv.org/abs/2206.12839',
  'engines': ['google scholar'],
  'category': 'science'},
 {'snippet': '… Figure 2 | The benefits of different components of a prompt '
             'for the largest language model (Gopher), as estimated from '
             'hierarchical logistic regression. Each point estimates the '
             'unique …',
  'title': 'Can language models learn from explanations in context?',
  'link': 'https://arxiv.org/abs/2204.02329',


'link': 'https://arxiv.org/abs/2204.02329',
  'engines': ['google scholar'],
  'category': 'science'}]
Get papers from arxiv
results = search.results("Large Language Model prompt", num_results=5, engines=['arxiv'])
pprint.pp(results)
[{'snippet': 'Thanks to the advanced improvement of large pre-trained language '
             'models, prompt-based fine-tuning is shown to be effective on a '
             'variety of downstream tasks. Though many prompting methods have '
             'been investigated, it remains unknown which type of prompts are '
             'the most effective among three types of prompts (i.e., '
             'human-designed prompts, schema prompts and null prompts). In '
             'this work, we empirically compare the three types of prompts '
             'under both few-shot and fully-supervised settings. Our '
             'experimental results show that schema prompts are the most '
             'effective in general. Besides, the performance gaps tend to '
             'diminish when the scale of training data grows large.',
  'title': 'Do Prompts Solve NLP Tasks Using Natural Language?',
  'link': 'http://arxiv.org/abs/2203.00902v1',
  'engines': ['arxiv'],
  'category': 'science'},
 {'snippet': 'Cross-prompt automated essay scoring (AES) requires the system '
             'to use non target-prompt essays to award scores to a '
             'target-prompt essay. Since obtaining a large quantity of '
             'pre-graded essays to a particular prompt is often difficult and '
             'unrealistic, the task of cross-prompt AES is vital for the '
             'development of real-world AES systems, yet it remains an '


'development of real-world AES systems, yet it remains an '
             'under-explored area of research. Models designed for '
             'prompt-specific AES rely heavily on prompt-specific knowledge '
             'and perform poorly in the cross-prompt setting, whereas current '
             'approaches to cross-prompt AES either require a certain quantity '
             'of labelled target-prompt essays or require a large quantity of '
             'unlabelled target-prompt essays to perform transfer learning in '
             'a multi-step manner. To address these issues, we introduce '
             'Prompt Agnostic Essay Scorer (PAES) for cross-prompt AES. Our '
             'method requires no access to labelled or unlabelled '
             'target-prompt data during training and is a single-stage '
             'approach. PAES is easy to apply in practice and achieves '
             'state-of-the-art performance on the Automated Student Assessment '
             'Prize (ASAP) dataset.',
  'title': 'Prompt Agnostic Essay Scorer: A Domain Generalization Approach to '
           'Cross-prompt Automated Essay Scoring',
  'link': 'http://arxiv.org/abs/2008.01441v1',
  'engines': ['arxiv'],
  'category': 'science'},
 {'snippet': 'Research on prompting has shown excellent performance with '
             'little or even no supervised training across many tasks. '
             'However, prompting for machine translation is still '
             'under-explored in the literature. We fill this gap by offering a '
             'systematic study on prompting strategies for translation, '
             'examining various factors for prompt template and demonstration '
             'example selection. We further explore the use of monolingual '


'example selection. We further explore the use of monolingual '
             'data and the feasibility of cross-lingual, cross-domain, and '
             'sentence-to-document transfer learning in prompting. Extensive '
             'experiments with GLM-130B (Zeng et al., 2022) as the testbed '
             'show that 1) the number and the quality of prompt examples '
             'matter, where using suboptimal examples degenerates translation; '
             '2) several features of prompt examples, such as semantic '
             'similarity, show significant Spearman correlation with their '
             'prompting performance; yet, none of the correlations are strong '
             'enough; 3) using pseudo parallel prompt examples constructed '
             'from monolingual data via zero-shot prompting could improve '
             'translation; and 4) improved performance is achievable by '
             'transferring knowledge from prompt examples selected in other '
             'settings. We finally provide an analysis on the model outputs '
             'and discuss several problems that prompting still suffers from.',
  'title': 'Prompting Large Language Model for Machine Translation: A Case '
           'Study',
  'link': 'http://arxiv.org/abs/2301.07069v2',
  'engines': ['arxiv'],
  'category': 'science'},
 {'snippet': 'Large language models can perform new tasks in a zero-shot '
             'fashion, given natural language prompts that specify the desired '
             'behavior. Such prompts are typically hand engineered, but can '
             'also be learned with gradient-based methods from labeled data. '
             'However, it is underexplored what factors make the prompts '
             'effective, especially when the prompts are natural language. In '


'effective, especially when the prompts are natural language. In '
             'this paper, we investigate common attributes shared by effective '
             'prompts. We first propose a human readable prompt tuning method '
             '(F LUENT P ROMPT) based on Langevin dynamics that incorporates a '
             'fluency constraint to find a diverse distribution of effective '
             'and fluent prompts. Our analysis reveals that effective prompts '
             'are topically related to the task domain and calibrate the prior '
             'probability of label words. Based on these findings, we also '
             'propose a method for generating prompts using only unlabeled '
             'data, outperforming strong baselines by an average of 7.0% '
             'accuracy across three tasks.',
  'title': "Toward Human Readable Prompt Tuning: Kubrick's The Shining is a "
           'good movie, and a good prompt too?',
  'link': 'http://arxiv.org/abs/2212.10539v1',
  'engines': ['arxiv'],
  'category': 'science'},
 {'snippet': 'Prevailing methods for mapping large generative language models '
             "to supervised tasks may fail to sufficiently probe models' novel "
             'capabilities. Using GPT-3 as a case study, we show that 0-shot '
             'prompts can significantly outperform few-shot prompts. We '
             'suggest that the function of few-shot examples in these cases is '
             'better described as locating an already learned task rather than '
             'meta-learning. This analysis motivates rethinking the role of '
             'prompts in controlling and evaluating powerful language models. '
             'In this work, we discuss methods of prompt programming, '


'In this work, we discuss methods of prompt programming, '
             'emphasizing the usefulness of considering prompts through the '
             'lens of natural language. We explore techniques for exploiting '
             'the capacity of narratives and cultural anchors to encode '
             'nuanced intentions and techniques for encouraging deconstruction '
             'of a problem into components before producing a verdict. '
             'Informed by this more encompassing theory of prompt programming, '
             'we also introduce the idea of a metaprompt that seeds the model '
             'to generate its own natural language prompts for a range of '
             'tasks. Finally, we discuss how these more general methods of '
             'interacting with language models can be incorporated into '
             'existing and future benchmarks and practical applications.',
  'title': 'Prompt Programming for Large Language Models: Beyond the Few-Shot '
           'Paradigm',
  'link': 'http://arxiv.org/abs/2102.07350v1',
  'engines': ['arxiv'],
  'category': 'science'}]
In this example we query for large language models under the it category. We then filter the results that come from github.
results = search.results("large language model", num_results = 20, categories='it')
pprint.pp(list(filter(lambda r: r['engines'][0] == 'github', results)))
[{'snippet': 'Guide to using pre-trained large language models of source code',
  'title': 'Code-LMs',
  'link': 'https://github.com/VHellendoorn/Code-LMs',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Dramatron uses large language models to generate coherent '
             'scripts and screenplays.',


'scripts and screenplays.',
  'title': 'dramatron',
  'link': 'https://github.com/deepmind/dramatron',
  'engines': ['github'],
  'category': 'it'}]
We could also directly query for results from github and other source forges.
results = search.results("large language model", num_results = 20, engines=['github', 'gitlab'])
pprint.pp(results)
[{'snippet': "Implementation of 'A Watermark for Large Language Models' paper "
             'by Kirchenbauer & Geiping et. al.',
  'title': 'Peutlefaire / LMWatermark',
  'link': 'https://gitlab.com/BrianPulfer/LMWatermark',
  'engines': ['gitlab'],
  'category': 'it'},
 {'snippet': 'Guide to using pre-trained large language models of source code',
  'title': 'Code-LMs',
  'link': 'https://github.com/VHellendoorn/Code-LMs',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': '',
  'title': 'Simen Burud / Large-scale Language Models for Conversational '
           'Speech Recognition',
  'link': 'https://gitlab.com/BrianPulfer',
  'engines': ['gitlab'],
  'category': 'it'},
 {'snippet': 'Dramatron uses large language models to generate coherent '
             'scripts and screenplays.',
  'title': 'dramatron',
  'link': 'https://github.com/deepmind/dramatron',
  'engines': ['github'],
  'category': 'it'},


'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Code for loralib, an implementation of "LoRA: Low-Rank '
             'Adaptation of Large Language Models"',
  'title': 'LoRA',
  'link': 'https://github.com/microsoft/LoRA',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Code for the paper "Evaluating Large Language Models Trained on '
             'Code"',
  'title': 'human-eval',
  'link': 'https://github.com/openai/human-eval',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'A trend starts from "Chain of Thought Prompting Elicits '
             'Reasoning in Large Language Models".',
  'title': 'Chain-of-ThoughtsPapers',
  'link': 'https://github.com/Timothyxxx/Chain-of-ThoughtsPapers',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Mistral: A strong, northwesterly wind: Framework for transparent '
             'and accessible large-scale language model training, built with '
             'Hugging Face 🤗 Transformers.',
  'title': 'mistral',
  'link': 'https://github.com/stanford-crfm/mistral',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'A prize for finding tasks that cause large language models to '
             'show inverse scaling',
  'title': 'prize',
  'link': 'https://github.com/inverse-scaling/prize',
  'engines': ['github'],


'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Optimus: the first large-scale pre-trained VAE language model',
  'title': 'Optimus',
  'link': 'https://github.com/ChunyuanLI/Optimus',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Seminar on Large Language Models (COMP790-101 at UNC Chapel '
             'Hill, Fall 2022)',
  'title': 'llm-seminar',
  'link': 'https://github.com/craffel/llm-seminar',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'A central, open resource for data and tools related to '
             'chain-of-thought reasoning in large language models. Developed @ '
             'Samwald research group: https://samwald.info/',
  'title': 'ThoughtSource',
  'link': 'https://github.com/OpenBioLink/ThoughtSource',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'A comprehensive list of papers using large language/multi-modal '
             'models for Robotics/RL, including papers, codes, and related '
             'websites',
  'title': 'Awesome-LLM-Robotics',
  'link': 'https://github.com/GT-RIPL/Awesome-LLM-Robotics',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Tools for curating biomedical training data for large-scale '
             'language modeling',
  'title': 'biomedical',
  'link': 'https://github.com/bigscience-workshop/biomedical',


'link': 'https://github.com/bigscience-workshop/biomedical',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'ChatGPT @ Home: Large Language Model (LLM) chatbot application, '
             'written by ChatGPT',
  'title': 'ChatGPT-at-Home',
  'link': 'https://github.com/Sentdex/ChatGPT-at-Home',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Design and Deploy Large Language Model Apps',
  'title': 'dust',
  'link': 'https://github.com/dust-tt/dust',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Polyglot: Large Language Models of Well-balanced Competence in '
             'Multi-languages',
  'title': 'polyglot',
  'link': 'https://github.com/EleutherAI/polyglot',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'Code release for "Learning Video Representations from Large '
             'Language Models"',
  'title': 'LaViLa',
  'link': 'https://github.com/facebookresearch/LaViLa',
  'engines': ['github'],
  'category': 'it'},
 {'snippet': 'SmoothQuant: Accurate and Efficient Post-Training Quantization '
             'for Large Language Models',
  'title': 'smoothquant',
  'link': 'https://github.com/mit-han-lab/smoothquant',
  'engines': ['github'],
  'category': 'it'},


'engines': ['github'],
  'category': 'it'},
 {'snippet': 'This repository contains the code, data, and models of the paper '
             'titled "XL-Sum: Large-Scale Multilingual Abstractive '
             'Summarization for 44 Languages" published in Findings of the '
             'Association for Computational Linguistics: ACL-IJCNLP 2021.',
  'title': 'xl-sum',
  'link': 'https://github.com/csebuetnlp/xl-sum',
  'engines': ['github'],
  'category': 'it'}]
previous
Search Tools
next
SerpAPI
 Contents

Custom Parameters
Obtaining results with metadata
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Bing Search
 Contents
Number of results
Metadata Results
Bing Search#
This notebook goes over how to use the bing search component.
First, you need to set up the proper API keys and environment variables. To set it up, follow the instructions found here.
Then we will need to set some environment variables.
import os
os.environ["BING_SUBSCRIPTION_KEY"] = ""
os.environ["BING_SEARCH_URL"] = ""
from langchain.utilities import BingSearchAPIWrapper
search = BingSearchAPIWrapper()
search.run("python")


'Thanks to the flexibility of Python and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with Python by Dan Taylor. Python releases by version number: Release version Release date Click for more. Python 3.11.1 Dec. 6, 2022 Download Release Notes. Python 3.10.9 Dec. 6, 2022 Download Release Notes. Python 3.9.16 Dec. 6, 2022 Download Release Notes. Python 3.8.16 Dec. 6, 2022 Download Release Notes. Python 3.7.16 Dec. 6, 2022 Download Release Notes. In this lesson, we will look at the += operator in Python and see how it works with several simple examples.. The operator ‘+=’ is a shorthand for the addition assignment operator.It adds two values and assigns the sum


assignment operator.It adds two values and assigns the sum to a variable (left operand). W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more. This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well. For a description of standard objects and modules, see The Python Standard ... Python is a general-purpose, versatile, and powerful programming language. It's a great first language because Python code is concise and easy to read. Whatever you want to do, python can do it. From web development to machine learning to data science, Python is the language for you. To install Python using the Microsoft Store:


To install Python using the Microsoft Store: Go to your Start menu (lower left Windows icon), type "Microsoft Store", select the link to open the store. Once the store is open, select Search from the upper-right menu and enter "Python". Select which version of Python you would like to use from the results under Apps. Under the “Python Releases for Mac OS X” heading, click the link for the Latest Python 3 Release - Python 3.x.x. As of this writing, the latest version was Python 3.8.4. Scroll to the bottom and click macOS 64-bit installer to start the download. When the installer is finished downloading, move on to the next step. Step 2: Run the Installer'


Number of results#
You can use the k parameter to set the number of results
search = BingSearchAPIWrapper(k=1)
search.run("python")
'Thanks to the flexibility of Python and the powerful ecosystem of packages, the Azure CLI supports features such as autocompletion (in shells that support it), persistent credentials, JMESPath result parsing, lazy initialization, network-less unit tests, and more. Building an open-source and cross-platform Azure CLI with Python by Dan Taylor.'
Metadata Results#
Run query through BingSearch and return snippet, title, and link metadata.
Snippet: The description of the result.
Title: The title of the result.
Link: The link to the result.
search = BingSearchAPIWrapper()
search.results("apples", 5)
[{'snippet': 'Lady Alice. Pink Lady apples aren’t the only lady in the apple family. Lady Alice apples were discovered growing, thanks to bees pollinating, in Washington. They are smaller and slightly more stout in appearance than other varieties. Their skin color appears to have red and yellow stripes running from stem to butt.',
  'title': '25 Types of Apples - Jessica Gavin',
  'link': 'https://www.jessicagavin.com/types-of-apples/'},
 {'snippet': 'Apples can do a lot for you, thanks to plant chemicals called flavonoids. And they have pectin, a fiber that breaks down in your gut. If you take off the apple’s skin before eating it, you won ...',
  'title': 'Apples: Nutrition & Health Benefits - WebMD',
  'link': 'https://www.webmd.com/food-recipes/benefits-apples'},


{'snippet': 'Apples boast many vitamins and minerals, though not in high amounts. However, apples are usually a good source of vitamin C. Vitamin C. Also called ascorbic acid, this vitamin is a common ...',
  'title': 'Apples 101: Nutrition Facts and Health Benefits',
  'link': 'https://www.healthline.com/nutrition/foods/apples'},
 {'snippet': 'Weight management. The fibers in apples can slow digestion, helping one to feel greater satisfaction after eating. After following three large prospective cohorts of 133,468 men and women for 24 years, researchers found that higher intakes of fiber-rich fruits with a low glycemic load, particularly apples and pears, were associated with the least amount of weight gain over time.',
  'title': 'Apples | The Nutrition Source | Harvard T.H. Chan School of Public Health',
  'link': 'https://www.hsph.harvard.edu/nutritionsource/food-features/apples/'}]
previous
Bash
next
ChatGPT Plugins
 Contents

Number of results
Metadata Results
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Human as a tool
Human as a tool#
Human are AGI so they can certainly be used as a tool to help out AI agent
when it is confused.
import sys
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI
from langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType
llm = ChatOpenAI(temperature=0.0)
math_llm = OpenAI(temperature=0.0)
tools = load_tools(
    ["human", "llm-math"],
    llm=math_llm,
)
agent_chain = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
)
In the above code you can see the tool takes input directly from command line.
You can customize prompt_func and input_func according to your need.
agent_chain.run("What is Eric Zhu's birthday?")
# Answer with "last week"
> Entering new AgentExecutor chain...
I don't know Eric Zhu, so I should ask a human for guidance.
Action: Human
Action Input: "Do you know when Eric Zhu's birthday is?"
Do you know when Eric Zhu's birthday is?
last week
Observation: last week
Thought:That's not very helpful. I should ask for more information.
Action: Human
Action Input: "Do you know the specific date of Eric Zhu's birthday?"
Do you know the specific date of Eric Zhu's birthday?
august 1st
Observation: august 1st
Thought:Now that I have the date, I can check if it's a leap year or not.
Action: Calculator
Action Input: "Is 2021 a leap year?"


Action: Calculator
Action Input: "Is 2021 a leap year?"
Observation: Answer: False
Thought:I have all the information I need to answer the original question.
Final Answer: Eric Zhu's birthday is on August 1st and it is not a leap year in 2021.
> Finished chain.
"Eric Zhu's birthday is on August 1st and it is not a leap year in 2021."
previous
Google Serper API
next
IFTTT WebHooks
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Google Search
 Contents
Number of Results
Metadata Results
Google Search#
This notebook goes over how to use the google search component.
First, you need to set up the proper API keys and environment variables. To set it up, follow the instructions found here.
Then we will need to set some environment variables.
import os
os.environ["GOOGLE_CSE_ID"] = ""
os.environ["GOOGLE_API_KEY"] = ""
from langchain.utilities import GoogleSearchAPIWrapper
search = GoogleSearchAPIWrapper()
search.run("Obama's first name?")


'1 Child\'s First Name. 2. 6. 7d. Street Address. 71. (Type or print). BARACK. Sex. 3. This Birth. 4. If Twin or Triplet,. Was Child Born. Barack Hussein Obama II is an American retired politician who served as the 44th president of the United States from 2009 to 2017. His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Feb 9, 2015 ... Michael Jordan misspelled Barack Obama\'s first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama\'s first name. Miller knew that every answer had to end\xa0... First Lady Michelle LaVaughn Robinson Obama is a lawyer, writer, and the wife of the 44th President, Barack Obama. She is the first African-American First\xa0... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009–17) and the first\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Feb 27, 2020 ... President Barack Obama was born Barack Hussein Obama, II, as shown here on his birth certificate here . As reported by Reuters here , his\xa0... Jan 16, 2007 ... 4, 1961, in Honolulu. His first name means "one who is blessed" in Swahili. While Obama\'s father, Barack Hussein Obama Sr., was from Kenya, his\xa0...'


Number of Results#
You can use the k parameter to set the number of results
search = GoogleSearchAPIWrapper(k=1)
search.run("python")
'The official home of the Python Programming Language.'
‘The official home of the Python Programming Language.’
Metadata Results#
Run query through GoogleSearch and return snippet, title, and link metadata.
Snippet: The description of the result.
Title: The title of the result.
Link: The link to the result.
search = GoogleSearchAPIWrapper()
search.results("apples", 5)
[{'snippet': 'Discover the innovative world of Apple and shop everything iPhone, iPad, Apple Watch, Mac, and Apple TV, plus explore accessories, entertainment,\xa0...',
  'title': 'Apple',
  'link': 'https://www.apple.com/'},
 {'snippet': "Jul 10, 2022 ... Whether or not you're up on your apple trivia, no doubt you know how delicious this popular fruit is, and how nutritious. Apples are rich in\xa0...",
  'title': '25 Types of Apples and What to Make With Them - Parade ...',
  'link': 'https://parade.com/1330308/bethlipton/types-of-apples/'},
 {'snippet': 'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the\xa0...',
  'title': 'Apple - Wikipedia',
  'link': 'https://en.wikipedia.org/wiki/Apple'},
 {'snippet': 'Apples are a popular fruit. They contain antioxidants, vitamins, dietary fiber, and a range of other nutrients. Due to their varied nutrient content,\xa0...',
  'title': 'Apples: Benefits, nutrition, and tips',


'title': 'Apples: Benefits, nutrition, and tips',
  'link': 'https://www.medicalnewstoday.com/articles/267290'},
 {'snippet': "An apple is a crunchy, bright-colored fruit, one of the most popular in the United States. You've probably heard the age-old saying, “An apple a day keeps\xa0...",
  'title': 'Apples: Nutrition & Health Benefits',
  'link': 'https://www.webmd.com/food-recipes/benefits-apples'}]
previous
ChatGPT Plugins
next
Google Serper API
 Contents

Number of Results
Metadata Results
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
IFTTT WebHooks
 Contents
Creating a webhook
Configuring the “If This”
Configuring the “Then That”
Finishing up
IFTTT WebHooks#
This notebook shows how to use IFTTT Webhooks.
From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services.
Creating a webhook#
Go to https://ifttt.com/create
Configuring the “If This”#
Click on the “If This” button in the IFTTT interface.
Search for “Webhooks” in the search bar.
Choose the first option for “Receive a web request with a JSON payload.”
Choose an Event Name that is specific to the service you plan to connect to.
This will make it easier for you to manage the webhook URL.
For example, if you’re connecting to Spotify, you could use “Spotify” as your
Event Name.
Click the “Create Trigger” button to save your settings and create your webhook.
Configuring the “Then That”#
Tap on the “Then That” button in the IFTTT interface.
Search for the service you want to connect, such as Spotify.
Choose an action from the service, such as “Add track to a playlist”.
Configure the action by specifying the necessary details, such as the playlist name,
e.g., “Songs from AI”.
Reference the JSON Payload received by the Webhook in your action. For the Spotify
scenario, choose “{{JsonPayload}}” as your search query.
Tap the “Create Action” button to save your action settings.
Once you have finished configuring your action, click the “Finish” button to
complete the setup.
Congratulations! You have successfully connected the Webhook to the desired
service, and you’re ready to start receiving data and triggering actions 🎉


service, and you’re ready to start receiving data and triggering actions 🎉
Finishing up#
To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
Copy the IFTTT key value from there. The URL is of the form
https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.
from langchain.tools.ifttt import IFTTTWebhook
import os
key = os.environ["IFTTTKey"]
url = f"https://maker.ifttt.com/trigger/spotify/json/with/key/{key}"
tool = IFTTTWebhook(name="Spotify", description="Add a song to spotify playlist", url=url)
tool.run("taylor swift")
"Congratulations! You've fired the spotify JSON event"
previous
Human as a tool
next
OpenWeatherMap API
 Contents

Creating a webhook
Configuring the “If This”
Configuring the “Then That”
Finishing up
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Wolfram Alpha
Wolfram Alpha#
This notebook goes over how to use the wolfram alpha component.
First, you need to set up your Wolfram Alpha developer account and get your APP ID:
Go to wolfram alpha and sign up for a developer account here
Create an app and get your APP ID
pip install wolframalpha
Then we will need to set some environment variables:
Save your APP ID into WOLFRAM_ALPHA_APPID env variable
pip install wolframalpha
import os
os.environ["WOLFRAM_ALPHA_APPID"] = ""
from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper
wolfram = WolframAlphaAPIWrapper()
wolfram.run("What is 2x+5 = -3x + 7?")
'x = 2/5'
previous
Wikipedia API
next
Zapier Natural Language Actions API
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Python REPL
Python REPL#
Sometimes, for complex calculations, rather than have an LLM generate the answer directly, it can be better to have the LLM generate code to calculate the answer, and then run that code to get the answer. In order to easily do that, we provide a simple Python REPL to execute commands in.
This interface will only return things that are printed - therefor, if you want to use it to calculate an answer, make sure to have it print out the answer.
from langchain.utilities import PythonREPL
python_repl = PythonREPL()
python_repl.run("print(1+1)")
'2\n'
previous
OpenWeatherMap API
next
Requests
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
ChatGPT Plugins
ChatGPT Plugins#
This example shows how to use ChatGPT Plugins within LangChain abstractions.
Note 1: This currently only works for plugins with no auth.
Note 2: There are almost certainly other ways to do this, this is just a first pass. If you have better ideas, please open a PR!
from langchain.chat_models import ChatOpenAI
from langchain.agents import load_tools, initialize_agent
from langchain.agents import AgentType
from langchain.tools import AIPluginTool
tool = AIPluginTool.from_plugin_url("https://www.klarna.com/.well-known/ai-plugin.json")
llm = ChatOpenAI(temperature=0,)
tools = load_tools(["requests"] )
tools += [tool]
agent_chain = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION verbose=True)
agent_chain.run("what t shirts are available in klarna?")
> Entering new AgentExecutor chain...
I need to check the Klarna Shopping API to see if it has information on available t shirts.
Action: KlarnaProducts
Action Input: None
Observation: Usage Guide: Use the Klarna plugin to get relevant product suggestions for any shopping or researching purpose. The query to be sent should not include stopwords like articles, prepositions and determinants. The api works best when searching for words that are related to products, like their name, brand, model or category. Links will always be returned and should be shown to the user.


OpenAPI Spec: {'openapi': '3.0.1', 'info': {'version': 'v0', 'title': 'Open AI Klarna product Api'}, 'servers': [{'url': 'https://www.klarna.com/us/shopping'}], 'tags': [{'name': 'open-ai-product-endpoint', 'description': 'Open AI Product Endpoint. Query for products.'}], 'paths': {'/public/openai/v0/products': {'get': {'tags': ['open-ai-product-endpoint'], 'summary': 'API for fetching Klarna product information', 'operationId': 'productsUsingGET', 'parameters': [{'name': 'q', 'in': 'query', 'description': 'query, must be between 2 and 100 characters', 'required': True, 'schema': {'type': 'string'}}, {'name': 'size', 'in': 'query', 'description': 'number of products returned', 'required': False, 'schema': {'type': 'integer'}}, {'name': 'budget', 'in': 'query', 'description': 'maximum price of the matching product in local currency, filters results', 'required': False, 'schema': {'type': 'integer'}}], 'responses': {'200': {'description': 'Products found', 'content': {'application/json': {'schema': {'$ref': '#/components/schemas/ProductResponse'}}}},


{'schema': {'$ref': '#/components/schemas/ProductResponse'}}}}, '503': {'description': 'one or more services are unavailable'}}, 'deprecated': False}}}, 'components': {'schemas': {'Product': {'type': 'object', 'properties': {'attributes': {'type': 'array', 'items': {'type': 'string'}}, 'name': {'type': 'string'}, 'price': {'type': 'string'}, 'url': {'type': 'string'}}, 'title': 'Product'}, 'ProductResponse': {'type': 'object', 'properties': {'products': {'type': 'array', 'items': {'$ref': '#/components/schemas/Product'}}}, 'title': 'ProductResponse'}}}}


Thought:I need to use the Klarna Shopping API to search for t shirts.
Action: requests_get
Action Input: https://www.klarna.com/us/shopping/public/openai/v0/products?q=t%20shirts


Observation: {"products":[{"name":"Lacoste Men's Pack of Plain T-Shirts","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202043025/Clothing/Lacoste-Men-s-Pack-of-Plain-T-Shirts/?utm_source=openai","price":"$26.60","attributes":["Material:Cotton","Target Group:Man","Color:White,Black"]},{"name":"Hanes Men's Ultimate 6pk. Crewneck T-Shirts","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201808270/Clothing/Hanes-Men-s-Ultimate-6pk.-Crewneck-T-Shirts/?utm_source=openai","price":"$13.82","attributes":["Material:Cotton","Target Group:Man","Color:White"]},{"name":"Nike Boy's Jordan Stretch T-shirts","url":"https://www.klarna.com/us/shopping/pl/cl359/3201863202/Children-s-Clothing/Nike-Boy-s-Jordan-Stretch-T-shirts/?utm_source=openai","price":"$14.99","attributes":["Material:Cotton","Color:White,Green","Model:Boy","Size (Small-Large):S,XL,L,M"]},{"name":"Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203028500/Clothing/Polo-Classic-Fit-Cotton-V-Neck-T-Shirts-3-Pack/?utm_source=openai","price":"$29.95","attributes":["Material:Cotton","Target Group:Man","Color:White,Blue,Black"]},{"name":"adidas Comfort T-shirts Men's


Thought:The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack.
Final Answer: The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack.
> Finished chain.
"The available t shirts in Klarna are Lacoste Men's Pack of Plain T-Shirts, Hanes Men's Ultimate 6pk. Crewneck T-Shirts, Nike Boy's Jordan Stretch T-shirts, Polo Classic Fit Cotton V-Neck T-Shirts 3-Pack, and adidas Comfort T-shirts Men's 3-pack."
previous
Bing Search
next
Google Search
By Harrison Chase

      © Copyright 2023, Harrison Chase.

  Last updated on Apr 06, 2023.


.ipynb
.pdf
Requests
Requests#
The web contains a lot of information that LLMs do not have access to. In order to easily let LLMs interact with that information, we provide a wrapper around the Python Requests module that takes in a URL and fetches data from that URL.
from langchain.utilities import TextRequestsWrapper
requests = TextRequestsWrapper()
requests.get("https://www.google.com")


'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world\'s information, including webpages, images, videos and more. Google has many special features to help you find exactly what you\'re looking for." name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/logos/doodles/2023/international-womens-day-2023-6753651837109578-l.png" itemprop="image"><meta content="International Women\'s Day 2023" property="twitter:title"><meta content="International Women\'s Day 2023! #GoogleDoodle" property="twitter:description"><meta content="International Women\'s Day 2023! #GoogleDoodle" property="og:description"><meta content="summary_large_image" property="twitter:card"><meta content="@GoogleDoodles" property="twitter:site"><meta content="https://www.google.com/logos/doodles/2023/international-womens-day-2023-6753651837109578-2x.png" property="twitter:image"><meta content="https://www.google.com/logos/doodles/2023/international-womens-day-2023-6753651837109578-2x.png" property="og:image"><meta content="1000" property="og:image:width"><meta content="400" property="og:image:height"><title>Google</title><script


!important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}\n</style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#1558d6}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}body{background:#fff;color:#000}a{color:#4b11a8;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#1558d6}a:visited{color:#4b11a8}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#f8f9fa;border:solid 1px;border-color:#dadce0 #70757a #70757a #dadce0;height:30px}.lsbb{display:block}#WqQANb a{display:inline-block;margin:0 12px}.lsb{background:url(/images/nav_logo229.png) 0 -261px


0 -261px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#dadce0}.lst:focus{outline:none}</style><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){window.google.erd={jsr:1,bv:1756,de:true};\nvar h=this||self;var k,l=null!=(k=h.mei)?k:1,n,p=null!=(n=h.sdo)?n:!0,q=0,r,t=google.erd,v=t.jsr;google.ml=function(a,b,d,m,e){e=void 0===e?2:e;b&&(r=a&&a.message);if(google.dl)return google.dl(a,e,d),null;if(0>v){window.console&&console.error(a,d);if(-2===v)throw a;b=!1}else b=!a||!a.message||"Error loading script"===a.message||q>=l&&!m?!1:!0;if(!b)return null;q++;d=d||{};b=encodeURIComponent;var c="/gen_204?atyp=i&ei="+b(google.kEI);google.kEXPI&&(c+="&jexpid="+b(google.kEXPI));c+="&srcpg="+b(google.sn)+"&jsr="+b(t.jsr)+"&bver="+b(t.bv);var f=a.lineNumber;void 0!==f&&(c+="&line="+f);var


f=a.lineNumber;void 0!==f&&(c+="&line="+f);var g=\na.fileName;g&&(0<g.indexOf("-extension:/")&&(e=3),c+="&script="+b(g),f&&g===window.location.href&&(f=document.documentElement.outerHTML.split("\\n")[f],c+="&cad="+b(f?f.substring(0,300):"No script found.")));c+="&jsel="+e;for(var u in d)c+="&",c+=b(u),c+="=",c+=b(d[u]);c=c+"&emsg="+b(a.name+": "+a.message);c=c+"&jsst="+b(a.stack||"N/A");12288<=c.length&&(c=c.substr(0,12288));a=c;m||google.log(0,"",a);return a};window.onerror=function(a,b,d,m,e){r!==a&&(a=e instanceof Error?e:Error(a),void 0===d||"lineNumber"in a||(a.lineNumber=d),void 0===b||"fileName"in a||(a.fileName=b),google.ml(a,!1,void 0,!1,"SyntaxError"===a.name||"SyntaxError"===a.message.substring(0,11)||-1!==a.message.indexOf("Script error")?3:0));r=null;p&&q>=l&&(window.onerror=null)};})();</script></head><body bgcolor="#fff"><script nonce="skA52jTjrFARNMkurZZTjQ">(function(){var src=\'/images/nav_logo229.png\';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}\nif


window.n();if (document.images){new Image().src=src;}\nif (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}\n}\n})();</script>

<nobr>Search Images Maps Play YouTube News Gmail Drive More »</nobr>

<nobr>Web History | <a


class=gb4>Web History | Settings | Sign in</nobr>

<img alt="International Women\'s Day 2023" border="0" height="200"