Categorygithub.com/coze-dev/coze-go
modulepackage
0.0.0-20250205074941-5c21d40b5904
Repository: https://github.com/coze-dev/coze-go.git
Documentation: pkg.go.dev

# README

Coze Go API SDK

codecov

Introduction

The Coze API SDK for Go is a powerful tool designed to seamlessly integrate Coze's open APIs into your Go projects.

Key Features:

  • Full support for Coze open APIs and authentication APIs
  • Both synchronous and streaming API calls
  • Optimized streaming APIs with io.Reader interface
  • Optimized list APIs with Iterator interface
  • Simple and idiomatic Go API design

Installation

go get github.com/coze-dev/coze-go

Usage

Examples

ExampleFile
pat authpat_example.go
oauth by web codeweb_oauth_example.go
oauth by jwt flowjwt_oauth_example.go
oauth by pkce flowpkce_oauth_example.go
oauth by device flowdevice_oauth_example.go
handle auth exceptionhandle_auth_exception_example.go
bot create, publish and chatpublish_bot_example.go
get bot and bot listretrieve_bot_example.go
non-stream chatnon_stream_chat_example.go
stream chatstream_chat_example.go
chat with local pluginsubmit_tool_output_example.go
chat with imagechat_with_image_example.go
non-stream workflow chatnon_stream_workflow_run_example.go
stream workflow chatstream_workflow_run_example.go
async workflow runasync_workflow_run_example.go
conversationconversation_example.go
list conversationlist_conversation_example.go
workspacelist_workspace_example.go
create update delete messagecreate_update_delete_message_example.go
list messagelist_message_example.go
create update delete documentcreate_update_delete_document_example.go
list documentslist_documents_example.go
initial clientinit_client_example.go
how to handle errorhandle_error_example.go
get response log idlog_example.go

Initialize the Coze Client

To get started, visit https://www.coze.com/open/oauth/pats (or https://www.coze.cn/open/oauth/pats for the CN environment).

Create a new token by clicking "Add Token". Configure the token name, expiration time, and required permissions. Click OK to generate your personal access token.

Important: Store your personal access token securely to prevent unauthorized access.

func main() {
    // Get an access_token through personal access token or oauth.
    token := os.Getenv("COZE_API_TOKEN")
    authCli := coze.NewTokenAuth(token)
    
    /*
     * The default access is api.coze.com, but if you need to access api.coze.cn
     * please use baseUrl to configure the API endpoint to access
     */
    baseURL := os.Getenv("COZE_API_BASE")
    cozeCli := coze.NewCozeAPI(authCli, coze.WithBaseURL(baseURL))
}

Chat

First, create a bot instance in Coze. The bot ID is the last number in the web link URL.

Non-Stream Chat

The SDK provides a convenient wrapper function for non-streaming chat operations. It handles polling and message retrieval automatically:

func main() {
    token := os.Getenv("COZE_API_TOKEN")
    botID := os.Getenv("PUBLISHED_BOT_ID")
    uid := os.Getenv("USER_ID")
    
    authCli := coze.NewTokenAuth(token)
    cozeCli := coze.NewCozeAPI(authCli, coze.WithBaseURL(os.Getenv("COZE_API_BASE")))
    
    ctx := context.Background()
    req := &coze.CreateChatReq{
        BotID:  botID,
        UserID: uid,
        Messages: []coze.Message{
            coze.BuildUserQuestionText("What can you do?", nil),
        },
    }
    
    chat, err := cozeCli.Chat.CreateAndPoll(ctx, req, nil)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    if chat.Status == coze.ChatStatusCompleted {
        fmt.Printf("Token usage: %d\n", chat.Usage.TokenCount)
    }
}

Stream Chat

Use cozeCli.Chat.Stream() to create a streaming chat session:

func main() {
    // ... initialize client as above ...
    
    ctx := context.Background()
    req := &coze.CreateChatReq{
        BotID:  botID,
        UserID: userID,
        Messages: []coze.Message{
            coze.BuildUserQuestionObjects([]coze.MessageObjectString{
                coze.NewTextMessageObject("Describe this picture"),
                coze.NewImageMessageObjectByID(imageInfo.FileInfo.ID),
            }, nil),
        },
    }
    
    resp, err := cozeCli.Chat.Stream(ctx, req)
    if err != nil {
        fmt.Println("Error starting stream:", 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)
        }
    }
}

Files

func main() {
    // ... initialize client as above ...
    
    ctx := context.Background()
    filePath := os.Getenv("FILE_PATH")
    
    // Upload file
    uploadResp, err := cozeCli.Files.Upload(ctx, coze.NewUploadFilesReqWithPath(filePath))
    if err != nil {
        fmt.Println("Error uploading file:", err)
        return
    }
    fileInfo := uploadResp.FileInfo
    
    // Wait for file processing
    time.Sleep(time.Second)
    
    // Retrieve file
    retrievedResp, err := cozeCli.Files.Retrieve(ctx, &coze.RetrieveFilesReq{
        FileID: fileInfo.ID,
    })
    if err != nil {
        fmt.Println("Error retrieving file:", err)
        return
    }
    fmt.Println(retrievedResp.FileInfo)
}

Pagination

The SDK provides an iterator interface for handling paginated results:

func main() {
    // ... initialize client as above ...
    
    ctx := context.Background()
    datasetID, _ := strconv.ParseInt(os.Getenv("DATASET_ID"), 10, 64)
    
    // Use iterator to automatically retrieve next page
    documents, err := cozeCli.Datasets.Documents.List(ctx, &coze.ListDatasetsDocumentsReq{
        Size: 1,
        DatasetID: datasetID,
    })
    if err != nil {
        fmt.Println("Error fetching documents:", err)
        return
    }
    
    for documents.Next() {
        fmt.Println(documents.Current())
    }
    
    fmt.Println("has_more:", documents.HasMore())
}

Error Handling

The SDK uses Go's standard error handling patterns. All API calls return an error value that should be checked:

resp, err := cozeCli.Chat.Create(ctx, req)
if err != nil {
    if cozeErr, ok := coze.AsCozeError(err); ok {
    // Handle Coze API error
    fmt.Printf("Coze API error: %s (code: %s)\n", cozeErr.ErrorMessage, cozeErr.ErrorCode)
    return
    }
}

# Packages

No description provided by the author

# Functions

AsAuthError 判断错误是否为 CozeAuthError 类型.
AsCozeError checks if the error is of type Error.
BuildAssistantAnswer builds an answer message from assistant.
No description provided by the author
BuildUserQuestionObjects builds an object message for user question.
BuildUserQuestionText builds a text message for user question.
DocumentBaseBuildImage creates basic document information for image type.
DocumentBaseBuildLocalFile creates basic document information for local file type.
DocumentBaseBuildWebPage creates basic document information for webpage type.
DocumentSourceInfoBuildImage creates document source information for image type.
DocumentSourceInfoBuildLocalFile creates document source information for local file type.
DocumentSourceInfoBuildWebPage creates document source information for webpage type.
DocumentUpdateRuleBuildAutoUpdate creates a rule for automatic updates with specified interval.
DocumentUpdateRuleBuildNoAuto creates a rule for no automatic updates.
LoadOAuthAppFromConfig creates an OAuth client based on the provided JSON configuration bytes.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewDeviceOAuthClient creates a new device OAuth core.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewJWTOAuthClient creates a new JWT OAuth core.
No description provided by the author
NewLevelLogger ...
No description provided by the author
No description provided by the author
No description provided by the author
NewPKCEOAuthClient creates a new PKCE OAuth core.
NewTextMessageObject Helper functions for creating MessageObjectString.
NewTokenAuth creates a new token authentication instance.
No description provided by the author
NewWebOAuthClient creates a new Web OAuth core.
ParseWorkflowEventError parses JSON string to WorkflowEventError.
ParseWorkflowEventInterrupt parses JSON string to WorkflowEventInterrupt.
WithAuthBaseURL adds base URL.
No description provided by the author
WithAuthWWWURL adds base URL.
WithBaseURL adds the base URL for the API.
WithHttpClient sets a custom HTTP core.
No description provided by the author
WithLogLevel sets the logging level.

# Constants

* The user has denied the authorization */.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
* The user has not completed authorization yet, please try again later */.
No description provided by the author
No description provided by the author
ChatEventConversationAudioDelta Audio delta event.
ChatEventConversationChatCompleted The conversation is completed.
ChatEventConversationChatCreated Event for creating a conversation, indicating the start of the conversation.
ChatEventConversationChatFailed This event is used to mark a failed conversation.
ChatEventConversationChatInProgress The server is processing the conversation.
ChatEventConversationChatRequiresAction The conversation is interrupted and requires the user to report the execution results of the tool.
ChatEventConversationMessageCompleted The message has been completely replied to.
ChatEventConversationMessageDelta Incremental message, usually an incremental message when type=answer.
ChatEventDone The streaming response for this session ended normally.
ChatEventError Error events during the streaming response process.
ChatStatusCancelled The session is user cancelled chat.
ChatStatusCompleted The Bot has finished processing, and the session has ended.
ChatStatusCreated The session has been created.
ChatStatusFailed The session has failed.
ChatStatusInProgress The Bot is processing.
ChatStatusRequiresAction The session is interrupted and requires further processing.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Document type, such as txt, pdf, online web pages, etc.
Images type, such as png images, etc.
Spreadsheet type, such as xls spreadsheets, etc.
Upload local files.
Upload online web pages.
Completed.
Processing failed, it is recommended to re-upload.
Processing.
Automatically update.
Do not automatically update.
* The token is expired */.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
已完成.
处理中.
处理失败.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
LogLevelTrace ...
LogLevelTrace ...
LogLevelTrace ...
LogLevelTrace ...
LogLevelTrace ...
MessageContentTypeAudio If there is a audioVoices message in the input message, the conversation.audio.delta event will be returned in the streaming response event.
MessageContentTypeCard This enum value only appears in the interface response and is not supported as an input parameter.
MessageContentTypeObjectString Multimodal content, that is, a combination of text and files, or a combination of text and images.
MessageContentTypeText Text.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
MessageRoleAssistant Indicates that the content of the message is sent by the bot.
No description provided by the author
MessageRoleUser Indicates that the content of the message is sent by the user.
MessageTypeAnswer The message content returned by the Bot to the user, supporting incremental return.
MessageTypeFollowUp If the user question suggestion switch is turned on in the Bot configuration, the reply content related to the recommended questions will be returned.
MessageTypeFunctionCall Intermediate results of the function (function call) called during the Bot conversation process.
MessageTypeQuestion User input content.
MessageTypeToolOutput Results returned after calling the tool (function call).
MessageTypeToolResponse Results returned after calling the tool (function call).
No description provided by the author
* The request is too frequent, please try again later */.
TemplateEntityTypeAgent represents an agent template.
End.
An error has occurred.
Interruption.
The output message from the workflow node, such as the output message from the message node or end node.
WorkflowExecuteStatusFail Execution failed.
WorkflowExecuteStatusRunning Execution in progress.
WorkflowExecuteStatusSuccess Execution succeeded.
WorkflowRunModeAsynchronous Asynchronous operation.
WorkflowRunModeStreaming Streaming operation.
WorkflowRunModeSynchronous Synchronous operation.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Structs

No description provided by the author
Bot represents complete bot information.
BotKnowledge represents bot knowledge base configuration.
BotModelInfo represents bot model information.
BotOnboardingInfo represents bot onboarding information.
BotPluginAPIInfo represents bot plugin API information.
BotPluginInfo represents bot plugin information.
BotPromptInfo represents bot prompt information.
CancelChatsReq represents the request to cancel a chat.
No description provided by the author
Chat represents chat information.
ChatError represents error information.
ChatEvent represents a chat event in the streaming response.
ChatPoll represents polling information for a chat.
ChatRequiredAction represents required action information.
ChatSubmitToolOutputs represents tool outputs that need to be submitted.
ChatToolCall represents a tool call.
ChatToolCallFunction represents a function call in a tool.
ChatUsage represents token usage information.
ClearConversationsReq represents request for clearing conversation.
No description provided by the author
CloneAudioVoicesReq represents the request for cloning a voice.
CloneAudioVoicesResp represents the response for cloning a voice.
Conversation represents conversation information.
No description provided by the author
CreateAudioRoomsReq represents the request for creating an audio room.
CreateAudioRoomsResp represents the response for creating an audio room.
CreateAudioSpeechReq represents the request for creating speech.
CreateAudioSpeechResp represents the response for creating speech.
No description provided by the author
No description provided by the author
CreateChatsReq represents the request to create a chat.
No description provided by the author
CreateConversationsReq represents request for creating conversation.
No description provided by the author
No description provided by the author
CreateDatasetsDocumentsReq represents request for creating document.
CreateDatasetsDocumentsResp represents response for creating document.
CreateDatasetsReq 表示创建数据集的请求.
CreateMessageReq represents request for creating message.
CreateMessageResp represents response for creating message.
Dataset 表示数据集信息.
DeleteConversationsMessagesReq represents request for deleting message.
DeleteConversationsMessagesResp represents response for creating message.
DeleteDatasetsDocumentsReq represents request for deleting datasetsDocuments.
DeleteDatasetsDocumentsResp represents response for deleting datasetsDocuments.
DeleteDatasetsReq 表示删除数据集的请求.
No description provided by the author
DeviceAuthReq represents the device authorization request.
DeviceOAuthClient represents the device OAuth core.
Document represents a document in the datasets.
DocumentBase represents base information for creating a document.
DocumentChunkStrategy represents chunking strategy for datasetsDocuments.
DocumentProgress 表示文档处理进度.
DocumentSourceInfo represents source information for a document.
DocumentUpdateRule represents update rules for datasetsDocuments.
DuplicateTemplateReq represents the request to duplicate a template.
No description provided by the author
FileInfo represents information about a file.
GetDeviceAuthResp represents the device authorization response.
No description provided by the author
No description provided by the author
GetJWTAccessTokenReq represents options for getting JWT OAuth token.
No description provided by the author
No description provided by the author
GetPKCEOAuthURLResp represents the PKCE authorization URL response.
No description provided by the author
No description provided by the author
Image 表示图片信息.
JWTOAuthClient represents the JWT OAuth core.
ListAudioVoicesReq represents the request for listing voices.
ListAudioVoicesResp represents the response for listing voices.
ListBotsReq represents the request structure for listing bots.
ListChatsMessagesReq represents the request to list messages.
No description provided by the author
ListConversationsMessagesReq represents request for listing messages.
No description provided by the author
ListConversationsReq represents request for listing conversations.
ListConversationsResp represents response for listing conversations.
ListDatasetsDocumentsReq represents request for listing datasetsDocuments.
ListDatasetsDocumentsResp represents response for listing datasetsDocuments.
ListDatasetsImagesReq 表示列出图片的请求.
ListDatasetsReq 表示列出数据集的请求.
No description provided by the author
No description provided by the author
ListWorkspaceReq represents the request parameters for listing workspaces.
ListWorkspaceResp represents the response for listing workspaces.
Message represents a message in conversation.
MessageObjectString represents a multimodal message object.
No description provided by the author
OAuthClient represents the base OAuth core structure.
OAuthConfig represents the configuration for OAuth clients.
OAuthToken represents the OAuth token response.
PKCEOAuthClient PKCE OAuth core.
ProcessDocumentsReq 表示处理文档的请求.
No description provided by the author
PublishBotsReq represents the request structure for publishing a bot.
No description provided by the author
ResumeRunWorkflowsReq represents request for resuming workflow runs.
RetrieveBotsReq represents the request structure for retrieving a bot.
No description provided by the author
RetrieveChatsReq represents the request to retrieve a chat.
No description provided by the author
RetrieveConversationsMessagesReq represents request for retrieving message.
RetrieveConversationsMessagesResp represents response for creating message.
RetrieveConversationsReq represents request for retrieving conversation.
No description provided by the author
RetrieveFilesReq represents request for retrieving file.
RetrieveFilesResp represents response for retrieving file.
RetrieveWorkflowRunsHistoriesResp represents response for retrieving workflow runs history.
RetrieveWorkflowsRunsHistoriesReq represents request for retrieving workflow runs history.
RoomAudioConfig represents the room audio configuration.
RoomConfig represents the room configuration.
RunWorkflowsReq represents request for running workflow.
RunWorkflowsResp represents response for running workflow.
Scope represents the OAuth scope.
ScopeAccountPermission represents the account permissions in the scope.
ScopeAttributeConstraint represents the attribute constraints in the scope.
ScopeAttributeConstraintConnectorBotChatAttribute represents the bot chat attributes.
SimpleBot represents simplified bot information.
SubmitToolOutputsChatReq represents the request to submit tool outputs.
No description provided by the author
TemplateDuplicateResp represents the response from duplicating a template.
ToolOutput represents the output of a tool.
UpdateBotsReq represents the request structure for updating a bot.
No description provided by the author
UpdateConversationMessagesReq represents request for updating message.
UpdateConversationMessagesResp represents response for creating message.
UpdateDatasetImageReq 表示更新图片的请求.
No description provided by the author
UpdateDatasetsDocumentsReq represents request for updating document.
UpdateDatasetsDocumentsResp represents response for updating document.
UpdateDatasetsReq 表示更新数据集的请求.
No description provided by the author
No description provided by the author
UploadFilesResp represents response for uploading file.
User represents a Coze user.
Voice represents the voice model.
WebOAuthClient Web OAuth core.
WorkflowEvent represents an event in a workflow.
WorkflowEventError represents an error event in a workflow.
WorkflowEventInterrupt represents an interruption event in a workflow.
WorkflowEventInterruptData represents the data of an interruption event.
WorkflowEventMessage represents a message event in a workflow.
WorkflowRunHistory represents the history of a workflow runs.
WorkflowRunResult represents the result of a workflow runs.
WorkflowsChatStreamReq 表示工作流聊天流式请求.
Workspace represents workspace information.

# Interfaces

No description provided by the author
No description provided by the author
No description provided by the author
HTTPClient an interface for making HTTP requests.
No description provided by the author
No description provided by the author
No description provided by the author
Logger ...
No description provided by the author
No description provided by the author
No description provided by the author

# Type aliases

AudioCodec represents the audio codec.
AudioFormat represents the audio format type.
AuthErrorCode represents authentication error codes.
BotMode represents the bot mode.
ChatEventType Event types for chat.
ChatStatus The running status of the session.
CodeChallengeMethod represents the code challenge method.
No description provided by the author
DatasetStatus 表示数据集状态.
DocumentFormatType represents the format type of a document.
DocumentSourceType represents the source type of a document.
DocumentStatus represents the status of a document.
DocumentUpdateType represents the update type of a document.
GrantType represents the OAuth grant type.
ImageStatus 表示图片状态.
LanguageCode represents the language code.
No description provided by the author
MessageContentType represents the type of message content.
MessageObjectStringType represents the type of multimodal message content.
MessageRole represents the role of message sender.
MessageType represents the type of message.
No description provided by the author
PageFetcher interface.
RequestOption 请求选项函数类型.
TemplateEntityType represents the type of template entity.
WorkflowEventType represents the type of workflow event.
WorkflowExecuteStatus represents the execution status of a workflow.
WorkflowRunMode represents how the workflow runs.
WorkspaceRoleType represents the workspace role type.
WorkspaceType represents the workspace type.