feat: golem15.golem plugin with the OpenAI-compatible adapter and AIService.Send
- Prompt, Payload and AIResponse value objects ported from Golem15.Golem - OpenAIAdapter: chat completions mapping with PHP's response_format, max_completion_tokens and reasoning_effort rules - AIService.Send through fetchguard (TrustedMode for operator models, PublicOnlyMode otherwise) with PHP's failure messages - config defaults for the SSRF allowlist and the AI timeout, lang, README
This commit is contained in:
114
classes/providers/adapter.go
Normal file
114
classes/providers/adapter.go
Normal file
@@ -0,0 +1,114 @@
|
||||
// Package providers maps AI requests and answers to each provider's wire
|
||||
// format: the OpenAI-compatible chat completions API and the Anthropic
|
||||
// Messages API. The adapters only build and parse JSON; the AI service in
|
||||
// classes/services sends the requests through the framework's guarded
|
||||
// outbound client.
|
||||
package providers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/sm-golem-plugin/classes/valueobjects"
|
||||
"git.golem15.com/golem15/summercms/modules/fetchguard"
|
||||
)
|
||||
|
||||
// Adapter is one provider's mapping (PHP AIProviderAdapter).
|
||||
type Adapter interface {
|
||||
// Headers are the provider's auth and version headers for apiKey.
|
||||
Headers(apiKey string) http.Header
|
||||
// ChatEndpoint is the chat URL under baseURL ("" means the
|
||||
// provider's default base URL).
|
||||
ChatEndpoint(baseURL string) string
|
||||
// FilesEndpoint is the file upload URL under baseURL.
|
||||
FilesEndpoint(baseURL string) string
|
||||
// ImageEndpoint is the image generation URL, "" when the provider
|
||||
// has none.
|
||||
ImageEndpoint(baseURL string) string
|
||||
// BuildChatPayload is the chat request body for prompt, with modelID
|
||||
// unless the prompt overrides the model.
|
||||
BuildChatPayload(prompt valueobjects.Prompt, modelID string) *valueobjects.Payload
|
||||
// FileUploadFields are the plain multipart fields of a file upload.
|
||||
FileUploadFields(purpose string) []fetchguard.FormField
|
||||
// FileUploadHeaders are the headers of a file upload.
|
||||
FileUploadHeaders(apiKey string) http.Header
|
||||
// ParseChatResponse maps a decoded chat answer to an AIResponse.
|
||||
ParseChatResponse(data map[string]any) valueobjects.AIResponse
|
||||
// ParseStreamChunk reads one server-sent-events line: the content
|
||||
// delta it carries ("" when none) and whether the stream ended.
|
||||
ParseStreamChunk(line string) (delta string, done bool)
|
||||
}
|
||||
|
||||
// Default base URLs, used when a config leaves base_url empty.
|
||||
const (
|
||||
OpenAIBaseURL = "https://api.openai.com/v1"
|
||||
AnthropicBaseURL = "https://api.anthropic.com/v1"
|
||||
)
|
||||
|
||||
// ForName is ProviderFactory::make: the Anthropic adapter for "anthropic",
|
||||
// the OpenAI-compatible adapter for anything else.
|
||||
func ForName(adapter string) Adapter {
|
||||
return OpenAIAdapter{}
|
||||
}
|
||||
|
||||
// endpoint is rtrim(base, '/') . path, with def standing in for an empty
|
||||
// base.
|
||||
func endpoint(base, def, path string) string {
|
||||
if base == "" {
|
||||
base = def
|
||||
}
|
||||
return strings.TrimRight(base, "/") + path
|
||||
}
|
||||
|
||||
// dig walks nested JSON objects and arrays (PHP $a['x'][0]['y'] ?? null).
|
||||
func dig(v any, path ...any) any {
|
||||
for _, p := range path {
|
||||
switch key := p.(type) {
|
||||
case string:
|
||||
m, ok := v.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
v = m[key]
|
||||
case int:
|
||||
s, ok := v.([]any)
|
||||
if !ok || key < 0 || key >= len(s) {
|
||||
return nil
|
||||
}
|
||||
v = s[key]
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// errorMessage is PHP's `$data['error']['message'] ?? 'Unknown API
|
||||
// error'` for a response that carries an error key, and false otherwise.
|
||||
func errorMessage(data map[string]any) (string, bool) {
|
||||
e, ok := data["error"]
|
||||
if !ok || e == nil {
|
||||
return "", false
|
||||
}
|
||||
if msg := dig(e, "message"); msg != nil {
|
||||
return phpString(msg), true
|
||||
}
|
||||
return "Unknown API error", true
|
||||
}
|
||||
|
||||
// phpString is a PHP string cast of a decoded JSON scalar.
|
||||
func phpString(v any) string {
|
||||
switch t := v.(type) {
|
||||
case string:
|
||||
return t
|
||||
case bool:
|
||||
if t {
|
||||
return "1"
|
||||
}
|
||||
return ""
|
||||
case float64:
|
||||
return strconv.FormatFloat(t, 'f', -1, 64)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
107
classes/providers/openai.go
Normal file
107
classes/providers/openai.go
Normal file
@@ -0,0 +1,107 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// OpenAIAdapter is the OpenAI-compatible chat completions mapping (PHP
|
||||
// OpenAIAdapter). It also serves compatible providers (Groq, Together,
|
||||
// local model servers) through their base URL.
|
||||
type OpenAIAdapter struct{}
|
||||
|
||||
var _ Adapter = OpenAIAdapter{}
|
||||
|
||||
// reasoningModel matches the o-series and gpt-5 model ids, which spend
|
||||
// completion tokens on hidden reasoning.
|
||||
var reasoningModel = regexp.MustCompile(`(?i)^(o\d|gpt-5)`)
|
||||
|
||||
// Headers is Authorization: Bearer <key>.
|
||||
func (OpenAIAdapter) Headers(apiKey string) http.Header {
|
||||
return http.Header{"Authorization": {fetchguard.Bearer(apiKey)}}
|
||||
}
|
||||
|
||||
// ChatEndpoint is <base>/chat/completions.
|
||||
func (OpenAIAdapter) ChatEndpoint(baseURL string) string {
|
||||
return endpoint(baseURL, OpenAIBaseURL, "/chat/completions")
|
||||
}
|
||||
|
||||
// FilesEndpoint is <base>/files.
|
||||
func (OpenAIAdapter) FilesEndpoint(baseURL string) string {
|
||||
return endpoint(baseURL, OpenAIBaseURL, "/files")
|
||||
}
|
||||
|
||||
// ImageEndpoint is <base>/images/generations.
|
||||
func (OpenAIAdapter) ImageEndpoint(baseURL string) string {
|
||||
return endpoint(baseURL, OpenAIBaseURL, "/images/generations")
|
||||
}
|
||||
|
||||
// BuildChatPayload is the prompt's chat completions body with three
|
||||
// adjustments PHP makes: response_format is dropped (recognition asks for
|
||||
// JSON in the prompt instead), a max_tokens option becomes
|
||||
// max_completion_tokens (an explicit max_completion_tokens wins), and an
|
||||
// o-series or gpt-5 model gets reasoning_effort low unless the prompt set
|
||||
// one.
|
||||
func (OpenAIAdapter) BuildChatPayload(prompt valueobjects.Prompt, modelID string) *valueobjects.Payload {
|
||||
payload := prompt.ToAPIPayload(modelID)
|
||||
payload.Delete("response_format")
|
||||
if payload.IsSet("max_tokens") || payload.IsSet("max_completion_tokens") {
|
||||
v, _ := payload.Get("max_completion_tokens")
|
||||
if v == nil {
|
||||
v, _ = payload.Get("max_tokens")
|
||||
}
|
||||
payload.Set("max_completion_tokens", v)
|
||||
payload.Delete("max_tokens")
|
||||
}
|
||||
if reasoningModel.MatchString(modelID) && !payload.IsSet("reasoning_effort") {
|
||||
payload.Set("reasoning_effort", "low")
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
// FileUploadFields is the purpose field.
|
||||
func (OpenAIAdapter) FileUploadFields(purpose string) []fetchguard.FormField {
|
||||
return []fetchguard.FormField{{Name: "purpose", Value: purpose}}
|
||||
}
|
||||
|
||||
// FileUploadHeaders is Authorization: Bearer <key>.
|
||||
func (OpenAIAdapter) FileUploadHeaders(apiKey string) http.Header {
|
||||
return http.Header{"Authorization": {fetchguard.Bearer(apiKey)}}
|
||||
}
|
||||
|
||||
// ParseChatResponse reads choices[0].message.content; an error object is a
|
||||
// failure carrying the provider's message and the whole body.
|
||||
func (OpenAIAdapter) ParseChatResponse(data map[string]any) valueobjects.AIResponse {
|
||||
if msg, ok := errorMessage(data); ok {
|
||||
return valueobjects.Failure(msg, data)
|
||||
}
|
||||
content := dig(data, "choices", 0, "message", "content")
|
||||
if content == nil {
|
||||
return valueobjects.Failure("No content in AI response.", data)
|
||||
}
|
||||
usage, _ := data["usage"].(map[string]any)
|
||||
return valueobjects.Success(phpString(content), usage, data)
|
||||
}
|
||||
|
||||
// ParseStreamChunk reads a `data: {...}` line's choices[0].delta.content;
|
||||
// `data: [DONE]` ends the stream.
|
||||
func (OpenAIAdapter) ParseStreamChunk(line string) (string, bool) {
|
||||
payload, ok := strings.CutPrefix(line, "data: ")
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
if payload == "[DONE]" {
|
||||
return "", true
|
||||
}
|
||||
var v map[string]any
|
||||
if json.Unmarshal([]byte(payload), &v) != nil || len(v) == 0 {
|
||||
return "", false
|
||||
}
|
||||
delta, _ := dig(v, "choices", 0, "delta", "content").(string)
|
||||
return delta, false
|
||||
}
|
||||
181
classes/providers/providers_test.go
Normal file
181
classes/providers/providers_test.go
Normal file
@@ -0,0 +1,181 @@
|
||||
package providers
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/sm-golem-plugin/classes/valueobjects"
|
||||
)
|
||||
|
||||
func payloadMap(t *testing.T, p *valueobjects.Payload) map[string]any {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// TestOpenAIAdapterPayload ports OpenAIAdapterTest.php.
|
||||
func TestOpenAIAdapterPayload(t *testing.T) {
|
||||
a := OpenAIAdapter{}
|
||||
|
||||
t.Run("strips response_format and migrates max_tokens", func(t *testing.T) {
|
||||
prompt := valueobjects.NewPrompt().
|
||||
WithSystem("You catalog physical items.").
|
||||
AddUserMessage("List the items.").
|
||||
WithOptions(map[string]any{"response_format": map[string]any{"type": "json_object"}, "max_tokens": 800}, "response_format", "max_tokens")
|
||||
p := a.BuildChatPayload(prompt, "gpt-4o")
|
||||
if p.Has("response_format") {
|
||||
t.Fatal("response_format must be stripped")
|
||||
}
|
||||
if p.Has("max_tokens") {
|
||||
t.Fatal("legacy max_tokens must be removed")
|
||||
}
|
||||
if v, _ := p.Get("max_completion_tokens"); v != 800 {
|
||||
t.Fatalf("max_completion_tokens = %v, want 800", v)
|
||||
}
|
||||
m := payloadMap(t, p)
|
||||
msgs := m["messages"].([]any)
|
||||
if first := msgs[0].(map[string]any); first["role"] != "system" || first["content"] != "You catalog physical items." {
|
||||
t.Fatalf("system message first: %v", first)
|
||||
}
|
||||
if strings.Join(p.Keys(), ",") != "model,messages,max_completion_tokens" {
|
||||
t.Fatalf("keys = %v", p.Keys())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("explicit max_completion_tokens wins", func(t *testing.T) {
|
||||
prompt := valueobjects.NewPrompt().AddUserMessage("List the items.").
|
||||
WithOptions(map[string]any{"max_tokens": 800, "max_completion_tokens": 1200}, "max_tokens", "max_completion_tokens")
|
||||
p := a.BuildChatPayload(prompt, "gpt-4o")
|
||||
if p.Has("max_tokens") {
|
||||
t.Fatal("max_tokens leaked")
|
||||
}
|
||||
if v, _ := p.Get("max_completion_tokens"); v != 1200 {
|
||||
t.Fatalf("max_completion_tokens = %v, want 1200", v)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("reasoning models get reasoning_effort low", func(t *testing.T) {
|
||||
prompt := valueobjects.NewPrompt().AddUserMessage("List the items.")
|
||||
for _, model := range []string{"gpt-5.5", "gpt-5", "o1", "o3-mini", "o4-mini", "O3"} {
|
||||
if v, _ := a.BuildChatPayload(prompt, model).Get("reasoning_effort"); v != "low" {
|
||||
t.Fatalf("%s: reasoning_effort = %v", model, v)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("non-reasoning models get none and a caller value wins", func(t *testing.T) {
|
||||
prompt := valueobjects.NewPrompt().AddUserMessage("List the items.")
|
||||
for _, model := range []string{"gpt-4o", "gpt-4.1", "gpt-4o-mini"} {
|
||||
if a.BuildChatPayload(prompt, model).Has("reasoning_effort") {
|
||||
t.Fatalf("%s: reasoning_effort must not be set", model)
|
||||
}
|
||||
}
|
||||
explicit := prompt.WithOptions(map[string]any{"reasoning_effort": "high"})
|
||||
if v, _ := a.BuildChatPayload(explicit, "gpt-5.5").Get("reasoning_effort"); v != "high" {
|
||||
t.Fatalf("caller reasoning_effort overridden: %v", v)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("native image_url block passes through", func(t *testing.T) {
|
||||
b64 := base64.StdEncoding.EncodeToString([]byte("fake-image-bytes"))
|
||||
prompt := valueobjects.NewPrompt().AddUserMessageWithImage("What is in this photo?", b64, "image/jpeg")
|
||||
m := payloadMap(t, a.BuildChatPayload(prompt, "gpt-4o"))
|
||||
parts := m["messages"].([]any)[0].(map[string]any)["content"].([]any)
|
||||
img := parts[1].(map[string]any)
|
||||
if img["type"] != "image_url" {
|
||||
t.Fatalf("block = %v", img)
|
||||
}
|
||||
iu := img["image_url"].(map[string]any)
|
||||
if iu["url"] != "data:image/jpeg;base64,"+b64 || iu["detail"] != "high" {
|
||||
t.Fatalf("image_url = %v", iu)
|
||||
}
|
||||
if text := parts[0].(map[string]any); text["type"] != "text" || text["text"] != "What is in this photo?" {
|
||||
t.Fatalf("text block = %v", text)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("prompt model override", func(t *testing.T) {
|
||||
prompt := valueobjects.NewPrompt().AddUserMessage("hi").WithModel("gpt-4.1")
|
||||
if v, _ := a.BuildChatPayload(prompt, "gpt-4o").Get("model"); v != "gpt-4.1" {
|
||||
t.Fatalf("model = %v", v)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("parse surfaces the API error", func(t *testing.T) {
|
||||
r := a.ParseChatResponse(map[string]any{"error": map[string]any{"message": "invalid API key"}})
|
||||
if r.Success || r.Error != "invalid API key" {
|
||||
t.Fatalf("response = %+v", r)
|
||||
}
|
||||
r = a.ParseChatResponse(map[string]any{"error": map[string]any{"code": "x"}})
|
||||
if r.Error != "Unknown API error" {
|
||||
t.Fatalf("error without message = %q", r.Error)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("parse content and usage", func(t *testing.T) {
|
||||
var data map[string]any
|
||||
_ = json.Unmarshal([]byte(`{"choices":[{"message":{"content":"pong"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1,"total_tokens":4}}`), &data)
|
||||
r := a.ParseChatResponse(data)
|
||||
if !r.Success || r.Content != "pong" || r.TotalTokens() != 4 {
|
||||
t.Fatalf("response = %+v", r)
|
||||
}
|
||||
if dig(r.Raw, "choices", 0, "finish_reason") != "stop" {
|
||||
t.Fatal("raw keeps finish_reason")
|
||||
}
|
||||
r = a.ParseChatResponse(map[string]any{"choices": []any{}})
|
||||
if r.Success || r.Error != "No content in AI response." {
|
||||
t.Fatalf("no content = %+v", r)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("endpoints and headers", func(t *testing.T) {
|
||||
if got := a.ChatEndpoint(""); got != "https://api.openai.com/v1/chat/completions" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := a.ChatEndpoint("https://llm.example.test/v1/"); got != "https://llm.example.test/v1/chat/completions" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := a.FilesEndpoint(""); got != "https://api.openai.com/v1/files" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := a.ImageEndpoint(""); got != "https://api.openai.com/v1/images/generations" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if got := a.Headers("sk-test").Get("Authorization"); got != "Bearer sk-test" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if f := a.FileUploadFields("assistants"); len(f) != 1 || f[0].Name != "purpose" || f[0].Value != "assistants" {
|
||||
t.Fatalf("fields = %v", f)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stream chunks", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
line string
|
||||
delta string
|
||||
done bool
|
||||
}{
|
||||
{"", "", false},
|
||||
{": keep-alive", "", false},
|
||||
{`data: {"choices":[{"delta":{"content":"Hel"}}]}`, "Hel", false},
|
||||
{`data: {"choices":[{"delta":{}}]}`, "", false},
|
||||
{"data: not json", "", false},
|
||||
{"data: [DONE]", "", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
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