MiniMax
  1. Assistants 接口
MiniMax
  • 公告通知
  • 产品定价
  • 概述
  • FAQ
  • 大模型介绍
    • 文本大模型
    • 语音大模型
  • 接入说明
    • 新手指南
    • 速率说明
  • 开发指南
    • 快速开始
  • 文本大模型接口
    • ChatCompletion Pro(对话)
      • 概述
      • ChatCompletion Pro API 文档
        • ChatCompletion Pro API
        • 示例对话功能
        • 限制返回格式功能(glyph)
        • 函数调用功能(function calling)
        • 插件功能(plugins)
        • 知识库检索功能(retrieval)
    • ChatCompletion(对话)
      • 概述
      • ChatCompletion 快速接入
      • ChatCompletion 调优指南
      • ChatCompletion API 文档
        • ChatCompletion API
        • 知识库检索功能(retrieval)
  • Assistants 接口
    • Assistants 操作指南
    • Assistans API 文档
      • Assistant
        • 创建 Assistant
        • 检索 Assistants
        • 删除 assistant
        • 查看 assistant 列表
      • Assistant File
        • 创建 assistant 文件
        • 检索 assistant 关联的文件
        • 列出 assistant 文件
      • Thread
        • 创建 thread
        • 检索 thread
      • Message
        • 创建 message
        • 检索 message
        • message 列表
      • Run
        • 创建 run
        • 检索 run
        • 列表 run
        • Submit tool outputs to run
      • Run Step
        • 检索 run step
        • 列表 run step
  • File(文档)
    • File(文档)
      GET
    • Upload 接口
      GET
    • Retrieve 接口
      GET
    • Delete 接口
      POST
    • RetrieveContent 接口
      GET
  • Retrieval(知识库检索)
    • 新建知识库
      POST
    • 删除知识库
      POST
    • 查看知识库详情
      GET
    • 查看知识库列表
      GET
    • 增加知识库文档
      POST
    • 删除知识库文档
      POST
    • 修改知识库文档
      POST
    • 查看知识库文档
      GET
    • 检索 Chatcompletion
      POST
    • 检索 Chatcompletion pro
      POST
  • 微调
    • Finetune 操作指南
    • Finetune API文档
      • 创建微调任务
      • 列出微调任务
      • 检索微调任务
      • 删除微调任务
      • 列出微调事件
      • 列举微调模型
      • 查询微调模型
      • 删除微调模型
  • 向量化
    • Embeddings(向量化)
  • 语音大模型接口
    • T2A (语音生成)
      • T2A 快速接入
      • T2A API 接口
        • T2A API接口
        • 字典功能(Dictionary)
    • T2A pro(长文本语音生成)
      • T2A Pro 快速接入
      • T2A Pro API 接口
      • 字典功能(Dictionary)
    • T2A large(异步超长文本语音生成)
      • T2A Large 快速接入
      • T2A Large API 接口
        • T2A Large API 接口
        • 字典功能(Dictionary)
    • T2A Stream(流式语音生成)
      • T2A Stream(流式语音生成)
      • 字典功能(Dictionary)
    • 快速复刻(Voice Cloning)
      • 上传文件
      • 音频复刻
  • 有声内容创作
    • Role Classification (文本角色分类)
      • 创建并异步运行角色识别任务
      • 查询角色识别任务
    • Role Audio Generation (角色音频生成)
      • 角色音频生成
  1. Assistants 接口

Assistants 操作指南

仔细阅读本文档,您可以了解如何构建并运行一个Assistant。
关于Assistants API的详细信息,您可以通过阅读Assistants API文档来进行了解。

一、概述#

通过Assistants API您可以构建一个Assistant,该Assistant可以遵从指令,使用大模型和工具调用来响应用户的查询。
目前Assistants API支持以下四种类型的工具:
Code Interpreter(代码解释器)
Retrieval(知识库检索)
Function Calling(函数调用)
Web Search(网络搜索)
您可以通过以下步骤来构建一个Assistant:
通过Assistants API创建一个assistant id并选择模型,如有需要可考虑关联上传好的file并开启Code Interpreter、Retrieval和Function calling、Web Search等工具;
注:仅在该步骤关联file并开启retrieval时,retrieval才会生效,并会对向量存储进行计费;
在用户发送请求时,通过Thread API创建一个thread id,并通过Message向thread id创建并添加一条message id;
使用thread id关联assistant id创建run,运行以得到请求回复,有需要时该Assistant会自动使用file调用此前启用的相关工具;
通过retrieve run 检索run的完成状态,如已完成,可以通过list message查看回复

二、操作步骤#

您可以按照以下的详细步骤,一步一步地构建一个Assistant。

1、创建assistant#

可以通过配置以下参数,构建一个assistant得到对应的assistants id,以响应用户的请求:
instructions:代表的是对assistant的背景设定;
model:该接口目前只支持abab5.5;
tools:该接口支持Code Interpreter(代码解释器)、Retrieval(知识库检索)、Function Calling(函数调用)、Web Search(网络搜索)功能,并支持开启多个工具。
如果使用了Retrieval,在创建assistant时可能会消耗几分钟的时间用于进行向量化和入库,在创建run时需要等待assistant创建完成,可以通过retrieve assistant 查看创建状态。

1.1 请求示例#

import requests
import json

url = "https://api.minimax.chat/v1/assistants/create?GroupId=$GroupId"

payload = json.dumps({
  "model": "abab5.5",
  "name": "小说解读专家",
  "description": "小说解读专家,用在小说解读场景中回答用户问题",
  "instructions": "是一个小说解读专家,读过万卷书,了解小说里的各种细致情节,另外也非常热心,会热情的帮读者解答小说里的问题",
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  },
  "tools": [
    {
      "type": "code_interpreter"
    },
    {
      "type": "retrieval"
    },
    {
      "type": "web_search"
    }
  ]
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json',
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/assistants/create?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "model": "abab5.5",
    "name": "小说解读专家",
    "description": "小说解读专家,用在小说解读场景中回答用户问题",
    "instructions": "是一个小说解读专家,读过万卷书,了解小说里的各种细致情节,另外也非常热心,会热情的帮读者解答小说里的问题",
    "metadata": {
        "key1": "value1",
        "key2": "value2"
    },
    "tools": [
        {"type":"code_interpreter"},
        {"type":"retrieval"},
        {"type":"web_search"}
    ]
}'

2、创建thread#

我们建议在用户发出请求之后立刻为assistant id创建一个thread id,并添加message,在此thread id中传递关于用户请求的上下文和文件。在后续的请求中,如果您判断是一次连续的对话,则无需自己拼接上下文,只需将最新的message添加到对应的thread id 即可得到包含了thread id 历史上下文的回复,历史上下文超过我们会帮您自动截断。另外,thread没有数值限制,您可以向thread添加任意数量的message。

2.1 请求示例#

import requests
import json

url = "https://api.minimax.chat/v1/threads/create?GroupId=$GroupId"

payload = json.dumps({
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  }
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json',
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/threads/create?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "metadata": {
        "key1": "value1",
        "key2": "value2"
    }
}'

3、添加message#

3.1 向thread添加message#

message包含了文本,以及允许用户按照自己的需求上传file。message需要添加到特定的thread中。
在message层级添加的文件,仅支持code interpreter工具的使用,如要使用retrieval工具则需在assistants层级添加文件,方可使用。
目前支持通过message添加文本content,此外一个message中最多可附加20个文件。

3.2 请求示例#

import requests
import json

url = "https://api.minimax.chat/v1/threads/messages/add?GroupId=$GroupId"

payload = json.dumps({
  "thread_id": "$Thread_Id",
  "role": "user",
  "content": "在倚天屠龙记中,无俗念词的作者是谁?",
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  },
  "file_ids": [
      "${file id}"
  ]
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json',
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/threads/messages/add?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "thread_id": "$Thread_Id",
    "role": "user",
    "content": "在倚天屠龙记中,无俗念词的作者是谁?",
    "metadata": {
        "key1": "value1",
        "key2": "value2"
    },
    "file_ids": [
      "${file id}"
  ]
}'

3.3 列表message#

您可以在thread中列出message,此时您可以看到您的message已被添加进thread。

3.4 请求示例#

import requests
import json

url = "https://api.minimax.chat/v1/threads/messages/list?GroupId=$GroupId"

payload = json.dumps({
  "thread_id": "$Thread_Id"
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json',
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
curl --location --request GET 'https://api.minimax.chat/v1/threads/messages/list?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
"thread_id": "$Thread_Id"
}'

4、运行assistant#

要使创建的assistant响应用户的请求消息,您还需要创建一个run来运行,请确保您的assistant id和thread id 都已创建完成。
此时assistant将会读取thread并决定是否调用工具(若构建assistant时工具已启用)。
随着run的进行,assistant会将模型回复的message添加到thread中。

4.1 请求示例#

import requests
import json

url = "https://api.minimax.chat/v1/threads/run/create?GroupId=$GroupId"

payload = json.dumps({
  "thread_id": "$Thread_Id",
  "assistant_id": "$Assistant_Id"
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json',
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/threads/run/create?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "thread_id": "$Thread_Id",
    "assistant_id": "$Assistant_Id"
}'

5、检查运行状态#

在默认的情况下,创建的run将进入排队状态。您可以定期检索run id的运行状态,以查看它是否运行完成。

5.1 请求示例#

import requests
import json

url = "https://api.minimax.chat/v1/threads/run/retrieve?GroupId=$GroupId"

payload = json.dumps({
  "thread_id": "$Thread_Id",
  "run_id": "$Run_Id"
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
curl --location --request GET 'https://api.minimax.chat/v1/threads/run/retrieve?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "thread_id": "$Thread_Id",
    "run_id": "$Run_Id"
}'

6、查看回复内容#

创建的run id运行完成后,您可以列出assistant添加到thread的用户message来查看请求回复的内容。

6.1 请求示例#

import requests
import json

url = "https://api.minimax.chat/v1/threads/messages/list?GroupId=$GroupId"

payload = json.dumps({
  "thread_id": "$Thread_Id"
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
curl --location --request GET 'https://api.minimax.chat/v1/threads/messages/list?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "thread_id": "$Thread_Id"
}'

7、完整示例#

7.1 Retrieval示例#

包含文档上传、创建assistant、创建thread、添加message、运行assistant、检查运行状态和查看回复内容等流程。
import requests
import json
import time

# 请使用自己的groupid和api key
GroupId = ${group_id}
headers = {
    'Authorization': 'Bearer ${api_key}',
    'Content-Type': 'application/json'
}
headers_retrieval = {
    'Authorization': 'Bearer  ${api_key}',
    'authority': 'api.minimax.chat',
}


# 流程零:上传文档
def create_file():
    url = f"https://api.minimax.chat/v1/files/upload?GroupId={GroupId}"
    data = {
        'purpose': 'assistants'
    }

    files = {
        'file': open('./倚天屠龙记.txt', 'rb')
    }
    response = requests.post(url, headers=headers_retrieval, data=data,files=files)
    return response.json()

#流程一:创建助手
def create_assistant(file_id):
    url = f"https://api.minimax.chat/v1/assistants/create?GroupId={GroupId}"
    payload = json.dumps({
        "model": "abab5.5",# 模型版本,目前仅支持abab5.5
        "name": "小说专家", # 助手名称
        "description": "小说专家,用在小说解读场景中回答用户问题", # 助手描述
        "instructions": "是一个小说专家,读过万卷书,了解小说里的各种细致情节,另外也非常热心,会热情的帮读者解答小说里的问题",# 助手设定(即bot_setting)
        "file_ids": [
            str(file_id)
        ],
        #"tools": [{"type": "code_interpreter"}, {"type": "web_search"}]
        "tools": [{"type": "retrieval"},{"type": "web_search"}]

    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程二:创建线程
def create_thread():
    url = f"https://api.minimax.chat/v1/threads/create?GroupId={GroupId}"
    response = requests.post( url, headers=headers)
    return response.json()

# 流程三:往线程里添加信息
def add_message_to_thread(thread_id):
    url = f"https://api.minimax.chat/v1/threads/messages/add?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id,
        "role": "user",
        "content": "在倚天屠龙记中,无俗念词的作者是谁?",
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程四:使用助手处理该线程
def run_thread_with_assistant(thread_id, assistant_id):
    time.sleep(200) #创建assistants进行向量化以及存储时需要一定的时间,可以考虑使用retrieve assistant检索是否创建成功
    url = f"https://api.minimax.chat/v1/threads/run/create?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id,
        "assistant_id": assistant_id
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程五:获取线程中助手处理出的新信息
def get_thread_messages(thread_id):
    url = f"https://api.minimax.chat/v1/threads/messages/list?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id
    })
    response = requests.get(url, headers=headers, data=payload)
    return response.json()
def check_thread_run_status(thread_id, run_id):
    url = f"https://api.minimax.chat/v1/threads/run/retrieve?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": str(thread_id),
        "run_id": str(run_id)
    })
    completed = False
    while not completed:
        response = requests.request("GET", url, headers=headers, data=payload)
        if response.status_code == 200:
            response_data = response.json()
            status = response_data.get('status', '')
            print(f"Status: {status}")
            if status == 'completed':
                completed = True
                print("Process completed, exiting loop.")
            else:
                time.sleep(2)  # 如果状态不是completed,等待两秒后重新请求
        else:
            print(f"Error: {response.status_code}")
            break  # 如果请求失败,退出循环
    return completed
# 主流程
def main():
    # 上传文档
    file_response = create_file()
    file_id = file_response.get('file', {}).get('file_id')
    print("file_id:",file_id)

    # 创建助手
    assistant_response = create_assistant(file_id)
    assistant_id = assistant_response.get('id', '')
    print("assistant_id:",assistant_id)

    # 创建线程
    thread_response = create_thread()
    thread_id = thread_response.get('id', '')
    print("thread_id:",thread_id)

    # 往线程里添加信息
    add_message_to_thread(thread_id)  # 不保存返回值

    # 使用助手处理该线程
    run_response = run_thread_with_assistant(thread_id, assistant_id)
    run_id = run_response.get('id', '')  # 假设run_response是正确的JSON响应,并包含run_id
    print("run_id:",run_id)

    # 检查助手处理状态
    if check_thread_run_status(thread_id, run_id):
        # 获取线程中助手处理出的新信息
        thread_messages_response = get_thread_messages(thread_id)
        # 打印JSON数据
        print(json.dumps(thread_messages_response, indent=4, ensure_ascii=False))

if __name__ == "__main__":
    main()
输出示例
file_id: 891849227529
assistant_id: asst_9f399f168c445093853ba08332346e
thread_id: thread_8578198eb840cbaec7344b56ae2f8f
run_id: run_080adf40e20749b34e59225326f3
Status: in_progress
Status: in_progress
Status: completed
Process completed, exiting loop.
{
    "object": "list",
    "data": [
        {
            "id": "msg_ff35404520504e1787b08c74058b928d",
            "object": "message",
            "created_at": 1703419324,
            "thread_id": "thread_8578198eb840cbaec7344b56ae2f8f",
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "在倚天屠龙记中,无俗念词的作者是谁?",
                        "annotations": []
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_9f399f168c445093853ba08332346e",
            "run_id": "run_080adf40e20749b3914e5109225326f3",
            "metadata": null
        },
        {
            "id": "msg_01c12f5874174e87950bfa5f4dcd0d3c",
            "object": "message",
            "created_at": 1703419528,
            "thread_id": "thread_8578198eb840cbaec7344b56ae2f8f",
            "role": "ai",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "在《倚天屠龙记》中,无俗念词的作者是南宋末年的一位武学名家,有道之士,他姓丘,名处机,道号长春子,名列全真七子之一,是全真教中出类拔萃的人物。【1†source】",
                        "annotations": [
                            {
                                "type": "file_citation",
                                "text": "【1†source】",
                                "start_index": 71,
                                "end_index": 81,
                                "file_citation": {
                                    "file_id": "",
                                    "quote": "###《倚天屠龙记》\n\n###第01章 天涯思君不可忘\n\n“春游浩荡,是年年寒食,梨花时节。白锦无纹香烂漫,玉树琼苞堆雪。静夜沉沉,浮光霭霭,冷浸溶溶月。人间天上,烂银霞照通彻。\n\n浑似姑射真人,天姿灵秀,意气殊高洁。万蕊参差谁信道,不与群芳同列。浩气清英,仙才卓荦,下土难分别。瑶台归去,洞天方看清绝。”\n\n作这一首无俗念词的,乃南宋末年一位武学名家,有道之士。此人姓丘,名处机,道号长春子,名列全真七子之一,是全真教中出类拔萃的人物。词品评论此词道:“长春,世之所谓仙人也,而词之清拔如此”。\n\n这首词诵的似是梨花,其实同中真意却是赞誉一位身穿白衣的美貌少女,说她“浑似姑射真人,天姿灵秀,意气殊高洁”,又说她“浩气清英,仙才卓荦”,“不与群芳同列”。词中所颂这美女,乃古墓派传人小龙女。她一生爱穿白衣,当真如风拂玉树,雪裹琼苞,兼之生性清冷,实当得起“冷浸溶溶月”的形容,以“无俗念”三字赠之,可说十分贴切。长春子丘处机和她在终南山上比邻而居,当年一见,便写下这首词来。\n\n这时丘处机逝世已久,小龙女也已嫁与神雕大侠杨过为妻。在河南少室山山道之上,却另有一个少女,正在低低念诵此词。"
                                }
                            }
                        ]
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_9f399f168c445093853ba08332346e",
            "run_id": "run_080adf40e20749b34e59225326f3",
            "metadata": null
        }
    ],
    "first_id": "msg_ff35404520504e1787b08c74058b928d",
    "last_id": "msg_01c12f5874174e87950bfa5f4dcd0d3c",
    "base_resp": {
        "status_code": 0,
        "status_msg": "success"
    }
}

7.2 Code Interpreter示例#

请求示例
包含文档上传、创建assistant、创建thread、添加message、运行assistant、检查运行状态和查看回复内容等流程。
import requests
import json
import time

# 请使用自己的groupid和api key
GroupId = ${group_id}
headers = {
    'Authorization': 'Bearer ${api_key}',
    'Content-Type': 'application/json'
}
headers_retrieval = {
    'Authorization': 'Bearer  ${api_key}',
    'authority': 'api.minimax.chat',
}


# 流程零:上传文档
def create_file():
    url = f"https://api.minimax.chat/v1/files/upload?GroupId={GroupId}"
    data = {
        'purpose': 'assistants'
    }

    files = {
        'file': open('./M国gdp.csv', 'rb')
    }
    response = requests.post(url, headers=headers_retrieval, data=data,files=files)
    return response.json()

#流程一:创建助手
def create_assistant(file_id):
    url = f"https://api.minimax.chat/v1/assistants/create?GroupId={GroupId}"
    payload = json.dumps({
        "model": "abab5.5",# 模型版本,目前仅支持abab5.5
        "name": "数据分析师", # 助手名称
        "description": "数据分析师,用在数据分析场景", # 助手描述
        "instructions": "是一个数据分析师,善于读取文件进行数据分析,并能严谨精准的给出分析结论",# 助手设定(即bot_setting)
        "file_ids": [
            str(file_id)
        ],
        #"tools": [{"type": "code_interpreter"}, {"type": "web_search"}]
        "tools": [{"type": "code_interpreter"},{"type": "web_search"}]

    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程二:创建线程
def create_thread():
    url = f"https://api.minimax.chat/v1/threads/create?GroupId={GroupId}"
    response = requests.post( url, headers=headers)
    return response.json()

# 流程三:往线程里添加信息
def add_message_to_thread(thread_id):
    url = f"https://api.minimax.chat/v1/threads/messages/add?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id,
        "role": "user",
        "content": "M国的2000-2005年的gdp趋势是怎么样的,2005同比增长了还是下降了?",
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程四:使用助手处理该线程
def run_thread_with_assistant(thread_id, assistant_id):
    time.sleep(200) #创建assistants进行向量化以及存储时需要一定的时间,可以考虑使用retrieve assistant检索是否创建成功
    url = f"https://api.minimax.chat/v1/threads/run/create?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id,
        "assistant_id": assistant_id
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程五:获取线程中助手处理出的新信息
def get_thread_messages(thread_id):
    url = f"https://api.minimax.chat/v1/threads/messages/list?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id
    })
    response = requests.get(url, headers=headers, data=payload)
    return response.json()
def check_thread_run_status(thread_id, run_id):
    url = f"https://api.minimax.chat/v1/threads/run/retrieve?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": str(thread_id),
        "run_id": str(run_id)
    })
    completed = False
    while not completed:
        response = requests.request("GET", url, headers=headers, data=payload)
        if response.status_code == 200:
            response_data = response.json()
            status = response_data.get('status', '')
            print(f"Status: {status}")
            if status == 'completed':
                completed = True
                print("Process completed, exiting loop.")
            else:
                time.sleep(2)  # 如果状态不是completed,等待两秒后重新请求
        else:
            print(f"Error: {response.status_code}")
            break  # 如果请求失败,退出循环
    return completed
# 主流程
def main():
    # 上传文档
    file_response = create_file()
    file_id = file_response.get('file', {}).get('file_id')
    print("file_id:",file_id)

    # 创建助手
    assistant_response = create_assistant(file_id)
    assistant_id = assistant_response.get('id', '')
    print("assistant_id:",assistant_id)

    # 创建线程
    thread_response = create_thread()
    thread_id = thread_response.get('id', '')
    print("thread_id:",thread_id)

    # 往线程里添加信息
    add_message_to_thread(thread_id)  # 不保存返回值

    # 使用助手处理该线程
    run_response = run_thread_with_assistant(thread_id, assistant_id)
    run_id = run_response.get('id', '')  # 假设run_response是正确的JSON响应,并包含run_id
    print("run_id:",run_id)

    # 检查助手处理状态
    if check_thread_run_status(thread_id, run_id):
        # 获取线程中助手处理出的新信息
        thread_messages_response = get_thread_messages(thread_id)
        # 打印JSON数据
        print(json.dumps(thread_messages_response, indent=4, ensure_ascii=False))

if __name__ == "__main__":
    main()
输出示例
file_id: 892087299164
assistant_id: asst_e61ea32224284aacc40b36a6d61b
thread_id: thread_b6e8ef88333c4f148a84a5f45606
run_id: run_3c184429d47f414294403fc59c560
Status: in_progress
Status: in_progress
Status: in_progress
Status: in_progress
Status: in_progress
Status: completed
Process completed, exiting loop.
{
    "object": "list",
    "data": [
        {
            "id": "msg_d8ca1b4cd4644f91a75807b5549a17",
            "object": "message",
            "created_at": 1703418313,
            "thread_id": "thread_b6e8ef88334f118c248a84a5f45606",
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "M国的2000-2005年的gdp趋势是怎么样的,2005同比增长了还是下降了?",
                        "annotations": []
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_e61ea32224284aacc40b36a6d61b",
            "run_id": "run_3c184429d47f414294403fc59c560",
            "metadata": null
        },
        {
            "id": "msg_d6166cd827134c93afb5c3c49204a784",
            "object": "message",
            "created_at": 1703418523,
            "thread_id": "thread_b6e8ef88333c4f148a84a5f45606",
            "role": "ai",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "根据提供的数据,M国的GDP在2000年至2005年间的趋势如下:\n\n- 2000年:GDP为1\n- 2001年:GDP为2\n- 2002年:GDP为3\n- 2003年:GDP为4\n- 2004年:GDP为5\n- 2005年:GDP为6\n\n因此,2005年的GDP相比2004年增长了。",
                        "annotations": []
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_e61ea32224284aacc40b36a6d61b",
            "run_id": "run_3c184429d47f414294403fc59c560",
            "metadata": null
        }
    ],
    "first_id": "msg_d8ca1b4cd4644f91a757f807b5549a17",
    "last_id": "msg_d6166cd827134c93afb5c3c49204a784",
    "base_resp": {
        "status_code": 0,
        "status_msg": "success"
    }
}

7.3 Web Search示例#

请求示例
包含文档上传、创建assistant、创建thread、添加message、运行assistant、检查运行状态和查看回复内容等流程。
import json
import time

import requests

# # 请使用自己的groupid和api key
# GroupId = ${group_id}
# headers = {
#     'Authorization': 'Bearer ${api_key}',
#     'Content-Type': 'application/json'
# }

#流程一:创建助手
def create_assistant():
    url = f"https://api.minimax.chat/v1/assistants/create?GroupId={GroupId}"
    payload = json.dumps({
        "model": "abab5.5",# 模型版本,目前仅支持abab5.5
        "name": "AI搜索引擎", # 助手名称
        "description": "AI搜索引擎,用在搜索场景", # 助手描述
        "instructions": "是一个AI搜索引擎,擅长利用网络搜索参考资料回答用的问题",# 助手设定(即bot_setting)
        #"tools": [{"type": "code_interpreter"}, {"type": "web_search"}]
        "tools": [{"type": "web_search"}]

    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程二:创建线程
def create_thread():
    url = f"https://api.minimax.chat/v1/threads/create?GroupId={GroupId}"
    response = requests.post( url, headers=headers)
    return response.json()

# 流程三:往线程里添加信息
def add_message_to_thread(thread_id):
    url = f"https://api.minimax.chat/v1/threads/messages/add?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id,
        "role": "user",
        "content": "上海迪士尼2024圣诞节会举办什么活动?",
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程四:使用助手处理该线程
def run_thread_with_assistant(thread_id, assistant_id):
    time.sleep(2) #创建assistants进行向量化以及存储时需要一定的时间,可以考虑使用retrieve assistant检索是否创建成功
    url = f"https://api.minimax.chat/v1/threads/run/create?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id,
        "assistant_id": assistant_id
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()

# 流程五:获取线程中助手处理出的新信息
def get_thread_messages(thread_id):
    url = f"https://api.minimax.chat/v1/threads/messages/list?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id
    })
    response = requests.get(url, headers=headers, data=payload)
    return response.json()

def check_thread_run_status(thread_id, run_id):
    url = f"https://api.minimax.chat/v1/threads/run/retrieve?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": str(thread_id),
        "run_id": str(run_id)
    })
    completed = False
    while not completed:
        response = requests.request("GET", url, headers=headers, data=payload)
        if response.status_code == 200:
            response_data = response.json()
            status = response_data.get('status', '')
            print(f"Status: {status}")
            if status == 'completed':
                completed = True
                print("Process completed, exiting loop.")
            else:
                time.sleep(2)  # 如果状态不是completed,等待两秒后重新请求
        else:
            print(f"Error: {response.status_code}")
            break  # 如果请求失败,退出循环
    return completed

def post_process_message(message):
    message_content = message["content"][0]["text"]
    annotations = message_content["annotations"]
    citations = []

    # Iterate over the annotations and add footnotes
    for index, annotation in enumerate(annotations):
        # Replace the text with a footnote
        message_content["value"] = message_content["value"].replace(annotation["text"], f' [{index}]')
        # Gather citations based on annotation attributes
        if annotation["type"] == "file_citation":
            citations.append(f'[{index}] {annotation["file_citation"]["quote"]}')
        elif annotation["type"] == "web_citation":
            res = f"[{index}]"
            if annotation["web_citation"]["url"]:
                res += f' 网址:{annotation["web_citation"]["url"]}'
            if annotation["web_citation"]["quote"]:
                res += f' {annotation["web_citation"]["quote"]}'
            citations.append(res)

    message_content["value"] += '\n' + '\n'.join(citations)
    print(message_content["value"])


# 主流程
def main():
    # 创建助手
    assistant_response = create_assistant()
    assistant_id = assistant_response.get('id', '')
    print("assistant_id:",assistant_id)

    # 创建线程
    thread_response = create_thread()
    thread_id = thread_response.get('id', '')
    print("thread_id:",thread_id)

    # 往线程里添加信息
    add_message_to_thread(thread_id)  # 不保存返回值

    # 使用助手处理该线程
    run_response = run_thread_with_assistant(thread_id, assistant_id)
    run_id = run_response.get('id', '')  # 假设run_response是正确的JSON响应,并包含run_id
    print("run_id:",run_id)

    # 检查助手处理状态
    if check_thread_run_status(thread_id, run_id):
        # 获取线程中助手处理出的新信息
        thread_messages_response = get_thread_messages(thread_id)
        # 打印JSON数据
        print(json.dumps(thread_messages_response, indent=4, ensure_ascii=False))
        # 打印后处理后的信息
        print(post_process_message(thread_messages_response["data"][-1]))

if __name__ == "__main__":
    main()
输出示例
assistant_id: asst_5e65f2aae3a044f2b9c26012aaed1a95
thread_id: thread_4f8d5e7dfd894d2186fe3baac45c0085
run_id: run_ef18b2b8185744c3a58453dc1020f497
Status: in_progress
Status: in_progress
Status: in_progress
Status: in_progress
Status: in_progress
Status: in_progress
Status: in_progress
Status: in_progress
Status: in_progress
Status: completed
Process completed, exiting loop.
{
    "object": "list",
    "data": [
        {
            "id": "msg_66a208c1de5d49ab88b664adef704364",
            "object": "message",
            "created_at": 1703579772,
            "thread_id": "thread_4f8d5e7dfd894d2186fe3baac45c0085",
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "上海迪士尼2024圣诞节会举办什么活动?",
                        "annotations": []
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_5e65f2aae3a044f2b9c26012aaed1a95",
            "run_id": "run_ef18b2b8185744c3a58453dc1020f497",
            "metadata": null
        },
        {
            "id": "msg_8f428bd21e4b403182ab0c5f6ea47781",
            "object": "message",
            "created_at": 1703579795,
            "thread_id": "thread_4f8d5e7dfd894d2186fe3baac45c0085",
            "role": "ai",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "2024年上海迪士尼的圣诞节活动主要包括以下部分:\n\n1. 米奇、达菲和朋友们一起点亮了魔法奇观环绕的圣诞大树,在烟花的照耀下,照亮了大家的童话梦想。这一活动会在上海迪士尼度假区圣诞季期间(2023年11月23日至2024年1月1日)举行。\n\n2. 圣诞树寻踪活动,游客可以加入我们庆祝的行列,走入暖心的童话故事,漫步小镇街头,一起寻踪不一样的圣诞奇妙。完成圣诞树寻踪任务后,即可获得一份精美小礼物。圣诞树寻踪小屋运营时间为周一至周四: 12:00 - 19:00; 周五至周日及2023年12月25日、2024年1月1日: 11:00 - 19:00;惊喜兑奖小屋运营时间为周一至周四 12:00 - 20:00。\n\n3. 迪士尼小镇也将变身童话圣诞世界,2023年11月23日起至2024年1月1日,米奇和朋友们、达菲和朋友们将换上圣诞新造型。\n\n4. 「奇妙集章 点亮童话圣诞」惊喜上线,完成任务,点亮印章,叠加3枚印章图案,就能解锁圣诞好礼【4†source】。\n\n5. 「迪士尼冬日奇幻冰雪节」将在2023年11月10日至2024年2月24日举行,这一活动将呈现梦幻冬日奇境,让即将到来的冬日暖意融融、爱意满满【5†source】。\n\n以上活动具体内容和时间可能会根据实际安排有所变动,建议您提前关注上海迪士尼度假区官方网站或官方社交媒体获取最新信息。",
                        "annotations": [
                            {
                                "type": "web_citation",
                                "text": "【4†source】",
                                "start_index": 454,
                                "end_index": 464,
                                "web_citation": {
                                    "url": "https://www.weibo.com/5200478600/NtfYcexxE",
                                    "quote": "#上海迪士尼童话圣诞# 🎄2023年11月23日起至2024年1月1日,上海迪士尼圣诞季来袭! 🌟米奇和朋友们、达菲和朋友们将换上圣诞新造型 💡达菲和玲娜贝儿将首次加入圣诞树点灯仪式! 🎉迪士尼小镇也将变身童话圣诞世界 ️"
                                }
                            },
                            {
                                "type": "web_citation",
                                "text": "【5†source】",
                                "start_index": 540,
                                "end_index": 550,
                                "web_citation": {
                                    "url": "https://www.weibo.com/5200478600/NuVFF7Enb",
                                    "quote": "#上海迪士尼童话圣诞# 🎉2023年12月1日起至2024年1月1日,「奇妙集章 点亮童话圣诞」惊喜上线啦! 完成任务,点亮印章,叠加3枚印章图案,就能解锁圣诞好礼,快来查收这份「圣诞集章攻略」吧~ 🎄童话圣诞正在进行中,等你前来集章,一起点亮属于你的节日祝愿吧~"
                                }
                            }
                        ]
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_5e65f2aae3a044f2b9c26012aaed1a95",
            "run_id": "run_ef18b2b8185744c3a58453dc1020f497",
            "metadata": null
        }
    ],
    "first_id": "msg_66a208c1de5d49ab88b664adef704364",
    "last_id": "msg_8f428bd21e4b403182ab0c5f6ea47781",
    "base_resp": {
        "status_code": 0,
        "status_msg": "success"
    }
}
2024年上海迪士尼的圣诞节活动主要包括以下部分:

1. 米奇、达菲和朋友们一起点亮了魔法奇观环绕的圣诞大树,在烟花的照耀下,照亮了大家的童话梦想。这一活动会在上海迪士尼度假区圣诞季期间(2023年11月23日至2024年1月1日)举行。

2. 圣诞树寻踪活动,游客可以加入我们庆祝的行列,走入暖心的童话故事,漫步小镇街头,一起寻踪不一样的圣诞奇妙。完成圣诞树寻踪任务后,即可获得一份精美小礼物。圣诞树寻踪小屋运营时间为周一至周四: 12:00 - 19:00; 周五至周日及2023年12月25日、2024年1月1日: 11:00 - 19:00;惊喜兑奖小屋运营时间为周一至周四 12:00 - 20:00。

3. 迪士尼小镇也将变身童话圣诞世界,2023年11月23日起至2024年1月1日,米奇和朋友们、达菲和朋友们将换上圣诞新造型。

4. 「奇妙集章 点亮童话圣诞」惊喜上线,完成任务,点亮印章,叠加3枚印章图案,就能解锁圣诞好礼 [0]。

5. 「迪士尼冬日奇幻冰雪节」将在2023年11月10日至2024年2月24日举行,这一活动将呈现梦幻冬日奇境,让即将到来的冬日暖意融融、爱意满满 [1]。

以上活动具体内容和时间可能会根据实际安排有所变动,建议您提前关注上海迪士尼度假区官方网站或官方社交媒体获取最新信息。
[0] 网址:https://www.weibo.com/5200478600/NtfYcexxE #上海迪士尼童话圣诞# 🎄2023年11月23日起至2024年1月1日,上海迪士尼圣诞季来袭! 🌟米奇和朋友们、达菲和朋友们将换上圣诞新造型 💡达菲和玲娜贝儿将首次加入圣诞树点灯仪式! 🎉迪士尼小镇也将变身童话圣诞世界 ️
[1] 网址:https://www.weibo.com/5200478600/NuVFF7Enb #上海迪士尼童话圣诞# 🎉2023年12月1日起至2024年1月1日,「奇妙集章 点亮童话圣诞」惊喜上线啦! 完成任务,点亮印章,叠加3枚印章图案,就能解锁圣诞好礼,快来查收这份「圣诞集章攻略」吧~ 🎄童话圣诞正在进行中,等你前来集章,一起点亮属于你的节日祝愿吧~

7.4 Function calling示例#

请求示例
包含文档上传、创建assistant、创建thread、添加message、运行assistant、检查运行状态和查看回复内容等流程。
import json
import time

import requests

# 请使用自己的groupid和api key
GroupId = "${GroupId}"
headers = {
    'Authorization': 'Bearer ${api_key}',
    'Content-Type': 'application/json'
}


#流程一:创建助手
def create_assistant():
    url = f"https://api.minimax.chat/v1/assistants/create?GroupId={GroupId}"
    payload = json.dumps({
        "model": "abab5.5",# 模型版本,目前仅支持abab5.5
        "name": "function专家", # 助手名称
        "description": "根据用户定义的function,执行方案", # 助手描述
        "instructions": "根据用户定义的function,执行方案", # 助手设定(即bot_setting)
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "get_weather",
                    "description": "获得天气信息",
                    "parameters": {
                        "type": "object",
                        "required": ["location"],
                        "properties": {"location": {"type": "string", "description": "获得天气的地点"}},
                    },
                },
            }
        ],
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()


# 流程二:创建线程
def create_thread():
    url = f"https://api.minimax.chat/v1/threads/create?GroupId={GroupId}"
    response = requests.post( url, headers=headers)
    return response.json()


# 流程三:往线程里添加信息
def add_message_to_thread(thread_id):
    url = f"https://api.minimax.chat/v1/threads/messages/add?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id,
        "role": "user",
        "content": "上海天气怎么样",
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()


# 流程四:使用助手处理该线程
def run_thread_with_assistant(thread_id, assistant_id):
    url = f"https://api.minimax.chat/v1/threads/run/create?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id,
        "assistant_id": assistant_id
    })
    response = requests.post(url, headers=headers, data=payload)
    return response.json()


# 流程五:获取线程中助手处理出的新信息
def get_thread_messages(thread_id):
    url = f"https://api.minimax.chat/v1/threads/messages/list?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": thread_id
    })
    response = requests.get(url, headers=headers, data=payload)
    return response.json()

# 流程六:查看run
def check_thread_run_status(thread_id, run_id, wanted_status):
    url = f"https://api.minimax.chat/v1/threads/run/retrieve?GroupId={GroupId}"
    payload = json.dumps({
        "thread_id": str(thread_id),
        "run_id": str(run_id)
    })
    completed = False
    max_count = 10
    count = 0
    while not completed and count < max_count:
        response = requests.request("GET", url, headers=headers, data=payload)
        if response.status_code == 200:
            response_data = response.json()
            status = response_data.get('status', '')
            print(f"Status: {status}")
            if status == wanted_status:
                completed = True
                print("Process completed, exiting loop.")
            else:
                time.sleep(2)  # 如果状态不是completed,等待两秒后重新请求
        else:
            print(f"Error: {response.status_code}")
            break  # 如果请求失败,退出循环
        count += 1
    return completed

# 流程七:查看required_action
def get_required_action(thread_id, run_id):
    url = f"https://api.minimax.chat/v1/threads/run/retrieve?GroupId={GroupId}"
    payload = json.dumps(
        {
            "thread_id": thread_id,
            "run_id": run_id
        }
    )
    response = requests.request("GET", url, headers=headers, data=payload)
    required_action = response.json()["required_action"]
    return required_action


# 流程八:提交结果
def submit_output(thread_id, run_id, required_action, output):
    url = f"https://api.minimax.chat/v1/threads/run/submit_tool_outputs?GroupId={GroupId}"
    payload = json.dumps(
        {
            "thread_id": thread_id,
            "run_id": run_id,
            "tool_outputs": [{
                "tool_call_id": required_action["submit_tool_outputs"]["tool_calls"][0]["id"],
                "output": output,
            }]
        }
    )
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json()

def main():
    # 创建助手
    assistant_response = create_assistant()
    assistant_id = assistant_response.get('id', '')
    print("assistant_id:",assistant_id)

    # 创建线程
    thread_response = create_thread()
    thread_id = thread_response.get('id', '')
    print("thread_id:",thread_id)

    # 往线程里添加信息
    add_message_to_thread(thread_id)  # 不保存返回值

    # 使用助手处理该线程
    run_response = run_thread_with_assistant(thread_id, assistant_id)
    run_id = run_response.get('id', '')  # 假设run_response是正确的JSON响应,并包含run_id
    print("run_id:",run_id)

    # 检查助手处理状态
    if check_thread_run_status(thread_id, run_id, "requires_action"):
        required_action = get_required_action(thread_id, run_id)
        # fc_output = "上海天气晴朗"
        fc_output = '{"result": "上海最高气温7度 最低零下一度 晴"}'
        resp = submit_output(thread_id, run_id, required_action, fc_output)
        print(resp)

    # 检查助手处理状态
    if check_thread_run_status(thread_id, run_id, "completed"):
        # 获取线程中助手处理出的新信息
        thread_messages_response = get_thread_messages(thread_id)
        # 打印JSON数据
        print(json.dumps(thread_messages_response, indent=4, ensure_ascii=False))

if __name__ == "__main__":
    main()
16:21
assistant_id: asst_d7b4152fa8414d4e804733d35d445064
thread_id: thread_0a98d23117424cf088af4c32f99738ce
run_id: run_072537334b2f426eade029a77e6410c5
Status: in_progress
Status: requires_action
Process completed, exiting loop.
{'id': 'run_072537334b2f426eade029a77e6410c5', 'object': 'thread.run', 'created_at': 1703492444, 'assistant_id': 'asst_d7b4152fa8414d4e804733d35d445064', 'thread_id': 'thread_0a98d23117424cf088af4c32f99738ce', 'run_id': '', 'status': 'queued', 'started_at': 1703492444, 'expires_at': 0, 'cancelled_at': 0, 'failed_at': 0, 'completed_at': 0, 'last_error': None, 'model': 'abab5.5-chat', 'instructions': '根据用户定义的function,执行方案', 'tools': [{'type': 'function', 'function': {'name': 'get_weather', 'description': '获得天气信息', 'parameters': {'type': 'object', 'required': ['location'], 'properties': {'location': {'type': 'string', 'description': '获得天气的地点'}}}}}], 'file_ids': None, 'metadata': None, 'base_resp': {'status_code': 0, 'status_msg': 'success'}}
Status: in_progress
Status: completed
Process completed, exiting loop.
{
    "object": "list",
    "data": [
        {
            "id": "msg_fd788f009f7146a4835bedcee03c12ce",
            "object": "message",
            "created_at": 1703492444,
            "thread_id": "thread_0a98d23117424cf088af4c32f99738ce",
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "上海天气怎么样",
                        "annotations": []
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_d7b4152fa8414d4e804733d35d445064",
            "run_id": "run_072537334b2f426eade029a77e6410c5",
            "metadata": null
        },
        {
            "id": "msg_d6e3ef29ff7342a698cb9bc9c571edca",
            "object": "message",
            "created_at": 1703492448,
            "thread_id": "thread_0a98d23117424cf088af4c32f99738ce",
            "role": "ai",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "上海今天的天气是晴,最高气温7度,最低气温零下一度。",
                        "annotations": []
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_d7b4152fa8414d4e804733d35d445064",
            "run_id": "run_072537334b2f426eade029a77e6410c5",
            "metadata": null
        }
    ],
    "first_id": "msg_fd788f009f7146a4835bedcee03c12ce",
    "last_id": "msg_d6e3ef29ff7342a698cb9bc9c571edca",
    "base_resp": {
        "status_code": 0,
        "status_msg": "success"
    }
}
输出示例
assistant_id: asst_d7b4152fa8414d4e804733d35d445064
thread_id: thread_0a98d23117424cf088af4c32f99738ce
run_id: run_072537334b2f426eade029a77e6410c5
Status: in_progress
Status: requires_action
Process completed, exiting loop.
{'id': 'run_072537334b2f426eade029a77e6410c5', 'object': 'thread.run', 'created_at': 1703492444, 'assistant_id': 'asst_d7b4152fa8414d4e804733d35d445064', 'thread_id': 'thread_0a98d23117424cf088af4c32f99738ce', 'run_id': '', 'status': 'queued', 'started_at': 1703492444, 'expires_at': 0, 'cancelled_at': 0, 'failed_at': 0, 'completed_at': 0, 'last_error': None, 'model': 'abab5.5-chat', 'instructions': '根据用户定义的function,执行方案', 'tools': [{'type': 'function', 'function': {'name': 'get_weather', 'description': '获得天气信息', 'parameters': {'type': 'object', 'required': ['location'], 'properties': {'location': {'type': 'string', 'description': '获得天气的地点'}}}}}], 'file_ids': None, 'metadata': None, 'base_resp': {'status_code': 0, 'status_msg': 'success'}}
Status: in_progress
Status: completed
Process completed, exiting loop.
{
    "object": "list",
    "data": [
        {
            "id": "msg_fd788f009f7146a4835bedcee03c12ce",
            "object": "message",
            "created_at": 1703492444,
            "thread_id": "thread_0a98d23117424cf088af4c32f99738ce",
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "上海天气怎么样",
                        "annotations": []
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_d7b4152fa8414d4e804733d35d445064",
            "run_id": "run_072537334b2f426eade029a77e6410c5",
            "metadata": null
        },
        {
            "id": "msg_d6e3ef29ff7342a698cb9bc9c571edca",
            "object": "message",
            "created_at": 1703492448,
            "thread_id": "thread_0a98d23117424cf088af4c32f99738ce",
            "role": "ai",
            "content": [
                {
                    "type": "text",
                    "text": {
                        "value": "上海今天的天气是晴,最高气温7度,最低气温零下一度。",
                        "annotations": []
                    }
                }
            ],
            "file_ids": null,
            "assistant_id": "asst_d7b4152fa8414d4e804733d35d445064",
            "run_id": "run_072537334b2f426eade029a77e6410c5",
            "metadata": null
        }
    ],
    "first_id": "msg_fd788f009f7146a4835bedcee03c12ce",
    "last_id": "msg_d6e3ef29ff7342a698cb9bc9c571edca",
    "base_resp": {
        "status_code": 0,
        "status_msg": "success"
    }
}

三、支持工具#

Assistant可以访问MiniMax提供的工具,如代码解释器(Code Interpreter)、知识库检索(Retrieval)、函数调用(Function calling)。
使用以上工具需要支付一定的额外费用,具体的定价计费您可以在产品定价进行详细的了解。

1、Code Interpreter(代码解释器)#

Code Interpreter使得Assistants API可以在沙盒执行环境中编写和运行Python代码。该工具可以处理具有不同数据和格式的文件,并且可以生成图像文件。
利用Code Interpreter工具,Assistants可以生成并运行代码,以帮助用户解决具有难度的文件处理、数据分析或者复杂的数学逻辑问题。

1.1 启用Code Interpreter#

通过Assistants object数组中的tool参数里上传code_interpreter参数以启用Code Interpreter。
import requests
import json

url = "https://api.minimax.chat/v1/assistants/create?GroupId=$GroupId"

payload = json.dumps({
  "model": "abab5.5",
  "name": "数据分析师",
  "description": "数据分析师,用在数据分析场景",
  "instructions": "是一个数据分析师,善于读取文件进行数据分析,并能严谨精准的给出分析结论",
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  },
  "file_ids": [
    "88731293343809"
  ],
  "tools": [
    {
      "type": "code_interpreter"
    }
  ]
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json',
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/assistants/create?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'bedrock_lane: lane_xh' \
--data '{
    "model": "abab5.5",
    "name": "数据分析师",
    "description": "数据分析师,用在数据分析场景",
    "instructions": "是一个数据分析师,善于读取文件进行数据分析,并能严谨精准的给出分析结论",
    "metadata": {
    "key1": "value1",
    "key2": "value2"
    },
    "file_ids":["${file id}"],
        "tools": [
            {
                "type": "code_interpreter"
            }
        ]

    }
'
启用Code Interpreter之后模型会根据用户的请求内容判断何时调用工具。

1.2 上传文件给Code Interpreter#

Code Interpreter可以分析文档file中的数据,此功能适用于当您希望向Assistants提供文档数据或者允许用户上传自己的文档进行分析的时候。使用File接口上传文件(purpose = assistants),然后将file id作为assistant的一部分创建。
上传文件到Assistants层级的文件可以被使用此assistant的所有run访问:
import requests
import json

url = "https://api.minimax.chat/v1/assistants/create?GroupId=${GroupId}"

payload = json.dumps({
  "model": "abab5.5",
  "name": "数据分析师",
  "description": "数据分析师",
  "instructions": "是一个数据分析师,善于读取文件进行数据分析,并能严谨精准的给出分析结论",
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  },
  "file_ids": [
      "${file id}"
  ],
  "tools": [
    {
      "type": "code_interpreter"
    },
    {
      "type": "web_search"
    }
  ]
})
headers = {
  'Authorization': 'Bearer ${API_KEY}',
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/assistants/create?GroupId=${GroupId}' \
--header 'Authorization: Bearer ${API_KEY}' \
--header 'Content-Type: application/json' \
--data '{
    "model": "my_model",
    "name": "function",
    "description": "代码机器人",
    "instructions": "Follow the instructions carefully",
    "metadata": {
        "key1": "value1",
        "key2": "value2"
    },
    "file_ids":["${file id}"],
    "tools": [        
        {"type":"code_interpreter"},
    ]
}'
文件也可以通过message进行上传,这些文件只能由特定thread访问,使用File接口上传文件,然后将file id作为message的一部分创建:
import requests
import json

url = "https://api.minimax.chat/v1/threads/messages/add?GroupId=$GroupId"

payload = json.dumps({
  "thread_id": "thread_abc123",
  "role": "user",
  "file_ids": [
    "${file id}"
  ],
  "content": "统计一下总进球数?",
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  }
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/threads/messages/add?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "thread_id": "thread_abc123",
    "role": "user",
    "file_ids":["${file id}"],
    "content": "统计一下总进球数?",
    "metadata": {
    "key1": "value1",
    "key2": "value2"
    }
}'
文件最大支持512MB。Code Interpreter支持多种文件格式,包括.csv、.pdf、.json等。相关支持的文件(及其相应的MIME类型)的更多详细信息,可以跳转至“支持文件类型”部分得到详细信息。

1.3 Code Interpreter 的输入和输出日志#

通过列出名为Code Interpreter的Run Step,您可以检查Code Interpreter的日志
import requests
import json

url = "https://api.minimax.chat/v1/threads/run_steps/list?GroupId=$GroupId"

payload = json.dumps({
  "thread_id": "thread_abc123",
  "run_id": "run_abc123"
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
curl --location --request GET 'https://api.minimax.chat/v1/threads/run_steps/list?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "thread_id": "thread_abc123",
    "run_id": "run_abc123"
}'
{
  "object": "list",
  "data": [
    {
      "id": "step_abc123",
      "object": "thread.run.step",
      "type": "tool_calls",
      "run_id": "run_abc123",
      "thread_id": "thread_abc123",
      "status": "completed",
      "step_details": {
        "type": "tool_calls",
        "tool_calls": [
          {
            "type": "code",
            "code": {
              "input": "# 计算 2 + 2\nresult = 2 + 2\nresult",
              "outputs": [
                {
                  "type": "logs",
                  "logs": "4"
                }
    ...
 }

2、知识库检索(Retrieval)#

知识库检索会利用外部的知识(例如专有产品信息或者用户提供的文档)来增强模型的专业知识。
一旦文件上传到知识库检索,模型将对您的文档进行切片,索引和向量化,检索相关内容以回答用户的请求。

2.1 启用知识库检索#

通过Assistant object数组中的tool参数里上传retireval参数以启用知识库检索。
import requests
import json

url = "https://api.minimax.chat/v1/assistants/create?GroupId=$GroupId"

payload = json.dumps({
  "model": "abab5.5",
  "name": "小说专家",
  "description": "小说专家,用在小说解读场景中回答用户问题",
  "instructions": "是一个小说专家,读过万卷书,了解小说里的各种细致情节,另外也非常热心,会热情的帮读者解答小说里的问题",
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  },
  "file_ids": [
    "${file id}"
  ],
  "tools": [
    {
      "type": "retrieval"
    }
  ]
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json',
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/assistants/create?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'bedrock_lane: lane_xh' \
--data '{
    "model": "abab5.5",
    "name": "assistant名称",
    "description": "assistant设定描述",
    "instructions": "Follow the instructions carefully",
    "metadata": {
    "key1": "value1",
    "key2": "value2"
    },
    "file_ids":["${file id}"],
        "tools": [
            {
                "type": "retrieval"
            }
        ]

    }
'

2.2 工作原理#

当Assistant启用知识库检索工具并关联文档后,会先对文档进行向量化存储,在请求时Assistants api会自行判断是否对文档进行检索增强生成。

2.3 上传文件进行检索#

上传文件分为两种类型,分别可以通过Assistant级别或者Assistants File级别进行上传。
Assistant级别上传
import requests
import json

url = "https://api.minimax.chat/v1/threads/messages/add?GroupId=$GroupId"

payload = json.dumps({
  "thread_id": "thread_b6c183200cf0448f93d1c32e79dd71d0",
  "role": "user",
  "file_ids": [
    "${file id}"
  ],
  "content": "在倚天屠龙记中,无俗念词的作者是谁?",
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  }
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/threads/messages/add?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--data '{
    "thread_id": "thread_abc123",
    "role": "user",
    "file_ids":["${file id}"],
    "content": "在倚天屠龙记中,无俗念词的作者是谁?",
    "metadata": {
    "key1": "value1",
    "key2": "value2"
    }
}'
此外,您无需根据通过File接口上传的文件的大小付费,只须根据您附加到Assistants API中已向量化后存储的容量付费。
可以添加的文件大小最大为512MB。知识库检索支持多种文件格式,包括pdf、md、docx等。
相关支持的文件(及其相应的MIME类型)的更多详细信息,可以跳转至“支持文件类型”部分,得到详细信息。

2.4 检索的引用信息#

当在Message中出现file_citation的annotations时,即调用了retrieval,可以查看annotations字段来查看本次回复的文档引用信息。
{
  "id": "msg_83b789a095c74af5a192e1ce737c872d",
    "object": "message",
      "created_at": 1703416137,
        "thread_id": "thread_d98733725c7845eca48a56e14f6b1ce9",
          "role": "ai",
            "content": [
              {
                "type": "text",
                "text": {
                  "value": "在《倚天屠龙记》中,无俗念词的作者是南宋末年的一位武学名家,有道之士,他姓丘,名处机,道号长春子,名列全真七子之一,是全真教中出类拔萃的人物。【1†source】",
                  "annotations": [
                    {
                      "type": "file_citation",
                      "text": "【1†source】",
                      "start_index": 71,
                      "end_index": 81,
                      "file_citation": {
                        "file_id": "",
                        "quote": "###《倚天屠龙记》\n\n###第01章 天涯思君不可忘\n\n“春游浩荡,是年年寒食,梨花时节。白锦无纹香烂漫,玉树琼苞堆雪。静夜沉沉,浮光霭霭,冷浸溶溶月。人间天上,烂银霞照通彻。\n\n浑似姑射真人,天姿灵秀,意气殊高洁。万蕊参差谁信道,不与群芳同列。浩气清英,仙才卓荦,下土难分别。瑶台归去,洞天方看清绝。”\n\n作这一首无俗念词的,乃南宋末年一位武学名家,有道之士。此人姓丘,名处机,道号长春子,名列全真七子之一,是全真教中出类拔萃的人物。词品评论此词道:“长春,世之所谓仙人也,而词之清拔如此”。\n\n这首词诵的似是梨花,其实同中真意却是赞誉一位身穿白衣的美貌少女,说她“浑似姑射真人,天姿灵秀,意气殊高洁”,又说她“浩气清英,仙才卓荦”,“不与群芳同列”。词中所颂这美女,乃古墓派传人小龙女。她一生爱穿白衣,当真如风拂玉树,雪裹琼苞,兼之生性清冷,实当得起“冷浸溶溶月”的形容,以“无俗念”三字赠之,可说十分贴切。长春子丘处机和她在终南山上比邻而居,当年一见,便写下这首词来。\n\n这时丘处机逝世已久,小龙女也已嫁与神雕大侠杨过为妻。在河南少室山山道之上,却另有一个少女,正在低低念诵此词。"
                      }
                    }
                  ]
                }
              }

3、Web_search(网络搜索)#

Assistants API支持调用MiniMax提供的web_search函数,以便获得实时搜索数据辅助大模型返回更好的结果
import requests
import json

url = "https://api.minimax.chat/v1/threads/run_steps/list?GroupId=${GroupId}"

payload = json.dumps({
  "thread_id": "$Thread_Id",
  "run_id": "$Run_Id"
})
headers = {
  'Authorization': 'Bearer ${API_KEY}',
  'Content-Type': 'application/json'
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.json())

//
{
    "object": "list",
    "data": [
        {
            "id": "step_abc123",
            "object": "thread.run.step",
            "created_at": 1703322284,
            "run_id": "run_abc123",
            "assistant_id": "asst_abc123",
            "thread_id": "thread_abc123",
            "type": "tool_calls",
            "status": "completed",
            "step_details": {
                "type": "tool_calls",
                "tool_calls": [
                    {
                        "id": "call_123",
                        "type": "web_search",
                        "web_search": {
                            "name": "get_web_search_result",
                            "arguments": "{\"search_query\": \"2022年11月23日上海 天气\"}",
                            "output": "[{\"no\":1,\"content\":\"全球天气网(www.tianqi.com)提供上海11月份天气数据....]"
                        }
                    }
                ]
    ...
}

4、Function calling(函数调用)#

与Chatcompletion API以及Chatcompletion Pro API类似,Assistants API支持函数调用。
Assistants API在调用函数时将在进行中的Run中进行暂停,您可以提供函数调用结果已继续执行Run。

4.1 自定义函数#

首先,您需要在创建assistant时定义函数:
import requests
import json

url = "https://api.minimax.chat/v1/assistants/create?GroupId=$GroupId"

payload = json.dumps({
  "model": "abab5.5",
  "name": "assistant名称",
  "description": "assistant设定描述",
  "instructions": "Follow the instructions carefully",
  "metadata": {
    "key1": "value1",
    "key2": "value2"
  },
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "get weather",
        "parameters": {
          "type": "object",
          "required": [
            "city"
          ],
          "properties": {
            "city": {
              "type": "string"
            }
          }
        }
      }
    }
  ]
})
headers = {
  'Authorization': 'Bearer $API_KEY',
  'bedrock_lane': 'lane_xh'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/assistants/create?GroupId=$GroupId' \
--header 'Authorization: Bearer $API_KEY' \
--header 'Content-Type: application/json' \
--header 'bedrock_lane: lane_xh' \
--data '{
    "model": "abab5.5",
    "name": "assistant名称",
    "description": "assistant设定描述",
    "instructions": "Follow the instructions carefully",
    "metadata": {
    "key1": "value1",
    "key2": "value2"
    },
        "tools": [
            {
                "type": "function",
                "function":{
                    "name":"get_weather",
                    "description":"get weather",
                    "parameters":{
                        "type":"object",
                        "required":["city"],
                        "properties":{"city":{"type":"string"}}
                    }
                }
            }
        ]
    }
'

4.2 读取Assistant调用的函数#

当assistant判断用户的Message需要调用函数时,包含该条Message的 Thread的运行将进入暂停状态。函数调用结果生成后,Run将进入下一状态,您可以通过requires_action来检索Run状态。
{
    "assistant_id": "asst_abc123",
    "id": "run_abc123",
    "object": "thread.run",
    "required_action": {
        "submit_tool_outputs": {
            "tool_calls": [
                {
                    "function": {
                        "arguments": '{"city": ' '"上海"}',
                        "name": "get_weather",
                    },
                    "id": "call_abc123",
                    "type": "function",
                }
            ]
        },
        "type": "submit_tool_outputs",
    },
    ...
}

4.3 提交函数的输出内容#

您可以通过提交所调用的函数返回的submit_tool_outputs来完成运行。
您可以使用tool_calls_id通过require_action匹配每个函数调用的输出输出结果。
import requests
import json

url = "https://api.minimax.chat/v1/threads/run/submit_tool_outputs?GroupId= ${Groupid}"

payload = json.dumps({
    "thread_id": "thread_abc123",
    "run_id": "run_abc123",
    "tool_outputs": [
        {
            "tool_call_id": "call_abc123",
            "output": "内容"
        }
    ]
})
headers = {
    'Authorization': 'Bearer ${API KEY}',
    'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, data=payload)

print(response.text)
curl --location 'https://api.minimax.chat/v1/threads/run/submit_tool_outputs?GroupId= ${Groupid}' \
--header 'Authorization: Bearer ${API KEY}' \
--header 'Content-Type: application/json' \
--data '{
    "thread_id": "thread_abc123",
    "run_id": "run_abc123",
    "tool_outputs": [
        {
            "tool_call_id": "call_abc123",
            "output": "内容"
        }
    ]
}'

5、支持文件类型#

对于text/MIME类型,编码必须是utf-8、utf-16或ascii之一
文件格式MIME类型Code Interpreter是否支持Retrieval是否支持
.ctext/x-c✅✅
.cpptext/x-c++✅✅
.csvapplication/csv✅
.docxapplication/vnd.openxmlformats-officedocument.wordprocessingml.document✅✅
.htmltext/html✅✅
.javatext/x-java✅✅
.jsonapplication/json✅✅
.mdtext/markdown✅✅
.pdfapplication/pdf✅✅
.phptext/x-php✅✅
.pptxapplication/vnd.openxmlformats-officedocument.presentationml.presentation✅✅
.pytext/x-python✅✅
.pytext/x-script.python✅✅
.rbtext/x-ruby✅✅
.textext/x-tex✅✅
.txttext/plain✅✅
.csstext/css✅
.jpegimage/jpeg✅
.jpgimage/jpeg✅
.jstext/javascript✅
.gifimage/gif✅
.pngimage/png✅
.tarapplication/x-tar✅
.tsapplication/typescript✅
.xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet✅
.xmlapplication/xml or "text/xml"✅
.zipapplication/zip✅
上一页
知识库检索功能(retrieval)
下一页
创建 Assistant
Built with