mirror of
https://github.com/tiennm99/goclaw.git
synced 2026-07-12 19:04:49 +00:00
934ab7e485
read_image and read_document failed when only claude-cli was configured because the fallback chains only listed 'anthropic'. Adding claude-cli as fallback (PR #802) surfaced a deeper bug: buildStreamJSONInput hardcoded 'type: image' for every content block, so PDFs routed through claude-cli were rejected by the Anthropic API with a MIME mismatch. - providers/claude_cli_session.go: buildStreamJSONInput now picks the Anthropic block type from MIME — application/pdf -> document, image/* -> image. - tools/read_image.go, read_document.go: add claude-cli to the fallback priority and model defaults (empty string lets the provider pick its own default model). - tools/read_image.go, read_document_resolve.go: scope disable_tools to claude-cli only instead of leaking a CLI-specific flag into the shared Options map every provider in the chain receives. - providers/claude_cli_session_test.go: table test covering png/pdf/ mixed/unknown MIME routing plus the empty-text edge case. Closes #801.
135 lines
4.3 KiB
Go
135 lines
4.3 KiB
Go
package tools
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"log/slog"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/nextlevelbuilder/goclaw/internal/providers"
|
|
)
|
|
|
|
// resolveDocumentFile finds the document file path from context MediaRefs.
|
|
func (t *ReadDocumentTool) resolveDocumentFile(ctx context.Context, mediaID string) (path, mime string, err error) {
|
|
refs := MediaDocRefsFromCtx(ctx)
|
|
if len(refs) == 0 {
|
|
return "", "", fmt.Errorf("no documents available in this conversation. The user may not have sent a document.")
|
|
}
|
|
|
|
// Find specific media_id or use most recent document.
|
|
var ref *providers.MediaRef
|
|
if mediaID != "" {
|
|
for i := range refs {
|
|
if refs[i].ID == mediaID {
|
|
ref = &refs[i]
|
|
break
|
|
}
|
|
}
|
|
if ref == nil {
|
|
return "", "", fmt.Errorf("document with media_id %q not found in conversation", mediaID)
|
|
}
|
|
} else {
|
|
// Use the last (most recent) document ref.
|
|
ref = &refs[len(refs)-1]
|
|
}
|
|
|
|
// Prefer persisted workspace path; fall back to legacy .media/ lookup.
|
|
p := ref.Path
|
|
if p == "" {
|
|
var err error
|
|
if t.mediaLoader == nil {
|
|
return "", "", fmt.Errorf("no media storage configured")
|
|
}
|
|
p, err = t.mediaLoader.LoadPath(ref.ID)
|
|
if err != nil {
|
|
return "", "", fmt.Errorf("document file not found: %v", err)
|
|
}
|
|
}
|
|
|
|
// Determine MIME type: prefer ref's stored MIME, fall back to extension.
|
|
mime = ref.MimeType
|
|
if mime == "" || mime == "application/octet-stream" {
|
|
mime = mimeFromDocExt(filepath.Ext(p))
|
|
}
|
|
|
|
return p, mime, nil
|
|
}
|
|
|
|
// callProvider dispatches document analysis to the appropriate provider API.
|
|
// For Gemini: uses native generateContent API (supports PDF natively).
|
|
// For others: uses standard Chat API with base64 document.
|
|
func (t *ReadDocumentTool) callProvider(ctx context.Context, cp credentialProvider, providerName, model string, params map[string]any) ([]byte, *providers.Usage, error) {
|
|
prompt := GetParamString(params, "prompt", "Analyze this document and describe its contents.")
|
|
data, _ := params["data"].([]byte)
|
|
mime := GetParamString(params, "mime", "application/octet-stream")
|
|
|
|
// Gemini: use native API (requires credentials; OpenAI-compat endpoint doesn't support non-image MIME types).
|
|
ptype := GetParamString(params, "_provider_type", providerTypeFromName(providerName))
|
|
if cp != nil && ptype == "gemini" {
|
|
slog.Info("read_document: using gemini native API",
|
|
"provider", providerName, "model", model,
|
|
"doc_size", len(data), "mime", mime)
|
|
resp, err := geminiNativeDocumentCall(ctx, cp.APIKey(), model, prompt, data, mime)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("gemini native call: %w", err)
|
|
}
|
|
return []byte(resp.Content), resp.Usage, nil
|
|
}
|
|
|
|
// Other providers: use standard Chat API with document as base64 image_url.
|
|
p, err := t.registry.Get(ctx, providerName)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("provider %q not available: %w", providerName, err)
|
|
}
|
|
|
|
slog.Info("read_document: using chat API", "provider", providerName, "model", model, "doc_size", len(data))
|
|
|
|
opts := map[string]any{
|
|
"max_tokens": 16384,
|
|
"temperature": 0.2,
|
|
}
|
|
// Scope disable_tools to claude-cli only — it's a CLI-bridge-specific
|
|
// option that skips loading the built-in MCP toolset for one-shot calls.
|
|
// Other providers silently ignore unknown keys today, but leaking
|
|
// provider-specific flags into the shared Options map couples layers.
|
|
if providerName == "claude-cli" {
|
|
opts["disable_tools"] = true
|
|
}
|
|
|
|
resp, err := p.Chat(ctx, providers.ChatRequest{
|
|
Messages: []providers.Message{
|
|
{
|
|
Role: "user",
|
|
Content: prompt,
|
|
Images: []providers.ImageContent{{MimeType: mime, Data: base64.StdEncoding.EncodeToString(data)}},
|
|
},
|
|
},
|
|
Model: model,
|
|
Options: opts,
|
|
})
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("chat call: %w", err)
|
|
}
|
|
return []byte(resp.Content), resp.Usage, nil
|
|
}
|
|
|
|
// mimeFromDocExt returns MIME type for document file extensions.
|
|
func mimeFromDocExt(ext string) string {
|
|
switch strings.ToLower(ext) {
|
|
case ".pdf":
|
|
return "application/pdf"
|
|
case ".doc", ".docx":
|
|
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
|
case ".xls", ".xlsx":
|
|
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
|
case ".ppt", ".pptx":
|
|
return "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
|
case ".csv":
|
|
return "text/csv"
|
|
default:
|
|
return "application/octet-stream"
|
|
}
|
|
}
|