Documentation
¶
Overview ¶
Package mistral provides a Go client library for the Mistral AI API.
This library allows you to easily integrate Mistral AI's powerful language models into your Go applications. It supports all major features of the Mistral AI API:
- Chat completions (both standard and streaming)
- Text embeddings for semantic search and similarity
- File management for fine-tuning and batch processing
- Model information and management
- Function/tool calling for building AI agents
Getting Started ¶
First, create a client with your API key:
client := mistral.NewClient("your-api-key-here")
Then use the client methods to interact with the API:
resp, err := client.CreateChatCompletion(ctx, &mistral.ChatCompletionRequest{
Model: "mistral-large-latest",
Messages: []mistral.ChatMessage{
{Role: mistral.RoleUser, Content: "Hello!"},
},
})
Authentication ¶
You need a Mistral AI API key to use this library. Get one at https://console.mistral.ai/ Pass your API key when creating the client:
client := mistral.NewClient(os.Getenv("MISTRAL_API_KEY"))
Configuration ¶
Customize the client with functional options:
client := mistral.NewClient(
apiKey,
mistral.WithTimeout(30*time.Second),
mistral.WithBaseURL("https://api.custom-domain.com"),
)
Error Handling ¶
API errors are returned as *APIError, which includes the HTTP status code, error message, type, and code:
resp, err := client.CreateChatCompletion(ctx, req)
if err != nil {
if apiErr, ok := err.(*mistral.APIError); ok {
fmt.Printf("API error %d: %s\n", apiErr.StatusCode, apiErr.Message)
}
return err
}
Examples ¶
See the example_test.go file for comprehensive examples of all features.
Index ¶
- type APIError
- type Agent
- type ChatCompletionChoice
- type ChatCompletionRequest
- type ChatCompletionResponse
- type ChatCompletionStreamResponse
- type ChatMessage
- type Client
- func (c *Client) CreateChatCompletion(ctx context.Context, req *ChatCompletionRequest) (*ChatCompletionResponse, error)
- func (c *Client) CreateChatCompletionStream(ctx context.Context, req *ChatCompletionRequest) (<-chan ChatCompletionStreamResponse, <-chan error)
- func (c *Client) CreateEmbedding(ctx context.Context, req *EmbeddingRequest) (*EmbeddingResponse, error)
- func (c *Client) DeleteFile(ctx context.Context, fileID string) (*DeleteFileResponse, error)
- func (c *Client) DeleteModel(ctx context.Context, modelID string) (*DeleteModelResponse, error)
- func (c *Client) DownloadFile(ctx context.Context, fileID string) (io.ReadCloser, error)
- func (c *Client) GetFile(ctx context.Context, fileID string) (*File, error)
- func (c *Client) GetModel(ctx context.Context, modelID string) (*Model, error)
- func (c *Client) ListFiles(ctx context.Context, params *ListFilesParams) (*FileList, error)
- func (c *Client) ListModels(ctx context.Context) (*ModelList, error)
- func (c *Client) UploadFile(ctx context.Context, req *UploadFileRequest) (*File, error)
- type Conversation
- type DeleteFileResponse
- type DeleteModelResponse
- type EmbeddingObject
- type EmbeddingRequest
- type EmbeddingResponse
- type File
- type FileList
- type FilePurpose
- type FunctionCall
- type ListFilesParams
- type Model
- type ModelList
- type Option
- type ResponseFormat
- type Role
- type Tool
- type ToolCall
- type ToolChoice
- type ToolFunctionDetails
- type UploadFileRequest
- type Usage
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type APIError ¶
type APIError struct {
// StatusCode is the HTTP status code of the error response (e.g., 400, 401, 500).
StatusCode int `json:"-"`
// Message is a human-readable error message describing what went wrong.
Message string `json:"message"`
// Type is the category or type of error (e.g., "invalid_request_error", "authentication_error").
Type string `json:"type,omitempty"`
// Code is a specific error code for programmatic error handling.
Code string `json:"code,omitempty"`
}
APIError represents an error response from the Mistral API. It encapsulates all error information returned by the API, including HTTP status codes, error messages, types, and error codes. This struct implements the error interface.
func (*APIError) Error ¶
Error implements the error interface for APIError. It returns a formatted error message that includes the error type (if available) followed by the error message. This allows APIError to be used wherever a standard Go error is expected. Returns a string in the format "type: message" if Type is set, otherwise just "message".
type Agent ¶
type Agent struct {
// ID is a unique identifier for the agent.
ID string `json:"id"`
// Object is the object type, typically "agent".
Object string `json:"object"`
// CreatedAt is the timestamp when the agent was created.
CreatedAt time.Time `json:"created_at"`
// Name is a human-readable name for the agent.
Name string `json:"name"`
// Description is an optional description explaining the agent's purpose or capabilities.
Description string `json:"description,omitempty"`
// Model is the ID of the model this agent uses for generation (e.g., "mistral-large-latest").
Model string `json:"model"`
// Instructions are system-level instructions that guide the agent's behavior. These are
// similar to system messages and define the agent's personality, constraints, and objectives.
Instructions string `json:"instructions,omitempty"`
// Tools is an array of tools/functions available to the agent for accomplishing tasks.
Tools []Tool `json:"tools,omitempty"`
// Metadata contains custom key-value pairs for storing additional information about the agent.
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Agent represents an AI agent configured with specific behavior and capabilities. Agents are persistent entities that encapsulate a model, instructions, available tools, and other configuration to provide consistent behavior across multiple conversations.
type ChatCompletionChoice ¶
type ChatCompletionChoice struct {
// Index is the index of this choice in the list of choices (0-based).
Index int `json:"index"`
// Message is the generated chat message from the assistant. This contains the actual
// response content and any tool calls the model wants to make.
Message ChatMessage `json:"message"`
// FinishReason is the reason why the model stopped generating tokens. Possible values:
// - "stop" - Natural stopping point or provided stop sequence was reached
// - "length" - Maximum token limit was reached
// - "tool_calls" - The model called a function/tool
// - "content_filter" - Content was filtered due to safety settings
FinishReason string `json:"finish_reason"`
// Delta is used only in streaming responses. Contains the incremental changes
// to the message as new tokens are generated. Null in non-streaming responses.
Delta *ChatMessage `json:"delta,omitempty"`
}
ChatCompletionChoice represents a single generated completion alternative. When N>1 in the request, multiple choices are generated and you can select the most appropriate one for your use case.
type ChatCompletionRequest ¶
type ChatCompletionRequest struct {
// Model is the ID of the model to use (e.g., "mistral-large-latest", "mistral-small").
// This is required. Choose based on your needs for speed vs. capability.
Model string `json:"model"`
// Messages is an array of ChatMessage objects that form the conversation history.
// Must contain at least one message. The model will generate a response based on this context.
Messages []ChatMessage `json:"messages"`
// Temperature controls randomness in generation. Range: 0.0 to 1.0 (or higher for some models).
// Lower values (e.g., 0.2) make output more focused and deterministic. Higher values (e.g., 0.8)
// make output more creative and varied. Default is typically 0.7.
Temperature *float64 `json:"temperature,omitempty"`
// TopP is the nucleus sampling parameter. Range: 0.0 to 1.0. Alternative to temperature for
// controlling randomness. The model considers tokens with top_p probability mass.
// For example, 0.1 means only tokens comprising the top 10% probability mass are considered.
TopP *float64 `json:"top_p,omitempty"`
// MaxTokens is the maximum number of tokens to generate in the completion.
// The total length of input tokens plus max_tokens cannot exceed the model's context length.
MaxTokens *int `json:"max_tokens,omitempty"`
// MinTokens is the minimum number of tokens to generate. Useful when you need
// a response of at least a certain length.
MinTokens *int `json:"min_tokens,omitempty"`
// Stream indicates whether to stream partial message deltas as server-sent events.
// If true, use CreateChatCompletionStream instead of CreateChatCompletion.
Stream bool `json:"stream,omitempty"`
// Stop contains up to 4 sequences where the API will stop generating further tokens.
// The returned text will not contain the stop sequence.
Stop []string `json:"stop,omitempty"`
// RandomSeed, if specified, makes the system attempt to sample deterministically
// such that repeated requests with the same seed and parameters return the same result.
// Determinism is not guaranteed.
RandomSeed *int `json:"random_seed,omitempty"`
// Tools is a list of tools/functions the model may call. The model can choose to call
// one or more of these functions if it determines they would help fulfill the request.
Tools []Tool `json:"tools,omitempty"`
// ToolChoice controls how the model uses the provided tools. Options: "auto", "any", "none".
// Default is "auto", which lets the model decide whether to use tools.
ToolChoice ToolChoice `json:"tool_choice,omitempty"`
// ResponseFormat specifies the format of the response. Set to {"type": "json_object"}
// to enable JSON mode, which guarantees the message the model generates is valid JSON.
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
// SafePrompt indicates whether to inject a safety prompt before all conversations. Default is false.
SafePrompt bool `json:"safe_prompt,omitempty"`
// N is how many chat completion choices to generate for each input message.
// Note: N>1 may consume significantly more tokens.
N *int `json:"n,omitempty"`
// PresencePenalty is a number between -2.0 and 2.0. Positive values penalize new tokens
// based on whether they appear in the text so far, increasing the model's likelihood
// to talk about new topics.
PresencePenalty *float64 `json:"presence_penalty,omitempty"`
// FrequencyPenalty is a number between -2.0 and 2.0. Positive values penalize new tokens
// based on their existing frequency in the text so far, decreasing the model's likelihood
// to repeat the same line verbatim.
FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
// Metadata is optional metadata to attach to the request for tracking and filtering purposes.
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ChatCompletionRequest represents a request to the Mistral AI chat completions API. This structure contains all parameters needed to generate text completions based on conversational context. The request supports both simple text generation and advanced features like function calling, structured outputs, and streaming responses.
type ChatCompletionResponse ¶
type ChatCompletionResponse struct {
// ID is a unique identifier for this completion request.
ID string `json:"id"`
// Object is the object type, typically "chat.completion".
Object string `json:"object"`
// Created is a Unix timestamp (in seconds) of when the completion was created.
Created int64 `json:"created"`
// Model is the model used for generating the completion.
Model string `json:"model"`
// Choices is an array of completion choices. If N=1 in the request, this will contain
// a single choice. Each choice contains the generated message and metadata.
Choices []ChatCompletionChoice `json:"choices"`
// Usage contains token usage statistics for this request, including prompt tokens,
// completion tokens, and total tokens used.
Usage Usage `json:"usage"`
}
ChatCompletionResponse represents a complete response from the chat completions API. This is returned by non-streaming chat completion requests and contains the full generated response along with metadata about the request.
type ChatCompletionStreamResponse ¶
type ChatCompletionStreamResponse struct {
// ID is a unique identifier for this completion request (consistent across all chunks).
ID string `json:"id"`
// Object is the object type, typically "chat.completion.chunk".
Object string `json:"object"`
// Created is a Unix timestamp (in seconds) of when the completion was created.
Created int64 `json:"created"`
// Model is the model used for generating the completion.
Model string `json:"model"`
// Choices is an array of completion choice deltas. Each choice contains the Delta field
// with incremental content. The last chunk will have a FinishReason set.
Choices []ChatCompletionChoice `json:"choices"`
}
ChatCompletionStreamResponse represents a single chunk in a streaming response. When using streaming mode (Stream: true), the API returns multiple chunks as server-sent events. Each chunk contains incremental updates to the response. Combine all chunks to reconstruct the complete response.
type ChatMessage ¶
type ChatMessage struct {
// Role is the sender of the message (system, user, assistant, or tool).
Role Role `json:"role"`
// Content is the message content. Can be a string for simple text or an array of
// content parts for multimodal messages (text, images, etc.).
Content interface{} `json:"content"`
// Name is an optional name of the message author, useful for distinguishing between
// multiple users or tools in a conversation.
Name string `json:"name,omitempty"`
// ToolCallID is used when the role is "tool". It contains the ID of the tool call
// that this message is responding to, linking the result back to the request.
ToolCallID string `json:"tool_call_id,omitempty"`
// ToolCalls contains the list of tool calls the assistant wants to make when
// the assistant determines it needs to use tools/functions.
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
}
ChatMessage represents a single message in a chat conversation. Messages form the core of interactions with the Mistral AI chat models, carrying content between users, the AI assistant, system instructions, and tool results.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a Mistral AI API client. This is the main entry point for interacting with the Mistral AI API. Create a new client using NewClient and then call its methods to access chat completions, embeddings, file management, and model operations.
The client is safe for concurrent use by multiple goroutines.
func NewClient ¶
NewClient creates a new Mistral AI API client with the provided API key. You can customize the client behavior by passing functional options.
Parameters:
- apiKey: Your Mistral AI API key (required). Get one from https://console.mistral.ai/
- opts: Optional configuration functions to customize the client (see WithBaseURL, WithHTTPClient, WithTimeout)
Returns:
- A configured Client ready to make API requests
Example:
client := mistral.NewClient("your-api-key-here")
// Or with options:
client := mistral.NewClient(
"your-api-key-here",
mistral.WithTimeout(30*time.Second),
)
func (*Client) CreateChatCompletion ¶
func (c *Client) CreateChatCompletion(ctx context.Context, req *ChatCompletionRequest) (*ChatCompletionResponse, error)
CreateChatCompletion creates a chat completion using the Mistral AI chat API. This method sends a conversation history to the model and receives a complete response. For streaming responses, use CreateChatCompletionStream instead.
Parameters:
- ctx: Context for request cancellation and timeout control
- req: The chat completion request containing model, messages, and generation parameters
Returns:
- A ChatCompletionResponse with the generated completion and metadata, or an error if the request fails
Example:
resp, err := client.CreateChatCompletion(ctx, &mistral.ChatCompletionRequest{
Model: "mistral-large-latest",
Messages: []mistral.ChatMessage{
{Role: mistral.RoleUser, Content: "Hello!"},
},
})
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/ua1984/mistral"
)
func main() {
client := mistral.NewClient(os.Getenv("MISTRAL_API_KEY"))
resp, err := client.CreateChatCompletion(context.Background(), &mistral.ChatCompletionRequest{
Model: "mistral-large-latest",
Messages: []mistral.ChatMessage{
{
Role: mistral.RoleUser,
Content: "What is the capital of France?",
},
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Choices[0].Message.Content)
}
Output:
func (*Client) CreateChatCompletionStream ¶
func (c *Client) CreateChatCompletionStream(ctx context.Context, req *ChatCompletionRequest) (<-chan ChatCompletionStreamResponse, <-chan error)
CreateChatCompletionStream creates a streaming chat completion. This method returns two channels: one for receiving response chunks as they're generated, and one for errors. The chunks arrive incrementally, allowing you to display partial responses to users as they're generated. This automatically sets req.Stream to true.
Parameters:
- ctx: Context for request cancellation and timeout control
- req: The chat completion request. The Stream field will be set to true automatically
Returns:
- A channel that receives ChatCompletionStreamResponse chunks as they arrive
- A channel that receives at most one error (or nil if the stream completes successfully)
Both channels are closed when the stream ends or an error occurs.
Example:
respChan, errChan := client.CreateChatCompletionStream(ctx, &mistral.ChatCompletionRequest{
Model: "mistral-large-latest",
Messages: []mistral.ChatMessage{
{Role: mistral.RoleUser, Content: "Tell me a story"},
},
})
for chunk := range respChan {
// Process each chunk as it arrives
fmt.Print(chunk.Choices[0].Delta.Content)
}
if err := <-errChan; err != nil {
// Handle error
}
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/ua1984/mistral"
)
func main() {
client := mistral.NewClient(os.Getenv("MISTRAL_API_KEY"))
ctx := context.Background()
respChan, errChan := client.CreateChatCompletionStream(ctx, &mistral.ChatCompletionRequest{
Model: "mistral-large-latest",
Messages: []mistral.ChatMessage{
{
Role: mistral.RoleUser,
Content: "Tell me a short story",
},
},
})
for {
select {
case chunk, ok := <-respChan:
if !ok {
return
}
if len(chunk.Choices) > 0 && chunk.Choices[0].Delta != nil {
fmt.Print(chunk.Choices[0].Delta.Content)
}
case err := <-errChan:
if err != nil {
log.Fatal(err)
}
return
case <-ctx.Done():
return
}
}
}
Output:
func (*Client) CreateEmbedding ¶
func (c *Client) CreateEmbedding(ctx context.Context, req *EmbeddingRequest) (*EmbeddingResponse, error)
CreateEmbedding creates embeddings for the given input texts. Embeddings are dense vector representations of text that capture semantic meaning, useful for similarity search, clustering, classification, and other ML tasks.
Parameters:
- ctx: Context for request cancellation and timeout control
- req: The embedding request containing the model and input texts
Returns:
- An EmbeddingResponse containing embedding vectors for each input text, or an error
Example:
resp, err := client.CreateEmbedding(ctx, &mistral.EmbeddingRequest{
Model: "mistral-embed",
Input: []string{"Hello world", "Goodbye world"},
})
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/ua1984/mistral"
)
func main() {
client := mistral.NewClient(os.Getenv("MISTRAL_API_KEY"))
resp, err := client.CreateEmbedding(context.Background(), &mistral.EmbeddingRequest{
Model: "mistral-embed",
Input: []string{
"Hello, world!",
"How are you?",
},
})
if err != nil {
log.Fatal(err)
}
for i, emb := range resp.Data {
fmt.Printf("Embedding %d has %d dimensions\n", i, len(emb.Embedding))
}
}
Output:
func (*Client) DeleteFile ¶
DeleteFile deletes a file from your account. This permanently removes the file and it cannot be recovered. The file ID will no longer be valid for any operations.
Parameters:
- ctx: Context for request cancellation and timeout control
- fileID: The unique identifier of the file to delete
Returns:
- A DeleteFileResponse confirming the deletion, or an error if the file doesn't exist or the request fails
Example:
resp, err := client.DeleteFile(ctx, "file-abc123")
if err != nil {
return err
}
if resp.Deleted {
fmt.Println("File successfully deleted")
}
func (*Client) DeleteModel ¶
DeleteModel deletes a fine-tuned model from your account. This only works for custom fine-tuned models; you cannot delete base models provided by Mistral AI. Once deleted, the model cannot be recovered and will no longer be usable for completions.
Parameters:
- ctx: Context for request cancellation and timeout control
- modelID: The unique identifier of the fine-tuned model to delete
Returns:
- A DeleteModelResponse confirming the deletion, or an error if the model doesn't exist, is not a fine-tuned model, or the request fails
Example:
resp, err := client.DeleteModel(ctx, "my-fine-tuned-model")
if err != nil {
return err
}
if resp.Deleted {
fmt.Println("Model successfully deleted")
}
func (*Client) DownloadFile ¶
DownloadFile downloads the actual content of a file. This returns an io.ReadCloser that streams the file content. You are responsible for closing the reader when done to free resources.
Parameters:
- ctx: Context for request cancellation and timeout control
- fileID: The unique identifier of the file to download
Returns:
- An io.ReadCloser that streams the file content. Must be closed by the caller. Returns an error if the file doesn't exist or the request fails
Example:
reader, err := client.DownloadFile(ctx, "file-abc123")
if err != nil {
return err
}
defer reader.Close()
content, err := io.ReadAll(reader)
if err != nil {
return err
}
func (*Client) GetFile ¶
GetFile retrieves metadata about a specific file by its ID. This returns information about the file but not its content. Use DownloadFile to retrieve the actual file content.
Parameters:
- ctx: Context for request cancellation and timeout control
- fileID: The unique identifier of the file to retrieve
Returns:
- A File object containing metadata about the file, or an error if the file doesn't exist or the request fails
Example:
file, err := client.GetFile(ctx, "file-abc123")
func (*Client) GetModel ¶
GetModel retrieves detailed information about a specific model by its ID. This is useful for checking a model's capabilities, token limits, and other metadata before using it.
Parameters:
- ctx: Context for request cancellation and timeout control
- modelID: The unique identifier of the model (e.g., "mistral-large-latest")
Returns:
- A Model object containing detailed metadata, or an error if the model doesn't exist or the request fails
Example:
model, err := client.GetModel(ctx, "mistral-large-latest")
if err != nil {
return err
}
fmt.Printf("Max tokens: %d\n", model.MaxTokens)
func (*Client) ListFiles ¶
ListFiles retrieves a paginated list of files that have been uploaded to your account. You can filter by purpose, search by filename, and control pagination.
Parameters:
- ctx: Context for request cancellation and timeout control
- params: Optional filtering and pagination parameters. Pass nil to use defaults
Returns:
- A FileList containing an array of File objects and pagination metadata, or an error if the request fails
Example:
// List all files
files, err := client.ListFiles(ctx, nil)
// List only fine-tuning files with pagination
files, err := client.ListFiles(ctx, &mistral.ListFilesParams{
Purpose: mistral.FilePurposeFineTune,
Page: 1,
PageSize: 20,
})
func (*Client) ListModels ¶
ListModels retrieves a list of all available models. This includes both base models provided by Mistral AI and any fine-tuned models in your account. The response includes metadata about each model's capabilities and limitations.
Parameters:
- ctx: Context for request cancellation and timeout control
Returns:
- A ModelList containing an array of Model objects, or an error if the request fails
Example:
models, err := client.ListModels(ctx)
if err != nil {
return err
}
for _, model := range models.Data {
fmt.Printf("Model: %s, Max Tokens: %d\n", model.ID, model.MaxTokens)
}
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/ua1984/mistral"
)
func main() {
client := mistral.NewClient(os.Getenv("MISTRAL_API_KEY"))
models, err := client.ListModels(context.Background())
if err != nil {
log.Fatal(err)
}
for _, model := range models.Data {
fmt.Printf("Model: %s\n", model.ID)
}
}
Output:
func (*Client) UploadFile ¶
UploadFile uploads a file to the Mistral API for use in fine-tuning or batch processing. The file content is sent as multipart form data along with metadata.
Parameters:
- ctx: Context for request cancellation and timeout control
- req: The upload request containing the file content, filename, and purpose
Returns:
- A File object with metadata about the uploaded file (including its ID for future reference), or an error if the upload fails
Example:
file, err := os.Open("training_data.jsonl")
if err != nil {
return err
}
defer file.Close()
uploadedFile, err := client.UploadFile(ctx, &mistral.UploadFileRequest{
File: file,
Filename: "training_data.jsonl",
Purpose: mistral.FilePurposeFineTune,
})
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/ua1984/mistral"
)
func main() {
client := mistral.NewClient(os.Getenv("MISTRAL_API_KEY"))
file, err := os.Open("training_data.jsonl")
if err != nil {
log.Fatal(err)
}
defer file.Close()
uploadedFile, err := client.UploadFile(context.Background(), &mistral.UploadFileRequest{
File: file,
Filename: "training_data.jsonl",
Purpose: mistral.FilePurposeFineTune,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Uploaded file ID: %s\n", uploadedFile.ID)
}
Output:
type Conversation ¶
type Conversation struct {
// ID is a unique identifier for the conversation.
ID string `json:"id"`
// Object is the object type, typically "conversation".
Object string `json:"object"`
// CreatedAt is the timestamp when the conversation was created.
CreatedAt time.Time `json:"created_at"`
// Model is an optional override for the model to use in this conversation. If not set,
// uses the agent's model (if associated with an agent) or a default model.
Model string `json:"model,omitempty"`
// AgentID is an optional ID of the agent associated with this conversation. If set,
// the conversation will use the agent's instructions and tools.
AgentID string `json:"agent_id,omitempty"`
// Metadata contains custom key-value pairs for storing additional information about
// the conversation.
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Conversation represents a persistent conversation thread. Conversations maintain the message history and context for ongoing interactions, optionally associated with a specific agent.
type DeleteFileResponse ¶
type DeleteFileResponse struct {
// ID is the unique identifier of the file that was deleted.
ID string `json:"id"`
// Object is the object type, typically "file".
Object string `json:"object"`
// Deleted is a boolean indicating whether the deletion was successful.
Deleted bool `json:"deleted"`
}
DeleteFileResponse represents the API response after attempting to delete a file. This confirms whether a file was successfully removed from storage.
type DeleteModelResponse ¶
type DeleteModelResponse struct {
// ID is the unique identifier of the model that was deleted.
ID string `json:"id"`
// Object is the object type, typically "model".
Object string `json:"object"`
// Deleted is a boolean indicating whether the deletion was successful.
Deleted bool `json:"deleted"`
}
DeleteModelResponse represents the API response after attempting to delete a model. This is returned when deleting fine-tuned models (base models cannot be deleted).
type EmbeddingObject ¶
type EmbeddingObject struct {
// Object is the object type, typically "embedding".
Object string `json:"object"`
// Embedding is a vector of floating-point numbers representing the semantic embedding
// of the input text. The dimensionality depends on the embedding model used.
Embedding []float64 `json:"embedding"`
// Index is the position of this embedding in the original input array, allowing you
// to match results back to the corresponding input text.
Index int `json:"index"`
}
EmbeddingObject represents a single embedding vector and its metadata. Embeddings are dense vector representations of text that capture semantic meaning, useful for tasks like similarity search, clustering, and classification.
type EmbeddingRequest ¶
type EmbeddingRequest struct {
// Model is the ID of the embeddings model to use (e.g., "mistral-embed").
// This is required. Different models may produce embeddings with different dimensions.
Model string `json:"model"`
// Input is an array of strings to generate embeddings for. Each string will be converted
// into a separate embedding vector. Maximum items and total length depend on the model's limits.
Input []string `json:"input"`
// EncodingFormat is the format in which to return the embeddings. Options:
// - "float" (default) - Returns embeddings as arrays of floating-point numbers
// - "base64" - Returns embeddings as base64-encoded strings, which is more compact
// for transmission but requires decoding before use
EncodingFormat string `json:"encoding_format,omitempty"`
}
EmbeddingRequest represents a request to the Mistral AI embeddings API. Embeddings convert text into dense numerical vectors that capture semantic meaning, enabling tasks like similarity search, clustering, recommendation systems, and classification.
type EmbeddingResponse ¶
type EmbeddingResponse struct {
// ID is a unique identifier for this embeddings request.
ID string `json:"id"`
// Object is the object type, typically "list".
Object string `json:"object"`
// Data is an array of EmbeddingObject instances, one for each input string.
// The order matches the order of strings in the Input field of the request.
// Use the Index field of each embedding to correlate results with inputs.
Data []EmbeddingObject `json:"data"`
// Model is the model that was used to generate the embeddings.
Model string `json:"model"`
// Usage contains token usage statistics for this request. Embeddings consume prompt tokens
// based on the length of input text.
Usage Usage `json:"usage"`
}
EmbeddingResponse represents a response from the embeddings API. This contains the generated embedding vectors along with metadata about the request.
type File ¶
type File struct {
// ID is a unique identifier for the file, used to reference it in other API calls.
ID string `json:"id"`
// Object is the object type, typically "file".
Object string `json:"object"`
// Bytes is the size of the file in bytes.
Bytes int `json:"bytes"`
// CreatedAt is the timestamp when the file was uploaded.
CreatedAt time.Time `json:"created_at"`
// Filename is the original name of the uploaded file.
Filename string `json:"filename"`
// Purpose is the intended purpose of the file (e.g., "fine-tune", "batch").
// This determines how the file can be used.
Purpose string `json:"purpose"`
// Source contains optional information about the source or origin of the file.
Source string `json:"source,omitempty"`
}
File represents a file that has been uploaded to the Mistral API. Files can be used for various purposes such as fine-tuning models or batch processing.
type FileList ¶
type FileList struct {
// Object is the object type, typically "list".
Object string `json:"object"`
// Data is an array of File objects containing details about each uploaded file.
Data []File `json:"data"`
}
FileList represents a paginated list of files returned by the API. This is the response structure when listing uploaded files.
type FilePurpose ¶
type FilePurpose string
FilePurpose represents the intended purpose of a file uploaded to the Mistral API. The purpose determines how the file can be used and which API endpoints accept it.
const ( // FilePurposeFineTune indicates the file contains training data for fine-tuning models. // Fine-tuning files should typically be in JSONL format with training examples. FilePurposeFineTune FilePurpose = "fine-tune" // FilePurposeBatch indicates the file contains batch processing requests. // Batch files allow you to process multiple API requests asynchronously // at a reduced cost compared to real-time API calls. FilePurposeBatch FilePurpose = "batch" )
type FunctionCall ¶
type FunctionCall struct {
// Name is the name of the function to call, matching one of the functions
// defined in the tools parameter of the chat completion request.
Name string `json:"name"`
// Arguments is a JSON-encoded string containing the arguments to pass to the function.
// This should be parsed according to the function's parameter schema.
Arguments string `json:"arguments"`
}
FunctionCall represents the details of a specific function call. This structure contains the function name and its arguments in JSON format, which your application should parse and execute.
type ListFilesParams ¶
type ListFilesParams struct {
// Page is the page number to retrieve (1-indexed). Use this with PageSize for pagination.
// If 0, defaults to the first page.
Page int
// PageSize is the number of files to return per page. If 0, uses the API's default page size.
// Useful for controlling the amount of data returned in a single request.
PageSize int
// Purpose filters files by their purpose. If empty, returns files of all purposes.
// Use this to retrieve only fine-tuning files or only batch files.
Purpose FilePurpose
// Search is a search query to filter files by name. If empty, returns all files
// (subject to other filters). This performs a substring match on filenames.
Search string
}
ListFilesParams represents optional parameters for filtering and paginating file lists. All fields are optional; omit them or use zero values to use defaults.
type Model ¶
type Model struct {
// ID is the unique identifier for the model (e.g., "mistral-large-latest", "mistral-small").
ID string `json:"id"`
// Object is the object type, typically "model".
Object string `json:"object"`
// Created is a Unix timestamp indicating when the model was created or released.
Created int64 `json:"created"`
// OwnedBy is the organization or entity that owns/provides the model (e.g., "mistralai").
OwnedBy string `json:"owned_by"`
// Type is the type or category of model (e.g., "base", "fine-tuned").
Type string `json:"type,omitempty"`
// Capabilities is a list of capabilities the model supports, such as "completion",
// "chat", "embeddings", "function_calling".
Capabilities []string `json:"capabilities,omitempty"`
// Description is a human-readable description of the model and its characteristics.
Description string `json:"description,omitempty"`
// MaxTokens is the maximum number of tokens (input + output) the model can handle
// in a single request.
MaxTokens int `json:"max_tokens,omitempty"`
}
Model represents detailed information about a Mistral AI model. This structure contains metadata about available models, including their capabilities, limitations, and ownership.
type ModelList ¶
type ModelList struct {
// Object is the object type, typically "list".
Object string `json:"object"`
// Data is an array of Model objects containing details about each available model.
Data []Model `json:"data"`
}
ModelList represents a paginated list of models returned by the API. This is the response structure when listing available models.
type Option ¶
type Option func(*Client)
Option is a functional option for configuring the Client. Options allow you to customize client behavior such as the base URL, HTTP client, and request timeout. Pass options to NewClient to configure the client during initialization.
func WithBaseURL ¶
WithBaseURL sets a custom base URL for the Mistral API. Use this option if you need to use a different API endpoint, such as a proxy or a custom deployment of the Mistral API.
Parameters:
- baseURL: The base URL to use (e.g., "https://api.custom-domain.com"). Do not include a trailing slash
Returns:
- An Option that configures the client's base URL
Example:
client := mistral.NewClient(
"your-api-key",
mistral.WithBaseURL("https://api.custom-domain.com"),
)
func WithHTTPClient ¶
WithHTTPClient sets a custom HTTP client for making API requests. Use this option when you need fine-grained control over HTTP behavior, such as custom TLS configuration, transport settings, or connection pooling.
Parameters:
- httpClient: A configured *http.Client to use for all API requests. The client should have appropriate timeout and transport settings
Returns:
- An Option that configures the client's HTTP client
Example:
customHTTPClient := &http.Client{
Timeout: 90 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
},
}
client := mistral.NewClient(
"your-api-key",
mistral.WithHTTPClient(customHTTPClient),
)
func WithTimeout ¶
WithTimeout sets the timeout for all HTTP requests made by the client. This is a convenience option that configures the timeout on the client's HTTP client. The timeout applies to the entire request-response cycle, including connection time, request sending, and response reading.
Parameters:
- timeout: The maximum duration to wait for a request to complete. Choose based on your expected response times. Streaming requests may need longer timeouts
Returns:
- An Option that configures the client's request timeout
Example:
client := mistral.NewClient(
"your-api-key",
mistral.WithTimeout(30 * time.Second),
)
type ResponseFormat ¶
type ResponseFormat struct {
// Type is the format type. Valid values are:
// - "text" - Standard text response (default)
// - "json_object" - Response will be valid JSON. When using this mode,
// you should also instruct the model to produce JSON in your prompt
Type string `json:"type"`
}
ResponseFormat specifies the desired format for the model's response. This controls the structure of the generated output.
type Role ¶
type Role string
Role represents the role of a message sender in a chat conversation. Each message in a chat must have an associated role that indicates who or what generated the message. This is critical for the model to understand the context and generate appropriate responses.
const ( // RoleSystem represents system-level instructions that guide the model's behavior. // System messages typically contain instructions, context, or guidelines that // should influence how the model responds throughout the conversation. RoleSystem Role = "system" // RoleUser represents messages from the end user or human. // These are the questions, prompts, or inputs from the person // interacting with the AI model. RoleUser Role = "user" // RoleAssistant represents messages generated by the AI model. // These are the model's responses to user messages or continuations // of the conversation from the AI's perspective. RoleAssistant Role = "assistant" // RoleTool represents messages from tool executions. // When the model requests a tool/function call, the results of that // call are returned in a message with this role. RoleTool Role = "tool" )
type Tool ¶
type Tool struct {
// Type is the type of tool (currently only "function" is supported).
Type string `json:"type"`
// Function contains the detailed specification of the function, including its name,
// description, and parameter schema.
Function ToolFunctionDetails `json:"function"`
}
Tool represents a tool/function that can be made available to the model. Tools extend the model's capabilities by allowing it to request execution of external functions when needed. You define the available tools upfront, and the model can choose to use them during generation.
type ToolCall ¶
type ToolCall struct {
// ID is a unique identifier for this specific tool call, used to match the call
// with its corresponding result message.
ID string `json:"id"`
// Type is the type of tool being called (typically "function").
Type string `json:"type"`
// Function contains details about the function to call, including its name and arguments.
Function FunctionCall `json:"function"`
}
ToolCall represents a tool/function call request made by the model. When the model determines it needs to use a tool to fulfill a request, it generates one or more ToolCall objects that specify which function to call and with what arguments.
type ToolChoice ¶
type ToolChoice string
ToolChoice represents the strategy for how the model should use the provided tools. This controls whether and when the model should use tool calls in its response.
const ( // ToolChoiceAuto lets the model automatically decide whether to use tools. // The model will use its judgment to determine if a tool call would be helpful // for answering the user's request. This is the default and most flexible option. ToolChoiceAuto ToolChoice = "auto" // ToolChoiceAny forces the model to use at least one of the provided tools. // The model must make at least one tool call in its response, choosing from // the available tools based on the context. ToolChoiceAny ToolChoice = "any" // ToolChoiceNone prevents the model from using any tools. // Even if tools are provided in the request, the model will not make any // tool calls and will respond purely with text generation. ToolChoiceNone ToolChoice = "none" )
type ToolFunctionDetails ¶
type ToolFunctionDetails struct {
// Name is the unique name of the function. This is what the model will reference
// when making a function call.
Name string `json:"name"`
// Description is a clear description of what the function does. The model uses this
// to determine when the function would be helpful. Be specific and detailed to
// improve the model's decision-making.
Description string `json:"description,omitempty"`
// Parameters is a JSON Schema object describing the function's parameters. This should
// follow the JSON Schema specification and define the expected structure, types,
// and constraints for the function's input.
Parameters map[string]interface{} `json:"parameters,omitempty"`
}
ToolFunctionDetails represents the complete specification of a tool function. This structure defines the function's interface so the model can understand when and how to call it.
type UploadFileRequest ¶
type UploadFileRequest struct {
// File is an io.Reader providing the file content to upload. This could be an open file handle,
// bytes.Buffer, or any other type implementing io.Reader.
File io.Reader
// Filename is the name to assign to the uploaded file. This should include the file extension
// (e.g., "training_data.jsonl") to help the API identify the file format.
Filename string
// Purpose is the intended use for this file. This determines which API operations can use
// the file and may affect validation and processing requirements.
Purpose FilePurpose
}
UploadFileRequest represents a request to upload a file to the Mistral API. Files can be used for various purposes such as fine-tuning models or batch processing.
type Usage ¶
type Usage struct {
// PromptTokens is the number of tokens in the input prompt/messages sent to the model.
// This includes all messages in the conversation history.
PromptTokens int `json:"prompt_tokens"`
// CompletionTokens is the number of tokens in the generated response/completion from the model.
CompletionTokens int `json:"completion_tokens"`
// TotalTokens is the sum of PromptTokens and CompletionTokens, representing
// the total tokens used in this API request.
TotalTokens int `json:"total_tokens"`
}
Usage represents token usage statistics for an API request. This information is essential for tracking costs and monitoring usage, as API pricing is typically based on token consumption.