gateway: Ollama's /api/chat and /api/generate, for Zed's Ollama provider (super_lalalalala on Discord)

Zed's Ollama provider chats on POST /api/chat, which magpie answered 404:
it served only /api/version, /api/tags and /api/show. Both routes are now
served on the mux, so lanGuard, counted, corsGuard, callerGuard, withCaller
and keyLimited cover them as they cover /v1/chat/completions. The body is
turned into a /v1/chat/completions body and handed to the same
handle(provider.Chat) on a clone of the request, so routing, a key's models,
usage and errors are the /v1 path's own.

Request (ollamaChatBody, after Ollama v0.12.6's api/types.go and Zed's
crates/ollama):
- messages: images as data-URL parts (type sniffed); a tool message's
  images in a user message after it; an assistant's thinking as
  reasoning_content; tool_calls given ids when Ollama sent none, and
  arguments sent as a JSON string;
- a tool result goes with its call by tool_call_id, else tool_name (what
  Zed sends), else in order; one with no call is a 400;
- /api/generate: system, prompt and images as a two-message chat;
- tools, format ("json" or a schema), think (a level is
  reasoning_effort, false hides thinking in the reply);
- options: temperature, top_p, seed, stop, presence/frequency penalty,
  num_predict > 0 as max_tokens; num_ctx, top_k and Ollama's other own
  options are dropped.

Reply (ollamaWriter): NDJSON lines unless stream:false, then one object;
message.content/thinking (or response) as they arrive, tool calls with
an id and their arguments as an object, and a done line with done_reason
(stop or length) and the token counts. An error is {"error":"..."} with
the status /v1 gives. A request with nothing to say is answered
done_reason "load", as Ollama warms a model.

/api/show took "plan/seer:latest" (what `ollama run plan/seer` asks for)
as unknown and the CLI then tried to pull it; ollamaName now gives the
bare id for show and both chat routes.

Broken by hand, each red: tool_name ignored, tool-call ids not kept,
arguments as a string, num_ctx passed upstream, status 200 on an error,
thinking kept with think:false, no route, and /api/show without
ollamaName (plan/plain:latest 404).
Real client: a sandbox gateway (magpie serve, sandbox HOME and
XDG dirs, MAGPIE_ADDR=127.0.0.1:3592) over a fake OpenAI upstream on
3591, with the ollama CLI 0.6.8: `ollama list` lists plan/seer,
`ollama show plan/seer` prints it, `ollama run plan/seer "hi"` and
`ollama run plan/seer:latest "hi"` print the upstream's streamed
"Hello from the sandbox gateway" (the :latest one failed with a pull
error before ollamaName). curl /api/chat and /api/generate, streamed and
stream:false, and a chat with tools, a nameless tool call and a
tool_name result: NDJSON/whole replies, upstream got ids paired and no
num_ctx. Zed itself not run (it would read the live Zed settings).

Run: gofmt -l (none); go vet ./... on darwin, GOOS=linux -tags nogui and
GOOS=windows: clean. `set -o pipefail; go test -timeout 45m ./...` at
1ebda9026 (this batch on 318697dce, movers then at qoder 0.2.21,
workbuddy 0.1.26, no devin raise): 65 packages ok, exit 0. Rebased onto
a9304efe0 (codex images, codex list tag, sessions decoders): gofmt, the
three vets and go test of internal/gateway, internal/provider,
internal/plugin and internal/sessions ok. Then the mover mins were raised
to qoder 0.2.23, workbuddy 0.1.27 and devin 0.1.21 (the only change
since, three strings): gofmt, the three vets of internal/provider and
go test ./internal/provider/ ok at the head of this batch.
This commit is contained in:
yetone
2026-10-21 01:11:05 +08:00
parent a2f8fd86a0
commit 0fe039f14d
6 changed files with 868 additions and 4 deletions
File diff suppressed because one or more lines are too long
+4
View File
@@ -642,6 +642,10 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/version", s.ollamaVersion)
mux.HandleFunc("GET /api/tags", s.ollamaTags)
mux.HandleFunc("POST /api/show", s.ollamaShow)
// and its chat routes, for a client that chats only through them
// (Zed's Ollama provider; ollama_chat.go)
mux.HandleFunc("POST /api/chat", s.ollamaChat(false))
mux.HandleFunc("POST /api/generate", s.ollamaChat(true))
mux.HandleFunc("GET /v1/magpie/quotas", s.quotas)
mux.HandleFunc("GET /v1/magpie/usage", s.usageSummary)
mux.HandleFunc("GET /v1/magpie/usage/requests", s.usageRequests)
+16
View File
@@ -44,6 +44,21 @@ func (s *Server) ollamaTags(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"models": models})
}
// ollamaName is the model id a request names: the ollama CLI names a
// model with no tag as name:latest, which is the bare id unless a model is
// really called that.
func ollamaName(r *http.Request, id string) string {
if _, ok := ollamaEntry(r, id); ok {
return id
}
if bare, cut := strings.CutSuffix(id, ":latest"); cut {
if _, ok := ollamaEntry(r, bare); ok {
return bare
}
}
return id
}
// ollamaShow is one model as Ollama's /api/show tells it. A client reads
// what it takes from capabilities, its window from model_info's
// "<general.architecture>.context_length" (VS Code's Copilot takes 32768
@@ -69,6 +84,7 @@ func (s *Server) ollamaShow(w http.ResponseWriter, r *http.Request) {
ollamaError(w, http.StatusBadRequest, "model is required")
return
}
id = ollamaName(r, id)
e, ok := ollamaEntry(r, id)
if !ok {
ollamaError(w, http.StatusNotFound, "model '"+id+"' not found")
+569
View File
@@ -0,0 +1,569 @@
package gateway
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// Ollama's own chat routes, POST /api/chat and POST /api/generate, for a
// client that chats only through them (Zed's Ollama provider,
// super_lalalalala on Discord; the ollama CLI). Each request is written
// as a Chat Completions one and served by the very handler
// /v1/chat/completions is (s.handle(provider.Chat)), on the request that
// came in, so lanGuard, corsGuard, the caller's key and the models it may
// use, its limits, routing, fallbacks and usage are /v1/chat/completions'
// own. What comes back is said Ollama's way: NDJSON lines, one per part,
// the last "done": true with done_reason and the token counts, or one
// JSON object when the request says "stream": false (Ollama's API,
// docs/api.md at v0.12.6).
// ollamaMessage is a message as Ollama's /api/chat takes and gives one.
type ollamaMessage struct {
Role string `json:"role"`
Content string `json:"content"`
Thinking string `json:"thinking,omitempty"`
Images []string `json:"images,omitempty"`
ToolCalls []ollamaToolCall `json:"tool_calls,omitempty"`
ToolName string `json:"tool_name,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
}
// ollamaToolCall is a tool call as Ollama says one: its arguments an
// object, not a JSON string. Zed reads id as required.
type ollamaToolCall struct {
ID string `json:"id,omitempty"`
Function struct {
Index int `json:"index"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
} `json:"function"`
}
// ollamaRequest is /api/chat's and /api/generate's request: messages for
// the one, prompt, system and images for the other.
type ollamaRequest struct {
Model string `json:"model"`
Messages []ollamaMessage `json:"messages"`
Prompt string `json:"prompt"`
System string `json:"system"`
Images []string `json:"images"`
Tools json.RawMessage `json:"tools"`
Format json.RawMessage `json:"format"`
Options map[string]any `json:"options"`
Stream *bool `json:"stream"`
Think any `json:"think"`
}
func (s *Server) ollamaChat(generate bool) http.HandlerFunc {
chat := s.handle(provider.Chat)
return func(w http.ResponseWriter, r *http.Request) {
body, ok := s.requestBody(w, r, provider.Chat)
if !ok {
return
}
var req ollamaRequest
if err := json.Unmarshal(body, &req); err != nil {
ollamaError(w, http.StatusBadRequest, "invalid request: "+err.Error())
return
}
req.Model = strings.TrimSpace(req.Model)
if req.Model == "" {
ollamaError(w, http.StatusBadRequest, "model is required")
return
}
req.Model = ollamaName(r, req.Model)
stream := req.Stream == nil || *req.Stream
if generate && req.Prompt == "" && len(req.Images) == 0 || !generate && len(req.Messages) == 0 {
// what Ollama answers a request with nothing to say: the
// model loaded, which a client asks to warm it up
if _, ok := ollamaEntry(r, req.Model); !ok {
ollamaError(w, http.StatusNotFound, "model '"+req.Model+"' not found")
return
}
out := map[string]any{"model": req.Model, "created_at": ollamaNow(), "done": true, "done_reason": "load"}
if generate {
out["response"] = ""
} else {
out["message"] = map[string]any{"role": "assistant", "content": ""}
}
if stream {
w.Header().Set("Content-Type", "application/x-ndjson")
}
writeJSON(w, 200, out)
return
}
cbody, err := ollamaChatBody(req, generate, stream)
if err != nil {
ollamaError(w, http.StatusBadRequest, err.Error())
return
}
in := r.Clone(r.Context())
in.Body, in.ContentLength = io.NopCloser(bytes.NewReader(cbody)), int64(len(cbody))
in.Header.Set("Content-Type", "application/json")
in.Header.Del("Content-Encoding")
in.Header.Del("Content-Length")
// a reply that comes back compressed couldn't be read here
in.Header.Del("Accept-Encoding")
ow := &ollamaWriter{w: w, header: http.Header{}, model: req.Model, generate: generate, stream: stream,
noThinking: req.Think == false, start: time.Now()}
chat(ow, in)
ow.finish()
}
}
// ollamaChatBody is req as a Chat Completions request.
func ollamaChatBody(req ollamaRequest, generate, stream bool) ([]byte, error) {
var msgs []map[string]any
if generate {
if req.System != "" {
msgs = append(msgs, map[string]any{"role": "system", "content": req.System})
}
msgs = append(msgs, map[string]any{"role": "user", "content": ollamaContent(req.Prompt, req.Images)})
} else {
var err error
if msgs, err = ollamaMessages(req.Messages); err != nil {
return nil, err
}
}
out := map[string]any{"model": req.Model, "messages": msgs, "stream": stream}
if stream {
out["stream_options"] = map[string]any{"include_usage": true}
}
if !generate && len(req.Tools) > 0 && !bytes.Equal(bytes.TrimSpace(req.Tools), []byte("null")) {
// Ollama's tools are Chat Completions' own shape
out["tools"] = req.Tools
}
if f := bytes.TrimSpace(req.Format); len(f) > 0 && !bytes.Equal(f, []byte("null")) && !bytes.Equal(f, []byte(`""`)) {
var name string
switch {
case json.Unmarshal(f, &name) == nil && name == "json":
out["response_format"] = map[string]any{"type": "json_object"}
case f[0] == '{':
out["response_format"] = map[string]any{"type": "json_schema", "json_schema": map[string]any{"name": "response", "schema": json.RawMessage(f)}}
default:
return nil, fmt.Errorf("invalid format: %s", f)
}
}
// the options a Chat Completions API takes; the rest (num_ctx, top_k,
// repeat_penalty, …) are the local runner's, and have no place there
o := req.Options
for _, k := range []string{"temperature", "top_p", "seed", "presence_penalty", "frequency_penalty"} {
if v, ok := o[k]; ok && v != nil {
out[k] = v
}
}
if v, ok := o["stop"]; ok && v != nil {
out["stop"] = v
}
// -1 is no limit and -2 fill the window, which a Chat API says by
// leaving max_tokens out
if n, ok := o["num_predict"].(float64); ok && n > 0 {
out["max_tokens"] = int(n)
}
switch t := req.Think.(type) {
case string:
if t != "" {
out["reasoning_effort"] = t
}
case nil, bool:
default:
return nil, fmt.Errorf("invalid think value: %v", t)
}
return json.Marshal(out)
}
// ollamaMessages are Ollama's messages in Chat Completions' shape. A tool
// call gets an id when it has none (Ollama's have none before 0.12.x),
// and a tool's result is matched to its call by the id it names, else by
// the tool's name, else in order.
func ollamaMessages(in []ollamaMessage) ([]map[string]any, error) {
type call struct{ id, name string }
var open []call
out := make([]map[string]any, 0, len(in))
for i, m := range in {
role := strings.ToLower(m.Role)
switch role {
case "system", "developer":
out = append(out, map[string]any{"role": role, "content": m.Content})
case "user":
out = append(out, map[string]any{"role": "user", "content": ollamaContent(m.Content, m.Images)})
case "assistant":
msg := map[string]any{"role": "assistant", "content": m.Content}
if m.Thinking != "" {
msg["reasoning_content"] = m.Thinking
}
if len(m.ToolCalls) > 0 {
calls := make([]map[string]any, 0, len(m.ToolCalls))
open = open[:0]
for j, tc := range m.ToolCalls {
id := tc.ID
if id == "" {
id = fmt.Sprintf("call_%d_%d", i, j)
}
args := string(bytes.TrimSpace(tc.Function.Arguments))
var str string
switch {
case args == "" || args == "null":
args = "{}"
case json.Unmarshal(tc.Function.Arguments, &str) == nil:
// already a JSON string, as a Chat client sends them
args = str
}
calls = append(calls, map[string]any{"id": id, "type": "function",
"function": map[string]any{"name": tc.Function.Name, "arguments": args}})
open = append(open, call{id, tc.Function.Name})
}
msg["tool_calls"] = calls
if m.Content == "" {
msg["content"] = nil
}
}
out = append(out, msg)
case "tool":
id := m.ToolCallID
pick := -1
for j, c := range open {
if id != "" && c.id == id || id == "" && m.ToolName != "" && c.name == m.ToolName {
pick = j
break
}
}
if pick < 0 && id == "" && len(open) > 0 {
pick = 0
}
if pick >= 0 {
id = open[pick].id
open = append(open[:pick], open[pick+1:]...)
}
if id == "" {
return nil, fmt.Errorf("messages[%d]: a tool result with no tool call before it", i)
}
out = append(out, map[string]any{"role": "tool", "tool_call_id": id, "content": m.Content})
if len(m.Images) > 0 {
// a Chat tool message carries text alone: its images go
// in a user message after it
out = append(out, map[string]any{"role": "user", "content": ollamaContent("", m.Images)})
}
default:
return nil, fmt.Errorf("messages[%d]: unknown role %q", i, m.Role)
}
}
return out, nil
}
// ollamaContent is a message's text with its images, which Ollama sends
// as bare base64, as Chat Completions content parts with data URLs.
func ollamaContent(text string, images []string) any {
if len(images) == 0 {
return text
}
parts := []map[string]any{}
if text != "" {
parts = append(parts, map[string]any{"type": "text", "text": text})
}
for _, img := range images {
url := img
if !strings.HasPrefix(img, "data:") {
url = "data:" + ollamaImageType(img) + ";base64," + img
}
parts = append(parts, map[string]any{"type": "image_url", "image_url": map[string]any{"url": url}})
}
return parts
}
// ollamaImageType is the media type of a base64 image, from its first
// bytes.
func ollamaImageType(b64 string) string {
head := b64
if len(head) > 64 {
head = head[:64]
}
raw, _ := base64.StdEncoding.DecodeString(head[:len(head)/4*4])
if t := http.DetectContentType(raw); strings.HasPrefix(t, "image/") {
return t
}
return "image/png"
}
func ollamaNow() string { return time.Now().UTC().Format(time.RFC3339Nano) }
// ollamaWriter takes what the Chat Completions handler writes, a stream of
// chunks or one completion or an error, and writes it to w as Ollama
// would have.
type ollamaWriter struct {
w http.ResponseWriter
header http.Header
model string
generate bool
stream bool
noThinking bool
start time.Time
status int
sse bool
buf []byte // a partial SSE line, or the whole body when it isn't a stream
started bool // the reply's own status and first line are written
done bool
content, thinking strings.Builder
calls []*ollamaToolCall
args []strings.Builder
finishReason string
promptTokens int
outputTokens int
firstToken time.Time
}
func (o *ollamaWriter) Header() http.Header { return o.header }
func (o *ollamaWriter) Unwrap() http.ResponseWriter { return o.w }
func (o *ollamaWriter) WriteHeader(code int) {
if o.status != 0 {
return
}
o.status = code
o.sse = strings.HasPrefix(o.header.Get("Content-Type"), "text/event-stream")
// what says why it waits or failed (Retry-After, magpie's own marks)
// reaches the client as it would on /v1
for k, vs := range o.header {
if k == "Retry-After" || strings.HasPrefix(k, "X-") {
o.w.Header()[k] = vs
}
}
}
func (o *ollamaWriter) Write(p []byte) (int, error) {
if o.status == 0 {
o.WriteHeader(http.StatusOK)
}
o.buf = append(o.buf, p...)
if !o.sse || o.status >= 300 {
return len(p), nil
}
for {
i := bytes.IndexByte(o.buf, '\n')
if i < 0 {
break
}
line := strings.TrimRight(string(o.buf[:i]), "\r")
o.buf = o.buf[i+1:]
o.sseLine(line)
}
return len(p), nil
}
func (o *ollamaWriter) Flush() {
if f, ok := o.w.(http.Flusher); ok && o.started {
f.Flush()
}
}
// sseLine takes one line of a Chat Completions stream.
func (o *ollamaWriter) sseLine(line string) {
data, ok := strings.CutPrefix(line, "data:")
if !ok {
return
}
data = strings.TrimSpace(data)
if data == "" || data == "[DONE]" {
return
}
if e := gjson.Get(data, "error"); e.Exists() {
msg := e.Get("message").String()
if msg == "" {
msg = e.String()
}
o.line(map[string]any{"error": msg})
o.done = true
return
}
o.chunk(gjson.Parse(data))
}
// chunk takes one stream chunk, or a whole completion (its message where
// a chunk has its delta), and writes what it adds when streaming.
func (o *ollamaWriter) chunk(c gjson.Result) {
if u := c.Get("usage"); u.IsObject() {
o.promptTokens, o.outputTokens = int(u.Get("prompt_tokens").Int()), int(u.Get("completion_tokens").Int())
}
ch := c.Get("choices.0")
if !ch.Exists() {
return
}
d := ch.Get("delta")
if !d.Exists() {
d = ch.Get("message")
}
text := d.Get("content").String()
think := d.Get("reasoning_content").String()
if think == "" {
think = d.Get("reasoning").String()
}
if o.noThinking {
think = ""
}
for _, tc := range d.Get("tool_calls").Array() {
i := len(o.calls)
if idx := tc.Get("index"); idx.Exists() {
i = int(idx.Int())
}
for len(o.calls) <= i {
o.calls = append(o.calls, &ollamaToolCall{})
o.args = append(o.args, strings.Builder{})
}
if id := tc.Get("id").String(); id != "" {
o.calls[i].ID = id
}
if n := tc.Get("function.name").String(); n != "" {
o.calls[i].Function.Name = n
}
o.args[i].WriteString(tc.Get("function.arguments").String())
}
if f := ch.Get("finish_reason").String(); f != "" {
o.finishReason = f
}
if text == "" && think == "" {
return
}
if o.firstToken.IsZero() {
o.firstToken = time.Now()
}
o.content.WriteString(text)
o.thinking.WriteString(think)
if o.stream {
o.line(o.part(text, think, nil, false))
}
}
// part is one line of Ollama's reply.
func (o *ollamaWriter) part(text, think string, calls []ollamaToolCall, done bool) map[string]any {
out := map[string]any{"model": o.model, "created_at": ollamaNow(), "done": done}
if o.generate {
out["response"] = text
if think != "" {
out["thinking"] = think
}
} else {
msg := map[string]any{"role": "assistant", "content": text}
if think != "" {
msg["thinking"] = think
}
if len(calls) > 0 {
msg["tool_calls"] = calls
}
out["message"] = msg
}
if done {
reason := "stop"
if o.finishReason == "length" {
reason = "length"
}
end := time.Now()
first := o.firstToken
if first.IsZero() {
first = end
}
out["done_reason"] = reason
out["total_duration"] = end.Sub(o.start).Nanoseconds()
out["load_duration"] = 0
out["prompt_eval_count"] = o.promptTokens
out["prompt_eval_duration"] = first.Sub(o.start).Nanoseconds()
out["eval_count"] = o.outputTokens
out["eval_duration"] = end.Sub(first).Nanoseconds()
}
return out
}
// toolCalls are the calls the reply made, their arguments as objects.
func (o *ollamaWriter) toolCalls() []ollamaToolCall {
var out []ollamaToolCall
for i, c := range o.calls {
if c.Function.Name == "" {
continue
}
tc := *c
tc.Function.Index = i
if tc.ID == "" {
tc.ID = fmt.Sprintf("call_%d", i)
}
args := strings.TrimSpace(o.args[i].String())
if args == "" || !json.Valid([]byte(args)) {
if args != "" {
// what a model wrote that isn't JSON is kept, as a string
b, _ := json.Marshal(args)
args = string(b)
} else {
args = "{}"
}
}
tc.Function.Arguments = json.RawMessage(args)
out = append(out, tc)
}
return out
}
// line writes one NDJSON line, the reply's status and type first.
func (o *ollamaWriter) line(v any) {
if !o.started {
o.started = true
o.w.Header().Set("Content-Type", "application/x-ndjson")
o.w.WriteHeader(http.StatusOK)
}
b, _ := json.Marshal(v)
o.w.Write(append(b, '\n'))
o.Flush()
}
// finish writes the end of the reply, once the Chat handler is done.
func (o *ollamaWriter) finish() {
if o.status == 0 {
o.status = http.StatusOK
}
if o.status >= 300 {
msg := gjson.GetBytes(o.buf, "error.message").String()
if msg == "" {
msg = gjson.GetBytes(o.buf, "error").String()
}
if msg == "" {
msg = strings.TrimSpace(string(o.buf))
}
if msg == "" {
msg = http.StatusText(o.status)
}
if o.started {
o.line(map[string]any{"error": msg})
} else {
ollamaError(o.w, o.status, msg)
}
return
}
if !o.sse {
// one completion, as asked with stream false
o.chunk(gjson.ParseBytes(o.buf))
o.buf = nil
} else if len(o.buf) > 0 {
o.sseLine(strings.TrimRight(string(o.buf), "\r"))
}
if o.done {
return
}
calls := o.toolCalls()
if o.stream {
if len(calls) > 0 {
o.line(o.part("", "", calls, false))
}
o.line(o.part("", "", nil, true))
return
}
writeJSON(o.w, 200, o.part(o.content.String(), o.thinking.String(), calls, true))
}
+248
View File
@@ -0,0 +1,248 @@
package gateway
import (
"bufio"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
)
// ollamaUpstream is a Chat Completions provider that keeps each request
// it is sent in *got (when got isn't nil) and answers with reasoning,
// text and a tool call split over chunks, then usage, streamed or whole
// as asked.
func ollamaUpstream(t *testing.T, got *[]string) *httptest.Server {
t.Helper()
var mu sync.Mutex
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
if got != nil {
mu.Lock()
*got = append(*got, string(b))
mu.Unlock()
}
if !gjson.GetBytes(b, "stream").Bool() {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"seer","choices":[{"index":0,"message":{"role":"assistant","content":"whole answer","reasoning_content":"pondered","tool_calls":[{"id":"call_up","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"a.go\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":11,"completion_tokens":7}}`)
return
}
w.Header().Set("Content-Type", "text/event-stream")
for _, c := range []string{
`{"choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"let me "}}]}`,
`{"choices":[{"index":0,"delta":{"reasoning_content":"think"}}]}`,
`{"choices":[{"index":0,"delta":{"content":"Hello"}}]}`,
`{"choices":[{"index":0,"delta":{"content":", world"}}]}`,
`{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_up","type":"function","function":{"name":"read_file","arguments":"{\"pa"}}]}}]}`,
`{"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"th\":\"a.go\"}"}}]}}]}`,
`{"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
`{"choices":[],"usage":{"prompt_tokens":11,"completion_tokens":7}}`,
} {
io.WriteString(w, "data: "+c+"\n\n")
w.(http.Flusher).Flush()
}
io.WriteString(w, "data: [DONE]\n\n")
}))
t.Cleanup(up.Close)
return up
}
// ollamaCall posts body to path as a client on this computer would, through
// the whole guarded stack.
func ollamaCall(t *testing.T, h http.Handler, path, body string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest("POST", path, strings.NewReader(body))
r.RemoteAddr, r.Host = "127.0.0.1:50123", "127.0.0.1:3425"
r.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// ndjson is each line of an NDJSON reply.
func ndjson(t *testing.T, body string) []gjson.Result {
t.Helper()
var out []gjson.Result
sc := bufio.NewScanner(strings.NewReader(body))
for sc.Scan() {
if !json.Valid(sc.Bytes()) {
t.Fatalf("not a JSON line: %q in %s", sc.Text(), body)
}
out = append(out, gjson.Parse(sc.Text()))
}
return out
}
// Zed's Ollama provider (super_lalalalala on Discord) chats on
// /api/chat, which magpie answered 404: it is served now, as
// /v1/chat/completions is, with Zed's own request (crates/ollama
// ChatRequest: stream true, keep_alive, options num_ctx/num_predict/
// temperature, think, tools; an assistant's tool call with an id, a tool
// result named by tool_name alone; a user image as bare base64). The
// provider is sent it as Chat Completions, and the reply comes back as
// Ollama's NDJSON: thinking and text as they arrive, the tool call whole
// with its arguments an object and an id, and a last done line with the
// reason and the token counts.
func TestOllamaChatStreams(t *testing.T) {
fresh(t)
var got []string
ollamaPlan(t, ollamaUpstream(t, &got).URL+"/v1")
h := lanGuard(New().Handler())
const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
body := `{"model":"plan/seer","messages":[` +
`{"role":"system","content":"You are Zed."},` +
`{"role":"user","content":"look","images":["` + png + `"]},` +
`{"role":"assistant","content":"","tool_calls":[{"id":"t1","function":{"name":"read_file","arguments":{"path":"x.go"}}},{"function":{"name":"grep","arguments":{"q":"y"}}}],"thinking":"hm"},` +
`{"role":"tool","tool_name":"grep","content":"no match"},` +
`{"role":"tool","tool_name":"read_file","content":"package x"}` +
`],"stream":true,"keep_alive":"5m","options":{"num_ctx":32768,"num_predict":512,"temperature":0.3,"top_k":40,"stop":["</end>"]},` +
`"tools":[{"type":"function","function":{"name":"read_file","description":"Read","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}}],"think":true}`
w := ollamaCall(t, h, "/api/chat", body)
if w.Code != 200 || w.Header().Get("Content-Type") != "application/x-ndjson" {
t.Fatalf("chat: %d %s %s", w.Code, w.Header().Get("Content-Type"), w.Body)
}
if len(got) != 1 {
t.Fatalf("upstream asked %d times", len(got))
}
up := gjson.Parse(got[0])
for k, want := range map[string]string{
"model": "seer", "stream": "true", "stream_options.include_usage": "true", "max_tokens": "512", "temperature": "0.3", "stop.0": "</end>",
"messages.0.role": "system", "messages.0.content": "You are Zed.",
"messages.1.content.0.text": "look", "messages.1.content.1.image_url.url": "data:image/png;base64," + png,
"messages.2.tool_calls.0.id": "t1", "messages.2.tool_calls.0.function.arguments": `{"path":"x.go"}`,
"messages.2.tool_calls.1.function.name": "grep", "messages.2.reasoning_content": "hm",
"messages.3.role": "tool", "messages.3.content": "no match",
"messages.4.tool_call_id": "t1", "messages.4.content": "package x",
"tools.0.function.name": "read_file",
} {
if g := up.Get(k).String(); g != want {
t.Errorf("upstream %s = %q, want %q (sent %s)", k, g, want, got[0])
}
}
if id := up.Get("messages.3.tool_call_id").String(); id == "" || id != up.Get("messages.2.tool_calls.1.id").String() {
t.Errorf("grep's result went with %q, its call has id %q", id, up.Get("messages.2.tool_calls.1.id"))
}
for _, k := range []string{"num_ctx", "top_k", "keep_alive", "options", "think", "images"} {
if up.Get(k).Exists() {
t.Errorf("upstream was sent Ollama's own %s: %s", k, got[0])
}
}
lines := ndjson(t, w.Body.String())
var text, think string
var calls []gjson.Result
for _, l := range lines[:len(lines)-1] {
if l.Get("done").Bool() || l.Get("model").String() != "plan/seer" || l.Get("message.role").String() != "assistant" || !l.Get("message.content").Exists() || !l.Get("created_at").Exists() {
t.Fatalf("part %s", l.Raw)
}
text += l.Get("message.content").String()
think += l.Get("message.thinking").String()
calls = append(calls, l.Get("message.tool_calls").Array()...)
}
if text != "Hello, world" || think != "let me think" {
t.Errorf("text %q thinking %q", text, think)
}
if len(calls) != 1 || calls[0].Get("id").String() != "call_up" || calls[0].Get("function.name").String() != "read_file" || calls[0].Get("function.arguments").Raw != `{"path":"a.go"}` {
t.Errorf("tool calls %v", calls)
}
last := lines[len(lines)-1]
if !last.Get("done").Bool() || last.Get("done_reason").String() != "stop" || last.Get("prompt_eval_count").Int() != 11 || last.Get("eval_count").Int() != 7 || last.Get("message.content").String() != "" {
t.Errorf("done line %s", last.Raw)
}
}
// "stream": false gets one JSON object, the whole reply in it; and with
// think false a model's reasoning isn't told.
func TestOllamaChatWhole(t *testing.T) {
fresh(t)
var got []string
ollamaPlan(t, ollamaUpstream(t, &got).URL+"/v1")
h := lanGuard(New().Handler())
w := ollamaCall(t, h, "/api/chat", `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}],"stream":false,"format":"json","think":"high"}`)
if w.Code != 200 || len(got) != 1 {
t.Fatalf("chat: %d %s (upstream %d)", w.Code, w.Body, len(got))
}
if up := gjson.Parse(got[0]); up.Get("stream").Bool() || up.Get("response_format.type").String() != "json_object" || up.Get("reasoning_effort").String() != "high" {
t.Errorf("upstream sent %s", got[0])
}
r := gjson.Parse(w.Body.String())
if !r.Get("done").Bool() || r.Get("message.content").String() != "whole answer" || r.Get("message.thinking").String() != "pondered" ||
r.Get("message.tool_calls.0.function.arguments.path").String() != "a.go" || r.Get("eval_count").Int() != 7 || strings.Count(w.Body.String(), "\n") > 1 {
t.Errorf("whole reply %s", w.Body)
}
w = ollamaCall(t, h, "/api/chat", `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}],"stream":false,"think":false}`)
if r := gjson.Parse(w.Body.String()); w.Code != 200 || r.Get("message.thinking").Exists() || r.Get("message.content").String() != "whole answer" {
t.Errorf("think false: %d %s", w.Code, w.Body)
}
}
// /api/generate takes a prompt, a system prompt and images, and answers
// in "response", streamed or whole; the ollama CLI's name:latest for a
// model with no tag is the model.
func TestOllamaGenerate(t *testing.T) {
fresh(t)
var got []string
ollamaPlan(t, ollamaUpstream(t, &got).URL+"/v1")
h := lanGuard(New().Handler())
w := ollamaCall(t, h, "/api/generate", `{"model":"plan/seer:latest","prompt":"why is the sky blue","system":"be brief","images":["/9j/4AAQSkZJRgABAQ=="],"options":{"seed":7,"top_p":0.9,"num_predict":-1}}`)
if w.Code != 200 || len(got) != 1 {
t.Fatalf("generate: %d %s", w.Code, w.Body)
}
up := gjson.Parse(got[0])
if up.Get("model").String() != "seer" || up.Get("messages.0.content").String() != "be brief" || up.Get("messages.1.content.0.text").String() != "why is the sky blue" ||
!strings.HasPrefix(up.Get("messages.1.content.1.image_url.url").String(), "data:image/jpeg;base64,") || up.Get("seed").Int() != 7 || up.Get("top_p").Float() != 0.9 || up.Get("max_tokens").Exists() {
t.Errorf("upstream sent %s", got[0])
}
lines := ndjson(t, w.Body.String())
var text string
for _, l := range lines {
if l.Get("message").Exists() {
t.Fatalf("generate answered with a message: %s", l.Raw)
}
text += l.Get("response").String()
}
if text != "Hello, world" || !lines[len(lines)-1].Get("done").Bool() {
t.Errorf("generate streamed %s", w.Body)
}
w = ollamaCall(t, h, "/api/generate", `{"model":"plan/seer","prompt":"hi","stream":false}`)
if r := gjson.Parse(w.Body.String()); w.Code != 200 || r.Get("response").String() != "whole answer" || !r.Get("done").Bool() {
t.Errorf("generate whole: %d %s", w.Code, w.Body)
}
// nothing to say: the model loaded, as a client warms it up
w = ollamaCall(t, h, "/api/generate", `{"model":"plan/seer"}`)
if r := gjson.Parse(w.Body.String()); w.Code != 200 || r.Get("done_reason").String() != "load" || len(got) != 2 {
t.Errorf("generate with no prompt: %d %s (upstream %d)", w.Code, w.Body, len(got))
}
}
// A model magpie doesn't serve, and a provider's refusal, are told as
// Ollama tells an error: {"error": "…"} with the status.
func TestOllamaChatErrors(t *testing.T) {
fresh(t)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, `{"error":{"message":"context too long for seer","type":"invalid_request_error"}}`)
}))
defer up.Close()
ollamaPlan(t, up.URL+"/v1")
h := lanGuard(New().Handler())
for _, path := range []string{"/api/chat", "/api/generate"} {
w := ollamaCall(t, h, path, `{"model":"nowhere/none","messages":[{"role":"user","content":"hi"}],"prompt":"hi"}`)
if e := gjson.Get(w.Body.String(), "error"); w.Code < 400 || e.Type != gjson.String || e.String() == "" {
t.Errorf("%s, unknown model: %d %s", path, w.Code, w.Body)
}
w = ollamaCall(t, h, path, `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}],"prompt":"hi"}`)
if e := gjson.Get(w.Body.String(), "error"); w.Code != 400 || e.Type != gjson.String || !strings.Contains(e.String(), "context too long") {
t.Errorf("%s, refused: %d %s", path, w.Code, w.Body)
}
}
if w := ollamaCall(t, h, "/api/chat", `{"model":"plan/seer","messages":[{"role":"tool","content":"orphan"}]}`); w.Code != 400 || gjson.Get(w.Body.String(), "error").Type != gjson.String {
t.Errorf("a tool result with no call: %d %s", w.Code, w.Body)
}
}
+30 -3
View File
@@ -10,6 +10,7 @@ import (
"strings"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
@@ -110,6 +111,14 @@ func TestOllamaModelRoutes(t *testing.T) {
t.Fatalf("model_info %s: %v", k, s.ModelInfo[k])
}
}
// "ollama run plan/plain" asks for plan/plain:latest, and pulls the
// model when show says it isn't there
if c, s := show(`{"model":"plan/plain:latest"}`); c != 200 || !slices.Equal(s.Capabilities, []string{"completion", "tools"}) {
t.Fatalf("show plain:latest: %d %+v", c, s)
}
if c, _ := show(`{"model":"plan/nothing:latest"}`); c != 404 {
t.Fatal("an unknown model:latest:", c)
}
if c, _ := show(`{"model":"plan/nothing"}`); c != 404 {
t.Fatal("an unknown model:", c)
}
@@ -119,10 +128,11 @@ func TestOllamaModelRoutes(t *testing.T) {
}
// A gateway key held to some models is listed and shown those alone on the
// Ollama routes, as on /v1/models.
// Ollama routes, as on /v1/models, and chats on /api/chat and
// /api/generate with those alone, as on /v1/chat/completions.
func TestOllamaRoutesHoldAKey(t *testing.T) {
fresh(t)
ollamaPlan(t, "http://127.0.0.1:1/v1")
ollamaPlan(t, ollamaUpstream(t, nil).URL+"/v1")
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/plain"}}); err != nil {
t.Fatal(err)
@@ -144,6 +154,21 @@ func TestOllamaRoutesHoldAKey(t *testing.T) {
if w := do("POST", "/api/show", `{"model":"plan/plain"}`); w.Code != 200 {
t.Fatalf("held key's own model: %d %s", w.Code, w.Body)
}
v1 := do("POST", "/v1/chat/completions", `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}]}`)
if v1.Code == 200 {
t.Fatalf("held key chatted with a model it may not use on /v1: %s", v1.Body)
}
for _, rt := range [][2]string{
{"/api/chat", `{"model":"%s","messages":[{"role":"user","content":"hi"}],"stream":false}`},
{"/api/generate", `{"model":"%s","prompt":"hi","stream":false}`},
} {
if w := do("POST", rt[0], fmt.Sprintf(rt[1], "plan/seer")); w.Code != v1.Code || gjson.Get(w.Body.String(), "error").Type != gjson.String {
t.Fatalf("%s: held key with a model it may not use: %d %s, want %d as /v1 and Ollama's error", rt[0], w.Code, w.Body, v1.Code)
}
if w := do("POST", rt[0], fmt.Sprintf(rt[1], "plan/plain")); w.Code != 200 || !strings.Contains(w.Body.String(), `"done":true`) {
t.Fatalf("%s: held key's own model: %d %s", rt[0], w.Code, w.Body)
}
}
}
// The Ollama routes are guarded as every gateway route is, through the
@@ -157,12 +182,14 @@ func TestOllamaRoutesGuarded(t *testing.T) {
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
ollamaPlan(t, "http://127.0.0.1:1/v1")
ollamaPlan(t, ollamaUpstream(t, nil).URL+"/v1")
srv := lanGuard(New().Handler())
routes := []struct{ method, path, body string }{
{"GET", "/api/version", ""},
{"GET", "/api/tags", ""},
{"POST", "/api/show", `{"model":"plan/seer"}`},
{"POST", "/api/chat", `{"model":"plan/seer","messages":[{"role":"user","content":"hi"}],"stream":false}`},
{"POST", "/api/generate", `{"model":"plan/seer","prompt":"hi","stream":false}`},
}
const gw = "127.0.0.1:3425"
browser := []string{"User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15",