mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-08 02:45:22 +03:00
5.3 KiB
5.3 KiB
In [3]:
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
from langchain.chains import LLMChain
from langchain.utilities import SerpAPIWrapperIn [4]:
search = SerpAPIWrapper()
tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to answer questions about current events"
)
]In [6]:
prefix = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:"""
suffix = """Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args"""
prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
input_variables=[]
)In [7]:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)In [8]:
messages = [
SystemMessagePromptTemplate(prompt=prompt),
HumanMessagePromptTemplate.from_template("{input}\n\nThis was your previous work "
f"(but I haven't seen any of it! I only see what "
"you return as final answer):\n{agent_scratchpad}")
]In [9]:
prompt = ChatPromptTemplate.from_messages(messages)In [10]:
llm_chain = LLMChain(llm=ChatOpenAI(temperature=0), prompt=prompt)In [11]:
tool_names = [tool.name for tool in tools]
agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)In [12]:
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)In [13]:
agent_executor.run("How many people live in canada as of 2023?")Out [13]:
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3mArrr, ye be in luck, matey! I'll find ye the answer to yer question. Thought: I need to search for the current population of Canada. Action: Search Action Input: "current population of Canada 2023" [0m Observation: [36;1m[1;3mThe current population of Canada is 38,623,091 as of Saturday, March 4, 2023, based on Worldometer elaboration of the latest United Nations data.[0m Thought:[32;1m[1;3mAhoy, me hearties! I've found the answer to yer question. Final Answer: As of March 4, 2023, the population of Canada be 38,623,091. Arrr![0m [1m> Finished chain.[0m
'As of March 4, 2023, the population of Canada be 38,623,091. Arrr!'
In [ ]: