Documentation
¶
Overview ¶
Package gigachat provides a Go client SDK for the GigaChat API. It supports chat completions, models management, file uploads, and streaming.
Index ¶
- Variables
- func GetMIMEType(filename string) (string, error)
- type AccessPolicy
- type ChatRequest
- func NewChatRequest(model ModelWithPreview, messages []Message) *ChatRequest
- func NewChatRequestWithAudio(model string, prompt string, audioIDs []string) *ChatRequest
- func NewChatRequestWithImages(model string, prompt string, imageIDs []string) *ChatRequest
- func NewChatRequestWithTextFiles(model string, prompt string, fileIDs []string, functionCallAuto bool) *ChatRequest
- type ChatResponse
- type Choice
- type Client
- func (c *Client) ClearModelsCache()
- func (c *Client) Completion(ctx context.Context, req *ChatRequest, opts ...RequestOption) (*ChatResponse, error)
- func (c *Client) CompletionStream(ctx context.Context, req *ChatRequest, opts ...RequestOption) (<-chan StreamChunk, <-chan error)
- func (c *Client) DeleteFile(ctx context.Context, fileID string) (*DeleteResponse, error)
- func (c *Client) GetFile(ctx context.Context, fileID string) (*File, error)
- func (c *Client) GetModel(ctx context.Context, modelID string) (*entity.Model, error)
- func (c *Client) List(ctx context.Context) (*entity.ModelsResponse, error)
- func (c *Client) ListAICheckModels(ctx context.Context) ([]entity.Model, error)
- func (c *Client) ListChatModels(ctx context.Context) ([]entity.Model, error)
- func (c *Client) ListEmbedderModels(ctx context.Context) ([]entity.Model, error)
- func (c *Client) ListFiles(ctx context.Context) (*FilesResponse, error)
- func (c *Client) ListPreviewModels(ctx context.Context) ([]entity.Model, error)
- func (c *Client) ListProductionModels(ctx context.Context) ([]entity.Model, error)
- func (c *Client) UploadFile(ctx context.Context, req *UploadFileRequest) (*File, error)
- func (c *Client) UploadFileFromPath(ctx context.Context, filePath string, purpose FilePurpose, clientID string) (*File, error)
- type Config
- type CustomFunction
- type DeleteResponse
- type FewShotExample
- type File
- type FilePurpose
- type FilesResponse
- type FinishReason
- type FunctionCall
- type FunctionCallMode
- type FunctionCallParam
- type Message
- type Modality
- type ModelWithPreview
- type RequestOption
- type RequestOptions
- type Role
- type StreamChoice
- type StreamChunk
- type StreamDelta
- type UploadFileRequest
- type Usage
Constants ¶
This section is empty.
Variables ¶
var ( ErrBadRequest = errors.New("bad request") ErrTokenManagerRequired = errors.New("token manager is required") ErrModelNotFound = errors.New("model not found") ErrFileRequired = errors.New("file is required") ErrFileNameRequired = errors.New("file name is required") ErrFileSizeRequired = errors.New("file size must be positive") )
Common errors returned by the client.
var ( ModelGigaChat = NewModel("GigaChat", false) ModelGigaChatPro = NewModel("GigaChat-Pro", false) ModelGigaChatPlus = NewModel("GigaChat-Plus", false) ModelGigaChat2Max = NewModel("GigaChat-2-Max", false) ModelGigaChatPreview = NewModel("GigaChat", true) ModelGigaChatProPreview = NewModel("GigaChat-Pro", true) ModelGigaChatPlusPreview = NewModel("GigaChat-Plus", true) ModelGigaChat2MaxPreview = NewModel("GigaChat-2-Max", true) )
Common GigaChat models.
Functions ¶
func GetMIMEType ¶
GetMIMEType returns the MIME type for a file extension.
Types ¶
type AccessPolicy ¶
type AccessPolicy string
AccessPolicy represents file access policy.
const ( // AccessPolicyPrivate means only the uploader can access. AccessPolicyPrivate AccessPolicy = "private" )
type ChatRequest ¶
type ChatRequest struct {
// Model ID to use for completion.
Model string `json:"model"`
// Messages in the conversation.
Messages []Message `json:"messages"`
// FunctionCall controls function calling behavior.
FunctionCall *FunctionCallParam `json:"function_call,omitempty"`
// Functions available for the model to call.
Functions []CustomFunction `json:"functions,omitempty"`
// Temperature controls randomness (0-2).
Temperature *float64 `json:"temperature,omitempty"`
// TopP controls nucleus sampling.
TopP *float64 `json:"top_p,omitempty"`
// Stream indicates if the response should be streamed.
Stream bool `json:"stream"`
// MaxTokens limits the response length.
MaxTokens *int32 `json:"max_tokens,omitempty"`
// RepetitionPenalty discourages repetition.
RepetitionPenalty *float64 `json:"repetition_penalty,omitempty"`
// UpdateInterval for streaming updates.
UpdateInterval *float64 `json:"update_interval,omitempty"`
}
ChatRequest represents a request to the chat completions API.
func NewChatRequest ¶
func NewChatRequest(model ModelWithPreview, messages []Message) *ChatRequest
NewChatRequest creates a new chat request with preview model support.
func NewChatRequestWithAudio ¶
func NewChatRequestWithAudio(model string, prompt string, audioIDs []string) *ChatRequest
NewChatRequestWithAudio creates a chat request for audio analysis.
func NewChatRequestWithImages ¶
func NewChatRequestWithImages(model string, prompt string, imageIDs []string) *ChatRequest
NewChatRequestWithImages creates a chat request for image analysis. Note: Only one image per message is allowed.
func NewChatRequestWithTextFiles ¶
func NewChatRequestWithTextFiles(model string, prompt string, fileIDs []string, functionCallAuto bool) *ChatRequest
NewChatRequestWithTextFiles creates a chat request for text document analysis.
type ChatResponse ¶
type ChatResponse struct {
// Choices are the completion choices.
Choices []Choice `json:"choices"`
// Created is the timestamp of creation.
Created int64 `json:"created"`
// Model used for completion.
Model string `json:"model"`
// Object is the type of object ("chat.completion").
Object string `json:"object"`
// Usage statistics for the request.
Usage Usage `json:"usage"`
}
ChatResponse represents a response from the chat completions API.
type Choice ¶
type Choice struct {
// Message containing the completion.
Message Message `json:"message"`
// Index of this choice.
Index int `json:"index"`
// FinishReason indicates why completion stopped.
FinishReason FinishReason `json:"finish_reason"`
}
Choice represents a single completion choice.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the GigaChat API client.
func NewClient ¶
func NewClient(tokenMgr *client.TokenManager, cfg Config) (*Client, error)
NewClient creates a new GigaChat client.
func (*Client) ClearModelsCache ¶
func (c *Client) ClearModelsCache()
ClearModelsCache clears the cached models list.
func (*Client) Completion ¶
func (c *Client) Completion(ctx context.Context, req *ChatRequest, opts ...RequestOption) (*ChatResponse, error)
Completion sends a chat completion request.
func (*Client) CompletionStream ¶
func (c *Client) CompletionStream(ctx context.Context, req *ChatRequest, opts ...RequestOption) (<-chan StreamChunk, <-chan error)
CompletionStream sends a streaming chat completion request. Returns two channels: one for chunks and one for errors.
func (*Client) DeleteFile ¶
DeleteFile deletes a file by ID.
func (*Client) ListAICheckModels ¶
ListAICheckModels returns only AI check models.
func (*Client) ListChatModels ¶
ListChatModels returns only chat models.
func (*Client) ListEmbedderModels ¶
ListEmbedderModels returns only embedder models.
func (*Client) ListFiles ¶
func (c *Client) ListFiles(ctx context.Context) (*FilesResponse, error)
ListFiles returns all uploaded files.
func (*Client) ListPreviewModels ¶
ListPreviewModels returns only preview models.
func (*Client) ListProductionModels ¶
ListProductionModels returns only production (non-preview) models.
func (*Client) UploadFile ¶
UploadFile uploads a file to GigaChat storage using streaming.
func (*Client) UploadFileFromPath ¶
func (c *Client) UploadFileFromPath(ctx context.Context, filePath string, purpose FilePurpose, clientID string) (*File, error)
UploadFileFromPath uploads a file from the local filesystem.
type Config ¶
type Config struct {
// BaseURL for all APIs (default: https://gigachat.devices.sberbank.ru/api/v1).
BaseURL string
// BaseURLModels overrides the entity API URL.
BaseURLModels string
// BaseURLCompletion overrides the chat completions API URL.
BaseURLCompletion string
// BaseURLFiles overrides the files API URL.
BaseURLFiles string
// AllowInsecure disables TLS verification (not recommended for production).
AllowInsecure bool
// Timeout for HTTP requests (default: 30s).
Timeout time.Duration
// Logger for debug output (optional).
Logger types.Logger
// ModelsCacheTTL sets how long to cache entity list (0 disables caching, default: 5m).
ModelsCacheTTL time.Duration
}
Config configures the GigaChat client.
type CustomFunction ¶
type CustomFunction struct {
// Name of the function.
Name string `json:"name"`
// Description of what the function does.
Description *string `json:"description,omitempty"`
// Parameters schema for the function.
Parameters map[string]interface{} `json:"parameters"`
// FewShotExamples are examples for the function.
FewShotExamples []FewShotExample `json:"few_shot_examples,omitempty"`
// ReturnParameters schema for the function's return value.
ReturnParameters map[string]interface{} `json:"return_parameters,omitempty"`
}
CustomFunction represents a user-defined function.
type DeleteResponse ¶
type DeleteResponse struct {
// ID of the deleted file.
ID string `json:"id"`
// Object is the type of object ("file").
Object string `json:"object"`
// Deleted indicates if deletion was successful.
Deleted bool `json:"deleted"`
}
DeleteResponse represents a file deletion response.
type FewShotExample ¶
type FewShotExample struct {
// Request is the user request.
Request string `json:"request"`
// Params are the function parameters.
Params map[string]interface{} `json:"params"`
}
FewShotExample represents an example for a function.
type File ¶
type File struct {
// ID is the unique file identifier.
ID string `json:"id"`
// Object is the type of object ("file").
Object string `json:"object"`
// Bytes is the file size in bytes.
Bytes int64 `json:"bytes"`
// CreatedAt is the upload timestamp.
CreatedAt int64 `json:"created_at"`
// Filename is the original file name.
Filename string `json:"filename"`
// Purpose of the file.
Purpose FilePurpose `json:"purpose"`
// AccessPolicy determines file access.
AccessPolicy AccessPolicy `json:"access_policy"`
// Modalities supported by the file.
Modalities []Modality `json:"modalities,omitempty"`
}
File represents a file in GigaChat storage.
type FilePurpose ¶
type FilePurpose string
FilePurpose represents the purpose of a file upload.
const ( // FilePurposeGeneral for use in chat completions. FilePurposeGeneral FilePurpose = "general" )
type FilesResponse ¶
type FilesResponse struct {
// Data contains the list of files.
Data []File `json:"data"`
// Object is the type of object ("list").
Object string `json:"object"`
}
FilesResponse represents a list of files.
type FinishReason ¶
type FinishReason string
FinishReason represents the reason why a completion finished.
const ( // FinishReasonStop indicates the model finished naturally. FinishReasonStop FinishReason = "stop" // FinishReasonLength indicates the completion exceeded max tokens. FinishReasonLength FinishReason = "length" // FinishReasonFunctionCall indicates the model called a function. FinishReasonFunctionCall FinishReason = "function_call" // FinishReasonBlacklist indicates content was blocked. FinishReasonBlacklist FinishReason = "blacklist" // FinishReasonError indicates an error occurred. FinishReasonError FinishReason = "error" )
type FunctionCall ¶
type FunctionCall struct {
// Name is the function name.
Name string `json:"name"`
// Arguments are the function arguments.
Arguments map[string]interface{} `json:"arguments"`
}
FunctionCall represents a function call in a message.
type FunctionCallMode ¶
type FunctionCallMode string
FunctionCallMode represents how functions should be called.
const ( // FunctionCallNone prevents function calling. FunctionCallNone FunctionCallMode = "none" // FunctionCallAuto allows the model to decide when to call functions. FunctionCallAuto FunctionCallMode = "auto" )
type FunctionCallParam ¶
type FunctionCallParam struct {
// contains filtered or unexported fields
}
FunctionCallParam represents the function_call parameter in chat requests. It can be either a mode ("auto", "none") or a specific function name.
func NewFunctionCallMode ¶
func NewFunctionCallMode(mode FunctionCallMode) FunctionCallParam
NewFunctionCallMode creates a FunctionCallParam with a mode.
func NewFunctionCallName ¶
func NewFunctionCallName(name string) FunctionCallParam
NewFunctionCallName creates a FunctionCallParam with a specific function name.
func (FunctionCallParam) MarshalJSON ¶
func (f FunctionCallParam) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
func (*FunctionCallParam) UnmarshalJSON ¶
func (f *FunctionCallParam) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler.
type Message ¶
type Message struct {
// Role of the message sender.
Role Role `json:"role"`
// Content of the message.
Content string `json:"content,omitempty"`
// FunctionsStateID is an optional state ID for functions.
FunctionsStateID *string `json:"functions_state_id,omitempty"`
// Attachments are file IDs attached to the message.
Attachments []string `json:"attachments,omitempty"`
// Name is used for function_in_progress messages.
Name *string `json:"name,omitempty"`
// Created is a timestamp for function_in_progress messages.
Created *int64 `json:"created,omitempty"`
// FunctionCall represents a function call in the message.
FunctionCall *FunctionCall `json:"function_call,omitempty"`
}
Message represents a chat message.
type ModelWithPreview ¶
ModelWithPreview represents a model with preview support.
func NewModel ¶
func NewModel(baseName string, preview bool) ModelWithPreview
NewModel creates a new model with preview support.
func (ModelWithPreview) String ¶
func (m ModelWithPreview) String() string
String returns the full model name with preview suffix if needed.
type RequestOption ¶
type RequestOption func(*RequestOptions)
RequestOption is a function that sets request options.
func WithClientID ¶
func WithClientID(clientID string) RequestOption
WithClientID sets the X-Client-ID header.
func WithRequestID ¶
func WithRequestID(requestID string) RequestOption
WithRequestID sets the X-Request-ID header. If not provided, a random UUID will be generated.
func WithSessionID ¶
func WithSessionID(sessionID string) RequestOption
WithSessionID sets the X-Session-ID header. If not provided, a random UUID will be generated.
type RequestOptions ¶
RequestOptions contains options for API requests.
type Role ¶
type Role string
Role represents a message role in a chat conversation.
const ( // RoleSystem represents a system message. RoleSystem Role = "system" // RoleUser represents a user message. RoleUser Role = "user" // RoleAssistant represents an assistant message. RoleAssistant Role = "assistant" // RoleFunction represents a function message. RoleFunction Role = "function" // RoleFunctionProgress represents a function progress message. RoleFunctionProgress Role = "function_in_progress" )
type StreamChoice ¶
type StreamChoice struct {
// Delta containing the new content.
Delta StreamDelta `json:"delta"`
// Index of this choice.
Index int `json:"index"`
// FinishReason when the choice is complete.
FinishReason *FinishReason `json:"finish_reason,omitempty"`
}
StreamChoice represents a choice in a stream chunk.
type StreamChunk ¶
type StreamChunk struct {
// Choices in this chunk.
Choices []StreamChoice `json:"choices"`
// Created timestamp.
Created int64 `json:"created"`
// Model being used.
Model string `json:"model"`
// Object type ("chat.completion.chunk").
Object string `json:"object"`
// Usage statistics (only in final chunk).
Usage *Usage `json:"usage,omitempty"`
}
StreamChunk represents a chunk from a streaming response.
type StreamDelta ¶
type StreamDelta struct {
// Role of the message sender.
Role *string `json:"role,omitempty"`
// Content delta.
Content *string `json:"content,omitempty"`
// Name for function_in_progress messages.
Name *string `json:"name,omitempty"`
// FunctionCall delta.
FunctionCall *FunctionCall `json:"function_call,omitempty"`
}
StreamDelta represents the content delta in a stream chunk.
type UploadFileRequest ¶
type UploadFileRequest struct {
// Reader provides the file data.
Reader io.Reader
// FileName is the name of the file.
FileName string
// ContentType is the MIME type (auto-detected if empty).
ContentType string
// Size is the file size in bytes.
Size int64
// Purpose of the file (defaults to "general").
Purpose FilePurpose
// ClientID for X-Client-ID header.
ClientID string
}
UploadFileRequest represents a request to upload a file.
func (*UploadFileRequest) Validate ¶
func (r *UploadFileRequest) Validate() error
Validate validates the upload request.
type Usage ¶
type Usage struct {
// PromptTokens used in the request.
PromptTokens int32 `json:"prompt_tokens"`
// CompletionTokens generated in the response.
CompletionTokens int32 `json:"completion_tokens"`
// PrecachedPromptTokens from cached content.
PrecachedPromptTokens int32 `json:"precached_prompt_tokens"`
// TotalTokens used (prompt + completion).
TotalTokens int32 `json:"total_tokens"`
}
Usage represents token usage statistics.