mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-10 03:45:17 +03:00
4.9 KiB
4.9 KiB
In [1]:
from langchain.agents import XMLAgent, tool, AgentExecutor
from langchain.chat_models import ChatAnthropicIn [2]:
model = ChatAnthropic(model="claude-2")In [3]:
@tool
def search(query: str) -> str:
"""Search things about current events."""
return "32 degrees"In [4]:
tool_list = [search]In [5]:
# Get prompt to use
prompt = XMLAgent.get_default_prompt()In [6]:
# Logic for going from intermediate steps to a string to pass into model
# This is pretty tied to the prompt
def convert_intermediate_steps(intermediate_steps):
log = ""
for action, observation in intermediate_steps:
log += (
f"<tool>{action.tool}</tool><tool_input>{action.tool_input}"
f"</tool_input><observation>{observation}</observation>"
)
return log
# Logic for converting tools to string to go in prompt
def convert_tools(tools):
return "\n".join([f"{tool.name}: {tool.description}" for tool in tools])In [7]:
agent = (
{
"question": lambda x: x["question"],
"intermediate_steps": lambda x: convert_intermediate_steps(x["intermediate_steps"])
}
| prompt.partial(tools=convert_tools(tool_list))
| model.bind(stop=["</tool_input>", "</final_answer>"])
| XMLAgent.get_default_output_parser()
)In [8]:
agent_executor = AgentExecutor(agent=agent, tools=tool_list, verbose=True)In [9]:
agent_executor.invoke({"question": "whats the weather in New york?"})Out [9]:
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m <tool>search</tool> <tool_input>weather in new york[0m[36;1m[1;3m32 degrees[0m[32;1m[1;3m <final_answer>The weather in New York is 32 degrees[0m [1m> Finished chain.[0m
{'question': 'whats the weather in New york?',
'output': 'The weather in New York is 32 degrees'}In [ ]: