gateway: answers as an Ollama server, so Copilot in Visual Studio and VS Code lists magpie's models when given the gateway as its Ollama URL (wani on Discord)

Visual Studio 2026's Copilot (Agent preview, bring your own model) takes a
custom endpoint only for OpenAI and Ollama. wani's OpenAI attempt failed
with "Session was not created with authentication info or custom
provider". That error comes from the Copilot runtime in VS: the session was
created without a GitHub token or a BYOK provider config, and nothing
reaches magpie, so magpie can't fix it.

What an Ollama client needs, read from vscode-copilot-chat's
src/extension/byok/vscode-node/ollamaProvider.ts (5863f5a):
- GET /api/version, which must be at least 0.6.4, or no model is listed;
- GET /api/tags, from which it takes each model's "model";
- POST /api/show of each. A model without "capabilities" is skipped. The
  window is model_info["<general.architecture>.context_length"] ?? 32768,
  and the name is general.basename;
- chat on <url>/v1/chat/completions, streamed, with an empty
  "Authorization: Bearer ". magpie already serves that.
It never calls /api/chat. The Copilot SDK under Visual Studio's agent
treats Ollama as an OpenAI API at <url>/v1 too.

ollama.go serves these three routes on Handler's mux, so every guard
/v1/* has covers them too:
- lanGuard: LAN sharing, a gateway key, rebound Host, forwarded loopback;
- corsGuard: a foreign Origin, Origin null and *.localhost;
- a key held to some models: catalogFor/keyAllowed.

/api/show tells:
- capabilities: completion and tools, plus vision from Images and thinking
  from Thinks;
- the window, or 32768 when magpie doesn't know it, since VS Code would
  take a 0;
- general.parameter_count and magpie.embedding_length, because the ollama
  CLI 0.6.8's "ollama show" read them unchecked and panicked without them.
  The real CLI found this.
/api/chat and /api/generate are not served, so "ollama run" doesn't work.

Tests (internal/gateway/ollama_test.go; lan_test.go lists the routes):
- TestOllamaModelRoutes, TestOllamaRoutesHoldAKey, TestOllamaRoutesGuarded
  and TestOllamaClientChats each fail with 404 without the routes.
- Broken by hand, each went red:
  - tags from provider.Catalog() instead of catalogFor: HoldAKey;
  - vision dropped: ModelRoutes;
  - corsGuard skipping /api/: Guarded (200 for a foreign page, Origin
    null and a localhost subdomain);
  - an unknown window told as 0: ModelRoutes;
  - parameter_count and embedding_length left out: ModelRoutes.

Real use, in a sandbox HOME with MAGPIE_NO_ACCOUNTS=1:
- a nogui build on 127.0.0.1:3561, with a custom provider on a fake
  OpenAI upstream (python, 127.0.0.1:3562);
- the real ollama 0.6.8 CLI with OLLAMA_HOST at it: "ollama --version"
  (server 0.12.6), "ollama list" (both models) and "ollama show" all
  worked. Before the model_info fix, show panicked;
- curl replaying VS Code's sequence (version, tags, show, then a streamed
  /v1/chat/completions with an empty Bearer and VS Code's body) streamed
  the upstream's reply, and the upstream got its own key;
- on the same server, a foreign Origin, Origin null and a rebound Host all
  got 403.

Not tried:
- Visual Studio 2026 itself (no Windows VS here);
- VS Code's Copilot itself (VS Code isn't installed);
- JetBrains' Ollama client, which likely needs /api/chat.

Run at this head (macOS):
- gofmt -l .: nothing;
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet
  ./...: clean;
- go test -timeout 45m ./... at e89d6a4f9, load ~300 to 400: 59 packages
  ok. These failed:
  - internal/agent, internal/gateway and internal/library ran past 45m
    (#2544, #2870, #2853);
  - TestClaudeAccountsSpentFallBackToCodex in gateway (#2858);
  - TestSetAnswersWhileDevinAndProvidersHang in gui, at 16s against its
    bound (#1375);
  - TestGatewayHookMixedPiPackage in plugin, starting plugins after 742s
    (#2865).
  Rerun alone:
  - gui's and plugin's tests: ok (gui 35s, plugin 499s);
  - internal/agent ok (2580s), internal/library ok (1112s);
  - internal/gateway in two halves by test name, each ok (1406s and
    1030s). Whole, it timed out again at 45m while starting
    TestRouteKeepsItsFolderShort, not stuck.
No GUI file changed.
This commit is contained in:
yetone
2026-10-19 22:32:37 +08:00
parent c863904338
commit 94df239265
8 changed files with 456 additions and 1 deletions
+11
View File
@@ -1693,6 +1693,7 @@ It exposes:
| `/v1/audio/transcriptions`, `/v1/audio/translations` | OpenAI speech to text (multipart, passed through) |
| `/v1/models`, `/v1beta/models` | the catalog |
| `/v1/codex/models` | the catalog as Codex's `model_catalog_url` reads it ([Codex on another computer](#providers-and-the-gateway)) |
| `/api/version`, `/api/tags`, `/api/show` | the catalog as an Ollama server lists it, for a client that takes a custom endpoint only as Ollama (below) |
Each `/v1/models` entry includes `reasoning` and `supported_reasoning_levels`
(`[{"effort":"low"}, ...]`), and the same levels as plain names in
@@ -1709,6 +1710,16 @@ what the agent asked, as before. `native_endpoints`
straight through on; it is left out of a routing group, and of a model every
request to which is translated anyway.
A client that takes a custom endpoint only as an Ollama server (Visual
Studio's and VS Code's Copilot: Manage Models, then Ollama) is given
`http://127.0.0.1:3425` as the Ollama URL, no `/v1`. It reads the models
from `/api/tags`, each one's tools, vision, thinking and window from
`/api/show`, and chats on `/v1/chat/completions`. Ollama's own chat
(`/api/chat`, `/api/generate`, so `ollama run`) isn't served. Copilot sends
no key, so this works on this computer only; behind a reverse proxy with a
single public URL, `/api` goes to `magpie web`'s page, so give the
gateway's own port.
Requests pass straight through when the vendor speaks the agent's API and
are translated otherwise, streaming, tool calls and reasoning included. The
key is `magpie` (any value works; the gateway only listens on loopback), and
File diff suppressed because one or more lines are too long
+5
View File
@@ -628,6 +628,11 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/hello", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"name": "magpie", "version": Version})
})
// the Ollama API's model routes, for a client that takes a custom
// endpoint only as an Ollama server (ollama.go)
mux.HandleFunc("GET /api/version", s.ollamaVersion)
mux.HandleFunc("GET /api/tags", s.ollamaTags)
mux.HandleFunc("POST /api/show", s.ollamaShow)
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)
+1
View File
@@ -332,6 +332,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) {
routes := [][2]string{
{"GET", "/"}, {"GET", "/v1"}, {"GET", "/v1/models"}, {"GET", "/models"}, {"GET", "/v1/models/x"},
{"GET", "/muse-code/models"}, {"GET", "/api/hello"},
{"GET", "/api/version"}, {"GET", "/api/tags"}, {"POST", "/api/show"},
{"GET", "/v1/magpie/quotas"}, {"GET", "/v1/magpie/quotas/history"},
{"GET", provider.RemoteCardsPath}, {"POST", provider.RemoteRefreshPath},
{"GET", "/v1/magpie/route?session=s"}, {"GET", "/v1/magpie/concurrency"}, {"GET", "/v1/magpie/limit"},
+159
View File
@@ -0,0 +1,159 @@
package gateway
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// The Ollama API's model routes, for a client that takes a custom endpoint
// only as an Ollama server (Visual Studio's Copilot BYOK, wani on Discord;
// VS Code's Copilot "Ollama" provider): the user enters the gateway's own
// address (http://127.0.0.1:3425) as the Ollama endpoint. VS Code's
// Copilot (vscode-copilot-chat, ollamaProvider.ts) asks /api/version and
// refuses a server older than 0.6.4, lists /api/tags and takes each
// model's "model", asks /api/show of each (a model whose show fails or
// has no capabilities is left out), and chats on the server's
// OpenAI-compatible /v1/chat/completions, which magpie serves already.
// These routes sit on Handler's mux, so lanGuard, corsGuard and the key
// limits judge them as every route.
// ollamaVersion is the Ollama release magpie answers /api/version as: one
// past every client's minimum (VS Code's Copilot asks 0.6.4).
const ollamaVersion = "0.12.6"
func (s *Server) ollamaVersion(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"version": ollamaVersion})
}
// ollamaTags lists the models the agent asking is shown, as Ollama's
// /api/tags lists the pulled ones: name and model are magpie's id, which
// the client sends back as the model to chat with.
func (s *Server) ollamaTags(w http.ResponseWriter, r *http.Request) {
models := []map[string]any{}
for _, e := range catalogFor(r) {
models = append(models, map[string]any{
"name": e.ID, "model": e.ID, "modified_at": ollamaModified, "size": 0,
"digest": ollamaDigest(e.ID), "details": ollamaDetails(e), "capabilities": ollamaCapabilities(e),
})
}
writeJSON(w, 200, map[string]any{"models": models})
}
// 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
// without it) and its name from "general.basename".
func (s *Server) ollamaShow(w http.ResponseWriter, r *http.Request) {
body, ok := s.requestBody(w, r, provider.Chat)
if !ok {
return
}
var req struct {
Model string `json:"model"`
Name string `json:"name"` // what clients before Ollama 0.5 send
}
if err := json.Unmarshal(body, &req); err != nil {
ollamaError(w, http.StatusBadRequest, "invalid request: "+err.Error())
return
}
id := strings.TrimSpace(req.Model)
if id == "" {
id = strings.TrimSpace(req.Name)
}
if id == "" {
ollamaError(w, http.StatusBadRequest, "model is required")
return
}
e, ok := ollamaEntry(r, id)
if !ok {
ollamaError(w, http.StatusNotFound, "model '"+id+"' not found")
return
}
// every key here is sent: the ollama CLI before 0.7 reads
// parameter_count, context_length and embedding_length without
// checking them and panics on one missing ("ollama show", 0.6.8)
window := e.Context
if window <= 0 {
// what VS Code's Copilot assumes without one; a 0 it would take
// as the window
window = ollamaDefaultContext
}
info := map[string]any{
"general.architecture": ollamaArch, "general.basename": provider.Labels([]provider.Entry{e})[0],
"general.parameter_count": 0, ollamaArch + ".context_length": window, ollamaArch + ".embedding_length": 0,
}
writeJSON(w, 200, map[string]any{
"modelfile": "", "parameters": "", "template": "",
"details": ollamaDetails(e), "model_info": info, "capabilities": ollamaCapabilities(e),
"modified_at": ollamaModified,
})
}
// ollamaCapabilities are what the model does, in Ollama's words: it
// completes and calls tools (every model magpie serves is asked with
// tools), sees when it takes images, and thinks when it reasons.
func ollamaCapabilities(e provider.Entry) []string {
caps := []string{"completion", "tools"}
if e.Images {
caps = append(caps, "vision")
}
if e.Thinks() {
caps = append(caps, "thinking")
}
return caps
}
// ollamaArch is the architecture every model is told as: model_info's
// keys are named after it.
const ollamaArch = "magpie"
// ollamaDefaultContext is the window told for a model whose own magpie
// doesn't know: the one VS Code's Copilot takes when none is told.
const ollamaDefaultContext = 32768
// ollamaModified stands in for when a model was pulled, which no model
// here was.
const ollamaModified = "2025-01-01T00:00:00Z"
// ollamaEntry is the model id names among those the caller is shown (a
// gateway key held to some models is shown those alone): by its catalog
// id, or its bare id when the user lists bare ids.
func ollamaEntry(r *http.Request, id string) (provider.Entry, bool) {
shown := catalogFor(r)
id = unprefixed(id)
for _, e := range shown {
if e.ID == id {
return e, true
}
}
if provider.BareModelIDs() {
return provider.BareEntry(shown, id)
}
return provider.Entry{}, false
}
func ollamaDetails(e provider.Entry) map[string]any {
d := map[string]any{"parent_model": "", "format": "", "family": ollamaArch, "families": []string{ollamaArch},
"parameter_size": "", "quantization_level": ""}
if e.Context > 0 {
d["context_length"] = e.Context
}
return d
}
// ollamaDigest stands in for a model file's digest: the same id always
// gives the same one.
func ollamaDigest(id string) string {
sum := sha256.Sum256([]byte(id))
return hex.EncodeToString(sum[:])
}
// ollamaError is an error as Ollama's API says one.
func ollamaError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]any{"error": msg})
}
+277
View File
@@ -0,0 +1,277 @@
package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// ollamaPlan is a provider with a model that sees, thinks and has a
// window, and one that does none of these, for the Ollama routes to tell
// of.
func ollamaPlan(t *testing.T, chat string) {
t.Helper()
yes, no := true, false
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: chat,
Models: []string{"seer", "plain"}, Contexts: map[string]int{"seer": 400000}}); err != nil {
t.Fatal(err)
}
for _, err := range []error{
provider.SetModelImage("plan/seer", &yes), provider.SetModelImage("plan/plain", &no),
provider.SetModelEfforts("plan/seer", []string{"low", "high"}),
} {
if err != nil {
t.Fatal(err)
}
}
}
// A client that takes a custom endpoint only as an Ollama server (Visual
// Studio's Copilot BYOK, wani on Discord; VS Code's Copilot Ollama
// provider) asks /api/version, lists /api/tags and reads each model's
// capabilities and window from /api/show, then chats on
// /v1/chat/completions. The list is magpie's catalog by its ids, and a
// model's window and what it takes are its catalog entry's.
func TestOllamaModelRoutes(t *testing.T) {
fresh(t)
ollamaPlan(t, "http://127.0.0.1:1/v1")
h := New().Handler()
do := func(method, path, body string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest(method, path, strings.NewReader(body))
r.RemoteAddr = "127.0.0.1:50123"
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
if w := do("GET", "/api/version", ""); w.Code != 200 || !strings.Contains(w.Body.String(), `"version":"`+ollamaVersion+`"`) {
t.Fatalf("version: %d %s", w.Code, w.Body)
}
var tags struct {
Models []struct {
Name, Model, Digest string
Details struct{ Family string }
}
}
w := do("GET", "/api/tags", "")
if err := json.Unmarshal(w.Body.Bytes(), &tags); err != nil || w.Code != 200 {
t.Fatalf("tags: %d %s", w.Code, w.Body)
}
var names []string
for _, m := range tags.Models {
if m.Name != m.Model || len(m.Digest) != 64 {
t.Fatalf("tag %+v", m)
}
names = append(names, m.Name)
}
if !slices.Contains(names, "plan/seer") || !slices.Contains(names, "plan/plain") {
t.Fatalf("tags list %v", names)
}
type shown struct {
Capabilities []string
ModelInfo map[string]any `json:"model_info"`
}
show := func(body string) (int, shown) {
t.Helper()
w := do("POST", "/api/show", body)
var s shown
if w.Code == 200 {
if err := json.Unmarshal(w.Body.Bytes(), &s); err != nil {
t.Fatal(w.Body.String())
}
}
return w.Code, s
}
c, s := show(`{"model":"plan/seer"}`)
arch, _ := s.ModelInfo["general.architecture"].(string)
if c != 200 || !slices.Equal(s.Capabilities, []string{"completion", "tools", "vision", "thinking"}) || s.ModelInfo[arch+".context_length"] != float64(400000) ||
!strings.Contains(fmt.Sprint(s.ModelInfo["general.basename"]), "seer") {
t.Fatalf("show seer: %d %+v", c, s)
}
// a client from before Ollama 0.5 names it "name"; a window magpie
// doesn't know is told as the one VS Code's Copilot assumes, never 0
c, s = show(`{"name":"plan/plain"}`)
if c != 200 || !slices.Equal(s.Capabilities, []string{"completion", "tools"}) || s.ModelInfo[arch+".context_length"] != float64(32768) {
t.Fatalf("show plain: %d %+v", c, s)
}
// the ollama CLI before 0.7 reads these as numbers unchecked, and
// panics on one missing ("ollama show" with 0.6.8)
for _, k := range []string{"general.parameter_count", arch + ".context_length", arch + ".embedding_length"} {
if _, ok := s.ModelInfo[k].(float64); !ok {
t.Fatalf("model_info %s: %v", k, s.ModelInfo[k])
}
}
if c, _ := show(`{"model":"plan/nothing"}`); c != 404 {
t.Fatal("an unknown model:", c)
}
if c, _ := show(`{}`); c != 400 {
t.Fatal("no model:", c)
}
}
// A gateway key held to some models is listed and shown those alone on the
// Ollama routes, as on /v1/models.
func TestOllamaRoutesHoldAKey(t *testing.T) {
fresh(t)
ollamaPlan(t, "http://127.0.0.1:1/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)
}
h := New().Handler()
do := func(method, path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, strings.NewReader(body))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
if w := do("GET", "/api/tags", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "plan/plain") || strings.Contains(w.Body.String(), "plan/seer") {
t.Fatalf("held key's tags: %d %s", w.Code, w.Body)
}
if w := do("POST", "/api/show", `{"model":"plan/seer"}`); w.Code != 404 {
t.Fatalf("held key shown a model it may not use: %d %s", w.Code, w.Body)
}
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)
}
}
// The Ollama routes are guarded as every gateway route is, through the
// real server stack: with no key, a page elsewhere, a sandboxed frame
// (Origin null), a page at a localhost subdomain, a page rebound to
// loopback under its own name, and another machine while magpie isn't
// shared or sends none are all refused, and none is told a model. An
// agent on this computer, and a keyed call, are answered.
func TestOllamaRoutesGuarded(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
ollamaPlan(t, "http://127.0.0.1:1/v1")
srv := lanGuard(New().Handler())
routes := []struct{ method, path, body string }{
{"GET", "/api/version", ""},
{"GET", "/api/tags", ""},
{"POST", "/api/show", `{"model":"plan/seer"}`},
}
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",
"Sec-Fetch-Mode", "no-cors", "Content-Type", "text/plain;charset=UTF-8"}
do := func(method, path, body, from, host string, hdr ...string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest(method, path, strings.NewReader(body))
r.RemoteAddr, r.Host = from, host
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
w := httptest.NewRecorder()
srv.ServeHTTP(w, r)
return w
}
refused := func(what string, w *httptest.ResponseRecorder, codes ...int) {
t.Helper()
if !slices.Contains(codes, w.Code) || strings.Contains(w.Body.String(), "plan/") || w.Header().Get("Access-Control-Allow-Origin") != "" {
t.Errorf("%s: %d %s", what, w.Code, w.Body)
}
}
for _, rt := range routes {
at := rt.method + " " + rt.path
// pages on this computer's browser, with no key
refused(at+" from a page elsewhere", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, append([]string{"Origin", "https://evil.example", "Sec-Fetch-Site", "cross-site"}, browser...)...), http.StatusForbidden)
refused(at+" from Origin null", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, append([]string{"Origin", "null", "Sec-Fetch-Site", "cross-site"}, browser...)...), http.StatusForbidden)
refused(at+" from a localhost subdomain", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, append([]string{"Origin", "http://evil.localhost", "Sec-Fetch-Site", "cross-site"}, browser...)...), http.StatusForbidden)
// rebound: no Origin on a GET, the page's own on a POST
hdr := append([]string{"Sec-Fetch-Site", "same-origin"}, browser...)
if rt.method == "POST" {
hdr = append(hdr, "Origin", "http://rebind.attacker.example:3425")
}
refused(at+" rebound", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", "rebind.attacker.example:3425", hdr...), http.StatusForbidden)
refused(at+" rebound at a localhost subdomain", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", "evil.localhost:3425", hdr...), http.StatusForbidden)
// another machine, no Origin at all: magpie not shared
refused(at+" from the LAN, not shared", do(rt.method, rt.path, rt.body, "192.168.1.9:5000", "192.168.1.2:3425"), http.StatusForbidden)
// a tunnel on loopback
refused(at+" through a tunnel, not shared", do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, "X-Forwarded-For", "203.0.113.9"), http.StatusForbidden)
// an agent here, as VS Code's Copilot calls it: answered
if w := do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, "User-Agent", "node-fetch"); w.Code != 200 {
t.Errorf("%s from an agent here: %d %s", at, w.Code, w.Body)
}
}
// shared: another machine needs an enabled key
_, secrets := newCaller(t, "Visual Studio")
for _, rt := range routes {
at := rt.method + " " + rt.path
for _, hdr := range [][]string{nil, {"Authorization", "Bearer magpie"}, {"Authorization", "Bearer sk-magpie-wrong"}} {
resetAuthThrottle()
refused(at+" from the LAN with "+strings.Join(hdr, " "), do(rt.method, rt.path, rt.body, "192.168.1.9:5000", "192.168.1.2:3425", hdr...), http.StatusUnauthorized)
}
if w := do(rt.method, rt.path, rt.body, "192.168.1.9:5000", "192.168.1.2:3425", "Authorization", "Bearer "+secrets[0]); w.Code != 200 {
t.Errorf("%s from the LAN with its key: %d %s", at, w.Code, w.Body)
}
// a sandboxed frame or a rebound page with an enabled key is
// answered, as on /v1
if w := do(rt.method, rt.path, rt.body, "127.0.0.1:50123", gw, append([]string{"Origin", "null", "Authorization", "Bearer " + secrets[0]}, browser...)...); w.Code != 200 {
t.Errorf("%s from Origin null with a key: %d %s", at, w.Code, w.Body)
}
}
settings.Save(settings.Settings{LAN: false})
}
// VS Code's Copilot chats with a model it listed from /api/tags on
// <endpoint>/v1/chat/completions, streamed, with an empty bearer (its
// Ollama provider has no key field) and stream_options it adds itself
// (openAIEndpoint.ts interceptBody): the request reaches the model's
// provider by the id the list gave, and the stream comes back.
func TestOllamaClientChats(t *testing.T) {
fresh(t)
var got []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var req struct{ Model string }
json.Unmarshal(b, &req)
got = append(got, r.URL.Path+" "+req.Model+" "+r.Header.Get("Authorization"))
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"hello from seer\"},\"finish_reason\":null}]}\n\n"+
"data: {\"id\":\"c1\",\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":3}}\n\ndata: [DONE]\n\n")
}))
defer up.Close()
ollamaPlan(t, up.URL+"/v1")
srv := lanGuard(New().Handler())
var tags struct{ Models []struct{ Model string } }
r := httptest.NewRequest("GET", "/api/tags", nil)
r.RemoteAddr, r.Host = "127.0.0.1:50123", "127.0.0.1:3425"
w := httptest.NewRecorder()
srv.ServeHTTP(w, r)
if err := json.Unmarshal(w.Body.Bytes(), &tags); err != nil || len(tags.Models) == 0 {
t.Fatalf("tags: %d %s", w.Code, w.Body)
}
model := ""
for _, m := range tags.Models {
if strings.HasSuffix(m.Model, "/seer") {
model = m.Model
}
}
body := `{"messages":[{"role":"system","content":"You are an AI programming assistant."},{"role":"user","content":"hi"}],"model":"` + model +
`","temperature":0.1,"top_p":1,"n":1,"stream":true,"tools":[{"type":"function","function":{"name":"read_file","description":"Read a file","parameters":{"type":"object","properties":{"path":{"type":"string"}}}}}],"stream_options":{"include_usage":true}}`
r = httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(body))
r.RemoteAddr, r.Host = "127.0.0.1:50123", "127.0.0.1:3425"
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Authorization", "Bearer ")
w = httptest.NewRecorder()
srv.ServeHTTP(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "hello from seer") {
t.Fatalf("chat: %d %s", w.Code, w.Body)
}
if len(got) != 1 || got[0] != "/v1/chat/completions seer Bearer upstream-secret" {
t.Fatalf("upstream got %q", got)
}
}
+1
View File
@@ -108,6 +108,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"</
<tr><td><code>/v1/messages</code>, <code>/v1/messages/count_tokens</code></td><td>Anthropic Messages</td></tr>
<tr><td><code>/v1beta/models/{model}:generateContent</code> (and <code>:streamGenerateContent</code>)</td><td>Google Gemini</td></tr>
<tr><td><code>/v1/models</code></td><td>the catalog</td></tr>
<tr><td><code>/api/version</code>, <code>/api/tags</code>, <code>/api/show</code></td><td>the catalog as an Ollama server lists it, for a client that takes only an Ollama endpoint (Copilot in Visual Studio and VS Code: enter <code>http://127.0.0.1:&lt;port&gt;</code> as the Ollama URL; it chats on <code>/v1/chat/completions</code>, and <code>/api/chat</code> isn’t served)</td></tr>
</table></div>
<h3>The key names your app</h3>
+1
View File
@@ -108,6 +108,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"</
<tr><td><code>/v1/messages</code>、<code>/v1/messages/count_tokens</code></td><td>Anthropic Messages</td></tr>
<tr><td><code>/v1beta/models/{model}:generateContent</code>(以及 <code>:streamGenerateContent</code>)</td><td>Google Gemini</td></tr>
<tr><td><code>/v1/models</code></td><td>模型目录</td></tr>
<tr><td><code>/api/version</code>、<code>/api/tags</code>、<code>/api/show</code></td><td>以 Ollama 服务器的格式列出模型目录,供只接受 Ollama 端点的客户端使用(Visual Studio 和 VS Code 里的 Copilot:Ollama 地址填 <code>http://127.0.0.1:&lt;端口&gt;</code>;对话走 <code>/v1/chat/completions</code>,不提供 <code>/api/chat</code>)</td></tr>
</table></div>
<h3>用 key 标明你的应用</h3>