掌握 OpenAI Tool Calling:用 Ruby 打造下一代智能对话助手

掌握 OpenAI Tool Calling:用 Ruby 打造下一代智能对话助手

在 AI 应用开发领域,Tool Calling(也称为 Function Calling)是一项革命性的功能。它让 AI 模型能够主动调用预定义的函数,极大地扩展了 AI 助手的能力边界。本文将带您深入了解 Tool Calling,并通过实例讲解如何使用 Ruby 实现这一强大功能。

Tool Calling 是什么?

Tool Calling 是 OpenAI 在 2023 年 6 月推出的重要特性(官方公告)。这项技术让 AI 模型能够:

  1. 智能判断:自主识别何时需要调用特定工具或函数
  2. 结构化输出:生成符合函数参数要求的规范数据
  3. 上下文理解:将函数返回的结果融入对话上下文
  4. 多工具协同:根据需要调用多个不同的工具

这项技术为 AI 应用带来了诸多可能:

  • 查询实时数据(如天气、股票价格)
  • 执行复杂计算
  • 控制智能家居设备
  • 访问外部 API 和数据库
  • 处理结构化数据转换

深入实战:用 Ruby 实现智能天气助手

让我们通过一个实际的天气查询助手来掌握 Tool Calling 的实现。

1. 环境准备

首先,创建一个新的 Ruby 项目并安装必要的 gem:

1
2
3
mkdir weather-assistant
cd weather-assistant
bundle init

在 Gemfile 中添加依赖:

1
2
3
4
source 'https://rubygems.org'

gem 'ruby-openai'
gem 'dotenv'  # 用于管理环境变量

安装依赖:

1
bundle install

2. 配置 OpenAI 客户端

创建主程序文件 weather_assistant.rb

1
2
3
4
5
6
7
8
9
require 'openai'
require 'dotenv/load'
require 'json'

# 配置 OpenAI 客户端
client = OpenAI::Client.new(
  access_token: ENV['OPENAI_API_KEY'],
  uri_base: ENV['OPENAI_API_BASE'] # 如果使用代理
)

3. 定义天气查询函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def get_weather(location)
  # 这里模拟天气 API 调用
  # 实际应用中,你可以接入真实的天气 API
  weather_data = {
    location: location,
    temperature: 25,
    condition: "晴朗",
    humidity: 65,
    wind_speed: 3.5
  }

  return weather_data
end

4. 定义 Tool 配置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
TOOLS = [
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "获取指定地点的实时天气信息",
      parameters: {
        type: "object",
        properties: {
          location: {
            type: "string",
            description: "查询的地点,如:北京、上海、广州"
          }
        },
        required: ["location"]
      }
    }
  }
]

5. 实现对话处理逻辑

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def chat_with_assistant(user_input)
  messages = [{ role: "user", content: user_input }]

  response = client.chat(
    parameters: {
      model: "gpt-4-1106-preview", # 或其他支持 tool calling 的模型
      messages: messages,
      tools: TOOLS,
      tool_choice: "auto"
    }
  )

  # 处理响应
  message = response.dig("choices", 0, "message")

  if message["tool_calls"]
    tool_calls = message["tool_calls"]

    # 处理每个工具调用
    tool_calls.each do |tool_call|
      function_name = tool_call.dig("function", "name")
      arguments = JSON.parse(tool_call.dig("function", "arguments"))

      # 执行函数调用
      result = case function_name
      when "get_weather"
        get_weather(arguments["location"])
      end

      # 将函数调用结果添加到消息历史
      messages << {
        role: "assistant",
        content: nil,
        tool_calls: [tool_call]
      }

      messages << {
        role: "tool",
        tool_call_id: tool_call["id"],
        content: result.to_json
      }
    end

    # 让助手处理函数返回结果
    final_response = client.chat(
      parameters: {
        model: "gpt-4-1106-preview",
        messages: messages
      }
    )

    return final_response.dig("choices", 0, "message", "content")
  end

  return message["content"]
end

6. 运行示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 主程序循环
puts "欢迎使用天气助手!输入 'quit' 退出"

loop do
  print "你: "
  user_input = gets.chomp
  break if user_input.downcase == 'quit'

  response = chat_with_assistant(user_input)
  puts "助手: #{response}"
end

实际效果展示

使用上述代码,我们可以进行如下对话:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
你: 北京今天天气怎么样?
助手: 根据查询,北京现在的天气情况如下:
- 温度:25°C
- 天气状况:晴朗
- 湿度:65%
- 风速:3.5米/秒
天气适合外出活动。

你: 上海呢?
助手: 让我为您查询上海的天气:
- 温度:25°C
- 天气状况:晴朗
- 湿度:65%
- 风速:3.5米/秒
今天上海的天气也很不错!

进阶提示

  1. 错误处理:在实际应用中,应添加适当的错误处理机制:

    • API 调用超时处理
    • 无效地点名称处理
    • API 限流处理
  2. 缓存机制:对于频繁查询的地点,可以实现缓存机制:

1
2
3
4
5
6
7
8
9
def get_weather_with_cache(location)
  cache_key = "weather_#{location}"
  cached = Redis.get(cache_key)
  return JSON.parse(cached) if cached

  weather = get_weather(location)
  Redis.set(cache_key, weather.to_json, ex: 1800) # 30分钟过期
  weather
end
  1. 日志记录:添加日志记录以便追踪和调试:
1
2
3
4
require 'logger'

logger = Logger.new('weather_assistant.log')
logger.info("Processing weather request for #{location}")

总结

OpenAI 的 Tool Calling 功能为 AI 应用开发带来了无限可能。通过 Ruby 实现这一功能,我们可以轻松构建智能、交互式的应用程序。本文展示的天气助手只是一个简单示例,你可以基于此扩展出更多有趣的应用,如:

  • 多源数据查询助手
  • 智能家居控制系统
  • 个人日程管理助手
  • 数据分析助手

希望本文能帮助你更好地理解和应用 OpenAI 的 Tool Calling 功能!

参考资源

Built with Hugo
Theme Stack designed by Jimmy