launch: pass fixed local context to Claude Code (#17058)

This commit is contained in:
Eva H authored and GitHub committed 2026-12-03 12:59:25 -05:00
1 parent b5f0eb268c
commit ce94980ea8
13 files changed
+356 -38

No files matched your search

+5
View File
@@ -947,6 +947,11 @@ type ShowResponse struct {
Manifests []ManifestSummary `json:"manifests,omitempty"`
ModifiedAt time.Time `json:"modified_at,omitempty"`
Requires string `json:"requires,omitempty"`
// ServingContextLength is the per-request local context limit when an
// explicit configuration makes it known without loading the model. Zero
// means unknown; the architecture maximum remains in ModelInfo.
ServingContextLength int `json:"serving_context_length,omitempty"`
}
// ManifestSummary describes one child manifest available through a model tag.
+30
View File
@@ -55,6 +55,32 @@ func (c *Claude) Run(model string, models []LaunchModel, args []string) error {
return err
}
// A passed-through --model can select a different client model. The local
// serving metadata belongs only to the model resolved by this launcher.
contextModel := model
for i, arg := range args {
if arg == "--" {
break
}
if arg == "--model" && i+1 < len(args) {
contextModel = args[i+1]
} else if value, ok := strings.CutPrefix(arg, "--model="); ok {
contextModel = value
}
}
// These aliases all use the selected Ollama model through modelEnvVars.
switch contextModel {
case "opus", "sonnet", "haiku", "opusplan":
contextModel = model
}
// The same base name can refer to both a local and a cloud model.
if !SameModelRef(contextModel, model) || isCloudModelName(contextModel) != isCloudModelName(model) {
models = cloneLaunchModels(models)
for i := range models {
models[i].ServingContextLength = 0
}
}
cmd := exec.Command(claudePath, c.args(model, args)...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
@@ -214,6 +240,10 @@ func (c *Claude) modelEnvVars(model string, models []LaunchModel) []string {
env = append(env, "CLAUDE_CODE_AUTO_COMPACT_WINDOW="+strconv.Itoa(min(ctxLen, claudeMaxAutoCompactWindow)))
}
}
} else if resolved.ServingContextLength > 0 {
// MAX applies below the AUTO_COMPACT_WINDOW minimum too. Leave
// compaction to the user's environment, CLI flags and settings.
env = append(env, "CLAUDE_CODE_MAX_CONTEXT_TOKENS="+strconv.Itoa(resolved.ServingContextLength))
}
return env
+107
View File
@@ -0,0 +1,107 @@
package launch
import (
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"testing"
"github.com/ollama/ollama/api"
)
type contextTestTransport func(*http.Request) (*http.Response, error)
func (f contextTestTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
func TestClaudeResolveServingContext(t *testing.T) {
for _, tt := range []struct {
name, body string
status int
want int
}{
{name: "known unloaded model", body: `{"serving_context_length":65536,"model_info":{"gemma4.context_length":262144}}`, want: 65536},
{name: "unknown automatic context", body: `{"model_info":{"gemma4.context_length":262144}}`},
{name: "old server default is not model capacity", body: `{"context_length":65536,"model_info":{"gemma4.context_length":262144}}`},
{name: "negative serving limit", body: `{"serving_context_length":-1}`},
{name: "contradicts architecture maximum", body: `{"serving_context_length":524288,"model_info":{"gemma4.context_length":262144}}`},
{name: "remote alias", body: `{"serving_context_length":65536,"remote_host":"https://ollama.com","remote_model":"remote"}`},
{name: "missing model", status: http.StatusNotFound, body: `{"error":"not found"}`},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("OLLAMA_HOST", "http://different.invalid:11434")
t.Setenv("OLLAMA_CONTEXT_LENGTH", "999999")
oldConfirm := DefaultConfirmPrompt
DefaultConfirmPrompt = func(string, ConfirmOptions) (bool, error) {
t.Fatal("context discovery must not add a launch confirmation")
return false, nil
}
t.Cleanup(func() { DefaultConfirmPrompt = oldConfirm })
calls := 0
transport := contextTestTransport(func(req *http.Request) (*http.Response, error) {
calls++
if req.URL.Host != "selected.test:12345" || req.URL.Path != "/api/show" {
t.Fatalf("unexpected metadata route: %s", req.URL)
}
var show api.ShowRequest
if err := json.NewDecoder(req.Body).Decode(&show); err != nil {
t.Fatal(err)
}
if show.Model != "gemma4:latest" || len(show.Options) != 0 {
t.Fatalf("show request = %+v", show)
}
status := tt.status
if status == 0 {
status = http.StatusOK
}
return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(tt.body)), Header: make(http.Header)}, nil
})
u, _ := url.Parse("http://selected.test:12345")
apiClient := api.NewClient(u, &http.Client{Transport: transport})
input := []LaunchModel{{Name: "other", ServingContextLength: 8192}, {Name: "gemma4:latest", ContextLength: 262144, ServingContextLength: 12345}}
client := &launcherClient{
apiClient: apiClient, recommendationsLoaded: true,
inventory: &modelInventory{client: apiClient, loaded: true, models: input},
}
got := client.resolveRunModels(t.Context(), "claude", []string{"gemma4"})
if len(got) != 1 || calls != 1 || got[0].ServingContextLength != tt.want || got[0].ContextLength != 262144 {
t.Fatalf("models = %+v, calls = %d, want selected serving context %d", got, calls, tt.want)
}
if input[1].ServingContextLength != 12345 || input[0].ServingContextLength != 8192 {
t.Fatal("mutated model inventory")
}
})
}
}
func TestClaudeResolveServingContextSkipsRemote(t *testing.T) {
apiClient := api.NewClient(&url.URL{Scheme: "http", Host: "selected.test"}, &http.Client{Transport: contextTestTransport(func(*http.Request) (*http.Response, error) {
t.Fatal("remote model should keep existing cloud metadata path")
return nil, nil
})})
for _, model := range []LaunchModel{{Name: "example:cloud"}, {Name: "remote-alias", Remote: true}} {
client := &launcherClient{
apiClient: apiClient, recommendationsLoaded: true,
inventory: &modelInventory{client: apiClient, loaded: true, models: []LaunchModel{model}},
}
got := client.resolveRunModels(t.Context(), "claude", []string{model.Name})
if len(got) != 1 || got[0].ServingContextLength != 0 {
t.Fatalf("remote models = %+v", got)
}
}
}
func TestClaudeLocalContextLeavesCompactionPreferences(t *testing.T) {
t.Setenv("CLAUDE_CODE_AUTO_COMPACT_WINDOW", "150000")
for _, length := range []int{65536, 196608} {
env := (&Claude{}).modelEnvVars("local", []LaunchModel{{Name: "local", ContextLength: 262144, ServingContextLength: length}})
for _, entry := range env {
if strings.HasPrefix(entry, "CLAUDE_CODE_AUTO_COMPACT_WINDOW=") {
t.Fatal("local metadata must not override compaction selection", entry)
}
}
}
}
+11 -1
View File
@@ -646,14 +646,24 @@ printf '%s\n' "$CLAUDE_CODE_MAX_CONTEXT_TOKENS" "$CLAUDE_CODE_AUTO_COMPACT_WINDO
name string
model LaunchModel
want string
args []string
}{
{name: "cloud model absent from fallback table", model: LaunchModel{Name: "muse-spark-open:cloud", ContextLength: 1048576}, want: "1048576"},
{name: "remote model without cloud suffix", model: LaunchModel{Name: "custom-cloud", Remote: true, ContextLength: 262144}, want: "262144"},
{name: "local trained maximum is not the allocated context", model: LaunchModel{Name: "qwen3:8b", ContextLength: 131072}, want: "12345"},
{name: "known local serving limit below auto compact minimum", model: LaunchModel{Name: "gemma4:12b", ContextLength: 262144, ServingContextLength: 65536}, want: "65536"},
{name: "managed sonnet alias retains local capacity", model: LaunchModel{Name: "gemma4:12b", ServingContextLength: 65536}, args: []string{"--model", "sonnet"}, want: "65536"},
{name: "managed opus alias retains local capacity", model: LaunchModel{Name: "gemma4:12b", ServingContextLength: 65536}, args: []string{"--model=opus"}, want: "65536"},
{name: "managed haiku alias retains local capacity", model: LaunchModel{Name: "gemma4:12b", ServingContextLength: 65536}, args: []string{"--model", "haiku"}, want: "65536"},
{name: "managed opusplan alias retains local capacity", model: LaunchModel{Name: "gemma4:12b", ServingContextLength: 65536}, args: []string{"--model=opusplan"}, want: "65536"},
{name: "different passed-through model cannot borrow local capacity", model: LaunchModel{Name: "gemma4:12b", ServingContextLength: 65536}, args: []string{"--model=other-local"}, want: "12345"},
{name: "cloud override with the same base cannot borrow local capacity", model: LaunchModel{Name: "qwen3.5", ServingContextLength: 65536}, args: []string{"--model=qwen3.5:cloud"}, want: "12345"},
{name: "legacy cloud override cannot borrow local capacity", model: LaunchModel{Name: "gemma4:12b", ServingContextLength: 65536}, args: []string{"--model", "gemma4:12b-cloud"}, want: "12345"},
{name: "later different model overrides managed alias", model: LaunchModel{Name: "gemma4:12b", ServingContextLength: 65536}, args: []string{"--model", "sonnet", "--model", "other-local"}, want: "12345"},
} {
t.Run(tt.name, func(t *testing.T) {
models := []LaunchModel{{Name: "other:cloud", ContextLength: 65536}, tt.model}
if err := (&Claude{}).Run(tt.model.Name, models, nil); err != nil {
if err := (&Claude{}).Run(tt.model.Name, models, tt.args); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(output)
+19 -3
View File
@@ -1567,15 +1567,31 @@ func (c *launcherClient) resolveRunModels(ctx context.Context, integration strin
resolved[i].Thinking = thinking.Clone()
}
}
if !slices.Contains([]string{"codex", "opencode", chatGPTIntegrationName, codexAppIntegrationName}, integration) {
if !slices.Contains([]string{"claude", "codex", "opencode", chatGPTIntegrationName, codexAppIntegrationName}, integration) {
return resolved
}
showCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
for i := range resolved {
if integration == "claude" {
resolved[i].ServingContextLength = 0
if resolved[i].Remote || isCloudModelName(resolved[i].Name) {
continue
}
}
if showCtx.Err() == nil {
if show, err := c.apiClient.Show(showCtx, &api.ShowRequest{Model: resolved[i].Name}); err == nil && show.Thinking.Valid() {
resolved[i].Thinking = show.Thinking.Clone()
if show, err := c.apiClient.Show(showCtx, &api.ShowRequest{Model: resolved[i].Name}); err == nil {
if show.Thinking.Valid() {
resolved[i].Thinking = show.Thinking.Clone()
}
// Serving limits must be fresh and come from this launch's server.
// Architecture metadata and automatic targets are not allocations.
if integration == "claude" && show.RemoteHost == "" && show.RemoteModel == "" && show.ServingContextLength > 0 {
maximum, known := modelInfoContextLength(show.ModelInfo)
if !known || show.ServingContextLength <= maximum {
resolved[i].ServingContextLength = show.ServingContextLength
}
}
}
}
}
+20 -4
View File
@@ -3896,7 +3896,7 @@ func TestLaunchIntegration_ClaudeModelOverrideDeprecatedDeclineOpensPicker(t *te
writeFakeBinary(t, binDir, "claude")
t.Setenv("PATH", binDir)
var showCalls atomic.Int32
var replacementShown atomic.Bool
var prompt string
var promptOptions ConfirmOptions
DefaultConfirmPrompt = func(p string, options ConfirmOptions) (bool, error) {
@@ -3907,6 +3907,9 @@ func TestLaunchIntegration_ClaudeModelOverrideDeprecatedDeclineOpensPicker(t *te
var selectorCalls int
DefaultSingleSelector = func(title string, items []SelectionItem, current string) (string, error) {
selectorCalls++
if replacementShown.Load() {
t.Fatal("model readiness must wait for picker selection")
}
if title != "Select model for Claude Code:" {
t.Fatalf("picker title = %q, want Claude Code model picker", title)
}
@@ -3934,8 +3937,19 @@ func TestLaunchIntegration_ClaudeModelOverrideDeprecatedDeclineOpensPicker(t *te
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"llama3.2"},{"name":"best-local"}]}`)
case "/api/show":
showCalls.Add(1)
var req api.ShowRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
t.Errorf("decode show request: %v", err)
return
}
if req.Model != "best-local" {
t.Errorf("expected only the selected replacement to be shown, got %q", req.Model)
}
replacementShown.Store(true)
fmt.Fprint(w, `{"model_info":{"general.context_length":131072}}`)
case "/api/pull":
t.Error("installed replacement must not trigger a download")
http.Error(w, "unexpected download", http.StatusBadRequest)
default:
http.NotFound(w, r)
}
@@ -3960,8 +3974,10 @@ func TestLaunchIntegration_ClaudeModelOverrideDeprecatedDeclineOpensPicker(t *te
if selectorCalls != 1 {
t.Fatalf("expected picker to open after declining override, got %d calls", selectorCalls)
}
if showCalls.Load() != 1 {
t.Fatalf("expected only replacement model readiness to call /api/show, got %d calls", showCalls.Load())
// Claude also refreshes context metadata after readiness. Both lookups must
// stay scoped to the selected replacement, not the rejected override.
if !replacementShown.Load() {
t.Fatal("expected replacement model readiness to call /api/show")
}
saved, err := config.LoadIntegration("claude")
if err != nil {
+3
View File
@@ -40,6 +40,9 @@ type LaunchModel struct {
EmbeddingLength int
Size int64
Details api.ModelDetails
// ServingContextLength is separate from the model architecture maximum.
ServingContextLength int
}
type modelInfo = LaunchModel
+9 -3
View File
@@ -1,16 +1,22 @@
package server
import "context"
import (
"context"
"github.com/ollama/ollama/api"
)
type modelCaches struct {
recommendations *modelRecommendationsCache
show *modelShowCache
}
func newModelCaches() *modelCaches {
func newModelCaches(getShowModelInfo func(api.ShowRequest) (*api.ShowResponse, error)) *modelCaches {
show := newModelShowCache()
show.getModelInfo = getShowModelInfo
return &modelCaches{
recommendations: newModelRecommendationsCache(),
show: newModelShowCache(),
show: show,
}
}
+17 -15
View File
@@ -15,6 +15,7 @@ import (
"time"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/envconfig"
internalcloud "github.com/ollama/ollama/internal/cloud"
"github.com/ollama/ollama/internal/modelref"
"github.com/ollama/ollama/manifest"
@@ -30,10 +31,8 @@ TODO(parthsareen): Consider removing show cache if /api/tags grows to cover
the remaining callers.
Local model entries are stored lazily by canonical model name, runner, and
verbose flag, with the manifest digest recorded in the entry. The manifest
digest is the freshness boundary: if the model content changes, the digest
changes, so the previous response is replaced instead of accumulating under an
old digest key.
verbose flag. The manifest digest and configured context length determine
freshness. A change replaces the previous response in the same cache slot.
Requests with System or Options overlays bypass the cache because those overlays
mutate the effective show response.
@@ -93,8 +92,9 @@ type modelShowLocalKey struct {
}
type modelShowLocalEntry struct {
Digest string
Response *api.ShowResponse
Digest string
ServerContext uint
Response *api.ShowResponse
}
// modelShowCloudKey intentionally excludes any local digest because cloud
@@ -146,8 +146,8 @@ func (c *modelShowCache) runStartup(ctx context.Context) {
}
}
// GetLocal returns a cached local show response when the current manifest
// digest matches. On a miss, it falls back to GetModelInfo, stores non-remote
// GetLocal returns a cached local show response when the manifest and configured
// server context match. On a miss, it loads the model metadata, stores non-remote
// local responses, and returns a clone to the caller.
func (c *modelShowCache) GetLocal(req api.ShowRequest) (*api.ShowResponse, error) {
key, digest, err := modelShowLocalKeyForRequest(req)
@@ -155,7 +155,8 @@ func (c *modelShowCache) GetLocal(req api.ShowRequest) (*api.ShowResponse, error
return nil, err
}
if resp, ok := c.getLocal(key, digest); ok {
serverContext := envconfig.ContextLength()
if resp, ok := c.getLocal(key, digest, serverContext); ok {
return resp, nil
}
@@ -166,7 +167,7 @@ func (c *modelShowCache) GetLocal(req api.ShowRequest) (*api.ShowResponse, error
}
if resp.RemoteHost == "" {
c.setLocal(key, digest, resp)
c.setLocal(key, digest, serverContext, resp)
}
return cloneShowResponse(resp), nil
@@ -186,21 +187,22 @@ func (c *modelShowCache) GetCloudSWR(ctx context.Context, req api.ShowRequest) (
return resp, true
}
func (c *modelShowCache) getLocal(key modelShowLocalKey, digest string) (*api.ShowResponse, bool) {
func (c *modelShowCache) getLocal(key modelShowLocalKey, digest string, serverContext uint) (*api.ShowResponse, bool) {
c.mu.RLock()
entry, ok := c.local[key]
c.mu.RUnlock()
if !ok || entry.Digest != digest || entry.Response == nil {
if !ok || entry.Digest != digest || entry.ServerContext != serverContext || entry.Response == nil {
return nil, false
}
return cloneShowResponse(entry.Response), true
}
func (c *modelShowCache) setLocal(key modelShowLocalKey, digest string, resp *api.ShowResponse) {
func (c *modelShowCache) setLocal(key modelShowLocalKey, digest string, serverContext uint, resp *api.ShowResponse) {
c.mu.Lock()
c.local[key] = modelShowLocalEntry{
Digest: digest,
Response: cloneShowResponse(resp),
Digest: digest,
ServerContext: serverContext,
Response: cloneShowResponse(resp),
}
c.mu.Unlock()
}
+1 -1
View File
@@ -186,7 +186,7 @@ func TestModelShowCacheBypassesSystemAndOptionsOverlays(t *testing.T) {
if err != nil {
t.Fatalf("local key failed: %v", err)
}
cache.setLocal(key, digest, &api.ShowResponse{System: "cached", ModelInfo: map[string]any{}})
cache.setLocal(key, digest, envconfig.ContextLength(), &api.ShowResponse{System: "cached", ModelInfo: map[string]any{}})
s := Server{modelCaches: &modelCaches{show: cache}}
w := createRequest(t, s.ShowHandler, api.ShowRequest{
+29 -5
View File
@@ -1844,7 +1844,7 @@ func (s *Server) ShowHandler(c *gin.Context) {
if modelShowCacheable(req) && s.modelCaches != nil && s.modelCaches.show != nil {
resp, err = s.modelCaches.show.GetLocal(req)
} else {
resp, err = GetModelInfo(req)
resp, err = s.getLocalShowModelInfo(req)
}
if err != nil {
writeShowError(c, req.Model, err)
@@ -1869,7 +1869,30 @@ func (s *Server) ShowHandler(c *gin.Context) {
c.JSON(http.StatusOK, resp)
}
// An automatic context may be reduced when the model is loaded. Its target,
// or an allocation made for a different request, is not a usable fixed limit.
func (s *Server) localServingContextLength(m *Model, requestOpts map[string]any) int {
if m == nil || m.Config.RemoteHost != "" || m.Config.ModelFormat != "gguf" || usesAutomaticNumCtx(m, requestOpts) {
return 0
}
opts, err := s.modelOptions(m, requestOpts)
maximum := m.metadata.Int("context_length")
if err != nil || opts.NumCtx < 4 || maximum <= 0 {
return 0
}
numCtx := max(opts.NumCtx, minimumRunnerContextLength(m))
return int(min(int64(numCtx), maximum))
}
func (s *Server) getLocalShowModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
return getModelInfo(req, s.localServingContextLength)
}
func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
return getModelInfo(req, nil)
}
func getModelInfo(req api.ShowRequest, servingContextLength func(*Model, map[string]any) int) (*api.ShowResponse, error) {
runner, err := normalizeRunner(req.Runner)
if err != nil {
return nil, api.StatusError{
@@ -1959,6 +1982,9 @@ func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
// default we return an empty map.
ModelInfo: make(map[string]any),
}
if servingContextLength != nil {
resp.ServingContextLength = servingContextLength(m, req.Options)
}
resp.Renderer = resolveRendererName(m)
resp.Parser = m.Config.Parser
resp.TemplateSource = m.templateSource()
@@ -2522,10 +2548,8 @@ func Serve(ln net.Listener) error {
}
}
s := &Server{
addr: ln.Addr(),
modelCaches: newModelCaches(),
}
s := &Server{addr: ln.Addr()}
s.modelCaches = newModelCaches(s.getLocalShowModelInfo)
if err := s.initRequestLogging(); err != nil {
return err
}
+7 -6
View File
@@ -221,15 +221,16 @@ func effectiveContext(numCtx, trainCtx int) int {
return numCtx
}
func (s *Scheduler) getRunner(c context.Context, m *Model, opts api.Options, sessionDuration *api.Duration, numCtxAuto bool, numBatchAuto bool, shift *bool) (chan *runnerRef, chan error) {
if opts.NumCtx < 4 {
opts.NumCtx = 4
}
func minimumRunnerContextLength(m *Model) int {
if m.CheckCapabilities(model.CapabilityVision) == nil || len(m.ProjectorPaths) > 0 {
// multimodal models require at least 2048 context
opts.NumCtx = max(opts.NumCtx, 2048)
return 2048
}
return 4
}
func (s *Scheduler) getRunner(c context.Context, m *Model, opts api.Options, sessionDuration *api.Duration, numCtxAuto bool, numBatchAuto bool, shift *bool) (chan *runnerRef, chan error) {
opts.NumCtx = max(opts.NumCtx, minimumRunnerContextLength(m))
req := &LlmRequest{
ctx: c,
+98
View File
@@ -0,0 +1,98 @@
package server
import (
"encoding/json"
"strconv"
"testing"
"github.com/ollama/ollama/api"
model "github.com/ollama/ollama/types/model"
)
func TestLocalServingContextLength(t *testing.T) {
for _, tt := range []struct {
name, env string
modelCtx, requestCtx any
vision bool
maximum int
want int
}{
{name: "unloaded explicit server context", env: "65536", maximum: 262144, want: 65536},
{name: "model overrides server", env: "65536", modelCtx: float64(32768), maximum: 262144, want: 32768},
{name: "request overrides model and server", env: "65536", modelCtx: float64(32768), requestCtx: float64(16384), maximum: 262144, want: 16384},
{name: "clamped to architecture", env: "524288", maximum: 262144, want: 262144},
{name: "small text context remains unchanged", env: "1024", maximum: 8192, want: 1024},
{name: "vision context uses runner minimum", env: "1024", vision: true, maximum: 8192, want: 2048},
{name: "vision context is still capped by architecture", env: "1024", vision: true, maximum: 1536, want: 1536},
{name: "automatic default is unknown before allocation", maximum: 262144},
{name: "unknown architecture", env: "65536"},
{name: "invalid option", env: "65536", requestCtx: "invalid", maximum: 262144},
{name: "invalid model context", modelCtx: float64(-1), maximum: 262144},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("OLLAMA_CONTEXT_LENGTH", tt.env)
m := &Model{Config: model.ConfigV2{ModelFormat: "gguf"}, Options: map[string]any{}, metadata: ggufMetadata{KV: map[string]any{"general.architecture": "test", "test.context_length": json.Number(strconv.Itoa(tt.maximum))}}}
if tt.vision {
m.Config.Capabilities = []string{string(model.CapabilityVision)}
}
if tt.modelCtx != nil {
m.Options["num_ctx"] = tt.modelCtx
}
opts := map[string]any{}
if tt.requestCtx != nil {
opts["num_ctx"] = tt.requestCtx
}
s := Server{defaultNumCtx: 262144}
if got := s.localServingContextLength(m, opts); got != tt.want {
t.Fatalf("serving context = %d, want %d", got, tt.want)
}
m.Config.RemoteHost = "https://ollama.com"
if got := s.localServingContextLength(m, opts); got != 0 {
t.Fatalf("remote context = %d, want unknown", got)
}
})
}
}
func TestShowServingContextIsFreshAndDoesNotLoad(t *testing.T) {
setTestHome(t, t.TempDir())
createShowCacheModel(t, "serving-context", map[string]any{"test.context_length": uint32(262144)})
s := Server{defaultNumCtx: 262144}
cacheLoads := 0
s.modelCaches = newModelCaches(func(req api.ShowRequest) (*api.ShowResponse, error) {
cacheLoads++
return s.getLocalShowModelInfo(req)
})
for _, tt := range []struct {
env string
request map[string]any
want int
wantLoads int
}{
{env: "65536", want: 65536, wantLoads: 1},
{env: "65536", want: 65536, wantLoads: 1},
{env: "32768", want: 32768, wantLoads: 2},
{env: "32768", request: map[string]any{"num_ctx": 16384}, want: 16384, wantLoads: 2},
{env: "32768", want: 32768, wantLoads: 2},
{want: 0, wantLoads: 3},
} {
t.Setenv("OLLAMA_CONTEXT_LENGTH", tt.env)
w := createRequest(t, s.ShowHandler, api.ShowRequest{Model: "serving-context", Options: tt.request})
if w.Code != 200 {
t.Fatalf("show: %d %s", w.Code, w.Body.String())
}
var resp api.ShowResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if resp.ServingContextLength != tt.want {
t.Fatalf("serving context = %d, want %d", resp.ServingContextLength, tt.want)
}
if cacheLoads != tt.wantLoads {
t.Fatalf("cache loads = %d, want %d", cacheLoads, tt.wantLoads)
}
}
if s.sched != nil {
t.Fatal("metadata should not create a scheduler")
}
}