> ## 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.

本文介绍如何使用 Coze API Go SDK 完成扣子编程的常用操作，例如如何初始化 SDK、创建一个智能体草稿、发布智能体为 API 服务、和智能体对话等。
## 准备工作 {#d140d184}
初始化 SDK 前，请确认已完成以下操作：

* 已安装 Coze API Go SDK。详见[安装 Go SDK](/developer_guides/go_installation)。
* 已实现授权流程，并通过环境变量方式配置了访问密钥。详细说明可参考[配置访问密钥](/developer_guides/go_access_token)。

:::tip 说明
请确保扣子编程 Go SDK 版本已升级至 **v0.0.0-20250604025746-0d3b62f445d2** 及之后版本，以免调用[发起对话](/developer_guides/chat_v3)或[执行对话流](/developer_guides/workflow_chat) API 失败。
:::
## 初始化 SDK {#353ab2b1}
初始化 Coze client 之后，才可以向扣子编程服务端发送 OpenAPI 请求。初始化时推荐通过环境变量动态获取访问密钥，以免硬编码引发数据安全风险。
初始化代码如下：
```Go
// This examples demonstrates how to initialize the Coze client with different configurations.
func main() {
    // Get an access_token through personal access token or oauth.
    token := os.Getenv("COZE_API_TOKEN")
    authCli := coze.NewTokenAuth(token)

    // 1. Initialize with default configuration
    cozeCli1 := coze.NewCozeAPI(authCli)
    fmt.Println("client 1:", cozeCli1)

    // 2. Initialize with custom base URL
    cozeAPIBase := os.Getenv("COZE_API_BASE")
    cozeCli2 := coze.NewCozeAPI(authCli, coze.WithBaseURL(cozeAPIBase))
    fmt.Println("client 2:", cozeCli2)

    // 3. Initialize with custom HTTP client
    customClient := &http.Client{
       Timeout: 30 * time.Second,
       Transport: &http.Transport{
          MaxIdleConns:        100,
          MaxIdleConnsPerHost: 100,
          IdleConnTimeout:     90 * time.Second,
       },
    }
    cozeCli3 := coze.NewCozeAPI(authCli,
       coze.WithBaseURL(cozeAPIBase),
       coze.WithHttpClient(customClient),
    )
    fmt.Println("client 3:", cozeCli3)
}
```

## 创建并发布智能体为 API 服务 {#84432f23}
通过 API 方式和智能体对话之前，你需要先创建一个智能体，并将其发布为 API 服务。你可以在扣子编程中创建智能体并发布，也可以通过调用相关的 API 实现。调用 API 创建智能体时，部分配置对应的 API 参数暂未开放，你只能为智能体添加知识库等有限的配置。创建智能体的操作步骤可参考[搭建一个低代码智能体](/guides/agent_quick_start)。将智能体发布为 API 服务的操作步骤可参考[发布为 API 服务](/guides/publish_agent_api)。

* 关于创建草稿智能体的完整示例代码，请参见 [GitHub 示例](https://github.com/coze-dev/coze-go/blob/main/examples/bots/publish/main.go)。
* 相关 API 接口描述，请参见：
   * [创建智能体](/developer_guides/create_bot)。
   * [发布智能体](/developer_guides/publish_bot)。

示例代码如下：
```Go
// This examples is for describing how to create a bot, update a bot and publish a bot to the API.
func main() {
    // Get an access_token through personal access token or oauth.
    token := os.Getenv("COZE_API_TOKEN")
    authCli := coze.NewTokenAuth(token)

    // Init the Coze client through the access_token.
    cozeCli := coze.NewCozeAPI(authCli, coze.WithBaseURL(os.Getenv("COZE_API_BASE")))

    // step one, create a bot
    workspaceID := os.Getenv("WORKSPACE_ID")

    // Call the upload file interface to get the avatar id.
    avatarPath := os.Getenv("IMAGE_FILE_PATH")
    ctx := context.Background()
    file, err := os.Open(avatarPath)
    if err != nil {
       fmt.Println("Error opening file:", err)
       return
    }
    uploadReq := &coze.UploadFilesReq{
       File: file,
    }
    avatarInfo, err := cozeCli.Files.Upload(ctx, uploadReq)
    if err != nil {
       fmt.Println("Error uploading avatar:", err)
       return
    }
    fmt.Println(avatarInfo)

    // build the request
    createResp, err := cozeCli.Bots.Create(ctx, &coze.CreateBotsReq{
       SpaceID:     workspaceID,
       Description: "the description of your bot",
       Name:        "the name of your bot",
       PromptInfo: &coze.BotPromptInfo{
          Prompt: "your prompt",
       },
       OnboardingInfo: &coze.BotOnboardingInfo{
          Prologue:           "the prologue of your bot",
          SuggestedQuestions: []string{"question 1", "question 2"},
       },
       IconFileID: avatarInfo.FileInfo.ID,
    })
    if err != nil {
       fmt.Println("Error creating bot:", err)
       return
    }
    botID := createResp.BotID
    fmt.Println(createResp)
    fmt.Println(createResp.LogID())

    //
    // step two, update the bot, you can update the bot after being created
    // in this examples, we will update the avatar of the bot

    publishResp, err := cozeCli.Bots.Publish(ctx, &coze.PublishBotsReq{
       BotID:        botID,
       ConnectorIDs: []string{"1024"},
    })
    if err != nil {
       fmt.Println("Error publishing bot:", err)
       return
    }
    fmt.Println(publishResp)
    fmt.Println(publishResp.LogID())

    //
    // step three, you can also modify the bot configuration and republish it.
    // in this examples, we will update the avatar of the bot

    newFile, err := os.Open(os.Getenv("IMAGE_FILE_PATH"))
    if err != nil {
       fmt.Println("Error opening file:", err)
       return
    }
    newUploadReq := &coze.UploadFilesReq{
       File: newFile,
    }
    newAvatarInfo, err := cozeCli.Files.Upload(ctx, newUploadReq)
    if err != nil {
       fmt.Println("Error uploading new avatar:", err)
       return
    }
    fmt.Println(newAvatarInfo)
    fmt.Println(newAvatarInfo.LogID())

    // Update bot
    updateResp, err := cozeCli.Bots.Update(ctx, &coze.UpdateBotsReq{
       BotID:      botID,
       IconFileID: newAvatarInfo.FileInfo.ID,
    })
    if err != nil {
       fmt.Println("Error updating bot:", err)
       return
    }
    fmt.Println(updateResp.LogID())

    // Republish bot
    publishResp, err = cozeCli.Bots.Publish(ctx, &coze.PublishBotsReq{
       BotID:        botID,
       ConnectorIDs: []string{"1024"},
    })
    if err != nil {
       fmt.Println("Error republishing bot:", err)
       return
    }
    fmt.Println(publishResp)
    fmt.Println(publishResp.LogID())
}
```

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

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

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

import (
    "context"
    "errors"
    "fmt"
    "io"
    "os"
    "time"

    "github.com/coze-dev/coze-go"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    // Get an access_token through personal access token or oauth.
    token := os.Getenv("COZE_API_TOKEN")
    botID := os.Getenv("PUBLISHED_BOT_ID")
    userID := os.Getenv("USER_ID")

    authCli := coze.NewTokenAuth(token)

    // Init the Coze client through the access_token.
    cozeCli := coze.NewCozeAPI(authCli, coze.WithBaseURL(os.Getenv("COZE_API_BASE")))

    //
    // Step one, create chats
    // Call the coze.chats().stream() method to create a chats. The create method is a streaming
    // chats and will return a Flowable ChatEvent. Developers should iterate the iterator to get
    // chats event and handle them.
    // //
    req := &coze.CreateChatsReq{
       BotID:  botID,
       UserID: userID,
       Messages: []*coze.Message{
          coze.BuildUserQuestionText("What can you do?", nil),
       },
    }

    resp, err := cozeCli.Chat.Stream(ctx, req)
    if err != nil {
       fmt.Printf("Error starting chats: %v\n", err)
       return
    }

    defer resp.Close()
    for {
       event, err := resp.Recv()
       if errors.Is(err, io.EOF) {
          fmt.Println("Stream finished")
          break
       }
       if err != nil {
          fmt.Println(err)
          break
       }
       if event.Event == coze.ChatEventConversationMessageDelta {
          fmt.Print(event.Message.Content)
       } else if event.Event == coze.ChatEventConversationChatCompleted {
          fmt.Printf("Token usage:%d\n", event.Chat.Usage.TokenCount)
       } else {
          fmt.Printf("\n")
       }
    }

    fmt.Printf("done, log:%s\n", resp.LogID())
}
```

