简介

Assistants API 允许您在自己的应用程序中构建 AI 助手。助手通过指令,利用模型、工具和知识来响应用户查询。Assistants 主要分为几大模块:

类型

支持的功能

Name

助理的名称。

Instructions

指示,预制的一些提示词,比如角色设定。

Model

可以指定任何 GPT-3.5 或 GPT-4 型号。检索工具至少需要 gpt-3.5-turbo-1106(支持较新版本)或 gpt-4-turbo-preview 型号。

Tools

包含 Code Interpreter、

Retrieval

检索工具至少需要 gpt-3.5-turbo-1106(支持较新版本)或 gpt-4-turbo-preview 型号。

Functions

API 允许您定义自定义函数签名,其行为与我们的函数调用功能类似。

前提条件

注意:

  1. 体验官方的 assistant 工具尽量使用付费账号,如果是非付费账号,能使用的 token 和 gpt 模型均有限制。体验会比较差。
  2. 付费账号必须要绑定国外的信用卡。

操作步骤

首先是界面操作步骤:

  1. 创建一个智能助理,或者复用已经创建好的助理。
  2. 创建一个线程。
  3. 给线程添加对应的信息。
  4. 执行该信息。
  5. 查看执行状态。
  6. 查看助理的返回信息。
代码调用

注意:使用代码调用前需要了解ChatGPT的API使用。

而代码调用步骤与界面操作步骤基本一致,代码如下:

import time
from openai import OpenAI
import os
# code interpreter的使用
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
# 1. 创建一个助理,或者复用已经创建好的助理。
assistant = "助理id"
# 2. 创建一个线程
thread = client.beta.threads.create()
# 3. 创建一条消息
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
)
# 4. 提问
run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant,
    instructions="You are a personal math tutor. When asked a math question, write and run code to answer the question.")
# 5. 循环查询问题是否已经解决完成
def wait_on_run(run, thread):
    while run.status == "queued" or run.status == "in_progress":
        run = client.beta.threads.runs.retrieve(
            thread_id=thread.id,
            run_id=run.id,
        )
        time.sleep(0.5)
    return run
wait_on_run(run, thread)
# 6. 获取历史消息
messages = client.beta.threads.messages.list(thread_id=thread.id).model_dump_json(indent=2)
print(messages)
  • 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.
工具介绍
  • Code Interpreter:ChatGPT 会自动使用一些内置的函数,比如数学运算等。
  • Knowledge Retrieval:上传文件,进行一次知识检索。
  • Function calling:调用外部的函数。

相关资料

  • 官方文档说明
  • 官方体验地址