Agents use case

This commit is contained in:
Lance Martin
2023-08-01 17:01:05 -07:00
parent 95cf7de112
commit dc10f16008
4 changed files with 692 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

View File

@@ -0,0 +1,692 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "842dd272",
"metadata": {},
"source": [
"# Agents\n",
"\n",
"\n",
"## Use case \n",
"\n",
"---\n",
"\n",
"LLM-based agents are powerful problem solvers.\n",
"\n",
"The [primary LLM agent components](https://lilianweng.github.io/posts/2023-06-23-agent/) include at least 3 things:\n",
"\n",
"* `Planning`: The ability to break down tasks into smaller sub-goals\n",
"* `Memory`: The ability to retain and recall information\n",
"* `Tools`: The ability to get information from external sources (e.g., APIs)\n",
"\n",
"![Image description](../../../docs_skeleton/static/img/agents_use_case_1.png)\n",
"\n",
"\n",
"## Overview \n",
"\n",
"--- \n",
" \n",
"**Planning**\n",
" \n",
"* `Prompt`: Can given the LLM personality, context, or strategies for learninng\n",
"* `Agent` Responsible for deciding what step to take next using LLM and the `Prompt`\n",
"\n",
"**Memory**\n",
"\n",
"* This can be short or long-term, allowing the agent to persist information.\n",
"\n",
"**Tools**\n",
"\n",
"* Tools are functions that an agent can call.\n",
"\n",
"\n",
"## Quickstart \n",
"\n",
"--- "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a31f0cd",
"metadata": {},
"outputs": [],
"source": [
"! pip install openai \n",
"! pip install langchain\n",
"! pip install google-search-results\n",
"\n",
"import os\n",
"os.environ[\"OPENAI_API_KEY\"] = \"your-api-key\"\n",
"# Optional\n",
"os.environ[\"SERPAPI_API_KEY\"] = \"your-api-key\""
]
},
{
"cell_type": "markdown",
"id": "639d41ad",
"metadata": {},
"source": [
"`Tool`\n",
"\n",
"LangChain has [many tools](https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/agents/load_tools.py) for Agents that we can load easily."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0303a7a1",
"metadata": {},
"outputs": [],
"source": [
"# Tool\n",
"from langchain.agents import load_tools\n",
"tools = load_tools([\"serpapi\", \"llm-math\"], llm=llm)"
]
},
{
"cell_type": "markdown",
"id": "431ba30b",
"metadata": {},
"source": [
"`Agent`\n",
"\n",
"LangChain has [many agents](https://python.langchain.com/docs/modules/agents/agent_types/).\n",
"\n",
"The [`OPENAI_FUNCTIONS` agent](https://python.langchain.com/docs/modules/agents/agent_types/openai_functions_agent) is a good one to start with.\n",
"\n",
"OpenAI models have been fine-tuned to recognize when function should be called.\n"
]
},
{
"cell_type": "code",
"execution_count": 86,
"id": "e5df3414",
"metadata": {},
"outputs": [],
"source": [
"# Prompt\n",
"from langchain.schema import SystemMessage\n",
"from langchain.agents import OpenAIFunctionsAgent\n",
"system_message = SystemMessage(content=\"You are a search assistant.\")\n",
"prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)\n",
"\n",
"# Agent\n",
"search_agent = OpenAIFunctionsAgent(llm=llm, tools=search_tool, prompt=prompt)\n",
"agent_executor = AgentExecutor(agent=search_agent, tools=search_tool, verbose=False)"
]
},
{
"cell_type": "code",
"execution_count": 87,
"id": "d636395f",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'The current population of Canada is 38,808,843 as of Tuesday, August 1, 2023, based on Worldometer elaboration of the latest United Nations data 1. Canada 2023\\xa0... Mar 22, 2023 ... Record-high population growth in the year 2022. Canada\\'s population was estimated at 39,566,248 on January 1, 2023, after a record population\\xa0... Jun 19, 2023 ... As of June 16, 2023, there are now 40 million Canadians! This is a historic milestone for Canada and certainly cause for celebration. It is also\\xa0... Jun 28, 2023 ... Canada\\'s population was estimated at 39,858,480 on April 1, 2023, an increase of 292,232 people (+0.7%) from January 1, 2023. This was the\\xa0... Jun 16, 2023 ... Canada\\'s population clock (real-time model) ... Consult \"Differences between Statistics Canada\\'s census counts and ... (April 1, 2023). The current population of Canada in 2023 is 38,781,291, a 0.85% increase from 2022. The population of Canada in 2022 was 38,454,327, a 0.78% increase from 2021. Jun 28, 2023 ... Index to the latest information from the Census of Population. ... 2023. Census in Brief: EnglishFrench bilingualism in Canada: Recent\\xa0... Statistics Canada conducts a country-wide census that collects demographic data every five ... Population pyramid of Canada in 2023. Jul 1, 2023 ... The U.S. Census Bureau\\'s International Database estimates the July 1, 2023, population of Canada at 38.5M (4.2 people per sq. km) and the\\xa0... Canada ranks 37th by population among countries of the world, comprising about 0.5% of the world\\'s total, with over 40.0 million Canadians as of 2023.'"
]
},
"execution_count": 87,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Run\n",
"agent_executor.run(\"How many people live in canada as of 2023?\")"
]
},
{
"cell_type": "markdown",
"id": "27842380",
"metadata": {},
"source": [
"Great, we have created a simple search agent with a tool!\n",
"\n",
"Looking at the LangSmith [trace](https://smith.langchain.com/public/b7c627dc-cf29-47ef-bc1f-9e4eddeb6c2b/r) we can see exactly what is going on: ChatOpenAI creates a function call to the search tool."
]
},
{
"cell_type": "markdown",
"id": "f4eb26ee",
"metadata": {},
"source": [
"![Image description](../../../docs_skeleton/static/img/agents_use_case_trace_1.png)"
]
},
{
"cell_type": "markdown",
"id": "0b93c7d0",
"metadata": {},
"source": [
"## Memory \n",
"\n",
"--- \n",
"\n",
"### Short-term memory\n",
"\n",
"Of course, `memory` is needed to enable conversation / persistence of information.\n",
"\n",
"LangChain has many options for [short-term memory](https://python.langchain.com/docs/modules/memory/types/), which are frequently used in [chat](https://python.langchain.com/docs/modules/memory/adding_memory.html). They can be [employed with agents](https://python.langchain.com/docs/modules/memory/agent_with_memory) too.\n",
"\n",
"`ConversationBufferMemory` is a popular choice for short-term memory.\n",
"\n",
"We set `MEMORY_KEY`, which can be referenced by the prompt later."
]
},
{
"cell_type": "code",
"execution_count": 88,
"id": "207cdfce",
"metadata": {},
"outputs": [],
"source": [
"from langchain.memory import ConversationBufferMemory\n",
"MEMORY_KEY = \"chat_history\"\n",
"memory = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)"
]
},
{
"cell_type": "markdown",
"id": "a45ae0bc",
"metadata": {},
"source": [
"Now, let's add memory to our agent."
]
},
{
"cell_type": "code",
"execution_count": 93,
"id": "1d291015",
"metadata": {},
"outputs": [],
"source": [
"# Prompt w/ placeholder for memory\n",
"from langchain.schema import SystemMessage\n",
"from langchain.agents import OpenAIFunctionsAgent\n",
"system_message = SystemMessage(content=\"You are a search assistant.\")\n",
"prompt = OpenAIFunctionsAgent.create_prompt(\n",
" system_message=system_message,\n",
" extra_prompt_messages=[MessagesPlaceholder(variable_name=MEMORY_KEY)]\n",
")\n",
"\n",
"# Agent\n",
"search_agent_memory = OpenAIFunctionsAgent(llm=llm, tools=search_tool, prompt=prompt, memory=memory)\n",
"agent_executor_memory = AgentExecutor(agent=search_agent_memory, tools=search_tool, memory=memory, verbose=False)"
]
},
{
"cell_type": "code",
"execution_count": 94,
"id": "b4b2249a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"Jun 19, 2023 ... As of June 16, 2023, there are now 40 million Canadians! This is a historic milestone for Canada and certainly cause for celebration. It is also\\xa0... Jun 28, 2023 ... Canada's population was estimated at 39,858,480 on April 1, 2023, an increase of 292,232 people (+0.7%) from January 1, 2023. This was the\\xa0... The current population of Canada is 38,808,843 as of Tuesday, August 1, 2023, based on Worldometer elaboration of the latest United Nations data 1. Canada 2023\\xa0... Mar 22, 2023 ... Record-high population growth in the year 2022. Canada's population was estimated at 39,566,248 on January 1, 2023, after a record population\\xa0... Jun 28, 2023 ... Index to the latest information from the Census of Population. ... 2023. Census in Brief: EnglishFrench bilingualism in Canada: Recent\\xa0... Jul 20, 2023 ... During the 1960's, aerial surveys identified the Ungava Peninsula in northern Québec as the primary nesting area for Atlantic flyway Canada\\xa0... The current population of Canada in 2023 is 38,781,291, a 0.85% increase from 2022. The population of Canada in 2022 was 38,454,327, a 0.78% increase from 2021. Jul 1, 2023 ... The U.S. Census Bureau's International Database estimates the July 1, 2023, population of Canada at 38.5M (4.2 people per sq. km) and the\\xa0... Statistics Canada conducts a country-wide census that collects demographic data every five ... Population pyramid of Canada in 2023. Aug 18, 2022 ... CAGO IPM predicted 2023 median number of breeding pairs was 180,500 (95% CI. = 124,500249,500; Figure 1, Table 2). Input data included in the\\xa0...\""
]
},
"execution_count": 94,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_executor_memory.run(\"How many people live in canada as of 2023?\")"
]
},
{
"cell_type": "code",
"execution_count": 96,
"id": "4d31b0cf",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"Its four largest provinces by area (Ontario, Quebec, British Columbia, and Alberta) are also its most populous; together they account for 86.5% of the country's\\xa0... Only three of Canada's ten provinces have populations of fewer than 1 million people. Ontario is the largest, boasting a population of more than 15 million\\xa0... Ontario and Quebec have always been the two biggest provinces in Canada, with together over 60% of the population at any given time. The population of the West\\xa0... Nov 22, 2022 ... Single population in Canada in 2022, by province ; Manitoba, 681,723 ; Saskatchewan, 566,419 ; Nova Scotia, 450,742 ; New Brunswick, 350,480. A population centre, in the context of a Canadian census, is a populated place, or a cluster of interrelated populated places, which meets the demographic\\xa0... Feb 8, 2017 ... In 2016, 6.6% of Canadians lived in the Atlantic provinces, with Nova Scotia (2.6%) accounting for the largest share, followed by New\\xa0... Jul 16, 2023 ... Quebec, eastern province of Canada. Constituting nearly one-sixth of Canada's total land area, Quebec is the largest of Canada's 10\\xa0... 14 records ... Estimated number of persons by quarter of a year and by year, Canada, provinces and territories. Jul 25, 2018 ... Many First Nations people lived in Ontario and the western provinces, but they made up the largest shares of the total population of the\\xa0... Feb 27, 2019 ... Sources: Statistics Canada, Census of Population, 1996, 2006 and 2016. Pie chart for Atlantic provinces: Longest history. The majority of the\\xa0...\""
]
},
"execution_count": 96,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_executor_memory.run(\"What is the population of its largest provence?\")"
]
},
{
"cell_type": "markdown",
"id": "3606c32a",
"metadata": {},
"source": [
"Looking at the [trace](https://smith.langchain.com/public/537b4a4b-35fa-409e-9a5b-d7f40e3b9772/r), we can see that the chat history is persisted."
]
},
{
"cell_type": "markdown",
"id": "384e37f8",
"metadata": {},
"source": [
"### Long-term memory \n",
"\n",
"Vectorstores are great options for long-term memory."
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "1489746c",
"metadata": {},
"outputs": [],
"source": [
"import faiss\n",
"from langchain.vectorstores import FAISS\n",
"from langchain.docstore import InMemoryDocstore\n",
"from langchain.embeddings import OpenAIEmbeddings\n",
"embedding_size = 1536\n",
"embeddings_model = OpenAIEmbeddings()\n",
"index = faiss.IndexFlatL2(embedding_size)\n",
"vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})"
]
},
{
"cell_type": "markdown",
"id": "9668ef5d",
"metadata": {},
"source": [
"### Going deeper \n",
"\n",
"* Explore projects using long-term memory, such as [autonomous agents](https://python.langchain.com/docs/use_cases/autonomous_agents/)."
]
},
{
"cell_type": "markdown",
"id": "43fe2bb3",
"metadata": {},
"source": [
"## Tools \n",
"\n",
"--- \n",
"\n",
"As mentioned above, LangChain has [many tools](https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/agents/load_tools.py) for Agents that we can load easily.\n",
"\n",
"We can also define [custom tools](https://python.langchain.com/docs/modules/agents/tools/custom_tools). For example, here is a search tool.\n",
"\n",
"The `Tool` dataclass wraps functions that accept a single string input and returns a string output.\n",
"\n",
"`return_direct` determines whether to return the tool's output directly. \n",
"\n",
"Setting this to `True` means that after the tool is called, the `AgentExecutor` will stop looping."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7357e496",
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import tool\n",
"from langchain.utilities import GoogleSearchAPIWrapper\n",
"search = GoogleSearchAPIWrapper()\n",
"search_tool = [\n",
" Tool(\n",
" name=\"Search\",\n",
" func=search.run,\n",
" description=\"useful for when you need to answer questions about current events\",\n",
" return_direct=True,\n",
" )\n",
"]"
]
},
{
"cell_type": "markdown",
"id": "c6ef5bfa",
"metadata": {},
"source": [
"To make it easier to define custom tools, a @tool decorator is provided. \n",
"\n",
"This decorator can be used to quickly create a Tool from a simple function."
]
},
{
"cell_type": "code",
"execution_count": 104,
"id": "b6308c69",
"metadata": {},
"outputs": [],
"source": [
"# Tool\n",
"@tool\n",
"def get_word_length(word: str) -> int:\n",
" \"\"\"Returns the length of a word.\"\"\"\n",
" return len(word)\n",
"word_length_tool = [get_word_length]"
]
},
{
"cell_type": "markdown",
"id": "83c104d7",
"metadata": {},
"source": [
"### Going deeper\n",
"\n",
"**Toolkits**\n",
"\n",
"Toolkits are groups of tools needed to accomplish specific objectives.\n",
"\n",
"[Here](https://python.langchain.com/docs/integrations/toolkits/) are > 15 different agent toolkits (e.g., Gmail, Pandas, etc). "
]
},
{
"cell_type": "markdown",
"id": "5eefe4a0",
"metadata": {},
"source": [
"## Agents\n",
"\n",
"--- \n",
"\n",
"There's a number of [agent types](https://python.langchain.com/docs/modules/agents/agent_types/) available in LangChain.\n",
"\n",
"**Action agents** \n",
"\n",
"Use an LLM to determine which actions to take and in what order:\n",
"\n",
"* [ReAct](https://python.langchain.com/docs/modules/agents/agent_types/react.html): This is the most general purpose action agent using the [ReAct framework](https://arxiv.org/pdf/2205.00445.pdf), which can work with [Docstores](https://python.langchain.com/docs/modules/agents/agent_types/react_docstore.html) or [Multi-tool Inputs](https://python.langchain.com/docs/modules/agents/agent_types/structured_chat.html).\n",
"* [OpenAI functions](https://python.langchain.com/docs/modules/agents/agent_types/openai_functions_agent.html): Designed to work with OpenAI function-calling models.\n",
"* [Conversational](https://python.langchain.com/docs/modules/agents/agent_types/chat_conversation_agent.html): This agent is designed to be used in conversational settings\n",
"* [Self-ask with search](https://python.langchain.com/docs/modules/agents/agent_types/self_ask_with_search.html): Designed to lookup factual answers to questions\n",
"\n",
"**Plan-and-execute agents** \n",
"\n",
"Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. \n",
"\n",
"* [BabyAGI](https://github.com/yoheinakajima/babyagi), which has a LangChain [user](https://python.langchain.com/docs/use_cases/agents/baby_agi) [guide](https://python.langchain.com/docs/use_cases/agents/baby_agi_with_agent)\n",
"\n",
"### OpenAI Functions agent\n",
"\n",
"As shown in Quickstart, let's continue with [`OpenAI functions` agent](https://python.langchain.com/docs/modules/agents/agent_types/).\n",
"\n",
"This uses OpenAI models, which are fine-tuned to detect when a function should to be called.\n",
"\n",
"They will respond with the inputs that should be passed to the function.\n",
"\n",
"But, we can unpack it, first with a custom prompt:"
]
},
{
"cell_type": "code",
"execution_count": 103,
"id": "1c2deb4a",
"metadata": {},
"outputs": [],
"source": [
"# Memory\n",
"MEMORY_KEY = \"chat_history\"\n",
"memory = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)\n",
"\n",
"# Prompt\n",
"from langchain.schema import SystemMessage\n",
"from langchain.agents import OpenAIFunctionsAgent\n",
"from langchain.prompts import MessagesPlaceholder\n",
"system_message = SystemMessage(content=\"You are very powerful assistant, but bad at calculating lengths of words.\")\n",
"prompt = OpenAIFunctionsAgent.create_prompt(\n",
" system_message=system_message,\n",
" extra_prompt_messages=[MessagesPlaceholder(variable_name=MEMORY_KEY)]\n",
")"
]
},
{
"cell_type": "markdown",
"id": "ee317a45",
"metadata": {},
"source": [
"Define agent:"
]
},
{
"cell_type": "code",
"execution_count": 105,
"id": "460dab9b",
"metadata": {},
"outputs": [],
"source": [
"# Agent \n",
"from langchain.agents import OpenAIFunctionsAgent\n",
"from langchain.chat_models import ChatOpenAI\n",
"llm = ChatOpenAI(temperature=0)\n",
"agent = OpenAIFunctionsAgent(llm=llm, tools=word_length_tool, prompt=prompt)"
]
},
{
"cell_type": "markdown",
"id": "184e6c23",
"metadata": {},
"source": [
"Run agent:"
]
},
{
"cell_type": "code",
"execution_count": 106,
"id": "f4f27d37",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'There are 5 letters in the word \"educa\".'"
]
},
"execution_count": 106,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Run the executer, including short-term memory we created\n",
"from langchain.agents import AgentExecutor\n",
"agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=False)\n",
"agent_executor.run(\"how many letters in the word educa?\")"
]
},
{
"cell_type": "markdown",
"id": "e4d9217e",
"metadata": {},
"source": [
"### ReAct\n",
"\n",
"If we are working with an LLM that does not support functions, [ReAct](https://arxiv.org/abs/2210.03629) agents are a popular choice.\n",
"\n",
"You can see the charecteristic `Thought`, `Action`, `Observation` [pattern in the output](https://lilianweng.github.io/posts/2023-06-23-agent/).\n",
"\n",
"Also note that we can use `initialize_agent` to easily create the agent.\n",
"\n",
"Browse all the agent types [here](https://github.com/langchain-ai/langchain/blob/master/libs/langchain/langchain/agents/types.py)."
]
},
{
"cell_type": "code",
"execution_count": 111,
"id": "232ad3a1",
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import load_tools\n",
"from langchain.agents import initialize_agent\n",
"from langchain.agents import AgentType"
]
},
{
"cell_type": "code",
"execution_count": 116,
"id": "85f033d3",
"metadata": {},
"outputs": [],
"source": [
"MEMORY_KEY = \"chat_history\"\n",
"memory = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)\n",
"react_agent = initialize_agent(search_tool, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False, memory=memory)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "141049ee",
"metadata": {},
"outputs": [],
"source": [
"react_agent(\"How many people live in canada as of 2023?\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cdbf6acb",
"metadata": {},
"outputs": [],
"source": [
"react_agent(\"What is its largest province?\")"
]
},
{
"cell_type": "markdown",
"id": "d4df0638",
"metadata": {},
"source": [
"The LangSmith [trace](https://smith.langchain.com/public/d3bbfa9a-e518-473f-8167-1d8690ecc38a/r) gives us insight into the ReAct prompt."
]
},
{
"cell_type": "markdown",
"id": "04026f19",
"metadata": {},
"source": [
"![Image description](../../../docs_skeleton/static/img/agents_use_case_trace_2.png)"
]
},
{
"cell_type": "markdown",
"id": "5cde8f9a",
"metadata": {},
"source": [
"### Custom\n",
"\n",
"Let's peel it back even further to define our own action agent.\n",
"\n",
"We can [create a custom agent](https://python.langchain.com/docs/modules/agents/how_to/custom_agent.html) to unpack the central pieces:\n",
"\n",
"* `Tools`: The tools the agent has available to use\n",
"* `Agent`: decides which action to take"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "3313f5cd",
"metadata": {
"scrolled": false
},
"outputs": [
{
"data": {
"text/plain": [
"\"The current population of Canada is 38,808,843 as of Tuesday, August 1, 2023, based on Worldometer elaboration of the latest United Nations data 1. Canada 2023\\xa0... Mar 22, 2023 ... Record-high population growth in the year 2022. Canada's population was estimated at 39,566,248 on January 1, 2023, after a record population\\xa0... Jun 19, 2023 ... As of June 16, 2023, there are now 40 million Canadians! This is a historic milestone for Canada and certainly cause for celebration. It is also\\xa0... Jun 28, 2023 ... Canada's population was estimated at 39,858,480 on April 1, 2023, an increase of 292,232 people (+0.7%) from January 1, 2023. The main driver of population growth is immigration, and to a lesser extent, natural growth. Demographics of Canada · Population pyramid of Canada in 2023. May 2, 2023 ... On January 1, 2023, Canada's population was estimated to be 39,566,248, following an unprecedented increase of 1,050,110 people between January\\xa0... Canada ranks 37th by population among countries of the world, comprising about 0.5% of the world's total, with over 40.0 million Canadians as of 2023. The current population of Canada in 2023 is 38,781,291, a 0.85% increase from 2022. The population of Canada in 2022 was 38,454,327, a 0.78% increase from 2021. Whether a given sub-nation is a province or a territory depends upon how its power and authority are derived. Provinces were given their power by the\\xa0... Jun 28, 2023 ... Index to the latest information from the Census of Population. ... 2023. Census in Brief: Multilingualism of Canadian households\\xa0...\""
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from typing import List, Tuple, Any, Union\n",
"from langchain.schema import AgentAction, AgentFinish\n",
"from langchain.agents import Tool, AgentExecutor, BaseSingleActionAgent\n",
"\n",
"class FakeAgent(BaseSingleActionAgent):\n",
" \"\"\"Fake Custom Agent.\"\"\"\n",
"\n",
" @property\n",
" def input_keys(self):\n",
" return [\"input\"]\n",
"\n",
" def plan(\n",
" self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any\n",
" ) -> Union[AgentAction, AgentFinish]:\n",
" \"\"\"Given input, decided what to do.\n",
"\n",
" Args:\n",
" intermediate_steps: Steps the LLM has taken to date,\n",
" along with observations\n",
" **kwargs: User inputs.\n",
"\n",
" Returns:\n",
" Action specifying what tool to use.\n",
" \"\"\"\n",
" return AgentAction(tool=\"Search\", tool_input=kwargs[\"input\"], log=\"\")\n",
"\n",
" async def aplan(\n",
" self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any\n",
" ) -> Union[AgentAction, AgentFinish]:\n",
" \"\"\"Given input, decided what to do.\n",
"\n",
" Args:\n",
" intermediate_steps: Steps the LLM has taken to date,\n",
" along with observations\n",
" **kwargs: User inputs.\n",
"\n",
" Returns:\n",
" Action specifying what tool to use.\n",
" \"\"\"\n",
" return AgentAction(tool=\"Search\", tool_input=kwargs[\"input\"], log=\"\")\n",
" \n",
"fake_agent = FakeAgent()\n",
"fake_agent_executor = AgentExecutor.from_agent_and_tools(agent=fake_agent, \n",
" tools=search_tool, \n",
" verbose=False)\n",
"\n",
"fake_agent_executor.run(\"How many people live in canada as of 2023?\")"
]
},
{
"cell_type": "markdown",
"id": "1335f0c6",
"metadata": {},
"source": [
"## Going deeper\n",
"\n",
"* Explore the other agent types [here](https://python.langchain.com/docs/modules/agents/agent_types/)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.16"
}
},
"nbformat": 4,
"nbformat_minor": 5
}