> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coze.cn/llms.txt
> Use this file to discover all available pages before exploring further.

本文介绍如何使用扣子编程 Python SDK 完成扣子编程的常用操作，例如如何初始化 SDK、创建一个智能体草稿、发布智能体为 API 服务、和智能体对话等。
:::tip 说明
初始化之前，请确认已完成以下操作：

* 已安装扣子编程 Python SDK。更多信息，可参见[安装 Python SDK](/developer_guides/python_installation)。
* 已实现授权流程，并通过环境变量等方式配置了访问密钥。详细说明可参考[配置访问密钥](/developer_guides/python_access_token)。
* 请确保扣子编程 Python SDK 版本已升级至 **0.17.0** 及之后版本，以免调用[发起对话](/developer_guides/chat_v3)或[执行对话流](/developer_guides/workflow_chat) API 失败。
:::
## 初始化 SDK {#75c24ee6}
初始化扣子编程 client 之后，才可以向扣子编程服务端发送 OpenAPI 请求。初始化时推荐通过环境变量动态获取访问密钥，以免硬编码引发数据安全风险。
初始化代码如下：
```Python
import os

from cozepy import Coze, TokenAuth, COZE_CN_BASE_URL
# 扣子编程建议你通过环境变量的方式管理访问密钥，关于环境变量的详细说明可参考 Python 官方文档。
coze = Coze(auth=TokenAuth(os.getenv("coze_api_token")), base_url=COZE_CN_BASE_URL)
```

## 创建并发布智能体为 API 服务 {#773defee}
通过 API 方式和智能体对话之前，你需要先创建一个智能体，并将其发布为 API 服务。你可以通过扣子编程平台或调用相关的 API 实现智能体的创建和发布。

* 通过扣子编程创建和发布智能体的操作请参见[搭建一个 AI 助手智能体](/guides/quickstart)、[发布智能体为 API 服务](/developer_guides/preparation#7c231be8)。
* 通过 API 创建和发布智能体的接口文档请参见[创建智能体](/developer_guides/create_bot)、[发布智能体](/developer_guides/publish_bot)。
   :::tip 说明
   调用 API 创建智能体时，部分配置对应的 API 参数暂未开放，你只能为智能体添加知识库等有限的配置。
   :::

示例代码如下：
完整的示例代码，请参见 [examples/bot_publish.py示例源码](https://github.com/coze-dev/coze-py/blob/main/examples/bot_publish.py)。
```Python
import os  # noqa
from pathlib import Path

# Get an access_token through personal access token oroauth.
coze_api_token = os.getenv("COZE_API_TOKEN")

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

# Init the Coze client
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=COZE_CN_BASE_URL)

# Call the upload file interface to get the avatar id.
avatar = coze.files.upload(file=Path("/path/avatar.jpg"))

# Invoke the create interface to create a bot in the draft status.
bot = coze.bots.create(
    # The bot should exist under a space and your space id needs configuration.
    space_id="workspace id",
    # Bot name
    name="translator bot",
    # Bot avatar
    icon_file_id=avatar.id,
    # Bot system prompt
    prompt_info=BotPromptInfo(prompt="your are a translator, translate the following text from English to Chinese"),
)

# Call the publish interface to publish the bot on the api channel.
coze.bots.publish(bot_id=bot.bot_id)

# 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(
    # The published bot's id
    bot_id=bot.bot_id,
    # biz user id, maybe random string
    user_id="user id",
    # user input
    additional_messages=[Message.build_user_question_text("chinese")],
):
    if (
        event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA
        and event.message.content.type == MessageContentType.TEXT
    ):
        print(event.message.content, end="")
```

## 发起对话 {#5469a0e6}
[发起对话](/developer_guides/chat_v3)接口用于向指定智能体发起一次对话，支持在对话时添加对话的上下文消息，以便智能体基于历史消息做出合理的回复。开发者可以按需选择响应方式，即流式或非流式响应，响应方式决定了开发者获取智能体回复的方式。

* **流式响应**：智能体在生成回复的同时，将回复消息以数据流的形式逐条发送给客户端。处理结束后，服务端会返回拼接后完整的智能体回复。详细说明可参考[流式响应](https://www.coze.cn/docs/developer_guides/chat_v3#AJThpr1GJe)。 
* **非流式响应**：无论对话是否处理完毕，立即发送响应消息。开发者可以通过接口[查看对话详情](https://www.coze.cn/docs/developer_guides/retrieve_chat)确认本次对话处理结束后，再调用[查看对话消息详情](https://www.coze.cn/docs/developer_guides/list_chat_messages)接口查看模型回复等完整响应内容。详细说明可参考[非流式响应](https://www.coze.cn/docs/developer_guides/chat_v3#337f3d53)。

本文档以流式响应为例，演示通过 API 方式和智能体对话相关示例代码。你也可以查看 Coze Python SDK [示例代码目录](https://github.com/coze-dev/coze-py/tree/main/examples)，查看发起对话接口的其他实现方式，例如非流式响应、对话中发送多模态内容等。
示例代码如下：
```Python
import os  # noqa

# Get an access_token through personal access token oroauth.
coze_api_token = os.getenv("COZE_API_TOKEN")

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_CN_BASE_URL)

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

# 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("How are you?")]
):
    if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
        message = event.message
        print(f"role={message.role}, content={message.content}")
```

