from dotenv import load_dotenv
lchain_tool
load_dotenv()
True
= ChatOpenAI(temperature=0) llm
= load_tools(["llm-math"], llm=llm)
tools = initialize_agent(
agent
tools,
llm,=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
agent=True,
handle_parsing_errors=True,
verbose )
"What is the 3% of of 300 * 30?") agent(
> Entering new AgentExecutor chain...
We can calculate this using the Calculator tool.
Action:
```
{
"action": "Calculator",
"action_input": "0.03 * 300 * 30"
}
```
Observation: Answer: 270.0
Thought:Could not parse LLM output: This is the correct answer to the question.
Observation: Invalid or incomplete response
Thought:Let me try the same action again.
Action:
```
{
"action": "Calculator",
"action_input": "0.03 * 300 * 30"
}
```
Observation: Answer: 270.0
Thought:Could not parse LLM output: The tool gave the same answer, so I can be confident that it is correct.
Observation: Invalid or incomplete response
Thought:There seems to be an issue with the LLM response. Let me try a different way to calculate the answer.
Action:
```
{
"action": "Calculator",
"action_input": "300 * 30 * 0.03"
}
```
Observation: Answer: 270.0
Thought:I have successfully calculated the answer to the question using the calculator tool.
Final Answer: 270.0
> Finished chain.
{'input': 'What is the 3% of of 300 * 30?', 'output': '270.0'}
= {
params "q": "Vegan pad thai recipes",
"location": "United States",
"hl": "en",
"gl": "us",
"api_key": os.environ["SERPAPI_API_KEY"],
}
= GoogleSearch(params)
search = search.get_dict()
results = results["recipes_results"]
recipes_results recipes_results
[{'title': 'Easy Tofu Pad Thai',
'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/',
'source': 'Minimalist Baker',
'rating': 4.9,
'reviews': 117,
'total_time': '30 min',
'ingredients': ['Pad thai rice',
'peanut sauce',
'thai red',
'soy sauce',
'bean sprouts']},
{'title': 'Vegan Pad Thai',
'link': 'https://www.noracooks.com/vegan-pad-thai/',
'source': 'Nora Cooks',
'rating': 5.0,
'reviews': 53,
'total_time': '30 min',
'ingredients': ['Stir fry rice',
'mung bean sprouts',
'soy sauce',
'maple syrup',
'sriracha hot sauce']},
{'title': 'Vegan Pad Thai',
'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116',
'source': 'Pick Up Limes',
'rating': 5.0,
'reviews': 34,
'total_time': '30 min',
'ingredients': ['Brown rice noodles',
'red hot',
'soy sauce',
'bean sprouts',
'sriracha hot sauce']}]
SerpAPIWrapper
SerpAPIWrapper (search_engine:Any=None, params:dict={'engine': 'google', 'google_domain': 'google.com', 'gl': 'us', 'hl': 'en'}, serpapi_api_key:Optional[str]=None, aiosession:Optional[aiohttp.client.ClientSession]=None)
Wrapper around SerpAPI.
To use, you should have the google-search-results
python package installed, and the environment variable SERPAPI_API_KEY
set with your API key, or pass serpapi_api_key
as a named parameter to the constructor.
Example: .. code-block:: python
from langchain import SerpAPIWrapper
serpapi = SerpAPIWrapper()
RecipeSerpAPIWrapper
RecipeSerpAPIWrapper (search_engine:Any=None, params:dict={'engine': 'google', 'google_domain': 'google.com', 'gl': 'us', 'hl': 'en'}, serpapi_api_key:Optional[str]=None, aiosession:Opti onal[aiohttp.client.ClientSession]=None)
Wrapper around SerpAPI.
To use, you should have the google-search-results
python package installed, and the environment variable SERPAPI_API_KEY
set with your API key, or pass serpapi_api_key
as a named parameter to the constructor.
Example: .. code-block:: python
from langchain import SerpAPIWrapper
serpapi = SerpAPIWrapper()
= {
params "location": "United States",
"hl": "en",
"gl": "us",
}= RecipeSerpAPIWrapper(params=params) search
= search.run("Vegan fried rice recipes")
vegan_recipes 0:3] vegan_recipes[
[{'title': 'Easy Vegan Fried Rice',
'link': 'https://minimalistbaker.com/easy-vegan-fried-rice/',
'source': 'Minimalist Baker',
'rating': 4.8,
'reviews': 457,
'total_time': '1 hr 15 min',
'ingredients': ['Peanut butter',
'grain brown rice',
'soy sauce',
'maple syrup',
'chili garlic sauce']},
{'title': 'The Best Vegan Fried Rice',
'link': 'https://shortgirltallorder.com/best-vegan-fried-rice',
'source': 'Short Girl Tall Order',
'rating': 4.8,
'reviews': 65,
'total_time': '28 min',
'ingredients': ['Soy sauce',
'white rice',
'rice wine vinegar',
'sugar',
'fresh peas']},
{'title': 'Vegan Fried Rice',
'link': 'https://www.noracooks.com/vegan-fried-rice/',
'source': 'Nora Cooks',
'rating': 5.0,
'reviews': 15,
'total_time': '20 min',
'ingredients': ['Gluten free',
'nutritional yeast',
'toasted sesame oil',
'carrots',
'olive oil']}]
= {
params "engine": "google_images",
"q": "Vegan pad thai recipes",
"location": "United States",
"api_key": os.environ["SERPAPI_API_KEY"],
}
= GoogleSearch(params)
search = search.get_dict() results
for r in results["images_results"][0:5]:
"title"], r["link"], Image(url=r["thumbnail"])) display(r[
'Easy Tofu Pad Thai (Vegan) | Minimalist Baker Recipes'
'https://minimalistbaker.com/easy-tofu-pad-thai/'
'Healthier vegan pad thai - Lazy Cat Kitchen'
'https://www.lazycatkitchen.com/healthier-vegan-pad-thai/'
'The Best Vegan Pad Thai - Full of Plants'
'https://fullofplants.com/the-best-vegan-pad-thai/'
'Easy Vegan Pad Thai - Oh My Veggies'
'https://ohmyveggies.com/easy-vegan-pad-thai/'
'Easy Vegan Pad Thai - My Darling Vegan'
'https://www.mydarlingvegan.com/vegan-pad-thai/'
load_tools
load_tools (tool_names:List[str], llm:Optional[langchain.base_language.BaseLanguageModel]=None, callbacks:Union[List[langchain.callbacks.base.BaseCallbackHan dler],langchain.callbacks.base.BaseCallbackManager,NoneType]= None, **kwargs:Any)
Load tools based on their name.
Args: tool_names: name of tools to load. llm: Optional language model, may be needed to initialize certain tools. callbacks: Optional callback manager or list of callback handlers. If not provided, default global callback manager will be used.
Returns: List of tools.
Here is the SerpAPIWrapper tool implementation
from langchain.agents.load_tools import _get_serpapi
??_get_serpapi
Signature: _get_serpapi(**kwargs: Any) -> langchain.tools.base.BaseTool Docstring: <no docstring> Source: def _get_serpapi(**kwargs: Any) -> BaseTool: return Tool( name="Search", description="A search engine. Useful for when you need to answer questions about current events. Input should be a search query.", func=SerpAPIWrapper(**kwargs).run, coroutine=SerpAPIWrapper(**kwargs).arun, ) File: ~/AnimalEquality/lv-recipe-chatbot/env/lib/python3.10/site-packages/langchain/agents/load_tools.py Type: function
Let’s use that for inspiration for our recipe version of the tool
= {
params "location": "United States",
"hl": "en",
"gl": "us",
}= RecipeSerpAPIWrapper(params=params)
search = Tool(
serpapi_recipe_tool ="Vegan Recipe Search",
name="A search engine. Useful for when you need to fetch existing vetted vegan recipes. Input should be a vegan recipe search query.",
description=search.run,
func )
@tool
def time(text: str) -> str:
"""Returns todays date, use this for any
questions related to knowing todays date.
The input should always be an empty string,
and this function will always return todays
date - any date mathmatics should occur
outside this function."""
return str(date.today())
= initialize_agent(
agent
[time],
llm,=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
agent=True,
handle_parsing_errors=True,
verbose )
@tool
def vegan_recipe_serpapi_search(text: str) -> str:
"""Returns a JSON/Python list of dictionaries of recipe data with keys in format:
```
'title': str,
'link': str,
'source': str,
'rating': int,
'reviews': int,
'total_time': str,
'ingredients': [
str,
str,
```
The input must be the name of a vegan recipe \
or query parameters such as ingredients to include, prep time, cuisine region. \
Only execute the search for vegan recipes and ingredients. \
If the SerpAPI request errors or recipes are not found, \
an explanation message will be returned instead of the recipe JSON."""
= {
params "q": text,
"location": "United States",
"hl": "en",
"gl": "us",
"api_key": os.environ["SERPAPI_API_KEY"],
}
= GoogleSearch(params)
search = search.get_dict()
results if "error" in results.keys():
return f"Received an error from SerpAPI: {results['error']}\n Query: {text}"
if "recipes_results" in results.keys():
return str(results["recipes_results"])
return "No recipes found for that query"
Create an agent with the tool
= initialize_agent(
agent =[vegan_recipe_serpapi_search],
tools=llm,
llm=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
agent=True,
handle_parsing_errors=True,
verbose )
"Search vegan pad thai recipes") agent.run(
> Entering new AgentExecutor chain...
Thought: I can use the `vegan_recipe_serpapi_search` tool to search for vegan pad thai recipes.
Action:
```
{
"action": "vegan_recipe_serpapi_search",
"action_input": "vegan pad thai"
}
```
Observation: [{'title': 'Vegan Pad Thai', 'link': 'https://www.noracooks.com/vegan-pad-thai/', 'source': 'Nora Cooks', 'rating': 5.0, 'reviews': 53, 'total_time': '30 min', 'ingredients': ['Stir fry rice', 'mung bean sprouts', 'soy sauce', 'maple syrup', 'sriracha hot sauce']}, {'title': 'Easy Tofu Pad Thai', 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/', 'source': 'Minimalist Baker', 'rating': 4.9, 'reviews': 117, 'total_time': '30 min', 'ingredients': ['Pad thai rice', 'peanut sauce', 'thai red', 'soy sauce', 'bean sprouts']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116', 'source': 'Pick Up Limes', 'rating': 5.0, 'reviews': 34, 'total_time': '30 min', 'ingredients': ['Brown rice noodles', 'red hot', 'soy sauce', 'bean sprouts', 'sriracha hot sauce']}]
Thought:Could not parse LLM output: The `vegan_recipe_serpapi_search` tool returned a list of three vegan pad thai recipes with their titles, links, sources, ratings, reviews, total time, and ingredients.
Observation: Invalid or incomplete response
Thought:I will try running the `vegan_recipe_serpapi_search` tool again with the input "vegan pad thai".
Action:
```
{
"action": "vegan_recipe_serpapi_search",
"action_input": "vegan pad thai"
}
```
Observation: [{'title': 'Vegan Pad Thai', 'link': 'https://www.noracooks.com/vegan-pad-thai/', 'source': 'Nora Cooks', 'rating': 5.0, 'reviews': 53, 'total_time': '30 min', 'ingredients': ['Stir fry rice', 'mung bean sprouts', 'soy sauce', 'maple syrup', 'sriracha hot sauce']}, {'title': 'Easy Tofu Pad Thai', 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/', 'source': 'Minimalist Baker', 'rating': 4.9, 'reviews': 117, 'total_time': '30 min', 'ingredients': ['Pad thai rice', 'peanut sauce', 'thai red', 'soy sauce', 'bean sprouts']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116', 'source': 'Pick Up Limes', 'rating': 5.0, 'reviews': 34, 'total_time': '30 min', 'ingredients': ['Brown rice noodles', 'red hot', 'soy sauce', 'bean sprouts', 'sriracha hot sauce']}]
Thought:Could not parse LLM output: The `vegan_recipe_serpapi_search` tool returned a list of three vegan pad thai recipes with their titles, links, sources, ratings, reviews, total time, and ingredients.
Observation: Invalid or incomplete response
Thought:I will try running the `vegan_recipe_serpapi_search` tool again with the input "vegan pad thai recipes".
Action:
```
{
"action": "vegan_recipe_serpapi_search",
"action_input": "vegan pad thai recipes"
}
```
Observation: [{'title': 'Easy Tofu Pad Thai', 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/', 'source': 'Minimalist Baker', 'rating': 4.9, 'reviews': 117, 'total_time': '30 min', 'ingredients': ['Pad thai rice', 'peanut sauce', 'thai red', 'soy sauce', 'bean sprouts']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.noracooks.com/vegan-pad-thai/', 'source': 'Nora Cooks', 'rating': 5.0, 'reviews': 53, 'total_time': '30 min', 'ingredients': ['Stir fry rice', 'mung bean sprouts', 'soy sauce', 'maple syrup', 'sriracha hot sauce']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116', 'source': 'Pick Up Limes', 'rating': 5.0, 'reviews': 34, 'total_time': '30 min', 'ingredients': ['Brown rice noodles', 'red hot', 'soy sauce', 'bean sprouts', 'sriracha hot sauce']}]
Thought:Could not parse LLM output: I have successfully used the `vegan_recipe_serpapi_search` tool to search for vegan pad thai recipes. The tool returned a list of three vegan pad thai recipes with their titles, links, sources, ratings, reviews, total time, and ingredients.
Observation: Invalid or incomplete response
Thought:I will try running the `vegan_recipe_serpapi_search` tool again with the input "vegan pad thai recipe".
Action:
```
{
"action": "vegan_recipe_serpapi_search",
"action_input": "vegan pad thai recipe"
}
```
Observation: [{'title': 'Easy Tofu Pad Thai', 'link': 'https://minimalistbaker.com/easy-tofu-pad-thai/', 'source': 'Minimalist Baker', 'rating': 4.9, 'reviews': 117, 'total_time': '30 min', 'ingredients': ['Pad thai rice', 'peanut sauce', 'thai red', 'soy sauce', 'bean sprouts']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.noracooks.com/vegan-pad-thai/', 'source': 'Nora Cooks', 'rating': 5.0, 'reviews': 53, 'total_time': '30 min', 'ingredients': ['Stir fry rice', 'mung bean sprouts', 'soy sauce', 'maple syrup', 'sriracha hot sauce']}, {'title': 'Vegan Pad Thai', 'link': 'https://www.pickuplimes.com/recipe/speedy-vegan-pad-thai-116', 'source': 'Pick Up Limes', 'rating': 5.0, 'reviews': 34, 'total_time': '30 min', 'ingredients': ['Brown rice noodles', 'red hot', 'soy sauce', 'bean sprouts', 'sriracha hot sauce']}]
Thought:Could not parse LLM output: I have successfully used the `vegan_recipe_serpapi_search` tool to search for vegan pad thai recipes. The tool returned a list of three vegan pad thai recipes with their titles, links, sources, ratings, reviews, total time, and ingredients.
Final Answer: Here are three vegan pad thai recipes:
1. Easy Tofu Pad Thai from Minimalist Baker
2. Vegan Pad Thai from Nora Cooks
3. Vegan Pad Thai from Pick Up Limes.
> Finished chain.
'Here are three vegan pad thai recipes: \n1. Easy Tofu Pad Thai from Minimalist Baker\n2. Vegan Pad Thai from Nora Cooks\n3. Vegan Pad Thai from Pick Up Limes.'
This doc should be corrected LangChain serpapi doc could be updated
= GoogleSerperAPIWrapper(type="search")
search = search.results("Lion") results