Source code for langchain.agents.format_scratchpad.tools
importjsonfromtypingimportList,Sequence,Tuplefromlangchain_core.agentsimportAgentActionfromlangchain_core.messagesimport(AIMessage,BaseMessage,ToolMessage,)fromlangchain.agents.output_parsers.toolsimportToolAgentActiondef_create_tool_message(agent_action:ToolAgentAction,observation:str)->ToolMessage:"""Convert agent action and observation into a tool message. Args: agent_action: the tool invocation request from the agent. observation: the result of the tool invocation. Returns: ToolMessage that corresponds to the original tool invocation. Raises: ValueError: if the observation cannot be converted to a string. """ifnotisinstance(observation,str):try:content=json.dumps(observation,ensure_ascii=False)exceptException:content=str(observation)else:content=observationreturnToolMessage(tool_call_id=agent_action.tool_call_id,content=content,additional_kwargs={"name":agent_action.tool},)
[docs]defformat_to_tool_messages(intermediate_steps:Sequence[Tuple[AgentAction,str]],)->List[BaseMessage]:"""Convert (AgentAction, tool output) tuples into ToolMessages. Args: intermediate_steps: Steps the LLM has taken to date, along with observations. Returns: list of messages to send to the LLM for the next prediction. """messages=[]foragent_action,observationinintermediate_steps:ifisinstance(agent_action,ToolAgentAction):new_messages=list(agent_action.message_log)+[_create_tool_message(agent_action,observation)]messages.extend([newfornewinnew_messagesifnewnotinmessages])else:messages.append(AIMessage(content=agent_action.log))returnmessages