ai

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertMessagesToMaps

func ConvertMessagesToMaps(messages []domain.ChatMessage) []map[string]string

ConvertMessagesToMaps converts domain.ChatMessage slice to OpenAI-compatible format. Used by OpenAI, Groq, and Ollama clients which share the same message format.

func ConvertToolsOpenAIFormat

func ConvertToolsOpenAIFormat(tools []domain.Tool) []map[string]any

ConvertToolsOpenAIFormat converts tools to OpenAI-compatible format. Used by OpenAI, Groq, and Ollama clients which share the same tools format.

func ExpandEnvVar

func ExpandEnvVar(value string) string

ExpandEnvVar expands environment variables in the format ${VAR_NAME}. This is a utility function used by all AI clients.

func FallbackStreamChat

func FallbackStreamChat(ctx context.Context, req *domain.ChatRequest, chatFunc func(context.Context, *domain.ChatRequest) (*domain.ChatResponse, error), callback func(chunk string) error) error

FallbackStreamChat provides a simple streaming implementation that calls Chat and returns the result. Used by clients that don't have native streaming support.

func GetAPIKeyFromEnv

func GetAPIKeyFromEnv(configKey, envVarName string) string

GetAPIKeyFromEnv tries to get API key from config, then falls back to env var.

func GetSchedulingTools

func GetSchedulingTools() []domain.Tool

GetSchedulingTools returns the function calling tools available for AI scheduling.

func GetSmartSchedulingTools

func GetSmartSchedulingTools() []domain.Tool

GetSmartSchedulingTools returns additional tools for advanced AI scheduling features.

Types

type AIScheduler

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

AIScheduler provides AI-powered scheduling functionality.

func NewAIScheduler

func NewAIScheduler(router ports.LLMRouter, nylasClient ports.NylasClient, providerName string) *AIScheduler

NewAIScheduler creates a new AI scheduler.

func (*AIScheduler) Schedule

func (s *AIScheduler) Schedule(ctx context.Context, req *ScheduleRequest) (*ScheduleResponse, error)

Schedule processes a natural language scheduling request and returns suggested options.

type AcceptancePattern

type AcceptancePattern struct {
	TimeSlot    string  `json:"time_slot"`   // e.g., "Monday 9-11 AM"
	AcceptRate  float64 `json:"accept_rate"` // 0-1
	EventCount  int     `json:"event_count"` // Number of events in this slot
	Description string  `json:"description"` // Human-readable explanation
	Confidence  float64 `json:"confidence"`  // 0-1, based on sample size
}

AcceptancePattern represents meeting acceptance rates by time/day.

type ActionItem

type ActionItem struct {
	Subject string `json:"subject"`
	From    string `json:"from"`
	Urgency string `json:"urgency"` // high, medium, low
	Reason  string `json:"reason"`
}

ActionItem represents an email that needs attention.

type AnalysisPeriod

type AnalysisPeriod struct {
	StartDate time.Time `json:"start_date"`
	EndDate   time.Time `json:"end_date"`
	Days      int       `json:"days"`
}

AnalysisPeriod defines the time period analyzed.

type BaseClient

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

BaseClient provides common HTTP client functionality for AI providers.

func NewBaseClient

func NewBaseClient(apiKey, model, baseURL string, timeout time.Duration) *BaseClient

NewBaseClient creates a new base client with common configuration.

func (*BaseClient) DoJSONRequest

func (b *BaseClient) DoJSONRequest(ctx context.Context, method, endpoint string, body any, headers map[string]string) (*http.Response, error)

DoJSONRequest performs an HTTP request with JSON body and returns the response.

func (*BaseClient) DoJSONRequestAndDecode

func (b *BaseClient) DoJSONRequestAndDecode(ctx context.Context, method, endpoint string, body any, headers map[string]string, result any) error

DoJSONRequestAndDecode performs a request and decodes the response in one call.

func (*BaseClient) GetModel

func (b *BaseClient) GetModel(requestModel string) string

GetModel returns the configured model or falls back to the provided default.

func (*BaseClient) IsConfigured

func (b *BaseClient) IsConfigured() bool

IsConfigured returns true if the API key is set.

func (*BaseClient) ReadJSONResponse

func (b *BaseClient) ReadJSONResponse(resp *http.Response, v any) error

ReadJSONResponse reads and unmarshals a JSON response.

type ClaudeClient

type ClaudeClient struct {
	*BaseClient
}

ClaudeClient implements LLMProvider for Anthropic Claude.

func NewClaudeClient

func NewClaudeClient(config *domain.ClaudeConfig) *ClaudeClient

NewClaudeClient creates a new Claude client.

func (*ClaudeClient) Chat

Chat sends a chat completion request.

func (*ClaudeClient) ChatWithTools

func (c *ClaudeClient) ChatWithTools(ctx context.Context, req *domain.ChatRequest, tools []domain.Tool) (*domain.ChatResponse, error)

ChatWithTools sends a chat request with function calling.

func (*ClaudeClient) IsAvailable

func (c *ClaudeClient) IsAvailable(ctx context.Context) bool

IsAvailable checks if Claude API key is configured.

func (*ClaudeClient) Name

func (c *ClaudeClient) Name() string

Name returns the provider name.

func (*ClaudeClient) StreamChat

func (c *ClaudeClient) StreamChat(ctx context.Context, req *domain.ChatRequest, callback func(chunk string) error) error

StreamChat streams chat responses.

type DurationPattern

type DurationPattern struct {
	MeetingType       string `json:"meeting_type"`       // e.g., "1-on-1", "Team standup"
	ScheduledDuration int    `json:"scheduled_duration"` // In minutes
	ActualDuration    int    `json:"actual_duration"`    // In minutes
	Variance          int    `json:"variance"`           // Difference
	EventCount        int    `json:"event_count"`        // Sample size
	Description       string `json:"description"`        // Pattern description
}

DurationPattern represents typical meeting duration patterns.

type EmailAnalyzer

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

EmailAnalyzer analyzes email threads to extract meeting context.

func NewEmailAnalyzer

func NewEmailAnalyzer(nylasClient ports.NylasClient, llmRouter ports.LLMRouter) *EmailAnalyzer

NewEmailAnalyzer creates a new email analyzer.

func (*EmailAnalyzer) AnalyzeInbox

AnalyzeInbox analyzes recent emails and returns a summary.

func (*EmailAnalyzer) AnalyzeThread

func (a *EmailAnalyzer) AnalyzeThread(ctx context.Context, grantID, threadID string, req *domain.EmailAnalysisRequest) (*domain.EmailThreadAnalysis, error)

AnalyzeThread analyzes an email thread and extracts meeting context.

type EmailCategory

type EmailCategory struct {
	Name     string   `json:"name"`
	Count    int      `json:"count"`
	Subjects []string `json:"subjects"`
}

EmailCategory groups emails by type.

type GroqClient

type GroqClient struct {
	*BaseClient
}

GroqClient implements LLMProvider for Groq.

func NewGroqClient

func NewGroqClient(config *domain.GroqConfig) *GroqClient

NewGroqClient creates a new Groq client.

func (*GroqClient) Chat

Chat sends a chat completion request.

func (*GroqClient) ChatWithTools

func (c *GroqClient) ChatWithTools(ctx context.Context, req *domain.ChatRequest, tools []domain.Tool) (*domain.ChatResponse, error)

ChatWithTools sends a chat request with function calling.

func (*GroqClient) IsAvailable

func (c *GroqClient) IsAvailable(ctx context.Context) bool

IsAvailable checks if Groq API key is configured.

func (*GroqClient) Name

func (c *GroqClient) Name() string

Name returns the provider name.

func (*GroqClient) StreamChat

func (c *GroqClient) StreamChat(ctx context.Context, req *domain.ChatRequest, callback func(chunk string) error) error

StreamChat streams chat responses.

type InboxSummaryRequest

type InboxSummaryRequest struct {
	Messages     []domain.Message
	ProviderName string // Optional: specific provider to use
}

InboxSummaryRequest represents a request to summarize recent emails.

type InboxSummaryResponse

type InboxSummaryResponse struct {
	Summary      string          `json:"summary"`
	Categories   []EmailCategory `json:"categories"`
	ActionItems  []ActionItem    `json:"action_items"`
	Highlights   []string        `json:"highlights"`
	ProviderUsed string          `json:"provider_used"`
	TokensUsed   int             `json:"tokens_used"`
}

InboxSummaryResponse represents the AI summary of emails.

type LearnPatternsRequest

type LearnPatternsRequest struct {
	GrantID          string  `json:"grant_id"`
	LookbackDays     int     `json:"lookback_days"`     // How far back to analyze
	MinConfidence    float64 `json:"min_confidence"`    // Minimum confidence threshold
	IncludeRecurring bool    `json:"include_recurring"` // Include recurring events
}

LearnPatternsRequest represents a request to learn patterns.

type OllamaClient

type OllamaClient struct {
	*BaseClient
}

OllamaClient implements LLMProvider for Ollama.

func NewOllamaClient

func NewOllamaClient(config *domain.OllamaConfig) *OllamaClient

NewOllamaClient creates a new Ollama client. Returns nil if config is nil - callers should validate config before calling.

func (*OllamaClient) Chat

Chat sends a chat completion request.

func (*OllamaClient) ChatWithTools

func (c *OllamaClient) ChatWithTools(ctx context.Context, req *domain.ChatRequest, tools []domain.Tool) (*domain.ChatResponse, error)

ChatWithTools sends a chat request with function calling. Note: Ollama's tool support may vary by model.

func (*OllamaClient) IsAvailable

func (c *OllamaClient) IsAvailable(ctx context.Context) bool

IsAvailable checks if Ollama is accessible.

func (*OllamaClient) Name

func (c *OllamaClient) Name() string

Name returns the provider name.

func (*OllamaClient) StreamChat

func (c *OllamaClient) StreamChat(ctx context.Context, req *domain.ChatRequest, callback func(chunk string) error) error

StreamChat streams chat responses.

type OpenAIClient

type OpenAIClient struct {
	*BaseClient
}

OpenAIClient implements LLMProvider for OpenAI.

func NewOpenAIClient

func NewOpenAIClient(config *domain.OpenAIConfig) *OpenAIClient

NewOpenAIClient creates a new OpenAI client.

func (*OpenAIClient) Chat

Chat sends a chat completion request.

func (*OpenAIClient) ChatWithTools

func (c *OpenAIClient) ChatWithTools(ctx context.Context, req *domain.ChatRequest, tools []domain.Tool) (*domain.ChatResponse, error)

ChatWithTools sends a chat request with function calling.

func (*OpenAIClient) IsAvailable

func (c *OpenAIClient) IsAvailable(ctx context.Context) bool

IsAvailable checks if OpenAI API key is configured.

func (*OpenAIClient) Name

func (c *OpenAIClient) Name() string

Name returns the provider name.

func (*OpenAIClient) StreamChat

func (c *OpenAIClient) StreamChat(ctx context.Context, req *domain.ChatRequest, callback func(chunk string) error) error

StreamChat streams chat responses.

type ParticipantTime

type ParticipantTime struct {
	Email     string    `json:"email"`
	Timezone  string    `json:"timezone"`
	LocalTime time.Time `json:"local_time"`
	TimeDesc  string    `json:"time_desc"` // e.g., "9:00 AM - 10:00 AM EST"
	Notes     string    `json:"notes"`     // e.g., "Morning", "End of day"
}

ParticipantTime shows the meeting time from a participant's perspective.

type PatternLearner

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

PatternLearner learns from calendar history to predict scheduling patterns.

func NewPatternLearner

func NewPatternLearner(nylasClient ports.NylasClient, llmRouter ports.LLMRouter) *PatternLearner

NewPatternLearner creates a new pattern learner.

func (*PatternLearner) ExportPatterns

func (p *PatternLearner) ExportPatterns(patterns *SchedulingPatterns) ([]byte, error)

ExportPatterns exports patterns to JSON.

func (*PatternLearner) LearnPatterns

LearnPatterns analyzes calendar history and learns scheduling patterns.

func (*PatternLearner) LoadPatterns

func (p *PatternLearner) LoadPatterns(ctx context.Context, userID string) (*SchedulingPatterns, error)

LoadPatterns loads previously learned patterns (stub for future storage implementation).

func (*PatternLearner) SavePatterns

func (p *PatternLearner) SavePatterns(ctx context.Context, patterns *SchedulingPatterns) error

SavePatterns saves learned patterns (stub for future storage implementation).

type ProductivityInsight

type ProductivityInsight struct {
	InsightType string   `json:"insight_type"` // e.g., "peak_focus", "low_energy"
	TimeSlot    string   `json:"time_slot"`    // e.g., "Tuesday 10 AM - 12 PM"
	Score       int      `json:"score"`        // 0-100
	Description string   `json:"description"`  // Explanation
	BasedOn     []string `json:"based_on"`     // What data this is based on
}

ProductivityInsight represents productivity patterns.

type Router

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

Router implements LLMRouter for routing between multiple LLM providers.

func NewRouter

func NewRouter(config *domain.AIConfig) *Router

NewRouter creates a new LLM router from configuration.

func (*Router) Chat

Chat sends a chat request using the default provider with fallback.

func (*Router) ChatWithProvider

func (r *Router) ChatWithProvider(ctx context.Context, providerName string, req *domain.ChatRequest) (*domain.ChatResponse, error)

ChatWithProvider sends a chat request using a specific provider.

func (*Router) GetProvider

func (r *Router) GetProvider(name string) (ports.LLMProvider, error)

GetProvider returns the specified provider or default if empty.

func (*Router) ListProviders

func (r *Router) ListProviders() []string

ListProviders returns available provider names.

type ScheduleOption

type ScheduleOption struct {
	Rank         int                        `json:"rank"`
	Score        int                        `json:"score"`      // 0-100
	StartTime    time.Time                  `json:"start_time"` // Proposed start time
	EndTime      time.Time                  `json:"end_time"`   // Proposed end time
	Timezone     string                     `json:"timezone"`
	Reasoning    string                     `json:"reasoning"` // AI explanation
	Warnings     []string                   `json:"warnings"`
	Participants map[string]ParticipantTime `json:"participants"` // Participant views
}

ScheduleOption represents a suggested meeting time option.

type ScheduleRequest

type ScheduleRequest struct {
	Query        string // Natural language request
	GrantID      string // User's grant ID
	UserTimezone string // User's timezone
	MaxOptions   int    // Maximum number of options to return
}

ScheduleRequest represents a natural language scheduling request.

type ScheduleResponse

type ScheduleResponse struct {
	Options      []ScheduleOption `json:"options"`
	Analysis     string           `json:"analysis"`      // AI's overall analysis
	ProviderUsed string           `json:"provider_used"` // Which LLM was used
	TokensUsed   int              `json:"tokens_used"`
}

ScheduleResponse contains AI-suggested meeting options.

type SchedulingPatterns

type SchedulingPatterns struct {
	UserID               string                `json:"user_id"`
	AnalysisPeriod       AnalysisPeriod        `json:"analysis_period"`
	AcceptancePatterns   []AcceptancePattern   `json:"acceptance_patterns"`
	DurationPatterns     []DurationPattern     `json:"duration_patterns"`
	TimezonePatterns     []TimezonePattern     `json:"timezone_patterns"`
	ProductivityInsights []ProductivityInsight `json:"productivity_insights"`
	Recommendations      []string              `json:"recommendations"`
	TotalEventsAnalyzed  int                   `json:"total_events_analyzed"`
	GeneratedAt          time.Time             `json:"generated_at"`
}

SchedulingPatterns represents discovered patterns from calendar history.

type TimezonePattern

type TimezonePattern struct {
	Timezone      string  `json:"timezone"`       // e.g., "America/New_York"
	EventCount    int     `json:"event_count"`    // Number of events
	Percentage    float64 `json:"percentage"`     // % of total events
	PreferredTime string  `json:"preferred_time"` // e.g., "2-4 PM PST"
	Description   string  `json:"description"`    // Pattern description
}

TimezonePattern represents timezone preferences.

Jump to

Keyboard shortcuts

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