Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

feat(ai): Add streaming support and notable models to AI providers

rcourtman4fe3d7df775c
diff --git a/internal/ai/providers/anthropic.go b/internal/ai/providers/anthropic.go
index ef2e84352e..f0974c24b6 100644
--- a/internal/ai/providers/anthropic.go
+++ b/internal/ai/providers/anthropic.go
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/url"
+ "strings"
"time"
"github.com/rs/zerolog/log"
@@ -405,12 +406,326 @@ func (c *AnthropicClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
}
models := make([]ModelInfo, 0, len(result.Data))
+ cache := GetNotableCache()
+ notableCount := 0
for _, m := range result.Data {
+ isNotable := cache.IsNotable("anthropic", m.ID, 0)
+ if isNotable {
+ notableCount++
+ }
models = append(models, ModelInfo{
- ID: m.ID,
- Name: m.DisplayName,
+ ID: m.ID,
+ Name: m.DisplayName,
+ Notable: isNotable,
})
}
+ log.Info().Int("total", len(models)).Int("notable", notableCount).Msg("Anthropic ListModels returned")
+
+ // Log model IDs for debugging
+ var modelIDs []string
+ for _, m := range models {
+ modelIDs = append(modelIDs, m.ID)
+ }
+ log.Debug().Strs("models", modelIDs).Msg("Anthropic models")
+
return models, nil
}
+
+// SupportsThinking returns true if the model supports extended thinking
+func (c *AnthropicClient) SupportsThinking(model string) bool {
+ // Claude 3.5+ models with "thinking" capability
+ // Currently no public Claude models have extended thinking like DeepSeek
+ return false
+}
+
+// anthropicStreamRequest is the request body for streaming API calls
+type anthropicStreamRequest struct {
+ Model string `json:"model"`
+ Messages []anthropicMessage `json:"messages"`
+ MaxTokens int `json:"max_tokens"`
+ System string `json:"system,omitempty"`
+ Temperature float64 `json:"temperature,omitempty"`
+ Tools []anthropicTool `json:"tools,omitempty"`
+ Stream bool `json:"stream"`
+}
+
+// anthropicStreamEvent represents a streaming event from the Anthropic API
+type anthropicStreamEvent struct {
+ Type string `json:"type"`
+ Index int `json:"index,omitempty"`
+ ContentBlock *anthropicContent `json:"content_block,omitempty"`
+ Delta *anthropicDelta `json:"delta,omitempty"`
+ Message *anthropicResponse `json:"message,omitempty"`
+ Usage *anthropicUsage `json:"usage,omitempty"`
+}
+
+type anthropicDelta struct {
+ Type string `json:"type,omitempty"`
+ Text string `json:"text,omitempty"`
+ PartialJSON string `json:"partial_json,omitempty"`
+ StopReason string `json:"stop_reason,omitempty"`
+}
+
+// ChatStream sends a chat request and streams the response via callback
+func (c *AnthropicClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error {
+ // Convert messages to Anthropic format (same as Chat)
+ messages := make([]anthropicMessage, 0, len(req.Messages))
+ for _, m := range req.Messages {
+ if m.Role == "system" {
+ continue
+ }
+
+ if m.ToolResult != nil {
+ contentJSON, _ := json.Marshal(m.ToolResult.Content)
+ messages = append(messages, anthropicMessage{
+ Role: "user",
+ Content: []anthropicContent{
+ {
+ Type: "tool_result",
+ ToolUseID: m.ToolResult.ToolUseID,
+ Content: contentJSON,
+ IsError: m.ToolResult.IsError,
+ },
+ },
+ })
+ continue
+ }
+
+ if m.Role == "assistant" && len(m.ToolCalls) > 0 {
+ contentBlocks := make([]anthropicContent, 0)
+ if m.Content != "" {
+ contentBlocks = append(contentBlocks, anthropicContent{
+ Type: "text",
+ Text: m.Content,
+ })
+ }
+ for _, tc := range m.ToolCalls {
+ contentBlocks = append(contentBlocks, anthropicContent{
+ Type: "tool_use",
+ ID: tc.ID,
+ Name: tc.Name,
+ Input: tc.Input,
+ })
+ }
+ messages = append(messages, anthropicMessage{
+ Role: "assistant",
+ Content: contentBlocks,
+ })
+ continue
+ }
+
+ messages = append(messages, anthropicMessage{
+ Role: m.Role,
+ Content: m.Content,
+ })
+ }
+
+ model := req.Model
+ if len(model) > 10 && model[:10] == "anthropic:" {
+ model = model[10:]
+ }
+ if model == "" {
+ model = c.model
+ }
+
+ maxTokens := req.MaxTokens
+ if maxTokens == 0 {
+ maxTokens = 4096
+ }
+
+ anthropicReq := anthropicStreamRequest{
+ Model: model,
+ Messages: messages,
+ MaxTokens: maxTokens,
+ System: req.System,
+ Stream: true,
+ }
+
+ if req.Temperature > 0 {
+ anthropicReq.Temperature = req.Temperature
+ }
+
+ if len(req.Tools) > 0 {
+ anthropicReq.Tools = make([]anthropicTool, len(req.Tools))
+ for i, t := range req.Tools {
+ if t.Type == "web_search_20250305" {
+ anthropicReq.Tools[i] = anthropicTool{
+ Type: t.Type,
+ Name: t.Name,
+ MaxUses: t.MaxUses,
+ }
+ } else {
+ anthropicReq.Tools[i] = anthropicTool{
+ Name: t.Name,
+ Description: t.Description,
+ InputSchema: t.InputSchema,
+ }
+ }
+ }
+ }
+
+ body, err := json.Marshal(anthropicReq)
+ if err != nil {
+ return fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL, bytes.NewReader(body))
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("x-api-key", c.apiKey)
+ httpReq.Header.Set("anthropic-version", anthropicAPIVersion)
+ httpReq.Header.Set("Accept", "text/event-stream")
+
+ resp, err := c.client.Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ respBody, _ := io.ReadAll(resp.Body)
+ var errResp anthropicError
+ if err := json.Unmarshal(respBody, &errResp); err == nil && errResp.Error.Message != "" {
+ return fmt.Errorf("API error (%d): %s", resp.StatusCode, errResp.Error.Message)
+ }
+ return fmt.Errorf("API error (%d): %s", resp.StatusCode, string(respBody))
+ }
+
+ // Parse SSE stream
+ reader := resp.Body
+ buf := make([]byte, 4096)
+ var eventData string
+ var toolCalls []ToolCall
+ var currentToolID string
+ var currentToolName string
+ var currentToolInput strings.Builder
+ var inputTokens, outputTokens int
+
+ for {
+ n, err := reader.Read(buf)
+ if err != nil {
+ if err == io.EOF {
+ break
+ }
+ return fmt.Errorf("stream read error: %w", err)
+ }
+
+ data := string(buf[:n])
+ lines := strings.Split(data, "\n")
+
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+
+ if strings.HasPrefix(line, "event:") {
+ // New event type, reset data
+ eventData = ""
+ continue
+ }
+
+ if strings.HasPrefix(line, "data:") {
+ eventData = strings.TrimPrefix(line, "data:")
+ eventData = strings.TrimSpace(eventData)
+
+ if eventData == "" {
+ continue
+ }
+
+ var event anthropicStreamEvent
+ if err := json.Unmarshal([]byte(eventData), &event); err != nil {
+ log.Debug().Err(err).Str("data", eventData).Msg("Failed to parse stream event")
+ continue
+ }
+
+ switch event.Type {
+ case "message_start":
+ if event.Message != nil && event.Message.Usage.InputTokens > 0 {
+ inputTokens = event.Message.Usage.InputTokens
+ }
+
+ case "content_block_start":
+ if event.ContentBlock != nil {
+ switch event.ContentBlock.Type {
+ case "tool_use":
+ currentToolID = event.ContentBlock.ID
+ currentToolName = event.ContentBlock.Name
+ currentToolInput.Reset()
+ callback(StreamEvent{
+ Type: "tool_start",
+ Data: ToolStartEvent{
+ ID: currentToolID,
+ Name: currentToolName,
+ },
+ })
+ }
+ }
+
+ case "content_block_delta":
+ if event.Delta != nil {
+ switch event.Delta.Type {
+ case "text_delta":
+ if event.Delta.Text != "" {
+ callback(StreamEvent{
+ Type: "content",
+ Data: ContentEvent{Text: event.Delta.Text},
+ })
+ }
+ case "input_json_delta":
+ currentToolInput.WriteString(event.Delta.PartialJSON)
+ }
+ }
+
+ case "content_block_stop":
+ if currentToolID != "" {
+ // Parse the accumulated tool input
+ var input map[string]interface{}
+ if err := json.Unmarshal([]byte(currentToolInput.String()), &input); err != nil {
+ input = map[string]interface{}{"raw": currentToolInput.String()}
+ }
+ toolCalls = append(toolCalls, ToolCall{
+ ID: currentToolID,
+ Name: currentToolName,
+ Input: input,
+ })
+ currentToolID = ""
+ currentToolName = ""
+ }
+
+ case "message_delta":
+ if event.Delta != nil && event.Delta.StopReason != "" {
+ if event.Usage != nil {
+ outputTokens = event.Usage.OutputTokens
+ }
+ }
+
+ case "message_stop":
+ stopReason := "end_turn"
+ if len(toolCalls) > 0 {
+ stopReason = "tool_use"
+ }
+ callback(StreamEvent{
+ Type: "done",
+ Data: DoneEvent{
+ StopReason: stopReason,
+ ToolCalls: toolCalls,
+ InputTokens: inputTokens,
+ OutputTokens: outputTokens,
+ },
+ })
+
+ case "error":
+ callback(StreamEvent{
+ Type: "error",
+ Data: ErrorEvent{Message: "Stream error from Anthropic"},
+ })
+ return fmt.Errorf("stream error from Anthropic")
+ }
+ }
+ }
+ }
+
+ return nil
+}
diff --git a/internal/ai/providers/gemini.go b/internal/ai/providers/gemini.go
index f16b6e39da..7cd3499b7b 100644
--- a/internal/ai/providers/gemini.go
+++ b/internal/ai/providers/gemini.go
@@ -195,6 +195,11 @@ func (c *GeminiClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
continue
}
+ // Skip messages with empty content - Gemini requires at least one of text, functionCall, or functionResponse
+ if m.Content == "" {
+ continue
+ }
+
// Simple text message
contents = append(contents, geminiContent{
Role: role,
@@ -441,6 +446,264 @@ func (c *GeminiClient) TestConnection(ctx context.Context) error {
return err
}
+// SupportsThinking returns true if the model supports extended thinking
+func (c *GeminiClient) SupportsThinking(model string) bool {
+ // Gemini models don't currently expose extended thinking in the streaming API
+ return false
+}
+
+// geminiStreamEvent represents a streaming event from the Gemini API
+type geminiStreamEvent struct {
+ Candidates []geminiCandidate `json:"candidates,omitempty"`
+ UsageMetadata *geminiUsageMetadata `json:"usageMetadata,omitempty"`
+}
+
+// ChatStream sends a chat request and streams the response via callback
+func (c *GeminiClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error {
+ // Convert messages to Gemini format (same as Chat)
+ contents := make([]geminiContent, 0, len(req.Messages))
+ for _, m := range req.Messages {
+ if m.Role == "system" {
+ continue
+ }
+
+ role := m.Role
+ if role == "assistant" {
+ role = "model"
+ }
+
+ if m.ToolResult != nil {
+ contents = append(contents, geminiContent{
+ Role: "user",
+ Parts: []geminiPart{
+ {
+ FunctionResponse: &geminiFunctionResponse{
+ Name: m.ToolResult.ToolUseID,
+ Response: struct {
+ Content string `json:"content"`
+ }{
+ Content: m.ToolResult.Content,
+ },
+ },
+ },
+ },
+ })
+ continue
+ }
+
+ if m.Role == "assistant" && len(m.ToolCalls) > 0 {
+ parts := make([]geminiPart, 0)
+ if m.Content != "" {
+ parts = append(parts, geminiPart{Text: m.Content})
+ }
+ for _, tc := range m.ToolCalls {
+ parts = append(parts, geminiPart{
+ FunctionCall: &geminiFunctionCall{
+ Name: tc.Name,
+ Args: tc.Input,
+ },
+ })
+ }
+ contents = append(contents, geminiContent{
+ Role: "model",
+ Parts: parts,
+ })
+ continue
+ }
+
+ // Skip messages with empty content - Gemini requires at least one of text, functionCall, or functionResponse
+ if m.Content == "" {
+ continue
+ }
+
+ contents = append(contents, geminiContent{
+ Role: role,
+ Parts: []geminiPart{
+ {Text: m.Content},
+ },
+ })
+ }
+
+ model := req.Model
+ if strings.HasPrefix(model, "gemini:") {
+ model = strings.TrimPrefix(model, "gemini:")
+ }
+ if model == "" {
+ model = c.model
+ }
+
+ geminiReq := geminiRequest{
+ Contents: contents,
+ }
+
+ if req.System != "" {
+ geminiReq.SystemInstruction = &geminiContent{
+ Parts: []geminiPart{{Text: req.System}},
+ }
+ }
+
+ geminiReq.GenerationConfig = &geminiGenerationConfig{}
+ if req.MaxTokens > 0 {
+ geminiReq.GenerationConfig.MaxOutputTokens = req.MaxTokens
+ } else {
+ geminiReq.GenerationConfig.MaxOutputTokens = 8192
+ }
+ if req.Temperature > 0 {
+ geminiReq.GenerationConfig.Temperature = req.Temperature
+ }
+
+ if len(req.Tools) > 0 {
+ funcDecls := make([]geminiFunctionDeclaration, 0, len(req.Tools))
+ for _, t := range req.Tools {
+ if t.Type != "" && t.Type != "function" {
+ continue
+ }
+ funcDecls = append(funcDecls, geminiFunctionDeclaration{
+ Name: t.Name,
+ Description: t.Description,
+ Parameters: t.InputSchema,
+ })
+ }
+ if len(funcDecls) > 0 {
+ geminiReq.Tools = []geminiToolDef{{FunctionDeclarations: funcDecls}}
+ }
+ }
+
+ body, err := json.Marshal(geminiReq)
+ if err != nil {
+ return fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ // Use streamGenerateContent endpoint for streaming
+ url := fmt.Sprintf("%s/models/%s:streamGenerateContent?key=%s&alt=sse", c.baseURL, model, c.apiKey)
+
+ httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("Accept", "text/event-stream")
+
+ resp, err := c.client.Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ respBody, _ := io.ReadAll(resp.Body)
+ var errResp geminiError
+ if err := json.Unmarshal(respBody, &errResp); err == nil && errResp.Error.Message != "" {
+ return fmt.Errorf("API error (%d): %s", resp.StatusCode, errResp.Error.Message)
+ }
+ return fmt.Errorf("API error (%d): %s", resp.StatusCode, string(respBody))
+ }
+
+ // Parse SSE stream
+ reader := resp.Body
+ buf := make([]byte, 4096)
+ var pendingData string
+ var toolCalls []ToolCall
+ var inputTokens, outputTokens int
+ var finishReason string
+
+ for {
+ n, err := reader.Read(buf)
+ if err != nil {
+ if err == io.EOF {
+ break
+ }
+ return fmt.Errorf("stream read error: %w", err)
+ }
+
+ pendingData += string(buf[:n])
+ lines := strings.Split(pendingData, "\n")
+
+ // Keep the last incomplete line for next iteration
+ pendingData = lines[len(lines)-1]
+ lines = lines[:len(lines)-1]
+
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+
+ if !strings.HasPrefix(line, "data:") {
+ continue
+ }
+
+ data := strings.TrimPrefix(line, "data:")
+ data = strings.TrimSpace(data)
+
+ if data == "" {
+ continue
+ }
+
+ var event geminiStreamEvent
+ if err := json.Unmarshal([]byte(data), &event); err != nil {
+ log.Debug().Err(err).Str("data", data).Msg("Failed to parse Gemini stream event")
+ continue
+ }
+
+ if event.UsageMetadata != nil {
+ inputTokens = event.UsageMetadata.PromptTokenCount
+ outputTokens = event.UsageMetadata.CandidatesTokenCount
+ }
+
+ for _, candidate := range event.Candidates {
+ if candidate.FinishReason != "" {
+ finishReason = candidate.FinishReason
+ }
+
+ for _, part := range candidate.Content.Parts {
+ if part.Text != "" {
+ callback(StreamEvent{
+ Type: "content",
+ Data: ContentEvent{Text: part.Text},
+ })
+ }
+
+ if part.FunctionCall != nil {
+ toolID := fmt.Sprintf("%s_%d", part.FunctionCall.Name, len(toolCalls))
+ callback(StreamEvent{
+ Type: "tool_start",
+ Data: ToolStartEvent{
+ ID: toolID,
+ Name: part.FunctionCall.Name,
+ Input: part.FunctionCall.Args,
+ },
+ })
+ toolCalls = append(toolCalls, ToolCall{
+ ID: toolID,
+ Name: part.FunctionCall.Name,
+ Input: part.FunctionCall.Args,
+ })
+ }
+ }
+ }
+ }
+ }
+
+ // Send done event
+ stopReason := finishReason
+ if len(toolCalls) > 0 {
+ stopReason = "tool_use"
+ } else if stopReason == "STOP" {
+ stopReason = "end_turn"
+ }
+
+ callback(StreamEvent{
+ Type: "done",
+ Data: DoneEvent{
+ StopReason: stopReason,
+ ToolCalls: toolCalls,
+ InputTokens: inputTokens,
+ OutputTokens: outputTokens,
+ },
+ })
+
+ return nil
+}
+
// ListModels fetches available models from the Gemini API
func (c *GeminiClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
url := fmt.Sprintf("%s/models?key=%s", c.baseURL, c.apiKey)
@@ -475,6 +738,7 @@ func (c *GeminiClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
}
models := make([]ModelInfo, 0, len(result.Models))
+ cache := GetNotableCache()
for _, m := range result.Models {
// Only include models that support generateContent (chat)
supportsChat := false
@@ -524,6 +788,7 @@ func (c *GeminiClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
ID: modelID,
Name: m.DisplayName,
Description: m.Description,
+ Notable: cache.IsNotable("gemini", modelID, 0),
})
}
diff --git a/internal/ai/providers/notable_models.go b/internal/ai/providers/notable_models.go
new file mode 100644
index 0000000000..7a532e5fc4
--- /dev/null
+++ b/internal/ai/providers/notable_models.go
@@ -0,0 +1,326 @@
+// Package providers contains AI provider client implementations
+package providers
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// ModelsDevInfo represents model data from models.dev API
+type ModelsDevInfo struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Family string `json:"family"`
+ ReleaseDate string `json:"release_date"`
+ LastUpdated string `json:"last_updated"`
+ Reasoning bool `json:"reasoning"`
+}
+
+// ModelsDevProvider represents a provider entry from models.dev
+type ModelsDevProvider struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Models map[string]ModelsDevInfo `json:"models"`
+}
+
+// NotableModelsCache caches model metadata from models.dev
+type NotableModelsCache struct {
+ mu sync.RWMutex
+ data map[string]ModelsDevInfo // keyed by "provider:model_id"
+ lastFetched time.Time
+ ttl time.Duration
+ apiURL string
+}
+
+// notableCutoffMonths defines how many months old a model can be to still be "notable"
+const notableCutoffMonths = 3
+
+// cacheDefaultTTL is the default cache time-to-live
+const cacheDefaultTTL = 24 * time.Hour
+
+// modelsDevAPIURL is the public API endpoint
+const modelsDevAPIURL = "https://models.dev/api.json"
+
+var (
+ defaultCache *NotableModelsCache
+ defaultCacheOnce sync.Once
+)
+
+// GetNotableCache returns the singleton NotableModelsCache instance
+func GetNotableCache() *NotableModelsCache {
+ defaultCacheOnce.Do(func() {
+ defaultCache = NewNotableModelsCache(modelsDevAPIURL, cacheDefaultTTL)
+ })
+ return defaultCache
+}
+
+// NewNotableModelsCache creates a new cache with the specified API URL and TTL
+func NewNotableModelsCache(apiURL string, ttl time.Duration) *NotableModelsCache {
+ return &NotableModelsCache{
+ data: make(map[string]ModelsDevInfo),
+ ttl: ttl,
+ apiURL: apiURL,
+ }
+}
+
+// providerMapping maps our internal provider names to models.dev provider IDs
+var providerMapping = map[string][]string{
+ "anthropic": {"anthropic"},
+ "openai": {"openai", "firmware", "github-copilot", "abacus"},
+ "google": {"google", "google-vertex"},
+ "gemini": {"google", "google-vertex"},
+ "xai": {"xai"},
+ "mistral": {"mistral"},
+ "deepseek": {"deepseek"},
+ "cohere": {"cohere"},
+}
+
+// Refresh fetches the latest data from models.dev API
+func (c *NotableModelsCache) Refresh(ctx context.Context) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ // Skip if cache is still fresh
+ if time.Since(c.lastFetched) < c.ttl && len(c.data) > 0 {
+ return nil
+ }
+
+ log.Debug().Str("url", c.apiURL).Msg("Refreshing notable models cache from models.dev")
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.apiURL, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("User-Agent", "Pulse/1.0")
+
+ client := &http.Client{Timeout: 30 * time.Second}
+ resp, err := client.Do(req)
+ if err != nil {
+ log.Warn().Err(err).Msg("Failed to fetch models.dev API, using fallback")
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ log.Warn().Int("status", resp.StatusCode).Msg("models.dev API returned non-200 status")
+ return nil
+ }
+
+ // Parse the response - it's a map of provider ID to provider info
+ var providers map[string]ModelsDevProvider
+ if err := json.NewDecoder(resp.Body).Decode(&providers); err != nil {
+ log.Warn().Err(err).Msg("Failed to decode models.dev API response")
+ return err
+ }
+
+ // Build the lookup map
+ newData := make(map[string]ModelsDevInfo)
+ for providerID, provider := range providers {
+ for modelID, modelInfo := range provider.Models {
+ // Store with provider prefix for lookup
+ key := normalizeKey(providerID, modelID)
+ newData[key] = modelInfo
+
+ // Also store just the model ID for fuzzy matching
+ keyNoProvider := normalizeModelID(modelID)
+ if _, exists := newData[keyNoProvider]; !exists {
+ newData[keyNoProvider] = modelInfo
+ }
+ }
+ }
+
+ c.data = newData
+ c.lastFetched = time.Now()
+ log.Info().Int("models", len(newData)).Msg("Notable models cache refreshed")
+
+ return nil
+}
+
+// IsNotable determines if a model should be marked as notable
+// Priority:
+// 1. Ollama models are always notable (user explicitly pulled them)
+// 2. Check models.dev data for release_date
+// 3. Fall back to createdAt timestamp
+func (c *NotableModelsCache) IsNotable(provider, modelID string, createdAt int64) bool {
+ // Ollama models are always notable - user explicitly pulled them
+ if strings.EqualFold(provider, "ollama") {
+ return true
+ }
+
+ // Try to refresh cache if needed (non-blocking, best effort)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ err := c.Refresh(ctx)
+ if err != nil {
+ log.Debug().Err(err).Str("provider", provider).Str("model", modelID).Msg("Cache refresh failed in IsNotable")
+ }
+
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+
+ // Log cache size for debugging
+ log.Debug().Int("cache_size", len(c.data)).Str("provider", provider).Str("model", modelID).Msg("Checking IsNotable")
+
+ // Try exact match with provider prefix
+ for _, providerID := range getProviderIDs(provider) {
+ key := normalizeKey(providerID, modelID)
+ if info, found := c.data[key]; found {
+ isNotable := isRecentlyReleased(info.ReleaseDate, info.LastUpdated)
+ log.Debug().Str("key", key).Str("release", info.ReleaseDate).Bool("notable", isNotable).Msg("Found model in cache")
+ return isNotable
+ }
+ }
+
+ // Try fuzzy match on just model ID
+ key := normalizeModelID(modelID)
+ if info, found := c.data[key]; found {
+ isNotable := isRecentlyReleased(info.ReleaseDate, info.LastUpdated)
+ log.Debug().Str("key", key).Str("release", info.ReleaseDate).Bool("notable", isNotable).Msg("Found model via fuzzy match")
+ return isNotable
+ }
+
+ // Fallback: Use createdAt timestamp if available
+ if createdAt > 0 {
+ createdTime := time.Unix(createdAt, 0)
+ cutoff := time.Now().AddDate(0, -notableCutoffMonths, 0)
+ return createdTime.After(cutoff)
+ }
+
+ // Check if this model family has a newer release that's notable
+ // This handles Anthropic API returning old-style names like "claude-3-5-haiku-20241022"
+ // when there's a newer "claude-haiku-4-5" in models.dev
+ if aliases := getModelFamilyAliases(modelID); len(aliases) > 0 {
+ for _, alias := range aliases {
+ for _, providerID := range getProviderIDs(provider) {
+ key := normalizeKey(providerID, alias)
+ if info, found := c.data[key]; found {
+ if isRecentlyReleased(info.ReleaseDate, info.LastUpdated) {
+ log.Debug().Str("original", modelID).Str("alias", alias).Str("release", info.ReleaseDate).Msg("Model family has notable newer release")
+ return true
+ }
+ }
+ }
+ }
+ }
+
+ // Default: not notable
+ log.Debug().Str("provider", provider).Str("model", modelID).Msg("Model not found in cache, defaulting to not notable")
+ return false
+}
+
+// getModelFamilyAliases returns alternative model names to check for notable status
+// This maps old-style API names to their newer model.dev equivalents
+func getModelFamilyAliases(modelID string) []string {
+ modelID = strings.ToLower(modelID)
+
+ // Anthropic model family mappings
+ if strings.Contains(modelID, "haiku") {
+ return []string{"claude-haiku-4-5", "claude-3-5-haiku-latest"}
+ }
+ if strings.Contains(modelID, "sonnet") {
+ return []string{"claude-sonnet-4-5", "claude-3-5-sonnet-latest"}
+ }
+ if strings.Contains(modelID, "opus") {
+ return []string{"claude-opus-4-5", "claude-opus-4-1", "claude-opus-4-0"}
+ }
+
+ // OpenAI model family mappings
+ if strings.Contains(modelID, "gpt-4o") {
+ return []string{"gpt-4o", "gpt-4o-2024-11-20"}
+ }
+ if strings.Contains(modelID, "o1") || strings.Contains(modelID, "o3") {
+ return []string{"o1", "o1-pro", "o3-mini"}
+ }
+
+ return nil
+}
+
+// getProviderIDs returns the models.dev provider IDs for our internal provider name
+func getProviderIDs(provider string) []string {
+ provider = strings.ToLower(provider)
+ if ids, found := providerMapping[provider]; found {
+ return ids
+ }
+ return []string{provider}
+}
+
+// normalizeKey creates a normalized lookup key
+func normalizeKey(provider, modelID string) string {
+ return strings.ToLower(provider) + ":" + normalizeModelID(modelID)
+}
+
+// normalizeModelID normalizes a model ID for comparison
+func normalizeModelID(modelID string) string {
+ // Remove common prefixes
+ modelID = strings.ToLower(modelID)
+ modelID = strings.TrimPrefix(modelID, "models/")
+ modelID = strings.TrimPrefix(modelID, "gemini-")
+
+ // Strip date suffixes like -20251022 or -20240620 from model IDs
+ // This helps match "claude-3-5-sonnet-20241022" to "claude-3-5-sonnet"
+ if len(modelID) > 9 {
+ // Check if last 8 chars look like a date (YYYYMMDD)
+ suffix := modelID[len(modelID)-8:]
+ if len(suffix) == 8 {
+ // All digits and starts with 20XX
+ if suffix[0] == '2' && suffix[1] == '0' {
+ allDigits := true
+ for _, c := range suffix {
+ if c < '0' || c > '9' {
+ allDigits = false
+ break
+ }
+ }
+ if allDigits && len(modelID) > 9 && modelID[len(modelID)-9] == '-' {
+ modelID = modelID[:len(modelID)-9]
+ }
+ }
+ }
+ }
+
+ return modelID
+}
+
+// isRecentlyReleased checks if a model was released within the notable cutoff
+func isRecentlyReleased(releaseDate, lastUpdated string) bool {
+ cutoff := time.Now().AddDate(0, -notableCutoffMonths, 0)
+
+ // Try release_date first
+ if releaseDate != "" {
+ if t, err := parseFlexibleDate(releaseDate); err == nil {
+ return t.After(cutoff)
+ }
+ }
+
+ // Fall back to last_updated
+ if lastUpdated != "" {
+ if t, err := parseFlexibleDate(lastUpdated); err == nil {
+ return t.After(cutoff)
+ }
+ }
+
+ return false
+}
+
+// parseFlexibleDate parses dates in various formats used by models.dev
+func parseFlexibleDate(dateStr string) (time.Time, error) {
+ formats := []string{
+ "2006-01-02",
+ "2006-01",
+ "2006",
+ }
+
+ for _, format := range formats {
+ if t, err := time.Parse(format, dateStr); err == nil {
+ return t, nil
+ }
+ }
+
+ return time.Time{}, nil
+}
diff --git a/internal/ai/providers/notable_models_test.go b/internal/ai/providers/notable_models_test.go
new file mode 100644
index 0000000000..55aac40b33
--- /dev/null
+++ b/internal/ai/providers/notable_models_test.go
@@ -0,0 +1,73 @@
+package providers
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+func TestNotableModelsCache_Refresh(t *testing.T) {
+ // Test that we can successfully fetch and parse models.dev API
+ cache := NewNotableModelsCache(modelsDevAPIURL, 1*time.Hour)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ err := cache.Refresh(ctx)
+ if err != nil {
+ t.Fatalf("Failed to refresh cache: %v", err)
+ }
+
+ if len(cache.data) == 0 {
+ t.Fatal("Cache is empty after refresh")
+ }
+
+ t.Logf("Cache contains %d models", len(cache.data))
+
+ // Check for some known models
+ testCases := []struct {
+ provider string
+ modelID string
+ }{
+ {"anthropic", "claude-opus-4-5"},
+ {"anthropic", "claude-sonnet-4-5"},
+ {"openai", "gpt-4o"},
+ }
+
+ for _, tc := range testCases {
+ key := normalizeKey(tc.provider, tc.modelID)
+ if info, found := cache.data[key]; found {
+ t.Logf("Found %s: release_date=%s, last_updated=%s", key, info.ReleaseDate, info.LastUpdated)
+ } else {
+ t.Logf("Model %s not found in cache (key=%s)", tc.modelID, key)
+ // Try fuzzy match
+ fuzzyKey := normalizeModelID(tc.modelID)
+ if info, found := cache.data[fuzzyKey]; found {
+ t.Logf("Found via fuzzy match %s: release_date=%s", fuzzyKey, info.ReleaseDate)
+ }
+ }
+ }
+}
+
+func TestIsNotable_Integration(t *testing.T) {
+ cache := GetNotableCache()
+
+ // Test Ollama - should always be notable
+ if !cache.IsNotable("ollama", "llama3", 0) {
+ t.Error("Ollama models should always be notable")
+ }
+
+ // Test Anthropic models
+ // claude-opus-4-5 was released 2025-11-21, should be notable
+ notable := cache.IsNotable("anthropic", "claude-opus-4-5", 0)
+ t.Logf("claude-opus-4-5 notable: %v", notable)
+
+ // claude-3-5-sonnet-20241022 was released 2024-10-22, should NOT be notable (>6 months old)
+ notable = cache.IsNotable("anthropic", "claude-3-5-sonnet-20241022", 0)
+ t.Logf("claude-3-5-sonnet-20241022 notable: %v", notable)
+
+ // Print cache size
+ cache.mu.RLock()
+ t.Logf("Cache size: %d", len(cache.data))
+ cache.mu.RUnlock()
+}
diff --git a/internal/ai/providers/ollama.go b/internal/ai/providers/ollama.go
index d2f958d51b..762f9d22ab 100644
--- a/internal/ai/providers/ollama.go
+++ b/internal/ai/providers/ollama.go
@@ -257,6 +257,200 @@ func (c *OllamaClient) Chat(ctx context.Context, req ChatRequest) (*ChatResponse
return chatResp, nil
}
+// SupportsThinking returns true if the model supports extended thinking
+func (c *OllamaClient) SupportsThinking(model string) bool {
+ // Ollama models don't currently support extended thinking in stream output
+ return false
+}
+
+// ollamaStreamResponse is a single chunk from the Ollama streaming API
+type ollamaStreamResponse struct {
+ Model string `json:"model"`
+ CreatedAt string `json:"created_at"`
+ Message ollamaMessageResp `json:"message"`
+ Done bool `json:"done"`
+ DoneReason string `json:"done_reason,omitempty"`
+ TotalDuration int64 `json:"total_duration,omitempty"`
+ LoadDuration int64 `json:"load_duration,omitempty"`
+ PromptEvalCount int `json:"prompt_eval_count,omitempty"`
+ EvalCount int `json:"eval_count,omitempty"`
+}
+
+// ChatStream sends a chat request and streams the response via callback
+func (c *OllamaClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error {
+ // Convert messages to Ollama format (same as Chat)
+ messages := make([]ollamaMessage, 0, len(req.Messages)+1)
+
+ if req.System != "" {
+ messages = append(messages, ollamaMessage{
+ Role: "system",
+ Content: req.System,
+ })
+ }
+
+ for _, m := range req.Messages {
+ msg := ollamaMessage{
+ Role: m.Role,
+ Content: m.Content,
+ }
+ if len(m.ToolCalls) > 0 {
+ for _, tc := range m.ToolCalls {
+ msg.ToolCalls = append(msg.ToolCalls, ollamaToolCall{
+ Function: ollamaFunctionCall{
+ Name: tc.Name,
+ Arguments: tc.Input,
+ },
+ })
+ }
+ }
+ if m.ToolResult != nil {
+ msg.Role = "tool"
+ msg.Content = m.ToolResult.Content
+ }
+ messages = append(messages, msg)
+ }
+
+ model := req.Model
+ if strings.HasPrefix(model, "ollama:") {
+ model = strings.TrimPrefix(model, "ollama:")
+ }
+ if model == "" {
+ model = c.model
+ }
+ if model == "" {
+ model = "llama3"
+ }
+
+ ollamaReq := ollamaRequest{
+ Model: model,
+ Messages: messages,
+ Stream: true, // Enable streaming
+ }
+
+ if len(req.Tools) > 0 {
+ ollamaReq.Tools = make([]ollamaTool, 0, len(req.Tools))
+ for _, t := range req.Tools {
+ if t.Type != "" && t.Type != "function" {
+ continue
+ }
+ ollamaReq.Tools = append(ollamaReq.Tools, ollamaTool{
+ Type: "function",
+ Function: ollamaToolFunction{
+ Name: t.Name,
+ Description: t.Description,
+ Parameters: t.InputSchema,
+ },
+ })
+ }
+ }
+
+ if req.MaxTokens > 0 || req.Temperature > 0 {
+ ollamaReq.Options = &ollamaOptions{}
+ if req.MaxTokens > 0 {
+ ollamaReq.Options.NumPredict = req.MaxTokens
+ }
+ if req.Temperature > 0 {
+ ollamaReq.Options.Temperature = req.Temperature
+ }
+ }
+
+ body, err := json.Marshal(ollamaReq)
+ if err != nil {
+ return fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ url := c.baseURL + "/api/chat"
+ httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+
+ httpReq.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.client.Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ respBody, _ := io.ReadAll(resp.Body)
+ return fmt.Errorf("API error (%d): %s", resp.StatusCode, string(respBody))
+ }
+
+ // Parse NDJSON stream (newline-delimited JSON, not SSE)
+ decoder := json.NewDecoder(resp.Body)
+ var toolCalls []ToolCall
+ var inputTokens, outputTokens int
+ var doneReason string
+
+ for {
+ var chunk ollamaStreamResponse
+ if err := decoder.Decode(&chunk); err != nil {
+ if err == io.EOF {
+ break
+ }
+ return fmt.Errorf("stream decode error: %w", err)
+ }
+
+ // Regular content
+ if chunk.Message.Content != "" {
+ callback(StreamEvent{
+ Type: "content",
+ Data: ContentEvent{Text: chunk.Message.Content},
+ })
+ }
+
+ // Tool calls
+ for _, tc := range chunk.Message.ToolCalls {
+ toolCallID := tc.ID
+ if toolCallID == "" {
+ toolCallID = fmt.Sprintf("ollama_%s_%d", tc.Function.Name, len(toolCalls))
+ }
+ callback(StreamEvent{
+ Type: "tool_start",
+ Data: ToolStartEvent{
+ ID: toolCallID,
+ Name: tc.Function.Name,
+ Input: tc.Function.Arguments,
+ },
+ })
+ toolCalls = append(toolCalls, ToolCall{
+ ID: toolCallID,
+ Name: tc.Function.Name,
+ Input: tc.Function.Arguments,
+ })
+ }
+
+ if chunk.Done {
+ inputTokens = chunk.PromptEvalCount
+ outputTokens = chunk.EvalCount
+ doneReason = chunk.DoneReason
+ break
+ }
+ }
+
+ // Send done event
+ stopReason := doneReason
+ if len(toolCalls) > 0 {
+ stopReason = "tool_use"
+ } else if stopReason == "" || stopReason == "stop" {
+ stopReason = "end_turn"
+ }
+
+ callback(StreamEvent{
+ Type: "done",
+ Data: DoneEvent{
+ StopReason: stopReason,
+ ToolCalls: toolCalls,
+ InputTokens: inputTokens,
+ OutputTokens: outputTokens,
+ },
+ })
+
+ return nil
+}
+
// TestConnection validates connectivity by checking the Ollama version endpoint
func (c *OllamaClient) TestConnection(ctx context.Context) error {
url := c.baseURL + "/api/version"
@@ -312,8 +506,9 @@ func (c *OllamaClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
models := make([]ModelInfo, 0, len(result.Models))
for _, m := range result.Models {
models = append(models, ModelInfo{
- ID: m.Name,
- Name: m.Name,
+ ID: m.Name,
+ Name: m.Name,
+ Notable: true, // Ollama models are always notable - user explicitly pulled them
})
}
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index 1bbf6b79ef..10a32c9e53 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -523,6 +523,338 @@ func (c *OpenAIClient) modelsEndpoint() string {
return u.Scheme + "://" + u.Host + path
}
+// SupportsThinking returns true if the model supports extended thinking
+func (c *OpenAIClient) SupportsThinking(model string) bool {
+ // DeepSeek reasoner models support extended thinking
+ if c.isDeepSeek() && strings.Contains(model, "reasoner") {
+ return true
+ }
+ // OpenAI o1/o3/o4 models have reasoning but not in the same streaming format
+ return false
+}
+
+// openaiStreamRequest extends openaiRequest with streaming field
+type openaiStreamRequest struct {
+ Model string `json:"model"`
+ Messages []openaiMessage `json:"messages"`
+ MaxTokens int `json:"max_tokens,omitempty"`
+ MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
+ Temperature float64 `json:"temperature,omitempty"`
+ Tools []openaiTool `json:"tools,omitempty"`
+ ToolChoice interface{} `json:"tool_choice,omitempty"`
+ Stream bool `json:"stream"`
+ StreamOptions *streamOptions `json:"stream_options,omitempty"`
+}
+
+type streamOptions struct {
+ IncludeUsage bool `json:"include_usage"`
+}
+
+// openaiStreamEvent represents a streaming event from the OpenAI API
+type openaiStreamEvent struct {
+ ID string `json:"id"`
+ Object string `json:"object"`
+ Created int64 `json:"created"`
+ Model string `json:"model"`
+ Choices []openaiStreamChoice `json:"choices"`
+ Usage *openaiUsage `json:"usage,omitempty"`
+}
+
+type openaiStreamChoice struct {
+ Index int `json:"index"`
+ Delta openaiStreamDelta `json:"delta"`
+ FinishReason string `json:"finish_reason"`
+}
+
+type openaiStreamDelta struct {
+ Role string `json:"role,omitempty"`
+ Content string `json:"content,omitempty"`
+ ReasoningContent string `json:"reasoning_content,omitempty"`
+ ToolCalls []openaiToolCallDelta `json:"tool_calls,omitempty"`
+}
+
+type openaiToolCallDelta struct {
+ Index int `json:"index"`
+ ID string `json:"id,omitempty"`
+ Type string `json:"type,omitempty"`
+ Function struct {
+ Name string `json:"name,omitempty"`
+ Arguments string `json:"arguments,omitempty"`
+ } `json:"function,omitempty"`
+}
+
+// ChatStream sends a chat request and streams the response via callback
+func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error {
+ // Convert messages to OpenAI format (same as Chat)
+ messages := make([]openaiMessage, 0, len(req.Messages)+1)
+
+ if req.System != "" {
+ messages = append(messages, openaiMessage{
+ Role: "system",
+ Content: req.System,
+ })
+ }
+
+ for _, m := range req.Messages {
+ msg := openaiMessage{
+ Role: m.Role,
+ }
+
+ if len(m.ToolCalls) > 0 {
+ msg.Content = nil
+ if m.Content != "" {
+ msg.Content = m.Content
+ }
+ if c.isDeepSeekReasoner() && m.ReasoningContent != "" {
+ msg.ReasoningContent = m.ReasoningContent
+ }
+ for _, tc := range m.ToolCalls {
+ argsJSON, _ := json.Marshal(tc.Input)
+ msg.ToolCalls = append(msg.ToolCalls, openaiToolCall{
+ ID: tc.ID,
+ Type: "function",
+ Function: openaiToolFunction{
+ Name: tc.Name,
+ Arguments: string(argsJSON),
+ },
+ })
+ }
+ } else if m.ToolResult != nil {
+ msg.Role = "tool"
+ msg.Content = m.ToolResult.Content
+ msg.ToolCallID = m.ToolResult.ToolUseID
+ } else {
+ msg.Content = m.Content
+ if c.isDeepSeekReasoner() && m.ReasoningContent != "" {
+ msg.ReasoningContent = m.ReasoningContent
+ }
+ }
+
+ messages = append(messages, msg)
+ }
+
+ model := req.Model
+ if strings.HasPrefix(model, "openai:") {
+ model = strings.TrimPrefix(model, "openai:")
+ } else if strings.HasPrefix(model, "deepseek:") {
+ model = strings.TrimPrefix(model, "deepseek:")
+ }
+ if model == "" {
+ model = c.model
+ }
+
+ openaiReq := openaiStreamRequest{
+ Model: model,
+ Messages: messages,
+ Stream: true,
+ StreamOptions: &streamOptions{
+ IncludeUsage: true,
+ },
+ }
+
+ if req.MaxTokens > 0 {
+ if c.isDeepSeek() {
+ openaiReq.MaxTokens = req.MaxTokens
+ } else {
+ openaiReq.MaxCompletionTokens = req.MaxTokens
+ }
+ }
+
+ if req.Temperature > 0 && !c.isDeepSeekReasoner() && !c.requiresMaxCompletionTokens(model) {
+ openaiReq.Temperature = req.Temperature
+ }
+
+ if len(req.Tools) > 0 {
+ for _, t := range req.Tools {
+ if t.Type != "" && t.Type != "function" {
+ continue
+ }
+ openaiReq.Tools = append(openaiReq.Tools, openaiTool{
+ Type: "function",
+ Function: openaiFunction{
+ Name: t.Name,
+ Description: t.Description,
+ Parameters: t.InputSchema,
+ },
+ })
+ }
+ if len(openaiReq.Tools) > 0 {
+ openaiReq.ToolChoice = "auto"
+ }
+ }
+
+ body, err := json.Marshal(openaiReq)
+ if err != nil {
+ return fmt.Errorf("failed to marshal request: %w", err)
+ }
+
+ httpReq, err := http.NewRequestWithContext(ctx, "POST", c.baseURL, bytes.NewReader(body))
+ if err != nil {
+ return fmt.Errorf("failed to create request: %w", err)
+ }
+
+ httpReq.Header.Set("Content-Type", "application/json")
+ httpReq.Header.Set("Authorization", "Bearer "+c.apiKey)
+ httpReq.Header.Set("Accept", "text/event-stream")
+
+ resp, err := c.client.Do(httpReq)
+ if err != nil {
+ return fmt.Errorf("request failed: %w", err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ respBody, _ := io.ReadAll(resp.Body)
+ var errResp openaiError
+ if err := json.Unmarshal(respBody, &errResp); err == nil && errResp.Error.Message != "" {
+ return fmt.Errorf("API error (%d): %s", resp.StatusCode, errResp.Error.Message)
+ }
+ return fmt.Errorf("API error (%d): %s", resp.StatusCode, string(respBody))
+ }
+
+ // Parse SSE stream
+ reader := resp.Body
+ buf := make([]byte, 4096)
+ var pendingData string
+ var toolCalls []ToolCall
+ toolCallBuilders := make(map[int]*struct {
+ id string
+ name string
+ args strings.Builder
+ })
+ var inputTokens, outputTokens int
+ var finishReason string
+
+ for {
+ n, err := reader.Read(buf)
+ if err != nil {
+ if err == io.EOF {
+ break
+ }
+ return fmt.Errorf("stream read error: %w", err)
+ }
+
+ pendingData += string(buf[:n])
+ lines := strings.Split(pendingData, "\n")
+
+ // Keep the last incomplete line for next iteration
+ pendingData = lines[len(lines)-1]
+ lines = lines[:len(lines)-1]
+
+ for _, line := range lines {
+ line = strings.TrimSpace(line)
+
+ if !strings.HasPrefix(line, "data:") {
+ continue
+ }
+
+ data := strings.TrimPrefix(line, "data:")
+ data = strings.TrimSpace(data)
+
+ if data == "[DONE]" {
+ // Build final tool calls from builders
+ for _, builder := range toolCallBuilders {
+ var input map[string]interface{}
+ if err := json.Unmarshal([]byte(builder.args.String()), &input); err != nil {
+ input = map[string]interface{}{"raw": builder.args.String()}
+ }
+ toolCalls = append(toolCalls, ToolCall{
+ ID: builder.id,
+ Name: builder.name,
+ Input: input,
+ })
+ }
+
+ stopReason := finishReason
+ if len(toolCalls) > 0 {
+ stopReason = "tool_use"
+ } else if stopReason == "stop" {
+ stopReason = "end_turn"
+ }
+
+ callback(StreamEvent{
+ Type: "done",
+ Data: DoneEvent{
+ StopReason: stopReason,
+ ToolCalls: toolCalls,
+ InputTokens: inputTokens,
+ OutputTokens: outputTokens,
+ },
+ })
+ return nil
+ }
+
+ var event openaiStreamEvent
+ if err := json.Unmarshal([]byte(data), &event); err != nil {
+ log.Debug().Err(err).Str("data", data).Msg("Failed to parse stream event")
+ continue
+ }
+
+ // Handle usage info
+ if event.Usage != nil {
+ inputTokens = event.Usage.PromptTokens
+ outputTokens = event.Usage.CompletionTokens
+ }
+
+ for _, choice := range event.Choices {
+ if choice.FinishReason != "" {
+ finishReason = choice.FinishReason
+ }
+
+ delta := choice.Delta
+
+ // Regular content
+ if delta.Content != "" {
+ callback(StreamEvent{
+ Type: "content",
+ Data: ContentEvent{Text: delta.Content},
+ })
+ }
+
+ // Reasoning content (DeepSeek)
+ if delta.ReasoningContent != "" {
+ callback(StreamEvent{
+ Type: "thinking",
+ Data: ThinkingEvent{Text: delta.ReasoningContent},
+ })
+ }
+
+ // Tool calls
+ for _, tc := range delta.ToolCalls {
+ builder, exists := toolCallBuilders[tc.Index]
+ if !exists {
+ builder = &struct {
+ id string
+ name string
+ args strings.Builder
+ }{}
+ toolCallBuilders[tc.Index] = builder
+ }
+
+ if tc.ID != "" {
+ builder.id = tc.ID
+ }
+ if tc.Function.Name != "" {
+ builder.name = tc.Function.Name
+ callback(StreamEvent{
+ Type: "tool_start",
+ Data: ToolStartEvent{
+ ID: builder.id,
+ Name: builder.name,
+ },
+ })
+ }
+ if tc.Function.Arguments != "" {
+ builder.args.WriteString(tc.Function.Arguments)
+ }
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
// ListModels fetches available models from the OpenAI API
func (c *OpenAIClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
modelsURL := c.modelsEndpoint()
@@ -558,14 +890,22 @@ func (c *OpenAIClient) ListModels(ctx context.Context) ([]ModelInfo, error) {
}
models := make([]ModelInfo, 0, len(result.Data))
+ cache := GetNotableCache()
for _, m := range result.Data {
// Filter to only chat-capable models
if strings.Contains(m.ID, "gpt") || strings.Contains(m.ID, "o1") ||
- strings.Contains(m.ID, "o3") || strings.Contains(m.ID, "deepseek") {
+ strings.Contains(m.ID, "o3") || strings.Contains(m.ID, "o4") ||
+ strings.Contains(m.ID, "deepseek") {
+ // Use correct provider for notable detection
+ provider := "openai"
+ if strings.Contains(m.ID, "deepseek") {
+ provider = "deepseek"
+ }
models = append(models, ModelInfo{
ID: m.ID,
Name: m.ID, // OpenAI uses ID as name
CreatedAt: m.Created,
+ Notable: cache.IsNotable(provider, m.ID, m.Created),
})
}
}
diff --git a/internal/ai/providers/provider.go b/internal/ai/providers/provider.go
index ea545e6368..ae4c224469 100644
--- a/internal/ai/providers/provider.go
+++ b/internal/ai/providers/provider.go
@@ -64,6 +64,7 @@ type ModelInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
CreatedAt int64 `json:"created_at,omitempty"`
+ Notable bool `json:"notable"` // Whether this is a "latest and greatest" model
}
// Provider defines the interface for AI providers
@@ -81,3 +82,59 @@ type Provider interface {
// Returns nil if the provider doesn't support listing models
ListModels(ctx context.Context) ([]ModelInfo, error)
}
+
+// StreamEvent represents a streaming event from the AI provider
+type StreamEvent struct {
+ Type string // "content", "thinking", "tool_start", "tool_end", "done", "error"
+ Data interface{} // Type-specific data
+}
+
+// ContentEvent is the data for "content" stream events
+type ContentEvent struct {
+ Text string `json:"text"`
+}
+
+// ThinkingEvent is the data for "thinking" stream events (extended thinking/reasoning)
+type ThinkingEvent struct {
+ Text string `json:"text"`
+}
+
+// ToolStartEvent is the data for "tool_start" stream events
+type ToolStartEvent struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Input map[string]interface{} `json:"input,omitempty"`
+}
+
+// ToolEndEvent is the data for "tool_end" stream events
+type ToolEndEvent struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Result string `json:"result,omitempty"`
+ IsError bool `json:"is_error,omitempty"`
+}
+
+// ErrorEvent is the data for "error" stream events
+type ErrorEvent struct {
+ Message string `json:"message"`
+}
+
+// DoneEvent is the data for "done" stream events
+type DoneEvent struct {
+ StopReason string `json:"stop_reason,omitempty"`
+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`
+ InputTokens int `json:"input_tokens,omitempty"`
+ OutputTokens int `json:"output_tokens,omitempty"`
+}
+
+// StreamCallback is called for each streaming event
+type StreamCallback func(event StreamEvent)
+
+// StreamingProvider extends Provider with streaming support
+type StreamingProvider interface {
+ Provider
+ // ChatStream sends a chat request and streams the response via callback
+ ChatStream(ctx context.Context, req ChatRequest, callback StreamCallback) error
+ // SupportsThinking returns true if the model supports extended thinking/reasoning
+ SupportsThinking(model string) bool
+}
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 5fbed3915c..050cd797bf 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -3437,6 +3437,7 @@ func (s *Service) ListModelsWithCache(ctx context.Context) ([]providers.ModelInf
Name: m.Name,
Description: providerDisplayName(providerName) + ": " + m.ID,
CreatedAt: m.CreatedAt,
+ Notable: m.Notable,
})
}
}