PromptTemplate(input_variables=['agent_scratchpad', 'input', 'tool_names', 'tools'], metadata={'lc_hub_owner': 'hwchase17', 'lc_hub_repo': 'react', 'lc_hub_commit_hash': 'd15fe3c426f1c4b3f37c9198853e4a86e20c425ca7f4752ec0c9b0e97ca7ea4d'}, template='Answer the following questions as best you can. You have access to the following tools:\n\n{tools}\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [{tool_names}]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: {input}\nThought:{agent_scratchpad}'))
Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought:{agent_scratchpad}
"""
复制代码
Thought: you should always think about what to doAction: the action to take, should be one of [{tool_names}]Action Input: the input to the actionObservation: the result of the action… (this Thought/Action/Action Input/Observation can repeat N times)
from langchain.agents import AgentExecutor, create_react_agent
@tooldefget_employee_id(name):"""
To get employee id, it takes employee name as arguments
name(str): Name of the employee
"""
fake_employees ={"Alice":"E001","Bob":"E002","Charlie":"E003","Diana":"E004","Evan":"E005","Fiona":"E006","George":"E007","Hannah":"E008","Ian":"E009","Jasmine":"E010"}return fake_employees.get(name,"Employee not found")# Custom tool for the Agent # ValueError: Function must have a docstring if description not provided.@tooldefget_employee_salary(employee_id):"""
To get the salary of an employee, it takes employee_id as input and return salary
"""
employee_salaries ={"E001":56000,"E002":47000,"E003":52000,"E004":61000,"E005":45000,"E006":58000,"E007":49000,"E008":53000,"E009":50000,"E010":55000}return employee_salaries.get(employee_id,"Employee not found")
result = agent_executor.invoke({"input": input1,"chat_history": chat_history})
chat_history.extend([
HumanMessage(content=input1),
AIMessage(content=result["output"]),])
agent_executor.invoke({"input":"is that a real word?","chat_history": chat_history})"""
> Entering new AgentExecutor chain...
Invoking: `get_word_length` with `{'word': 'educa'}`
5The word "educa" has 5 letters.
> Finished chain.
> Entering new AgentExecutor chain...
"Educa" is not a standard English word. It might be a truncated form of "education" or a name, but it is not commonly recognized as a standalone word in English.
> Finished chain.
{'input': 'is that a real word?',
'chat_history': [HumanMessage(content='how many letters in the word educa?'),
AIMessage(content='The word "educa" has 5 letters.')],
'output': '"Educa" is not a standard English word. It might be a truncated form of "education" or a name, but it is not commonly recognized as a standalone word in English.'}
result = agent_executor.invoke({"input": input1,"chat_history": chat_history})
chat_history.extend([
HumanMessage(content=input1),
AIMessage(content=result["output"]),])
agent_executor.invoke({"input":"is that a real word?","chat_history": chat_history})
复制代码
输出结果:
> Entering new AgentExecutor chain...
Invoking: `get_word_length` with `{'word':'dadebfdr'}`
8The word "dadebfdr" has 8 letters.> Finished chain.> Entering new AgentExecutor chain...
No,"dadebfdr" does not appear to be a real word in the English language. It seems to be a random string of letters.> Finished chain.{'input':'is that a real word?','chat_history':[HumanMessage(content='how many letters in the word dadebfdr?'),
AIMessage(content='The word "dadebfdr" has 8 letters.')],'output':'No, "dadebfdr" does not appear to be a real word in the English language. It seems to be a random string of letters.'}
第一个tool的回答作为第二个tool的输入
Tools are interfaces that an agent can use to interact with the world. They combine a few things:
The name of the toolA description of what the tool isJSON schema of what the inputs to the tool areThe function to call
import random
@tool("upper_case", return_direct=True)defto_upper_case(input:str)->str:"""Returns the input as all upper case."""returninput.upper()@tool("random_number", return_direct=True)defrandom_number_maker(input:str)->str:"""Returns a random number between 0-100."""return random.randint(0,100)
inputs ={"input":"give me a random number and then write in words and make it upper case.","chat_history":[],"intermediate_steps":[]}
agent_outcome = agent.invoke(inputs)# AgentActionMessageLog(tool='random_number', tool_input={'input': 'Generate a random number'}, log="\nInvoking: `random_number` with `{'input': 'Generate a random number'}`\n\n\n", message_log=[AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"input":"Generate a random number"}', 'name': 'random_number'}}, response_metadata={'finish_reason': 'function_call', 'model_name': 'gpt-4o-2024-05-13', 'system_fingerprint': 'fp_3aa7262c27'}, id='run-e2652fc2-03db-4c6c-9b26-310d80e0f06a-0')])
output = tool_executor.invoke(agent_action)print(f"The agent action is {agent_action}")print(f"The tool result is: {output}")# AgentState.intermediate_steps: 追加逻辑return{"intermediate_steps":[(agent_action,str(output))]}defshould_continue(state):ifisinstance(state['agent_outcome'], AgentFinish):return"end"return"continue"