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>
464 lines
13 KiB
Go
464 lines
13 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Package ai is Docwell's AI layer (ADR-15): provider drivers, the BYOK
|
|
// profiles workspaces and the instance configure, the embeddings index,
|
|
// chat sessions with citations, writing actions and the MCP endpoint.
|
|
//
|
|
// Only the server talks to providers. Every request is checked against
|
|
// Docwell's permissions before anything is sent.
|
|
package ai
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// Provider kinds.
|
|
const (
|
|
KindOpenAI = "openai"
|
|
KindAnthropic = "anthropic"
|
|
KindOllama = "ollama"
|
|
)
|
|
|
|
// Message is one chat turn: role "user" or "assistant".
|
|
type Message struct {
|
|
Role string
|
|
Content string
|
|
}
|
|
|
|
// ChatRequest is a chat call. System is the system prompt.
|
|
type ChatRequest struct {
|
|
Model string
|
|
System string
|
|
Messages []Message
|
|
MaxTokens int
|
|
// Effort is the Anthropic effort level ("" leaves the model's default).
|
|
Effort string
|
|
// PDF goes with the last message, for models that read documents
|
|
// (scanned pages too). Drivers that cannot send one return ErrNoDocuments.
|
|
PDF []byte
|
|
}
|
|
|
|
// Usage is what a call cost, as the provider reports it.
|
|
type Usage struct {
|
|
InputTokens int `json:"inputTokens"`
|
|
OutputTokens int `json:"outputTokens"`
|
|
}
|
|
|
|
// Provider is one configured backend.
|
|
type Provider interface {
|
|
// Chat streams the answer to onDelta and returns the usage once done.
|
|
Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error)
|
|
// Embed returns one vector per input text.
|
|
Embed(ctx context.Context, model string, texts []string) ([][]float32, Usage, error)
|
|
// Transcribe turns speech in an audio or video file into text.
|
|
Transcribe(ctx context.Context, model, filename string, data []byte) (string, error)
|
|
}
|
|
|
|
// ErrNoEmbeddings is returned by providers that cannot embed text.
|
|
var ErrNoEmbeddings = errors.New("this provider has no embeddings API")
|
|
|
|
// ErrNoTranscription is returned by providers that cannot transcribe audio.
|
|
var ErrNoTranscription = errors.New("this provider has no speech-to-text API")
|
|
|
|
// ErrNoDocuments is returned by providers that cannot read PDF files.
|
|
var ErrNoDocuments = errors.New("this provider cannot read PDF files")
|
|
|
|
// ErrRefused is returned when the model declined to answer.
|
|
var ErrRefused = errors.New("the model declined to answer this request")
|
|
|
|
// ProviderError is an HTTP error from a provider, with its status.
|
|
type ProviderError struct {
|
|
Status int
|
|
Message string
|
|
}
|
|
|
|
func (e *ProviderError) Error() string {
|
|
if e.Message == "" {
|
|
return fmt.Sprintf("provider answered %d", e.Status)
|
|
}
|
|
return fmt.Sprintf("provider answered %d: %s", e.Status, e.Message)
|
|
}
|
|
|
|
// DefaultBaseURL is the address a kind uses when a profile leaves it empty.
|
|
func DefaultBaseURL(kind string) string {
|
|
switch kind {
|
|
case KindOpenAI:
|
|
return "https://api.openai.com/v1"
|
|
case KindAnthropic:
|
|
return "https://api.anthropic.com"
|
|
case KindOllama:
|
|
return "http://localhost:11434"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// NewProvider builds the driver for a kind. client carries the address
|
|
// rules (see webhooks.Guard) and has no overall timeout, so answers can
|
|
// stream for as long as the context allows.
|
|
func NewProvider(kind, baseURL, apiKey string, client *http.Client) (Provider, error) {
|
|
if baseURL == "" {
|
|
baseURL = DefaultBaseURL(kind)
|
|
}
|
|
baseURL = strings.TrimRight(baseURL, "/")
|
|
switch kind {
|
|
case KindOpenAI:
|
|
return &openAI{base: baseURL, key: apiKey, http: client}, nil
|
|
case KindAnthropic:
|
|
return newAnthropic(baseURL, apiKey, client), nil
|
|
case KindOllama:
|
|
return &ollama{base: baseURL, key: apiKey, http: client}, nil
|
|
}
|
|
return nil, fmt.Errorf("unknown provider kind %q", kind)
|
|
}
|
|
|
|
// postJSON sends body and returns the response, or a ProviderError for a
|
|
// status of 400 or more.
|
|
func postJSON(ctx context.Context, client *http.Client, url string, headers map[string]string, body any) (*http.Response, error) {
|
|
raw, err := json.Marshal(body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(raw))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
for k, v := range headers {
|
|
if v != "" {
|
|
req.Header.Set(k, v)
|
|
}
|
|
}
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if res.StatusCode >= 400 {
|
|
defer res.Body.Close()
|
|
return nil, readProviderError(res)
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// readProviderError pulls a message out of the usual error bodies:
|
|
// {"error": {"message": …}}, {"error": "…"} or plain text.
|
|
func readProviderError(res *http.Response) error {
|
|
raw, _ := io.ReadAll(io.LimitReader(res.Body, 4096))
|
|
var body struct {
|
|
Error json.RawMessage `json:"error"`
|
|
}
|
|
msg := strings.TrimSpace(string(raw))
|
|
if json.Unmarshal(raw, &body) == nil && len(body.Error) > 0 {
|
|
var nested struct {
|
|
Message string `json:"message"`
|
|
}
|
|
var flat string
|
|
if json.Unmarshal(body.Error, &nested) == nil && nested.Message != "" {
|
|
msg = nested.Message
|
|
} else if json.Unmarshal(body.Error, &flat) == nil && flat != "" {
|
|
msg = flat
|
|
}
|
|
}
|
|
if len(msg) > 300 {
|
|
msg = msg[:300]
|
|
}
|
|
return &ProviderError{Status: res.StatusCode, Message: msg}
|
|
}
|
|
|
|
// ---- OpenAI-compatible --------------------------------------------------------
|
|
|
|
type openAI struct {
|
|
base string
|
|
key string
|
|
http *http.Client
|
|
}
|
|
|
|
func (p *openAI) headers() map[string]string {
|
|
if p.key == "" {
|
|
return nil
|
|
}
|
|
return map[string]string{"Authorization": "Bearer " + p.key}
|
|
}
|
|
|
|
func (p *openAI) Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error) {
|
|
msgs := []map[string]any{}
|
|
if req.System != "" {
|
|
msgs = append(msgs, map[string]any{"role": "system", "content": req.System})
|
|
}
|
|
for i, m := range req.Messages {
|
|
if len(req.PDF) > 0 && i == len(req.Messages)-1 {
|
|
// OpenAI's file input; compatible servers that lack it answer an error.
|
|
msgs = append(msgs, map[string]any{"role": m.Role, "content": []map[string]any{
|
|
{"type": "file", "file": map[string]string{
|
|
"filename": "document.pdf", "file_data": "data:application/pdf;base64," + base64.StdEncoding.EncodeToString(req.PDF),
|
|
}},
|
|
{"type": "text", "text": m.Content},
|
|
}})
|
|
continue
|
|
}
|
|
msgs = append(msgs, map[string]any{"role": m.Role, "content": m.Content})
|
|
}
|
|
body := map[string]any{
|
|
"model": req.Model, "messages": msgs, "stream": true,
|
|
"stream_options": map[string]bool{"include_usage": true},
|
|
}
|
|
if req.MaxTokens > 0 {
|
|
body["max_tokens"] = req.MaxTokens
|
|
}
|
|
res, err := postJSON(ctx, p.http, p.base+"/chat/completions", p.headers(), body)
|
|
if err != nil {
|
|
return Usage{}, err
|
|
}
|
|
defer res.Body.Close()
|
|
var usage Usage
|
|
err = readSSE(res.Body, func(data string) error {
|
|
if data == "[DONE]" {
|
|
return io.EOF
|
|
}
|
|
var chunk struct {
|
|
Choices []struct {
|
|
Delta struct {
|
|
Content string `json:"content"`
|
|
} `json:"delta"`
|
|
FinishReason string `json:"finish_reason"`
|
|
} `json:"choices"`
|
|
Usage *struct {
|
|
Prompt int `json:"prompt_tokens"`
|
|
Completion int `json:"completion_tokens"`
|
|
} `json:"usage"`
|
|
}
|
|
if err := json.Unmarshal([]byte(data), &chunk); err != nil {
|
|
return nil
|
|
}
|
|
for _, c := range chunk.Choices {
|
|
if c.Delta.Content != "" {
|
|
onDelta(c.Delta.Content)
|
|
}
|
|
if c.FinishReason == "content_filter" {
|
|
return ErrRefused
|
|
}
|
|
}
|
|
if chunk.Usage != nil {
|
|
usage = Usage{InputTokens: chunk.Usage.Prompt, OutputTokens: chunk.Usage.Completion}
|
|
}
|
|
return nil
|
|
})
|
|
return usage, err
|
|
}
|
|
|
|
func (p *openAI) Embed(ctx context.Context, model string, texts []string) ([][]float32, Usage, error) {
|
|
res, err := postJSON(ctx, p.http, p.base+"/embeddings", p.headers(), map[string]any{"model": model, "input": texts})
|
|
if err != nil {
|
|
return nil, Usage{}, err
|
|
}
|
|
defer res.Body.Close()
|
|
var body struct {
|
|
Data []struct {
|
|
Index int `json:"index"`
|
|
Embedding []float32 `json:"embedding"`
|
|
} `json:"data"`
|
|
Usage struct {
|
|
Prompt int `json:"prompt_tokens"`
|
|
} `json:"usage"`
|
|
}
|
|
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
|
|
return nil, Usage{}, fmt.Errorf("embeddings: %w", err)
|
|
}
|
|
out := make([][]float32, len(texts))
|
|
for i, d := range body.Data {
|
|
idx := d.Index
|
|
if idx < 0 || idx >= len(out) {
|
|
idx = i
|
|
}
|
|
if idx < len(out) {
|
|
out[idx] = d.Embedding
|
|
}
|
|
}
|
|
for _, v := range out {
|
|
if len(v) == 0 {
|
|
return nil, Usage{}, errors.New("embeddings: the provider returned fewer vectors than texts")
|
|
}
|
|
}
|
|
return out, Usage{InputTokens: body.Usage.Prompt}, nil
|
|
}
|
|
|
|
// Transcribe posts the file to {base}/audio/transcriptions (Whisper and
|
|
// compatible servers: Groq, LocalAI, faster-whisper-server, vLLM …).
|
|
func (p *openAI) Transcribe(ctx context.Context, model, filename string, data []byte) (string, error) {
|
|
var body bytes.Buffer
|
|
w := multipart.NewWriter(&body)
|
|
_ = w.WriteField("model", model)
|
|
_ = w.WriteField("response_format", "json")
|
|
part, err := w.CreateFormFile("file", filename)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if _, err := part.Write(data); err != nil {
|
|
return "", err
|
|
}
|
|
if err := w.Close(); err != nil {
|
|
return "", err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.base+"/audio/transcriptions", &body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("Content-Type", w.FormDataContentType())
|
|
for k, v := range p.headers() {
|
|
req.Header.Set(k, v)
|
|
}
|
|
res, err := p.http.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode >= 400 {
|
|
return "", readProviderError(res)
|
|
}
|
|
var out struct {
|
|
Text string `json:"text"`
|
|
}
|
|
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
|
return "", fmt.Errorf("transcription: %w", err)
|
|
}
|
|
return out.Text, nil
|
|
}
|
|
|
|
// readSSE calls fn with the data of each server-sent event until the
|
|
// stream ends or fn returns an error (io.EOF ends it cleanly).
|
|
func readSSE(r io.Reader, fn func(data string) error) error {
|
|
sc := bufio.NewScanner(r)
|
|
sc.Buffer(make([]byte, 64<<10), 4<<20)
|
|
var data strings.Builder
|
|
flush := func() error {
|
|
if data.Len() == 0 {
|
|
return nil
|
|
}
|
|
d := data.String()
|
|
data.Reset()
|
|
return fn(d)
|
|
}
|
|
for sc.Scan() {
|
|
line := sc.Text()
|
|
if line == "" {
|
|
if err := flush(); err != nil {
|
|
if errors.Is(err, io.EOF) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
if v, ok := strings.CutPrefix(line, "data:"); ok {
|
|
if data.Len() > 0 {
|
|
data.WriteByte('\n')
|
|
}
|
|
data.WriteString(strings.TrimPrefix(v, " "))
|
|
}
|
|
}
|
|
if err := sc.Err(); err != nil {
|
|
return err
|
|
}
|
|
if err := flush(); err != nil && !errors.Is(err, io.EOF) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ---- Ollama ---------------------------------------------------------------------
|
|
|
|
type ollama struct {
|
|
base string
|
|
key string
|
|
http *http.Client
|
|
}
|
|
|
|
func (p *ollama) headers() map[string]string {
|
|
if p.key == "" {
|
|
return nil
|
|
}
|
|
return map[string]string{"Authorization": "Bearer " + p.key}
|
|
}
|
|
|
|
func (p *ollama) Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error) {
|
|
if len(req.PDF) > 0 {
|
|
return Usage{}, ErrNoDocuments
|
|
}
|
|
msgs := []map[string]string{}
|
|
if req.System != "" {
|
|
msgs = append(msgs, map[string]string{"role": "system", "content": req.System})
|
|
}
|
|
for _, m := range req.Messages {
|
|
msgs = append(msgs, map[string]string{"role": m.Role, "content": m.Content})
|
|
}
|
|
body := map[string]any{"model": req.Model, "messages": msgs, "stream": true}
|
|
if req.MaxTokens > 0 {
|
|
body["options"] = map[string]int{"num_predict": req.MaxTokens}
|
|
}
|
|
res, err := postJSON(ctx, p.http, p.base+"/api/chat", p.headers(), body)
|
|
if err != nil {
|
|
return Usage{}, err
|
|
}
|
|
defer res.Body.Close()
|
|
dec := json.NewDecoder(res.Body)
|
|
var usage Usage
|
|
for {
|
|
var chunk struct {
|
|
Message struct {
|
|
Content string `json:"content"`
|
|
} `json:"message"`
|
|
Done bool `json:"done"`
|
|
Error string `json:"error"`
|
|
PromptEval int `json:"prompt_eval_count"`
|
|
Eval int `json:"eval_count"`
|
|
}
|
|
if err := dec.Decode(&chunk); err != nil {
|
|
if errors.Is(err, io.EOF) {
|
|
return usage, nil
|
|
}
|
|
return usage, err
|
|
}
|
|
if chunk.Error != "" {
|
|
return usage, &ProviderError{Status: http.StatusBadGateway, Message: chunk.Error}
|
|
}
|
|
if chunk.Message.Content != "" {
|
|
onDelta(chunk.Message.Content)
|
|
}
|
|
if chunk.Done {
|
|
return Usage{InputTokens: chunk.PromptEval, OutputTokens: chunk.Eval}, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *ollama) Transcribe(context.Context, string, string, []byte) (string, error) {
|
|
return "", ErrNoTranscription
|
|
}
|
|
|
|
func (p *ollama) Embed(ctx context.Context, model string, texts []string) ([][]float32, Usage, error) {
|
|
res, err := postJSON(ctx, p.http, p.base+"/api/embed", p.headers(), map[string]any{"model": model, "input": texts})
|
|
if err != nil {
|
|
return nil, Usage{}, err
|
|
}
|
|
defer res.Body.Close()
|
|
var body struct {
|
|
Embeddings [][]float32 `json:"embeddings"`
|
|
PromptEval int `json:"prompt_eval_count"`
|
|
}
|
|
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
|
|
return nil, Usage{}, fmt.Errorf("embeddings: %w", err)
|
|
}
|
|
if len(body.Embeddings) != len(texts) {
|
|
return nil, Usage{}, errors.New("embeddings: the provider returned fewer vectors than texts")
|
|
}
|
|
return body.Embeddings, Usage{InputTokens: body.PromptEval}, nil
|
|
}
|