LangChain LLM 带工具:工具调用教程
带有工具的 LangChain LLM 需要三样东西:指向 OpenAI 兼容接口的聊天模型、绑定到该模型的工具函数列表,以及运行模型请求的工具的循环。本教程针对本站的 无审查文本 API 构建该功能。

要点
- 当你设置 base_url、api_key 和 model 时,ChatOpenAI 可与任何 OpenAI 兼容接口配合使用。
- bind_tools 发送你的函数模式;你运行工具并将结果作为工具消息返回。
- 当你不需要工具时,JSON 模式提供可解析的输出。
- 注意限制:完整密钥允许 8 个并发请求和每分钟 300 个请求。
设置
安装软件包并将密钥保存在环境变量中。你可以在 API 密钥页面 获取密钥并领取 $0.50 试用额度。
pip install langchain-openai langchain-core
export API_KEY="your-key-here"
该服务使用 OpenAI chat completions 格式,因此 LangChain 的 ChatOpenAI 类无需更改即可使用。三个值很重要:Base URL、密钥和模型 ID,即 uncensored。
import os
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="uncensored",
base_url="https://api.acestep.cc/v1",
api_key=os.environ["API_KEY"],
temperature=0,
max_retries=2,
)
print(llm.invoke("Say hello in five words.").content)
如果打印出简短的问候语,则连接正常。较低 temperature 是工具使用的良好默认值,因为你希望参数值稳定。
定义工具并绑定
@tool 装饰器将 Python 函数转换为工具。LangChain 读取函数名、类型提示和 docstring 以构建发送给模型的 JSON 模式,因此将 docstring 写成给模型的指令,而不是给人类读者的说明。
from langchain_core.tools import tool
@tool
def word_count(text: str) -> int:
"""Count the words in a piece of text, for example song lyrics."""
return len(text.split())
tools = [word_count]
llm_with_tools = llm.bind_tools(tools)
bind_tools 将 tools 字段添加到每个请求。你还可以传递 tool_choice 以强制使用特定工具,或者不传递它让模型自行决定。
运行调用循环
模型不执行任何操作。它返回带有 tool_calls 的助手消息,每个调用包含名称、参数和 ID。你的代码运行函数并发送带有相同 ID 的工具消息。然后再次调用模型,以便它编写最终答案。
from langchain_core.messages import HumanMessage, ToolMessage
registry = {t.name: t for t in tools}
messages = [HumanMessage("How many words are in: 'the rain keeps writing the chorus'?")]
ai = llm_with_tools.invoke(messages)
messages.append(ai)
for call in ai.tool_calls:
result = registry[call["name"]].invoke(call["args"])
messages.append(ToolMessage(content=str(result), tool_call_id=call["id"]))
final = llm_with_tools.invoke(messages)
print(final.content)
结果应包含六个单词。在 API 请求中,这与原始格式的流程相同:工具结果以 role: "tool" 返回,LangChain 的 ToolMessage 映射到该格式。
处理多轮次的循环
实际任务通常需要多轮:模型调用工具,读取结果并调用另一个工具。将步骤包装在带有硬限制的循环中,以防模型陷入无限循环。
def run(question, max_rounds=5):
messages = [HumanMessage(question)]
for _ in range(max_rounds):
ai = llm_with_tools.invoke(messages)
messages.append(ai)
if not ai.tool_calls:
return ai.content
for call in ai.tool_calls:
try:
out = registry[call["name"]].invoke(call["args"])
except Exception as exc:
out = f"Tool error: {exc}"
messages.append(ToolMessage(content=str(out), tool_call_id=call["id"]))
return "Stopped after too many tool rounds."
print(run("Count the words in 'hold the line' and in 'break the silence', then add them."))
将错误文本作为工具结果返回而不是抛出异常,可以让模型看到错误并尝试使用更好的参数。当模型在一条消息中发送多个工具调用时,全部运行它们并为每次调用追加一条工具消息。
LangChain 还提供现成的代理辅助工具,它们在此接口上同样有效:它们只需要支持工具调用的聊天模型。手动编写一次循环仍然值得,因为这样你就确切知道发送了什么以及计费情况。
流式工具调用
API 通过服务器发送事件进行流式传输,工具调用分片到达。LangChain 消息块可以相加,从而重建完整的调用:
full = None
for chunk in llm_with_tools.stream("How many words are in 'one two three'?"):
full = chunk if full is None else full + chunk
print(full.tool_calls)
在等待时为用户流式传输文本,仅在流完成时才对工具调用采取行动。使用情况在流结束时报告,因此计费数据在最后一个块之后可用。
在链中使用工具
如果你更喜欢 LangChain 的管道语法,绑定模型可以像其他可运行对象一样插入链中。提示模板为模型提供输入,解析器将最终消息转换为文本:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
prompt = ChatPromptTemplate.from_messages([
("system", "You help writers check their drafts. Use tools when counting is needed."),
("human", "{question}"),
])
chain = prompt | llm | StrOutputParser()
print(chain.invoke({"question": "Write a two-line chorus about rain."}))
此链不运行工具。它适合纯生成步骤。当步骤需要工具时,调用绑定模型并使用上述循环,或将该循环放入函数中并用可运行 lambda 包装它。保持工具循环显式化使得记录每次调用更容易,这在参数看起来不正确时很有帮助。
不带工具的结构化 JSON
当你需要数据且不需要函数执行时,使用 JSON 模式。它将 response_format 设置为 {"type": "json_object"}。提示词还必须告诉模型返回的形状。
import json
json_llm = llm.bind(response_format={"type": "json_object"})
msg = json_llm.invoke(
"Return a JSON object with keys 'title' (string) and 'tags' (list of 3 strings) "
"for a song about a night train."
)
data = json.loads(msg.content)
print(data["title"], data["tags"])
JSON 模式提高生成有效 JSON 的可能性,但不强制执行你的模式。使用 Pydantic 等工具自行验证键和类型,如果验证失败则重试一次。
陷阱和限制
- 参数按模型编写的方式到达。 在工具中验证类型;不要相信数字就是数字。
- 工具描述引导行为。 模糊的 docstring 会导致错误的工具选择。说明何时使用工具以及何时不使用。
- HTTP 429。 完整密钥允许 8 个并发请求和每分钟 300 个请求;试用密钥允许 2 个和 60 个。错误代码为
rate_limited和concurrency。带有Retry-After: 5的 429 表示临时过载,客户端上的max_retries有助于处理这种情况。流式输出会占用其槽位直到结束。 - 上下文。 上下文窗口为 100,000 个 token,包括提示词和补全。每次工具轮次都会重新发送历史记录,因此长代理运行会迅速增长。
快速入门 包含完整的参数列表。此模型仅支持文本,因此依赖图像、音频或嵌入的工具需要其他服务来处理管道的这一部分。
工具循环的成本
定价为每 1M 输入 token $0.15,每 1M 输出 token $0.50。通过一轮工具回答一个问题需要进行两次调用。假设两次调用共发送 4,000 个输入 token 并生成 600 个输出 token。输入成本为 4,000 / 1,000,000 x $0.15 = $0.0006,输出成本为 600 / 1,000,000 x $0.50 = $0.0003,因此该问题的成本为 $0.0009。失败或被拒绝的请求不收费。查看 定价页面 了解充值金额和支付方式。
更多指南
问答
此 API 支持工具调用吗?
是的。它接受工具和 tool_choice,返回 tool_calls(流式输出时也可用),并将结果作为 role 为 tool 的消息接收。
我应该使用哪个 LangChain 类?
来自 langchain-openai 的 ChatOpenAI,将 base_url 设置为 API 接口,并传入你的密钥和模型 ID uncensored。
我可以使用模式获取结构化输出吗?
JSON 模式返回有效的 JSON 对象,但不强制执行模式。在提示词中描述结构,并在代码中验证结果。
如何在并行链中避免速率限制错误?
使用完整密钥时,并发数请保持在 8 以内(含 8),并对 429 响应使用客户端重试。试用密钥允许 2 个并发请求。