Documentation
¶
Overview ¶
assistants.go
File: pkg/aiyou/audio.go
Package aiyou provides authentication functionalities for the AI.YOU API.
Package aiyou provides a client for interacting with the AI.YOU API from Cloud Temple.
Copyright (C) 2024 Cloud Temple ¶
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Copyright (C) 2024 Cloud Temple ¶
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
File: pkg/aiyou/conversation.go
File: pkg/aiyou/models.go
File: pkg/aiyou/threads.go
Package aiyou defines types used across the AI.YOU API client.
Index ¶
- Variables
- func MaskSensitiveInfo(input string) string
- func NewDefaultLogger(w io.Writer) *defaultLogger
- func SafeLog(logger Logger) func(level LogLevel, format string, args ...interface{})
- type APIError
- type Assistant
- type AssistantsResponse
- type AudioTranscriptionRequest
- type AudioTranscriptionResponse
- type AuthenticationError
- type Authenticator
- type BearerAuthenticator
- type ChatCompletionRequest
- type ChatCompletionResponse
- type Choice
- type Client
- func (c *Client) AuthenticatedRequest(ctx context.Context, method, path string, body io.Reader) (*http.Response, error)
- func (c *Client) ChatCompletion(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, error)
- func (c *Client) ChatCompletionStream(ctx context.Context, req ChatCompletionRequest) (*StreamReader, error)
- func (c *Client) CreateChatCompletion(ctx context.Context, messages []Message, assistantID string) (*ChatCompletionResponse, error)
- func (c *Client) CreateChatCompletionStream(ctx context.Context, messages []Message, assistantID string) (*StreamReader, error)
- func (c *Client) CreateModel(ctx context.Context, req ModelRequest) (*ModelResponse, error)
- func (c *Client) DeleteThread(ctx context.Context, threadID string) error
- func (c *Client) GetConversation(ctx context.Context, threadID string) (*ConversationThread, error)
- func (c *Client) GetModels(ctx context.Context) (*ModelsResponse, error)
- func (c *Client) GetUserAssistants(ctx context.Context) (*AssistantsResponse, error)
- func (c *Client) GetUserThreads(ctx context.Context, params *UserThreadsParams) (*UserThreadsOutput, error)
- func (c *Client) SaveConversation(ctx context.Context, req SaveConversationRequest) (*SaveConversationResponse, error)
- func (c *Client) SetBaseURL(url string)
- func (c *Client) SetBearerToken(token string) error
- func (c *Client) SetLogger(logger Logger)
- func (c *Client) TranscribeAudioFile(ctx context.Context, filePath string, opts *AudioTranscriptionRequest) (*AudioTranscriptionResponse, error)
- type ClientOption
- func WithBaseURL(url string) ClientOption
- func WithBearerToken(token string) ClientOption
- func WithEmailPassword(email, password string) ClientOption
- func WithLogger(logger Logger) ClientOption
- func WithRateLimiter(config RateLimiterConfig) ClientOption
- func WithRetry(maxRetries int, initialDelay time.Duration) ClientOption
- type Config
- type ContentPart
- type ConversationThread
- type Delta
- type JWTAuthenticator
- type LogLevel
- type Logger
- type LoginRequest
- type LoginResponse
- type Message
- type MessageBuilder
- type Model
- type ModelProperties
- type ModelRequest
- type ModelResponse
- type ModelsResponse
- type NetworkError
- type RateLimitError
- type RateLimiter
- type RateLimiterConfig
- type SaveConversationRequest
- type SaveConversationResponse
- type StreamOptions
- type StreamReader
- type SupportedAudioFormat
- type ThreadFilter
- type ThreadHistory
- type Usage
- type User
- type UserThreadsOutput
- type UserThreadsParams
Constants ¶
This section is empty.
Variables ¶
var SupportedFormats = []SupportedAudioFormat{ {Extension: ".mp3", MimeTypes: []string{"audio/mpeg"}, MaxSize: 25 * 1024 * 1024}, {Extension: ".wav", MimeTypes: []string{"audio/wav", "audio/x-wav"}, MaxSize: 25 * 1024 * 1024}, {Extension: ".m4a", MimeTypes: []string{"audio/mp4", "audio/x-m4a"}, MaxSize: 25 * 1024 * 1024}, }
Formats audio supportés
Functions ¶
func MaskSensitiveInfo ¶
MaskSensitiveInfo masks sensitive information in the given string. It replaces email addresses, JWT tokens, and password fields with redacted placeholders.
func NewDefaultLogger ¶
NewDefaultLogger creates a new instance of defaultLogger with the specified output writer, prefix, and flags. It sets the initial log level to INFO.
Types ¶
type APIError ¶
APIError représente une erreur retournée par l'API AI.YOU. Il contient le code de statut HTTP et le message d'erreur.
type Assistant ¶
type Assistant struct {
ID string `json:"id"`
AssistantID string `json:"assistantId"`
Name string `json:"name"`
ThreadHistories []ThreadHistory `json:"threadHistories"`
Image string `json:"image"`
Model string `json:"model"`
ModelAi string `json:"modelAi"`
Instructions string `json:"instructions"`
}
Assistant represents an AI assistant.
type AssistantsResponse ¶
type AssistantsResponse struct {
Context string `json:"@context"`
ID string `json:"@id"`
Type string `json:"@type"`
TotalItems int `json:"hydra:totalItems"`
Members []Assistant `json:"hydra:member"`
}
AssistantsResponse represents the response from the assistants endpoint.
type AudioTranscriptionRequest ¶
type AudioTranscriptionRequest struct {
FileName string `json:"fileName"` // Nom du fichier audio
Language string `json:"language,omitempty"` // Code langue ISO (ex: "fr", "en")
Format string `json:"format,omitempty"` // Format de sortie souhaité
}
AudioTranscriptionRequest represents an audio transcription request.
type AudioTranscriptionResponse ¶
type AudioTranscriptionResponse struct {
Transcription string `json:"transcription"` // Texte transcrit
}
AudioTranscriptionResponse represents an audio transcription response.
type AuthenticationError ¶
type AuthenticationError struct {
Message string
}
AuthenticationError représente une erreur d'authentification
func (*AuthenticationError) Error ¶
func (e *AuthenticationError) Error() string
type Authenticator ¶
Authenticator manages authentication for API requests.
type BearerAuthenticator ¶ added in v1.2.0
type BearerAuthenticator struct {
// contains filtered or unexported fields
}
BearerAuthenticator implements the Authenticator interface for direct bearer token authentication without requiring email/password credentials.
func NewBearerAuthenticator ¶ added in v1.2.0
func NewBearerAuthenticator(token string, logger Logger) *BearerAuthenticator
NewBearerAuthenticator creates a new instance of BearerAuthenticator for direct token authentication.
func (*BearerAuthenticator) Authenticate ¶ added in v1.2.0
func (a *BearerAuthenticator) Authenticate(ctx context.Context) error
Authenticate for BearerAuthenticator validates the token existence and returns immediately as no API call is needed.
func (*BearerAuthenticator) SetLogger ¶ added in v1.2.0
func (a *BearerAuthenticator) SetLogger(logger Logger)
SetLogger sets a custom logger for the Bearer authenticator
func (*BearerAuthenticator) SetToken ¶ added in v1.2.0
func (a *BearerAuthenticator) SetToken(token string)
SetToken updates the bearer token
func (*BearerAuthenticator) Token ¶ added in v1.2.0
func (a *BearerAuthenticator) Token() string
Token returns the bearer token
type ChatCompletionRequest ¶
type ChatCompletionRequest struct {
Messages []Message `json:"messages"` // Liste des messages de la conversation
AssistantID string `json:"assistantId"` // ID de l'assistant à utiliser
Temperature float64 `json:"temperature"` // Contrôle de la créativité (1-10)
TopP float64 `json:"top_p"` // Contrôle de la diversité des réponses
Stream bool `json:"stream"` // Activer le mode streaming
PromptSystem string `json:"promptSystem,omitempty"` // Message système personnalisé
Form string `json:"form,omitempty"` // Format de sortie
Stop []string `json:"stop,omitempty"` // Séquences d'arrêt
ThreadId string `json:"threadId,omitempty"` // ID du thread de conversation
MaxTokens *int `json:"max_tokens,omitempty"` // Nombre maximum de tokens
}
ChatCompletionRequest represents a request to the chat completions endpoint.
type ChatCompletionResponse ¶
type ChatCompletionResponse struct {
ID string `json:"id"` // Identifiant unique de la réponse
Object string `json:"object"` // Type d'objet retourné
Created int64 `json:"created"` // Timestamp de création
Model string `json:"model"` // Modèle utilisé
Choices []Choice `json:"choices"` // Liste des choix de réponse
Usage *Usage `json:"usage,omitempty"` // Statistiques d'utilisation
}
ChatCompletionResponse represents the response from the chat completions endpoint.
type Choice ¶
type Choice struct {
Index int `json:"index"` // Index du choix
Message Message `json:"message,omitempty"` // Message pour mode non-streaming
Delta *Delta `json:"delta,omitempty"` // Delta pour mode streaming
FinishReason string `json:"finish_reason,omitempty"` // Raison de fin de génération
}
Choice represents a single completion choice in the response.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a client for the AI.YOU API.
func NewClient ¶
func NewClient(options ...ClientOption) (*Client, error)
NewClient creates a new instance of Client with the given options. At least one authentication method (email/password or bearer token) must be provided.
func (*Client) AuthenticatedRequest ¶
func (c *Client) AuthenticatedRequest(ctx context.Context, method, path string, body io.Reader) (*http.Response, error)
AuthenticatedRequest performs an authenticated request to the API.
func (*Client) ChatCompletion ¶
func (c *Client) ChatCompletion(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, error)
ChatCompletion attempts non-streaming first and falls back to aggregated streaming if needed
func (*Client) ChatCompletionStream ¶
func (c *Client) ChatCompletionStream(ctx context.Context, req ChatCompletionRequest) (*StreamReader, error)
ChatCompletionStream sends a streaming chat completion request
func (*Client) CreateChatCompletion ¶
func (c *Client) CreateChatCompletion(ctx context.Context, messages []Message, assistantID string) (*ChatCompletionResponse, error)
CreateChatCompletion is a helper method that wraps ChatCompletion
func (*Client) CreateChatCompletionStream ¶
func (c *Client) CreateChatCompletionStream(ctx context.Context, messages []Message, assistantID string) (*StreamReader, error)
CreateChatCompletionStream is a helper method that wraps ChatCompletionStream
func (*Client) CreateModel ¶
func (c *Client) CreateModel(ctx context.Context, req ModelRequest) (*ModelResponse, error)
CreateModel crée un nouveau modèle dans le système AI.YOU
func (*Client) DeleteThread ¶
DeleteThread supprime un thread spécifique
func (*Client) GetConversation ¶
GetConversation récupère une conversation spécifique par son ID
func (*Client) GetModels ¶
func (c *Client) GetModels(ctx context.Context) (*ModelsResponse, error)
GetModels récupère la liste des modèles disponibles
func (*Client) GetUserAssistants ¶
func (c *Client) GetUserAssistants(ctx context.Context) (*AssistantsResponse, error)
GetUserAssistants récupère la liste des assistants disponibles pour l'utilisateur
func (*Client) GetUserThreads ¶
func (c *Client) GetUserThreads(ctx context.Context, params *UserThreadsParams) (*UserThreadsOutput, error)
GetUserThreads récupère la liste des threads de l'utilisateur avec pagination et filtrage
func (*Client) SaveConversation ¶
func (c *Client) SaveConversation(ctx context.Context, req SaveConversationRequest) (*SaveConversationResponse, error)
SaveConversation sauvegarde une conversation dans le système
func (*Client) SetBaseURL ¶
SetBaseURL sets the base URL for API requests
func (*Client) SetBearerToken ¶ added in v1.2.0
SetBearerToken updates the bearer token if using bearer token authentication
func (*Client) TranscribeAudioFile ¶
func (c *Client) TranscribeAudioFile(ctx context.Context, filePath string, opts *AudioTranscriptionRequest) (*AudioTranscriptionResponse, error)
TranscribeAudioFile transcrit un fichier audio en texte
type ClientOption ¶
ClientOption is a function type to modify Client.
func WithBaseURL ¶
func WithBaseURL(url string) ClientOption
WithBaseURL sets the base URL for API requests.
func WithBearerToken ¶ added in v1.2.0
func WithBearerToken(token string) ClientOption
WithBearerToken configures the client to use bearer token authentication
func WithEmailPassword ¶ added in v1.2.0
func WithEmailPassword(email, password string) ClientOption
WithEmailPassword configures the client to use email/password authentication
func WithLogger ¶
func WithLogger(logger Logger) ClientOption
WithLogger sets a custom logger for the client.
func WithRateLimiter ¶
func WithRateLimiter(config RateLimiterConfig) ClientOption
WithRateLimiter configures the rate limiter for the client
type ContentPart ¶
type ContentPart struct {
Type string `json:"type"` // Type de contenu (text, image, etc.)
Text string `json:"text"` // Texte du contenu
}
ContentPart represents a part of the message content.
type ConversationThread ¶
type ConversationThread struct {
ID string `json:"id"`
ThreadIdParam int `json:"threadIdParam"`
Content string `json:"content"`
AssistantContentJson string `json:"assistantContentJson"`
AssistantName string `json:"assistantName"`
AssistantModel *string `json:"assistantModel"`
AssistantId int `json:"assistantId"`
AssistantIdOpenAi string `json:"assistantIdOpenAi"`
FirstMessage string `json:"firstMessage"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
IsNewAppThread bool `json:"isNewAppThread"`
}
ConversationThread represents a conversation thread.
type Delta ¶ added in v1.0.0
type Delta struct {
Role string `json:"role,omitempty"` // Rôle du message
Content string `json:"content,omitempty"` // Contenu du message
}
Delta represents a streaming response delta.
type JWTAuthenticator ¶
type JWTAuthenticator struct {
// contains filtered or unexported fields
}
JWTAuthenticator implements the Authenticator interface for JWT-based authentication using email and password credentials.
func NewJWTAuthenticator ¶
func NewJWTAuthenticator(email, password, baseURL string, client *http.Client, logger Logger) *JWTAuthenticator
NewJWTAuthenticator creates a new instance of JWTAuthenticator for email/password authentication.
func (*JWTAuthenticator) Authenticate ¶
func (a *JWTAuthenticator) Authenticate(ctx context.Context) error
Authenticate performs the authentication process and obtains a JWT token for email/password authentication.
func (*JWTAuthenticator) SetLogger ¶
func (a *JWTAuthenticator) SetLogger(logger Logger)
SetLogger sets a custom logger for the JWT authenticator
func (*JWTAuthenticator) Token ¶
func (a *JWTAuthenticator) Token() string
Token returns the current JWT token
type Logger ¶
type Logger interface {
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Warnf(format string, args ...interface{})
Errorf(format string, args ...interface{})
SetLevel(level LogLevel)
}
Logger interface extends the standard log.Logger interface with additional methods for different log levels and the ability to set the logging level.
type LoginRequest ¶
LoginRequest represents the login request payload.
type LoginResponse ¶
type LoginResponse struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
User User `json:"user"`
}
LoginResponse represents the login response from the API.
type Message ¶
type Message struct {
Role string `json:"role"` // Rôle du message (user, assistant, system)
Content []ContentPart `json:"content"` // Contenu du message
}
Message represents a single message in the conversation.
func NewImageMessage ¶
NewImageMessage creates a new Message with a single image content part.
func NewTextMessage ¶
NewTextMessage creates a new Message with a single text content part.
type MessageBuilder ¶
type MessageBuilder struct {
// contains filtered or unexported fields
}
MessageBuilder helps construct complex messages with multiple content types.
func NewMessageBuilder ¶
func NewMessageBuilder(role string, logger Logger) *MessageBuilder
NewMessageBuilder creates a new MessageBuilder with the specified role.
func (*MessageBuilder) AddImage ¶
func (mb *MessageBuilder) AddImage(imageURL string) *MessageBuilder
AddImage adds an image content part to the message.
func (*MessageBuilder) AddText ¶
func (mb *MessageBuilder) AddText(text string) *MessageBuilder
AddText adds a text content part to the message.
func (*MessageBuilder) Build ¶
func (mb *MessageBuilder) Build() Message
Build returns the constructed Message.
type Model ¶
type Model struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Version string `json:"version"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Properties ModelProperties `json:"properties"`
}
Model represents an AI model in the system.
type ModelProperties ¶
type ModelProperties struct {
MaxTokens int `json:"maxTokens"`
Temperature float64 `json:"temperature"`
Provider string `json:"provider"`
Capabilities []string `json:"capabilities"`
}
ModelProperties represents the properties of an AI model.
type ModelRequest ¶
type ModelRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Properties ModelProperties `json:"properties"`
}
ModelRequest represents a request to create a new model.
type ModelResponse ¶
type ModelResponse struct {
Model Model `json:"model"`
}
ModelResponse represents the response when creating or retrieving a model.
type ModelsResponse ¶
ModelsResponse represents the response when retrieving multiple models.
type NetworkError ¶
type NetworkError struct {
Err error
}
NetworkError représente une erreur de réseau survenue lors d'une requête.
func (*NetworkError) Error ¶
func (e *NetworkError) Error() string
type RateLimitError ¶
type RateLimitError struct {
RetryAfter int // en secondes
IsClientSide bool // pour distinguer entre le rate limiting côté client et serveur
}
RateLimitError indique que la limite de taux a été atteinte. RetryAfter indique le nombre de secondes à attendre avant de réessayer.
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter contrôle le taux de requêtes
func NewRateLimiter ¶
func NewRateLimiter(config RateLimiterConfig, logger Logger) *RateLimiter
NewRateLimiter crée un nouveau rate limiter
func (*RateLimiter) GetWaitTime ¶
func (r *RateLimiter) GetWaitTime() time.Duration
type RateLimiterConfig ¶
RateLimiterConfig contient les options de configuration
type SaveConversationRequest ¶
type SaveConversationRequest struct {
AssistantID string `json:"assistantId"`
Conversation string `json:"conversation"`
ThreadID string `json:"threadId,omitempty"`
FirstMessage string `json:"firstMessage"`
ContentJson string `json:"contentJson"`
ModelName string `json:"modelName"`
IsNewAppThread bool `json:"isNewAppThread"`
}
SaveConversationRequest represents a request to save a conversation.
type SaveConversationResponse ¶
type SaveConversationResponse struct {
ID string `json:"id"`
Object string `json:"object"`
CreatedAt int64 `json:"createdAt"`
}
SaveConversationResponse represents the response after saving a conversation.
type StreamOptions ¶ added in v1.0.0
type StreamOptions struct {
IncludeUsage bool `json:"include_usage"`
ContinuousUsageStats bool `json:"continuous_usage_stats"`
}
StreamOptions represents options for streaming responses.
type StreamReader ¶
type StreamReader struct {
// contains filtered or unexported fields
}
StreamReader helps read and process the streaming response
func NewStreamReader ¶
func NewStreamReader(r io.ReadCloser, logger Logger) *StreamReader
NewStreamReader creates a new StreamReader
func (*StreamReader) Close ¶
func (sr *StreamReader) Close() error
Close closes the underlying reader
func (*StreamReader) ReadChunk ¶
func (sr *StreamReader) ReadChunk() (*ChatCompletionResponse, error)
ReadChunk reads and processes a single chunk from the stream Dans pkg/aiyou/chat.go
func (*StreamReader) SetLogger ¶
func (sr *StreamReader) SetLogger(logger Logger)
SetLogger sets a custom logger for the StreamReader
type SupportedAudioFormat ¶
type SupportedAudioFormat struct {
Extension string `json:"extension"` // Extension du fichier (.mp3, .wav, etc.)
MimeTypes []string `json:"mimeTypes"` // Types MIME supportés
MaxSize int64 `json:"maxSize"` // Taille maximale en bytes
}
SupportedAudioFormat represents a supported audio format.
type ThreadFilter ¶
type ThreadFilter struct {
AssistantID string `json:"assistantId,omitempty"`
StartDate time.Time `json:"startDate,omitempty"`
EndDate time.Time `json:"endDate,omitempty"`
Page int `json:"page,omitempty"`
Limit int `json:"limit,omitempty"`
}
ThreadFilter represents filter options for retrieving threads.
type ThreadHistory ¶ added in v1.0.0
type ThreadHistory struct {
ThreadID string `json:"threadId"`
FirstMessage string `json:"firstMessage"`
}
ThreadHistory represents the history of a conversation thread.
type Usage ¶
type Usage struct {
PromptTokens int `json:"prompt_tokens"` // Nombre de tokens dans la requête
CompletionTokens int `json:"completion_tokens"` // Nombre de tokens dans la réponse
TotalTokens int `json:"total_tokens"` // Nombre total de tokens
}
Usage represents token usage information.
type User ¶
type User struct {
ID int `json:"id"` // Changé de string à int
Email string `json:"email"`
ProfileImage string `json:"profileImage"`
FirstName string `json:"firstName"`
}
User represents a user in the AI.YOU system.
type UserThreadsOutput ¶ added in v1.0.0
type UserThreadsOutput struct {
Threads []ConversationThread `json:"threads"`
TotalItems int `json:"totalItems"`
ItemsPerPage int `json:"itemsPerPage"`
CurrentPage int `json:"currentPage"`
}
UserThreadsOutput represents the response containing user threads.
type UserThreadsParams ¶ added in v1.0.0
type UserThreadsParams struct {
Page int `json:"page,omitempty"`
ItemsPerPage int `json:"itemsPerPage,omitempty"`
Search string `json:"search,omitempty"`
}
UserThreadsParams represents the parameters for retrieving user threads.