feat: AI models admin, settings import, Anthropic adapter and the rest of AIService
- golem15_golem_models (encrypted write-only api_key) with its cabana list and form under golem15.golem.access_settings, and the Settings lookups (Models, DefaultModel with PHP's position-0 quirk, Vision, Image, File, ByName), every one Trusted - golem:import-settings copies the WinterCMS golem_settings repeater once - AnthropicAdapter; SendStream, SendFile/SendFilePath/SendFileReader, SendWithModel, SendToImageModel, SendToVisionModel, GenerateImage, Ask - PromptFactory; README documents the config keys, the environment variable, the command and the admin screen
This commit is contained in:
@@ -49,6 +49,9 @@ const (
|
||||
// ForName is ProviderFactory::make: the Anthropic adapter for "anthropic",
|
||||
// the OpenAI-compatible adapter for anything else.
|
||||
func ForName(adapter string) Adapter {
|
||||
if adapter == "anthropic" {
|
||||
return AnthropicAdapter{}
|
||||
}
|
||||
return OpenAIAdapter{}
|
||||
}
|
||||
|
||||
|
||||
195
classes/providers/anthropic.go
Normal file
195
classes/providers/anthropic.go
Normal file
@@ -0,0 +1,195 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/sm-golem-plugin/classes/valueobjects"
|
||||
"git.golem15.com/golem15/summercms/modules/fetchguard"
|
||||
)
|
||||
|
||||
// Anthropic API headers PHP sends on every request.
|
||||
const (
|
||||
AnthropicVersion = "2023-06-01"
|
||||
AnthropicBeta = "files-api-2025-04-14"
|
||||
)
|
||||
|
||||
// AnthropicAdapter is the Anthropic Messages API mapping (PHP
|
||||
// AnthropicAdapter).
|
||||
type AnthropicAdapter struct{}
|
||||
|
||||
var _ Adapter = AnthropicAdapter{}
|
||||
|
||||
var dataURL = regexp.MustCompile(`^data:([^;]+);base64,(.+)$`)
|
||||
|
||||
func anthropicHeaders(apiKey string) http.Header {
|
||||
return http.Header{
|
||||
"X-Api-Key": {apiKey},
|
||||
"Anthropic-Version": {AnthropicVersion},
|
||||
"Anthropic-Beta": {AnthropicBeta},
|
||||
}
|
||||
}
|
||||
|
||||
// Headers are x-api-key, anthropic-version and anthropic-beta.
|
||||
func (AnthropicAdapter) Headers(apiKey string) http.Header { return anthropicHeaders(apiKey) }
|
||||
|
||||
// ChatEndpoint is <base>/messages.
|
||||
func (AnthropicAdapter) ChatEndpoint(baseURL string) string {
|
||||
return endpoint(baseURL, AnthropicBaseURL, "/messages")
|
||||
}
|
||||
|
||||
// FilesEndpoint is <base>/files.
|
||||
func (AnthropicAdapter) FilesEndpoint(baseURL string) string {
|
||||
return endpoint(baseURL, AnthropicBaseURL, "/files")
|
||||
}
|
||||
|
||||
// ImageEndpoint is "": Anthropic generates no images.
|
||||
func (AnthropicAdapter) ImageEndpoint(string) string { return "" }
|
||||
|
||||
// BuildChatPayload is the Messages body: model (the prompt's override or
|
||||
// modelID), the messages with image_url blocks rewritten to image blocks
|
||||
// (base64 for a data: URL, url otherwise) and file blocks to document
|
||||
// blocks, the system prompt when set, max_tokens (the max_tokens option,
|
||||
// else max_completion_tokens, else 4096) and every other option except
|
||||
// response_format and max_completion_tokens.
|
||||
func (AnthropicAdapter) BuildChatPayload(prompt valueobjects.Prompt, modelID string) *valueobjects.Payload {
|
||||
msgs := prompt.Messages()
|
||||
out := make([]map[string]any, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
out = append(out, map[string]any{"role": m.Role, "content": anthropicContent(m)})
|
||||
}
|
||||
payload := valueobjects.NewPayload()
|
||||
model := modelID
|
||||
if p := prompt.Model(); p != nil {
|
||||
model = *p
|
||||
}
|
||||
payload.Set("model", model)
|
||||
payload.Set("messages", out)
|
||||
if s := prompt.SystemPrompt(); s != "" {
|
||||
payload.Set("system", s)
|
||||
}
|
||||
opts := prompt.Options()
|
||||
var maxTokens any = 4096
|
||||
if opts.IsSet("max_tokens") {
|
||||
maxTokens, _ = opts.Get("max_tokens")
|
||||
} else if opts.IsSet("max_completion_tokens") {
|
||||
maxTokens, _ = opts.Get("max_completion_tokens")
|
||||
}
|
||||
payload.Set("max_tokens", maxTokens)
|
||||
for _, k := range opts.Keys() {
|
||||
if k == "response_format" || k == "max_completion_tokens" {
|
||||
continue
|
||||
}
|
||||
v, _ := opts.Get(k)
|
||||
payload.Set(k, v)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func anthropicContent(m valueobjects.Message) any {
|
||||
if m.Parts == nil {
|
||||
return m.Text
|
||||
}
|
||||
blocks := make([]any, 0, len(m.Parts))
|
||||
for _, part := range m.Parts {
|
||||
switch part.Type {
|
||||
case "image_url":
|
||||
u := ""
|
||||
if part.ImageURL != nil {
|
||||
u = part.ImageURL.URL
|
||||
}
|
||||
if strings.HasPrefix(u, "data:") {
|
||||
media, data := "image/jpeg", ""
|
||||
if mm := dataURL.FindStringSubmatch(u); mm != nil {
|
||||
media, data = mm[1], mm[2]
|
||||
}
|
||||
blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": media, "data": data}})
|
||||
} else {
|
||||
blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": u}})
|
||||
}
|
||||
case "file":
|
||||
id := ""
|
||||
if part.File != nil {
|
||||
id = part.File.FileID
|
||||
}
|
||||
blocks = append(blocks, map[string]any{"type": "document", "source": map[string]any{"type": "file", "file_id": id}})
|
||||
default:
|
||||
blocks = append(blocks, part)
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
// FileUploadFields is empty: the Anthropic files API takes the file only.
|
||||
func (AnthropicAdapter) FileUploadFields(string) []fetchguard.FormField { return nil }
|
||||
|
||||
// FileUploadHeaders are the Messages headers.
|
||||
func (AnthropicAdapter) FileUploadHeaders(apiKey string) http.Header {
|
||||
return anthropicHeaders(apiKey)
|
||||
}
|
||||
|
||||
// ParseChatResponse reads content[0].text; usage gains PHP's
|
||||
// prompt_tokens, completion_tokens and total_tokens next to Anthropic's
|
||||
// input_tokens and output_tokens; Raw keeps the whole answer, stop_reason
|
||||
// included.
|
||||
func (AnthropicAdapter) ParseChatResponse(data map[string]any) valueobjects.AIResponse {
|
||||
if msg, ok := errorMessage(data); ok {
|
||||
return valueobjects.Failure(msg, data)
|
||||
}
|
||||
content := dig(data, "content", 0, "text")
|
||||
if content == nil {
|
||||
return valueobjects.Failure("No content in AI response.", data)
|
||||
}
|
||||
usage := map[string]any{}
|
||||
if u, ok := data["usage"].(map[string]any); ok {
|
||||
for k, v := range u {
|
||||
usage[k] = v
|
||||
}
|
||||
}
|
||||
if in, ok := usage["input_tokens"]; ok && in != nil {
|
||||
prompt := number(in)
|
||||
completion := number(usage["output_tokens"])
|
||||
usage["prompt_tokens"] = in
|
||||
if usage["output_tokens"] == nil {
|
||||
usage["completion_tokens"] = 0
|
||||
} else {
|
||||
usage["completion_tokens"] = usage["output_tokens"]
|
||||
}
|
||||
usage["total_tokens"] = prompt + completion
|
||||
}
|
||||
return valueobjects.Success(phpString(content), usage, data)
|
||||
}
|
||||
|
||||
func number(v any) float64 {
|
||||
if f, ok := v.(float64); ok {
|
||||
return f
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// ParseStreamChunk reads Anthropic's event stream: `event: message_stop`
|
||||
// ends it, a `data:` line of type content_block_delta carries the text
|
||||
// delta, anything else is skipped.
|
||||
func (AnthropicAdapter) ParseStreamChunk(line string) (string, bool) {
|
||||
if line == "" {
|
||||
return "", false
|
||||
}
|
||||
if event, ok := strings.CutPrefix(line, "event: "); ok {
|
||||
return "", event == "message_stop"
|
||||
}
|
||||
payload, ok := strings.CutPrefix(line, "data: ")
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
var v map[string]any
|
||||
if json.Unmarshal([]byte(payload), &v) != nil || len(v) == 0 {
|
||||
return "", false
|
||||
}
|
||||
if v["type"] != "content_block_delta" {
|
||||
return "", false
|
||||
}
|
||||
text, _ := dig(v, "delta", "text").(string)
|
||||
return text, false
|
||||
}
|
||||
@@ -179,3 +179,135 @@ func TestOpenAIAdapterPayload(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestAnthropicAdapterPayload pins AnthropicAdapter.php: headers,
|
||||
// endpoints, the max_tokens fallback chain, the dropped options, image
|
||||
// and file block rewriting, response parsing and the event stream.
|
||||
func TestAnthropicAdapterPayload(t *testing.T) {
|
||||
a := AnthropicAdapter{}
|
||||
if _, ok := ForName("anthropic").(AnthropicAdapter); !ok {
|
||||
t.Fatal("ForName(anthropic) is not the Anthropic adapter")
|
||||
}
|
||||
if _, ok := ForName("").(OpenAIAdapter); !ok {
|
||||
t.Fatal("ForName(\"\") is not the OpenAI adapter")
|
||||
}
|
||||
|
||||
t.Run("headers and endpoints", func(t *testing.T) {
|
||||
h := a.Headers("sk-ant-test")
|
||||
if h.Get("X-Api-Key") != "sk-ant-test" || h.Get("Anthropic-Version") != "2023-06-01" || h.Get("Anthropic-Beta") != "files-api-2025-04-14" || h.Get("Authorization") != "" {
|
||||
t.Fatalf("headers = %v", h)
|
||||
}
|
||||
if a.FileUploadHeaders("k").Get("X-Api-Key") != "k" {
|
||||
t.Fatal("file upload headers")
|
||||
}
|
||||
if got := a.ChatEndpoint(""); got != "https://api.anthropic.com/v1/messages" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := a.ChatEndpoint("https://proxy.example.test/v1///"); got != "https://proxy.example.test/v1/messages" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := a.FilesEndpoint(""); got != "https://api.anthropic.com/v1/files" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if a.ImageEndpoint("") != "" || a.FileUploadFields("assistants") != nil {
|
||||
t.Fatal("anthropic has no image endpoint and no upload fields")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("max_tokens chain and dropped options", func(t *testing.T) {
|
||||
base := valueobjects.NewPrompt().AddUserMessage("hi")
|
||||
if v, _ := a.BuildChatPayload(base, "claude-sonnet-4-6").Get("max_tokens"); v != 4096 {
|
||||
t.Fatalf("default max_tokens = %v", v)
|
||||
}
|
||||
p := a.BuildChatPayload(base.WithOptions(map[string]any{"max_completion_tokens": 8192, "response_format": map[string]any{"type": "json_object"}, "temperature": 0.2}), "claude-sonnet-4-6")
|
||||
if v, _ := p.Get("max_tokens"); v != 8192 {
|
||||
t.Fatalf("max_completion_tokens fallback = %v", v)
|
||||
}
|
||||
if p.Has("max_completion_tokens") || p.Has("response_format") {
|
||||
t.Fatalf("dropped options leaked: %v", p.Keys())
|
||||
}
|
||||
if v, _ := p.Get("temperature"); v != 0.2 {
|
||||
t.Fatal("other options pass through")
|
||||
}
|
||||
p = a.BuildChatPayload(base.WithOptions(map[string]any{"max_tokens": 100, "max_completion_tokens": 200}, "max_tokens", "max_completion_tokens"), "m")
|
||||
if v, _ := p.Get("max_tokens"); v != 100 {
|
||||
t.Fatalf("explicit max_tokens wins: %v", v)
|
||||
}
|
||||
if p.Has("system") {
|
||||
t.Fatal("system without a system prompt")
|
||||
}
|
||||
if got := strings.Join(a.BuildChatPayload(base.WithSystem("sys"), "m").Keys(), ","); got != "model,messages,system,max_tokens" {
|
||||
t.Fatalf("keys = %s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("image and file blocks", func(t *testing.T) {
|
||||
prompt := valueobjects.NewPrompt().
|
||||
WithSystem("You catalog physical items.").
|
||||
AddUserMessageWithImage("What is this?", "QUJD", "image/png").
|
||||
AddUserMessageWithFileID("Read this.", "file_123").
|
||||
WithModel("claude-opus")
|
||||
m := payloadMap(t, a.BuildChatPayload(prompt, "claude-sonnet-4-6"))
|
||||
if m["model"] != "claude-opus" || m["system"] != "You catalog physical items." {
|
||||
t.Fatalf("payload = %v", m)
|
||||
}
|
||||
msgs := m["messages"].([]any)
|
||||
if len(msgs) != 2 {
|
||||
t.Fatalf("messages = %v (the system prompt is not a message)", msgs)
|
||||
}
|
||||
img := msgs[0].(map[string]any)["content"].([]any)[1].(map[string]any)
|
||||
src := img["source"].(map[string]any)
|
||||
if img["type"] != "image" || src["type"] != "base64" || src["media_type"] != "image/png" || src["data"] != "QUJD" {
|
||||
t.Fatalf("image block = %v", img)
|
||||
}
|
||||
doc := msgs[1].(map[string]any)["content"].([]any)[1].(map[string]any)
|
||||
if doc["type"] != "document" || doc["source"].(map[string]any)["file_id"] != "file_123" {
|
||||
t.Fatalf("document block = %v", doc)
|
||||
}
|
||||
remote := valueobjects.Message{Role: "user", Parts: []valueobjects.ContentPart{{Type: "image_url", ImageURL: &valueobjects.ImageURL{URL: "https://img.example.test/a.jpg"}}}}
|
||||
blk := anthropicContent(remote).([]any)[0].(map[string]any)["source"].(map[string]any)
|
||||
if blk["type"] != "url" || blk["url"] != "https://img.example.test/a.jpg" {
|
||||
t.Fatalf("remote image = %v", blk)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("parse", func(t *testing.T) {
|
||||
var data map[string]any
|
||||
_ = json.Unmarshal([]byte(`{"content":[{"type":"text","text":"[]"}],"stop_reason":"max_tokens","usage":{"input_tokens":10,"output_tokens":5}}`), &data)
|
||||
r := a.ParseChatResponse(data)
|
||||
if !r.Success || r.Content != "[]" || r.Raw["stop_reason"] != "max_tokens" {
|
||||
t.Fatalf("response = %+v", r)
|
||||
}
|
||||
if r.PromptTokens() != 10 || r.CompletionTokens() != 5 || r.TotalTokens() != 15 || r.Usage["input_tokens"] != float64(10) {
|
||||
t.Fatalf("usage = %v", r.Usage)
|
||||
}
|
||||
r = a.ParseChatResponse(map[string]any{"type": "error", "error": map[string]any{"type": "authentication_error", "message": "invalid x-api-key"}})
|
||||
if r.Success || r.Error != "invalid x-api-key" {
|
||||
t.Fatalf("error = %+v", r)
|
||||
}
|
||||
r = a.ParseChatResponse(map[string]any{"content": []any{}})
|
||||
if r.Error != "No content in AI response." {
|
||||
t.Fatalf("empty = %+v", r)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stream", func(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
line string
|
||||
delta string
|
||||
done bool
|
||||
}{
|
||||
{"", "", false},
|
||||
{"event: content_block_delta", "", false},
|
||||
{`data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"Hi"}}`, "Hi", false},
|
||||
{`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, "", false},
|
||||
{"data: {}", "", false},
|
||||
{"event: message_stop", "", true},
|
||||
} {
|
||||
d, done := a.ParseStreamChunk(c.line)
|
||||
if d != c.delta || done != c.done {
|
||||
t.Fatalf("%q: (%q,%v)", c.line, d, done)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user