### Install Coze Go API SDK Source: https://github.com/coze-dev/coze-go/blob/main/README.md Use 'go get' to install the Coze Go API SDK. Ensure you have Go installed and configured. ```bash go get github.com/coze-dev/coze-go ``` -------------------------------- ### Install Dependencies Source: https://github.com/coze-dev/coze-go/blob/main/CONTRIBUTING.md Run this command to install or update project dependencies using Go modules. ```shell go mod tidy ``` -------------------------------- ### Build Project Source: https://github.com/coze-dev/coze-go/blob/main/CONTRIBUTING.md Compile the project to produce executable binaries. ```shell go build ./... ``` -------------------------------- ### File Upload and Retrieval with Coze Go SDK Source: https://github.com/coze-dev/coze-go/blob/main/README.md Demonstrates uploading a file using its path and then retrieving its information. Ensure the FILE_PATH environment variable is set. ```go 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) } ``` -------------------------------- ### Files Upload and Retrieve Source: https://github.com/coze-dev/coze-go/blob/main/README.md Demonstrates how to upload a file and then retrieve its information using the Coze Go SDK. ```APIDOC ## Files Upload and Retrieve ### Description Uploads a file to Coze and then retrieves its details. ### Methods 1. `cozeCli.Files.Upload(ctx context.Context, req *coze.UploadFilesReq) (*coze.UploadFilesResp, error)` 2. `cozeCli.Files.Retrieve(ctx context.Context, req *coze.RetrieveFilesReq) (*coze.RetrieveFilesResp, error)` ### Parameters #### Upload Files - **Request Body** (`coze.NewUploadFilesReqWithPath(filePath string)`) - **FilePath** (string) - Required - The path to the file to upload. #### Retrieve Files - **Request Body** (`coze.RetrieveFilesReq`) - **FileID** (string) - Required - The ID of the file to retrieve. ### Request Example ```go // Upload file uploadResp, err := cozeCli.Files.Upload(ctx, coze.NewUploadFilesReqWithPath(filePath)) if err != nil { fmt.Println("Error uploading file:", err) return } fileInfo := uploadResp.FileInfo // 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) ``` ### Response #### Success Response (200) - **FileInfo** (coze.FileInfo) - Information about the uploaded or retrieved file. ``` -------------------------------- ### Initialize Coze Client with Token Source: https://github.com/coze-dev/coze-go/blob/main/README.md Initialize the Coze client using a personal access token (PAT) or OAuth. The COZE_API_TOKEN environment variable should contain your token. Optionally, configure a custom base URL for the CN environment using COZE_API_BASE. ```go 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)) } ``` -------------------------------- ### Check Code Format Source: https://github.com/coze-dev/coze-go/blob/main/CONTRIBUTING.md Use `gofumpt` to check and automatically format the code according to project standards. ```shell gofumpt -l -w . ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/coze-dev/coze-go/blob/main/CONTRIBUTING.md Run tests and generate a coverage report. The report can be viewed in a web browser. ```shell go test -coverprofile=coverage.out ./... ``` ```shell go tool cover -html=coverage.out ``` -------------------------------- ### Run All Tests Source: https://github.com/coze-dev/coze-go/blob/main/CONTRIBUTING.md Execute all tests within the project to ensure code correctness. ```shell go test ./... ``` -------------------------------- ### Generate Audio: Success Response (Go) Source: https://github.com/coze-dev/coze-go/blob/main/testdata/websocket_chat_generate_audio_success.txt Handles a successful response when generating audio. This snippet focuses on the structure of a successful audio generation response. ```Go func (c *Client) GenerateAudio(ctx context.Context, req *GenerateAudioReq) (*GenerateAudioResp, error) { resp := &GenerateAudioResp{} err := c.c.WriteJSON(req) if err != nil { return nil, fmt.Errorf("write json failed: %w", err) } err = c.c.ReadJSON(resp) if err != nil { return nil, fmt.Errorf("read json failed: %w", err) } return resp, nil } ``` -------------------------------- ### WebSocket Chat: Send Message (Go) Source: https://github.com/coze-dev/coze-go/blob/main/testdata/websocket_chat_generate_audio_success.txt Demonstrates sending a message over a WebSocket connection for chat functionality. Ensure the WebSocket is properly initialized before use. ```Go func (c *Client) SendMessage(ctx context.Context, req *SendMessageReq) (*SendMessageResp, error) { resp := &SendMessageResp{} err := c.c.WriteJSON(req) if err != nil { return nil, fmt.Errorf("write json failed: %w", err) } var v interface{} err = c.c.ReadJSON(&v) if err != nil { return nil, fmt.Errorf("read json failed: %w", err) } return resp, nil } ``` -------------------------------- ### Pagination with Iterator Source: https://github.com/coze-dev/coze-go/blob/main/README.md Shows how to use the SDK's iterator interface to handle paginated results, specifically for listing dataset documents. ```APIDOC ## Pagination with Iterator ### Description Utilizes an iterator interface to automatically handle paginated results when listing dataset documents. ### Method `cozeCli.Datasets.Documents.List(ctx context.Context, req *coze.ListDatasetsDocumentsReq) (*coze.ListDatasetsDocumentsRespIterator, error)` ### Parameters #### Path Parameters None #### Query Parameters - **Size** (int) - Optional - The number of items per page. - **DatasetID** (int64) - Required - The ID of the dataset. ### Request Example ```go 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()) ``` ### Response #### Success Response (200) - **Iterator** (`coze.ListDatasetsDocumentsRespIterator`) - An iterator to traverse through paginated results. - `Next() bool` - Advances the iterator to the next item. - `Current() interface{}` - Returns the current item. - `HasMore() bool` - Indicates if there are more pages available. ``` -------------------------------- ### Stream Chat with Coze Go SDK Source: https://github.com/coze-dev/coze-go/blob/main/README.md Initiate a streaming chat session using cozeCli.Chat.Stream(). This is suitable for real-time responses. Remember to close the response stream using defer resp.Close(). ```go 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) } } } ``` -------------------------------- ### Paginated Data Listing with Coze Go SDK Iterator Source: https://github.com/coze-dev/coze-go/blob/main/README.md Handles paginated results using an iterator interface for automatic page retrieval. Requires the DATASET_ID environment variable to be set. ```go 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 Source: https://github.com/coze-dev/coze-go/blob/main/README.md Explains how the Coze Go SDK handles errors using Go's standard error patterns and provides a way to check for specific Coze API errors. ```APIDOC ## Error Handling ### Description Demonstrates how to check for and handle errors returned by the Coze Go SDK, including specific Coze API errors. ### Method All API calls return an `error` value which should be checked. ### Error Checking Use `coze.AsCozeError(err)` to check if an error is a Coze API error. ### Response #### Coze API Error Structure - **ErrorMessage** (string) - A human-readable error message from the Coze API. - **ErrorCode** (string) - A specific code identifying the error. ### Error Handling Example ```go 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 } // Handle other types of errors } ``` ``` -------------------------------- ### Coze Go SDK Error Handling Source: https://github.com/coze-dev/coze-go/blob/main/README.md Illustrates Go's standard error handling patterns for API calls. It shows how to check for errors and specifically handle Coze API errors by type assertion. ```go 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 } } ``` -------------------------------- ### Stream Chat Source: https://github.com/coze-dev/coze-go/blob/main/README.md Initiates a streaming chat session using `cozeCli.Chat.Stream()`, allowing for real-time message processing. ```APIDOC ## Stream Chat ### Description Creates a streaming chat session for real-time message processing. ### Method `cozeCli.Chat.Stream(ctx context.Context, req *coze.CreateChatReq, opts ...coze.Option) (*coze.ChatStreamResponse, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **BotID** (string) - Required - The ID of the bot. - **UserID** (string) - Required - The ID of the user. - **Messages** ([]coze.Message) - Required - A list of messages for the chat, can include text and image objects. ### Request Example ```go 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), }, } ``` ### Response #### Success Response (200) - **Event** (string) - The type of event received (e.g., `coze.ChatEventConversationMessageDelta`, `coze.ChatEventConversationChatCompleted`). - **Message** (coze.Message) - The chat message content when `Event` is `coze.ChatEventConversationMessageDelta`. - **Chat** (coze.Chat) - Chat completion details when `Event` is `coze.ChatEventConversationChatCompleted`. #### Response Example ```go 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) } } ``` ``` -------------------------------- ### WebSocket Chat: Receive Message (Go) Source: https://github.com/coze-dev/coze-go/blob/main/testdata/websocket_chat_generate_audio_success.txt Illustrates receiving messages from a WebSocket connection. This is crucial for real-time chat applications. The code assumes a valid WebSocket connection is established. ```Go func (c *Client) ReceiveMessage(ctx context.Context) (interface{}, error) { var v interface{} err := c.c.ReadJSON(&v) if err != nil { return nil, fmt.Errorf("read json failed: %w", err) } return v, nil } ``` -------------------------------- ### Non-Stream Chat Source: https://github.com/coze-dev/coze-go/blob/main/README.md This function demonstrates how to perform non-streaming chat operations using the Coze Go SDK. It automatically handles polling and message retrieval. ```APIDOC ## Non-Stream Chat ### Description Performs non-streaming chat operations, automatically handling polling and message retrieval. ### Method `cozeCli.Chat.CreateAndPoll(ctx context.Context, req *coze.CreateChatReq, opts ...coze.Option) (*coze.Chat, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **BotID** (string) - Required - The ID of the bot. - **UserID** (string) - Required - The ID of the user. - **Messages** ([]coze.Message) - Required - A list of messages for the chat. ### Request Example ```go req := &coze.CreateChatReq{ BotID: botID, UserID: uid, Messages: []coze.Message{ coze.BuildUserQuestionText("What can you do?", nil), }, } ``` ### Response #### Success Response (200) - **Status** (coze.ChatStatus) - The status of the chat. - **Usage** (coze.Usage) - Token usage information. #### Response Example ```go if chat.Status == coze.ChatStatusCompleted { fmt.Printf("Token usage: %d\n", chat.Usage.TokenCount) } ``` ``` -------------------------------- ### Non-Stream Chat with Coze Go SDK Source: https://github.com/coze-dev/coze-go/blob/main/README.md Use this function for non-streaming chat operations. It automatically handles polling and message retrieval. Ensure COZE_API_TOKEN, PUBLISHED_BOT_ID, and USER_ID environment variables are set. ```go 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) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.