create_xml_agent#

langchain.agents.xml.base.create_xml_agent(llm: ~langchain_core.language_models.base.BaseLanguageModel, tools: ~typing.Sequence[~langchain_core.tools.base.BaseTool], prompt: ~langchain_core.prompts.base.BasePromptTemplate, tools_renderer: ~typing.Callable[[list[~langchain_core.tools.base.BaseTool]], str] = <function render_text_description>, *, stop_sequence: bool | ~typing.List[str] = True) Runnable[source]#

创建一个使用XML来格式化其逻辑的代理。

Parameters:
  • llm (BaseLanguageModel) – 用作代理的LLM。

  • tools (Sequence[BaseTool]) – 此代理可以访问的工具。

  • prompt (BasePromptTemplate) – 要使用的提示,必须包含输入键 tools: 包含每个工具的描述。 agent_scratchpad: 包含先前的代理操作和工具输出。

  • tools_renderer (Callable[[list[BaseTool]], str]) – 这控制了工具如何转换为字符串,然后传递给LLM。默认是render_text_description

  • stop_sequence (bool | List[str]) –

    布尔值或字符串列表。 如果为True,则添加一个“”的停止标记以避免幻觉。 如果为False,则不添加停止标记。 如果是字符串列表,则使用提供的列表作为停止标记。

    默认值为True。如果您使用的LLM不支持停止序列,您可能需要将其设置为False。

Returns:

一个表示代理的可运行序列。它接收与传入提示相同的所有输入变量作为输入。它返回一个AgentAction或AgentFinish作为输出。

Return type:

Runnable

示例

from langchain import hub
from langchain_community.chat_models import ChatAnthropic
from langchain.agents import AgentExecutor, create_xml_agent

prompt = hub.pull("hwchase17/xml-agent-convo")
model = ChatAnthropic(model="claude-3-haiku-20240307")
tools = ...

agent = create_xml_agent(model, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)

agent_executor.invoke({"input": "hi"})

# Use with chat history
from langchain_core.messages import AIMessage, HumanMessage
agent_executor.invoke(
    {
        "input": "what's my name?",
        # Notice that chat_history is a string
        # since this prompt is aimed at LLMs, not chat models
        "chat_history": "Human: My name is Bob\nAI: Hello Bob!",
    }
)

提示:

The prompt must have input keys:
  • tools: 包含每个工具的描述。

  • agent_scratchpad: 包含之前的代理操作和工具输出,以XML字符串形式存在。

这是一个例子:

from langchain_core.prompts import PromptTemplate

template = '''You are a helpful assistant. Help the user answer any questions.

You have access to the following tools:

{tools}

In order to use a tool, you can use <tool></tool> and <tool_input></tool_input> tags. You will then get back a response in the form <observation></observation>
For example, if you have a tool called 'search' that could run a google search, in order to search for the weather in SF you would respond:

<tool>search</tool><tool_input>weather in SF</tool_input>
<observation>64 degrees</observation>

When you are done, respond with a final answer between <final_answer></final_answer>. For example:

<final_answer>The weather in SF is 64 degrees</final_answer>

Begin!

Previous Conversation:
{chat_history}

Question: {input}
{agent_scratchpad}'''
prompt = PromptTemplate.from_template(template)