Files
Docwell/Server/internal/ai/anthropic.go
T
tajniak81andClaude Opus 5.5 c239d859b8 Transcribe long recordings, read scanned PDFs, and bring AI writing to phones
Follow-ups to Phase E (ADR-15):

- Recordings over 25 MB are cut into pieces and transcribed in turn:
  with ffmpeg (now in the server and all-in-one images) any format is
  re-encoded to 16 kHz mono MP3 in 20-minute pieces; without it, MP3 is
  cut at frame boundaries and WAV at sample boundaries in Go.
- PDFs without a text layer are written out by a document-capable chat
  model (Anthropic document input, OpenAI file input); Ollama is skipped.
- Phone app: AI answers render as Markdown with tappable citations; the
  editing toolbar opens the writing actions on the selection; audio
  files get Transcribe. Editor bridge protocol 4 adds setAi,
  getSelection, insertMarkdown and transcribe/transcribed.
- The transcript HTML builder moves to @docwell/editor, shared by the
  web app and the phone editor.
- An integration test runs chat, Transcribe and writing actions on a
  device against a live server; the editor test no longer expects
  headings to have only a level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:04:10 +01:00

131 lines
4.1 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"context"
"encoding/base64"
"errors"
"net/http"
"strings"
"github.com/anthropics/anthropic-sdk-go/v2"
"github.com/anthropics/anthropic-sdk-go/v2/option"
)
// DefaultAnthropicModel is offered for new Anthropic profiles.
const DefaultAnthropicModel = "claude-opus-5-5"
type anthropicProvider struct {
client anthropic.Client
// official is true for api.anthropic.com, where server-side refusal
// fallbacks exist; gateways and proxies may not accept the field.
official bool
}
func newAnthropic(base, key string, client *http.Client) *anthropicProvider {
opts := []option.RequestOption{
option.WithHTTPClient(client),
option.WithMaxRetries(1),
option.WithBaseURL(base + "/"),
}
if key != "" {
opts = append(opts, option.WithAPIKey(key))
}
return &anthropicProvider{
client: anthropic.NewClient(opts...),
official: strings.HasPrefix(base, "https://api.anthropic.com"),
}
}
// fallbackModels are the models with the server-side refusal fallback.
var fallbackModels = []string{"claude-fable-5", "claude-opus-5", "claude-sonnet-5-5"}
func hasFallback(model string) bool {
for _, p := range fallbackModels {
if strings.HasPrefix(model, p) {
return true
}
}
return false
}
func (p *anthropicProvider) Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error) {
maxTokens := int64(req.MaxTokens)
if maxTokens <= 0 {
maxTokens = 16000
}
params := anthropic.BetaMessageNewParams{
Model: anthropic.Model(req.Model),
MaxTokens: maxTokens,
}
if req.System != "" {
params.System = []anthropic.BetaTextBlockParam{{Text: req.System}}
}
for i, m := range req.Messages {
block := anthropic.NewBetaTextBlock(m.Content)
if m.Role == "assistant" {
params.Messages = append(params.Messages, anthropic.BetaMessageParam{
OfAssistant: &anthropic.BetaAssistantMessageParam{Content: []anthropic.BetaContentBlockParamUnion{block}},
})
} else if len(req.PDF) > 0 && i == len(req.Messages)-1 {
// The document goes before the question about it.
doc := anthropic.NewBetaDocumentBlock(anthropic.BetaBase64PDFSourceParam{Data: base64.StdEncoding.EncodeToString(req.PDF)})
params.Messages = append(params.Messages, anthropic.NewBetaUserMessage(doc, block))
} else {
params.Messages = append(params.Messages, anthropic.NewBetaUserMessage(block))
}
}
if req.Effort != "" {
params.OutputConfig = anthropic.BetaOutputConfigParam{Effort: anthropic.BetaOutputConfigEffort(req.Effort)}
}
if p.official && hasFallback(req.Model) {
params.Betas = []anthropic.AnthropicBeta{anthropic.AnthropicBetaServerSideFallback2026_07_01}
params.Fallbacks = anthropic.BetaFallbacksParamOfDefault()
}
stream := p.client.Beta.Messages.NewStreaming(ctx, params)
defer stream.Close()
msg := anthropic.BetaMessage{}
for stream.Next() {
ev := stream.Current()
_ = msg.Accumulate(ev)
if d, ok := ev.AsAny().(anthropic.BetaRawContentBlockDeltaEvent); ok {
if t, ok := d.Delta.AsAny().(anthropic.BetaTextDelta); ok && t.Text != "" {
onDelta(t.Text)
}
}
}
usage := Usage{InputTokens: int(msg.Usage.InputTokens + msg.Usage.CacheReadInputTokens + msg.Usage.CacheCreationInputTokens), OutputTokens: int(msg.Usage.OutputTokens)}
if err := stream.Err(); err != nil {
var apiErr *anthropic.Error
if errors.As(err, &apiErr) {
return usage, &ProviderError{Status: apiErr.StatusCode, Message: anthropicMessage(apiErr)}
}
return usage, err
}
if msg.StopReason == anthropic.BetaStopReasonRefusal {
return usage, ErrRefused
}
return usage, nil
}
func anthropicMessage(e *anthropic.Error) string {
raw := e.RawJSON()
if i := strings.Index(raw, `"message":"`); i >= 0 {
rest := raw[i+len(`"message":"`):]
if j := strings.Index(rest, `"`); j >= 0 {
return rest[:j]
}
}
return http.StatusText(e.StatusCode)
}
func (p *anthropicProvider) Transcribe(context.Context, string, string, []byte) (string, error) {
return "", ErrNoTranscription
}
func (p *anthropicProvider) Embed(context.Context, string, []string) ([][]float32, Usage, error) {
return nil, Usage{}, ErrNoEmbeddings
}