跳转到主要内容

通过 API 使用 AI 机器人

概述

Discourse AI 提供一个管理员/API 端点,用于通过原始分块 HTTP 回应流式传输 AI 代理回复。

  • **协议:**原始分块 HTTP 传输编码(非 Server-Sent Events)。
  • **实现:**劫持 Rack 套接字以流式传输以换行符分隔的 JSON 对象。
  • **副作用:**这不仅仅是一个补全 API,它还会创建真实的 Discourse 私信(PM)帖子。

端点详细信息

  • 地点:plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb:175-272
  • 路由:POST /admin/plugins/discourse-ai/ai-agents/stream-reply.json
  • API 密钥作用域:ai:stream_completion(注册于 plugins/discourse-ai/lib/ai_bot/entry_point.rb:283-286)

请求标题

POST /admin/plugins/discourse-ai/ai-agents/stream-reply.json
Api-Key: <your_api_key>
Api-Username: <your_username>
Content-Type: application/json

请求正文参数

参数 类型 必选 描述
agent_id 整数 可选* 代理的标识符。
agent_name 字符串 可选* 代理的替代标识符。
query 字符串 是 用户的提示/问题。
username 字符串 省略 user_unique_id 时必选 在聊天私信需要与现有用户关联时使用。
user_unique_id 字符串 省略 username 时必选 标识最终用户。创建/复用以自定义字段 ai-stream-conversation-unique-id 为键的暂存用户。
preferred_username 字符串 可选* 用户的用户名(如果未使用 user_unique_id)。
topic_id 整数 可选 继续现有的私信对话。
custom_instructions 字符串 可选 追加到代理提示上下文中。

**注意:**你必须通过 username(现有 Discourse 用户)或 user_unique_id 来标识最终用户。


回应格式

服务器返回带有 Transfer-Encoding: chunked 的 200 OK 回应。该流由以换行符分隔的 JSON 对象组成。

HTTP 标题

HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked
Cache-Control: no-cache, no-store, must-revalidate
Connection: close
X-Accel-Buffering: no
X-Content-Type-Options: nosniff

流有效负载结构

  1. **上下文块:**提供元数据(话题 ID、机器人用户 ID、代理 ID)。
  2. **部分块:**包含流式传输的文本片段。

流示例:

{"topic_id":42,"bot_user_id":7,"agent_id":123}

{"partial":"Hello"}

{"partial":" there"}

客户端应拼接 partial 字段来构建最终答案。


工作流程与副作用

该端点在执行期间执行以下操作:

  1. 使用原始 query 创建用户帖子。
  2. 通过分块回应流式传输 AI 答案。
  3. 使用累积的答案创建最终的 AI 回复帖子。
  4. 对于新的私信,可能会自动为话题设置标题。

自定义客户端执行的工具

您可以提供工具定义,让模型调用外部工具。调用工具时,服务器会暂停流,让客户端执行工具并恢复流。

1. 带工具的初始请求

在请求正文中包含 custom_tools:

{
  "agent_id": 123,
  "query": "What's the weather?",
  "user_unique_id": "external-user-42",
  "custom_tools": [
    {
      "name": "client_weather",
      "description": "Gets weather from the client runtime",
      "parameters": [
        {
          "name": "city",
          "description": "City to fetch weather for",
          "type": "string",
          "required": true
        }
      ]
    }
  ]
}

2. 工具调用事件

如果模型调用了工具,流会发出 tool_calls 事件并停止:

{
  "event": "tool_calls",
  "tool_calls": [
    {
      "id": "tool_1",
      "name": "client_weather",
      "parameters": { "city": "Austin" }
    }
  ],
  "resume_token": "..."
}

此时服务器会将对话状态持久化到 Redis 中。

3. 使用工具结果恢复流

客户端执行工具并恢复流:

{
  "resume_token": "...",
  "tool_results": [
    {
      "tool_call_id": "tool_1",
      "content": { "temperature_c": 23 }
    }
  ]
}

服务器重新加载已保存的提示状态,插入工具结果,继续生成,并流式传输更多 partial 数据块。

工具限制

  • 自定义工具数量上限:20
  • 工具结果数量上限:20
  • 自定义工具定义大小上限:10,000 字节
  • 工具结果内容大小上限:100 KB
  • 恢复 TTL:15 分钟
  • 恢复轮数上限:10

实现参考

  • 控制器:plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb
  • 流式处理器:plugins/discourse-ai/lib/ai_bot/response_http_streamer.rb
  • 自定义工具会话:plugins/discourse-ai/lib/ai_bot/stream_reply_custom_tools_session.rb

测试示例

查看 plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb 中的完整示例:

  • **新的流式对话:**第 1248-1356 行
  • **自定义工具 + 恢复令牌:**第 1358-1448 行
  • **并行工具调用:**第 1467-1590 行

示例实现

[details=Ruby 脚本]

require 'net/http'
require 'json'
require 'uri'

# Configuration
DISCOURSE_URL = '<your site URL>'
API_KEY = '<your API key>'
USERNAME = '<your username>'
AGENT_ID = -1 # Or use agent_name
QUERY = "Hello, how are you today?"
USER_UNIQUE_ID ='leave empty if want the PM to be sent to the USERNAME user'


# Helper to create the URI
uri = URI("#{DISCOURSE_URL}/admin/plugins/discourse-ai/ai-agents/stream-reply.json")

# Create the HTTP request
request = Net::HTTP::Post.new(uri)
request['Api-Key'] = API_KEY
request['Api-Username'] = USERNAME
request['Content-Type'] = 'application/json'

# Prepare the request body
body = {
  agent_id: AGENT_ID,
  query: QUERY,
  ## uncomment the below line if you want to use an existing user for the conversation. Also, `username` takes precedence over `user_unique_id` if passed.
  # username: USERNAME,
  ## use the below field along with `user_unique_id` in order to create a new staged user. When using this, skip passing the `username`.
  # preferred_username: USER_UNIQUE_ID
}
body[:user_unique_id] = USER_UNIQUE_ID unless USER_UNIQUE_ID.empty?

body = body.to_json
request.body = body

http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = (uri.scheme == 'https')

http.request(request) do |response|
    # Check if the response is successful
    if response.code == '200'
    puts "Stream started successfully."
    puts "Response headers: #{response.to_hash}"
    puts "Streaming content:"

    # Read the chunked response
    response.read_body do |chunk|
        # The response is newline-separated JSON objects
        chunk.each_line do |line|
        line = line.strip
        next if line.empty?

        begin
            json = JSON.parse(line)

            if json['topic_id']
            puts "--- Context Received ---"
            puts "Topic ID: #{json['topic_id']}"
            puts "Bot User ID: #{json['bot_user_id']}"
            puts "Agent ID: #{json['agent_id']}"
            elsif json['partial']
            # Stream the partial content
            print json['partial']
            elsif json['event'] == 'tool_calls'
            puts "--- Tool Call Received ---"
            puts JSON.pretty_generate(json)
            # Here you would handle tool execution and resume
            # For this example, we just print it
            end

            # puts "<new word>"
        rescue JSON::ParserError => e
            puts "Error parsing JSON: #{e.message}"
            puts "Raw line: #{line}"
        end
        end
    end
    puts "--- Stream Finished ---"

    else
    puts "Error: #{response.code} #{response.message}"
    puts "Response body: #{response.body}"
    end
end

[/details]

注意事项

  • 如果您希望以新的暂存用户身份进行对话,请将 unique_user_id 和 preferred_username 作为新期望的用户名传入,并跳过 username 字段。
  • 如果您希望使用现有用户进行对话,请传入该用户的 username,并跳过 unique_user_id 和 preferred_username 字段。