AI Agent 开发:Function Calling / Tool Use 实战教程

在当今AI技术快速发展的背景下,Function Calling(函数调用)和Tool Use(工具使用)已成为构建智能AI Agent的核心能力。本教程将深入讲解如何利用GPT-4o、Claude 3等先进模型,通过無量Api(api2everything.xyz)快速开发能够调用外部工具的AI Agent。

什么是Function Calling/Tool Use?

Function Calling是AI模型理解用户请求后,决定调用哪些外部函数/工具来完成任务的机制。它使AI突破纯文本生成的限制,实现:

2023年后发布的GPT-4、Claude 3、Gemini等模型都原生支持此功能,通过無量Api可稳定调用这些模型。

开发环境准备

1. 注册無量Api账号

無量Api提供300+AI模型的统一接入,国内直连无需翻墙:

# Python安装
pip install openai

# Node.js安装
npm install openai

2. 获取API密钥

登录api2everything.xyz后,在控制台"API Keys"页面创建密钥。

Python实战示例

基础Function Calling

构建一个查询天气的AI Agent:

from openai import OpenAI

client = OpenAI(
    api_key="您的無量Api密钥",
    base_url="https://api2everything.xyz/v1"
)

def get_current_weather(location, unit="celsius"):
    """模拟天气API"""
    return f"{location}当前天气:25°{unit},晴天"

tools = [{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": {
            "location": "城市名称,如'北京'",
            "unit": "温度单位,'celsius'或'fahrenheit'"
        }
    }
}]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "上海现在天气如何?"}],
    tools=tools,
    tool_choice="auto"
)

# 处理函数调用
tool_call = response.choices[0].message.tool_calls[0]
if tool_call.function.name == "get_current_weather":
    weather = get_current_weather(**eval(tool_call.function.arguments))
    print(weather)  # 输出:上海当前天气:25°celsius,晴天

多工具协同调用

让AI自动选择合适工具处理复杂请求:

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_stock_price",
            "description": "查询股票当前价格",
            "parameters": {
                "symbol": "股票代码,如'AAPL'"
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "send_email",
            "description": "发送电子邮件通知",
            "parameters": {
                "to": "收件人邮箱",
                "subject": "邮件主题",
                "body": "邮件内容"
            }
        }
    }
]

response = client.chat.completions.create(
    model="claude-3-opus-20240229",
    messages=[{
        "role": "user", 
        "content": "如果苹果股价超过200美元就发邮件通知我"
    }],
    tools=tools
)

Node.js实现方案

基础设置

const OpenAI = require('openai');

const openai = new OpenAI({
  apiKey: '您的無量Api密钥',
  baseURL: 'https://api2everything.xyz/v1'
});

async function calling示例
async function askAI() {
  const response = await openai.chat.completions.create({
    model: "gpt-4-turbo",
    messages: [{ role: "user", content: "旧金山现在几点?" }],
    tools: [{
      type: "function",
      function: {
        name: "get_current_time",
        description: "获取指定城市的当前时间",
        parameters: {
          city: "城市名称"
        }
      }
    }]
  });
  
  console.log(response.choices[0].message);
}

高级应用技巧

1. 工具描述优化

精确的函数描述能显著提升调用准确率:

2. 错误处理机制

try:
    response = client.chat.completions.create(...)
    tool_call = response.choices[0].message.tool_calls[0]
    
    if tool_call.function.name == "get_weather":
        try:
            result = get_weather(**eval(tool_call.function.arguments))
        except Exception as e:
            result = f"天气查询失败:{str(e)}"
            
    # 将结果返回给AI继续处理
    messages.append({
        "role": "tool",
        "content": result,
        "tool_call_id": tool_call.id
    })
    
except Exception as e:
    print(f"AI调用失败:{str(e)}")

3. 成本优化策略

通过無量Api可节省70%成本:

模型 官方价格 無量Api价格
GPT-4o $5/百万tokens $1.5/百万tokens
Claude 3 Opus $15/百万tokens $4.5/百万tokens

常见问题解答

Q1: 如何选择最适合Function Calling的模型?

A: GPT-4o和Claude 3 Opus在工具调用准确率上表现最佳。通过無量Api可轻松切换对比不同模型。

Q2: 国内调用需要特殊配置吗?

A: 無量Api服务器位于香港,国内可直接访问,无需VPN。平均延迟<300ms。

Q3: 如何处理敏感数据?

A: 建议:1) 使用無量Api的企业版私有部署 2) 对敏感参数加密 3) 设置API调用频率限制

Q4: 为什么我的函数调用总是不准确?

A: 检查:1) 函数描述是否清晰 2) 参数定义是否完整 3) 尝试更换模型版本 4) 使用few-shot示例

立即体验高效AI开发

注册無量Api即送$5体验金,支持GPT-4o、Claude 3等300+模型,国内直连稳定可靠

免费注册 →