1. 发布API

Coze的API功能需要通过应用发布功能启用。

在这里插入图片描述

2. 调试

2.1 入口

发布成功后在工作流画布页面可以看到API调试入口

在这里插入图片描述
在这里插入图片描述

2.2 查看工作流ID和应用ID

通过上述入口进入API playground,选择右侧的Shell请求

可以看到工作流ID:workflow_id

应用ID:app_id

在这里插入图片描述

2.3 授权API key

左侧窗口下滑,可以看到token,这就是API Key,点击授权

在这里插入图片描述

点击“授权”后自动生成并填充 API Key

在这里插入图片描述

右侧的Shell命令窗口同步更新

2.4 添加参数

parameters属性下的JSON用于向工作流传递参数。

该JSON对象的每个属性对应一个工作流的输入变量

在这里插入图片描述

2.5 运行

可以直接点击Shell命令窗口右上角的“运行”按钮

在这里插入图片描述

2.6 完整命令

curl -X POST 'https://api.coze.cn/v3/chat?' \
-H "Authorization: xxxxxx" \
-H "Content-Type: application/json" \
-d '{
  "bot_id": "7669363834150862858",
  "user_id": "123456789",
  "stream": true,
  "additional_messages": [
    {
      "content": "hello",
      "content_type": "text",
      "role": "user",
      "type": "question"
    }
  ],
  "parameters": {
    "input": "你是?"
  }
}'

2.7 运行结果

在这里插入图片描述

右下角可以看到运行结果

200表示通信正常

PING是用于维持通信连接的心跳响应

Message是携带数据的响应

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

此处的content是工作流的输出。

Done是最后一个响应,表示工作流执行完毕,在Message响应之后。

3.通过python代码调用工作流

3.1 官方提供了调用API的Python代码

在这里插入图片描述

3.2 源码如下

"""
This example is about how to use the streaming interface to start a chat request
and handle chat events
"""

import os
# Our official coze sdk for Python [cozepy](https://github.com/coze-dev/coze-py)
from cozepy import COZE_CN_BASE_URL

# Get an access_token through personal access token or oauth.
coze_api_token = 'cztei_qwL8CVSDyZxxxxxJxxxx7mLZ5uQA3r5vI'
# The default access is api.coze.com, but if you need to access api.coze.cn,
# please use base_url to configure the api endpoint to access
coze_api_base = COZE_CN_BASE_URL

from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType  # noqa

# Init the Coze client through the access_token.
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)

# Create a bot instance in Coze, copy the last number from the web link as the bot's ID.
bot_id = '7669363834150862858'
# The user id identifies the identity of a user. Developers can use a custom business ID
# or a random string.
user_id = '123456789'

# Call the coze.chat.stream method to create a chat. The create method is a streaming
# chat and will return a Chat Iterator. Developers should iterate the iterator to get
# chat event and handle them.
for event in coze.chat.stream(
    bot_id=bot_id,
    user_id=user_id,
    additional_messages=[
        Message.build_user_question_text("Tell a 500-word story."),
    ],
):
    if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
        print(event.message.content, end="", flush=True)

    if event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
        print()
        print("token usage:", event.chat.usage.token_count)

将源码粘贴到PyCharm。

3.3 在本地PyCharm中运行需要安装cozepy

pip install cozepy

代码粘贴后,运行:

在这里插入图片描述

3.4 优化代码

完善代码,具备交互功能:

"""
This example is about how to use the streaming interface to start a chat request
and handle chat events, with interactive multi-turn conversation support.
"""

import os
from cozepy import COZE_CN_BASE_URL

coze_api_token = 'cztei_qZqYvHQ411YIrxxxxxxxxxxxxxxxKIa'
coze_api_base = COZE_CN_BASE_URL

from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, ChatEventType  # noqa

coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)

bot_id = '7669363834150862858'
user_id = '123456789'

conversation_id = None

print("=== Coze 智能助手 ===")
print("输入消息开始对话,输入 'exit' 或 '退出' 结束程序\n")

while True:
    user_input = input("你: ").strip()

    if not user_input:
        continue

    if user_input.lower() in ('exit', 'quit', '退出', 'q'):
        print("再见!对话已结束。")
        break

    try:
        chat_params = {
            "bot_id": bot_id,
            "user_id": user_id,
            "additional_messages": [
                Message.build_user_question_text(user_input),
            ],
        }
        if conversation_id:
            chat_params["conversation_id"] = conversation_id

        print("助手: ", end="", flush=True)

        for event in coze.chat.stream(**chat_params):
            if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                print(event.message.content, end="", flush=True)

            if event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                conversation_id = event.chat.conversation_id
                print()
                print(f"[token usage: {event.chat.usage.token_count}]")

    except Exception as e:
        print(f"\n发生错误: {e}")

运行结果:
在这里插入图片描述

更多推荐