coze

package module
v0.0.0-...-7d7c88a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 6, 2025 License: MIT Imports: 22 Imported by: 0

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
Example File
pat auth pat_example.go
oauth by web code web_oauth_example.go
oauth by jwt flow jwt_oauth_example.go
oauth by pkce flow pkce_oauth_example.go
oauth by device flow device_oauth_example.go
handle auth exception handle_auth_exception_example.go
bot create, publish and chat publish_bot_example.go
get bot and bot list retrieve_bot_example.go
non-stream chat non_stream_chat_example.go
stream chat stream_chat_example.go
chat with local plugin submit_tool_output_example.go
chat with image chat_with_image_example.go
non-stream workflow chat non_stream_workflow_run_example.go
stream workflow chat stream_workflow_run_example.go
async workflow run async_workflow_run_example.go
conversation conversation_example.go
list conversation list_conversation_example.go
workspace list_workspace_example.go
create update delete message create_update_delete_message_example.go
list message list_message_example.go
create update delete document create_update_delete_document_example.go
list documents list_documents_example.go
initial client init_client_example.go
how to handle error handle_error_example.go
get response log id log_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
    }
}

Documentation

Index

Constants

View Source
const (
	ComBaseURL = "https://api.coze.com"
	CnBaseURL  = "https://api.coze.cn"
)

Variables

This section is empty.

Functions

func LoadOAuthAppFromConfig

func LoadOAuthAppFromConfig(config *OAuthConfig) (interface{}, error)

LoadOAuthAppFromConfig creates an OAuth client based on the provided JSON configuration bytes

Types

type AudioCodec

type AudioCodec string

AudioCodec represents the audio codec

const (
	AudioCodecAACLC AudioCodec = "AACLC"
	AudioCodecG711A AudioCodec = "G711A"
	AudioCodecOPUS  AudioCodec = "OPUS"
	AudioCodecG722  AudioCodec = "G722"
)

type AudioFormat

type AudioFormat string

AudioFormat represents the audio format type

const (
	AudioFormatWAV     AudioFormat = "wav"
	AudioFormatPCM     AudioFormat = "pcm"
	AudioFormatOGGOPUS AudioFormat = "ogg_opus"
	AudioFormatM4A     AudioFormat = "m4a"
	AudioFormatAAC     AudioFormat = "aac"
	AudioFormatMP3     AudioFormat = "mp3"
)

func (AudioFormat) Ptr

func (f AudioFormat) Ptr() *AudioFormat

func (AudioFormat) String

func (f AudioFormat) String() string

type Auth

type Auth interface {
	Token(ctx context.Context) (string, error)
}

func NewJWTAuth

func NewJWTAuth(client *JWTOAuthClient, opt *GetJWTAccessTokenReq) Auth

func NewTokenAuth

func NewTokenAuth(accessToken string) Auth

NewTokenAuth creates a new token authentication instance.

type AuthError

type AuthError struct {
	HttpCode     int
	Code         AuthErrorCode
	ErrorMessage string
	Param        string
	LogID        string
	// contains filtered or unexported fields
}

func AsAuthError

func AsAuthError(err error) (*AuthError, bool)

AsAuthError 判断错误是否为 CozeAuthError 类型

func NewAuthError

func NewAuthError(error *authErrorFormat, statusCode int, logID string) *AuthError

func (*AuthError) Error

func (e *AuthError) Error() string

Error implements the error interface

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

Unwrap returns the parent error

type AuthErrorCode

type AuthErrorCode string

AuthErrorCode represents authentication error codes

const (
	/*
	 * The user has not completed authorization yet, please try again later
	 */
	AuthorizationPending AuthErrorCode = "authorization_pending"
	/*
	 * The request is too frequent, please try again later
	 */
	SlowDown AuthErrorCode = "slow_down"
	/*
	 * The user has denied the authorization
	 */
	AccessDenied AuthErrorCode = "access_denied"
	/*
	 * The token is expired
	 */
	ExpiredToken AuthErrorCode = "expired_token"
)

func (AuthErrorCode) String

func (c AuthErrorCode) String() string

String implements the Stringer interface

type BasePaged

type BasePaged[T any] interface {
	Err() error
	Items() []*T
	Current() *T
	Next() bool
	HasMore() bool
}

type Bot

type Bot struct {
	BotID          string             `json:"bot_id"`
	Name           string             `json:"name"`
	Description    string             `json:"description,omitempty"`
	IconURL        string             `json:"icon_url,omitempty"`
	CreateTime     int64              `json:"create_time"`
	UpdateTime     int64              `json:"update_time"`
	Version        string             `json:"version,omitempty"`
	PromptInfo     *BotPromptInfo     `json:"prompt_info,omitempty"`
	OnboardingInfo *BotOnboardingInfo `json:"onboarding_info,omitempty"`
	BotMode        BotMode            `json:"bot_mode"`
	PluginInfoList []*BotPluginInfo   `json:"plugin_info_list,omitempty"`
	ModelInfo      *BotModelInfo      `json:"model_info,omitempty"`
}

Bot represents complete bot information

type BotKnowledge

type BotKnowledge struct {
	DatasetIDs     []string `json:"dataset_ids"`
	AutoCall       bool     `json:"auto_call"`
	SearchStrategy int      `json:"search_strategy"`
}

BotKnowledge represents bot knowledge base configuration

type BotMode

type BotMode int

BotMode represents the bot mode

const (
	BotModeMultiAgent          BotMode = 1
	BotModeSingleAgentWorkflow BotMode = 0
)

type BotModelInfo

type BotModelInfo struct {
	ModelID   string `json:"model_id"`
	ModelName string `json:"model_name"`
}

BotModelInfo represents bot model information

type BotModelInfoConfig

type BotModelInfoConfig struct {
	TopK             int     `json:"top_k,omitempty"`
	TopP             float64 `json:"top_p,omitempty"`
	ModelID          string  `json:"model_id"`
	MaxTokens        int     `json:"max_tokens,omitempty"`
	Temperature      float64 `json:"temperature,omitempty"`
	ContextRound     int     `json:"context_round,omitempty"`
	ResponseFormat   string  `json:"response_format,omitempty"` // text,markdown,json
	PresencePenalty  float64 `json:"presence_penalty,omitempty"`
	FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
}

type BotOnboardingInfo

type BotOnboardingInfo struct {
	Prologue           string   `json:"prologue,omitempty"`
	SuggestedQuestions []string `json:"suggested_questions,omitempty"`
}

BotOnboardingInfo represents bot onboarding information

type BotPluginAPIInfo

type BotPluginAPIInfo struct {
	APIID       string `json:"api_id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
}

BotPluginAPIInfo represents bot plugin API information

type BotPluginInfo

type BotPluginInfo struct {
	PluginID    string              `json:"plugin_id"`
	Name        string              `json:"name"`
	Description string              `json:"description,omitempty"`
	IconURL     string              `json:"icon_url,omitempty"`
	APIInfoList []*BotPluginAPIInfo `json:"api_info_list,omitempty"`
}

BotPluginInfo represents bot plugin information

type BotPromptInfo

type BotPromptInfo struct {
	Prompt string `json:"prompt"`
}

BotPromptInfo represents bot prompt information

type CancelChatsReq

type CancelChatsReq struct {
	// The Conversation ID can be viewed in the 'conversation_id' field of the Response when
	// initiating a conversation through the Chat API.
	ConversationID string `json:"conversation_id"`

	// The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the
	// Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response.
	ChatID string `json:"chat_id"`
}

CancelChatsReq represents the request to cancel a chat

type CancelChatsResp

type CancelChatsResp struct {
	Chat
	// contains filtered or unexported fields
}

func (*CancelChatsResp) LogID

func (r *CancelChatsResp) LogID() string

func (*CancelChatsResp) Response

func (r *CancelChatsResp) Response() HTTPResponse

type Chat

type Chat struct {
	// The ID of the chat.
	ID string `json:"id"`
	// The ID of the conversation.
	ConversationID string `json:"conversation_id"`
	// The ID of the bot.
	BotID string `json:"bot_id"`
	// Indicates the create time of the chat. The value format is Unix timestamp in seconds.
	CreatedAt int `json:"created_at"`
	// Indicates the end time of the chat. The value format is Unix timestamp in seconds.
	CompletedAt int `json:"completed_at,omitempty"`
	// Indicates the failure time of the chat. The value format is Unix timestamp in seconds.
	FailedAt int `json:"failed_at,omitempty"`
	// Additional information when creating a message, and this additional information will also be
	// returned when retrieving messages.
	MetaData map[string]string `json:"meta_data,omitempty"`
	// When the chat encounters an auth_error, this field returns detailed error information.
	LastError *ChatError `json:"last_error,omitempty"`
	// The running status of the session.
	Status ChatStatus `json:"status"`
	// Details of the information needed for execution.
	RequiredAction *ChatRequiredAction `json:"required_action,omitempty"`
	// Detailed information about Token consumption.
	Usage *ChatUsage `json:"usage,omitempty"`
}

Chat represents chat information

type ChatError

type ChatError struct {
	// The error code. An integer type. 0 indicates success, other values indicate failure.
	Code int `json:"code"`
	// The error message. A string type.
	Msg string `json:"msg"`
}

ChatError represents error information

type ChatEvent

type ChatEvent struct {
	Event   ChatEventType `json:"event"`
	Chat    *Chat         `json:"chat,omitempty"`
	Message *Message      `json:"message,omitempty"`
}

ChatEvent represents a chat event in the streaming response

func (*ChatEvent) IsDone

func (c *ChatEvent) IsDone() bool

type ChatEventType

type ChatEventType string

ChatEventType Event types for chat.

const (
	// ChatEventConversationChatCreated Event for creating a conversation, indicating the start of the conversation.
	ChatEventConversationChatCreated ChatEventType = "conversation.chat.created"
	// ChatEventConversationChatInProgress The server is processing the conversation.
	ChatEventConversationChatInProgress ChatEventType = "conversation.chat.in_progress"
	// ChatEventConversationMessageDelta Incremental message, usually an incremental message when type=answer.
	ChatEventConversationMessageDelta ChatEventType = "conversation.message.delta"
	// ChatEventConversationMessageCompleted The message has been completely replied to.
	ChatEventConversationMessageCompleted ChatEventType = "conversation.message.completed"
	// ChatEventConversationChatCompleted The conversation is completed.
	ChatEventConversationChatCompleted ChatEventType = "conversation.chat.completed"
	// ChatEventConversationChatFailed This event is used to mark a failed conversation.
	ChatEventConversationChatFailed ChatEventType = "conversation.chat.failed"
	// ChatEventConversationChatRequiresAction The conversation is interrupted and requires the user to report the execution results of the tool.
	ChatEventConversationChatRequiresAction ChatEventType = "conversation.chat.requires_action"
	// ChatEventConversationAudioDelta Audio delta event
	ChatEventConversationAudioDelta ChatEventType = "conversation.audio.delta"
	// ChatEventError Error events during the streaming response process.
	ChatEventError ChatEventType = "error"
	// ChatEventDone The streaming response for this session ended normally.
	ChatEventDone ChatEventType = "done"
)

type ChatPoll

type ChatPoll struct {
	Chat     *Chat      `json:"chat"`
	Messages []*Message `json:"messages"`
}

ChatPoll represents polling information for a chat

type ChatRequiredAction

type ChatRequiredAction struct {
	// The type of additional operation, with the enum value of submit_tool_outputs.
	Type string `json:"type"`
	// Details of the results that need to be submitted, uploaded through the submission API, and the
	// chat can continue afterward.
	SubmitToolOutputs *ChatSubmitToolOutputs `json:"submit_tool_outputs,omitempty"`
}

ChatRequiredAction represents required action information

type ChatStatus

type ChatStatus string

ChatStatus The running status of the session.

const (
	// ChatStatusCreated The session has been created.
	ChatStatusCreated ChatStatus = "created"
	// ChatStatusInProgress The Bot is processing.
	ChatStatusInProgress ChatStatus = "in_progress"
	// ChatStatusCompleted The Bot has finished processing, and the session has ended.
	ChatStatusCompleted ChatStatus = "completed"
	// ChatStatusFailed The session has failed.
	ChatStatusFailed ChatStatus = "failed"
	// ChatStatusRequiresAction The session is interrupted and requires further processing.
	ChatStatusRequiresAction ChatStatus = "requires_action"
	// ChatStatusCancelled The session is user cancelled chat.
	ChatStatusCancelled ChatStatus = "canceled"
)

type ChatSubmitToolOutputs

type ChatSubmitToolOutputs struct {
	// Details of the specific reported information.
	ToolCalls []*ChatToolCall `json:"tool_calls"`
}

ChatSubmitToolOutputs represents tool outputs that need to be submitted

type ChatToolCall

type ChatToolCall struct {
	// The ID for reporting the running results.
	ID string `json:"id"`
	// The type of tool, with the enum value of function.
	Type string `json:"type"`
	// The definition of the execution method function.
	Function *ChatToolCallFunction `json:"function"`
}

ChatToolCall represents a tool call

type ChatToolCallFunction

type ChatToolCallFunction struct {
	// The name of the method.
	Name string `json:"name"`
	// The parameters of the method.
	Arguments string `json:"arguments"`
}

ChatToolCallFunction represents a function call in a tool

type ChatUsage

type ChatUsage struct {
	// The total number of Tokens consumed in this chat, including the consumption for both the input
	// and output parts.
	TokenCount int `json:"token_count"`
	// The total number of Tokens consumed for the output part.
	OutputCount int `json:"output_count"`
	// The total number of Tokens consumed for the input part.
	InputCount int `json:"input_count"`
}

ChatUsage represents token usage information

type ClearConversationsReq

type ClearConversationsReq struct {
	// The ID of the conversation.
	ConversationID string `json:"conversation_id"`
}

ClearConversationsReq represents request for clearing conversation

type ClearConversationsResp

type ClearConversationsResp struct {
	ConversationID string `json:"conversation_id"`
	// contains filtered or unexported fields
}

func (*ClearConversationsResp) LogID

func (r *ClearConversationsResp) LogID() string

func (*ClearConversationsResp) Response

func (r *ClearConversationsResp) Response() HTTPResponse

type CloneAudioVoicesReq

type CloneAudioVoicesReq struct {
	VoiceName   string
	File        io.Reader
	AudioFormat AudioFormat
	Language    *LanguageCode
	VoiceID     *string
	PreviewText *string
	Text        *string
	SpaceID     *string
	Description *string
}

CloneAudioVoicesReq represents the request for cloning a voice

type CloneAudioVoicesResp

type CloneAudioVoicesResp struct {
	VoiceID string `json:"voice_id"`
	// contains filtered or unexported fields
}

CloneAudioVoicesResp represents the response for cloning a voice

func (*CloneAudioVoicesResp) LogID

func (r *CloneAudioVoicesResp) LogID() string

func (*CloneAudioVoicesResp) Response

func (r *CloneAudioVoicesResp) Response() HTTPResponse

type CodeChallengeMethod

type CodeChallengeMethod string

CodeChallengeMethod represents the code challenge method

const (
	CodeChallengeMethodPlain CodeChallengeMethod = "plain"
	CodeChallengeMethodS256  CodeChallengeMethod = "S256"
)

func (CodeChallengeMethod) Ptr

func (CodeChallengeMethod) String

func (m CodeChallengeMethod) String() string

type Conversation

type Conversation struct {
	// The ID of the conversation
	ID string `json:"id"`

	// Indicates the create time of the conversation. The value format is Unix timestamp in seconds.
	CreatedAt int `json:"created_at"`

	// Additional information when creating a message, and this additional information will also be
	// returned when retrieving messages.
	MetaData map[string]string `json:"meta_data,omitempty"`

	// section_id is used to distinguish the context sections of the session history.
	// The same section is one context.
	LastSectionID string `json:"last_section_id"`
}

Conversation represents conversation information

type CozeAPI

type CozeAPI struct {
	Audio         *audio
	Bots          *bots
	Chat          *chat
	Conversations *conversations
	Workflows     *workflows
	Workspaces    *workspace
	Datasets      *datasets
	Files         *files
	Templates     *templates
	Users         *users
	// contains filtered or unexported fields
}

func NewCozeAPI

func NewCozeAPI(auth Auth, opts ...CozeAPIOption) CozeAPI

type CozeAPIOption

type CozeAPIOption func(*newCozeAPIOpt)

func WithBaseURL

func WithBaseURL(baseURL string) CozeAPIOption

WithBaseURL adds the base URL for the API

func WithHttpClient

func WithHttpClient(client *http.Client) CozeAPIOption

WithHttpClient sets a custom HTTP core

func WithLogLevel

func WithLogLevel(level LogLevel) CozeAPIOption

WithLogLevel sets the logging level

func WithLogger

func WithLogger(logger Logger) CozeAPIOption

type CreateAudioRoomsReq

type CreateAudioRoomsReq struct {
	BotID          string      `json:"bot_id"`
	ConversationID string      `json:"conversation_id,omitempty"`
	VoiceID        string      `json:"voice_id,omitempty"`
	UID            string      `json:"uid,omitempty"`
	Config         *RoomConfig `json:"config,omitempty"`
}

CreateAudioRoomsReq represents the request for creating an audio room

type CreateAudioRoomsResp

type CreateAudioRoomsResp struct {
	RoomID string `json:"room_id"`
	AppID  string `json:"app_id"`
	Token  string `json:"token"`
	UID    string `json:"uid"`
	// contains filtered or unexported fields
}

CreateAudioRoomsResp represents the response for creating an audio room

func (*CreateAudioRoomsResp) LogID

func (r *CreateAudioRoomsResp) LogID() string

func (*CreateAudioRoomsResp) Response

func (r *CreateAudioRoomsResp) Response() HTTPResponse

type CreateAudioSpeechReq

type CreateAudioSpeechReq struct {
	Input          string       `json:"input"`
	VoiceID        string       `json:"voice_id"`
	ResponseFormat *AudioFormat `json:"response_format"`
	Speed          *float32     `json:"speed"`
}

CreateAudioSpeechReq represents the request for creating speech

type CreateAudioSpeechResp

type CreateAudioSpeechResp struct {

	// TODO 没有 json tag?
	Data io.ReadCloser
	// contains filtered or unexported fields
}

CreateAudioSpeechResp represents the response for creating speech

func (*CreateAudioSpeechResp) GetCode

func (r *CreateAudioSpeechResp) GetCode() int

func (*CreateAudioSpeechResp) GetMsg

func (r *CreateAudioSpeechResp) GetMsg() string

func (*CreateAudioSpeechResp) LogID

func (r *CreateAudioSpeechResp) LogID() string

func (*CreateAudioSpeechResp) SetCode

func (r *CreateAudioSpeechResp) SetCode(code int)

func (*CreateAudioSpeechResp) SetHTTPResponse

func (r *CreateAudioSpeechResp) SetHTTPResponse(httpResponse *httpResponse)

func (*CreateAudioSpeechResp) SetMsg

func (r *CreateAudioSpeechResp) SetMsg(msg string)

func (*CreateAudioSpeechResp) WriteToFile

func (c *CreateAudioSpeechResp) WriteToFile(path string) error

type CreateBotsReq

type CreateBotsReq struct {
	SpaceID         string              `json:"space_id"`          // Space ID
	Name            string              `json:"name"`              // Name
	Description     string              `json:"description"`       // Description
	IconFileID      string              `json:"icon_file_id"`      // Icon file ID
	PromptInfo      *BotPromptInfo      `json:"prompt_info"`       // Prompt information
	OnboardingInfo  *BotOnboardingInfo  `json:"onboarding_info"`   // Onboarding information
	ModelInfoConfig *BotModelInfoConfig `json:"model_info_config"` // ModelInfoConfig information
}

type CreateBotsResp

type CreateBotsResp struct {
	BotID string `json:"bot_id"`
	// contains filtered or unexported fields
}

func (*CreateBotsResp) LogID

func (r *CreateBotsResp) LogID() string

func (*CreateBotsResp) Response

func (r *CreateBotsResp) Response() HTTPResponse

type CreateChatsReq

type CreateChatsReq struct {
	// Indicate which conversation the chat is taking place in.
	ConversationID string `json:"-"`

	// The ID of the bot that the API interacts with.
	BotID string `json:"bot_id"`

	// The user who calls the API to chat with the bot.
	UserID string `json:"user_id"`

	// Additional information for the conversation. You can pass the user's query for this
	// conversation through this field. The array length is limited to 100, meaning up to 100 messages can be input.
	Messages []*Message `json:"additional_messages,omitempty"`

	// developer can ignore this param
	Stream *bool `json:"stream,omitempty"`

	// The customized variable in a key-value pair.
	CustomVariables map[string]string `json:"custom_variables,omitempty"`

	// Whether to automatically save the history of conversation records.
	AutoSaveHistory *bool `json:"auto_save_history,omitempty"`

	// Additional information, typically used to encapsulate some business-related fields.
	MetaData map[string]string `json:"meta_data,omitempty"`
}

CreateChatsReq represents the request to create a chat

type CreateChatsResp

type CreateChatsResp struct {
	Chat
	// contains filtered or unexported fields
}

func (*CreateChatsResp) LogID

func (r *CreateChatsResp) LogID() string

func (*CreateChatsResp) Response

func (r *CreateChatsResp) Response() HTTPResponse

type CreateConversationsReq

type CreateConversationsReq struct {
	// Messages in the conversation. For more information, see EnterMessage object.
	Messages []*Message `json:"messages,omitempty"`

	// Additional information when creating a message, and this additional information will also be
	// returned when retrieving messages.
	MetaData map[string]string `json:"meta_data,omitempty"`

	// Bind and isolate conversation on different bots.
	BotID string `json:"bot_id,omitempty"`
}

CreateConversationsReq represents request for creating conversation

type CreateConversationsResp

type CreateConversationsResp struct {
	Conversation
	// contains filtered or unexported fields
}

func (*CreateConversationsResp) LogID

func (r *CreateConversationsResp) LogID() string

func (*CreateConversationsResp) Response

func (r *CreateConversationsResp) Response() HTTPResponse

type CreateDatasetResp

type CreateDatasetResp struct {
	DatasetID string `json:"dataset_id"`
	// contains filtered or unexported fields
}

func (*CreateDatasetResp) LogID

func (r *CreateDatasetResp) LogID() string

func (*CreateDatasetResp) Response

func (r *CreateDatasetResp) Response() HTTPResponse

type CreateDatasetsDocumentsReq

type CreateDatasetsDocumentsReq struct {
	// The ID of the knowledge base.
	DatasetID int64 `json:"dataset_id"`

	// The metadata information of the files awaiting upload. The array has a maximum length of 10,
	// meaning up to 10 files can be uploaded at a time. For detailed instructions, refer to the
	// DocumentBase object.
	DocumentBases []*DocumentBase `json:"document_bases"`

	// Chunk strategy. These rules must be set only when uploading a file to new knowledge for the
	// first time. For subsequent file uploads to this knowledge, it is not necessary to pass these
	// rules; the default is to continue using the initial settings, and modifications are not
	// supported. For detailed instructions, refer to the ChunkStrategy object.
	ChunkStrategy *DocumentChunkStrategy `json:"chunk_strategy,omitempty"`

	// The type of file format. Values include:
	// 0: Document type, such as txt, pdf, online web pages, etc.
	// 2: Images type, such as png images, etc.
	FormatType DocumentFormatType `json:"format_type"`
}

CreateDatasetsDocumentsReq represents request for creating document

type CreateDatasetsDocumentsResp

type CreateDatasetsDocumentsResp struct {
	DocumentInfos []*Document `json:"document_infos"`
	// contains filtered or unexported fields
}

CreateDatasetsDocumentsResp represents response for creating document

func (*CreateDatasetsDocumentsResp) LogID

func (r *CreateDatasetsDocumentsResp) LogID() string

func (*CreateDatasetsDocumentsResp) Response

func (r *CreateDatasetsDocumentsResp) Response() HTTPResponse

type CreateDatasetsReq

type CreateDatasetsReq struct {
	Name        string             `json:"name"`
	SpaceID     string             `json:"space_id"`
	FormatType  DocumentFormatType `json:"format_type"`
	Description string             `json:"description,omitempty"`
	IconFileID  string             `json:"file_id,omitempty"`
}

CreateDatasetsReq 表示创建数据集的请求

type CreateMessageReq

type CreateMessageReq struct {
	// The ID of the conversation.
	ConversationID string `json:"-"`

	// The entity that sent this message.
	Role MessageRole `json:"role"`

	// The content of the message, supporting pure text, multimodal (mixed input of text, images, files),
	// cards, and various types of content.
	Content string `json:"content"`

	// The type of message content.
	ContentType MessageContentType `json:"content_type"`

	// Additional information when creating a message, and this additional information will also be
	// returned when retrieving messages.
	MetaData map[string]string `json:"meta_data,omitempty"`
}

CreateMessageReq represents request for creating message

func (*CreateMessageReq) SetObjectContext

func (c *CreateMessageReq) SetObjectContext(objs []*MessageObjectString)

type CreateMessageResp

type CreateMessageResp struct {
	Message
	// contains filtered or unexported fields
}

CreateMessageResp represents response for creating message

func (*CreateMessageResp) LogID

func (r *CreateMessageResp) LogID() string

func (*CreateMessageResp) Response

func (r *CreateMessageResp) Response() HTTPResponse

type Dataset

type Dataset struct {
	ID                   string                 `json:"dataset_id"`
	Name                 string                 `json:"name"`
	Description          string                 `json:"description"`
	SpaceID              string                 `json:"space_id"`
	Status               DatasetStatus          `json:"status"`
	FormatType           DocumentFormatType     `json:"format_type"`
	CanEdit              bool                   `json:"can_edit"`
	IconURL              string                 `json:"icon_url"`
	DocCount             int                    `json:"doc_count"`
	FileList             []string               `json:"file_list"`
	HitCount             int                    `json:"hit_count"`
	BotUsedCount         int                    `json:"bot_used_count"`
	SliceCount           int                    `json:"slice_count"`
	AllFileSize          string                 `json:"all_file_size"`
	ChunkStrategy        *DocumentChunkStrategy `json:"chunk_strategy,omitempty"`
	FailedFileList       []string               `json:"failed_file_list"`
	ProcessingFileList   []string               `json:"processing_file_list"`
	ProcessingFileIDList []string               `json:"processing_file_id_list"`
	AvatarURL            string                 `json:"avatar_url"`
	CreatorID            string                 `json:"creator_id"`
	CreatorName          string                 `json:"creator_name"`
	CreateTime           int                    `json:"create_time"`
	UpdateTime           int                    `json:"update_time"`
}

Dataset 表示数据集信息

type DatasetStatus

type DatasetStatus int

DatasetStatus 表示数据集状态

const (
	DatasetStatusEnabled  DatasetStatus = 1
	DatasetStatusDisabled DatasetStatus = 3
)

type DeleteConversationsMessagesReq

type DeleteConversationsMessagesReq struct {
	// The ID of the conversation.
	ConversationID string `json:"conversation_id"`

	// message id
	MessageID string `json:"message_id"`
}

DeleteConversationsMessagesReq represents request for deleting message

type DeleteConversationsMessagesResp

type DeleteConversationsMessagesResp struct {
	Message
	// contains filtered or unexported fields
}

DeleteConversationsMessagesResp represents response for creating message

func (*DeleteConversationsMessagesResp) LogID

func (r *DeleteConversationsMessagesResp) LogID() string

func (*DeleteConversationsMessagesResp) Response

func (r *DeleteConversationsMessagesResp) Response() HTTPResponse

type DeleteDatasetsDocumentsReq

type DeleteDatasetsDocumentsReq struct {
	DocumentIDs []int64 `json:"document_ids"`
}

DeleteDatasetsDocumentsReq represents request for deleting datasetsDocuments

type DeleteDatasetsDocumentsResp

type DeleteDatasetsDocumentsResp struct {
	// contains filtered or unexported fields
}

DeleteDatasetsDocumentsResp represents response for deleting datasetsDocuments

func (*DeleteDatasetsDocumentsResp) LogID

func (r *DeleteDatasetsDocumentsResp) LogID() string

func (*DeleteDatasetsDocumentsResp) Response

func (r *DeleteDatasetsDocumentsResp) Response() HTTPResponse

type DeleteDatasetsReq

type DeleteDatasetsReq struct {
	DatasetID string `json:"-"`
}

DeleteDatasetsReq 表示删除数据集的请求

type DeleteDatasetsResp

type DeleteDatasetsResp struct {
	// contains filtered or unexported fields
}

func (*DeleteDatasetsResp) LogID

func (r *DeleteDatasetsResp) LogID() string

func (*DeleteDatasetsResp) Response

func (r *DeleteDatasetsResp) Response() HTTPResponse

type DeviceAuthReq

type DeviceAuthReq struct {
	ClientID string `json:"client_id"`
	LogID    string `json:"log_id,omitempty"`
}

DeviceAuthReq represents the device authorization request

type DeviceOAuthClient

type DeviceOAuthClient struct {
	*OAuthClient
}

DeviceOAuthClient represents the device OAuth core

func NewDeviceOAuthClient

func NewDeviceOAuthClient(clientID string, opts ...OAuthClientOption) (*DeviceOAuthClient, error)

NewDeviceOAuthClient creates a new device OAuth core

func (*DeviceOAuthClient) GetAccessToken

func (*DeviceOAuthClient) GetDeviceCode

GetDeviceCode gets the device code

func (*DeviceOAuthClient) RefreshToken

func (c *DeviceOAuthClient) RefreshToken(ctx context.Context, refreshToken string) (*OAuthToken, error)

RefreshToken refreshes the access token

type Document

type Document struct {
	// The ID of the file.
	DocumentID string `json:"document_id"`

	// The total character count of the file content.
	CharCount int `json:"char_count"`

	// The chunking rules. For detailed instructions, refer to the ChunkStrategy object.
	ChunkStrategy *DocumentChunkStrategy `json:"chunk_strategy"`

	// The upload time of the file, in the format of a 10-digit Unix timestamp.
	CreateTime int `json:"create_time"`

	// The last modified time of the file, in the format of a 10-digit Unix timestamp.
	UpdateTime int `json:"update_time"`

	// The type of file format. Values include:
	// 0: Document type, such as txt, pdf, online web pages, etc.
	// 1: Spreadsheet type, such as xls spreadsheets, etc.
	// 2: Images type, such as png images, etc.
	FormatType DocumentFormatType `json:"format_type"`

	// The number of times the file has been hit in conversations.
	HitCount int `json:"hit_count"`

	// The name of the file.
	Name string `json:"name"`

	// The size of the file in bytes.
	Size int `json:"size"`

	// The number of slices the file has been divided into.
	SliceCount int `json:"slice_count"`

	// The method of uploading the file. Values include:
	// 0: Upload local files.
	// 1: Upload online web pages.
	SourceType DocumentSourceType `json:"source_type"`

	// The processing status of the file. Values include:
	// 0: Processing
	// 1: Completed
	// 9: Processing failed, it is recommended to re-upload
	Status DocumentStatus `json:"status"`

	// The format of the local file, i.e., the file extension, such as "txt".
	// Supported formats include PDF, TXT, DOC, DOCX.
	Type string `json:"type"`

	// The frequency of automatic updates for online web pages, in hours.
	UpdateInterval int `json:"update_interval"`

	// Whether the online web page is automatically updated. Values include:
	// 0: Do not automatically update
	// 1: Automatically update
	UpdateType DocumentUpdateType `json:"update_type"`
}

Document represents a document in the datasets

type DocumentBase

type DocumentBase struct {
	// The name of the file.
	Name string `json:"name"`

	// The metadata information of the file.
	SourceInfo *DocumentSourceInfo `json:"source_info"`

	// The update strategy for online web pages. Defaults to no automatic update.
	UpdateRule *DocumentUpdateRule `json:"update_rule,omitempty"`
}

DocumentBase represents base information for creating a document

func DocumentBaseBuildImage

func DocumentBaseBuildImage(name string, fileID int64) *DocumentBase

DocumentBaseBuildImage creates basic document information for image type

func DocumentBaseBuildLocalFile

func DocumentBaseBuildLocalFile(name string, content string, fileType string) *DocumentBase

DocumentBaseBuildLocalFile creates basic document information for local file type

func DocumentBaseBuildWebPage

func DocumentBaseBuildWebPage(name string, url string, interval *int) *DocumentBase

DocumentBaseBuildWebPage creates basic document information for webpage type

type DocumentChunkStrategy

type DocumentChunkStrategy struct {
	// The chunking settings. Values include:
	// 0: Automatic chunking and cleaning. Uses preset rules for data chunking and processing.
	// 1: Custom. In this case, details need to be specified through separator, max_tokens,
	// remove_extra_spaces, and remove_urls_emails.
	ChunkType int `json:"chunk_type"`

	// Maximum chunk length, ranging from 100 to 2000.
	// Required when chunk_type=1.
	MaxTokens int `json:"max_tokens,omitempty"`

	// Whether to automatically filter consecutive spaces, line breaks, and tabs.
	// Values include:
	// true: Automatically filter
	// false: (Default) Do not automatically filter
	// Takes effect when chunk_type=1.
	RemoveExtraSpaces bool `json:"remove_extra_spaces,omitempty"`

	// Whether to automatically filter all URLs and email addresses.
	// Values include:
	// true: Automatically filter
	// false: (Default) Do not automatically filter
	// Takes effect when chunk_type=1.
	RemoveUrlsEmails bool `json:"remove_urls_emails,omitempty"`

	// The chunk identifier.
	// Required when chunk_type=1.
	Separator string `json:"separator,omitempty"`
}

DocumentChunkStrategy represents chunking strategy for datasetsDocuments

type DocumentFormatType

type DocumentFormatType int

DocumentFormatType represents the format type of a document

const (
	// Document type, such as txt, pdf, online web pages, etc.
	DocumentFormatTypeDocument DocumentFormatType = 0
	// Spreadsheet type, such as xls spreadsheets, etc.
	DocumentFormatTypeSpreadsheet DocumentFormatType = 1
	// Images type, such as png images, etc.
	DocumentFormatTypeImage DocumentFormatType = 2
)

type DocumentProgress

type DocumentProgress struct {
	DocumentID     string             `json:"document_id"`
	URL            string             `json:"url"`
	Size           int                `json:"size"`
	Type           string             `json:"type"`
	Status         DocumentStatus     `json:"status"`
	Progress       int                `json:"progress"`
	UpdateType     DocumentUpdateType `json:"update_type"`
	DocumentName   string             `json:"document_name"`
	RemainingTime  int                `json:"remaining_time"`
	StatusDescript string             `json:"status_descript"`
	UpdateInterval int                `json:"update_interval"`
}

DocumentProgress 表示文档处理进度

type DocumentSourceInfo

type DocumentSourceInfo struct {
	// Base64 encoding of the local file.
	// Required when uploading local files.
	FileBase64 *string `json:"file_base64,omitempty"`

	// The format of the local file, i.e., the file extension, such as "txt".
	// Supported formats include PDF, TXT, DOC, DOCX.
	// The uploaded file type should match the knowledge base type.
	// Required when uploading local files.
	FileType *string `json:"file_type,omitempty"`

	// The URL of the webpage.
	// Required when uploading webpages.
	WebUrl *string `json:"web_url,omitempty"`

	// The upload method of the file.
	// 1 to indicate uploading online webpages.
	// 5 to indicate uploading fileID.
	// Required when uploading online webpages.
	DocumentSource *int `json:"document_source,omitempty"`

	SourceFileID *int64 `json:"source_file_id,omitempty"`
}

DocumentSourceInfo represents source information for a document

func DocumentSourceInfoBuildImage

func DocumentSourceInfoBuildImage(fileID int64) *DocumentSourceInfo

DocumentSourceInfoBuildImage creates document source information for image type

func DocumentSourceInfoBuildLocalFile

func DocumentSourceInfoBuildLocalFile(content string, fileType string) *DocumentSourceInfo

DocumentSourceInfoBuildLocalFile creates document source information for local file type

func DocumentSourceInfoBuildWebPage

func DocumentSourceInfoBuildWebPage(url string) *DocumentSourceInfo

DocumentSourceInfoBuildWebPage creates document source information for webpage type

type DocumentSourceType

type DocumentSourceType int

DocumentSourceType represents the source type of a document

const (
	// Upload local files.
	DocumentSourceTypeLocalFile DocumentSourceType = 0
	// Upload online web pages.
	DocumentSourceTypeOnlineWeb DocumentSourceType = 1
)

type DocumentStatus

type DocumentStatus int

DocumentStatus represents the status of a document

const (
	// Processing
	DocumentStatusProcessing DocumentStatus = 0
	// Completed
	DocumentStatusCompleted DocumentStatus = 1
	// Processing failed, it is recommended to re-upload
	DocumentStatusFailed DocumentStatus = 9
)

type DocumentUpdateRule

type DocumentUpdateRule struct {
	// Whether the online webpage is automatically updated.
	// Values include:
	// 0: Do not automatically update
	// 1: Automatically update
	UpdateType DocumentUpdateType `json:"update_type"`

	// The frequency of automatic updates for online webpages, in hours.
	// Minimum value is 24.
	UpdateInterval int `json:"update_interval"`
}

DocumentUpdateRule represents update rules for datasetsDocuments

func DocumentUpdateRuleBuildAutoUpdate

func DocumentUpdateRuleBuildAutoUpdate(interval int) *DocumentUpdateRule

DocumentUpdateRuleBuildAutoUpdate creates a rule for automatic updates with specified interval

func DocumentUpdateRuleBuildNoAuto

func DocumentUpdateRuleBuildNoAuto() *DocumentUpdateRule

DocumentUpdateRuleBuildNoAuto creates a rule for no automatic updates

type DocumentUpdateType

type DocumentUpdateType int

DocumentUpdateType represents the update type of a document

const (
	// Do not automatically update
	DocumentUpdateTypeNoAutoUpdate DocumentUpdateType = 0
	// Automatically update
	DocumentUpdateTypeAutoUpdate DocumentUpdateType = 1
)

type DuplicateTemplateReq

type DuplicateTemplateReq struct {
	WorkspaceID string  `json:"workspace_id"`
	Name        *string `json:"name,omitempty"`
}

DuplicateTemplateReq represents the request to duplicate a template

type Error

type Error struct {
	Code    int
	Message string
	LogID   string
}

func AsCozeError

func AsCozeError(err error) (*Error, bool)

AsCozeError checks if the error is of type Error

func NewError

func NewError(code int, msg, logID string) *Error

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

type FileInfo

type FileInfo struct {
	// The ID of the uploaded file.
	ID string `json:"id"`

	// The total byte size of the file.
	Bytes int `json:"bytes"`

	// The upload time of the file, in the format of a 10-digit Unix timestamp in seconds (s).
	CreatedAt int `json:"created_at"`

	// The name of the file.
	FileName string `json:"file_name"`
}

FileInfo represents information about a file

type FileTypes

type FileTypes interface {
	io.Reader
	Name() string
}

func NewUploadFile

func NewUploadFile(reader io.Reader, fileName string) FileTypes

type GetDeviceAuthResp

type GetDeviceAuthResp struct {
	DeviceCode      string `json:"device_code"`
	UserCode        string `json:"user_code"`
	VerificationURI string `json:"verification_uri"`
	VerificationURL string `json:"verification_url"`
	ExpiresIn       int    `json:"expires_in"`
	Interval        int    `json:"interval"`
	// contains filtered or unexported fields
}

GetDeviceAuthResp represents the device authorization response

func (*GetDeviceAuthResp) GetCode

func (r *GetDeviceAuthResp) GetCode() int

func (*GetDeviceAuthResp) GetMsg

func (r *GetDeviceAuthResp) GetMsg() string

func (*GetDeviceAuthResp) LogID

func (r *GetDeviceAuthResp) LogID() string

func (*GetDeviceAuthResp) SetCode

func (r *GetDeviceAuthResp) SetCode(code int)

func (*GetDeviceAuthResp) SetHTTPResponse

func (r *GetDeviceAuthResp) SetHTTPResponse(httpResponse *httpResponse)

func (*GetDeviceAuthResp) SetMsg

func (r *GetDeviceAuthResp) SetMsg(msg string)

type GetDeviceOAuthAccessTokenReq

type GetDeviceOAuthAccessTokenReq struct {
	DeviceCode string
	Poll       bool
}

type GetDeviceOAuthCodeReq

type GetDeviceOAuthCodeReq struct {
	WorkspaceID *string
}

type GetJWTAccessTokenReq

type GetJWTAccessTokenReq struct {
	TTL         int     `json:"ttl,omitempty"`          // Token validity period (in seconds)
	Scope       *Scope  `json:"scope,omitempty"`        // Permission scope
	SessionName *string `json:"session_name,omitempty"` // Session name
	AccountID   *int64  `json:"account_id,omitempty"`   // Account ID
}

GetJWTAccessTokenReq represents options for getting JWT OAuth token

type GetPKCEAccessTokenReq

type GetPKCEAccessTokenReq struct {
	Code, RedirectURI, CodeVerifier string
}

type GetPKCEOAuthURLReq

type GetPKCEOAuthURLReq struct {
	RedirectURI string
	State       string
	Method      *CodeChallengeMethod
	WorkspaceID *string
}

type GetPKCEOAuthURLResp

type GetPKCEOAuthURLResp struct {
	CodeVerifier     string `json:"code_verifier"`
	AuthorizationURL string `json:"authorization_url"`
}

GetPKCEOAuthURLResp represents the PKCE authorization URL response

type GetWebOAuthAccessTokenReq

type GetWebOAuthAccessTokenReq struct {
	Code, RedirectURI string
}

type GetWebOAuthURLReq

type GetWebOAuthURLReq struct {
	RedirectURI, State string
	WorkspaceID        *string
}

type GrantType

type GrantType string

GrantType represents the OAuth grant type

const (
	GrantTypeAuthorizationCode GrantType = "authorization_code"
	GrantTypeDeviceCode        GrantType = "urn:ietf:params:oauth:grant-type:device_code"
	GrantTypeJWTCode           GrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
	GrantTypeRefreshToken      GrantType = "refresh_token"
)

func (GrantType) String

func (r GrantType) String() string

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient an interface for making HTTP requests

type HTTPResponse

type HTTPResponse interface {
	LogID() string
}

type Image

type Image struct {
	// The ID of the file.
	DocumentID string `json:"document_id"`

	// The total character count of the file content.
	CharCount int `json:"char_count"`

	// The chunking rules. For detailed instructions, refer to the ChunkStrategy object.
	ChunkStrategy *DocumentChunkStrategy `json:"chunk_strategy"`

	// The upload time of the file, in the format of a 10-digit Unix timestamp.
	CreateTime int `json:"create_time"`

	// The last modified time of the file, in the format of a 10-digit Unix timestamp.
	UpdateTime int `json:"update_time"`

	// The type of file format. Values include:
	// 0: Document type, such as txt, pdf, online web pages, etc.
	// 1: Spreadsheet type, such as xls spreadsheets, etc.
	// 2: Images type, such as png images, etc.
	FormatType DocumentFormatType `json:"format_type"`

	// The number of times the file has been hit in conversations.
	HitCount int `json:"hit_count"`

	// The name of the file.
	Name string `json:"name"`

	// The size of the file in bytes.
	Size int `json:"size"`

	// The number of slices the file has been divided into.
	SliceCount int `json:"slice_count"`

	// The method of uploading the file. Values include:
	// 0: Upload local files.
	// 1: Upload online web pages.
	SourceType DocumentSourceType `json:"source_type"`

	// The processing status of the file. Values include:
	// 0: Processing
	// 1: Completed
	// 9: Processing failed, it is recommended to re-upload
	Status ImageStatus `json:"status"`

	// The caption of the image.
	Caption string `json:"caption"`

	// The ID of the creator.
	CreatorID string `json:"creator_id"`
}

Image 表示图片信息

type ImageStatus

type ImageStatus int

ImageStatus 表示图片状态

const (
	ImageStatusInProcessing     ImageStatus = 0 // 处理中
	ImageStatusCompleted        ImageStatus = 1 // 已完成
	ImageStatusProcessingFailed ImageStatus = 9 // 处理失败
)

type JWTOAuthClient

type JWTOAuthClient struct {
	*OAuthClient
	// contains filtered or unexported fields
}

JWTOAuthClient represents the JWT OAuth core

func NewJWTOAuthClient

func NewJWTOAuthClient(param NewJWTOAuthClientParam, opts ...OAuthClientOption) (*JWTOAuthClient, error)

NewJWTOAuthClient creates a new JWT OAuth core

func (*JWTOAuthClient) GetAccessToken

func (c *JWTOAuthClient) GetAccessToken(ctx context.Context, opts *GetJWTAccessTokenReq) (*OAuthToken, error)

GetAccessToken gets the access token, using options pattern

type LanguageCode

type LanguageCode string

LanguageCode represents the language code

const (
	LanguageCodeZH LanguageCode = "zh"
	LanguageCodeEN LanguageCode = "en"
	LanguageCodeJA LanguageCode = "ja"
	LanguageCodeES LanguageCode = "es"
	LanguageCodeID LanguageCode = "id"
	LanguageCodePT LanguageCode = "pt"
)

func (LanguageCode) String

func (l LanguageCode) String() string

type LastIDPaged

type LastIDPaged[T any] interface {
	BasePaged[T]
	GetLastID() string
}

func NewLastIDPaged

func NewLastIDPaged[T any](fetcher PageFetcher[T], pageSize int, nextID *string) (LastIDPaged[T], error)

type LevelLogger

type LevelLogger interface {
	Logger
	SetLevel(level LogLevel)
}

func NewLevelLogger

func NewLevelLogger(logger Logger, level LogLevel) LevelLogger

NewLevelLogger ...

type ListAudioVoicesReq

type ListAudioVoicesReq struct {
	FilterSystemVoice bool `json:"filter_system_voice,omitempty"`
	PageNum           int  `json:"page_num"`
	PageSize          int  `json:"page_size"`
}

ListAudioVoicesReq represents the request for listing voices

type ListAudioVoicesResp

type ListAudioVoicesResp struct {
	Data struct {
		VoiceList []*Voice `json:"voice_list"`
	} `json:"data"`
	// contains filtered or unexported fields
}

ListAudioVoicesResp represents the response for listing voices

func (*ListAudioVoicesResp) GetCode

func (r *ListAudioVoicesResp) GetCode() int

func (*ListAudioVoicesResp) GetMsg

func (r *ListAudioVoicesResp) GetMsg() string

func (*ListAudioVoicesResp) LogID

func (r *ListAudioVoicesResp) LogID() string

func (*ListAudioVoicesResp) SetCode

func (r *ListAudioVoicesResp) SetCode(code int)

func (*ListAudioVoicesResp) SetHTTPResponse

func (r *ListAudioVoicesResp) SetHTTPResponse(httpResponse *httpResponse)

func (*ListAudioVoicesResp) SetMsg

func (r *ListAudioVoicesResp) SetMsg(msg string)

type ListBotsReq

type ListBotsReq struct {
	SpaceID  string `json:"space_id"`  // Space ID
	PageNum  int    `json:"page_num"`  // Page number
	PageSize int    `json:"page_size"` // Page size
}

ListBotsReq represents the request structure for listing bots

type ListChatsMessagesReq

type ListChatsMessagesReq struct {
	// The Conversation ID can be viewed in the 'conversation_id' field of the Response when
	// initiating a conversation through the Chat API.
	ConversationID string `json:"conversation_id"`

	// The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the
	// Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response.
	ChatID string `json:"chat_id"`
}

ListChatsMessagesReq represents the request to list messages

type ListChatsMessagesResp

type ListChatsMessagesResp struct {
	Messages []*Message `json:"data"`
	// contains filtered or unexported fields
}

func (*ListChatsMessagesResp) LogID

func (r *ListChatsMessagesResp) LogID() string

func (*ListChatsMessagesResp) Response

func (r *ListChatsMessagesResp) Response() HTTPResponse

type ListConversationsMessagesReq

type ListConversationsMessagesReq struct {
	// The ID of the conversation.
	ConversationID string `json:"-"`

	// The sorting method for the message list.
	Order *string `json:"order,omitempty"`

	// The ID of the Chat.
	ChatID *string `json:"chat_id,omitempty"`

	// Get messages before the specified position.
	BeforeID *string `json:"before_id,omitempty"`

	// Get messages after the specified position.
	AfterID *string `json:"after_id,omitempty"`

	// The amount of data returned per query. Default is 50, with a range of 1 to 50.
	Limit int `json:"limit,omitempty"`

	BotID *string `json:"bot_id,omitempty"`
}

ListConversationsMessagesReq represents request for listing messages

type ListConversationsMessagesResp

type ListConversationsMessagesResp struct {
	HasMore  bool       `json:"has_more"`
	FirstID  string     `json:"first_id"`
	LastID   string     `json:"last_id"`
	Messages []*Message `json:"data"`
	// contains filtered or unexported fields
}

func (*ListConversationsMessagesResp) LogID

func (r *ListConversationsMessagesResp) LogID() string

func (*ListConversationsMessagesResp) Response

func (r *ListConversationsMessagesResp) Response() HTTPResponse

type ListConversationsReq

type ListConversationsReq struct {
	// The ID of the bot.
	BotID string `json:"bot_id"`

	// The page number.
	PageNum int `json:"page_num,omitempty"`

	// The page size.
	PageSize int `json:"page_size,omitempty"`
}

ListConversationsReq represents request for listing conversations

type ListConversationsResp

type ListConversationsResp struct {
	HasMore       bool            `json:"has_more"`
	Conversations []*Conversation `json:"conversations"`
	// contains filtered or unexported fields
}

ListConversationsResp represents response for listing conversations

func (*ListConversationsResp) LogID

func (r *ListConversationsResp) LogID() string

func (*ListConversationsResp) Response

func (r *ListConversationsResp) Response() HTTPResponse

type ListDatasetsDocumentsReq

type ListDatasetsDocumentsReq struct {
	// The ID of the knowledge base.
	DatasetID int64 `json:"dataset_id"`

	// The page number for paginated queries. Default is 1, meaning the data return starts from the
	// first page.
	Page int `json:"page,omitempty"`

	// The size of pagination. Default is 10, meaning that 10 data entries are returned per page.
	Size int `json:"size,omitempty"`
}

ListDatasetsDocumentsReq represents request for listing datasetsDocuments

type ListDatasetsDocumentsResp

type ListDatasetsDocumentsResp struct {
	Total         int64       `json:"total"`
	DocumentInfos []*Document `json:"document_infos"`
	// contains filtered or unexported fields
}

ListDatasetsDocumentsResp represents response for listing datasetsDocuments

func (*ListDatasetsDocumentsResp) LogID

func (r *ListDatasetsDocumentsResp) LogID() string

func (*ListDatasetsDocumentsResp) Response

func (r *ListDatasetsDocumentsResp) Response() HTTPResponse

type ListDatasetsImagesReq

type ListDatasetsImagesReq struct {
	DatasetID  string  `json:"-"`
	Keyword    *string `json:"keyword,omitempty"`
	HasCaption *bool   `json:"has_caption,omitempty"`
	PageNum    int     `json:"page_num"`
	PageSize   int     `json:"page_size"`
}

ListDatasetsImagesReq 表示列出图片的请求

type ListDatasetsReq

type ListDatasetsReq struct {
	SpaceID    string             `json:"space_id"`
	Name       string             `json:"name,omitempty"`
	FormatType DocumentFormatType `json:"format_type,omitempty"`
	PageNum    int                `json:"page_num"`
	PageSize   int                `json:"page_size"`
}

ListDatasetsReq 表示列出数据集的请求

func NewListDatasetsReq

func NewListDatasetsReq(spaceID string) *ListDatasetsReq

type ListDatasetsResp

type ListDatasetsResp struct {
	TotalCount  int        `json:"total_count"`
	DatasetList []*Dataset `json:"dataset_list"`
	// contains filtered or unexported fields
}

func (*ListDatasetsResp) LogID

func (r *ListDatasetsResp) LogID() string

func (*ListDatasetsResp) Response

func (r *ListDatasetsResp) Response() HTTPResponse

type ListImagesResp

type ListImagesResp struct {
	ImagesInfos []*Image `json:"photo_infos"`
	TotalCount  int      `json:"total_count"`
	// contains filtered or unexported fields
}

func (*ListImagesResp) LogID

func (r *ListImagesResp) LogID() string

func (*ListImagesResp) Response

func (r *ListImagesResp) Response() HTTPResponse

type ListWorkspaceReq

type ListWorkspaceReq struct {
	PageNum  int `json:"page_num"`
	PageSize int `json:"page_size"`
}

ListWorkspaceReq represents the request parameters for listing workspaces

func NewListWorkspaceReq

func NewListWorkspaceReq() *ListWorkspaceReq

type ListWorkspaceResp

type ListWorkspaceResp struct {
	TotalCount int          `json:"total_count"`
	Workspaces []*Workspace `json:"workspaces"`
	// contains filtered or unexported fields
}

ListWorkspaceResp represents the response for listing workspaces

func (*ListWorkspaceResp) LogID

func (r *ListWorkspaceResp) LogID() string

func (*ListWorkspaceResp) Response

func (r *ListWorkspaceResp) Response() HTTPResponse

type LogLevel

type LogLevel int
const (
	LogLevelTrace LogLevel = iota + 1
	LogLevelDebug
	LogLevelInfo
	LogLevelWarn
	LogLevelError
)

LogLevelTrace ...

func (LogLevel) String

func (r LogLevel) String() string

String ...

type Logger

type Logger interface {
	Log(ctx context.Context, level LogLevel, message string, args ...interface{})
}

Logger ...

type Message

type Message struct {
	// The entity that sent this message.
	Role MessageRole `json:"role"`

	// The type of message.
	Type MessageType `json:"type"`

	// The content of the message. It supports various types of content, including plain text,
	// multimodal (a mix of text, images, and files), message cards, and more.
	Content string `json:"content"`

	// The type of message content.
	ContentType MessageContentType `json:"content_type"`

	// Additional information when creating a message, and this additional information will also be
	// returned when retrieving messages. Custom key-value pairs should be specified in Map object
	// format, with a length of 16 key-value pairs. The length of the key should be between 1 and 64
	// characters, and the length of the value should be between 1 and 512 characters.
	MetaData map[string]string `json:"meta_data,omitempty"`

	ID             string `json:"id"`
	ConversationID string `json:"conversation_id"`

	// section_id is used to distinguish the context sections of the session history. The same section
	// is one context.
	SectionID string `json:"section_id"`
	BotID     string `json:"bot_id"`
	ChatID    string `json:"chat_id"`
	CreatedAt int64  `json:"created_at"`
	UpdatedAt int64  `json:"updated_at"`
}

Message represents a message in conversation

func BuildAssistantAnswer

func BuildAssistantAnswer(content string, metaData map[string]string) *Message

BuildAssistantAnswer builds an answer message from assistant

func BuildUserQuestionObjects

func BuildUserQuestionObjects(objects []*MessageObjectString, metaData map[string]string) *Message

BuildUserQuestionObjects builds an object message for user question

func BuildUserQuestionText

func BuildUserQuestionText(content string, metaData map[string]string) *Message

BuildUserQuestionText builds a text message for user question

type MessageContentType

type MessageContentType string

MessageContentType represents the type of message content

const (
	// MessageContentTypeText Text.
	MessageContentTypeText MessageContentType = "text"

	// MessageContentTypeObjectString Multimodal content, that is, a combination of text and files,
	// or a combination of text and images.
	MessageContentTypeObjectString MessageContentType = "object_string"

	// MessageContentTypeCard This enum value only appears in the interface response and is not supported as an
	// input parameter.
	MessageContentTypeCard MessageContentType = "card"

	// MessageContentTypeAudio If there is a audioVoices message in the input message,
	// the conversation.audio.delta event will be returned in the streaming response event.
	MessageContentTypeAudio MessageContentType = "audio"
)

type MessageObjectString

type MessageObjectString struct {
	// The content type of the multimodal message.
	Type MessageObjectStringType `json:"type"`

	// Text content. Required when type is text.
	Text string `json:"text,omitempty"`

	// The ID of the file or image content.
	FileID string `json:"file_id,omitempty"`

	// The online address of the file or image content. Must be a valid address that is publicly
	// accessible. file_id or file_url must be specified when type is file or image.
	FileURL string `json:"file_url,omitempty"`
}

MessageObjectString represents a multimodal message object

func NewAudioMessageObjectByID

func NewAudioMessageObjectByID(fileID string) *MessageObjectString

func NewAudioMessageObjectByURL

func NewAudioMessageObjectByURL(fileURL string) *MessageObjectString

func NewFileMessageObjectByID

func NewFileMessageObjectByID(fileID string) *MessageObjectString

func NewFileMessageObjectByURL

func NewFileMessageObjectByURL(fileURL string) *MessageObjectString

func NewImageMessageObjectByID

func NewImageMessageObjectByID(fileID string) *MessageObjectString

func NewImageMessageObjectByURL

func NewImageMessageObjectByURL(fileURL string) *MessageObjectString

func NewTextMessageObject

func NewTextMessageObject(text string) *MessageObjectString

NewTextMessageObject Helper functions for creating MessageObjectString

type MessageObjectStringType

type MessageObjectStringType string

MessageObjectStringType represents the type of multimodal message content

const (
	MessageObjectStringTypeText  MessageObjectStringType = "text"
	MessageObjectStringTypeFile  MessageObjectStringType = "file"
	MessageObjectStringTypeImage MessageObjectStringType = "image"
	MessageObjectStringTypeAudio MessageObjectStringType = "audio"
)

type MessageRole

type MessageRole string

MessageRole represents the role of message sender

const (
	MessageRoleUnknown MessageRole = "unknown"
	// MessageRoleUser Indicates that the content of the message is sent by the user.
	MessageRoleUser MessageRole = "user"
	// MessageRoleAssistant Indicates that the content of the message is sent by the bot.
	MessageRoleAssistant MessageRole = "assistant"
)

func (MessageRole) String

func (m MessageRole) String() string

type MessageType

type MessageType string

MessageType represents the type of message

const (
	// MessageTypeQuestion User input content.
	MessageTypeQuestion MessageType = "question"

	// MessageTypeAnswer The message content returned by the Bot to the user, supporting incremental return.
	MessageTypeAnswer MessageType = "answer"

	// MessageTypeFunctionCall Intermediate results of the function (function call) called during the
	// Bot conversation process.
	MessageTypeFunctionCall MessageType = "function_call"

	// MessageTypeToolOutput Results returned after calling the tool (function call).
	MessageTypeToolOutput MessageType = "tool_output"

	// MessageTypeToolResponse Results returned after calling the tool (function call).
	MessageTypeToolResponse MessageType = "tool_response"

	// 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.
	MessageTypeFollowUp MessageType = "follow_up"

	MessageTypeUnknown MessageType = ""
)

type NewJWTOAuthClientParam

type NewJWTOAuthClientParam struct {
	ClientID      string
	PublicKey     string
	PrivateKeyPEM string
	TTL           *int
}

type NumberPaged

type NumberPaged[T any] interface {
	BasePaged[T]
	Total() int
}

func NewNumberPaged

func NewNumberPaged[T any](fetcher PageFetcher[T], pageSize, pageNum int) (NumberPaged[T], error)

type OAuthClient

type OAuthClient struct {
	// contains filtered or unexported fields
}

OAuthClient represents the base OAuth core structure

type OAuthClientOption

type OAuthClientOption func(*oauthOption)

func WithAuthBaseURL

func WithAuthBaseURL(baseURL string) OAuthClientOption

WithAuthBaseURL adds base URL

func WithAuthHttpClient

func WithAuthHttpClient(client HTTPClient) OAuthClientOption

func WithAuthWWWURL

func WithAuthWWWURL(wwwURL string) OAuthClientOption

WithAuthWWWURL adds base URL

type OAuthConfig

type OAuthConfig struct {
	ClientID     string `json:"client_id"`
	ClientType   string `json:"client_type"`
	ClientSecret string `json:"client_secret,omitempty"`
	PrivateKey   string `json:"private_key,omitempty"`
	PublicKeyID  string `json:"public_key_id,omitempty"`
	CozeAPIBase  string `json:"coze_api_base,omitempty"`
	CozeWWWBase  string `json:"coze_www_base,omitempty"`
}

OAuthConfig represents the configuration for OAuth clients

type OAuthToken

type OAuthToken struct {
	AccessToken  string `json:"access_token"`
	ExpiresIn    int64  `json:"expires_in"`
	RefreshToken string `json:"refresh_token,omitempty"`
	// contains filtered or unexported fields
}

OAuthToken represents the OAuth token response

func (*OAuthToken) LogID

func (r *OAuthToken) LogID() string

func (*OAuthToken) Response

func (r *OAuthToken) Response() HTTPResponse

type PKCEOAuthClient

type PKCEOAuthClient struct {
	*OAuthClient
}

PKCEOAuthClient PKCE OAuth core

func NewPKCEOAuthClient

func NewPKCEOAuthClient(clientID string, opts ...OAuthClientOption) (*PKCEOAuthClient, error)

NewPKCEOAuthClient creates a new PKCE OAuth core

func (*PKCEOAuthClient) GetAccessToken

func (c *PKCEOAuthClient) GetAccessToken(ctx context.Context, req *GetPKCEAccessTokenReq) (*OAuthToken, error)

func (*PKCEOAuthClient) GetOAuthURL

GetOAuthURL generates OAuth URL

func (*PKCEOAuthClient) RefreshToken

func (c *PKCEOAuthClient) RefreshToken(ctx context.Context, refreshToken string) (*OAuthToken, error)

RefreshToken refreshes the access token

type PageFetcher

type PageFetcher[T any] func(request *pageRequest) (*pageResponse[T], error)

PageFetcher interface

type ProcessDocumentsReq

type ProcessDocumentsReq struct {
	DatasetID   string   `json:"-"`
	DocumentIDs []string `json:"document_ids"`
}

ProcessDocumentsReq 表示处理文档的请求

type ProcessDocumentsResp

type ProcessDocumentsResp struct {
	Data []*DocumentProgress `json:"data"`
	// contains filtered or unexported fields
}

func (*ProcessDocumentsResp) LogID

func (r *ProcessDocumentsResp) LogID() string

func (*ProcessDocumentsResp) Response

func (r *ProcessDocumentsResp) Response() HTTPResponse

type PublishBotsReq

type PublishBotsReq struct {
	BotID        string   `json:"bot_id"`        // Bot ID
	ConnectorIDs []string `json:"connector_ids"` // Connector ID list
}

PublishBotsReq represents the request structure for publishing a bot

type PublishBotsResp

type PublishBotsResp struct {
	BotID      string `json:"bot_id"`
	BotVersion string `json:"version"`
	// contains filtered or unexported fields
}

func (*PublishBotsResp) LogID

func (r *PublishBotsResp) LogID() string

func (*PublishBotsResp) Response

func (r *PublishBotsResp) Response() HTTPResponse

type RequestOption

type RequestOption func(*http.Request) error

RequestOption 请求选项函数类型

type Responser

type Responser interface {
	Response() HTTPResponse
}

type ResumeRunWorkflowsReq

type ResumeRunWorkflowsReq struct {
	// The ID of the workflow, which should have been published.
	WorkflowID string `json:"workflow_id"`

	// Event ID
	EventID string `json:"event_id"`

	// Resume data
	ResumeData string `json:"resume_data"`

	// Interrupt type
	InterruptType int `json:"interrupt_type"`
}

ResumeRunWorkflowsReq represents request for resuming workflow runs

type RetrieveBotsReq

type RetrieveBotsReq struct {
	BotID string `json:"bot_id"` // Bot ID
}

RetrieveBotsReq represents the request structure for retrieving a bot

type RetrieveBotsResp

type RetrieveBotsResp struct {
	Bot
	// contains filtered or unexported fields
}

func (*RetrieveBotsResp) LogID

func (r *RetrieveBotsResp) LogID() string

func (*RetrieveBotsResp) Response

func (r *RetrieveBotsResp) Response() HTTPResponse

type RetrieveChatsReq

type RetrieveChatsReq struct {
	// The Conversation ID can be viewed in the 'conversation_id' field of the Response when
	// initiating a conversation through the Chat API.
	ConversationID string `json:"conversation_id"`

	// The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the
	// Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response.
	ChatID string `json:"chat_id"`
}

RetrieveChatsReq represents the request to retrieve a chat

type RetrieveChatsResp

type RetrieveChatsResp struct {
	Chat
	// contains filtered or unexported fields
}

func (*RetrieveChatsResp) LogID

func (r *RetrieveChatsResp) LogID() string

func (*RetrieveChatsResp) Response

func (r *RetrieveChatsResp) Response() HTTPResponse

type RetrieveConversationsMessagesReq

type RetrieveConversationsMessagesReq struct {
	ConversationID string `json:"conversation_id"`
	MessageID      string `json:"message_id"`
}

RetrieveConversationsMessagesReq represents request for retrieving message

type RetrieveConversationsMessagesResp

type RetrieveConversationsMessagesResp struct {
	Message
	// contains filtered or unexported fields
}

RetrieveConversationsMessagesResp represents response for creating message

func (*RetrieveConversationsMessagesResp) LogID

func (r *RetrieveConversationsMessagesResp) LogID() string

func (*RetrieveConversationsMessagesResp) Response

func (r *RetrieveConversationsMessagesResp) Response() HTTPResponse

type RetrieveConversationsReq

type RetrieveConversationsReq struct {
	// The ID of the conversation.
	ConversationID string `json:"conversation_id"`
}

RetrieveConversationsReq represents request for retrieving conversation

type RetrieveConversationsResp

type RetrieveConversationsResp struct {
	Conversation
	// contains filtered or unexported fields
}

func (*RetrieveConversationsResp) LogID

func (r *RetrieveConversationsResp) LogID() string

func (*RetrieveConversationsResp) Response

func (r *RetrieveConversationsResp) Response() HTTPResponse

type RetrieveFilesReq

type RetrieveFilesReq struct {
	FileID string `json:"file_id"`
}

RetrieveFilesReq represents request for retrieving file

type RetrieveFilesResp

type RetrieveFilesResp struct {
	FileInfo
	// contains filtered or unexported fields
}

RetrieveFilesResp represents response for retrieving file

func (*RetrieveFilesResp) LogID

func (r *RetrieveFilesResp) LogID() string

func (*RetrieveFilesResp) Response

func (r *RetrieveFilesResp) Response() HTTPResponse

type RetrieveWorkflowRunsHistoriesResp

type RetrieveWorkflowRunsHistoriesResp struct {
	Histories []*WorkflowRunHistory `json:"data"`
	// contains filtered or unexported fields
}

RetrieveWorkflowRunsHistoriesResp represents response for retrieving workflow runs history

func (*RetrieveWorkflowRunsHistoriesResp) LogID

func (r *RetrieveWorkflowRunsHistoriesResp) LogID() string

func (*RetrieveWorkflowRunsHistoriesResp) Response

func (r *RetrieveWorkflowRunsHistoriesResp) Response() HTTPResponse

type RetrieveWorkflowsRunsHistoriesReq

type RetrieveWorkflowsRunsHistoriesReq struct {
	// The ID of the workflow.
	ExecuteID string `json:"execute_id"`

	// The ID of the workflow async execute.
	WorkflowID string `json:"workflow_id"`
}

RetrieveWorkflowsRunsHistoriesReq represents request for retrieving workflow runs history

type RoomAudioConfig

type RoomAudioConfig struct {
	Codec AudioCodec `json:"codec"`
}

RoomAudioConfig represents the room audio configuration

type RoomConfig

type RoomConfig struct {
	AudioConfig *RoomAudioConfig `json:"audio_config"`
}

RoomConfig represents the room configuration

type RunWorkflowsReq

type RunWorkflowsReq struct {
	// The ID of the workflow, which should have been published.
	WorkflowID string `json:"workflow_id"`

	// Input parameters and their values for the starting node of the workflow.
	Parameters map[string]any `json:"parameters,omitempty"`

	// The associated Bot ID required for some workflow executions.
	BotID string `json:"bot_id,omitempty"`

	// Used to specify some additional fields.
	Ext map[string]string `json:"ext,omitempty"`

	// Whether to runs asynchronously.
	IsAsync bool `json:"is_async,omitempty"`

	AppID string `json:"app_id,omitempty"`
}

RunWorkflowsReq represents request for running workflow

type RunWorkflowsResp

type RunWorkflowsResp struct {

	// Execution ID of asynchronous execution.
	ExecuteID string `json:"execute_id,omitempty"`

	// Workflow execution result.
	Data string `json:"data,omitempty"`

	DebugURL string `json:"debug_url,omitempty"`
	Token    int    `json:"token,omitempty"`
	Cost     string `json:"cost,omitempty"`
	// contains filtered or unexported fields
}

RunWorkflowsResp represents response for running workflow

func (*RunWorkflowsResp) LogID

func (r *RunWorkflowsResp) LogID() string

func (*RunWorkflowsResp) Response

func (r *RunWorkflowsResp) Response() HTTPResponse

type Scope

type Scope struct {
	AccountPermission   *ScopeAccountPermission   `json:"account_permission"`
	AttributeConstraint *ScopeAttributeConstraint `json:"attribute_constraint,omitempty"`
}

Scope represents the OAuth scope

func BuildBotChat

func BuildBotChat(botIDList []string, permissionList []string) *Scope

type ScopeAccountPermission

type ScopeAccountPermission struct {
	PermissionList []string `json:"permission_list"`
}

ScopeAccountPermission represents the account permissions in the scope

type ScopeAttributeConstraint

type ScopeAttributeConstraint struct {
	ConnectorBotChatAttribute *ScopeAttributeConstraintConnectorBotChatAttribute `json:"connector_bot_chat_attribute"`
}

ScopeAttributeConstraint represents the attribute constraints in the scope

type ScopeAttributeConstraintConnectorBotChatAttribute

type ScopeAttributeConstraintConnectorBotChatAttribute struct {
	BotIDList []string `json:"bot_id_list"`
}

ScopeAttributeConstraintConnectorBotChatAttribute represents the bot chat attributes

type SimpleBot

type SimpleBot struct {
	BotID       string `json:"bot_id"`
	BotName     string `json:"bot_name"`
	Description string `json:"description,omitempty"`
	IconURL     string `json:"icon_url,omitempty"`
	PublishTime string `json:"publish_time,omitempty"`
}

SimpleBot represents simplified bot information

type Stream

type Stream[T streamable] interface {
	Responser
	Close() error
	Recv() (*T, error)
}

type SubmitToolOutputsChatReq

type SubmitToolOutputsChatReq struct {
	// The Conversation ID can be viewed in the 'conversation_id' field of the Response when
	// initiating a conversation through the Chat API.
	ConversationID string `json:"-"`

	// The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the
	// Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response.
	ChatID string `json:"-"`

	// The execution result of the tool. For detailed instructions, refer to the ToolOutput Object
	ToolOutputs []*ToolOutput `json:"tool_outputs"`

	Stream *bool `json:"stream,omitempty"`
}

SubmitToolOutputsChatReq represents the request to submit tool outputs

type SubmitToolOutputsChatResp

type SubmitToolOutputsChatResp struct {
	Chat
	// contains filtered or unexported fields
}

func (*SubmitToolOutputsChatResp) LogID

func (r *SubmitToolOutputsChatResp) LogID() string

func (*SubmitToolOutputsChatResp) Response

func (r *SubmitToolOutputsChatResp) Response() HTTPResponse

type TemplateDuplicateResp

type TemplateDuplicateResp struct {
	EntityID   string             `json:"entity_id"`
	EntityType TemplateEntityType `json:"entity_type"`
	// contains filtered or unexported fields
}

TemplateDuplicateResp represents the response from duplicating a template

func (*TemplateDuplicateResp) LogID

func (r *TemplateDuplicateResp) LogID() string

func (*TemplateDuplicateResp) Response

func (r *TemplateDuplicateResp) Response() HTTPResponse

type TemplateEntityType

type TemplateEntityType string

TemplateEntityType represents the type of template entity

const (
	// TemplateEntityTypeAgent represents an agent template
	TemplateEntityTypeAgent TemplateEntityType = "agent"
)

type ToolOutput

type ToolOutput struct {
	// The ID for reporting the running results. You can get this ID under the tool_calls field in
	// response of the Chat API.
	ToolCallID string `json:"tool_call_id"`
	// The execution result of the tool.
	Output string `json:"output"`
}

ToolOutput represents the output of a tool

type UpdateBotsReq

type UpdateBotsReq struct {
	BotID           string              `json:"bot_id"`            // Bot ID
	Name            string              `json:"name"`              // Name
	Description     string              `json:"description"`       // Description
	IconFileID      string              `json:"icon_file_id"`      // Icon file ID
	PromptInfo      *BotPromptInfo      `json:"prompt_info"`       // Prompt information
	OnboardingInfo  *BotOnboardingInfo  `json:"onboarding_info"`   // Onboarding information
	Knowledge       *BotKnowledge       `json:"knowledge"`         // Knowledge
	ModelInfoConfig *BotModelInfoConfig `json:"model_info_config"` // ModelInfoConfig information
}

UpdateBotsReq represents the request structure for updating a bot

type UpdateBotsResp

type UpdateBotsResp struct {
	// contains filtered or unexported fields
}

func (*UpdateBotsResp) LogID

func (r *UpdateBotsResp) LogID() string

func (*UpdateBotsResp) Response

func (r *UpdateBotsResp) Response() HTTPResponse

type UpdateConversationMessagesReq

type UpdateConversationMessagesReq struct {
	// The ID of the conversation.
	ConversationID string `json:"conversation_id"`

	// The ID of the message.
	MessageID string `json:"message_id"`

	// The content of the message, supporting pure text, multimodal (mixed input of text, images, files),
	// cards, and various types of content.
	Content string `json:"content,omitempty"`

	MetaData map[string]string `json:"meta_data,omitempty"`

	// The type of message content.
	ContentType MessageContentType `json:"content_type,omitempty"`
}

UpdateConversationMessagesReq represents request for updating message

type UpdateConversationMessagesResp

type UpdateConversationMessagesResp struct {
	Message
	// contains filtered or unexported fields
}

UpdateConversationMessagesResp represents response for creating message

func (*UpdateConversationMessagesResp) LogID

func (r *UpdateConversationMessagesResp) LogID() string

func (*UpdateConversationMessagesResp) Response

func (r *UpdateConversationMessagesResp) Response() HTTPResponse

type UpdateDatasetImageReq

type UpdateDatasetImageReq struct {
	DatasetID  string  `json:"-"`
	DocumentID string  `json:"-"`
	Caption    *string `json:"caption"` // 图片描述
}

UpdateDatasetImageReq 表示更新图片的请求

type UpdateDatasetImageResp

type UpdateDatasetImageResp struct {
	// contains filtered or unexported fields
}

func (*UpdateDatasetImageResp) LogID

func (r *UpdateDatasetImageResp) LogID() string

func (*UpdateDatasetImageResp) Response

func (r *UpdateDatasetImageResp) Response() HTTPResponse

type UpdateDatasetsDocumentsReq

type UpdateDatasetsDocumentsReq struct {
	// The ID of the knowledge base file.
	DocumentID int64 `json:"document_id"`

	// The new name of the knowledge base file.
	DocumentName string `json:"document_name,omitempty"`

	// The update strategy for online web pages. Defaults to no automatic updates.
	// For detailed information, refer to the UpdateRule object.
	UpdateRule *DocumentUpdateRule `json:"update_rule,omitempty"`
}

UpdateDatasetsDocumentsReq represents request for updating document

type UpdateDatasetsDocumentsResp

type UpdateDatasetsDocumentsResp struct {
	// contains filtered or unexported fields
}

UpdateDatasetsDocumentsResp represents response for updating document

func (*UpdateDatasetsDocumentsResp) LogID

func (r *UpdateDatasetsDocumentsResp) LogID() string

func (*UpdateDatasetsDocumentsResp) Response

func (r *UpdateDatasetsDocumentsResp) Response() HTTPResponse

type UpdateDatasetsReq

type UpdateDatasetsReq struct {
	DatasetID   string `json:"-"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	IconFileID  string `json:"file_id,omitempty"`
}

UpdateDatasetsReq 表示更新数据集的请求

type UpdateDatasetsResp

type UpdateDatasetsResp struct {
	// contains filtered or unexported fields
}

func (*UpdateDatasetsResp) LogID

func (r *UpdateDatasetsResp) LogID() string

func (*UpdateDatasetsResp) Response

func (r *UpdateDatasetsResp) Response() HTTPResponse

type UploadFilesReq

type UploadFilesReq struct {
	File FileTypes
}

type UploadFilesResp

type UploadFilesResp struct {
	FileInfo
	// contains filtered or unexported fields
}

UploadFilesResp represents response for uploading file

func (*UploadFilesResp) LogID

func (r *UploadFilesResp) LogID() string

func (*UploadFilesResp) Response

func (r *UploadFilesResp) Response() HTTPResponse

type User

type User struct {
	UserID    string `json:"user_id"`
	UserName  string `json:"user_name"`
	NickName  string `json:"nick_name"`
	AvatarURL string `json:"avatar_url"`
	// contains filtered or unexported fields
}

User represents a Coze user

func (*User) LogID

func (r *User) LogID() string

func (*User) Response

func (r *User) Response() HTTPResponse

type Voice

type Voice struct {
	VoiceID                string `json:"voice_id"`
	Name                   string `json:"name"`
	IsSystemVoice          bool   `json:"is_system_voice"`
	LanguageCode           string `json:"language_code"`
	LanguageName           string `json:"language_name"`
	PreviewText            string `json:"preview_text"`
	PreviewAudio           string `json:"preview_audio"`
	AvailableTrainingTimes int    `json:"available_training_times"`
	CreateTime             int    `json:"create_time"`
	UpdateTime             int    `json:"update_time"`
}

Voice represents the voice model

type WebOAuthClient

type WebOAuthClient struct {
	*OAuthClient
}

WebOAuthClient Web OAuth core

func NewWebOAuthClient

func NewWebOAuthClient(clientID, clientSecret string, opts ...OAuthClientOption) (*WebOAuthClient, error)

NewWebOAuthClient creates a new Web OAuth core

func (*WebOAuthClient) GetAccessToken

func (c *WebOAuthClient) GetAccessToken(ctx context.Context, req *GetWebOAuthAccessTokenReq) (*OAuthToken, error)

GetAccessToken gets the access token

func (*WebOAuthClient) GetOAuthURL

func (c *WebOAuthClient) GetOAuthURL(ctx context.Context, req *GetWebOAuthURLReq) string

GetOAuthURL Get OAuth URL

func (*WebOAuthClient) RefreshToken

func (c *WebOAuthClient) RefreshToken(ctx context.Context, refreshToken string) (*OAuthToken, error)

RefreshToken refreshes the access token

type WorkflowEvent

type WorkflowEvent struct {
	// The event ID of this message in the interface response. It starts from 0.
	ID int `json:"id"`

	// The current streaming data packet event.
	Event WorkflowEventType `json:"event"`

	Message   *WorkflowEventMessage   `json:"message,omitempty"`
	Interrupt *WorkflowEventInterrupt `json:"interrupt,omitempty"`
	Error     *WorkflowEventError     `json:"error,omitempty"`
	DebugURL  *WorkflowEventDebugURL  `json:"debug_url,omitempty"`
}

WorkflowEvent represents an event in a workflow

func (*WorkflowEvent) IsDone

func (e *WorkflowEvent) IsDone() bool

type WorkflowEventDebugURL

type WorkflowEventDebugURL struct {
	URL string `json:"debug_url"`
}

type WorkflowEventError

type WorkflowEventError struct {
	// Status code. 0 represents a successful API call. Other values indicate that the call has
	// failed. You can determine the detailed reason for the error through the error_message field.
	ErrorCode int `json:"error_code"`

	// Status message. You can get detailed error information when the API call fails.
	ErrorMessage string `json:"error_message"`
}

WorkflowEventError represents an error event in a workflow

func ParseWorkflowEventError

func ParseWorkflowEventError(data string) (*WorkflowEventError, error)

ParseWorkflowEventError parses JSON string to WorkflowEventError

type WorkflowEventInterrupt

type WorkflowEventInterrupt struct {
	// The content of interruption event.
	InterruptData *WorkflowEventInterruptData `json:"interrupt_data"`

	// The name of the node that outputs the message, such as "Question".
	NodeTitle string `json:"node_title"`
}

WorkflowEventInterrupt represents an interruption event in a workflow

func ParseWorkflowEventInterrupt

func ParseWorkflowEventInterrupt(data string) (*WorkflowEventInterrupt, error)

ParseWorkflowEventInterrupt parses JSON string to WorkflowEventInterrupt

type WorkflowEventInterruptData

type WorkflowEventInterruptData struct {
	// The workflow interruption event ID, which should be passed back when resuming the workflow.
	EventID string `json:"event_id"`

	// The type of workflow interruption, which should be passed back when resuming the workflow.
	Type int `json:"type"`
}

WorkflowEventInterruptData represents the data of an interruption event

type WorkflowEventMessage

type WorkflowEventMessage struct {
	// The content of the streamed output message.
	Content string `json:"content"`

	// The name of the node that outputs the message, such as the message node or end node.
	NodeTitle string `json:"node_title"`

	// The message ID of this message within the node, starting at 0.
	NodeSeqID string `json:"node_seq_id"`

	// Whether the current message is the last data packet for this node.
	NodeIsFinish bool `json:"node_is_finish"`

	// Additional fields.
	Ext map[string]any `json:"ext,omitempty"`
}

WorkflowEventMessage represents a message event in a workflow

type WorkflowEventType

type WorkflowEventType string

WorkflowEventType represents the type of workflow event

const (
	// The output message from the workflow node, such as the output message from the message node or
	// end node. You can view the specific message content in data.
	WorkflowEventTypeMessage WorkflowEventType = "Message"

	// An error has occurred. You can view the error_code and error_message in data to troubleshoot
	// the issue.
	WorkflowEventTypeError WorkflowEventType = "Error"

	// End. Indicates the end of the workflow execution, where data is empty.
	WorkflowEventTypeDone WorkflowEventType = "Done"

	// Interruption. Indicates the workflow has been interrupted, where the data field contains
	// specific interruption information.
	WorkflowEventTypeInterrupt WorkflowEventType = "Interrupt"
)

type WorkflowExecuteStatus

type WorkflowExecuteStatus string

WorkflowExecuteStatus represents the execution status of a workflow

const (
	// WorkflowExecuteStatusSuccess Execution succeeded.
	WorkflowExecuteStatusSuccess WorkflowExecuteStatus = "Success"

	// WorkflowExecuteStatusRunning Execution in progress.
	WorkflowExecuteStatusRunning WorkflowExecuteStatus = "Running"

	// WorkflowExecuteStatusFail Execution failed.
	WorkflowExecuteStatusFail WorkflowExecuteStatus = "Fail"
)

type WorkflowRunHistory

type WorkflowRunHistory struct {
	// The ID of execute.
	ExecuteID string `json:"execute_id"`

	// Execute status: success: Execution succeeded. running: Execution in progress. fail: Execution failed.
	ExecuteStatus WorkflowExecuteStatus `json:"execute_status"`

	// The Bot ID specified when executing the workflow. Returns 0 if no Bot ID was specified.
	BotID string `json:"bot_id"`

	// The release connector ID of the agent. By default, only the Agent as API connector is
	// displayed, and the connector ID is 1024.
	ConnectorID string `json:"connector_id"`

	// User ID, the user_id specified by the ext field when executing the workflow. If not specified,
	// the token applicant's button ID is returned.
	ConnectorUid string `json:"connector_uid"`

	// How the workflow runs: 0: Synchronous operation. 1: Streaming operation. 2: Asynchronous operation.
	RunMode WorkflowRunMode `json:"run_mode"`

	// The Log ID of the asynchronously running workflow. If the workflow is executed abnormally, you
	// can contact the service team to troubleshoot the problem through the Log ID.
	LogID string `json:"logid"`

	// The start time of the workflow, in Unix time timestamp format, in seconds.
	CreateTime int `json:"create_time"`

	// The workflow resume running time, in Unix time timestamp format, in seconds.
	UpdateTime int `json:"update_time"`

	// The output of the workflow is usually a JSON serialized string, but it may also be a non-JSON
	// structured string.
	Output string `json:"output"`

	// Status code. 0 represents a successful API call. Other values indicate that the call has
	// failed. You can determine the detailed reason for the error through the error_message field.
	ErrorCode string `json:"error_code"`

	// Status message. You can get detailed error information when the API call fails.
	ErrorMessage string `json:"error_message"`

	// Workflow trial runs debugging page. Visit this page to view the running results, input and
	// output information of each workflow node.
	DebugURL string `json:"debug_url"`
}

WorkflowRunHistory represents the history of a workflow runs

type WorkflowRunMode

type WorkflowRunMode int

WorkflowRunMode represents how the workflow runs

const (
	// WorkflowRunModeSynchronous Synchronous operation.
	WorkflowRunModeSynchronous WorkflowRunMode = 0

	// WorkflowRunModeStreaming Streaming operation.
	WorkflowRunModeStreaming WorkflowRunMode = 1

	// WorkflowRunModeAsynchronous Asynchronous operation.
	WorkflowRunModeAsynchronous WorkflowRunMode = 2
)

type WorkflowRunResult

type WorkflowRunResult struct {
	DebugUrl string `json:"debug_url"`

	// Workflow execution result, usually a JSON serialized string. In some scenarios, a string with a
	// non-JSON structure may be returned.
	Data string `json:"data"`

	// Execution ID of asynchronous execution. Only returned when the workflow is executed
	// asynchronously (is_async=true). You can use execute_id to call the Query Workflow Asynchronous
	// Execution Result API to obtain the final execution result of the workflow.
	ExecuteID string `json:"execute_id"`
}

WorkflowRunResult represents the result of a workflow runs

type WorkflowsChatStreamReq

type WorkflowsChatStreamReq struct {
	WorkflowID         string            `json:"workflow_id"`               // 工作流ID
	AdditionalMessages []*Message        `json:"additional_messages"`       // 额外的消息信息
	Parameters         map[string]any    `json:"parameters,omitempty"`      // 工作流参数
	AppID              *string           `json:"app_id,omitempty"`          // 应用ID
	BotID              *string           `json:"bot_id,omitempty"`          // 机器人ID
	ConversationID     *string           `json:"conversation_id,omitempty"` // 会话ID
	Ext                map[string]string `json:"ext,omitempty"`             // 扩展信息
}

WorkflowsChatStreamReq 表示工作流聊天流式请求

type Workspace

type Workspace struct {
	ID            string            `json:"id"`
	Name          string            `json:"name"`
	IconUrl       string            `json:"icon_url"`
	RoleType      WorkspaceRoleType `json:"role_type"`
	WorkspaceType WorkspaceType     `json:"workspace_type"`
}

Workspace represents workspace information

type WorkspaceRoleType

type WorkspaceRoleType string

WorkspaceRoleType represents the workspace role type

const (
	WorkspaceRoleTypeOwner  WorkspaceRoleType = "owner"
	WorkspaceRoleTypeAdmin  WorkspaceRoleType = "admin"
	WorkspaceRoleTypeMember WorkspaceRoleType = "member"
)

type WorkspaceType

type WorkspaceType string

WorkspaceType represents the workspace type

const (
	WorkspaceTypePersonal WorkspaceType = "personal"
	WorkspaceTypeTeam     WorkspaceType = "team"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL