Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

launch: add codex model metadata catalog (#15795)

Eva H56b319f457d6
diff --git a/cmd/launch/codex.go b/cmd/launch/codex.go
index 7bd03e54c..fe48c9266 100644
--- a/cmd/launch/codex.go
+++ b/cmd/launch/codex.go
@@ -1,14 +1,21 @@
package launch
import (
+ "context"
+ "encoding/json"
"fmt"
+ "net/http"
"os"
"os/exec"
"path/filepath"
+ "slices"
+ "strconv"
"strings"
+ "github.com/ollama/ollama/api"
"github.com/ollama/ollama/cmd/internal/fileutil"
"github.com/ollama/ollama/envconfig"
+ "github.com/ollama/ollama/types/model"
"github.com/pelletier/go-toml/v2"
"golang.org/x/mod/semver"
)
@@ -19,8 +26,9 @@ type Codex struct{}
func (c *Codex) String() string { return "Codex" }
const (
- codexProfileName = "ollama-launch"
- codexProviderName = "Ollama"
+ codexProfileName = "ollama-launch"
+ codexProviderName = "Ollama"
+ codexFallbackContextWindow = 128_000
codexRootProfileKey = "profile"
codexRootModelKey = "model"
@@ -28,8 +36,11 @@ const (
codexRootModelCatalogJSONKey = "model_catalog_json"
)
-func (c *Codex) args(model string, extra []string) []string {
+func (c *Codex) args(model, modelCatalogPath string, extra []string) []string {
args := []string{"--profile", codexProfileName}
+ if modelCatalogPath != "" {
+ args = append(args, "-c", fmt.Sprintf("%s=%q", codexRootModelCatalogJSONKey, modelCatalogPath))
+ }
if model != "" {
args = append(args, "-m", model)
}
@@ -42,11 +53,16 @@ func (c *Codex) Run(model string, args []string) error {
return err
}
- if err := ensureCodexConfig(); err != nil {
+ if err := ensureCodexConfig(model); err != nil {
return fmt.Errorf("failed to configure codex: %w", err)
}
- cmd := exec.Command("codex", c.args(model, args)...)
+ catalogPath, err := codexModelCatalogPath()
+ if err != nil {
+ return fmt.Errorf("failed to configure codex: %w", err)
+ }
+
+ cmd := exec.Command("codex", c.args(model, catalogPath, args)...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
@@ -56,18 +72,25 @@ func (c *Codex) Run(model string, args []string) error {
return cmd.Run()
}
-// ensureCodexConfig writes a [profiles.ollama-launch] section to ~/.codex/config.toml
-// with openai_base_url pointing to the local Ollama server.
-func ensureCodexConfig() error {
+// ensureCodexConfig writes a Codex profile and model catalog so Codex uses the
+// local Ollama server and has model metadata available.
+func ensureCodexConfig(modelName string) error {
configPath, err := codexConfigPath()
if err != nil {
return err
}
- if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
+ codexDir := filepath.Dir(configPath)
+ if err := os.MkdirAll(codexDir, 0o755); err != nil {
return err
}
- return writeCodexProfile(configPath)
+
+ catalogPath := codexModelCatalogPathForConfig(configPath)
+ if err := writeCodexModelCatalog(catalogPath, modelName); err != nil {
+ return err
+ }
+
+ return writeCodexProfile(configPath, catalogPath)
}
func codexConfigPath() (string, error) {
@@ -78,12 +101,28 @@ func codexConfigPath() (string, error) {
return filepath.Join(home, ".codex", "config.toml"), nil
}
+func codexModelCatalogPath() (string, error) {
+ configPath, err := codexConfigPath()
+ if err != nil {
+ return "", err
+ }
+ return codexModelCatalogPathForConfig(configPath), nil
+}
+
+func codexModelCatalogPathForConfig(configPath string) string {
+ return filepath.Join(filepath.Dir(configPath), "model.json")
+}
+
// writeCodexProfile ensures ~/.codex/config.toml has the ollama-launch profile
// and model provider sections with the correct base URL.
-func writeCodexProfile(configPath string) error {
- return writeCodexLaunchProfile(configPath, codexLaunchProfileOptions{
+func writeCodexProfile(configPath string, modelCatalogPath ...string) error {
+ opts := codexLaunchProfileOptions{
forceAPIAuth: true,
- })
+ }
+ if len(modelCatalogPath) > 0 {
+ opts.modelCatalogPath = modelCatalogPath[0]
+ }
+ return writeCodexLaunchProfile(configPath, opts)
}
type codexLaunchProfileOptions struct {
@@ -538,6 +577,97 @@ func codexRootLineHasKey(line, key string) bool {
return ok
}
+func writeCodexModelCatalog(catalogPath, modelName string) error {
+ entry := buildCodexModelEntry(modelName)
+
+ catalog := map[string]any{
+ "models": []any{entry},
+ }
+
+ data, err := json.MarshalIndent(catalog, "", " ")
+ if err != nil {
+ return err
+ }
+
+ return os.WriteFile(catalogPath, data, 0o644)
+}
+
+func buildCodexModelEntry(modelName string) map[string]any {
+ contextWindow := codexFallbackContextWindow
+ hasVision := false
+ systemPrompt := ""
+
+ if l, ok := lookupCloudModelLimit(modelName); ok {
+ contextWindow = l.Context
+ }
+
+ client := api.NewClient(envconfig.Host(), http.DefaultClient)
+ resp, err := client.Show(context.Background(), &api.ShowRequest{Model: modelName})
+ if err == nil {
+ systemPrompt = resp.System
+ if slices.Contains(resp.Capabilities, model.CapabilityVision) {
+ hasVision = true
+ }
+
+ if !isCloudModelName(modelName) {
+ if n, ok := modelInfoContextLength(resp.ModelInfo); ok {
+ contextWindow = n
+ }
+ if resp.Details.Format != "safetensors" {
+ if ctxLen := envconfig.ContextLength(); ctxLen > 0 {
+ contextWindow = int(ctxLen)
+ }
+ if numCtx := parseNumCtx(resp.Parameters); numCtx > 0 {
+ contextWindow = numCtx
+ }
+ }
+ }
+ }
+
+ modalities := []string{"text"}
+ if hasVision {
+ modalities = append(modalities, "image")
+ }
+
+ truncationMode := "bytes"
+ if isCloudModelName(modelName) {
+ truncationMode = "tokens"
+ }
+
+ return map[string]any{
+ "slug": modelName,
+ "display_name": modelName,
+ "context_window": contextWindow,
+ "apply_patch_tool_type": "function",
+ "shell_type": "default",
+ "visibility": "list",
+ "supported_in_api": true,
+ "priority": 0,
+ "truncation_policy": map[string]any{"mode": truncationMode, "limit": 10000},
+ "input_modalities": modalities,
+ "base_instructions": systemPrompt,
+ "support_verbosity": true,
+ "default_verbosity": "low",
+ "supports_parallel_tool_calls": false,
+ "supports_reasoning_summaries": false,
+ "supported_reasoning_levels": []any{},
+ "experimental_supported_tools": []any{},
+ }
+}
+
+func parseNumCtx(parameters string) int {
+ for _, line := range strings.Split(parameters, "\n") {
+ fields := strings.Fields(line)
+ if len(fields) == 2 && fields[0] == "num_ctx" {
+ if v, err := strconv.ParseFloat(fields[1], 64); err == nil {
+ return int(v)
+ }
+ }
+ }
+
+ return 0
+}
+
func checkCodexVersion() error {
if _, err := exec.LookPath("codex"); err != nil {
return fmt.Errorf("codex is not installed, install with: npm install -g @openai/codex")
diff --git a/cmd/launch/codex_test.go b/cmd/launch/codex_test.go
index 5c1cc573b..37e1dac5a 100644
--- a/cmd/launch/codex_test.go
+++ b/cmd/launch/codex_test.go
@@ -1,6 +1,10 @@
package launch
import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
"os"
"path/filepath"
"slices"
@@ -12,6 +16,8 @@ import (
func TestCodexArgs(t *testing.T) {
c := &Codex{}
+ catalogPath := filepath.Join("tmp", "model.json")
+ catalogArg := fmt.Sprintf("%s=%q", codexRootModelCatalogJSONKey, catalogPath)
tests := []struct {
name string
@@ -19,15 +25,15 @@ func TestCodexArgs(t *testing.T) {
args []string
want []string
}{
- {"with model", "llama3.2", nil, []string{"--profile", "ollama-launch", "-m", "llama3.2"}},
- {"empty model", "", nil, []string{"--profile", "ollama-launch"}},
- {"with model and extra args", "qwen3.5", []string{"-p", "myprofile"}, []string{"--profile", "ollama-launch", "-m", "qwen3.5", "-p", "myprofile"}},
- {"with sandbox flag", "llama3.2", []string{"--sandbox", "workspace-write"}, []string{"--profile", "ollama-launch", "-m", "llama3.2", "--sandbox", "workspace-write"}},
+ {"with model", "llama3.2", nil, []string{"--profile", "ollama-launch", "-c", catalogArg, "-m", "llama3.2"}},
+ {"empty model", "", nil, []string{"--profile", "ollama-launch", "-c", catalogArg}},
+ {"with model and extra args", "qwen3.5", []string{"-p", "myprofile"}, []string{"--profile", "ollama-launch", "-c", catalogArg, "-m", "qwen3.5", "-p", "myprofile"}},
+ {"with sandbox flag", "llama3.2", []string{"--sandbox", "workspace-write"}, []string{"--profile", "ollama-launch", "-c", catalogArg, "-m", "llama3.2", "--sandbox", "workspace-write"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- got := c.args(tt.model, tt.args)
+ got := c.args(tt.model, catalogPath, tt.args)
if !slices.Equal(got, tt.want) {
t.Errorf("args(%q, %v) = %v, want %v", tt.model, tt.args, got, tt.want)
}
@@ -39,8 +45,9 @@ func TestWriteCodexProfile(t *testing.T) {
t.Run("creates new file when none exists", func(t *testing.T) {
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, "config.toml")
+ catalogPath := filepath.Join(tmpDir, "model.json")
- if err := writeCodexProfile(configPath); err != nil {
+ if err := writeCodexProfile(configPath, catalogPath); err != nil {
t.Fatal(err)
}
@@ -65,6 +72,9 @@ func TestWriteCodexProfile(t *testing.T) {
if !strings.Contains(content, `model_provider = "ollama-launch"`) {
t.Error("missing model_provider key")
}
+ if !strings.Contains(content, fmt.Sprintf("model_catalog_json = %q", catalogPath)) {
+ t.Error("missing model_catalog_json key")
+ }
if !strings.Contains(content, "[model_providers.ollama-launch]") {
t.Error("missing [model_providers.ollama-launch] section")
}
@@ -79,10 +89,11 @@ func TestWriteCodexProfile(t *testing.T) {
t.Run("appends profile to existing file without profile", func(t *testing.T) {
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, "config.toml")
+ catalogPath := filepath.Join(tmpDir, "model.json")
existing := "[some_other_section]\nkey = \"value\"\n"
os.WriteFile(configPath, []byte(existing), 0o644)
- if err := writeCodexProfile(configPath); err != nil {
+ if err := writeCodexProfile(configPath, catalogPath); err != nil {
t.Fatal(err)
}
@@ -100,10 +111,11 @@ func TestWriteCodexProfile(t *testing.T) {
t.Run("replaces existing profile section", func(t *testing.T) {
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, "config.toml")
+ catalogPath := filepath.Join(tmpDir, "model.json")
existing := "[profiles.ollama-launch]\nopenai_base_url = \"http://old:1234/v1/\"\n\n[model_providers.ollama-launch]\nname = \"Ollama\"\nbase_url = \"http://old:1234/v1/\"\n"
os.WriteFile(configPath, []byte(existing), 0o644)
- if err := writeCodexProfile(configPath); err != nil {
+ if err := writeCodexProfile(configPath, catalogPath); err != nil {
t.Fatal(err)
}
@@ -268,10 +280,11 @@ func TestWriteCodexProfile(t *testing.T) {
t.Run("replaces profile while preserving following sections", func(t *testing.T) {
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, "config.toml")
+ catalogPath := filepath.Join(tmpDir, "model.json")
existing := "[profiles.ollama-launch]\nopenai_base_url = \"http://old:1234/v1/\"\n[another_section]\nfoo = \"bar\"\n"
os.WriteFile(configPath, []byte(existing), 0o644)
- if err := writeCodexProfile(configPath); err != nil {
+ if err := writeCodexProfile(configPath, catalogPath); err != nil {
t.Fatal(err)
}
@@ -292,10 +305,11 @@ func TestWriteCodexProfile(t *testing.T) {
t.Run("appends newline to file not ending with newline", func(t *testing.T) {
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, "config.toml")
+ catalogPath := filepath.Join(tmpDir, "model.json")
existing := "[other]\nkey = \"val\""
os.WriteFile(configPath, []byte(existing), 0o644)
- if err := writeCodexProfile(configPath); err != nil {
+ if err := writeCodexProfile(configPath, catalogPath); err != nil {
t.Fatal(err)
}
@@ -315,8 +329,9 @@ func TestWriteCodexProfile(t *testing.T) {
t.Setenv("OLLAMA_HOST", "http://myhost:9999")
tmpDir := t.TempDir()
configPath := filepath.Join(tmpDir, "config.toml")
+ catalogPath := filepath.Join(tmpDir, "model.json")
- if err := writeCodexProfile(configPath); err != nil {
+ if err := writeCodexProfile(configPath, catalogPath); err != nil {
t.Fatal(err)
}
@@ -354,7 +369,7 @@ func TestEnsureCodexConfig(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
- if err := ensureCodexConfig(); err != nil {
+ if err := ensureCodexConfig("llama3.2"); err != nil {
t.Fatal(err)
}
@@ -371,16 +386,25 @@ func TestEnsureCodexConfig(t *testing.T) {
if !strings.Contains(content, "openai_base_url") {
t.Error("missing openai_base_url key")
}
+
+ catalogPath := filepath.Join(tmpDir, ".codex", "model.json")
+ data, err = os.ReadFile(catalogPath)
+ if err != nil {
+ t.Fatalf("model.json not created: %v", err)
+ }
+ if !strings.Contains(string(data), `"slug": "llama3.2"`) {
+ t.Error("missing model catalog entry for selected model")
+ }
})
t.Run("is idempotent", func(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
- if err := ensureCodexConfig(); err != nil {
+ if err := ensureCodexConfig("llama3.2"); err != nil {
t.Fatal(err)
}
- if err := ensureCodexConfig(); err != nil {
+ if err := ensureCodexConfig("llama3.2"); err != nil {
t.Fatal(err)
}
@@ -414,3 +438,217 @@ func assertBackupContains(t *testing.T, pattern, marker string) {
}
t.Fatalf("backup matching %q with marker %q not found", pattern, marker)
}
+
+func TestParseNumCtx(t *testing.T) {
+ tests := []struct {
+ name string
+ parameters string
+ want int
+ }{
+ {"num_ctx set", "num_ctx 8192", 8192},
+ {"num_ctx with other params", "temperature 0.7\nnum_ctx 4096\ntop_p 0.9", 4096},
+ {"no num_ctx", "temperature 0.7\ntop_p 0.9", 0},
+ {"empty string", "", 0},
+ {"malformed value", "num_ctx abc", 0},
+ {"float value", "num_ctx 8192.0", 8192},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := parseNumCtx(tt.parameters); got != tt.want {
+ t.Errorf("parseNumCtx(%q) = %d, want %d", tt.parameters, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestModelInfoContextLength(t *testing.T) {
+ tests := []struct {
+ name string
+ modelInfo map[string]any
+ want int
+ }{
+ {"float64 value", map[string]any{"qwen3_5_moe.context_length": float64(262144)}, 262144},
+ {"int value", map[string]any{"llama.context_length": 131072}, 131072},
+ {"no context_length key", map[string]any{"llama.embedding_length": float64(4096)}, 0},
+ {"empty map", map[string]any{}, 0},
+ {"nil map", nil, 0},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, _ := modelInfoContextLength(tt.modelInfo)
+ if got != tt.want {
+ t.Errorf("modelInfoContextLength() = %d, want %d", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestBuildCodexModelEntryContextWindow(t *testing.T) {
+ tests := []struct {
+ name string
+ modelName string
+ showResponse string
+ envContextLen string
+ wantContext int
+ }{
+ {
+ name: "architectural context length as fallback",
+ modelName: "llama3.2",
+ showResponse: `{
+ "model_info": {"llama.context_length": 131072},
+ "details": {"format": "gguf"}
+ }`,
+ wantContext: 131072,
+ },
+ {
+ name: "OLLAMA_CONTEXT_LENGTH overrides architectural",
+ modelName: "llama3.2",
+ showResponse: `{
+ "model_info": {"llama.context_length": 131072},
+ "details": {"format": "gguf"}
+ }`,
+ envContextLen: "64000",
+ wantContext: 64000,
+ },
+ {
+ name: "num_ctx overrides OLLAMA_CONTEXT_LENGTH",
+ modelName: "llama3.2",
+ showResponse: `{
+ "model_info": {"llama.context_length": 131072},
+ "parameters": "num_ctx 8192",
+ "details": {"format": "gguf"}
+ }`,
+ envContextLen: "64000",
+ wantContext: 8192,
+ },
+ {
+ name: "num_ctx overrides architectural",
+ modelName: "llama3.2",
+ showResponse: `{
+ "model_info": {"llama.context_length": 131072},
+ "parameters": "num_ctx 32768",
+ "details": {"format": "gguf"}
+ }`,
+ wantContext: 32768,
+ },
+ {
+ name: "safetensors uses architectural context only",
+ modelName: "llama3.2",
+ showResponse: `{
+ "model_info": {"llama.context_length": 131072},
+ "parameters": "num_ctx 8192",
+ "details": {"format": "safetensors"}
+ }`,
+ envContextLen: "64000",
+ wantContext: 131072,
+ },
+ {
+ name: "cloud model uses hardcoded limits",
+ modelName: "qwen3.5:cloud",
+ showResponse: `{
+ "model_info": {"qwen3_5_moe.context_length": 131072},
+ "details": {"format": "gguf"}
+ }`,
+ envContextLen: "64000",
+ wantContext: 262144,
+ },
+ {
+ name: "unknown cloud model uses fallback context",
+ modelName: "deepseek-v4-pro:cloud",
+ showResponse: `{
+ "model_info": {"deepseek.context_length": 131072},
+ "details": {"format": "gguf"}
+ }`,
+ envContextLen: "64000",
+ wantContext: codexFallbackContextWindow,
+ },
+ {
+ name: "vision capability without reasoning advertisement",
+ modelName: "llama3.2",
+ showResponse: `{
+ "model_info": {"llama.context_length": 131072},
+ "details": {"format": "gguf"},
+ "capabilities": ["vision", "thinking"]
+ }`,
+ wantContext: 131072,
+ },
+ {
+ name: "system prompt passed through",
+ modelName: "llama3.2",
+ showResponse: `{
+ "model_info": {"llama.context_length": 131072},
+ "details": {"format": "gguf"},
+ "system": "You are a helpful assistant."
+ }`,
+ wantContext: 131072,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/show":
+ fmt.Fprint(w, tt.showResponse)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("OLLAMA_HOST", srv.URL)
+
+ if tt.envContextLen != "" {
+ t.Setenv("OLLAMA_CONTEXT_LENGTH", tt.envContextLen)
+ } else {
+ t.Setenv("OLLAMA_CONTEXT_LENGTH", "")
+ }
+
+ entry := buildCodexModelEntry(tt.modelName)
+
+ gotContext, _ := entry["context_window"].(int)
+ if gotContext != tt.wantContext {
+ t.Errorf("context_window = %d, want %d", gotContext, tt.wantContext)
+ }
+
+ if tt.name == "vision capability without reasoning advertisement" {
+ modalities, _ := entry["input_modalities"].([]string)
+ if !slices.Contains(modalities, "image") {
+ t.Error("expected image in input_modalities")
+ }
+ levels, _ := entry["supported_reasoning_levels"].([]any)
+ if len(levels) != 0 {
+ t.Errorf("supported_reasoning_levels length = %d, want 0", len(levels))
+ }
+ if got, _ := entry["supports_reasoning_summaries"].(bool); got {
+ t.Error("supports_reasoning_summaries = true, want false")
+ }
+ }
+
+ if tt.name == "system prompt passed through" {
+ if got, _ := entry["base_instructions"].(string); got != "You are a helpful assistant." {
+ t.Errorf("base_instructions = %q, want %q", got, "You are a helpful assistant.")
+ }
+ }
+
+ if tt.name == "cloud model uses hardcoded limits" {
+ truncationPolicy, _ := entry["truncation_policy"].(map[string]any)
+ if mode, _ := truncationPolicy["mode"].(string); mode != "tokens" {
+ t.Errorf("truncation_policy mode = %q, want %q", mode, "tokens")
+ }
+ }
+
+ requiredKeys := []string{"slug", "display_name", "apply_patch_tool_type", "shell_type"}
+ for _, key := range requiredKeys {
+ if _, ok := entry[key]; !ok {
+ t.Errorf("missing required key %q", key)
+ }
+ }
+
+ if _, err := json.Marshal(entry); err != nil {
+ t.Errorf("entry is not JSON serializable: %v", err)
+ }
+ })
+ }
+}
diff --git a/docs/integrations/codex.mdx b/docs/integrations/codex.mdx
index 3bde7aa7f..c7e5ee57e 100644
--- a/docs/integrations/codex.mdx
+++ b/docs/integrations/codex.mdx
@@ -21,6 +21,9 @@ npm install -g @openai/codex
ollama launch codex
```
+When launched through `ollama launch codex`, Ollama refreshes the model catalog
+and passes it to Codex for that session.
+
To configure without launching:
```shell