docs: merging to remove retired model recommendations

This commit is contained in:
anra8571 committed 2026-11-06 15:21:50 -08:00
commit 04494de5b2
410 files changed
+44819 -3622

No files matched your search

+47 -13
View File
@@ -131,18 +131,21 @@ jobs:
arch: amd64
preset: 'CUDA 13 ARM64'
build-steps: cuda13Arm64Cross
install: https://packages.nvidia.com/prerelease/cuda/13.4.0/local_installers/cuda_13.4.0_windows_x86_64.exe
# CUDA 13.5 ships the ARM64 cross libraries in a separate installer.
install: https://developer.download.nvidia.com/compute/cuda/13.5.0/local_installers/cuda_13.5.0_windows_x86_64.exe
cuda-cross-install: https://developer.download.nvidia.com/compute/cuda/13.5.0/local_installers/cuda_cross_arm64_13.5.0_windows.exe
cuda-components:
- '"cudart"'
- '"cudart_cross"'
- '"nvcc"'
- '"nvcc_cross"'
- '"cublas_cross"'
- '"cublas_dev"'
- '"crt"'
- '"nvvm"'
- '"nvptxcompiler"'
cuda-version: '13.4'
cuda-cross-components:
- '"cudart_cross"'
- '"nvcc_cross"'
- '"cublas_cross"'
cuda-version: '13.5'
- os: windows
arch: amd64
preset: 'ROCm 7'
@@ -218,17 +221,28 @@ jobs:
C:\Program Files\AMD\ROCm
C:\VulkanSDK
C:\Program Files\NVIDIA\CUDNN
key: ${{ matrix.install }}-${{ matrix.cudnn-install }}
key: ${{ matrix.install }}-${{ matrix.cudnn-install }}${{ matrix.cuda-cross-install }}
- if: startsWith(matrix.preset, 'CUDA ') || startsWith(matrix.preset, 'MLX ')
name: Install CUDA ${{ matrix.cuda-version }}
run: |
$ErrorActionPreference = "Stop"
$ProgressPreference = 'SilentlyContinue'
if ("${{ steps.cache-install.outputs.cache-hit }}" -ne 'true') {
Invoke-WebRequest -Uri "${{ matrix.install }}" -OutFile "install.exe" -MaximumRetryCount 3 -RetryIntervalSec 2
curl.exe --fail --location --retry 3 --retry-all-errors --retry-delay 10 --remove-on-error --silent --show-error --output install.exe "${{ matrix.install }}"
if ($LASTEXITCODE -ne 0) { throw "CUDA download failed: $LASTEXITCODE" }
$subpackages = @(${{ join(matrix.cuda-components, ', ') }}) | Foreach-Object {"${_}_${{ matrix.cuda-version }}"}
Start-Process -FilePath .\install.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait
$installer = Start-Process -FilePath .\install.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait -PassThru
if ($installer.ExitCode -notin @(0, 3010)) { throw "CUDA install failed: $($installer.ExitCode)" }
Remove-Item install.exe
if ("${{ matrix.cuda-cross-install }}") {
curl.exe --fail --location --retry 3 --retry-all-errors --retry-delay 10 --remove-on-error --silent --show-error --output install-cross.exe "${{ matrix.cuda-cross-install }}"
if ($LASTEXITCODE -ne 0) { throw "CUDA cross download failed: $LASTEXITCODE" }
$subpackages = @(${{ join(matrix.cuda-cross-components, ', ') }}) | Foreach-Object {"${_}_${{ matrix.cuda-version }}"}
$installer = Start-Process -FilePath .\install-cross.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait -PassThru
if ($installer.ExitCode -notin @(0, 3010)) { throw "CUDA cross install failed: $($installer.ExitCode)" }
Remove-Item install-cross.exe
}
}
$cudaPath = (Resolve-Path "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\*").path
@@ -286,7 +300,7 @@ jobs:
echo "CUDNN_INCLUDE_PATH=$cudnnRoot\include" | Out-File -FilePath $env:GITHUB_ENV -Append
echo "CUDNN_LIBRARY_PATH=$cudnnRoot\lib\x64" | Out-File -FilePath $env:GITHUB_ENV -Append
echo "$cudnnRoot\bin\x64" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
- if: ${{ !cancelled() && steps.cache-install.outputs.cache-hit != 'true' }}
- if: ${{ success() && steps.cache-install.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v4
with:
path: |
@@ -294,7 +308,7 @@ jobs:
C:\Program Files\AMD\ROCm
C:\VulkanSDK
C:\Program Files\NVIDIA\CUDNN
key: ${{ matrix.install }}-${{ matrix.cudnn-install }}
key: ${{ matrix.install }}-${{ matrix.cudnn-install }}${{ matrix.cuda-cross-install }}
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
@@ -624,7 +638,12 @@ jobs:
GOFLAGS: ${{ needs.setup-environment.outputs.GOFLAGS }}
steps:
- uses: actions/checkout@v4
# Pin: v0.38.x deadlocks on the ~7.5GB type=local archive export
# (moby/buildkit#2950, grpc/grpc-go#9330). Unpin once a buildx release
# vendors grpc-go >= v1.85.0.
- uses: docker/setup-buildx-action@v3
with:
version: v0.37.2
- uses: docker/login-action@v3
with:
username: ${{ vars.DOCKER_USER }}
@@ -659,9 +678,6 @@ jobs:
build-args: ${{ matrix.build-args }}
outputs: type=local,dest=dist/${{ matrix.os }}-${{ matrix.arch }}
cache-from: ${{ matrix.cache-from }}
- name: Deduplicate CUDA libraries
run: |
./scripts/deduplicate_cuda_libs.sh dist/${{ matrix.os }}-${{ matrix.arch }}
- name: Verify Linux build payloads
shell: bash
run: |
@@ -673,6 +689,24 @@ jobs:
do
[ -f "$payload" ] || { echo "missing $payload"; exit 1; }
done
if [ "${{ matrix.arch }}" = "amd64" ] && [ "${{ matrix.suffix }}" != "-rocm" ]; then
for payload in \
"$base/lib/ollama/mlx_cuda_v13/libopenblas.so.0" \
"$base/lib/ollama/mlx_cuda_v13/libgfortran.so.5" \
"$base/lib/ollama/mlx_cuda_v13/libquadmath.so.0"
do
[ -f "$payload" ] || { echo "missing $payload"; exit 1; }
done
mlx_deps="$(ldd "$base/lib/ollama/mlx_cuda_v13/libmlxc.so")"
echo "$mlx_deps"
for dependency in libgfortran.so.5 libquadmath.so.0
do
echo "$mlx_deps" | grep -E "^[[:space:]]*$dependency => .*mlx_cuda_v13/" >/dev/null || {
echo "$dependency does not resolve from the MLX payload"
exit 1
}
done
fi
- run: |
for COMPONENT in bin/* lib/ollama/*; do
case "$COMPONENT" in
+24 -11
View File
@@ -218,7 +218,6 @@ jobs:
copy_payload cuda_jetpack6
fi
./scripts/deduplicate_cuda_libs.sh "${dest}"
- name: Verify Linux build payloads
shell: bash
run: |
@@ -329,18 +328,21 @@ jobs:
arch: amd64
preset: 'CUDA 13 ARM64'
build-steps: cuda13Arm64Cross
install: https://packages.nvidia.com/prerelease/cuda/13.4.0/local_installers/cuda_13.4.0_windows_x86_64.exe
# CUDA 13.5 ships the ARM64 cross libraries in a separate installer.
install: https://developer.download.nvidia.com/compute/cuda/13.5.0/local_installers/cuda_13.5.0_windows_x86_64.exe
cuda-cross-install: https://developer.download.nvidia.com/compute/cuda/13.5.0/local_installers/cuda_cross_arm64_13.5.0_windows.exe
cuda-components:
- '"cudart"'
- '"cudart_cross"'
- '"nvcc"'
- '"nvcc_cross"'
- '"cublas_cross"'
- '"cublas_dev"'
- '"crt"'
- '"nvvm"'
- '"nvptxcompiler"'
cuda-version: '13.4'
cuda-cross-components:
- '"cudart_cross"'
- '"nvcc_cross"'
- '"cublas_cross"'
cuda-version: '13.5'
- os: windows
arch: amd64
preset: 'ROCm 7'
@@ -381,17 +383,28 @@ jobs:
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA
C:\Program Files\AMD\ROCm
C:\VulkanSDK
key: ${{ matrix.install }}
key: ${{ matrix.install }}${{ matrix.cuda-cross-install }}
- if: startsWith(matrix.preset, 'CUDA ')
name: Install CUDA ${{ matrix.cuda-version }}
run: |
$ErrorActionPreference = "Stop"
$ProgressPreference = 'SilentlyContinue'
if ("${{ steps.cache-install.outputs.cache-hit }}" -ne 'true') {
Invoke-WebRequest -Uri "${{ matrix.install }}" -OutFile "install.exe" -MaximumRetryCount 3 -RetryIntervalSec 2
curl.exe --fail --location --retry 3 --retry-all-errors --retry-delay 10 --remove-on-error --silent --show-error --output install.exe "${{ matrix.install }}"
if ($LASTEXITCODE -ne 0) { throw "CUDA download failed: $LASTEXITCODE" }
$subpackages = @(${{ join(matrix.cuda-components, ', ') }}) | Foreach-Object {"${_}_${{ matrix.cuda-version }}"}
Start-Process -FilePath .\install.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait
$installer = Start-Process -FilePath .\install.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait -PassThru
if ($installer.ExitCode -notin @(0, 3010)) { throw "CUDA install failed: $($installer.ExitCode)" }
Remove-Item install.exe
if ("${{ matrix.cuda-cross-install }}") {
curl.exe --fail --location --retry 3 --retry-all-errors --retry-delay 10 --remove-on-error --silent --show-error --output install-cross.exe "${{ matrix.cuda-cross-install }}"
if ($LASTEXITCODE -ne 0) { throw "CUDA cross download failed: $LASTEXITCODE" }
$subpackages = @(${{ join(matrix.cuda-cross-components, ', ') }}) | Foreach-Object {"${_}_${{ matrix.cuda-version }}"}
$installer = Start-Process -FilePath .\install-cross.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait -PassThru
if ($installer.ExitCode -notin @(0, 3010)) { throw "CUDA cross install failed: $($installer.ExitCode)" }
Remove-Item install-cross.exe
}
}
$cudaPath = (Resolve-Path "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\*").path
@@ -430,14 +443,14 @@ jobs:
}
echo "$vulkanPath\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
echo "VULKAN_SDK=$vulkanPath" >> $env:GITHUB_ENV
- if: ${{ !cancelled() && matrix.preset != 'CPU' && steps.cache-install.outputs.cache-hit != 'true' }}
- if: ${{ success() && matrix.preset != 'CPU' && steps.cache-install.outputs.cache-hit != 'true' }}
uses: actions/cache/save@v4
with:
path: |
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA
C:\Program Files\AMD\ROCm
C:\VulkanSDK
key: ${{ matrix.install }}
key: ${{ matrix.install }}${{ matrix.cuda-cross-install }}
- uses: actions/checkout@v4
- uses: actions/cache@v4
with:
+3 -2
View File
@@ -216,7 +216,7 @@ jobs:
- preset: Vulkan
install: https://sdk.lunarg.com/sdk/download/1.4.321.1/windows/vulkansdk-windows-X64-1.4.321.1.exe
superbuild_target: ollama-llama-server-vulkan
superbuild_dir: build\local-superbuild-vulkan
superbuild_dir: build\vk
superbuild_args: '-DOLLAMA_LLAMA_BACKENDS=vulkan'
expected_payload: lib\ollama\vulkan\ggml-vulkan.dll
- preset: 'MLX CUDA 13'
@@ -267,7 +267,8 @@ jobs:
run: |
$ErrorActionPreference = "Stop"
if ("${{ steps.cache-install.outputs.cache-hit }}" -ne 'true') {
Invoke-WebRequest -Uri "${{ matrix.install }}" -OutFile "install.exe" -MaximumRetryCount 3 -RetryIntervalSec 2
curl.exe --fail --location --retry 3 --retry-all-errors --retry-delay 10 --remove-on-error --silent --show-error --output install.exe "${{ matrix.install }}"
if ($LASTEXITCODE -ne 0) { throw "CUDA download failed: $LASTEXITCODE" }
$subpackages = @(${{ join(matrix.cuda-components, ', ') }}) | Foreach-Object {"${_}_${{ matrix.cuda-version }}"}
Start-Process -FilePath .\install.exe -ArgumentList (@("-s") + $subpackages) -NoNewWindow -Wait
Remove-Item install.exe
+1 -1
View File
@@ -1 +1 @@
b11521
b12177
+1 -1
View File
@@ -1 +1 @@
a341b4925024b88b2c593468f16e12f5e17315da
57731b00e8bed710e0750e7356da9f18f8eb3e20
+1 -1
View File
@@ -1 +1 @@
97029597882f674a596958bc71fdec3213ccc192
54a70511f4ea151378d03b657a4fdd823386ea38
+1
View File
@@ -205,6 +205,7 @@ console.log(response.message.content);
#### Mobile
- [Ollama Android Chat](https://github.com/sunshine0523/OllamaServer) - One-click Ollama on Android
- [Quock](https://github.com/matteocelani/quock) - Native iOS client for Ollama Cloud
> SwiftChat, Enchanted, Maid, Ollama App, Reins, and ConfiChat listed above also support mobile platforms.
+21 -19
View File
@@ -804,25 +804,27 @@ type ShowRequest struct {
// ShowResponse is the response returned from [Client.Show].
type ShowResponse struct {
Thinking *model.Thinking `json:"thinking,omitempty"`
License string `json:"license,omitempty"`
Modelfile string `json:"modelfile,omitempty"`
Parameters string `json:"parameters,omitempty"`
Template string `json:"template,omitempty"`
System string `json:"system,omitempty"`
Renderer string `json:"renderer,omitempty"`
Parser string `json:"parser,omitempty"`
Details ModelDetails `json:"details,omitempty"`
Messages []Message `json:"messages,omitempty"`
RemoteModel string `json:"remote_model,omitempty"`
RemoteHost string `json:"remote_host,omitempty"`
ModelInfo map[string]any `json:"model_info"`
ProjectorInfo map[string]any `json:"projector_info,omitempty"`
Tensors []Tensor `json:"tensors,omitempty"`
Capabilities []model.Capability `json:"capabilities,omitempty"`
Manifests []ManifestSummary `json:"manifests,omitempty"`
ModifiedAt time.Time `json:"modified_at,omitempty"`
Requires string `json:"requires,omitempty"`
Thinking *model.Thinking `json:"thinking,omitempty"`
License string `json:"license,omitempty"`
Modelfile string `json:"modelfile,omitempty"`
Parameters string `json:"parameters,omitempty"`
Template string `json:"template,omitempty"`
System string `json:"system,omitempty"`
Renderer string `json:"renderer,omitempty"`
Parser string `json:"parser,omitempty"`
TemplateSource string `json:"template_source,omitempty"`
Details ModelDetails `json:"details,omitempty"`
Messages []Message `json:"messages,omitempty"`
RemoteModel string `json:"remote_model,omitempty"`
RemoteHost string `json:"remote_host,omitempty"`
ModelInfo map[string]any `json:"model_info"`
ProjectorInfo map[string]any `json:"projector_info,omitempty"`
Tensors []Tensor `json:"tensors,omitempty"`
Capabilities []model.Capability `json:"capabilities,omitempty"`
Voices []string `json:"voices,omitempty"`
Manifests []ManifestSummary `json:"manifests,omitempty"`
ModifiedAt time.Time `json:"modified_at,omitempty"`
Requires string `json:"requires,omitempty"`
}
// ManifestSummary describes one child manifest available through a model tag.
+7 -5
View File
@@ -1253,6 +1253,11 @@ func IsCodexDesktopConnected() C.bool {
return C._Bool(codexDesktop.OllamaConfigured())
}
//export IsCodexDesktopDisconnectPending
func IsCodexDesktopDisconnectPending() C.bool {
return C._Bool(!codexDesktop.OllamaConfigured() && codexDesktop.RestorePending())
}
//export IsCodexDesktopRunning
func IsCodexDesktopRunning() C.bool {
return C._Bool(codexDesktop.Running())
@@ -1267,11 +1272,8 @@ func CodexDesktopRequestCount() C.ulonglong {
func SetCodexDesktopConnected(connected, restartConfirmed C.bool) C.bool {
shouldConnect := connected != C._Bool(false)
confirmed := restartConfirmed != C._Bool(false)
if err := setCodexDesktopConnection(shouldConnect, confirmed); err != nil {
slog.Warn("failed to change ChatGPT integration", "connected", shouldConnect, "error", err)
return C._Bool(false)
}
return C._Bool(true)
result := changeCodexDesktopConnection(shouldConnect, confirmed)
return C._Bool(result.Error == "")
}
//export IsClaudeGatewayConfigured
+1
View File
@@ -57,6 +57,7 @@ bool IsClaudeDesktopInstalled(void);
bool IsClaudeDesktopRunning(void);
bool IsCodexDesktopInstalled(void);
bool IsCodexDesktopConnected(void);
bool IsCodexDesktopDisconnectPending(void);
bool IsCodexDesktopRunning(void);
unsigned long long CodexDesktopRequestCount(void);
bool SetCodexDesktopConnected(bool connected, bool restartConfirmed);
+24 -8
View File
@@ -715,6 +715,7 @@ static NSImage *ollamaApplicationIcon(void) {
- (void)refreshCodexAppState {
BOOL installed = IsCodexDesktopInstalled();
BOOL connected = IsCodexDesktopConnected();
BOOL disconnectPending = IsCodexDesktopDisconnectPending();
unsigned long long requests = connected ? CodexDesktopRequestCount() : 0;
NSString *activeStatus = requests == 1
? @"1 request this session"
@@ -722,9 +723,12 @@ static NSImage *ollamaApplicationIcon(void) {
[self.codexAppRow setActiveStatusText:connected
? activeStatus
: nil];
[self.codexAppRow setInactiveStatusText:installed
? @"Use Ollama models in ChatGPT"
: @"Not installed"];
[self.codexAppRow setInactiveStatusText:disconnectPending
? @"Try disconnecting again"
: (installed ? @"Use Ollama models in ChatGPT" : @"Not installed")];
[self.codexAppRow.integrationSwitch setAccessibilityLabel:disconnectPending
? @"Retry disconnecting ChatGPT"
: @"Use Ollama with ChatGPT"];
[self.codexAppRow setIntegrationActive:connected];
[self.codexAppRow setIntegrationReady:installed && connected];
[self applyShowAppsInMenu:shouldShowAppsInMenu()];
@@ -1353,7 +1357,11 @@ didCompleteWithError:(NSError *)error {
}
- (void)toggleCodexApp:(NSButton *)sender {
BOOL enabled = sender.state == NSControlStateValueOn;
BOOL disconnectPending = IsCodexDesktopDisconnectPending();
BOOL enabled = sender.state == NSControlStateValueOn && !disconnectPending;
if (disconnectPending) {
sender.state = NSControlStateValueOff;
}
if (enabled && !IsCodexDesktopInstalled()) {
[self refreshCodexAppState];
NSAlert *installAlert = [[NSAlert alloc] init];
@@ -1399,10 +1407,18 @@ didCompleteWithError:(NSError *)error {
[alert setAlertStyle:NSAlertStyleWarning];
[alert setIcon:ollamaApplicationIcon()];
[alert setMessageText:enabled
? @"Unable to add Ollama models to ChatGPT"
: @"Unable to remove Ollama models from ChatGPT"];
[alert setInformativeText:
@"ChatGPT could not complete the model update. Check the Ollama log for details, then try again."];
? @"Couldn’t connect ChatGPT"
: @"Couldn’t disconnect ChatGPT"];
[alert setInformativeText:@"Please try again."];
if (!enabled && (IsCodexDesktopConnected() || IsCodexDesktopDisconnectPending())) {
[alert addButtonWithTitle:@"Retry"];
[alert addButtonWithTitle:@"Not Now"];
if ([alert runModal] == NSAlertFirstButtonReturn) {
sender.state = NSControlStateValueOff;
[self toggleCodexApp:sender];
}
return;
}
[alert runModal];
return;
}
+1 -11
View File
@@ -29,17 +29,7 @@ func bindCodexDesktop(wv webview.WebView) {
wv.Bind("getCodexDesktopRequestCount", func() uint64 {
return codexDesktop.OllamaRequestCount()
})
wv.Bind("setCodexDesktopConnected", func(enabled, restartConfirmed bool) codexDesktopActionResult {
err := setCodexDesktopConnection(enabled, restartConfirmed)
result := codexDesktopActionResult{Status: getCodexDesktopStatus()}
if errors.Is(err, errCodexDesktopRestartConfirmationRequired) {
result.RestartConfirmationRequired = true
} else if err != nil {
result.Error = err.Error()
slog.Warn("failed to change ChatGPT integration from Settings", "connected", enabled, "error", err)
}
return result
})
wv.Bind("setCodexDesktopConnected", changeCodexDesktopConnection)
wv.Bind("installCodexDesktop", func() codexDesktopInstallResult {
return requestCodexDesktopInstall()
})
+40 -19
View File
@@ -35,6 +35,7 @@ var errCodexDesktopRestartConfirmationRequired = launch.ErrCodexAppRestartConfir
type codexDesktopController interface {
Installed() bool
OllamaConfigured() bool
RestorePending() bool
Running() bool
OllamaRequestCount() uint64
UseOllamaFromDesktop(string, []launch.LaunchModel, bool) error
@@ -62,15 +63,16 @@ var (
)
type codexDesktopStatus struct {
Used bool `json:"used"`
Supported bool `json:"supported"`
Installed bool `json:"installed"`
Connected bool `json:"connected"`
Running bool `json:"running"`
Model string `json:"model,omitempty"`
Models []string `json:"models,omitempty"`
MaxModels int `json:"maxModels"`
Requests uint64 `json:"requests"`
Used bool `json:"used"`
Supported bool `json:"supported"`
Installed bool `json:"installed"`
Connected bool `json:"connected"`
DisconnectPending bool `json:"disconnectPending,omitempty"`
Running bool `json:"running"`
Model string `json:"model,omitempty"`
Models []string `json:"models,omitempty"`
MaxModels int `json:"maxModels"`
Requests uint64 `json:"requests"`
}
type codexDesktopActionResult struct {
@@ -150,15 +152,16 @@ func getCodexDesktopStatus() codexDesktopStatus {
model = models[0]
}
return codexDesktopStatus{
Used: hasUsedCodexDesktopIntegration(),
Supported: true,
Installed: codexDesktop.Installed(),
Connected: connected,
Running: codexDesktop.Running(),
Model: model,
Models: models,
MaxModels: codexDesktopMaxModels,
Requests: requests,
Used: hasUsedCodexDesktopIntegration(),
Supported: true,
Installed: codexDesktop.Installed(),
Connected: connected,
DisconnectPending: !connected && codexDesktop.RestorePending(),
Running: codexDesktop.Running(),
Model: model,
Models: models,
MaxModels: codexDesktopMaxModels,
Requests: requests,
}
}
@@ -166,7 +169,7 @@ func setCodexDesktopConnection(enabled, restartConfirmed bool) error {
codexDesktopMu.Lock()
defer codexDesktopMu.Unlock()
if enabled == codexDesktop.OllamaConfigured() {
if enabled == codexDesktop.OllamaConfigured() && (enabled || !codexDesktop.RestorePending()) {
return nil
}
if !enabled {
@@ -213,6 +216,24 @@ func setCodexDesktopConnection(enabled, restartConfirmed bool) error {
return nil
}
// Native and webview controls share the connection handler.
func changeCodexDesktopConnection(enabled, restartConfirmed bool) codexDesktopActionResult {
err := setCodexDesktopConnection(enabled, restartConfirmed)
result := codexDesktopActionResult{Status: getCodexDesktopStatus()}
if err == nil {
return result
}
result.RestartConfirmationRequired = errors.Is(err, errCodexDesktopRestartConfirmationRequired)
result.Error = "Couldn’t disconnect ChatGPT. Try again."
if enabled {
result.Error = "Couldn’t connect ChatGPT. Try again."
}
if !result.RestartConfirmationRequired {
slog.Warn("failed to change ChatGPT integration", "connected", enabled, "error", err)
}
return result
}
func getCodexDesktopModelsSettings() (codexDesktopModelsSettings, error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
+69 -1
View File
@@ -27,6 +27,10 @@ type fakeCodexDesktopController struct {
installed bool
running bool
configured bool
restorePending bool
restores int
restoreErrs []error
restoreBeforeError bool
launched string
models []string
stopped bool
@@ -43,7 +47,8 @@ func (f *fakeCodexDesktopController) Installed() bool { return f.installed }
func (f *fakeCodexDesktopController) OllamaConfigured() bool {
return f.configured
}
func (f *fakeCodexDesktopController) Running() bool { return f.running }
func (f *fakeCodexDesktopController) RestorePending() bool { return f.restorePending }
func (f *fakeCodexDesktopController) Running() bool { return f.running }
func (f *fakeCodexDesktopController) OllamaRequestCount() uint64 {
return f.requests
}
@@ -133,9 +138,22 @@ func (f *fakeCodexDesktopController) RestoreFromDesktop(restartConfirmed bool) e
if f.running && !restartConfirmed {
return errCodexDesktopRestartConfirmationRequired
}
f.restores++
if len(f.restoreErrs) > 0 {
err := f.restoreErrs[0]
f.restoreErrs = f.restoreErrs[1:]
if err != nil {
if f.restoreBeforeError {
f.configured = false
f.restorePending = true
}
return err
}
}
f.stopped = true
f.running = false
f.configured = false
f.restorePending = false
return nil
}
@@ -264,6 +282,56 @@ func TestSetCodexDesktopConnectionRestoresProfileAfterPartialSwitchFailure(t *te
}
}
func TestChangeCodexDesktopConnectionReportsPartialCleanupAndRetry(t *testing.T) {
t.Setenv("HOME", t.TempDir())
originalController := codexDesktop
t.Cleanup(func() { codexDesktop = originalController })
fake := &fakeCodexDesktopController{
installed: true, configured: true, restoreBeforeError: true,
restoreErrs: []error{errors.New("/private/fixture cleanup obstruction")},
}
codexDesktop = fake
result := changeCodexDesktopConnection(false, false)
if result.Error == "" || result.Status.Connected || !result.Status.DisconnectPending {
t.Fatalf("partial disconnect reported as complete: %+v", result)
}
if result.Error != "Couldn’t disconnect ChatGPT. Try again." {
t.Fatalf("unexpected recovery message: %q", result.Error)
}
result = changeCodexDesktopConnection(false, false)
if result.Error != "" || result.Status.Connected || result.Status.DisconnectPending || fake.restores != 2 {
t.Fatalf("cleanup retry did not finish: result=%+v, restores=%d", result, fake.restores)
}
}
func TestChangeCodexDesktopConnectionPendingCleanupRequiresRestartConsent(t *testing.T) {
t.Setenv("HOME", t.TempDir())
originalController := codexDesktop
t.Cleanup(func() { codexDesktop = originalController })
fake := &fakeCodexDesktopController{installed: true, running: true, restorePending: true}
codexDesktop = fake
result := changeCodexDesktopConnection(false, false)
if !result.RestartConfirmationRequired || !result.Status.DisconnectPending || fake.restores != 0 {
t.Fatalf("pending cleanup bypassed restart consent: %+v", result)
}
result = changeCodexDesktopConnection(false, true)
if result.Error != "" || result.Status.DisconnectPending || fake.restores != 1 {
t.Fatalf("confirmed cleanup did not finish: %+v", result)
}
}
func TestChangeCodexDesktopConnectionHidesErrorDetails(t *testing.T) {
t.Setenv("HOME", t.TempDir())
original := codexDesktop
t.Cleanup(func() { codexDesktop = original })
stubCodexDesktopModelLoader(t)
codexDesktop = &fakeCodexDesktopController{installed: true, launchErrs: []error{errors.New("/private/fixture token=secret")}}
result := changeCodexDesktopConnection(true, false)
if result.Error != "Couldn’t connect ChatGPT. Try again." {
t.Fatalf("unexpected connection message: %q", result.Error)
}
}
func TestApplyCodexDesktopModelsRestartsConfiguredProfile(t *testing.T) {
t.Setenv("HOME", t.TempDir())
originalController := codexDesktop
-16
View File
@@ -1,7 +1,6 @@
import MessageList from "./MessageList";
import ChatForm from "./ChatForm";
import { FileUpload } from "./FileUpload";
import { DisplayUpgrade } from "./DisplayUpgrade";
import { DisplayStale } from "./DisplayStale";
import { DisplayLogin } from "./DisplayLogin";
import {
@@ -26,7 +25,6 @@ import {
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { useSelectedModel } from "@/hooks/useSelectedModel";
import { useUser } from "@/hooks/useUser";
import { useHasVisionCapability } from "@/hooks/useModelCapabilities";
import { Message } from "@/gotypes";
@@ -36,7 +34,6 @@ export default function Chat({ chatId }: { chatId: string }) {
const chatQuery = useChat(chatId === "new" ? "" : chatId);
const chatErrorQuery = useChatError(chatId === "new" ? "" : chatId);
const { selectedModel } = useSelectedModel(chatId);
const { user } = useUser();
const hasVisionCapability = useHasVisionCapability(selectedModel?.model);
const shouldShowStaleDisplay = useShouldShowStaleDisplay(selectedModel);
const dismissStaleModel = useDismissStaleModel();
@@ -259,19 +256,6 @@ export default function Chat({ chatId }: { chatId: string }) {
/>
</div>
)}
{chatError && chatError.code === "usage_limit_upgrade" && (
<div className="pb-2">
<DisplayUpgrade
error={chatError}
onDismiss={clearChatError}
href={
user?.plan === "pro"
? "https://ollama.com/settings/billing"
: "https://ollama.com/upgrade"
}
/>
</div>
)}
{chatError && chatError.code === "cloud_unauthorized" && (
<div className="pb-2">
<DisplayLogin error={chatError} />
@@ -72,6 +72,38 @@ function connectionButton(renderer: ReactTestRenderer) {
}
describe("CodexDesktopRow", () => {
it("retries a pending disconnect after reopening Apps", async () => {
const disconnect = vi.fn().mockResolvedValue({ status: status() });
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("window", {
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
setCodexDesktopConnected: disconnect,
});
let renderer;
try {
await act(async () => {
renderer = create(
<CodexDesktopRow
integration={integration}
initialStatus={status({ disconnectPending: true })}
/>,
);
});
const retry = connectionButton(renderer!);
expect(retry.props["aria-label"]).toBe("Retry disconnecting ChatGPT");
expect(retry.props["aria-pressed"]).toBe(false);
expect(retry.props.disabled).toBe(false);
await act(async () => retry.props.onClick());
expect(disconnect).toHaveBeenCalledWith(false, false);
expect(connectionButton(renderer!).props["aria-label"]).toBe(
"Add Ollama models to ChatGPT",
);
} finally {
await act(async () => renderer?.unmount());
}
});
it("matches Claude's connected copy before the first request", () => {
const html = renderToStaticMarkup(
<CodexDesktopRow
@@ -615,7 +647,7 @@ describe("CodexDesktopRow", () => {
})
.mockResolvedValueOnce({
status: status({ running: true }),
error: "quit ChatGPT: timed out waiting for ChatGPT to exit",
error: "Couldn’t connect ChatGPT. Try again.",
});
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("window", {
@@ -645,7 +677,7 @@ describe("CodexDesktopRow", () => {
expect(getStatus).not.toHaveBeenCalled();
expect(renderer!.root.findByProps({ role: "alert" }).children).toContain(
"quit ChatGPT: timed out waiting for ChatGPT to exit",
"Couldn’t connect ChatGPT. Try again.",
);
expect(toggle.props["aria-pressed"]).toBe(false);
} finally {
+25 -14
View File
@@ -79,6 +79,8 @@ function codexDesktopDescription(
status: CodexDesktopStatus | null,
defaultDescription: string,
): string {
if (status?.disconnectPending)
return "Couldn’t disconnect ChatGPT. Try again.";
if (!status?.connected) return defaultDescription;
const requestCount = status.requests ?? 0;
return `Connected to Ollama · ${requestCount} ${requestCount === 1 ? "request" : "requests"} this session`;
@@ -306,6 +308,7 @@ export function CodexDesktopRow({
}, [phase, beginOperation, finishOperation]);
const connected = status?.connected ?? false;
const disconnectPending = status?.disconnectPending ?? false;
const installed = status?.installed ?? integration.installed ?? false;
const pending = phase !== "idle" || savingAcknowledgment;
const displayedConnected =
@@ -362,7 +365,7 @@ export function CodexDesktopRow({
};
const toggleConnection = async (fromIntro = false) => {
const enabled = fromIntro || !connected;
const enabled = fromIntro || (!connected && !disconnectPending);
const nextPhase = enabled
? installed
? "connecting"
@@ -443,7 +446,10 @@ export function CodexDesktopRow({
setError(result.error);
return;
}
if (result.status.connected !== enabled) {
if (
result.status.connected !== enabled ||
(!enabled && result.status.disconnectPending)
) {
setError(
enabled
? "Ollama could not add its models to ChatGPT."
@@ -508,21 +514,26 @@ export function CodexDesktopRow({
connected={displayedConnected}
busy={pending}
progress={statusLabel}
idleLabel={disconnectPending ? "Retry disconnect" : undefined}
label={
showIntro
? "Finish connecting ChatGPT"
: connected
? "Remove Ollama models from ChatGPT"
: pending
? "Connecting ChatGPT"
: "Add Ollama models to ChatGPT"
disconnectPending
? "Retry disconnecting ChatGPT"
: showIntro
? "Finish connecting ChatGPT"
: connected
? "Remove Ollama models from ChatGPT"
: pending
? "Connecting ChatGPT"
: "Add Ollama models to ChatGPT"
}
title={
connected
? "Remove Ollama models"
: installed
? "Add Ollama models"
: "Install ChatGPT and add Ollama models"
disconnectPending
? "Finish disconnecting ChatGPT"
: connected
? "Remove Ollama models"
: installed
? "Add Ollama models"
: "Install ChatGPT and add Ollama models"
}
disabled={pending || showIntro}
onClick={() => void toggleConnection()}
@@ -1,44 +0,0 @@
import type { ErrorEvent } from "@/gotypes";
import { Display, type DisplayAction } from "@/components/ui/display";
interface DisplayUpgradeProps {
error: ErrorEvent | null;
onDismiss: () => void;
className?: string;
message?: string;
label?: string;
href?: string;
}
export const DisplayUpgrade = ({
error,
onDismiss,
className,
message,
label = "Upgrade",
href = "https://ollama.com/upgrade",
}: DisplayUpgradeProps) => {
if (!error || error.code !== "usage_limit_upgrade") return null;
const isUsageLimit = error.code === "usage_limit_upgrade";
const action: DisplayAction | undefined = isUsageLimit
? {
label,
href,
gradientColors: "from-cyan-500/20 via-purple-500/20 to-green-500/20",
}
: undefined;
const variant = isUsageLimit ? "neutral" : "red";
return (
<Display
message={message || error.error || "An error occurred"}
variant={variant}
onDismiss={onDismiss}
action={action}
className={className}
/>
);
};
@@ -6,12 +6,14 @@ export function IntegrationConnectButton({
busy,
progress,
label,
idleLabel,
...props
}: Pick<ComponentProps<"button">, "onClick" | "disabled" | "title"> & {
connected: boolean;
label: string;
busy: boolean;
progress?: string | null;
idleLabel?: string;
}) {
return (
<button
@@ -29,10 +31,8 @@ export function IntegrationConnectButton({
{progress ?? "Checking…"}
</span>
</>
) : connected ? (
"Disconnect"
) : (
"Connect"
(idleLabel ?? (connected ? "Disconnect" : "Connect"))
)}
</button>
);
+3 -3
View File
@@ -107,9 +107,9 @@ export default function MessageList({
})}
{/* Inline error message */}
{error &&
error.code !== "usage_limit_upgrade" &&
error.code !== "cloud_unauthorized" && <ErrorMessage error={error} />}
{error && error.code !== "cloud_unauthorized" && (
<ErrorMessage error={error} />
)}
{/* Indeterminate loading indicator */}
{showDots && (
+1
View File
@@ -66,6 +66,7 @@ interface CodexDesktopStatus {
supported: boolean;
installed: boolean;
connected: boolean;
disconnectPending?: boolean;
running: boolean;
model?: string;
models?: string[];
+8 -6
View File
@@ -629,15 +629,17 @@ func (s *Server) getError(err error) responses.ErrorEvent {
}
}
var statusErr api.StatusError
if errors.As(err, &statusErr) && statusErr.StatusCode == http.StatusPaymentRequired && strings.HasPrefix(statusErr.ErrorMessage, "this model is not included in your free usage") {
return responses.ErrorEvent{
EventName: "error",
Error: "This model is not included in your free usage. Upgrade your plan: https://ollama.com/upgrade or add usage credits to pay as you go: https://ollama.com/settings",
}
}
errStr := err.Error()
switch {
case strings.Contains(errStr, "402"):
return responses.ErrorEvent{
EventName: "error",
Error: "You've reached your usage limit, please upgrade to continue",
Code: "usage_limit_upgrade",
}
case strings.HasPrefix(errStr, "pull model manifest") && isNetworkError(errStr):
return responses.ErrorEvent{
EventName: "error",
+88
View File
@@ -475,6 +475,94 @@ func TestAuthenticationMiddleware(t *testing.T) {
}
}
func TestGetErrorServerResponse(t *testing.T) {
tests := []struct {
name string
status int
message string
wantError string
wantCode string
}{
{
name: "model not included in free usage",
status: http.StatusPaymentRequired,
message: "this model is not included in your free usage, add usage credits to pay as you go: https://ollama.com/settings or upgrade for included usage: https://ollama.com/upgrade",
wantError: "This model is not included in your free usage. Upgrade your plan: https://ollama.com/upgrade or add usage credits to pay as you go: https://ollama.com/settings",
},
{
name: "model not included in free usage with reference",
status: http.StatusPaymentRequired,
message: "this model is not included in your free usage, add usage credits to pay as you go: https://ollama.com/settings or upgrade for included usage: https://ollama.com/upgrade (ref: test-request)",
wantError: "This model is not included in your free usage. Upgrade your plan: https://ollama.com/upgrade or add usage credits to pay as you go: https://ollama.com/settings",
},
{
name: "free usage text in an unrelated error",
status: http.StatusBadRequest,
message: "this model is not included in your free usage",
},
{
name: "empty usage credit balance",
status: http.StatusPaymentRequired,
message: "this model uses usage credits only (not included plan usage) and your usage credit balance is empty, add usage credits or turn on auto reload at https://ollama.com/settings",
},
{
name: "credit auto reload payment failed",
status: http.StatusPaymentRequired,
message: "usage credits auto reload payment failed, update your payment method or add usage credits at https://ollama.com/settings",
},
{
name: "usage limit",
status: http.StatusTooManyRequests,
message: "you've reached your session usage limit, please wait or upgrade to continue",
},
{
name: "unrelated error containing 402",
status: http.StatusBadRequest,
message: "invalid request (ref: request-402)",
},
{
name: "sign in required",
status: http.StatusUnauthorized,
message: "unauthorized",
wantError: "Could not verify you are signed in. Please sign in and try again.",
wantCode: "cloud_unauthorized",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(tt.status)
json.NewEncoder(w).Encode(map[string]string{"error": tt.message})
}))
defer ts.Close()
t.Setenv("OLLAMA_HOST", ts.URL)
server := &Server{}
client := server.inferenceClient()
err := client.Chat(context.Background(), &api.ChatRequest{Model: "test"}, func(api.ChatResponse) error {
return nil
})
if err == nil {
t.Fatal("chat request succeeded, want an error")
}
want := responses.ErrorEvent{
EventName: "error",
Error: err.Error(),
Code: tt.wantCode,
}
if tt.wantError != "" {
want.Error = tt.wantError
}
if got := server.getError(err); got != want {
t.Errorf("getError() = %+v, want %+v", got, want)
}
})
}
}
func TestUserAgent(t *testing.T) {
ua := userAgent()
+44 -8
View File
@@ -12,6 +12,20 @@ set(_ollama_mlx_backends_doc "Semicolon-separated MLX backends to build: cuda_v1
set(OLLAMA_VERSION "0.0.0" CACHE STRING "Ollama version embedded in the local Go binary")
set(OLLAMA_PAYLOAD_INSTALL_PREFIX "${CMAKE_BINARY_DIR}" CACHE PATH
"Build-time staging prefix for nested Ollama native payloads")
set(OLLAMA_MLX_PAYLOAD_INSTALL_PREFIX "" CACHE PATH
"Optional separate staging prefix for the MLX overlay payload")
get_filename_component(_ollama_mlx_base_install_prefix
"${OLLAMA_PAYLOAD_INSTALL_PREFIX}" ABSOLUTE BASE_DIR "${CMAKE_BINARY_DIR}")
set(_ollama_mlx_payload_install_prefix "${_ollama_mlx_base_install_prefix}")
set(_ollama_mlx_overlay_package OFF)
if(OLLAMA_MLX_PAYLOAD_INSTALL_PREFIX)
get_filename_component(_ollama_mlx_payload_install_prefix
"${OLLAMA_MLX_PAYLOAD_INSTALL_PREFIX}" ABSOLUTE BASE_DIR "${CMAKE_BINARY_DIR}")
if(NOT "${_ollama_mlx_payload_install_prefix}" STREQUAL "${_ollama_mlx_base_install_prefix}")
set(_ollama_mlx_overlay_package ON)
endif()
endif()
string(REGEX REPLACE "^v" "" OLLAMA_VERSION "${OLLAMA_VERSION}")
@@ -102,6 +116,12 @@ else()
set(OLLAMA_MLX_BACKENDS "${OLLAMA_MLX_BACKENDS}" CACHE STRING "${_ollama_mlx_backends_doc}")
endif()
if(OLLAMA_MLX_BACKENDS AND _ollama_mlx_overlay_package)
add_custom_target(ollama-mlx-overlay-clean
COMMAND ${CMAKE_COMMAND} -E rm -rf "${_ollama_mlx_payload_install_prefix}"
COMMENT "Cleaning MLX overlay staging directory")
endif()
if(NOT OLLAMA_HAVE_LLAMA_SERVER)
if(OLLAMA_LLAMA_BACKENDS)
message(FATAL_ERROR "llama/server is required when OLLAMA_LLAMA_BACKENDS is set")
@@ -528,13 +548,14 @@ function(ollama_add_mlx_build name)
ollama_collect_cache_args_with_prefix("MLX_" _mlx_cache_args)
set(_cmake_args
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DCMAKE_INSTALL_PREFIX=${OLLAMA_PAYLOAD_INSTALL_PREFIX}
-DCMAKE_INSTALL_PREFIX=${_ollama_mlx_base_install_prefix}
-DOLLAMA_LIB_DIR:STRING=${OLLAMA_LIB_DIR}
-DOLLAMA_RUNNER_DIR=${ARG_RUNNER_DIR}
-DOLLAMA_SOURCE_DIR=${CMAKE_SOURCE_DIR}
-DFETCHCONTENT_SOURCE_DIR_MLX=${OLLAMA_MLX_SOURCE_DIR}
-DFETCHCONTENT_SOURCE_DIR_MLX-C=${OLLAMA_MLX_C_SOURCE_DIR}
-DOLLAMA_MLX_GENERATE_WRAPPERS=OFF
-DOLLAMA_MLX_OVERLAY_PACKAGE=${_ollama_mlx_overlay_package}
${ARG_CMAKE_ARGS}
${_mlx_cache_args}
)
@@ -575,6 +596,26 @@ function(ollama_add_mlx_build name)
${_cmake_args})
endif()
set(_install_command)
list(APPEND _install_command
${CMAKE_COMMAND} --install <BINARY_DIR>
${OLLAMA_NATIVE_CONFIG_ARG}
--prefix "${_ollama_mlx_payload_install_prefix}"
--component MLX
COMMAND ${CMAKE_COMMAND} --install <BINARY_DIR>
${OLLAMA_NATIVE_CONFIG_ARG}
--prefix "${_ollama_mlx_payload_install_prefix}"
--component MLX_VENDOR
COMMAND ${CMAKE_COMMAND} --install <BINARY_DIR>
${OLLAMA_NATIVE_CONFIG_ARG}
--prefix "${_ollama_mlx_base_install_prefix}"
--component MLX_SHARED)
set(_mlx_dependencies ollama-mlx-sources)
if(_ollama_mlx_overlay_package)
list(APPEND _mlx_dependencies ollama-mlx-overlay-clean)
endif()
ExternalProject_Add(ollama-mlx-${name}
SOURCE_DIR ${CMAKE_SOURCE_DIR}/cmake/mlx
BINARY_DIR ${_build_dir}
@@ -584,13 +625,8 @@ function(ollama_add_mlx_build name)
${OLLAMA_NATIVE_BUILD_TARGET_ARG} mlx
${OLLAMA_NATIVE_BUILD_TARGET_ARG} mlxc
${OLLAMA_NATIVE_BUILD_TARGET_ARG} ollama_xgrammar
INSTALL_COMMAND ${CMAKE_COMMAND} --install <BINARY_DIR>
${OLLAMA_NATIVE_CONFIG_ARG}
--component MLX
COMMAND ${CMAKE_COMMAND} --install <BINARY_DIR>
${OLLAMA_NATIVE_CONFIG_ARG}
--component MLX_VENDOR
DEPENDS ollama-mlx-sources
INSTALL_COMMAND ${_install_command}
DEPENDS ${_mlx_dependencies}
LIST_SEPARATOR |
BUILD_ALWAYS TRUE
${OLLAMA_NATIVE_EXTERNAL_OPTIONS}
+188 -97
View File
@@ -19,16 +19,6 @@ set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS ON)
if(APPLE)
set(CMAKE_BUILD_RPATH "@loader_path")
set(CMAKE_INSTALL_RPATH "@loader_path")
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
elseif(UNIX)
set(CMAKE_BUILD_RPATH "$ORIGIN")
set(CMAKE_INSTALL_RPATH "$ORIGIN")
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
endif()
if(NOT DEFINED OLLAMA_SOURCE_DIR OR "${OLLAMA_SOURCE_DIR}" STREQUAL "")
get_filename_component(OLLAMA_SOURCE_DIR "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE)
endif()
@@ -39,6 +29,42 @@ set(OLLAMA_LIB_DIR "lib/ollama" CACHE STRING "Install destination for Ollama run
set(OLLAMA_RUNNER_DIR "" CACHE STRING "Ollama runtime payload subdirectory")
set(OLLAMA_BUILD_DIR ${CMAKE_BINARY_DIR}/lib/ollama)
set(OLLAMA_INSTALL_DIR ${OLLAMA_LIB_DIR}/${OLLAMA_RUNNER_DIR})
set(OLLAMA_DEPENDENCY_INSTALL_DIR "")
set(OLLAMA_DEPENDENCY_RUNNER_DIR "")
if(OLLAMA_RUNNER_DIR MATCHES "^mlx_(cuda.*)$")
set(OLLAMA_DEPENDENCY_RUNNER_DIR "${CMAKE_MATCH_1}")
set(OLLAMA_DEPENDENCY_INSTALL_DIR "${OLLAMA_LIB_DIR}/${OLLAMA_DEPENDENCY_RUNNER_DIR}")
endif()
set(OLLAMA_MLX_JIT_INCLUDE_DESTINATIONS "${OLLAMA_INSTALL_DIR}/include")
set(OLLAMA_MLX_SHARED_CUDA_INSTALL_DIR "${OLLAMA_INSTALL_DIR}")
set(OLLAMA_MLX_PRIVATE_CUDA_INSTALL_DIR "${OLLAMA_INSTALL_DIR}")
set(OLLAMA_MLX_CUDNN_INSTALL_DIR "${OLLAMA_INSTALL_DIR}")
set(OLLAMA_MLX_RPATH)
if(APPLE)
set(OLLAMA_MLX_RPATH "@loader_path")
elseif(WIN32)
if(OLLAMA_DEPENDENCY_INSTALL_DIR)
set(OLLAMA_MLX_SHARED_CUDA_INSTALL_DIR "${OLLAMA_DEPENDENCY_INSTALL_DIR}")
set(OLLAMA_MLX_PRIVATE_CUDA_INSTALL_DIR "${OLLAMA_DEPENDENCY_INSTALL_DIR}")
set(MLX_CUDA_BIN_DIR "../${OLLAMA_DEPENDENCY_RUNNER_DIR}" CACHE STRING "" FORCE)
set(MLX_CUDNN_BIN_DIR "." CACHE STRING "" FORCE)
endif()
elseif(UNIX)
set(OLLAMA_MLX_RPATH "$ORIGIN")
list(APPEND OLLAMA_MLX_JIT_INCLUDE_DESTINATIONS "${OLLAMA_LIB_DIR}/include")
if(OLLAMA_DEPENDENCY_INSTALL_DIR)
set(OLLAMA_MLX_SHARED_CUDA_INSTALL_DIR "${OLLAMA_DEPENDENCY_INSTALL_DIR}")
list(APPEND OLLAMA_MLX_RPATH "$ORIGIN/../${OLLAMA_DEPENDENCY_RUNNER_DIR}")
endif()
endif()
if(OLLAMA_MLX_RPATH)
set(CMAKE_BUILD_RPATH ${OLLAMA_MLX_RPATH})
set(CMAKE_INSTALL_RPATH ${OLLAMA_MLX_RPATH})
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON)
endif()
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${OLLAMA_BUILD_DIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${OLLAMA_BUILD_DIR})
@@ -52,6 +78,7 @@ if(MLX_CUDA_ARCHITECTURES OR CMAKE_CUDA_ARCHITECTURES)
endif()
option(OLLAMA_MLX_GENERATE_WRAPPERS "Regenerate MLX Go wrappers" OFF)
option(OLLAMA_MLX_OVERLAY_PACKAGE "Install the MLX payload as an overlay package" OFF)
message(STATUS "Setting up MLX (this takes a while...)")
foreach(_cudnn_var CUDNN_INCLUDE_PATH CUDNN_LIBRARY_PATH)
@@ -61,6 +88,20 @@ foreach(_cudnn_var CUDNN_INCLUDE_PATH CUDNN_LIBRARY_PATH)
endforeach()
add_subdirectory(${OLLAMA_SOURCE_DIR}/mlx ${CMAKE_BINARY_DIR}/mlx)
if(UNIX AND NOT APPLE)
foreach(_mlx_target mlx mlxc)
if(TARGET ${_mlx_target})
set_target_properties(${_mlx_target} PROPERTIES
BUILD_RPATH "${OLLAMA_MLX_RPATH}"
INSTALL_RPATH "${OLLAMA_MLX_RPATH}"
BUILD_WITH_INSTALL_RPATH ON)
# DT_RPATH is inherited by transitive dependencies such as
# OpenBLAS -> libgfortran -> libquadmath; DT_RUNPATH is not.
target_link_options(${_mlx_target} PRIVATE LINKER:--disable-new-dtags)
endif()
endforeach()
endif()
include(FetchContent)
set(XGRAMMAR_VERSION v0.2.7)
FetchContent_Declare(xgrammar
@@ -93,7 +134,7 @@ add_subdirectory(${OLLAMA_SOURCE_DIR}/mlxrunner/xgrammar/native ${CMAKE_BINARY_D
find_package(CUDAToolkit)
# Build list of directories for runtime dependency resolution.
set(MLX_RUNTIME_DIRS ${CUDAToolkit_BIN_DIR} ${CUDAToolkit_BIN_DIR}/x64 ${CUDAToolkit_LIBRARY_DIR})
set(MLX_RUNTIME_SEARCH_DIRS ${CUDAToolkit_BIN_DIR} ${CUDAToolkit_BIN_DIR}/x64 ${CUDAToolkit_LIBRARY_DIR})
# Add cuDNN bin paths for DLLs (Windows MLX CUDA builds).
# CUDNN_ROOT_DIR is the standard CMake variable for cuDNN location.
if(CUDNN_ROOT_DIR)
@@ -105,24 +146,62 @@ if(_cudnn_root)
file(TO_CMAKE_PATH "${_cudnn_root}" _cudnn_root)
# cuDNN 9.x has versioned subdirectories under bin/ (e.g., bin/13.0/).
file(GLOB CUDNN_BIN_SUBDIRS "${_cudnn_root}/bin/*")
list(APPEND MLX_RUNTIME_DIRS ${CUDNN_BIN_SUBDIRS})
list(APPEND MLX_RUNTIME_SEARCH_DIRS ${CUDNN_BIN_SUBDIRS})
endif()
# Add build output directory and MLX dependency build directories.
list(APPEND MLX_RUNTIME_DIRS ${OLLAMA_BUILD_DIR})
list(APPEND MLX_RUNTIME_SEARCH_DIRS ${OLLAMA_BUILD_DIR})
if(UNIX AND NOT APPLE)
list(APPEND MLX_RUNTIME_SEARCH_DIRS ${CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES})
endif()
# OpenBLAS DLL location (pre-built zip extracts into openblas-src/bin/).
list(APPEND MLX_RUNTIME_DIRS ${CMAKE_BINARY_DIR}/_deps/openblas-src/bin)
list(APPEND MLX_RUNTIME_SEARCH_DIRS ${CMAKE_BINARY_DIR}/_deps/openblas-src/bin)
# NCCL: on Linux, if real NCCL is found, cmake bundles libnccl.so via the
# regex below. If NCCL is not found, MLX links a static stub (OBJECT lib)
# so there is no runtime dependency. This path covers the stub build dir
# for windows so we include the DLL in our dependencies.
list(APPEND MLX_RUNTIME_DIRS ${CMAKE_BINARY_DIR}/_deps/mlx-build/mlx/distributed/nccl/nccl_stub-prefix/src/nccl_stub-build/Release)
list(APPEND MLX_RUNTIME_SEARCH_DIRS ${CMAKE_BINARY_DIR}/_deps/mlx-build/mlx/distributed/nccl/nccl_stub-prefix/src/nccl_stub-build/Release)
# Non-link-time deps stay explicit; link-time deps derive from the mlx target.
set(MLX_INCLUDE_REGEXES cublas cublasLt cudart cufft nvrtc nvrtc-builtins cudnn nccl cusolver cusparse nv[Jj]it[Ll]ink openblas gfortran)
set(MLX_INCLUDE_REGEXES cublas cublasLt cudart cufft nvrtc nvrtc-builtins cudnn nccl cusolver cusparse nv[Jj]it[Ll]ink openblas gfortran quadmath)
# On Windows, also include dl.dll (dlfcn-win32 POSIX emulation layer).
if(WIN32)
list(APPEND MLX_INCLUDE_REGEXES "^dl\\.dll$")
endif()
set(MLX_RUNTIME_DEPENDENCY_FILTERS
DIRECTORIES ${MLX_RUNTIME_SEARCH_DIRS}
PRE_INCLUDE_REGEXES ${MLX_INCLUDE_REGEXES}
PRE_EXCLUDE_REGEXES ".*")
set(MLX_EXPLICIT_CUDA_RUNTIME_REGEXES)
if(WIN32)
list(APPEND MLX_EXPLICIT_CUDA_RUNTIME_REGEXES
"[/\\\\]cublas[^/\\\\]*\\.dll$"
"[/\\\\]cudart[^/\\\\]*\\.dll$"
"[/\\\\]cudnn[^/\\\\]*\\.dll$"
"[/\\\\]cufft[^/\\\\]*\\.dll$"
"[/\\\\]cusolver[^/\\\\]*\\.dll$"
"[/\\\\]cusparse[^/\\\\]*\\.dll$"
"[/\\\\]nvfatbin[^/\\\\]*\\.dll$"
"[/\\\\][nN][vV][jJ][iI][tT][lL][iI][nN][kK][^/\\\\]*\\.dll$"
"[/\\\\]nvrtc[^/\\\\]*\\.dll$"
"[/\\\\]nvrtc-builtins[^/\\\\]*\\.dll$")
elseif(UNIX AND NOT APPLE)
list(APPEND MLX_EXPLICIT_CUDA_RUNTIME_REGEXES
"[/\\\\]libcublas\\.so(\\..*)?$"
"[/\\\\]libcublasLt\\.so(\\..*)?$"
"[/\\\\]libcudart\\.so(\\..*)?$"
"[/\\\\]libcudnn[^/\\\\]*\\.so(\\..*)?$"
"[/\\\\]libcufft\\.so(\\..*)?$"
"[/\\\\]libcusolver\\.so(\\..*)?$"
"[/\\\\]libcusparse\\.so(\\..*)?$"
"[/\\\\]libnvfatbin\\.so(\\..*)?$"
"[/\\\\]libnvJitLink\\.so(\\..*)?$"
"[/\\\\]libnvrtc\\.so(\\..*)?$"
"[/\\\\]libnvrtc-builtins\\.so(\\..*)?$")
endif()
if(MLX_EXPLICIT_CUDA_RUNTIME_REGEXES)
list(APPEND MLX_RUNTIME_DEPENDENCY_FILTERS
POST_EXCLUDE_REGEXES ${MLX_EXPLICIT_CUDA_RUNTIME_REGEXES})
endif()
# Keep mlx/mlxc targets separate from runtime dependencies so --strip only
# applies to the binaries we build, not vendor DLLs/libs.
@@ -198,9 +277,7 @@ install(CODE "
" COMPONENT MLX)
install(RUNTIME_DEPENDENCY_SET mlx_runtime_deps
DIRECTORIES ${MLX_RUNTIME_DIRS}
PRE_INCLUDE_REGEXES ${MLX_INCLUDE_REGEXES}
PRE_EXCLUDE_REGEXES ".*"
${MLX_RUNTIME_DEPENDENCY_FILTERS}
RUNTIME DESTINATION ${OLLAMA_INSTALL_DIR} COMPONENT MLX_VENDOR
LIBRARY DESTINATION ${OLLAMA_INSTALL_DIR} COMPONENT MLX_VENDOR
)
@@ -222,21 +299,6 @@ if(APPLE AND CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64")
COMPONENT MLX)
endif()
# Install headers for NVRTC JIT compilation at runtime.
# MLX's own install rules use the default component so they get skipped by
# --component MLX. Headers are installed alongside libmlx in OLLAMA_INSTALL_DIR.
#
# Layout:
# ${OLLAMA_INSTALL_DIR}/include/cccl/ - CCCL headers
# ${OLLAMA_INSTALL_DIR}/include/{cute,cutlass}/ - CUTLASS/CUTE headers
# ${OLLAMA_INSTALL_DIR}/include/ - CUDA runtime/core headers
#
# MLX's jit_module.cpp resolves JIT support headers from the backend-local
# include directory. On Linux it also probes current_binary_dir().parent_path()
# / "include", so we create a symlink from lib/ollama/include to the backend
# include directory for archive packaging.
# This will need refinement if we add multiple CUDA versions for MLX in the future.
# CUDA runtime headers are found via CUDA_PATH env var (set by mlxrunner).
set(_mlx_jit_cccl_include_dir "")
if(CUDAToolkit_FOUND)
foreach(_dir ${CUDAToolkit_INCLUDE_DIRS})
@@ -252,28 +314,25 @@ endif()
if(_mlx_jit_cccl_include_dir)
foreach(_cccl_dir cuda nv cub thrust)
if(EXISTS "${_mlx_jit_cccl_include_dir}/${_cccl_dir}")
install(DIRECTORY "${_mlx_jit_cccl_include_dir}/${_cccl_dir}"
DESTINATION ${OLLAMA_INSTALL_DIR}/include/cccl
COMPONENT MLX)
foreach(_dst IN LISTS OLLAMA_MLX_JIT_INCLUDE_DESTINATIONS)
install(DIRECTORY "${_mlx_jit_cccl_include_dir}/${_cccl_dir}"
DESTINATION ${_dst}/cccl
COMPONENT MLX)
endforeach()
endif()
endforeach()
endif()
if(EXISTS ${CMAKE_BINARY_DIR}/_deps/cutlass-src/include/cute)
install(DIRECTORY ${CMAKE_BINARY_DIR}/_deps/cutlass-src/include/cute
DESTINATION ${OLLAMA_INSTALL_DIR}/include
COMPONENT MLX)
install(DIRECTORY ${CMAKE_BINARY_DIR}/_deps/cutlass-src/include/cutlass
DESTINATION ${OLLAMA_INSTALL_DIR}/include
COMPONENT MLX)
foreach(_dst IN LISTS OLLAMA_MLX_JIT_INCLUDE_DESTINATIONS)
install(DIRECTORY ${CMAKE_BINARY_DIR}/_deps/cutlass-src/include/cute
DESTINATION ${_dst}
COMPONENT MLX)
install(DIRECTORY ${CMAKE_BINARY_DIR}/_deps/cutlass-src/include/cutlass
DESTINATION ${_dst}
COMPONENT MLX)
endforeach()
endif()
# Install CUDA runtime/core headers needed by MLX JIT kernels.
# NVIDIA's NVRTC bundled-header model is CUDA Runtime + CCCL, not the entire
# toolkit include tree. Keep CCCL coherent above, include CUTLASS/CUTE above,
# and avoid shipping unrelated SDK headers such as NPP, CUPTI, cuRAND, NVML,
# cuBLAS, cuSPARSE, and cuSOLVER.
# The Go mlxrunner sets CUDA_PATH to OLLAMA_INSTALL_DIR so MLX finds them at
# $CUDA_PATH/include via NVRTC --include-path.
if(CUDAToolkit_FOUND)
# CUDAToolkit_INCLUDE_DIRS may be a semicolon-separated list
# (e.g. ".../include;.../include/cccl"). Find the entry that
@@ -288,8 +347,6 @@ if(CUDAToolkit_FOUND)
if(NOT _cuda_inc)
message(WARNING "Could not find cuda_runtime_api.h in CUDAToolkit_INCLUDE_DIRS: ${CUDAToolkit_INCLUDE_DIRS}")
else()
set(_dst "${OLLAMA_INSTALL_DIR}/include")
set(_mlx_jit_cuda_headers
builtin_types.h
channel_descriptor.h
@@ -367,28 +424,23 @@ if(CUDAToolkit_FOUND)
endif()
endforeach()
if(_mlx_jit_cuda_header_paths)
install(FILES ${_mlx_jit_cuda_header_paths}
DESTINATION ${_dst}
COMPONENT MLX)
foreach(_dst IN LISTS OLLAMA_MLX_JIT_INCLUDE_DESTINATIONS)
install(FILES ${_mlx_jit_cuda_header_paths}
DESTINATION ${_dst}
COMPONENT MLX)
endforeach()
endif()
foreach(_runtime_dir cooperative_groups crt)
if(EXISTS "${_cuda_inc}/${_runtime_dir}")
install(DIRECTORY "${_cuda_inc}/${_runtime_dir}"
DESTINATION ${_dst}
COMPONENT MLX)
foreach(_dst IN LISTS OLLAMA_MLX_JIT_INCLUDE_DESTINATIONS)
install(DIRECTORY "${_cuda_inc}/${_runtime_dir}"
DESTINATION ${_dst}
COMPONENT MLX)
endforeach()
endif()
endforeach()
if(NOT WIN32 AND NOT APPLE)
install(CODE "
set(_link \"${CMAKE_INSTALL_PREFIX}/${OLLAMA_LIB_DIR}/include\")
set(_target \"${OLLAMA_RUNNER_DIR}/include\")
if(NOT EXISTS \${_link})
execute_process(COMMAND \${CMAKE_COMMAND} -E create_symlink \${_target} \${_link})
endif()
" COMPONENT MLX)
endif()
endif()
endif()
@@ -403,46 +455,85 @@ if(WIN32 AND TARGET dl)
COMPONENT MLX)
endif()
# dlopen'd runtime libs, derived from MLX's dynamic.c/delayload.cpp
if(CUDAToolkit_FOUND)
file(GLOB MLX_CUDA_LIBS
"${CUDAToolkit_LIBRARY_DIR}/libcudart.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcublas.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcublasLt.so*"
"${CUDAToolkit_LIBRARY_DIR}/libnvrtc.so*"
"${CUDAToolkit_LIBRARY_DIR}/libnvrtc-builtins.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcufft.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcusolver.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcusparse.so*"
"${CUDAToolkit_LIBRARY_DIR}/libnvJitLink.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcudnn*.so*")
set(MLX_SHARED_CUDA_LIBS)
set(MLX_PRIVATE_CUDA_LIBS)
set(MLX_CUDNN_LIBS)
if(WIN32)
file(GLOB MLX_CUDA_DLLS
"${CUDAToolkit_BIN_DIR}/nvrtc-builtins64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/nvrtc-builtins64_*.dll"
"${CUDAToolkit_BIN_DIR}/cusolver64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/cusolver64_*.dll"
"${CUDAToolkit_BIN_DIR}/cusparse64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/cusparse64_*.dll"
file(GLOB MLX_SHARED_CUDA_LIBS
"${CUDAToolkit_BIN_DIR}/cublas64_*.dll"
"${CUDAToolkit_BIN_DIR}/cublasLt64_*.dll"
"${CUDAToolkit_BIN_DIR}/cudart64_*.dll"
"${CUDAToolkit_BIN_DIR}/nvfatbin_*.dll"
"${CUDAToolkit_BIN_DIR}/nvJitLink_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/nvJitLink_*.dll")
list(APPEND MLX_CUDA_LIBS ${MLX_CUDA_DLLS})
"${CUDAToolkit_BIN_DIR}/nvrtc64_*.dll"
"${CUDAToolkit_BIN_DIR}/nvrtc-builtins64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/cublas64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/cublasLt64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/cudart64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/nvfatbin_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/nvJitLink_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/nvrtc64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/nvrtc-builtins64_*.dll")
file(GLOB MLX_PRIVATE_CUDA_LIBS
"${CUDAToolkit_BIN_DIR}/cufft64_*.dll"
"${CUDAToolkit_BIN_DIR}/cusolver64_*.dll"
"${CUDAToolkit_BIN_DIR}/cusparse64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/cufft64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/cusolver64_*.dll"
"${CUDAToolkit_BIN_DIR}/x64/cusparse64_*.dll")
elseif(UNIX AND NOT APPLE)
file(GLOB MLX_SHARED_CUDA_LIBS
"${CUDAToolkit_LIBRARY_DIR}/libcudart.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcublas.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcublasLt.so*"
"${CUDAToolkit_LIBRARY_DIR}/libnvrtc.so*"
"${CUDAToolkit_LIBRARY_DIR}/libnvrtc-builtins.so*"
"${CUDAToolkit_LIBRARY_DIR}/libnvfatbin.so*"
"${CUDAToolkit_LIBRARY_DIR}/libnvJitLink.so*")
file(GLOB MLX_PRIVATE_CUDA_LIBS
"${CUDAToolkit_LIBRARY_DIR}/libcufft.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcusolver.so*"
"${CUDAToolkit_LIBRARY_DIR}/libcusparse.so*")
endif()
find_library(MLX_CUDNN_LIBRARY NAMES cudnn HINTS "$ENV{CUDNN_LIBRARY_PATH}")
if(MLX_CUDNN_LIBRARY)
get_filename_component(MLX_CUDNN_LIBRARY_DIR "${MLX_CUDNN_LIBRARY}" DIRECTORY)
file(GLOB MLX_CUDNN_LIBS "${MLX_CUDNN_LIBRARY_DIR}/libcudnn*.so*")
list(APPEND MLX_CUDA_LIBS ${MLX_CUDNN_LIBS})
if(MLX_SHARED_CUDA_LIBS)
list(REMOVE_DUPLICATES MLX_SHARED_CUDA_LIBS)
install(FILES ${MLX_SHARED_CUDA_LIBS}
DESTINATION ${OLLAMA_MLX_SHARED_CUDA_INSTALL_DIR}
COMPONENT MLX_SHARED)
endif()
if(MLX_PRIVATE_CUDA_LIBS)
list(REMOVE_DUPLICATES MLX_PRIVATE_CUDA_LIBS)
install(FILES ${MLX_PRIVATE_CUDA_LIBS}
DESTINATION ${OLLAMA_MLX_PRIVATE_CUDA_INSTALL_DIR}
COMPONENT MLX_VENDOR)
endif()
if(UNIX AND NOT APPLE)
find_library(MLX_CUDNN_LIBRARY NAMES cudnn
HINTS "${CUDNN_LIBRARY_PATH}" "$ENV{CUDNN_LIBRARY_PATH}")
if(MLX_CUDNN_LIBRARY)
get_filename_component(MLX_CUDNN_LIBRARY_DIR "${MLX_CUDNN_LIBRARY}" DIRECTORY)
file(GLOB MLX_CUDNN_LIBS "${MLX_CUDNN_LIBRARY_DIR}/libcudnn*.so*")
endif()
endif()
if(WIN32 AND _cudnn_root)
file(GLOB MLX_CUDNN_DLLS
"${_cudnn_root}/bin/${CUDAToolkit_VERSION_MAJOR}.0/cudnn*.dll"
"${_cudnn_root}/bin/x64/cudnn*.dll")
list(APPEND MLX_CUDA_LIBS ${MLX_CUDNN_DLLS})
list(APPEND MLX_CUDNN_LIBS ${MLX_CUDNN_DLLS})
endif()
if(MLX_CUDA_LIBS)
install(FILES ${MLX_CUDA_LIBS}
DESTINATION ${OLLAMA_INSTALL_DIR}
if(MLX_CUDNN_LIBS)
list(REMOVE_DUPLICATES MLX_CUDNN_LIBS)
install(FILES ${MLX_CUDNN_LIBS}
DESTINATION ${OLLAMA_MLX_CUDNN_INSTALL_DIR}
COMPONENT MLX_VENDOR)
endif()
endif()
if(OLLAMA_MLX_OVERLAY_PACKAGE)
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/README_MLX.txt"
"Extract this MLX package to the same location as the Ollama base package.\n")
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/README_MLX.txt"
DESTINATION .
COMPONENT MLX)
endif()
+7
View File
@@ -31,7 +31,14 @@ if(NOT CMAKE_CXX_COMPILER)
REQUIRED)
endif()
# llama.cpp's win-app manifest object needs a windres that compiles for
# the target machine; the unprefixed host one defaults to x64.
get_filename_component(_ollama_llvm_mingw_bin_dir "${CMAKE_CXX_COMPILER}" DIRECTORY)
find_program(CMAKE_RC_COMPILER
NAMES aarch64-w64-mingw32-windres
HINTS "${_ollama_llvm_mingw_bin_dir}"
NO_DEFAULT_PATH
REQUIRED)
if(NOT HOST_CXX_COMPILER)
find_program(_ollama_path_host_cxx
+6
View File
@@ -106,6 +106,12 @@ fail either mode. Stderr summaries report accuracy, latency percentiles and
requests/questions per second; CSV retains per-request results and input sizes.
CSV separates label `mismatches` from HTTP/invalid-response `error` values.
Summary percentiles use HTTP round-trip latency, including server queueing.
For local warm decision runs, the stderr JSON summary also includes
`size_bytes`, `vram_bytes`, and `num_ctx` from `/api/ps`. The sample is taken
after warmup, or after the measured requests when `-warmup 0`. Benchstat output
also prints the usual model Size/VRAM comment; CSV columns remain per-request.
External endpoints and cold-load runs omit memory because the local Ollama
running-model list would not describe those requests.
Compare identical corpora, model artifacts and settings on the same host. HTTP
latency includes model lookup and request setup, so warm runs capture routing and
metadata-cache improvements as well as inference. Use `-k 0 -concurrency 1` and a
+24 -3
View File
@@ -159,6 +159,15 @@ func benchmarkDecisionModel(opts flagOptions, client *api.Client, name string, c
return fmt.Errorf("%s warmup: %w", name, sample.Err)
}
}
info := ModelInfo{Name: name}
measureMemory := opts.decisionURL == nil || *opts.decisionURL == ""
measureMemory = measureMemory && *opts.keepAlive <= 0
if measureMemory && *opts.warmup > 0 {
memCtx, memCancel := context.WithTimeout(ctx, 5*time.Second)
info.SizeBytes, info.VRAMBytes = fetchMemoryUsage(memCtx, client, name)
info.NumCtx = fetchContextLength(memCtx, client, name)
memCancel()
}
if csvOut == nil {
fmt.Fprintf(out, "# API: systemone | Corpus: %s | SHA256: %s | Mode: %s | Concurrency: %d | Cache: unchanged corpus replay\n", *opts.decisionFile, corpus.SHA256, mode, *opts.concurrency)
}
@@ -220,7 +229,16 @@ func benchmarkDecisionModel(opts flagOptions, client *api.Client, name string, c
OutputMetrics(out, *opts.format, []Metrics{{Model: name, Step: step + "/metric=http", Count: 1, Duration: s.Duration}}, *opts.verbose)
}
}
writeDecisionSummary(os.Stderr, name, samples, total, elapsed)
if measureMemory && *opts.warmup == 0 {
memCtx, memCancel := context.WithTimeout(context.Background(), 5*time.Second)
info.SizeBytes, info.VRAMBytes = fetchMemoryUsage(memCtx, client, name)
info.NumCtx = fetchContextLength(memCtx, client, name)
memCancel()
}
if csvOut == nil {
outputModelInfo(out, *opts.format, info)
}
writeDecisionSummary(os.Stderr, name, samples, total, elapsed, info)
if err := context.Cause(ctx); err != nil {
return fmt.Errorf("%s: %w", name, err)
}
@@ -230,7 +248,7 @@ func benchmarkDecisionModel(opts flagOptions, client *api.Client, name string, c
return nil
}
func writeDecisionSummary(out io.Writer, model string, samples []decisionSample, total int, elapsed time.Duration) {
func writeDecisionSummary(out io.Writer, model string, samples []decisionSample, total int, elapsed time.Duration, info ModelInfo) {
type accuracy struct {
decisiontest.Tally
CaseAccuracy float64 `json:"case_accuracy_pct"`
@@ -246,9 +264,12 @@ func writeDecisionSummary(out io.Writer, model string, samples []decisionSample,
P50 float64 `json:"p50_ms"`
P95 float64 `json:"p95_ms"`
P99 float64 `json:"p99_ms"`
SizeBytes int64 `json:"size_bytes,omitempty"`
VRAMBytes int64 `json:"vram_bytes,omitempty"`
NumCtx int64 `json:"num_ctx,omitempty"`
Datasets map[string]accuracy `json:"datasets"`
}
s := summary{Model: model, Expected: total, Datasets: make(map[string]accuracy)}
s := summary{Model: model, Expected: total, SizeBytes: info.SizeBytes, VRAMBytes: info.VRAMBytes, NumCtx: info.NumCtx, Datasets: make(map[string]accuracy)}
var durations []time.Duration
var questions int
for _, sample := range samples {
+20 -3
View File
@@ -36,9 +36,12 @@ func TestDecisionBenchmarkPolicies(t *testing.T) {
{"unload failure", "score", `"noul":1`, true, false, http.StatusInternalServerError},
} {
t.Run(test.name, func(t *testing.T) {
var requests, unloads atomic.Int32
var requests, unloads, psReads atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/ps":
psReads.Add(1)
writeJSON(w, api.ProcessResponse{Models: []api.ProcessModelResponse{{Name: "test-model", Size: 5_000_000_000, SizeVRAM: 4_500_000_000, ContextLength: 4096}}})
case "/api/generate":
unloads.Add(1)
if test.unloadStatus != 0 {
@@ -95,6 +98,9 @@ func TestDecisionBenchmarkPolicies(t *testing.T) {
if unloads.Load() != wantUnloads || len(rows) != int(requests.Load())-*opts.warmup+1 {
t.Fatalf("unloads=%d requests=%d csv rows=%d", unloads.Load(), requests.Load(), len(rows))
}
if test.cold && psReads.Load() != 0 || !test.cold && psReads.Load() != 2 {
t.Fatalf("cold=%t running-model reads=%d, want 0 for cold or 2 for warm size/context", test.cold, psReads.Load())
}
if rows[1][3] != "test,case" || rows[1][6] != "42" {
t.Fatalf("missing per-request metadata or CSV escaping: %v", rows[1])
}
@@ -107,6 +113,10 @@ func TestDecisionBenchmarkPolicies(t *testing.T) {
func TestDecisionBenchmarkOutputError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/ps" {
writeJSON(w, api.ProcessResponse{Models: []api.ProcessModelResponse{{Name: "test-model", Size: 5_000_000_000, SizeVRAM: 4_500_000_000, ContextLength: 4096}}})
return
}
if r.URL.Path == "/api/generate" {
writeJSON(w, api.GenerateResponse{Done: true})
return
@@ -172,7 +182,7 @@ func TestDecisionSummaryPartialRun(t *testing.T) {
{Case: decisiontest.Case{Dataset: "b", Expected: map[string]decisiontest.Expected{"one": {}}}, Err: errors.New("HTTP 500")},
}
var out bytes.Buffer
writeDecisionSummary(&out, "test", samples, 5, time.Second)
writeDecisionSummary(&out, "test", samples, 5, time.Second, ModelInfo{SizeBytes: 5_000_000_000, VRAMBytes: 4_500_000_000, NumCtx: 4096})
var got struct {
decisiontest.Tally
Expected int `json:"expected_requests"`
@@ -182,12 +192,15 @@ func TestDecisionSummaryPartialRun(t *testing.T) {
P95 float64 `json:"p95_ms"`
Rate float64 `json:"requests_per_second"`
QuestionsRate float64 `json:"questions_per_second"`
SizeBytes int64 `json:"size_bytes"`
VRAMBytes int64 `json:"vram_bytes"`
NumCtx int64 `json:"num_ctx"`
Datasets map[string]decisiontest.Tally `json:"datasets"`
}
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.Complete || got.Expected != 5 || got.Requests != 3 || got.Errors != 1 || got.Questions != 5 || got.CorrectQuestions != 3 || got.QuestionAccuracy != 60 || got.P50 != 10 || got.P95 != 30 || got.Rate != 2 || got.QuestionsRate != 4 || got.Datasets["a"].CorrectCases != 1 || got.Datasets["b"].Errors != 1 {
if got.Complete || got.Expected != 5 || got.Requests != 3 || got.Errors != 1 || got.Questions != 5 || got.CorrectQuestions != 3 || got.QuestionAccuracy != 60 || got.P50 != 10 || got.P95 != 30 || got.Rate != 2 || got.QuestionsRate != 4 || got.SizeBytes != 5_000_000_000 || got.VRAMBytes != 4_500_000_000 || got.NumCtx != 4096 || got.Datasets["a"].CorrectCases != 1 || got.Datasets["b"].Errors != 1 {
t.Fatalf("incorrect partial-run summary: %s", out.String())
}
}
@@ -197,6 +210,8 @@ func TestDecisionBenchmarkConcurrency(t *testing.T) {
both := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/ps":
writeJSON(w, api.ProcessResponse{Models: []api.ProcessModelResponse{{Name: "test-model", Size: 5_000_000_000, SizeVRAM: 4_500_000_000, ContextLength: 4096}}})
case "/api/generate":
writeJSON(w, api.GenerateResponse{Done: true})
case "/v1/systemone":
@@ -238,6 +253,8 @@ func TestDecisionBenchmarkCancelsPeers(t *testing.T) {
started, canceled := make(chan struct{}), make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/ps":
writeJSON(w, api.ProcessResponse{Models: []api.ProcessModelResponse{{Name: "test-model", Size: 5_000_000_000, SizeVRAM: 4_500_000_000, ContextLength: 4096}}})
case "/api/generate":
writeJSON(w, api.GenerateResponse{Done: true})
case "/v1/systemone":
+62 -15
View File
@@ -903,23 +903,12 @@ func RunHandler(cmd *cobra.Command, args []string) error {
}
prompts := args[1:]
// prepend stdin to the prompt if provided
if !term.IsTerminal(int(os.Stdin.Fd())) {
in, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
// Only prepend stdin content if it's not empty
stdinContent := string(in)
if len(stdinContent) > 0 {
prompts = append([]string{stdinContent}, prompts...)
}
stdinPiped := !term.IsTerminal(int(os.Stdin.Fd()))
if stdinPiped {
opts.ShowConnect = false
opts.WordWrap = false
interactive = false
}
opts.Prompt = strings.Join(prompts, " ")
if len(prompts) > 0 {
interactive = false
}
@@ -932,7 +921,9 @@ func RunHandler(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
opts.WordWrap = !nowrap
// Wrapping rewrites the line with cursor escapes, which only a terminal
// can interpret; piped or redirected output stays plain text.
opts.WordWrap = !nowrap && term.IsTerminal(int(os.Stdout.Fd()))
// Fill out the rest of the options based on information about the
// model.
@@ -966,12 +957,34 @@ func RunHandler(cmd *cobra.Command, args []string) error {
applyShowResponseToRunOptions(&opts, info)
// prepend stdin to the prompt if provided; speech models read it as it
// arrives instead. Models that also chat speak when --voice is given and
// chat otherwise.
speech := slices.Contains(info.Capabilities, model.CapabilitySpeech) &&
(!slices.Contains(info.Capabilities, model.CapabilityCompletion) || cmd.Flags().Changed("voice"))
if stdinPiped && !speech {
in, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
// Only prepend stdin content if it's not empty
stdinContent := string(in)
if len(stdinContent) > 0 {
prompts = append([]string{stdinContent}, prompts...)
}
}
opts.Prompt = strings.Join(prompts, " ")
if slices.Contains(info.Capabilities, model.CapabilityDecision) {
return runDecision(cmd, opts, interactive)
}
if cmd.Flags().Changed("ask") {
return fmt.Errorf("%s is not a decision model, so it can't answer --ask questions", name)
}
if cmd.Flags().Changed("voice") && !speech {
return fmt.Errorf("%s is not a speech model, so it can't use --voice", name)
}
// Check if this is an embedding model
isEmbeddingModel := slices.Contains(info.Capabilities, model.CapabilityEmbedding)
@@ -996,6 +1009,18 @@ func RunHandler(cmd *cobra.Command, args []string) error {
return generateEmbedding(cmd, name, opts.Prompt, opts.KeepAlive, truncate, dimensions)
}
if speech {
voice, err := cmd.Flags().GetString("voice")
if err != nil {
return err
}
var input io.Reader
if stdinPiped {
input = os.Stdin
}
return runSpeech(cmd.Context(), name, voice, opts.Prompt, input, interactive)
}
if slices.Contains(info.Capabilities, model.CapabilityImage) {
return errors.New("image generation models are not currently supported")
}
@@ -1261,7 +1286,10 @@ func ListRunningHandler(cmd *cobra.Command, args []string) error {
} else {
until = format.HumanTime(m.ExpiresAt, "Never")
}
ctxStr := strconv.Itoa(m.ContextLength)
ctxStr := "-"
if m.ContextLength > 0 {
ctxStr = strconv.Itoa(m.ContextLength)
}
data = append(data, []string{m.Name, m.Digest[:12], format.HumanBytes(m.Size), procStr, ctxStr, m.Runner, until})
}
}
@@ -1448,6 +1476,15 @@ func showInfo(resp *api.ShowResponse, verbose bool, w io.Writer) error {
if resp.Requires != "" {
rows = append(rows, []string{"", "requires", resp.Requires})
}
if resp.Renderer != "" {
rows = append(rows, []string{"", "renderer", resp.Renderer})
}
if resp.Parser != "" {
rows = append(rows, []string{"", "parser", resp.Parser})
}
if resp.TemplateSource != "" && resp.TemplateSource != "none" {
rows = append(rows, []string{"", "template source", resp.TemplateSource})
}
if len(resp.Manifests) > 0 {
if runner, ok := showSelectedRunner(resp.Manifests); ok {
rows = append(rows, []string{"", "runner", runner})
@@ -1478,6 +1515,15 @@ func showInfo(resp *api.ShowResponse, verbose bool, w io.Writer) error {
})
}
if len(resp.Voices) > 0 {
tableRender("Voices", func() (rows [][]string) {
for _, voice := range resp.Voices {
rows = append(rows, []string{"", voice})
}
return
})
}
if resp.ProjectorInfo != nil {
tableRender("Projector", func() (rows [][]string) {
arch, _ := resp.ProjectorInfo["general.architecture"].(string)
@@ -2588,6 +2634,7 @@ func NewCLI() *cobra.Command {
runCmd.Flags().Bool("hidethinking", false, "Hide thinking output (if provided)")
runCmd.Flags().Bool("truncate", false, "For embedding models: truncate inputs exceeding context length (default: true). Set --truncate=false to error instead")
runCmd.Flags().Int("dimensions", 0, "Truncate output embeddings to specified dimension (embedding models only)")
runCmd.Flags().String("voice", "", "Voice to speak with (speech models only)")
var asked []askedQuestion
runCmd.Flags().Var(questionFlag{"ask", &asked}, "ask", "Ask a decision model a question, answered yes or no unless --choice or --level follow")
runCmd.Flags().Var(questionFlag{"choice", &asked}, "choice", `Add a label for the preceding --ask to choose from, e.g. billing="Payments and refunds"`)
+190
View File
@@ -138,6 +138,48 @@ func TestShowInfo(t *testing.T) {
}
})
t.Run("renderer and template source", func(t *testing.T) {
var b bytes.Buffer
if err := showInfo(&api.ShowResponse{
Details: api.ModelDetails{
Family: "test",
ParameterSize: "7B",
QuantizationLevel: "FP16",
},
Renderer: "gemma4-large",
Parser: "gemma4",
TemplateSource: "renderer_parser",
}, false, &b); err != nil {
t.Fatal(err)
}
for _, want := range []string{"renderer", "gemma4-large", "template source", "renderer_parser"} {
if !strings.Contains(b.String(), want) {
t.Errorf("expected output to contain %q:\n%s", want, b.String())
}
}
})
t.Run("renderer fields omitted when empty", func(t *testing.T) {
var b bytes.Buffer
if err := showInfo(&api.ShowResponse{
Details: api.ModelDetails{
Family: "test",
ParameterSize: "7B",
QuantizationLevel: "FP16",
},
TemplateSource: "none",
}, false, &b); err != nil {
t.Fatal(err)
}
for _, unwanted := range []string{"renderer", "template source"} {
if strings.Contains(b.String(), unwanted) {
t.Errorf("expected output to omit %q:\n%s", unwanted, b.String())
}
}
})
t.Run("bare model info", func(t *testing.T) {
var b bytes.Buffer
if err := showInfo(&api.ShowResponse{
@@ -537,6 +579,125 @@ func TestDeleteHandler(t *testing.T) {
}
}
// Output written to a pipe or file is plain text: word wrapping's cursor
// escapes would reach whatever reads it, such as a speech model.
func TestRunPipedOutputIsPlain(t *testing.T) {
text := "The sky is blue because of a phenomenon called Rayleigh scattering. When sunlight enters the atmosphere it travels through countless tiny gas molecules."
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/show":
json.NewEncoder(w).Encode(api.ShowResponse{Capabilities: []model.Capability{model.CapabilityCompletion}})
case "/api/generate":
for _, word := range strings.SplitAfter(text, " ") {
json.NewEncoder(w).Encode(api.GenerateResponse{Response: word})
}
json.NewEncoder(w).Encode(api.GenerateResponse{Done: true})
default:
http.NotFound(w, r)
}
}))
t.Setenv("OLLAMA_HOST", mockServer.URL)
t.Cleanup(mockServer.Close)
cmd := &cobra.Command{}
cmd.SetContext(t.Context())
for _, f := range []string{"keepalive", "format", "think", "voice"} {
cmd.Flags().String(f, "", "")
}
for _, f := range []string{"verbose", "insecure", "nowordwrap", "hidethinking"} {
cmd.Flags().Bool(f, false, "")
}
var err error
out := captureStdout(t, func() {
err = RunHandler(cmd, []string{"chat-model", "Why is the sky blue?"})
})
if err != nil {
t.Fatal(err)
}
if strings.Contains(out, "\x1b") || strings.TrimSpace(out) != text {
t.Fatalf("piped output %q, want the plain response", out)
}
}
// A model that both chats and speaks chats in ollama run, and speaks the text
// when --voice is given.
func TestRunChatSpeechModelVoice(t *testing.T) {
for _, tt := range []struct {
name string
voice string
speaks bool
}{
{name: "chat by default"},
{name: "speak with voice", voice: "default", speaks: true},
} {
t.Run(tt.name, func(t *testing.T) {
var mu sync.Mutex
var speech []map[string]string
chats := 0
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
switch r.URL.Path {
case "/api/show":
json.NewEncoder(w).Encode(api.ShowResponse{
Capabilities: []model.Capability{model.CapabilityCompletion, model.CapabilityAudio, model.CapabilitySpeech},
})
case "/v1/audio/speech":
var req map[string]string
json.NewDecoder(r.Body).Decode(&req)
speech = append(speech, req)
w.Write(append([]byte("RIFF\x00\x00\x00\x00WAVEfmt \x10\x00\x00\x00\x01\x00\x01\x00\xc0\x5d\x00\x00\x80\xbb\x00\x00\x02\x00\x10\x00data\x00\x00\x00\x00"), make([]byte, 64)...))
case "/api/generate", "/api/chat":
chats++
json.NewEncoder(w).Encode(api.GenerateResponse{Response: "hi", Done: true})
default:
http.NotFound(w, r)
}
}))
t.Setenv("OLLAMA_HOST", mockServer.URL)
t.Cleanup(mockServer.Close)
cmd := &cobra.Command{}
cmd.SetContext(t.Context())
for _, f := range []string{"keepalive", "format", "think", "voice"} {
cmd.Flags().String(f, "", "")
}
for _, f := range []string{"verbose", "insecure", "nowordwrap", "hidethinking"} {
cmd.Flags().Bool(f, false, "")
}
if tt.voice != "" {
if err := cmd.Flags().Set("voice", tt.voice); err != nil {
t.Fatal(err)
}
}
var err error
out := captureStdout(t, func() {
err = RunHandler(cmd, []string{"chat-speech-model", "Hello from Ollama."})
})
if err != nil {
t.Fatal(err)
}
mu.Lock()
defer mu.Unlock()
if !tt.speaks {
if len(speech) != 0 || chats != 1 {
t.Fatalf("%d speech and %d chat requests, want a chat", len(speech), chats)
}
return
}
if chats != 0 || len(speech) != 1 {
t.Fatalf("%d speech and %d chat requests, want speech", len(speech), chats)
}
if got := speech[0]; got["voice"] != tt.voice || !strings.Contains(got["input"], "Hello from Ollama.") {
t.Fatalf("speech request %v", got)
}
if !strings.HasPrefix(out, "RIFF") {
t.Fatalf("output %q, want a WAV", out[:min(len(out), 16)])
}
})
}
}
func TestRunEmbeddingModel(t *testing.T) {
reqCh := make(chan api.EmbedRequest, 1)
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -2818,6 +2979,35 @@ func TestShowInfoImageCapability(t *testing.T) {
}
}
func TestShowInfoSpeechVoices(t *testing.T) {
var b bytes.Buffer
err := showInfo(&api.ShowResponse{
Details: api.ModelDetails{Family: "phonon", ParameterSize: "31M", QuantizationLevel: "F32"},
Capabilities: []model.Capability{model.CapabilitySpeech},
Voices: []string{"default", "Fairy Godmother", "Zoey"},
}, false, &b)
if err != nil {
t.Fatal(err)
}
expect := " Model\n" +
" architecture phonon \n" +
" parameters 31M \n" +
" quantization F32 \n" +
"\n" +
" Capabilities\n" +
" speech \n" +
"\n" +
" Voices\n" +
" default \n" +
" Fairy Godmother \n" +
" Zoey \n" +
"\n"
if diff := cmp.Diff(expect, b.String()); diff != "" {
t.Errorf("unexpected output (-want +got):\n%s", diff)
}
}
func TestPushProgressMessage(t *testing.T) {
tests := []struct {
name string
+13 -11
View File
@@ -41,12 +41,12 @@ func runDecision(cmd *cobra.Command, opts runOptions, interactive bool) error {
return decide(cmd, opts, input, opts.Questions)
}
// yesNoQuestions asks each text as a yes/no question keyed by the text itself.
// yesNoQuestions asks each text as a yes/no question.
func yesNoQuestions(texts ...string) *api.SystemOneQuestions {
questions := &api.SystemOneQuestions{}
for _, text := range texts {
for i, text := range texts {
instructions, _ := json.Marshal(text)
questions.Set(text, api.SystemOneQuestion{Type: "noul", Instructions: instructions})
questions.Set(fmt.Sprintf("q%d", i+1), api.SystemOneQuestion{Type: "noul", Instructions: instructions})
}
return questions
}
@@ -95,7 +95,7 @@ func (f questionFlag) Set(value string) error {
return nil
}
// askedQuestions returns the --ask questions keyed by their text: yes/no, or
// askedQuestions returns the --ask questions: yes/no, or
// answered with a --choice label or on a --level scale.
func askedQuestions(cmd *cobra.Command) *api.SystemOneQuestions {
questions := &api.SystemOneQuestions{}
@@ -103,7 +103,7 @@ func askedQuestions(cmd *cobra.Command) *api.SystemOneQuestions {
if flag == nil {
return questions
}
for _, q := range *flag.Value.(questionFlag).asked {
for i, q := range *flag.Value.(questionFlag).asked {
question := api.SystemOneQuestion{Type: "noul"}
question.Instructions, _ = json.Marshal(q.text)
switch {
@@ -114,7 +114,7 @@ func askedQuestions(cmd *cobra.Command) *api.SystemOneQuestions {
question.Type = "score"
question.Criteria, _ = json.Marshal(q.levels)
}
questions.Set(q.text, question)
questions.Set(fmt.Sprintf("q%d", i+1), question)
}
return questions
}
@@ -165,10 +165,12 @@ func decide(cmd *cobra.Command, opts runOptions, input api.Message, questions *a
}
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
for name := range questions.All() {
for name, q := range questions.All() {
var text string
_ = json.Unmarshal(q.Instructions, &text)
raw, ok := resp.Answers.Get(name)
if !ok {
return fmt.Errorf("no answer to %q", name)
return fmt.Errorf("no answer to %q", text)
}
var a struct {
Type string `json:"type"`
@@ -179,7 +181,7 @@ func decide(cmd *cobra.Command, opts runOptions, input api.Message, questions *a
Probabilities map[string]float64 `json:"probabilities"`
}
if err := json.Unmarshal(raw, &a); err != nil {
return fmt.Errorf("answer to %q: %w", name, err)
return fmt.Errorf("answer to %q: %w", text, err)
}
var answer, measure string
switch a.Type {
@@ -204,10 +206,10 @@ func decide(cmd *cobra.Command, opts runOptions, input api.Message, questions *a
}
measure = fmt.Sprintf("%.0f%%\t%.1f / %d", a.Probabilities[level]*100, a.Score, len(a.Legend)-1)
default:
return fmt.Errorf("answer to %q has unknown type %q", name, a.Type)
return fmt.Errorf("answer to %q has unknown type %q", text, a.Type)
}
if questions.Len() > 1 {
fmt.Fprintf(tw, "%s\t", name)
fmt.Fprintf(tw, "%s\t", text)
}
fmt.Fprintf(tw, "%s\t%s\n", answer, measure)
}
+24 -13
View File
@@ -61,7 +61,7 @@ func runDecide(t *testing.T, stdin string, handler http.HandlerFunc, args ...str
}
func TestRunDecisionModel(t *testing.T) {
const refund = `{"Is a refund being requested?":{"type":"noul","instructions":"Is a refund being requested?"}}`
const refund = `{"q1":{"type":"noul","instructions":"Is a refund being requested?"}}`
for _, tt := range []struct {
name, stdin string
args []string
@@ -75,14 +75,14 @@ func TestRunDecisionModel(t *testing.T) {
stdin: "I was charged twice\n",
args: []string{"--ask", "Is a refund being requested?"},
questions: refund,
answers: `{"Is a refund being requested?":{"type":"noul","noul":0.97}}`,
answers: `{"q1":{"type":"noul","noul":0.97}}`,
want: "yes 97%\n",
},
{
name: "state as an argument",
args: []string{"I was charged twice", "--ask", "Is a refund being requested?"},
questions: refund,
answers: `{"Is a refund being requested?":{"type":"noul","noul":0.2}}`,
answers: `{"q1":{"type":"noul","noul":0.2}}`,
want: "no 80%\n",
},
{
@@ -90,31 +90,31 @@ func TestRunDecisionModel(t *testing.T) {
args: []string{"--ask", "Is a refund being requested?", `{"ticket": "I was charged twice"}`},
state: `{"ticket":"I was charged twice"}`,
questions: refund,
answers: `{"Is a refund being requested?":{"type":"noul","noul":0.97}}`,
answers: `{"q1":{"type":"noul","noul":0.97}}`,
want: "yes 97%\n",
},
{
name: "labels",
stdin: "I was charged twice",
args: []string{"--ask", "Which team should handle this?", "--choice", "billing=Payments and refunds", "--choice", "technical"},
questions: `{"Which team should handle this?":{"type":"choice","instructions":"Which team should handle this?","criteria":{"billing":"Payments and refunds","technical":null}}}`,
answers: `{"Which team should handle this?":{"type":"choice","choice":"billing","probabilities":{"billing":0.91,"technical":0.09},"confidence":0.6}}`,
questions: `{"q1":{"type":"choice","instructions":"Which team should handle this?","criteria":{"billing":"Payments and refunds","technical":null}}}`,
answers: `{"q1":{"type":"choice","choice":"billing","probabilities":{"billing":0.91,"technical":0.09},"confidence":0.6}}`,
want: "billing 91%\n",
},
{
name: "levels",
stdin: "I was charged twice",
args: []string{"--ask", "How urgent is this?", "--level", "Routine", "--level", "Soon", "--level", "Immediate"},
questions: `{"How urgent is this?":{"type":"score","instructions":"How urgent is this?","criteria":["Routine","Soon","Immediate"]}}`,
answers: `{"How urgent is this?":{"type":"score","score":1.83,"legend":{"0":"Routine","1":"Soon","2":"Immediate"},"probabilities":{"0":0.04,"1":0.09,"2":0.87},"confidence":0.7}}`,
questions: `{"q1":{"type":"score","instructions":"How urgent is this?","criteria":["Routine","Soon","Immediate"]}}`,
answers: `{"q1":{"type":"score","score":1.83,"legend":{"0":"Routine","1":"Soon","2":"Immediate"},"probabilities":{"0":0.04,"1":0.09,"2":0.87},"confidence":0.7}}`,
want: "Immediate 87% 1.8 / 2\n",
},
{
name: "most likely level, not the nearest",
stdin: "I was charged twice",
args: []string{"--ask", "How urgent is this?", "--level", "Routine", "--level", "Soon", "--level", "Immediate"},
questions: `{"How urgent is this?":{"type":"score","instructions":"How urgent is this?","criteria":["Routine","Soon","Immediate"]}}`,
answers: `{"How urgent is this?":{"type":"score","score":1.1,"legend":{"0":"Routine","1":"Soon","2":"Immediate"},"probabilities":{"0":0.45,"1":0,"2":0.55}}}`,
questions: `{"q1":{"type":"score","instructions":"How urgent is this?","criteria":["Routine","Soon","Immediate"]}}`,
answers: `{"q1":{"type":"score","score":1.1,"legend":{"0":"Routine","1":"Soon","2":"Immediate"},"probabilities":{"0":0.45,"1":0,"2":0.55}}}`,
want: "Immediate 55% 1.1 / 2\n",
},
{
@@ -125,8 +125,8 @@ func TestRunDecisionModel(t *testing.T) {
"--ask", "Which team?", "--choice", "billing", "--choice", "technical",
"--ask", "How urgent?", "--level", "routine", "--level", "soon", "--level", "immediate",
},
questions: `{"Is a refund being requested?":{"type":"noul","instructions":"Is a refund being requested?"},"Which team?":{"type":"choice","instructions":"Which team?","criteria":{"billing":null,"technical":null}},"How urgent?":{"type":"score","instructions":"How urgent?","criteria":["routine","soon","immediate"]}}`,
answers: `{"How urgent?":{"type":"score","score":1.2,"legend":{"0":"routine","1":"soon","2":"immediate"},"probabilities":{"0":0.1,"1":0.6,"2":0.3}},"Which team?":{"type":"choice","choice":"billing","probabilities":{"billing":0.91,"technical":0.09}},"Is a refund being requested?":{"type":"noul","noul":0.97}}`,
questions: `{"q1":{"type":"noul","instructions":"Is a refund being requested?"},"q2":{"type":"choice","instructions":"Which team?","criteria":{"billing":null,"technical":null}},"q3":{"type":"score","instructions":"How urgent?","criteria":["routine","soon","immediate"]}}`,
answers: `{"q3":{"type":"score","score":1.2,"legend":{"0":"routine","1":"soon","2":"immediate"},"probabilities":{"0":0.1,"1":0.6,"2":0.3}},"q2":{"type":"choice","choice":"billing","probabilities":{"billing":0.91,"technical":0.09}},"q1":{"type":"noul","noul":0.97}}`,
want: "Is a refund being requested? yes 97%\nWhich team? billing 91%\nHow urgent? soon 60% 1.2 / 2\n",
},
} {
@@ -158,7 +158,7 @@ func TestRunDecisionModel(t *testing.T) {
})
}
const response = `{"model":"nimble","answers":{"Is this urgent?":{"type":"noul","noul":0.9}},"usage":{"input_tokens":12,"output_tokens":1}}`
const response = `{"model":"nimble","answers":{"q1":{"type":"noul","noul":0.9}},"usage":{"input_tokens":12,"output_tokens":1}}`
out, err := runDecide(t, "", func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, response)
}, "nimble", "hello", "--ask", "Is this urgent?", "--format", "json")
@@ -167,6 +167,17 @@ func TestRunDecisionModel(t *testing.T) {
}
}
func TestYesNoQuestions(t *testing.T) {
got, err := json.Marshal(yesNoQuestions("Is this spam?", "Is it urgent?"))
if err != nil {
t.Fatal(err)
}
const want = `{"q1":{"type":"noul","instructions":"Is this spam?"},"q2":{"type":"noul","instructions":"Is it urgent?"}}`
if string(got) != want {
t.Fatalf("got %s, want %s", got, want)
}
}
func TestRunDecisionModelErrors(t *testing.T) {
const tooLong = "text and schema must not exceed 64 KiB"
_, err := runDecide(t, "", func(w http.ResponseWriter, r *http.Request) {
+11 -1
View File
@@ -240,6 +240,7 @@ func (c *launcherClient) confirmCloudModelPayment(ctx context.Context, model str
if !ok || strings.TrimSpace(item.RequiredPlan) == "" {
return nil
}
model = item.Name
state := launchAccountState(ctx, c.apiClient)
if state.Status != accountStateUnknown {
@@ -276,11 +277,20 @@ func (c *launcherClient) confirmCloudModelPayment(ctx context.Context, model str
}
func (c *launcherClient) modelRecommendationItem(ctx context.Context, model string) (ModelItem, bool) {
for _, item := range c.recommendations(ctx) {
items := c.recommendations(ctx)
for _, item := range items {
if item.Name == model {
return item, true
}
}
if isCloudModelName(model) {
key := launchModelRecommendationKey(model)
for _, item := range items {
if isCloudModelName(item.Name) && launchModelRecommendationKey(item.Name) == key {
return item, true
}
}
}
return ModelItem{}, false
}
+30 -11
View File
@@ -49,7 +49,7 @@ func (c *Claude) findPath() (string, error) {
return "", fmt.Errorf("claude binary not found")
}
func (c *Claude) Run(model string, _ []LaunchModel, args []string) error {
func (c *Claude) Run(model string, models []LaunchModel, args []string) error {
claudePath, err := ensureClaudeInstalled()
if err != nil {
return err
@@ -60,11 +60,11 @@ func (c *Claude) Run(model string, _ []LaunchModel, args []string) error {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = append(os.Environ(), c.envVars(model)...)
cmd.Env = append(os.Environ(), c.envVars(model, models)...)
return cmd.Run()
}
func (c *Claude) envVars(model string) []string {
func (c *Claude) envVars(model string, models []LaunchModel) []string {
env := []string{
"ANTHROPIC_BASE_URL=" + envconfig.Host().String(),
"ANTHROPIC_API_KEY=",
@@ -83,7 +83,7 @@ func (c *Claude) envVars(model string) []string {
env = append(env, "CLAUDE_CODE_AUTO_MODE_SERVER=0")
}
env = append(env, c.modelEnvVars(model)...)
env = append(env, c.modelEnvVars(model, models)...)
return env
}
@@ -168,8 +168,19 @@ func claudeInstallerCommand(goos string) (string, []string, error) {
}
}
// Claude Code caps output for unrecognized model IDs at 128,000 tokens.
const claudeMaxOutputTokens = 128_000
// As of 2026-10-19 (cc version 2.1.304), claude code warns the following:
// CLAUDE_CODE_AUTO_COMPACT_WINDOW="1048576" is too large, so Claude Code treats it as the 1M maximum.
// Set it to a size from 100k to 1M, such as 200k or 200000, or unset it.
const (
claudeMinAutoCompactWindow = 100_000
claudeMaxAutoCompactWindow = 1_000_000
)
// modelEnvVars returns Claude Code env vars that route all model tiers through Ollama.
func (c *Claude) modelEnvVars(model string) []string {
func (c *Claude) modelEnvVars(model string, models []LaunchModel) []string {
env := []string{
"ANTHROPIC_DEFAULT_OPUS_MODEL=" + model,
"ANTHROPIC_DEFAULT_SONNET_MODEL=" + model,
@@ -177,12 +188,20 @@ func (c *Claude) modelEnvVars(model string) []string {
"CLAUDE_CODE_SUBAGENT_MODEL=" + model,
}
if isCloudModelName(model) {
if l, ok := lookupCloudModelLimit(model); ok {
window := strconv.Itoa(l.Context)
env = append(env, "CLAUDE_CODE_MAX_CONTEXT_TOKENS="+window)
if os.Getenv("CLAUDE_CODE_AUTO_COMPACT_WINDOW") == "" {
env = append(env, "CLAUDE_CODE_AUTO_COMPACT_WINDOW="+window)
resolved, ok := findLaunchModel(models, model)
if ok {
resolved = resolved.WithCloudLimits().WithServerMetadata()
} else {
resolved = fallbackLaunchModel(model)
}
if resolved.Remote || isCloudModelName(model) {
if _, set := os.LookupEnv("CLAUDE_CODE_MAX_OUTPUT_TOKENS"); !set && resolved.MaxOutputTokens > 0 {
env = append(env, "CLAUDE_CODE_MAX_OUTPUT_TOKENS="+strconv.Itoa(min(resolved.MaxOutputTokens, claudeMaxOutputTokens)))
}
if ctxLen := resolved.ContextLength; ctxLen > 0 {
env = append(env, "CLAUDE_CODE_MAX_CONTEXT_TOKENS="+strconv.Itoa(ctxLen))
if os.Getenv("CLAUDE_CODE_AUTO_COMPACT_WINDOW") == "" && ctxLen >= claudeMinAutoCompactWindow {
env = append(env, "CLAUDE_CODE_AUTO_COMPACT_WINDOW="+strconv.Itoa(min(ctxLen, claudeMaxAutoCompactWindow)))
}
}
}
+53 -8
View File
@@ -24,6 +24,7 @@ const (
claudeDesktopProfileID = "00000000-0000-4000-8000-000000000114"
claudeDesktopGatewayBaseURL = "http://" + proxy.DefaultClaudeDesktopListenAddr
claudeDesktopProbeTimeout = 2 * time.Second
claudeDesktopCatalogTimeout = 2 * time.Second
claudeDesktopModelLabel = "Default Ollama model"
claudeDesktopSuccessMessage = "Claude Desktop profile changed to Ollama."
claudeDesktopRestoreMessage = "To restore the usual Claude profile, run: ollama launch claude-desktop --restore"
@@ -45,6 +46,7 @@ var (
claudeDesktopRunningAppPath = defaultClaudeDesktopRunningAppPath
claudeDesktopGlob = filepath.Glob
claudeDesktopProbeGateway = proxy.ProbeClaudeDesktop
claudeDesktopFetchCatalog = proxy.FetchClaudeDesktopCatalog
)
// ClaudeDesktop configures and launches Claude Desktop in third-party
@@ -67,9 +69,9 @@ func (c *ClaudeDesktop) AutodiscoveredModel() string {
return claudeDesktopModelLabel
}
// ConfigureAutodiscovery points Claude Desktop at Ollama's local gateway
// without pinning a model list, so Claude discovers the selected catalog and
// exact Ollama route names the gateway advertises.
// ConfigureAutodiscovery points Claude Desktop at Ollama's local gateway and
// pins the routes the gateway advertises, so the picker names the model behind
// each route instead of a name Claude Desktop derives from the route ID.
func (c *ClaudeDesktop) ConfigureAutodiscovery() error {
autoMode, err := claudeDesktopAutoModePreference()
if err != nil {
@@ -91,7 +93,21 @@ func (c *ClaudeDesktop) ConfigureAutodiscoveryWithAutoMode(autoMode bool) error
if err != nil {
return err
}
return configureClaudeDesktopTargets(targets, claudeDesktopGatewayBaseURL, "ollama", autoMode)
return configureClaudeDesktopTargets(targets, claudeDesktopGatewayBaseURL, "ollama", autoMode, claudeDesktopCatalog())
}
// claudeDesktopCatalog reads the routes the gateway advertises so the profile
// can pin the same names the gateway serves. Claude Desktop names well-known
// route IDs itself, so discovery alone never renames them in the picker. A
// failed read is not fatal: the profile then stays on plain discovery.
func claudeDesktopCatalog() []proxy.ClaudeDesktopCatalogModel {
ctx, cancel := context.WithTimeout(context.Background(), claudeDesktopCatalogTimeout)
defer cancel()
models, err := claudeDesktopFetchCatalog(ctx, nil, claudeDesktopGatewayBaseURL, "ollama")
if err != nil {
return nil
}
return models
}
func (c *ClaudeDesktop) RestoreHint() string {
@@ -382,9 +398,9 @@ func (c *ClaudeDesktop) Restore() error {
})
}
func configureClaudeDesktopTargets(targets claudeDesktopTargets, baseURL, apiKey string, autoMode bool) error {
func configureClaudeDesktopTargets(targets claudeDesktopTargets, baseURL, apiKey string, autoMode bool, models []proxy.ClaudeDesktopCatalogModel) error {
for _, target := range targets.thirdPartyProfiles {
if err := writeClaudeDesktopGatewayProfile(target.profile, baseURL, apiKey, true, autoMode); err != nil {
if err := writeClaudeDesktopGatewayProfile(target.profile, baseURL, apiKey, true, autoMode, models); err != nil {
return err
}
if err := writeClaudeDesktopMeta(target.meta, claudeDesktopProfileID, claudeDesktopProfileName); err != nil {
@@ -738,7 +754,7 @@ func writeClaudeDesktopMeta(path, id, name string) error {
return writeClaudeDesktopJSON(path, meta)
}
func writeClaudeDesktopGatewayProfile(path, baseURL, apiKey string, forceChooser, autoMode bool) error {
func writeClaudeDesktopGatewayProfile(path, baseURL, apiKey string, forceChooser, autoMode bool, models []proxy.ClaudeDesktopCatalogModel) error {
cfg, err := readClaudeDesktopJSONAllowMissing(path)
if err != nil {
return fmt.Errorf("parse Claude Desktop Ollama profile: %w", err)
@@ -749,7 +765,11 @@ func writeClaudeDesktopGatewayProfile(path, baseURL, apiKey string, forceChooser
cfg["inferenceGatewayAuthScheme"] = "bearer"
cfg["deploymentDisplayName"] = claudeDesktopProfileName
cfg["chatTabEnabled"] = true
delete(cfg, "inferenceModels")
if entries := claudeDesktopInferenceModels(models); len(entries) > 0 {
cfg["inferenceModels"] = entries
} else {
delete(cfg, "inferenceModels")
}
cfg["disableDeploymentModeChooser"] = forceChooser
cfg["coworkEgressAllowedHosts"] = claudeDesktopEgressHosts
cfg["disableEssentialTelemetry"] = true
@@ -758,6 +778,31 @@ func writeClaudeDesktopGatewayProfile(path, baseURL, apiKey string, forceChooser
return writeClaudeDesktopJSON(path, cfg)
}
// claudeDesktopInferenceModels converts gateway routes into the profile's
// pinned model list. labelOverride carries the gateway's name for the model so
// the picker shows that instead of a name derived from the route ID.
func claudeDesktopInferenceModels(models []proxy.ClaudeDesktopCatalogModel) []any {
entries := make([]any, 0, len(models))
for _, model := range models {
id := strings.TrimSpace(model.ID)
if id == "" {
continue
}
entry := map[string]any{"name": id}
if label := strings.TrimSpace(model.DisplayName); label != "" && label != id {
entry["labelOverride"] = label
}
if tier := strings.TrimSpace(model.AnthropicFamilyTier); tier != "" {
entry["anthropicFamilyTier"] = tier
}
if model.IsFamilyDefault {
entry["isFamilyDefault"] = true
}
entries = append(entries, entry)
}
return entries
}
func restoreClaudeDesktopMeta(path string) error {
meta, err := readClaudeDesktopJSONAllowMissing(path)
if err != nil {
+57
View File
@@ -16,17 +16,24 @@ import (
"time"
"github.com/ollama/ollama/cmd/config"
"github.com/ollama/ollama/internal/proxy"
)
func withClaudeDesktopPlatform(t *testing.T, goos string) {
t.Helper()
oldGOOS := claudeDesktopGOOS
oldProbe := claudeDesktopProbeGateway
oldCatalog := claudeDesktopFetchCatalog
claudeDesktopGOOS = goos
claudeDesktopProbeGateway = func(context.Context, string) error { return nil }
// Most tests exercise profile plumbing, not the gateway catalog.
claudeDesktopFetchCatalog = func(context.Context, *http.Client, string, string) ([]proxy.ClaudeDesktopCatalogModel, error) {
return nil, errors.New("no gateway in tests")
}
t.Cleanup(func() {
claudeDesktopGOOS = oldGOOS
claudeDesktopProbeGateway = oldProbe
claudeDesktopFetchCatalog = oldCatalog
})
}
@@ -1613,3 +1620,53 @@ func TestClaudeDesktopRunRejectsExtraArgs(t *testing.T) {
t.Fatalf("Run error = %v, want extra args rejection", err)
}
}
func TestClaudeDesktopConfigureAutodiscoveryPinsGatewayLabels(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
withClaudeDesktopPlatform(t, "darwin")
t.Setenv("OLLAMA_API_KEY", "test-api-key")
claudeDesktopFetchCatalog = func(context.Context, *http.Client, string, string) ([]proxy.ClaudeDesktopCatalogModel, error) {
return []proxy.ClaudeDesktopCatalogModel{
{ID: "claude-fable-5", DisplayName: "glm-5.2:cloud", AnthropicFamilyTier: "fable", IsFamilyDefault: true},
{ID: "claude-opus-5", DisplayName: "kimi-k3:cloud", AnthropicFamilyTier: "opus"},
}, nil
}
paths, err := claudeDesktopConfigPaths()
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(paths.profile), 0o755); err != nil {
t.Fatal(err)
}
if err := (&ClaudeDesktop{}).ConfigureAutodiscovery(); err != nil {
t.Fatalf("ConfigureAutodiscovery returned error: %v", err)
}
profile := claudeDesktopReadJSON(t, paths.profile)
entries, ok := profile["inferenceModels"].([]any)
if !ok || len(entries) != 2 {
t.Fatalf("inferenceModels = %v, want two pinned routes", profile["inferenceModels"])
}
first, _ := entries[0].(map[string]any)
if first["name"] != "claude-fable-5" || first["labelOverride"] != "glm-5.2:cloud" {
t.Fatalf("pinned route = %v, want the gateway model name on claude-fable-5", first)
}
if first["anthropicFamilyTier"] != "fable" || first["isFamilyDefault"] != true {
t.Fatalf("pinned tier metadata = %v", first)
}
second, _ := entries[1].(map[string]any)
if _, ok := second["isFamilyDefault"]; ok {
t.Fatalf("non-default route should omit isFamilyDefault: %v", second)
}
if err := restoreClaudeDesktopProfile(); err != nil {
t.Fatalf("restore returned error: %v", err)
}
restored := claudeDesktopReadJSON(t, paths.profile)
if _, ok := restored["inferenceModels"]; ok {
t.Fatalf("restore should drop the pinned list, got %v", restored["inferenceModels"])
}
}
+137 -6
View File
@@ -347,7 +347,7 @@ func TestClaudeEnvVars(t *testing.T) {
return m
}
got := envMap(c.envVars("llama3.2"))
got := envMap(c.envVars("llama3.2", nil))
for key, want := range map[string]string{
"ANTHROPIC_BASE_URL": envconfig.Host().String(),
"ANTHROPIC_API_KEY": "",
@@ -486,7 +486,7 @@ func TestClaudeModelEnvVars(t *testing.T) {
}
t.Run("maps all Claude model env vars to the provided model", func(t *testing.T) {
got := envMap(c.modelEnvVars("llama3.2"))
got := envMap(c.modelEnvVars("llama3.2", nil))
if got["ANTHROPIC_DEFAULT_OPUS_MODEL"] != "llama3.2" {
t.Errorf("OPUS = %q, want llama3.2", got["ANTHROPIC_DEFAULT_OPUS_MODEL"])
}
@@ -507,7 +507,7 @@ func TestClaudeModelEnvVars(t *testing.T) {
})
t.Run("supports empty model", func(t *testing.T) {
got := envMap(c.modelEnvVars(""))
got := envMap(c.modelEnvVars("", nil))
if got["ANTHROPIC_DEFAULT_OPUS_MODEL"] != "" {
t.Errorf("OPUS = %q, want empty", got["ANTHROPIC_DEFAULT_OPUS_MODEL"])
}
@@ -532,7 +532,7 @@ func TestClaudeModelEnvVars(t *testing.T) {
"glm-5:cloud": "202752",
"kimi-k2.6:cloud": "262144",
} {
got := envMap(c.modelEnvVars(model))
got := envMap(c.modelEnvVars(model, nil))
for _, key := range windowKeys {
if got[key] != want {
t.Errorf("%s: %s = %q, want %s", model, key, got[key], want)
@@ -541,10 +541,30 @@ func TestClaudeModelEnvVars(t *testing.T) {
}
})
t.Run("keeps the auto compact window within Claude Code's range", func(t *testing.T) {
setDynamicCloudModelLimits(map[string]cloudModelLimit{"tiny": {Context: 65_536}})
t.Cleanup(func() { setDynamicCloudModelLimits(nil) })
for _, tt := range []struct {
model LaunchModel
wantContext string
wantCompact string
}{
{model: LaunchModel{Name: "nemotron-3-nano:30b:cloud"}, wantContext: "1048576", wantCompact: "1000000"},
{model: LaunchModel{Name: "tiny:cloud"}, wantContext: "65536"},
{model: LaunchModel{Name: "new-large:cloud", ContextLength: 1_048_576}, wantContext: "1048576", wantCompact: "1000000"},
{model: LaunchModel{Name: "new-small:cloud", ContextLength: 65_536}, wantContext: "65536"},
} {
got := envMap(c.modelEnvVars(tt.model.Name, []LaunchModel{tt.model}))
if got["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] != tt.wantContext || got["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] != tt.wantCompact {
t.Errorf("%s: context = %q, compact = %q; want %q, %q", tt.model.Name, got["CLAUDE_CODE_MAX_CONTEXT_TOKENS"], got["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], tt.wantContext, tt.wantCompact)
}
}
})
t.Run("keeps the user's auto compact window but not their context window", func(t *testing.T) {
t.Setenv("CLAUDE_CODE_AUTO_COMPACT_WINDOW", "150000")
t.Setenv("CLAUDE_CODE_MAX_CONTEXT_TOKENS", "150000")
got := envMap(c.modelEnvVars("kimi-k2.6:cloud"))
got := envMap(c.modelEnvVars("kimi-k2.6:cloud", nil))
if v, ok := got["CLAUDE_CODE_AUTO_COMPACT_WINDOW"]; ok {
t.Errorf("AUTO_COMPACT_WINDOW = %q, want left to the user's setting", v)
}
@@ -553,8 +573,26 @@ func TestClaudeModelEnvVars(t *testing.T) {
}
})
t.Run("resolved cloud metadata takes precedence over fallback", func(t *testing.T) {
t.Setenv("CLAUDE_CODE_AUTO_COMPACT_WINDOW", "")
models := []LaunchModel{{Name: "kimi-k2.6:cloud", ContextLength: 524288}}
env := c.modelEnvVars("kimi-k2.6:cloud", models)
got := envMap(env)
for _, key := range windowKeys {
count := 0
for _, entry := range env {
if strings.HasPrefix(entry, key+"=") {
count++
}
}
if got[key] != "524288" || count != 1 {
t.Errorf("%s = %q (%d entries), want 524288 once", key, got[key], count)
}
}
})
t.Run("does not set windows for unknown cloud models", func(t *testing.T) {
got := envMap(c.modelEnvVars("unknown-model:cloud"))
got := envMap(c.modelEnvVars("unknown-model:cloud", nil))
for _, key := range windowKeys {
if v, ok := got[key]; ok {
t.Errorf("%s = %q, want unset", key, v)
@@ -562,3 +600,96 @@ func TestClaudeModelEnvVars(t *testing.T) {
}
})
}
func TestClaudeRunCloudContextWindow(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a POSIX shell fake binary")
}
dir := t.TempDir()
output := filepath.Join(dir, "context")
t.Setenv("PATH", dir)
t.Setenv("CLAUDE_LAUNCH_TEST_OUTPUT", output)
t.Setenv("CLAUDE_CODE_MAX_CONTEXT_TOKENS", "12345")
t.Setenv("CLAUDE_CODE_AUTO_COMPACT_WINDOW", "150000")
script := `#!/bin/sh
printf '%s\n' "$CLAUDE_CODE_MAX_CONTEXT_TOKENS" "$CLAUDE_CODE_AUTO_COMPACT_WINDOW" > "$CLAUDE_LAUNCH_TEST_OUTPUT"
`
if err := os.WriteFile(filepath.Join(dir, "claude"), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
for _, tt := range []struct {
name string
model LaunchModel
want 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"},
} {
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 {
t.Fatal(err)
}
got, err := os.ReadFile(output)
if err != nil {
t.Fatal(err)
}
if want := tt.want + "\n150000\n"; string(got) != want {
t.Fatalf("child context settings = %q, want %q", got, want)
}
})
}
}
func TestClaudeModelOutputTokens(t *testing.T) {
const outputKey = "CLAUDE_CODE_MAX_OUTPUT_TOKENS"
for _, tt := range []struct {
name string
model LaunchModel
override string
set bool
want string
}{
{name: "client ceiling", model: LaunchModel{Name: "large:cloud", ContextLength: 1_048_576, MaxOutputTokens: 393_216}, want: "128000"},
{name: "model ceiling overrides fallback", model: LaunchModel{Name: "qwen3.5:cloud", ContextLength: 262_144, MaxOutputTokens: 16_384}, want: "16384"},
{name: "remote alias", model: LaunchModel{Name: "custom-cloud", Remote: true, ContextLength: 262_144, MaxOutputTokens: 64_000}, want: "64000"},
{name: "fallback limit", model: LaunchModel{Name: "qwen3.5:cloud"}, want: "32768"},
{name: "unknown limit", model: LaunchModel{Name: "unknown:cloud", ContextLength: 262_144}},
{name: "local model", model: LaunchModel{Name: "local", ContextLength: 262_144, MaxOutputTokens: 65_536}},
{name: "explicit override", model: LaunchModel{Name: "large:cloud", ContextLength: 1_048_576, MaxOutputTokens: 393_216}, override: "64000", set: true},
{name: "explicit empty override", model: LaunchModel{Name: "large:cloud", ContextLength: 1_048_576, MaxOutputTokens: 393_216}, set: true},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv(outputKey, tt.override)
if !tt.set {
if err := os.Unsetenv(outputKey); err != nil {
t.Fatal(err)
}
}
env := (&Claude{}).modelEnvVars(tt.model.Name, []LaunchModel{tt.model})
var got string
var count int
for _, entry := range env {
key, value, _ := strings.Cut(entry, "=")
if key == outputKey {
got = value
count++
}
if key == "CLAUDE_CODE_EFFORT_LEVEL" || key == "MAX_THINKING_TOKENS" {
t.Errorf("unexpected thinking override: %s", entry)
}
}
wantCount := 0
if tt.want != "" {
wantCount = 1
}
if got != tt.want || count != wantCount {
t.Errorf("%s = %q (%d entries), want %q (%d entries)", outputKey, got, count, tt.want, wantCount)
}
})
}
}
+30 -19
View File
@@ -706,6 +706,27 @@ func writeCodexModelCatalog(catalogPath string, models []LaunchModel) error {
return os.WriteFile(catalogPath, data, 0o644)
}
func launchReasoningEffortLevels(thinking *model.Thinking) ([]string, string) {
contract, ok := codexAppThinkingContractFromRecommendation(thinking)
if !ok {
return nil, ""
}
var levels []string
for _, level := range contract.levels {
value := contract.values[level]
converted, err := openai.ThinkingFromReasoningEffort(level, thinking)
if err != nil || converted == nil {
continue
}
resolved := renderers.ResolveThinking(converted, thinking)
if resolved == nil || resolved.Value != value {
continue
}
levels = append(levels, level)
}
return levels, contract.defaultLevel
}
func buildCodexModelEntry(launchModel LaunchModel) map[string]any {
modelName := launchModel.Name
contextWindow := codexFallbackContextWindow
@@ -738,25 +759,15 @@ func buildCodexModelEntry(launchModel LaunchModel) map[string]any {
supportedReasoningLevels := make([]any, 0)
var defaultReasoningLevel any
if contract, ok := codexAppThinkingContractFromRecommendation(launchModel.Thinking); ok {
for _, level := range contract.levels {
value := contract.values[level]
converted, err := openai.ThinkingFromReasoningEffort(level, launchModel.Thinking)
if err != nil || converted == nil {
continue
}
resolved := renderers.ResolveThinking(converted, launchModel.Thinking)
if resolved == nil || resolved.Value != value {
continue
}
supportedReasoningLevels = append(supportedReasoningLevels, map[string]any{
"effort": level,
"description": codexAppThinkingLevelDescription(level),
})
}
if contract.defaultLevel != "" {
defaultReasoningLevel = contract.defaultLevel
}
levels, defaultLevel := launchReasoningEffortLevels(launchModel.Thinking)
for _, level := range levels {
supportedReasoningLevels = append(supportedReasoningLevels, map[string]any{
"effort": level,
"description": codexAppThinkingLevelDescription(level),
})
}
if defaultLevel != "" {
defaultReasoningLevel = defaultLevel
}
return map[string]any{
+41 -5
View File
@@ -680,6 +680,30 @@ func (c *CodexApp) OllamaConfigured() bool {
return c.CurrentModel() != ""
}
// RestorePending recognizes saved restore state and abandoned Ollama catalogs,
// including legacy connections that do not have a restore record.
func (c *CodexApp) RestorePending() bool {
if _, err := os.Lstat(codexAppRestoreStatePath()); !os.IsNotExist(err) {
return true
}
configPath, err := codexConfigPath()
if err != nil {
return false
}
if data, err := os.ReadFile(configPath); err == nil && codexAppRootReferencesCatalog(string(data)) {
return false
}
for _, path := range []string{
codexAppModelCatalogPathForConfig(configPath),
codexAppRoutingCatalogPathForConfig(configPath),
} {
if _, err := os.Lstat(path); !os.IsNotExist(err) {
return true
}
}
return false
}
// Running reports whether the user's regular ChatGPT app is open.
func (c *CodexApp) Running() bool {
return codexAppIsRunning()
@@ -818,10 +842,12 @@ func restoreCodexAppProfile() error {
data, err := os.ReadFile(configPath)
if err != nil {
if os.IsNotExist(err) {
if err := removeCodexAppManagedAuth(configPath); err != nil {
return codexAppRestoreFailure(configPath, err)
if _, err := os.Lstat(codexAppRestoreStatePath()); os.IsNotExist(err) {
if err := writeCodexAppRestoreState(codexAppRestoreState{}); err != nil {
return codexAppRestoreFailure(configPath, err)
}
}
if err := removeCodexAppRestoreState(); err != nil {
if err := removeCodexAppManagedAuth(configPath); err != nil {
return codexAppRestoreFailure(configPath, err)
}
if err := removeCodexAppProfileConfig(); err != nil {
@@ -830,6 +856,9 @@ func restoreCodexAppProfile() error {
if err := codexAppRemoveOwnedCatalog(); err != nil {
return codexAppRestoreFailure(configPath, err)
}
if err := removeCodexAppRestoreState(); err != nil {
return codexAppRestoreFailure(configPath, err)
}
return nil
}
return codexAppRestoreFailure(configPath, err)
@@ -854,16 +883,23 @@ func restoreCodexAppProfile() error {
if err := codexValidateConfigText(text); err != nil {
return codexAppRestoreFailure(configPath, err)
}
// Keep a durable retry record before changing settings, including legacy
// connections whose catalogs and original restore record are already gone.
if os.IsNotExist(stateErr) {
if err := writeCodexAppRestoreState(codexAppRestoreStateFromText(text)); err != nil {
return codexAppRestoreFailure(configPath, err)
}
}
if err := fileutil.WriteWithBackup(configPath, []byte(text), codexAppIntegrationName); err != nil {
return codexAppRestoreFailure(configPath, err)
}
if err := removeCodexAppProfileConfig(); err != nil {
return codexAppRestoreFailure(configPath, err)
}
if err := codexAppRemoveOwnedCatalogIfUnused(text); err != nil {
if err := removeCodexAppManagedAuth(configPath); err != nil {
return codexAppRestoreFailure(configPath, err)
}
if err := removeCodexAppManagedAuth(configPath); err != nil {
if err := codexAppRemoveOwnedCatalogIfUnused(text); err != nil {
return codexAppRestoreFailure(configPath, err)
}
if err := removeCodexAppRestoreState(); err != nil {
+158
View File
@@ -568,6 +568,159 @@ func TestCodexAppDesktopUsesAndRestoresRegularProfile(t *testing.T) {
}
}
func codexAppRestoreFixture(t *testing.T) (*CodexApp, string) {
t.Helper()
home := t.TempDir()
setTestHome(t, home)
withCodexAppPlatform(t, "darwin")
t.Setenv("OLLAMA_HOST", "http://127.0.0.1:11434")
old := codexAppProfileIsRunning
codexAppProfileIsRunning = func() bool { return false }
t.Cleanup(func() { codexAppProfileIsRunning = old })
withCodexAppProcessHooks(t,
func() bool { return false },
func() error { t.Fatal("unexpected process quit"); return nil },
func() error { t.Fatal("unexpected app launch"); return nil },
)
return &CodexApp{}, filepath.Join(home, ".codex", "config.toml")
}
func TestCodexAppDesktopCleanupFailureCanRetry(t *testing.T) {
app, configPath := codexAppRestoreFixture(t)
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
read := func(path string) string {
t.Helper()
data, err := os.ReadFile(path)
must(err)
return string(data)
}
original := "model = \"native-fixture\"\nmodel_provider = \"openai\"\n\n[mcp_servers.fixture]\ncommand = \"fixture-before\"\n"
must(os.MkdirAll(filepath.Dir(configPath), 0o700))
must(os.WriteFile(configPath, []byte(original), 0o600))
must(app.ConfigureWithModels("qwen3:8b", testLaunchModels("qwen3:8b")))
restoreState := read(codexAppRestoreStatePath())
must(os.WriteFile(configPath, []byte(strings.ReplaceAll(read(configPath), "fixture-before", "fixture-after")), 0o600))
catalog := codexAppModelCatalogPathForConfig(configPath)
must(os.Remove(catalog))
must(os.Mkdir(catalog, 0o700))
blocker := filepath.Join(catalog, "fixture-obstruction")
must(os.WriteFile(blocker, []byte("fixture"), 0o600))
if err := app.RestoreFromDesktop(false); err == nil {
t.Fatal("expected cleanup failure")
}
if app.OllamaConfigured() || !app.RestorePending() || read(codexAppRestoreStatePath()) != restoreState {
t.Fatal("partial disconnect lost or replaced its recovery state")
}
must(os.WriteFile(configPath, []byte(strings.ReplaceAll(read(configPath), "native-fixture", "native-after-failure")), 0o600))
must(os.Remove(blocker))
must(app.RestoreFromDesktop(false))
if app.RestorePending() {
t.Fatal("cleanup remained pending after retry")
}
want, err := codexParseConfigText(strings.NewReplacer("fixture-before", "fixture-after", "native-fixture", "native-after-failure").Replace(original))
must(err)
got, err := codexParseConfigText(read(configPath))
must(err)
if diff := cmp.Diff(want, got); diff != "" {
t.Fatalf("retry changed user settings (-want +got):\n%s", diff)
}
}
func TestCodexAppDesktopCleanupWithoutRestoreStateCanRetry(t *testing.T) {
for _, missingConfig := range []bool{false, true} {
t.Run(fmt.Sprintf("missing_config=%v", missingConfig), func(t *testing.T) {
app, configPath := codexAppRestoreFixture(t)
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
read := func(path string) string {
t.Helper()
data, err := os.ReadFile(path)
must(err)
return string(data)
}
must(app.ConfigureWithModels("qwen3:8b", testLaunchModels("qwen3:8b")))
must(os.WriteFile(configPath, []byte(codexAppSetReasoningEfforts(read(configPath), []string{"medium"})), 0o600))
for _, path := range []string{codexAppRestoreStatePath(), codexAppModelCatalogPathForConfig(configPath), codexAppRoutingCatalogPathForConfig(configPath)} {
must(os.Remove(path))
}
if missingConfig {
must(os.Remove(configPath))
}
authPath := filepath.Join(filepath.Dir(configPath), "auth.json")
must(os.Remove(authPath))
must(os.Mkdir(authPath, 0o700))
blocker := filepath.Join(authPath, "fixture-obstruction")
must(os.WriteFile(blocker, []byte("fixture"), 0o600))
history := filepath.Join(filepath.Dir(configPath), "sessions", "fixture.jsonl")
must(os.MkdirAll(filepath.Dir(history), 0o700))
must(os.WriteFile(history, []byte("fixture history"), 0o600))
if err := app.RestoreFromDesktop(false); err == nil {
t.Fatal("expected auth cleanup failure")
}
if app.OllamaConfigured() || !app.RestorePending() {
t.Fatal("retry disappeared without catalogs or an original restore record")
}
edited := "model = \"native-after-failure\"\n"
if !missingConfig {
parsed, err := codexParseConfig(read(configPath))
must(err)
if efforts, ok := codexAppConfigReasoningEfforts(parsed); !ok || !slices.Equal(efforts, []string{"medium"}) {
t.Fatal("legacy restore changed desktop settings")
}
must(os.WriteFile(configPath, []byte(edited), 0o600))
}
must(os.Remove(blocker))
must(os.Remove(authPath))
must(os.WriteFile(authPath, []byte(`{"fixture":"replacement user auth"}`), 0o600))
must(app.RestoreFromDesktop(false))
if app.RestorePending() {
t.Fatal("cleanup remained pending after retry")
}
if missingConfig {
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
t.Fatal("retry recreated missing config")
}
} else if read(configPath) != edited {
t.Fatal("retry overwrote user edits")
}
if read(authPath) != `{"fixture":"replacement user auth"}` || read(history) != "fixture history" {
t.Fatal("retry changed user auth or history")
}
})
}
}
func TestCodexAppRestorePendingKeepsReferencedCatalog(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
configPath := filepath.Join(tmpDir, ".codex", "config.toml")
catalogPath := codexAppModelCatalogPathForConfig(configPath)
if err := os.MkdirAll(filepath.Dir(configPath), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(catalogPath, []byte(`{"models":[]}`), 0o600); err != nil {
t.Fatal(err)
}
text := fmt.Sprintf("model = \"native-fixture\"\nmodel_catalog_json = %q\n", catalogPath)
if err := os.WriteFile(configPath, []byte(text), 0o600); err != nil {
t.Fatal(err)
}
if (&CodexApp{}).RestorePending() {
t.Fatal("a catalog still referenced by the user's config must not be treated as abandoned cleanup")
}
}
func TestCodexAppDesktopUpdatesStoppedProfileWithoutOpening(t *testing.T) {
tmpDir := t.TempDir()
setTestHome(t, tmpDir)
@@ -922,6 +1075,11 @@ func TestCodexAppCountsOnlyOllamaRequestsInRegularProfile(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// Keep session files newer than the cutoff even with coarse file timestamps.
start = start.Add(-time.Minute)
if err := os.WriteFile(startPath, []byte(start.Format(time.RFC3339Nano)), 0o600); err != nil {
t.Fatal(err)
}
configPath, err := codexConfigPath()
if err != nil {
t.Fatal(err)
+142
View File
@@ -7,11 +7,16 @@ import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync/atomic"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/cmd/config"
"github.com/ollama/ollama/internal/proxy"
"github.com/spf13/cobra"
)
@@ -281,6 +286,143 @@ type commandRestorableRunner struct {
func (r *commandRestorableRunner) SkipRestoreInstallCheck() bool { return true }
func TestLaunchCmdChatGPT(t *testing.T) {
for _, tt := range []struct {
name string
args []string
routerReady bool
wantOpen int
}{
{name: "unavailable launch", args: []string{"chatgpt", "--model", "qwen3:8b"}},
{name: "unavailable configure only", args: []string{"codex-app", "--model", "qwen3:8b", "--config"}},
{name: "healthy launch", args: []string{"chatgpt", "--model", "qwen3:8b"}, routerReady: true, wantOpen: 1},
{name: "healthy configure only", args: []string{"chatgpt", "--model", "qwen3:8b", "--config"}, routerReady: true},
{name: "restore without server", args: []string{"chatgpt", "--restore"}, wantOpen: 1},
} {
t.Run(tt.name, func(t *testing.T) {
home := t.TempDir()
setTestHome(t, home)
withInteractiveSession(t, false)
withCodexAppPlatform(t, "darwin")
t.Setenv(codexAppAutoReviewModelEnv, "")
var routerChecks atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
w.WriteHeader(http.StatusOK)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[]}`)
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"qwen3:8b"}]}`)
case "/api/show":
fmt.Fprint(w, `{"capabilities":["completion","tools"],"model_info":{"general.context_length":131072}}`)
case proxy.CodexDesktopPathPrefix + "/_health":
routerChecks.Add(1)
if tt.routerReady {
fmt.Fprint(w, `{"ok":true}`)
} else {
http.NotFound(w, r)
}
default:
http.NotFound(w, r)
}
}))
defer server.Close()
t.Setenv("OLLAMA_HOST", server.URL)
configDir := filepath.Join(home, ".codex")
if err := os.MkdirAll(configDir, 0o700); err != nil {
t.Fatal(err)
}
original := map[string]string{
"config.toml": "model = \"gpt-5.5\"\napproval_policy = \"on-request\"\nmodel_provider = \"openai\"\n",
"auth.json": `{"OPENAI_API_KEY":"test-existing-key"}`,
}
for name, data := range original {
if err := os.WriteFile(filepath.Join(configDir, name), []byte(data), 0o600); err != nil {
t.Fatal(err)
}
}
restoring := slices.Contains(tt.args, "--restore")
if restoring {
server.Close()
withCodexAppRouterHealth(t, func() error {
t.Error("restore must not check ChatGPT routing")
return fmt.Errorf("server is stopped")
})
if err := (&CodexApp{}).Configure("qwen3:8b"); err != nil {
t.Fatal(err)
}
}
openCalls, quitCalls := 0, 0
withCodexAppProcessHooks(t,
func() bool { return false },
func() error { quitCalls++; return nil },
func() error { openCalls++; return nil },
)
codexAppCanOpenID = func() bool { return true }
client, err := api.ClientFromEnvironment()
if err != nil {
t.Fatal(err)
}
heartbeatCalled := false
cmd := LaunchCmd(func(cmd *cobra.Command, _ []string) error {
heartbeatCalled = true
return client.Heartbeat(cmd.Context())
}, nil)
cmd.SetArgs(tt.args)
stderr := captureStderr(t, func() { err = cmd.Execute() })
wantHeartbeat := !restoring
if heartbeatCalled != wantHeartbeat {
t.Fatalf("heartbeat called = %v, want %v", heartbeatCalled, wantHeartbeat)
}
if tt.routerReady || restoring {
if err != nil {
t.Fatal(err)
}
} else if err == nil || !strings.Contains(err.Error(), "does not include ChatGPT routing") || !strings.Contains(err.Error(), "restart Ollama") {
t.Fatalf("expected missing-router recovery guidance, got %v", err)
}
if got := strings.Contains(stderr, codexAppConfigurationSuccess); got != tt.routerReady {
t.Fatalf("configuration success = %v, want %v; stderr=%q", got, tt.routerReady, stderr)
}
if tt.routerReady {
if got := (&CodexApp{}).CurrentModel(); got != "qwen3:8b" {
t.Fatalf("configured model = %q, want qwen3:8b", got)
}
} else {
for name, want := range original {
data, err := os.ReadFile(filepath.Join(configDir, name))
if err != nil || string(data) != want {
t.Fatalf("%s changed: data=%q err=%v", name, data, err)
}
}
entries, err := os.ReadDir(configDir)
if err != nil || len(entries) != len(original) {
t.Fatalf("client files changed: entries=%v err=%v", entries, err)
}
if !restoring {
if _, err := os.Stat(filepath.Join(home, ".ollama")); !os.IsNotExist(err) {
t.Fatalf("created launcher or restore state before router check: %v", err)
}
}
}
if quitCalls != 0 || openCalls != tt.wantOpen {
t.Fatalf("process calls = quit %d, open %d; want quit 0, open %d", quitCalls, openCalls, tt.wantOpen)
}
if got := routerChecks.Load(); !restoring && got != 1 {
t.Fatalf("router health checks = %d, want 1", got)
}
})
}
}
func TestLaunchCmdNilHeartbeat(t *testing.T) {
cmd := LaunchCmd(nil, nil)
if cmd == nil {
+83
View File
@@ -1,7 +1,13 @@
package launch
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/ollama/ollama/api"
)
@@ -17,3 +23,80 @@ func TestProcessContextWindowMatchesLatestAlias(t *testing.T) {
t.Fatalf("context window = %d, want 262144", got)
}
}
func TestLoadedContextLength(t *testing.T) {
for _, tt := range []struct {
name string
loadError bool
status int
processes string
wantLength int
}{
{"allocated context", false, 200, `{"models":[{"name":"local:latest","context_length":8192}]}`, 8192},
{"load failure", true, 200, "", 0},
{"lookup unsupported", false, 404, `{"error":"not found"}`, 0},
{"lookup unavailable", false, 503, `{"error":"unavailable"}`, 0},
{"older context metadata", false, 200, `{"models":[{"name":"local:latest"}]}`, 0},
{"selected model absent", false, 200, `{"models":[{"name":"other:latest","context_length":32768}]}`, 0},
} {
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/generate":
var req api.GenerateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Model != "local" || req.Prompt != "" || len(req.Options) != 0 {
t.Errorf("expected load-only request without option overrides: %+v, %v", req, err)
}
if tt.loadError {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, `{"error":"model requires more system memory"}`)
return
}
fmt.Fprintln(w, `{"done":true,"done_reason":"load"}`)
case "/api/ps":
if tt.loadError {
t.Error("looked up context after a failed load")
}
w.WriteHeader(tt.status)
fmt.Fprint(w, tt.processes)
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
length, err := loadedContextLength("local")
if length != tt.wantLength || (err != nil) != tt.loadError {
t.Fatalf("loadedContextLength = %d, %v; want %d, loadError=%v", length, err, tt.wantLength, tt.loadError)
}
if tt.loadError && !strings.Contains(err.Error(), "model requires more system memory") {
t.Fatalf("load error cause lost: %v", err)
}
})
}
}
func TestLoadedContextLengthBoundsMetadataWait(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/generate" {
fmt.Fprintln(w, `{"done":true,"done_reason":"load"}`)
return
}
select {
case <-r.Context().Done():
case <-time.After(10 * time.Second):
t.Error("optional metadata request was not cancelled promptly")
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
started := time.Now()
length, err := loadedContextLength("local")
if length != 0 || err != nil {
t.Fatalf("stalled metadata must allow fallback after successful load: %d, %v", length, err)
}
if elapsed := time.Since(started); elapsed > 10*time.Second {
t.Fatalf("optional metadata held up launch for %v", elapsed)
}
}
+30 -2
View File
@@ -22,8 +22,36 @@ const (
deepSeekHarnessProvider = "ollama"
deepSeekHarnessAPIKeyEnv = "OLLAMA_LAUNCH_DSH_API_KEY"
deepSeekHarnessWebSettings = "web-search-deepseek"
deepSeekHarnessCompactionHeadroom = 65_536
deepSeekHarnessMaxTokensContextFrac = 8
)
// deepSeekHarnessMaxTokens bounds the maxTokens dsh is told about so that its
// automatic context compaction keeps working. dsh (0.2.x) reserves maxTokens
// plus a 64k headroom out of the context window before it will compact, and
// disables compaction entirely when that reservation reaches the window. Our
// cloud limits often report an output limit equal to the full context window,
// which would leave dsh running without compaction until the context is simply
// full. The compaction threshold is also the window minus that reservation, so
// a large maxTokens makes compaction fire early: half of a 262k window as
// maxTokens would compact at 64k. Capping maxTokens to an eighth of the window
// keeps compaction at roughly seven eighths, and when even that leaves under
// two headrooms of room the value is omitted so dsh falls back to its default.
func deepSeekHarnessMaxTokens(contextLength, maxOutputTokens int) int {
if maxOutputTokens <= 0 {
return 0
}
if contextLength <= 0 {
return maxOutputTokens
}
maxTokens := min(maxOutputTokens, contextLength/deepSeekHarnessMaxTokensContextFrac)
if contextLength-maxTokens < 2*deepSeekHarnessCompactionHeadroom {
return 0
}
return maxTokens
}
var (
deepSeekHarnessLookPath = exec.LookPath
deepSeekHarnessCommand = exec.Command
@@ -392,8 +420,8 @@ func deepSeekHarnessModelConfigs(primary string, models []LaunchModel) []any {
if item.ContextLength > 0 {
entry["contextWindow"] = item.ContextLength
}
if item.MaxOutputTokens > 0 {
entry["maxTokens"] = item.MaxOutputTokens
if maxTokens := deepSeekHarnessMaxTokens(item.ContextLength, item.MaxOutputTokens); maxTokens > 0 {
entry["maxTokens"] = maxTokens
}
configs = append(configs, entry)
}
+22 -2
View File
@@ -123,8 +123,8 @@ func TestDeepSeekHarnessConfigurePreservesSettingsAndIsIdempotent(t *testing.T)
t.Fatalf("local model input = %#v", local["input"])
}
cloud, _ := configuredModels[1].(map[string]any)
if cloud["id"] != "kimi-k2.6:cloud" || cloud["contextWindow"] != 262144 || cloud["maxTokens"] != 262144 {
t.Fatalf("cloud model = %#v", cloud)
if cloud["id"] != "kimi-k2.6:cloud" || cloud["contextWindow"] != 262144 || cloud["maxTokens"] != 32768 {
t.Fatalf("cloud model = %#v, want maxTokens clamped to a quarter of the compaction budget", cloud)
}
web, _ := settings[deepSeekHarnessWebSettings].(map[string]any)
if web["baseURL"] != "http://127.0.0.1:12345/v1" || web["apiKeyEnv"] != deepSeekHarnessAPIKeyEnv || web["model"] != "qwen3.5:latest" {
@@ -554,3 +554,23 @@ func TestDeepSeekHarnessInstallDependencyError(t *testing.T) {
t.Fatalf("error = %v", err)
}
}
func TestDeepSeekHarnessMaxTokensKeepsCompactionBudget(t *testing.T) {
tests := []struct {
name string
contextLength int
maxOutput int
want int
}{
{"output below the fraction is kept", 262_144, 16_384, 16_384},
{"output equal to context is clamped", 262_144, 262_144, 32_768},
{"small context leaves no budget", 131_072, 131_072, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := deepSeekHarnessMaxTokens(tt.contextLength, tt.maxOutput); got != tt.want {
t.Fatalf("deepSeekHarnessMaxTokens(%d, %d) = %d, want %d", tt.contextLength, tt.maxOutput, got, tt.want)
}
})
}
}
+503 -58
View File
@@ -1,18 +1,22 @@
package launch
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strings"
"time"
"github.com/ollama/ollama/api"
"github.com/pelletier/go-toml/v2"
"github.com/pelletier/go-toml/v2/unstable"
"golang.org/x/mod/semver"
"github.com/ollama/ollama/cmd/internal/fileutil"
"github.com/ollama/ollama/envconfig"
modelpkg "github.com/ollama/ollama/types/model"
)
// Kimi implements Runner for Kimi Code CLI integration.
@@ -21,12 +25,14 @@ type Kimi struct{}
const (
kimiDefaultModelAlias = "ollama"
kimiDefaultMaxContextSize = 32768
kimiCodeProviderName = "ollama"
kimiLegacyVersionPrefix = "kimi, version "
kimiLegacyArchivedVersion = "v1.52.0"
kimiInstallScript = "curl -LsSf https://code.kimi.com/kimi-code/install.sh | bash"
kimiInstallPowerShell = "Invoke-RestMethod https://code.kimi.com/kimi-code/install.ps1 | Invoke-Expression"
)
var (
kimiGOOS = runtime.GOOS
kimiModelShowTimeout = 5 * time.Second
)
var kimiGOOS = runtime.GOOS
func (k *Kimi) String() string { return "Kimi Code CLI" }
@@ -36,7 +42,7 @@ func (k *Kimi) args(config string, extra []string) []string {
return args
}
func (k *Kimi) Run(model string, _ []LaunchModel, args []string) error {
func (k *Kimi) Run(model string, models []LaunchModel, args []string) error {
if strings.TrimSpace(model) == "" {
return fmt.Errorf("model is required")
}
@@ -44,30 +50,469 @@ func (k *Kimi) Run(model string, _ []LaunchModel, args []string) error {
return err
}
config, err := buildKimiInlineConfig(model, resolveKimiMaxContextSize(model))
if err != nil {
return fmt.Errorf("failed to build kimi config: %w", err)
}
bin, err := ensureKimiInstalled()
if err != nil {
return err
}
cmd := exec.Command(bin, k.args(config, args)...)
var cmdArgs []string
if _, legacy := kimiLegacyCLIVersion(bin); legacy {
config, err := buildKimiInlineConfig(model, resolveKimiMaxContextSize(model))
if err != nil {
return fmt.Errorf("failed to build kimi config: %w", err)
}
cmdArgs = k.args(config, args)
} else {
if err := writeKimiCodeConfig(model, models); err != nil {
return fmt.Errorf("failed to configure kimi: %w", err)
}
cmdArgs = append([]string{"-m", kimiCodeModelAlias(model)}, args...)
}
cmd := exec.Command(bin, cmdArgs...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
func kimiLegacyCLIVersion(bin string) (string, bool) {
out, err := exec.Command(bin, "--version").Output()
if err != nil {
return "", false
}
line, _, _ := strings.Cut(strings.TrimSpace(string(out)), "\n")
version, ok := strings.CutPrefix(strings.TrimSpace(line), kimiLegacyVersionPrefix)
if !ok {
return "", false
}
return strings.TrimSpace(version), true
}
func kimiLegacyCLIArchived(version string) bool {
v := "v" + strings.TrimPrefix(version, "v")
return semver.IsValid(v) && semver.Compare(v, kimiLegacyArchivedVersion) >= 0
}
func kimiInstallCommand(goos string) string {
if goos == "windows" {
return kimiInstallPowerShell
}
return kimiInstallScript
}
func kimiArchivedCLIError(version string) error {
return fmt.Errorf("kimi-cli %s no longer runs commands; install Kimi Code: %s", version, kimiInstallCommand(kimiGOOS))
}
func kimiCodeModelAlias(model string) string {
return kimiCodeProviderName + "/" + model
}
func kimiCodeConfigPath() (string, error) {
if home := strings.TrimSpace(os.Getenv("KIMI_CODE_HOME")); home != "" {
return filepath.Join(home, "config.toml"), nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, ".kimi-code", "config.toml"), nil
}
func writeKimiCodeConfig(primary string, models []LaunchModel) error {
path, err := kimiCodeConfigPath()
if err != nil {
return err
}
cfg := map[string]any{}
exists := false
data, err := os.ReadFile(path)
switch {
case err == nil:
exists = true
if err := toml.Unmarshal(data, &cfg); err != nil {
return fmt.Errorf("parse %s: %w", path, err)
}
case !os.IsNotExist(err):
return err
}
models = codexCatalogModels(primary, models)
aliases := make(map[string]bool, len(models))
for _, m := range models {
aliases[kimiCodeModelAlias(m.Name)] = true
}
modelsTable, _ := cfg["models"].(map[string]any)
providersTable, _ := cfg["providers"].(map[string]any)
defaultModel, _ := cfg["default_model"].(string)
nextDefault := defaultModel
if !kimiCodeDefaultSurvives(modelsTable, aliases, defaultModel) {
nextDefault = kimiCodeModelAlias(primary)
}
provider := kimiCodeProviderValues(providersTable[kimiCodeProviderName])
entries := make(map[string]map[string]any, len(models))
for _, m := range models {
alias := kimiCodeModelAlias(m.Name)
entries[alias] = kimiCodeModelEntryFor(m, modelsTable[alias])
}
updated, err := kimiCodeRemoveOwnedSections(string(data), aliases)
if err != nil {
return fmt.Errorf("parse %s: %w", path, err)
}
sections, err := kimiCodeSections([]string{"providers", kimiCodeProviderName}, provider)
if err != nil {
return err
}
for _, m := range models {
alias := kimiCodeModelAlias(m.Name)
entry := entries[alias]
if overrides, ok := kimiCodeModelOverrides(modelsTable, alias); ok {
entry["overrides"] = overrides
}
modelSections, err := kimiCodeSections([]string{"models", alias}, entry)
if err != nil {
return err
}
sections = append(sections, modelSections...)
}
updated = kimiCodeAppendSections(updated, sections)
updated = codexSetRootStringValue(updated, "default_model", nextDefault)
if err := toml.Unmarshal([]byte(updated), &map[string]any{}); err != nil {
merged, mergeErr := kimiCodeMergedConfig(cfg, provider, entries, nextDefault)
if mergeErr != nil {
return fmt.Errorf("kimi config %s could not be updated: %w", path, mergeErr)
}
updated = string(merged)
}
if exists {
if updated == string(data) {
return nil
}
if kimiCodeHasUserContent(cfg) {
ok, err := ConfirmPrompt(fmt.Sprintf("Kimi Code config %s already has settings. Update it for Ollama now? (your settings are kept and a backup is saved)", path))
if err != nil {
return err
}
if !ok {
return fmt.Errorf("kimi config %s was not updated; re-run with --yes to update it", path)
}
}
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
return fileutil.WriteWithBackup(path, []byte(updated), "kimi")
}
func kimiCodeDefaultSurvives(modelsTable map[string]any, aliases map[string]bool, alias string) bool {
if alias == "" {
return false
}
if aliases[alias] {
return true
}
if _, ok := modelsTable[alias]; ok {
return !kimiCodeOwnedAlias(alias)
}
return false
}
func kimiCodeOwnedAlias(alias string) bool {
return strings.HasPrefix(alias, kimiCodeProviderName+"/")
}
func kimiCodeRemoveOwnedSections(text string, aliases map[string]bool) (string, error) {
var parser unstable.Parser
parser.Reset([]byte(text))
var out strings.Builder
var table []string
offset, sectionStart := 0, -1
ownedSection := false
remove := func(start, end int) {
out.WriteString(text[offset:start])
offset = end
}
for parser.NextExpression() {
expr := parser.Expression()
var path []string
keys := expr.Key()
start := -1
for keys.Next() {
key := keys.Node()
if start < 0 {
start = int(key.Raw.Offset)
}
path = append(path, string(key.Data))
}
switch expr.Kind {
case unstable.Table, unstable.ArrayTable:
start = strings.LastIndexByte(text[:start], '\n') + 1
if ownedSection {
remove(sectionStart, start)
}
table = path
sectionStart = start
ownedSection = kimiCodeOwnsPath(path, aliases)
case unstable.KeyValue:
if ownedSection || !kimiCodeOwnsPath(append(slices.Clone(table), path...), aliases) {
continue
}
start = strings.LastIndexByte(text[:start], '\n') + 1
end := int(expr.Raw.Offset + expr.Raw.Length)
if newline := strings.IndexByte(text[end:], '\n'); newline >= 0 {
end += newline + 1
} else {
end = len(text)
}
remove(start, end)
}
}
if err := parser.Error(); err != nil {
return "", err
}
if ownedSection {
remove(sectionStart, len(text))
}
out.WriteString(text[offset:])
return out.String(), nil
}
func kimiCodeOwnsPath(path []string, aliases map[string]bool) bool {
return len(path) >= 2 && (path[0] == "providers" && path[1] == kimiCodeProviderName || path[0] == "models" && aliases[path[1]])
}
func kimiCodeProviderValues(existing any) map[string]any {
values := map[string]any{
"type": "openai",
"base_url": envconfig.ConnectableHost().String() + "/v1",
}
table, _ := existing.(map[string]any)
for key, value := range table {
if _, ours := values[key]; !ours {
values[key] = value
}
}
if values["api_key"] == nil && values["api_key_env"] == nil && values["oauth"] == nil {
values["api_key"] = "ollama"
}
return values
}
func kimiCodeModelEntryFor(m LaunchModel, existing any) map[string]any {
entry := kimiCodeModelEntry(m)
table, ok := existing.(map[string]any)
if !ok {
return entry
}
for key, value := range table {
if key == "overrides" {
continue
}
if _, ours := entry[key]; !ours {
entry[key] = value
}
}
return entry
}
func kimiCodeMergedConfig(cfg map[string]any, provider map[string]any, entries map[string]map[string]any, nextDefault string) ([]byte, error) {
providers, ok := cfg["providers"].(map[string]any)
if !ok {
providers = map[string]any{}
cfg["providers"] = providers
}
providers[kimiCodeProviderName] = provider
modelsTable, ok := cfg["models"].(map[string]any)
if !ok {
modelsTable = map[string]any{}
cfg["models"] = modelsTable
}
for alias, entry := range entries {
if overrides, ok := kimiCodeModelOverrides(modelsTable, alias); ok {
entry["overrides"] = overrides
}
modelsTable[alias] = entry
}
cfg["default_model"] = nextDefault
return toml.Marshal(cfg)
}
func kimiCodeModelOverrides(modelsTable map[string]any, alias string) (map[string]any, bool) {
entry, ok := modelsTable[alias].(map[string]any)
if !ok {
return nil, false
}
overrides, ok := entry["overrides"].(map[string]any)
if !ok || len(overrides) == 0 {
return nil, false
}
return overrides, true
}
func kimiCodeSections(path []string, values map[string]any) ([]string, error) {
scalars := make(map[string]any, len(values))
var nested []string
for key, value := range values {
if _, ok := value.(map[string]any); ok {
nested = append(nested, key)
continue
}
scalars[key] = value
}
slices.Sort(nested)
body, err := toml.Marshal(scalars)
if err != nil {
return nil, err
}
sections := []string{kimiCodeHeader(path) + "\n" + string(body)}
for _, key := range nested {
child, err := kimiCodeSections(append(append([]string(nil), path...), key), values[key].(map[string]any))
if err != nil {
return nil, err
}
sections = append(sections, child...)
}
return sections, nil
}
func kimiCodeHeader(path []string) string {
parts := make([]string, len(path))
for i, part := range path {
parts[i] = fmt.Sprintf("%q", part)
}
return "[" + strings.Join(parts, ".") + "]"
}
func kimiCodeAppendSections(text string, sections []string) string {
out := text
for _, section := range sections {
if out != "" {
if !strings.HasSuffix(out, "\n") {
out += "\n"
}
if !strings.HasSuffix(out, "\n\n") {
out += "\n"
}
}
out += strings.TrimRight(section, "\n") + "\n"
}
return out
}
func kimiCodeHasUserContent(cfg map[string]any) bool {
for key, value := range cfg {
switch key {
case "providers":
table, ok := value.(map[string]any)
if !ok {
return true
}
for name := range table {
if name != kimiCodeProviderName {
return true
}
}
case "models":
table, ok := value.(map[string]any)
if !ok {
return true
}
for alias := range table {
if !kimiCodeOwnedAlias(alias) {
return true
}
}
case "default_model":
default:
return true
}
}
return false
}
func kimiCodeModelEntry(m LaunchModel) map[string]any {
if m.Thinking == nil && m.HasCapability(modelpkg.CapabilityThinking) {
if meta, ok := lookupServerModelMetadata(m.Name); ok {
m.Thinking = meta.Thinking.Clone()
}
}
maxContextSize := m.ContextLength
if maxContextSize <= 0 {
maxContextSize = resolveKimiMaxContextSize(m.Name)
}
entry := map[string]any{
"provider": kimiCodeProviderName,
"model": m.Name,
"max_context_size": int64(maxContextSize),
}
capabilities := []string{}
if m.ToolCapable || m.HasCapability(modelpkg.CapabilityTools) {
capabilities = append(capabilities, "tool_use")
}
if m.HasCapability(modelpkg.CapabilityVision) {
capabilities = append(capabilities, "image_in")
}
levels, defaultLevel := launchReasoningEffortLevels(m.Thinking)
efforts := slices.DeleteFunc(slices.Clone(levels), func(level string) bool { return level == "none" })
if len(efforts) > 0 || m.HasCapability(modelpkg.CapabilityThinking) {
capabilities = append(capabilities, "thinking")
if slices.Contains(levels, "none") {
entry["off_effort"] = "none"
} else if len(efforts) > 0 {
capabilities = append(capabilities, "always_thinking")
}
if len(efforts) > 0 {
entry["support_efforts"] = kimiCodeStringList(efforts)
if slices.Contains(efforts, defaultLevel) {
entry["default_effort"] = defaultLevel
}
}
}
entry["capabilities"] = kimiCodeStringList(capabilities)
return entry
}
func kimiCodeStringList(values []string) []any {
out := make([]any, len(values))
for i, value := range values {
out[i] = value
}
return out
}
func (k *Kimi) ConfigureOnly(model string, models []LaunchModel) error {
return writeKimiCodeConfig(model, models)
}
func findKimiBinary() (string, error) {
home, _ := os.UserHomeDir()
kimiCodeBin := filepath.Join(home, ".kimi-code", "bin", "kimi")
if kimiGOOS == "windows" {
kimiCodeBin += ".exe"
}
if info, err := os.Stat(kimiCodeBin); err == nil && !info.IsDir() && (kimiGOOS == "windows" || info.Mode().Perm()&0o111 != 0) {
return kimiCodeBin, nil
}
if path, err := exec.LookPath("kimi"); err == nil {
return path, nil
}
home, _ := os.UserHomeDir()
var candidates []string
switch kimiGOOS {
case "windows":
@@ -191,62 +636,55 @@ func resolveKimiMaxContextSize(model string) int {
return l.Context
}
client, err := api.ClientFromEnvironment()
if err != nil {
return kimiDefaultMaxContextSize
}
ctx, cancel := context.WithTimeout(context.Background(), kimiModelShowTimeout)
defer cancel()
resp, err := client.Show(ctx, &api.ShowRequest{Model: model})
if err != nil {
return kimiDefaultMaxContextSize
}
if n, ok := modelInfoContextLength(resp.ModelInfo); ok {
if n := showContextLength(model); n > 0 {
return n
}
return kimiDefaultMaxContextSize
}
func modelInfoContextLength(modelInfo map[string]any) (int, bool) {
for key, val := range modelInfo {
if !strings.HasSuffix(key, ".context_length") {
continue
}
switch v := val.(type) {
case float64:
if v > 0 {
return int(v), true
}
case int:
if v > 0 {
return v, true
}
case int64:
if v > 0 {
return int(v), true
}
}
}
return 0, false
}
func ensureKimiInstalled() (string, error) {
if path, err := findKimiBinary(); err == nil {
return path, nil
existing, findErr := findKimiBinary()
version := ""
archived := false
if findErr == nil {
var legacy bool
version, legacy = kimiLegacyCLIVersion(existing)
if !legacy {
return existing, nil
}
archived = kimiLegacyCLIArchived(version)
}
if err := checkKimiInstallerDependencies(); err != nil {
if existing != "" {
if !kimiInstallerAvailable() || !isInteractiveSession() || currentLaunchConfirmPolicy.requireYesMessage {
if archived {
return "", kimiArchivedCLIError(version)
}
fmt.Fprintf(os.Stderr, "%sContinuing with kimi-cli %s%s\n\n", ansiYellow, version, ansiReset)
return existing, nil
}
} else if err := checkKimiInstallerDependencies(); err != nil {
return "", err
}
ok, err := ConfirmPrompt("Kimi is not installed. Install now?")
prompt := "Kimi is not installed. Install now?"
if existing != "" {
prompt = fmt.Sprintf("kimi-cli %s is no longer maintained and has been replaced by Kimi Code. Install Kimi Code now?", version)
}
ok, err := ConfirmPrompt(prompt)
if err != nil {
return "", err
}
if !ok {
if existing != "" {
if archived {
return "", kimiArchivedCLIError(version)
}
fmt.Fprintf(os.Stderr, "%sContinuing with kimi-cli %s%s\n\n", ansiYellow, version, ansiReset)
return existing, nil
}
return "", fmt.Errorf("kimi installation cancelled")
}
@@ -268,11 +706,18 @@ func ensureKimiInstalled() (string, error) {
if err != nil {
return "", fmt.Errorf("kimi was installed but the binary was not found on PATH\n\nYou may need to restart your shell")
}
if version, legacy := kimiLegacyCLIVersion(path); legacy && kimiLegacyCLIArchived(version) {
return "", kimiArchivedCLIError(version)
}
fmt.Fprintf(os.Stderr, "%sKimi installed successfully%s\n\n", ansiGreen, ansiReset)
return path, nil
}
func kimiInstallerAvailable() bool {
return checkKimiInstallerDependencies() == nil
}
func checkKimiInstallerDependencies() error {
switch kimiGOOS {
case "windows":
@@ -302,12 +747,12 @@ func kimiInstallerCommand(goos string) (string, []string, error) {
"-ExecutionPolicy",
"Bypass",
"-Command",
"Invoke-RestMethod https://code.kimi.com/install.ps1 | Invoke-Expression",
kimiInstallPowerShell,
}, nil
case "darwin", "linux":
return "bash", []string{
"-c",
"curl -LsSf https://code.kimi.com/install.sh | bash",
kimiInstallScript,
}, nil
default:
return "", nil, fmt.Errorf("unsupported platform for kimi install: %s", goos)
File diff suppressed because it is too large. Load diff
+52 -5
View File
@@ -286,9 +286,9 @@ func TestResolveKimiMaxContextSize(t *testing.T) {
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
oldTimeout := kimiModelShowTimeout
kimiModelShowTimeout = 100 * 1000 * 1000 // 100ms
t.Cleanup(func() { kimiModelShowTimeout = oldTimeout })
oldTimeout := modelShowTimeout
modelShowTimeout = 100 * 1000 * 1000 // 100ms
t.Cleanup(func() { modelShowTimeout = oldTimeout })
got := resolveKimiMaxContextSize("llama3.2")
if got != kimiDefaultMaxContextSize {
@@ -313,7 +313,7 @@ func TestKimiRun_RejectsConflictingArgsBeforeInstall(t *testing.T) {
}
}
func TestKimiRun_PassesInlineConfigAndExtraArgs(t *testing.T) {
func TestKimiRun_LegacyCLIPassesInlineConfigAndExtraArgs(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses POSIX shell fake binary")
}
@@ -322,6 +322,10 @@ func TestKimiRun_PassesInlineConfigAndExtraArgs(t *testing.T) {
setTestHome(t, tmpDir)
logPath := filepath.Join(tmpDir, "kimi-args.log")
script := fmt.Sprintf(`#!/bin/sh
if [ "$1" = "--version" ]; then
echo "kimi, version 1.50.0"
exit 0
fi
for arg in "$@"; do
printf "%%s\n" "$arg" >> %q
done
@@ -330,12 +334,24 @@ exit 0
if err := os.WriteFile(filepath.Join(tmpDir, "kimi"), []byte(script), 0o755); err != nil {
t.Fatalf("failed to write fake kimi: %v", err)
}
writeFakeBinary(t, tmpDir, "curl")
writeFakeBinary(t, tmpDir, "bash")
t.Setenv("PATH", tmpDir)
srv := httptest.NewServer(http.NotFoundHandler())
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
oldInteractive := isInteractiveSession
isInteractiveSession = func() bool { return true }
t.Cleanup(func() { isInteractiveSession = oldInteractive })
oldConfirm := DefaultConfirmPrompt
DefaultConfirmPrompt = func(prompt string, options ConfirmOptions) (bool, error) {
return false, nil
}
t.Cleanup(func() { DefaultConfirmPrompt = oldConfirm })
k := &Kimi{}
if err := k.Run("llama3.2", nil, []string{"--quiet", "--print"}); err != nil {
t.Fatalf("Run() error = %v", err)
@@ -481,7 +497,7 @@ exit 0
if err != nil {
t.Fatalf("failed to read install log: %v", err)
}
if !strings.Contains(string(logData), "https://code.kimi.com/install.sh") {
if !strings.Contains(string(logData), "https://code.kimi.com/kimi-code/install.sh") {
t.Fatalf("expected install.sh command in log, got:\n%s", string(logData))
}
})
@@ -634,3 +650,34 @@ func TestKimiInstallerCommand(t *testing.T) {
})
}
}
func TestKimiIntegrationInstallSpec(t *testing.T) {
spec, err := LookupIntegrationSpec("kimi")
if err != nil {
t.Fatalf("LookupIntegrationSpec() error = %v", err)
}
if !strings.Contains(spec.Install.URL, "kimi-code") {
t.Fatalf("install URL = %q, want kimi-code docs", spec.Install.URL)
}
if runtime.GOOS == "windows" {
t.Skip("uses POSIX executable names")
}
oldGOOS := kimiGOOS
kimiGOOS = runtime.GOOS
t.Cleanup(func() { kimiGOOS = oldGOOS })
homeDir := t.TempDir()
setTestHome(t, homeDir)
t.Setenv("PATH", "")
binPath := filepath.Join(homeDir, ".kimi-code", "bin", "kimi")
if err := os.MkdirAll(filepath.Dir(binPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(binPath, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
if !spec.Install.CheckInstalled() {
t.Fatal("CheckInstalled() = false, want true for a ~/.kimi-code/bin install")
}
}
+89 -21
View File
@@ -13,6 +13,7 @@ import (
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/cmd/config"
"github.com/ollama/ollama/internal/modelref"
modelpkg "github.com/ollama/ollama/types/model"
"github.com/spf13/cobra"
"golang.org/x/term"
@@ -187,6 +188,11 @@ type ManagedAutodiscoveryCloudIntegration interface {
UsesOllamaCloud() bool
}
// ConfigFileIntegration writes its own config file when launched with --config.
type ConfigFileIntegration interface {
ConfigureOnly(model string, models []LaunchModel) error
}
// RestoreHintIntegration can provide a short restore command after launch
// switches an app into a launch-managed mode.
type RestoreHintIntegration interface {
@@ -284,7 +290,7 @@ func LaunchCmd(checkServerHeartbeat func(cmd *cobra.Command, args []string) erro
Short: "Launch the Ollama menu or an integration",
Long: `Launch the Ollama interactive menu, or directly launch a specific integration.
Without arguments, this is equivalent to running 'ollama' directly.
Without arguments, choose a model or app from the interactive menu.
Flags and extra arguments require an integration name.
Supported integrations:
@@ -365,9 +371,14 @@ Examples:
return nil
}
if modelFlag != "" && isCloudModelName(modelFlag) {
canonical, _, _ := LookupIntegration(name)
piOverride := canonical == "pi" && piHasModelArgs(passArgs)
if modelFlag != "" && isCloudModelName(modelFlag) && !piOverride && !(canonical == "pi" && configFlag) {
if client, err := api.ClientFromEnvironment(); err == nil {
if disabled, _ := cloudStatusDisabled(cmd.Context(), client); disabled {
if canonical == "pi" {
return fmt.Errorf("cloud is disabled; enable cloud to use %s", modelFlag)
}
fmt.Fprintf(os.Stderr, "Warning: ignoring --model %s because cloud is disabled\n", modelFlag)
modelFlag = ""
}
@@ -378,7 +389,8 @@ Examples:
forceConfigure := configFlag || (modelFlag == "" && !headlessYes)
if forceConfigure && !configFlag && modelFlag == "" {
if _, runner, err := LookupIntegration(name); err == nil {
if _, ok := runner.(ManagedAutodiscoveryIntegration); ok {
switch runner.(type) {
case ManagedAutodiscoveryIntegration, *Pi:
forceConfigure = false
}
}
@@ -399,7 +411,7 @@ Examples:
},
}
cmd.Flags().StringVar(&modelFlag, "model", "", "Model to use")
cmd.Flags().StringVarP(&modelFlag, "model", "m", "", "Model to use")
cmd.Flags().BoolVar(&configFlag, "config", false, "Configure without launching")
cmd.Flags().BoolVar(&restoreFlag, "restore", false, "Restore an integration to its default profile")
cmd.Flags().BoolVarP(&yesFlag, "yes", "y", false, "Automatically answer yes to confirmation prompts")
@@ -487,6 +499,12 @@ func LaunchIntegration(ctx context.Context, req IntegrationLaunchRequest) error
return fmt.Errorf("headless --yes launch for %s requires --model <model>", name)
}
}
if pi, ok := runner.(*Pi); ok && !req.ForceConfigure && !req.ConfigureOnly && piHasModelArgs(req.ExtraArgs) {
if err := EnsureIntegrationInstalled(name, runner); err != nil {
return err
}
return runIntegration(pi, "", nil, req.ExtraArgs)
}
launchClient, saved, err := prepareIntegrationLaunch(name, policy)
if err != nil {
@@ -507,6 +525,11 @@ func LaunchIntegration(ctx context.Context, req IntegrationLaunchRequest) error
if err := EnsureIntegrationInstalled(name, runner); err != nil {
return err
}
if name == chatGPTIntegrationName {
if err := codexAppRouterHealth(); err != nil {
return err
}
}
return launchClient.launchManagedSingleIntegration(ctx, name, runner, managed, saved, req)
}
@@ -556,7 +579,10 @@ func prepareIntegrationLaunch(name string, policy LaunchPolicy) (*launcherClient
if err != nil {
return nil, nil, err
}
saved, _ := loadStoredIntegrationConfig(name)
saved, err := loadStoredIntegrationConfig(name)
if name == "pi" && err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, nil, err
}
return launchClient, saved, nil
}
@@ -630,6 +656,11 @@ func (c *launcherClient) launcherModelState(ctx context.Context, name string, is
if !hasModels {
return "", false, nil
}
if name == "pi" {
budget := modelShowTimeout
model, err := c.piTargetModel(ctx, cfg.Models[0], &budget)
return cfg.Models[0], err == nil && piSupportsChat(model), nil
}
if isEditor {
filtered := c.filterDisabledCloudModels(ctx, cfg.Models)
@@ -742,6 +773,9 @@ func (c *launcherClient) launchSingleIntegration(ctx context.Context, name strin
}
func (c *launcherClient) launchEditorIntegration(ctx context.Context, name string, runner Runner, editor Editor, saved *config.IntegrationConfig, req IntegrationLaunchRequest) error {
if pi, ok := editor.(*Pi); ok {
return c.launchPiIntegration(ctx, pi, saved, req)
}
previous := editorPreCheckedModels(saved, "")
models, needsConfigure := c.resolveEditorLaunchModels(ctx, saved, req)
if !needsConfigure && req.ModelOverride != "" && !slices.Contains(previous, req.ModelOverride) {
@@ -789,6 +823,9 @@ func (c *launcherClient) launchEditorIntegration(ctx context.Context, name strin
launchModels = c.resolveRunModels(ctx, name, models)
}
if name == "opencode" && len(req.ExtraArgs) == 0 {
launchModels = openCodeRuntimeModels(launchModels, c.recommendations(ctx))
}
return launchAfterConfiguration(name, runner, models[0], launchModels, req)
}
@@ -1084,6 +1121,12 @@ func (c *launcherClient) selectSingleModelWithSelectorReady(ctx context.Context,
if err != nil {
return "", err
}
if commandName == "pi" {
items = c.piSelectableModels(ctx, items)
if len(items) == 0 {
return "", errors.New("no chat models available, run 'ollama pull <model>' first")
}
}
previous := current
for {
@@ -1283,18 +1326,8 @@ func (c *launcherClient) ensureModelsReadyFor(ctx context.Context, models []stri
cloudModels := make(map[string]bool, len(models))
for _, model := range models {
if prompt := deprecatedLaunchModelPrompt(model, label, commandName, cloudRec, localRec); prompt != "" {
ok, err := ConfirmPromptWithOptions(prompt, ConfirmOptions{
YesLabel: "Launch anyway",
NoLabel: "Pick another model",
Default: ConfirmDefaultNo,
})
if err != nil {
return err
}
if !ok {
return errDeprecatedLaunchModelDeclined
}
if err := confirmDeprecatedLaunchModel(model, label, commandName, cloudRec, localRec); err != nil {
return err
}
isCloudModel := isCloudModelName(model)
if isCloudModel {
@@ -1307,6 +1340,23 @@ func (c *launcherClient) ensureModelsReadyFor(ctx context.Context, models []stri
return ensureAuth(ctx, c.apiClient, cloudModels, models)
}
func confirmDeprecatedLaunchModel(model, label, commandName, cloudRec, localRec string) error {
if prompt := deprecatedLaunchModelPrompt(model, label, commandName, cloudRec, localRec); prompt != "" {
ok, err := ConfirmPromptWithOptions(prompt, ConfirmOptions{
YesLabel: "Launch anyway",
NoLabel: "Pick another model",
Default: ConfirmDefaultNo,
})
if err != nil {
return err
}
if !ok {
return errDeprecatedLaunchModelDeclined
}
}
return nil
}
func (c *launcherClient) agentCapableRecommendations(ctx context.Context) (cloud, local string) {
recs := c.recommendations(ctx)
cloudDisabled, known := cloudStatusDisabled(ctx, c.apiClient)
@@ -1482,9 +1532,10 @@ func hasLocalModel(inventory []LaunchModel, name string) bool {
func (c *launcherClient) resolveRunModels(ctx context.Context, integration string, models []string) []LaunchModel {
recommendations := c.recommendations(ctx)
if integration == "codex" {
// Codex reads its /model choices from the generated catalog. Include
// installed tool-capable models as well as the requested starting model.
if integration == "codex" || integration == "kimi" {
// Codex reads its /model choices from a generated catalog and Kimi Code
// from config.toml. Include installed tool-capable models as well as the
// requested starting model.
if inventory, err := c.modelInventory().Load(ctx); err == nil {
cloudDisabled := false
if slices.ContainsFunc(inventory, func(model LaunchModel) bool { return model.Remote || isCloudModelName(model.Name) }) {
@@ -1532,7 +1583,19 @@ func (c *launcherClient) resolveRunModels(ctx context.Context, integration strin
}
func launchModelRecommendationKey(name string) string {
return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(name), ":latest"))
ref, err := modelref.ParseRef(name)
if err != nil {
return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(name), ":latest"))
}
key := strings.ToLower(strings.TrimSuffix(ref.Base, ":latest"))
switch ref.Source {
case modelref.ModelSourceCloud:
return key + ":cloud"
case modelref.ModelSourceLocal:
return key + ":local"
default:
return key
}
}
func runIntegration(runner Runner, modelName string, models []LaunchModel, args []string) error {
@@ -1544,6 +1607,11 @@ func runIntegration(runner Runner, modelName string, models []LaunchModel, args
func launchAfterConfiguration(name string, runner Runner, model string, models []LaunchModel, req IntegrationLaunchRequest) error {
if req.ConfigureOnly {
if configurable, ok := runner.(ConfigFileIntegration); ok {
if err := configurable.ConfigureOnly(model, models); err != nil {
return err
}
}
launch, err := ConfirmPrompt(fmt.Sprintf("Launch %s now?", runner))
if err != nil {
return err
+122 -2
View File
@@ -2,19 +2,36 @@ package launch
import (
"context"
"errors"
"slices"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/ollama/ollama/api"
modelpkg "github.com/ollama/ollama/types/model"
)
var (
modelShowTimeout = 5 * time.Second
lookupServerModelMetadata = cachedServerModelMetadata
serverModelMetadataCache sync.Map
serverModelMetadataUnavailable atomic.Bool
)
type serverModelMetadata struct {
ContextLength int
Capabilities []modelpkg.Capability
Thinking *modelpkg.Thinking
}
// LaunchModel is the model metadata Launch passes to integration config
// writers after resolving selected model names through the per-run inventory.
type LaunchModel struct {
Name string
Remote bool
RemoteModel string
ToolCapable bool
Capabilities []modelpkg.Capability
Thinking *api.ModelRecommendationThinking
@@ -46,6 +63,102 @@ func (m LaunchModel) WithCloudLimits() LaunchModel {
return m
}
func (m LaunchModel) WithServerMetadata() LaunchModel {
if (!m.Remote && !isCloudModelName(m.Name)) || (m.ContextLength > 0 && len(m.Capabilities) > 0) {
return m
}
meta, ok := lookupServerModelMetadata(m.Name)
if !ok {
return m
}
if m.ContextLength <= 0 {
m.ContextLength = meta.ContextLength
}
if len(m.Capabilities) == 0 {
m.Capabilities = slices.Clone(meta.Capabilities)
m.ToolCapable = slices.Contains(m.Capabilities, modelpkg.CapabilityTools)
}
if m.Thinking == nil {
m.Thinking = meta.Thinking.Clone()
}
return m
}
type serverModelMetadataEntry struct {
meta serverModelMetadata
ok bool
}
func cachedServerModelMetadata(model string) (serverModelMetadata, bool) {
if v, ok := serverModelMetadataCache.Load(model); ok {
entry := v.(serverModelMetadataEntry)
return entry.meta, entry.ok
}
if serverModelMetadataUnavailable.Load() {
return serverModelMetadata{}, false
}
meta, err := showModelMetadata(model)
if err != nil {
var statusErr api.StatusError
var authErr api.AuthorizationError
if !errors.As(err, &statusErr) && !errors.As(err, &authErr) {
serverModelMetadataUnavailable.Store(true)
}
}
ok := err == nil && (meta.ContextLength > 0 || len(meta.Capabilities) > 0 || meta.Thinking != nil)
serverModelMetadataCache.Store(model, serverModelMetadataEntry{meta: meta, ok: ok})
return meta, ok
}
func showModelMetadata(model string) (serverModelMetadata, error) {
client, err := api.ClientFromEnvironment()
if err != nil {
return serverModelMetadata{}, err
}
ctx, cancel := context.WithTimeout(context.Background(), modelShowTimeout)
defer cancel()
resp, err := client.Show(ctx, &api.ShowRequest{Model: model})
if err != nil {
return serverModelMetadata{}, err
}
meta := serverModelMetadata{
Capabilities: append([]modelpkg.Capability(nil), resp.Capabilities...),
Thinking: resp.Thinking.Clone(),
}
meta.ContextLength, _ = modelInfoContextLength(resp.ModelInfo)
return meta, nil
}
func showContextLength(model string) int {
meta, _ := showModelMetadata(model)
return meta.ContextLength
}
func modelInfoContextLength(modelInfo map[string]any) (int, bool) {
for key, val := range modelInfo {
if !strings.HasSuffix(key, ".context_length") {
continue
}
switch v := val.(type) {
case float64:
if v > 0 {
return int(v), true
}
case int:
if v > 0 {
return v, true
}
case int64:
if v > 0 {
return int(v), true
}
}
}
return 0, false
}
type modelInventory struct {
client *api.Client
@@ -63,6 +176,12 @@ func (i *modelInventory) Load(ctx context.Context) ([]LaunchModel, error) {
return i.load(ctx, false)
}
func (i *modelInventory) snapshot() []LaunchModel {
i.mu.Lock()
defer i.mu.Unlock()
return cloneLaunchModels(i.models)
}
func (i *modelInventory) Refresh(ctx context.Context) ([]LaunchModel, error) {
return i.load(ctx, true)
}
@@ -122,7 +241,7 @@ func resolveLaunchModels(names []string, models []LaunchModel) ([]LaunchModel, b
localMiss := false
for _, name := range names {
if model, ok := findLaunchModel(models, name); ok {
resolved = append(resolved, model.WithCloudLimits())
resolved = append(resolved, model.WithCloudLimits().WithServerMetadata())
continue
}
if !isCloudModelName(name) {
@@ -137,6 +256,7 @@ func launchModelFromListResponse(model api.ListModelResponse) LaunchModel {
return LaunchModel{
Name: model.Name,
Remote: model.RemoteModel != "",
RemoteModel: model.RemoteModel,
ToolCapable: slices.Contains(model.Capabilities, modelpkg.CapabilityTools),
Capabilities: append([]modelpkg.Capability(nil), model.Capabilities...),
ContextLength: model.Details.ContextLength,
@@ -147,7 +267,7 @@ func launchModelFromListResponse(model api.ListModelResponse) LaunchModel {
}
func fallbackLaunchModel(name string) LaunchModel {
return LaunchModel{Name: name, Remote: isCloudModelName(name)}.WithCloudLimits()
return LaunchModel{Name: name, Remote: isCloudModelName(name)}.WithCloudLimits().WithServerMetadata()
}
func findLaunchModel(models []LaunchModel, name string) (LaunchModel, bool) {
+104
View File
@@ -2,11 +2,14 @@ package launch
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"sync/atomic"
"testing"
"time"
"github.com/ollama/ollama/api"
modelpkg "github.com/ollama/ollama/types/model"
@@ -78,3 +81,104 @@ func TestModelInventoryResolveDoesNotRefreshCloudMiss(t *testing.T) {
t.Fatalf("cloud limits not applied: %#v", got[0])
}
}
func TestFallbackLaunchModelUsesServerMetadata(t *testing.T) {
useServerContextLookup(t)
var shown []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/show" {
http.NotFound(w, r)
return
}
var req api.ShowRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
t.Fatalf("decode show request: %v", err)
}
shown = append(shown, req.Model)
fmt.Fprint(w, `{"capabilities":["vision","thinking","completion","tools"],"thinking":{"values":[false,"low","high"],"default":"high"},"model_info":{"deepseek4.context_length":1048576}}`)
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
t.Run("cloud model missing from limits", func(t *testing.T) {
shown = nil
got := fallbackLaunchModel("deepseek-v4-pro-inventory-test:cloud")
if got.ContextLength != 1_048_576 {
t.Fatalf("ContextLength = %d, want 1048576", got.ContextLength)
}
if !got.ToolCapable || !got.HasCapability(modelpkg.CapabilityVision) || !got.HasCapability(modelpkg.CapabilityThinking) {
t.Fatalf("capabilities = %v, want vision, thinking and tools", got.Capabilities)
}
if got.Thinking == nil || got.Thinking.Default != "high" || len(got.Thinking.Values) != 3 {
t.Fatalf("Thinking = %#v, want the server's descriptor", got.Thinking)
}
if len(shown) != 1 || shown[0] != "deepseek-v4-pro-inventory-test:cloud" {
t.Fatalf("show calls = %v, want one for the model", shown)
}
shown = nil
if got := fallbackLaunchModel("deepseek-v4-pro-inventory-test:cloud"); got.ContextLength != 1_048_576 {
t.Fatalf("cached ContextLength = %d, want 1048576", got.ContextLength)
}
if len(shown) != 0 {
t.Fatalf("show calls = %v, want none when cached", shown)
}
})
t.Run("cloud model with known limits keeps the table context", func(t *testing.T) {
shown = nil
got := fallbackLaunchModel("kimi-k2.5:cloud")
if got.ContextLength != 262_144 || got.MaxOutputTokens != 262_144 {
t.Fatalf("limits = %d/%d, want the table's 262144/262144", got.ContextLength, got.MaxOutputTokens)
}
if !got.HasCapability(modelpkg.CapabilityVision) {
t.Fatalf("capabilities = %v, want the server's capabilities", got.Capabilities)
}
})
t.Run("local model", func(t *testing.T) {
shown = nil
got := fallbackLaunchModel("llama3.2")
if got.ContextLength != 0 || len(got.Capabilities) != 0 {
t.Fatalf("model = %#v, want no server metadata", got)
}
if len(shown) != 0 {
t.Fatalf("show calls = %v, want none for a local model", shown)
}
})
t.Run("resolved cloud model without metadata", func(t *testing.T) {
shown = nil
models := []LaunchModel{{Name: "glm-5.2-inventory-test:cloud", Remote: true}}
resolved, _ := resolveLaunchModels([]string{"glm-5.2-inventory-test:cloud"}, models)
if len(resolved) != 1 || resolved[0].ContextLength != 1_048_576 || !resolved[0].ToolCapable {
t.Fatalf("resolved = %#v, want ContextLength 1048576 and tool capability", resolved)
}
})
}
func TestServerModelMetadataStopsAfterUnreachableServer(t *testing.T) {
useServerContextLookup(t)
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
time.Sleep(300 * time.Millisecond)
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
oldTimeout := modelShowTimeout
modelShowTimeout = 50 * time.Millisecond
t.Cleanup(func() { modelShowTimeout = oldTimeout })
for _, name := range []string{"unreachable-a:cloud", "unreachable-b:cloud", "unreachable-a:cloud"} {
if _, ok := cachedServerModelMetadata(name); ok {
t.Fatalf("lookup for %s succeeded against a hanging server", name)
}
}
if got := hits.Load(); got != 1 {
t.Fatalf("show requests = %d, want 1 before the launcher stops asking", got)
}
}
+4
View File
@@ -275,6 +275,10 @@ func showOrPullWithPolicy(ctx context.Context, client *api.Client, model string,
}
}
return pullMissingModelWithPolicy(ctx, client, model, policy)
}
func pullMissingModelWithPolicy(ctx context.Context, client *api.Client, model string, policy missingModelPolicy) error {
switch policy {
case missingModelAutoPull:
return pullMissingModel(ctx, client, model)
+14 -7
View File
@@ -357,26 +357,33 @@ func museApplyLoadedContext(models []LaunchModel) []LaunchModel {
// museLoadedContextLength reports the effective context length of a model as
// the server loaded it, swappable so tests never touch a live server.
var museLoadedContextLength = loadedContextLength
var museLoadedContextLength = func(model string) int {
n, _ := loadedContextLength(model)
return n
}
// loadedContextLength loads model and reads the running instance's context
// length from the process list — the size the scheduler actually allocated.
// An empty generate request is ollama's load-only call: it returns once the
// model is resident without generating tokens, and the launch pays a load the
// first muse request would otherwise pay. Returns 0 when anything fails, and
// the caller keeps the inventory value.
func loadedContextLength(model string) int {
// first inference request would otherwise pay. Load failures return an error;
// a successful load with unavailable context metadata returns 0, nil.
func loadedContextLength(model string) (int, error) {
client, err := api.ClientFromEnvironment()
if err != nil {
return 0
return 0, err
}
ctx, cancel := context.WithTimeout(context.Background(), museLoadTimeout)
defer cancel()
if err := client.Generate(ctx, &api.GenerateRequest{Model: model}, func(api.GenerateResponse) error { return nil }); err != nil {
return 0
return 0, err
}
return LoadedContextWindow(ctx, client, model)
// Context metadata is optional; a stalled lookup must not hold up launch
// for the remainder of a large model's load timeout.
lookupCtx, cancelLookup := context.WithTimeout(ctx, 5*time.Second)
defer cancelLookup()
return LoadedContextWindow(lookupCtx, client, model), nil
}
// museRunModels puts the model being launched first, since muse takes its
+276 -8
View File
@@ -1,7 +1,9 @@
package launch
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
@@ -9,13 +11,17 @@ import (
"runtime"
"slices"
"strings"
"time"
"github.com/charmbracelet/x/ansi"
"github.com/ollama/ollama/cmd/internal/fileutil"
"github.com/ollama/ollama/envconfig"
)
const openCodeInstallScript = "curl -fsSL https://opencode.ai/install | bash"
const openCodeDefaultMaxOutputTokens = 32_000
var openCodeGOOS = runtime.GOOS
// OpenCode implements Runner and Editor for OpenCode integration.
@@ -53,18 +59,281 @@ func (o *OpenCode) Run(model string, models []LaunchModel, args []string) error
if err != nil {
return err
}
content, err := o.runContent(model, models, args...)
if err != nil {
return err
}
if len(args) == 0 && model != "" {
switch openCodeMajorVersion(opencodePath) {
case 2:
// The shared v2 service does not inherit this launch's inline config.
args = []string{"--standalone"}
case 1:
// V1 needs an explicit selection to override an agent's configured model.
if primary, ok := findLaunchModel(models, model); ok {
model = primary.Name
}
args = []string{"--model", "ollama/" + model}
}
}
cmd := exec.Command(opencodePath, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = os.Environ()
if content := o.resolveContent(model, models); content != "" {
if content != "" {
cmd.Env = append(cmd.Env, "OPENCODE_CONFIG_CONTENT="+content)
}
return cmd.Run()
}
// Return zero for an unknown version so neither version-specific flag is added.
func openCodeMajorVersion(path string) int {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, path, "--version")
cmd.WaitDelay = time.Second
data, err := cmd.Output()
if err != nil {
return 0
}
fields := strings.Fields(string(data))
if len(fields) == 0 {
return 0
}
version := strings.TrimPrefix(fields[len(fields)-1], "v")
if strings.HasPrefix(version, "1.") {
return 1
}
if strings.HasPrefix(version, "2.") {
return 2
}
return 0
}
var (
openCodeLoadedContextLength = loadedContextLength
openCodeReadConfig = readOpenCodeConfig
)
// Let OpenCode resolve its configuration layers, including JSONC and project settings.
func readOpenCodeConfig() ([]byte, error) {
path, ok := findOpenCode()
if !ok {
return nil, fmt.Errorf("could not find the OpenCode executable")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, path, "debug", "config")
// npm's launcher can leave a child holding the output pipes after cancellation.
cmd.WaitDelay = time.Second
data, err := cmd.Output()
if ctx.Err() != nil {
return nil, ctx.Err()
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if diagnostic := openCodeConfigDiagnostic(exitErr.Stderr); diagnostic != "" {
err = fmt.Errorf("%w: %s", err, diagnostic)
}
return nil, fmt.Errorf("%w\nRun `opencode debug config` for details.", err)
}
return data, err
}
// OpenCode's validation messages can echo credentials or the entire JSONC file.
// Keep only the config location and issue paths, never messages or input values.
func openCodeConfigDiagnostic(stderr []byte) string {
// Cmd.Output truncates large errors mid-message. A partial rejected value
// must not be mistaken for a field path; use the recovery command instead.
if len(stderr) > 16<<10 {
return ""
}
lines := strings.Split(ansi.Strip(string(stderr)), "\n")
for i, line := range lines {
line = strings.TrimPrefix(strings.TrimSuffix(line, "\r"), "Error: ")
if path, ok := strings.CutPrefix(line, "Config file at "); ok {
if path, _, ok := strings.Cut(path, " is not valid JSON(C)"); ok {
return fmt.Sprintf("config file at %q is not valid JSON(C)", path)
}
}
rest, ok := strings.CutPrefix(line, "Configuration is invalid")
if !ok {
continue
}
diagnostic := "configuration is invalid"
if path, ok := strings.CutPrefix(rest, " at "); ok {
path, _, _ = strings.Cut(path, ": ")
diagnostic += fmt.Sprintf(" at %q", path)
}
var fields []string
for _, issue := range lines[i+1:] {
issue = strings.TrimSuffix(issue, "\r")
if !strings.HasPrefix(issue, "↳ ") {
break
}
// OpenCode appends a space and the field path, even for root issues
// whose path is empty. Preserve that trailing space when parsing.
if last := strings.LastIndexByte(issue, ' '); last >= 0 && last < len(issue)-1 {
fields = append(fields, fmt.Sprintf("%q", issue[last+1:]))
}
}
if len(fields) > 0 {
diagnostic += " (invalid fields: " + strings.Join(fields, ", ") + ")"
}
return diagnostic
}
return ""
}
// runContent refreshes only the selected local model's limits after loading it.
// Edit remains metadata-only; other picker entries are not loaded, and their
// limits must not inherit the selected model's allocation.
func (o *OpenCode) runContent(model string, models []LaunchModel, args ...string) (string, error) {
content := o.resolveContent(model, models)
// Forwarded arguments may select another model, resume a session, or run a
// utility. Leave those invocations entirely to OpenCode.
if len(args) > 0 {
return content, nil
}
primary, _ := findLaunchModel(models, model)
if model == "" || primary.Remote || isCloudModelName(model) {
return content, nil
}
if primary.Name != "" {
model = primary.Name
}
var config map[string]any
if err := json.Unmarshal([]byte(content), &config); err != nil {
return "", err
}
providers, _ := config["provider"].(map[string]any)
provider, _ := providers["ollama"].(map[string]any)
entries, _ := provider["models"].(map[string]any)
entry, _ := entries[model].(map[string]any)
if entry == nil {
return content, nil
}
fmt.Fprintf(os.Stderr, "Loading %s...\n", model)
contextLength, err := openCodeLoadedContextLength(model)
if err != nil {
return "", fmt.Errorf("could not load %s: %w", model, err)
}
if contextLength < 4 {
fmt.Fprintf(os.Stderr, "Warning: could not read the context size for %s. Continuing with existing settings; long chats may lose earlier messages.\n", model)
return content, nil
}
data, err := openCodeReadConfig()
if err != nil {
return "", fmt.Errorf("could not read OpenCode configuration: %w", err)
}
saved, err := openCodeConfiguredLimits(data)
if err != nil {
return "", fmt.Errorf("could not read OpenCode model limits: %w", err)
}
// OpenCode prioritizes input over context for compaction. Override stale
// input limits too, while keeping a user's smaller limit.
input := contextLength
// Reserve a quarter of the context for output, capped at 8k. Avoid a
// minimum output budget that could consume a small allocation entirely.
output := min(8192, contextLength/4)
if primary.MaxOutputTokens > 0 {
output = min(output, primary.MaxOutputTokens)
}
for name, configured := range saved {
if !launchModelMatches(name, model) && !launchModelMatches(model, name) {
continue
}
if configured.Input != nil && *configured.Input > 0 {
input = min(input, *configured.Input)
}
if configured.Output != nil && *configured.Output > 0 {
output = min(output, *configured.Output)
}
}
limit, _ := entry["limit"].(map[string]any)
if limit == nil {
limit = make(map[string]any)
}
if known, ok := limit["output"].(float64); ok && known > 0 {
output = min(output, int(known))
}
limit["context"] = contextLength
limit["input"] = input
limit["output"] = output
entry["limit"] = limit
data, err = json.Marshal(config)
return string(data), err
}
type openCodeModelLimits struct{ Input, Output *int }
// V1 debug config returns a resolved object; V2 returns normalized source
// entries from lowest to highest priority. Read only Ollama model limits.
func openCodeConfiguredLimits(data []byte) (map[string]openCodeModelLimits, error) {
type providers map[string]struct {
Models map[string]struct{ Limit openCodeModelLimits }
}
var sources []providers
if strings.HasPrefix(strings.TrimSpace(string(data)), "[") {
var entries []struct {
Type string
Info struct{ Providers providers }
}
if err := json.Unmarshal(data, &entries); err != nil {
return nil, err
}
for _, entry := range entries {
if entry.Type == "document" {
sources = append(sources, entry.Info.Providers)
}
}
} else {
var config struct{ Provider providers }
if err := json.Unmarshal(data, &config); err != nil {
return nil, err
}
sources = append(sources, config.Provider)
}
limits := make(map[string]openCodeModelLimits)
for _, source := range sources {
for name, model := range source["ollama"].Models {
limit := limits[name]
if model.Limit.Input != nil {
limit.Input = model.Limit.Input
}
if model.Limit.Output != nil {
limit.Output = model.Limit.Output
}
limits[name] = limit
}
}
return limits, nil
}
// openCodeRuntimeModels carries recommended output ceilings to Run after Edit
// has built the fallback configuration. Native context metadata remains intact.
func openCodeRuntimeModels(models []LaunchModel, recommendations []ModelItem) []LaunchModel {
models = cloneLaunchModels(models)
for i := range models {
if models[i].Remote || isCloudModelName(models[i].Name) {
continue
}
for _, rec := range recommendations {
if launchModelRecommendationKey(models[i].Name) != launchModelRecommendationKey(rec.Name) || rec.MaxOutputTokens <= 0 {
continue
}
if models[i].MaxOutputTokens <= 0 || rec.MaxOutputTokens < models[i].MaxOutputTokens {
models[i].MaxOutputTokens = rec.MaxOutputTokens
}
}
}
return models
}
func ensureOpenCodeInstalled() (string, error) {
if opencodePath, ok := findOpenCode(); ok {
return opencodePath, nil
@@ -374,13 +643,12 @@ func buildModelEntries(modelList []LaunchModel) map[string]any {
}
}
}
if model.MaxOutputTokens > 0 {
limit := make(map[string]any)
if model.ContextLength > 0 {
limit["context"] = model.ContextLength
if model.ContextLength > 0 && (model.MaxOutputTokens > 0 || model.Remote || isCloudModelName(model.Name)) {
output := model.MaxOutputTokens
if output <= 0 {
output = openCodeDefaultMaxOutputTokens
}
limit["output"] = model.MaxOutputTokens
entry["limit"] = limit
entry["limit"] = map[string]any{"context": model.ContextLength, "output": output}
}
models[model.Name] = entry
}
+615
View File
@@ -0,0 +1,615 @@
package launch
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"time"
"github.com/ollama/ollama/api"
)
func TestOpenCodeRunContentLoadedContext(t *testing.T) {
for _, fromEdit := range []bool{false, true} {
t.Run(map[bool]string{false: "saved configuration", true: "fresh edit"}[fromEdit], func(t *testing.T) {
setTestHome(t, t.TempDir())
models := []LaunchModel{
{Name: "selected", ContextLength: 131072, Details: api.ModelDetails{ContextLength: 131072}},
{Name: "other", ContextLength: 65536, MaxOutputTokens: 4096},
{Name: "cloud-alias", Remote: true, ContextLength: 262144, MaxOutputTokens: 32768},
}
o := &OpenCode{}
var loaded []string
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(name string) (int, error) {
loaded = append(loaded, name)
return 8192, nil
}
t.Cleanup(func() { openCodeLoadedContextLength = previous })
if fromEdit {
if err := o.Edit(models); err != nil {
t.Fatal(err)
}
if len(loaded) != 0 {
t.Fatalf("Edit loaded models: %v", loaded)
}
}
before := o.resolveContent("selected", models)
after, err := o.runContent("selected", models)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(loaded, []string{"selected"}) {
t.Fatalf("loaded = %v, want selected only", loaded)
}
var expected, got map[string]any
if err := json.Unmarshal([]byte(before), &expected); err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(after), &got); err != nil {
t.Fatal(err)
}
entry := expected["provider"].(map[string]any)["ollama"].(map[string]any)["models"].(map[string]any)["selected"].(map[string]any)
entry["limit"] = map[string]any{"context": float64(8192), "input": float64(8192), "output": float64(2048)}
if !reflect.DeepEqual(got, expected) {
t.Fatalf("runtime config changed beyond selected limits:\ngot %s", after)
}
if models[0].ContextLength != 131072 || models[0].Details.ContextLength != 131072 || o.resolveContent("selected", models) != before {
t.Fatal("runtime limits mutated inventory or cached configuration")
}
})
}
}
func TestOpenCodeRunContentSkipsCloud(t *testing.T) {
setTestHome(t, t.TempDir())
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(name string) (int, error) {
t.Fatalf("cloud model %q was loaded locally", name)
return 0, nil
}
t.Cleanup(func() { openCodeLoadedContextLength = previous })
for _, primary := range []LaunchModel{
{Name: "glm-5:cloud", ContextLength: 202752, MaxOutputTokens: 131072},
{Name: "cloud-alias", Remote: true, ContextLength: 131072, MaxOutputTokens: 8192},
} {
o := &OpenCode{}
models := []LaunchModel{primary, {Name: "local", ContextLength: 32768}}
before := o.resolveContent(primary.Name, models)
after, err := o.runContent(primary.Name, models)
if err != nil || after != before {
t.Fatalf("cloud config changed: %s, %v", after, err)
}
}
}
func TestOpenCodeRunContentV2Config(t *testing.T) {
setTestHome(t, t.TempDir())
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(string) (int, error) { return 8192, nil }
t.Cleanup(func() { openCodeLoadedContextLength = previous })
openCodeReadConfig = func() ([]byte, error) {
// V2 debug config returns normalized sources in increasing priority order.
return []byte(`[
{"type":"document","info":{"providers":{"ollama":{"models":{"local:latest":{"limit":{"input":1024,"output":512}}}}}}},
{"type":"directory","path":"/scratch/.opencode"},
{"type":"document","info":{"providers":{"ollama":{"models":{"local:latest":{"limit":{"input":4096}}}}}}},
{"type":"document","info":{"providers":{"other":{"models":{"local:latest":{"limit":{"output":1}}}}}}}
]`), nil
}
content, err := (&OpenCode{}).runContent("local", []LaunchModel{{Name: "local:latest", ContextLength: 131072}})
if err != nil {
t.Fatal(err)
}
var cfg struct {
Model string
Provider map[string]struct {
Models map[string]struct {
Limit struct{ Context, Input, Output int }
}
}
}
if err := json.Unmarshal([]byte(content), &cfg); err != nil {
t.Fatal(err)
}
if cfg.Model != "ollama/local:latest" {
t.Fatalf("selected model = %q", cfg.Model)
}
limit := cfg.Provider["ollama"].Models["local:latest"].Limit
if want := (struct{ Context, Input, Output int }{8192, 4096, 512}); limit != want {
t.Fatalf("limit = %+v, want %+v", limit, want)
}
}
func TestOpenCodeConfiguredLimitsV2Reset(t *testing.T) {
data := []byte(`[
{"type":"document","info":{"providers":{"ollama":{"models":{"local":{"limit":{"input":1024,"output":512}}}}}}},
{"type":"document","info":{"providers":{"ollama":{"models":{"local":{"limit":{"input":0,"output":0}}}}}}}
]`)
limits, err := openCodeConfiguredLimits(data)
if err != nil {
t.Fatal(err)
}
limit := limits["local"]
if limit.Input == nil || *limit.Input != 0 || limit.Output == nil || *limit.Output != 0 {
t.Fatalf("higher-priority zero limits did not clear lower-priority caps: %+v", limit)
}
}
func TestOpenCodeConfiguredLimitsInvalid(t *testing.T) {
for _, data := range []string{
`{`,
`[`,
`{"provider":{"ollama":{"models":{"local":{"limit":{"input":"invalid"}}}}}}`,
`[{"type":"document","info":{"providers":{"ollama":{"models":{"local":{"limit":{"output":"invalid"}}}}}}}]`,
} {
if _, err := openCodeConfiguredLimits([]byte(data)); err == nil {
t.Errorf("accepted invalid model limits: %s", data)
}
}
}
func TestOpenCodeRunContentOutputBudget(t *testing.T) {
setTestHome(t, t.TempDir())
previous := openCodeLoadedContextLength
t.Cleanup(func() { openCodeLoadedContextLength = previous })
for _, tt := range []struct {
context, knownOutput, savedInput, savedOutput, wantInput, wantOutput int
}{
{1024, 0, 0, 0, 1024, 256},
{2048, 0, 0, 0, 2048, 512},
{16384, 0, 0, 0, 16384, 4096},
{65536, 0, 0, 0, 65536, 8192},
{16384, 1024, 0, 0, 16384, 1024},
{8192, 0, 131072, 0, 8192, 2048},
{8192, 0, 131072, 1024, 8192, 1024},
{8192, 0, 4096, 1024, 4096, 1024},
{8192, 0, 131072, 32768, 8192, 2048},
} {
openCodeLoadedContextLength = func(string) (int, error) { return tt.context, nil }
openCodeReadConfig = func() ([]byte, error) {
return fmt.Appendf(nil, `{"provider":{"ollama":{"models":{"local":{"limit":{"context":131072,"input":%d,"output":%d}}}}}}`, tt.savedInput, tt.savedOutput), nil
}
content, err := (&OpenCode{}).runContent("local", []LaunchModel{{Name: "local", ContextLength: 131072, MaxOutputTokens: tt.knownOutput}})
if err != nil {
t.Fatal(err)
}
var cfg struct {
Provider map[string]struct {
Models map[string]struct {
Limit struct{ Context, Input, Output int }
}
}
}
if err := json.Unmarshal([]byte(content), &cfg); err != nil {
t.Fatal(err)
}
limit := cfg.Provider["ollama"].Models["local"].Limit
want := struct{ Context, Input, Output int }{tt.context, tt.wantInput, tt.wantOutput}
if limit != want {
t.Fatalf("limit = %+v, want %+v", limit, want)
}
}
}
func TestOpenCodeRunContentConfigFailure(t *testing.T) {
setTestHome(t, t.TempDir())
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(string) (int, error) { return 8192, nil }
t.Cleanup(func() { openCodeLoadedContextLength = previous })
configErr := errors.New("configuration unavailable")
openCodeReadConfig = func() ([]byte, error) { return nil, configErr }
content, err := (&OpenCode{}).runContent("local", []LaunchModel{{Name: "local"}})
if content != "" || !errors.Is(err, configErr) {
t.Fatalf("configuration failure allowed launch or lost its cause: %q, %v", content, err)
}
}
func TestOpenCodeRunConfigDiagnostic(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a POSIX shell wrapper")
}
for _, tt := range []struct {
name, diagnostic string
want []string
}{
{
name: "invalid field",
diagnostic: "\x1b[91m\x1b[1mError: \x1b[0mConfiguration is invalid at %s: private diagnostic SYNTHETIC_SECRET\n↳ Expected string | undefined, got {\"apiKey\":\"SYNTHETIC_SECRET\"} model\n↳ Expected number, got \"SYNTHETIC_SECRET\" provider.ollama.models.local.limit.input\n",
want: []string{"%s", "model", "provider.ollama.models.local.limit.input"},
},
{
name: "invalid root",
diagnostic: "Error: Configuration is invalid at %s\n↳ Expected Config, got SYNTHETIC_SECRET \n",
want: []string{"%s"},
},
{
name: "invalid JSONC",
diagnostic: "Error: Config file at %s is not valid JSON(C): SYNTHETIC_SECRET\n--- JSONC Input ---\n{\"apiKey\":\"SYNTHETIC_SECRET\", invalid}\n",
want: []string{"%s", "not valid JSON(C)"},
},
{
name: "unknown diagnostic",
diagnostic: "Unexpected error: SYNTHETIC_SECRET\n",
},
{
name: "oversized diagnostic",
diagnostic: "Error: Configuration is invalid at %s\n↳ Expected string, got " + strings.Repeat("SYNTHETIC_SECRET ", 6000) + "model\n",
},
} {
t.Run(tt.name, func(t *testing.T) {
dir := t.TempDir()
setTestHome(t, dir)
path := filepath.Join(dir, "my config.jsonc")
diagnostic := strings.ReplaceAll(tt.diagnostic, "%s", path)
t.Setenv("OPENCODE_TEST_DIAGNOSTIC", diagnostic)
script := "#!/bin/sh\n[ \"$1 $2\" = 'debug config' ] || exit 99\nprintf '%s' 'SYNTHETIC_SECRET'\nprintf '%s' \"$OPENCODE_TEST_DIAGNOSTIC\" >&2\nexit 1\n"
if err := os.WriteFile(filepath.Join(dir, "opencode"), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir)
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(string) (int, error) { return 8192, nil }
t.Cleanup(func() { openCodeLoadedContextLength = previous })
openCodeReadConfig = readOpenCodeConfig
var err error
stderr := captureStderr(t, func() {
err = (&OpenCode{}).Run("local", []LaunchModel{{Name: "local"}}, nil)
})
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) || exitErr.ExitCode() != 1 {
t.Fatalf("config failure allowed launch or lost its cause: %v", err)
}
want := append([]string{"opencode debug config"}, tt.want...)
for _, text := range want {
text = strings.ReplaceAll(text, "%s", path)
if !strings.Contains(err.Error(), text) {
t.Errorf("config error %q does not identify %q", err, text)
}
}
if strings.Contains(err.Error()+stderr, "SYNTHETIC_") {
t.Fatal("config diagnostic exposed a rejected value or config contents")
}
})
}
}
func TestOpenCodeReadConfigBoundsDescendantWait(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a POSIX shell wrapper")
}
dir := t.TempDir()
setTestHome(t, dir)
// Like the npm launcher, the wrapper starts a child with inherited output.
if err := os.WriteFile(filepath.Join(dir, "opencode"), []byte("#!/bin/sh\nsleep 10 &\nwait\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
started := time.Now()
_, err := readOpenCodeConfig()
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("lookup error = %v, want deadline exceeded", err)
}
if elapsed := time.Since(started); elapsed > 9*time.Second {
t.Fatalf("lookup waited for descendant output after cancellation: %v", elapsed)
}
}
func TestOpenCodeRunContentUnknownAllocationKeepsConfig(t *testing.T) {
setTestHome(t, t.TempDir())
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(string) (int, error) { return 0, nil }
t.Cleanup(func() { openCodeLoadedContextLength = previous })
for _, knownOutput := range []int{0, 4096} {
o := &OpenCode{}
models := []LaunchModel{{Name: "local", ContextLength: 131072, MaxOutputTokens: knownOutput}}
before := o.resolveContent("local", models)
warning := captureStderr(t, func() {
content, err := o.runContent("local", models)
if err != nil || content != before {
t.Fatalf("unknown allocation changed launch config: %q, %v", content, err)
}
})
if strings.Count(warning, "Warning:") != 1 || !strings.Contains(warning, "local") {
t.Fatalf("expected one warning identifying the model, got %q", warning)
}
}
}
func TestOpenCodeRunContentLoadFailurePreservesCause(t *testing.T) {
setTestHome(t, t.TempDir())
previous := openCodeLoadedContextLength
loadErr := errors.New("model requires more system memory")
openCodeLoadedContextLength = func(string) (int, error) { return 0, loadErr }
t.Cleanup(func() { openCodeLoadedContextLength = previous })
content, err := (&OpenCode{}).runContent("local", []LaunchModel{{Name: "local"}})
if content != "" || !errors.Is(err, loadErr) || !strings.Contains(err.Error(), "local") {
t.Fatalf("load error lost its cause or allowed launch: %q, %v", content, err)
}
}
func TestOpenCodeRunContentLatestAlias(t *testing.T) {
setTestHome(t, t.TempDir())
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(name string) (int, error) {
if name != "local:latest" {
t.Fatalf("loaded %q, want canonical selected model", name)
}
return 8192, nil
}
t.Cleanup(func() { openCodeLoadedContextLength = previous })
openCodeReadConfig = func() ([]byte, error) {
return []byte(`{"provider":{"ollama":{"models":{
"local":{"limit":{"input":4096,"output":1024}},
"local:latest":{"limit":{"input":16384,"output":8192}},
"local:7b":{"limit":{"input":128,"output":32}}
}}}}`), nil
}
content, err := (&OpenCode{}).runContent("local", []LaunchModel{{Name: "local:latest"}})
if err != nil {
t.Fatal(err)
}
var cfg map[string]any
if err := json.Unmarshal([]byte(content), &cfg); err != nil {
t.Fatal(err)
}
limit := cfg["provider"].(map[string]any)["ollama"].(map[string]any)["models"].(map[string]any)["local:latest"].(map[string]any)["limit"]
want := map[string]any{"context": float64(8192), "input": float64(4096), "output": float64(1024)}
if !reflect.DeepEqual(limit, want) {
t.Fatalf("canonical model limits = %v, want %v", limit, want)
}
}
func TestOpenCodeConfigureOnlySkipsLoad(t *testing.T) {
setTestHome(t, t.TempDir())
previousLoad, previousConfirm := openCodeLoadedContextLength, DefaultConfirmPrompt
openCodeLoadedContextLength = func(name string) (int, error) {
t.Fatalf("configuration-only loaded %q", name)
return 0, nil
}
DefaultConfirmPrompt = func(prompt string, _ ConfirmOptions) (bool, error) {
if prompt != "Launch OpenCode now?" {
t.Fatalf("unexpected prompt: %s", prompt)
}
return false, nil
}
t.Cleanup(func() {
openCodeLoadedContextLength, DefaultConfirmPrompt = previousLoad, previousConfirm
})
o := &OpenCode{}
models := []LaunchModel{{Name: "local", ContextLength: 131072}}
if err := o.Edit(models); err != nil {
t.Fatal(err)
}
if err := launchAfterConfiguration("opencode", o, "local", models, IntegrationLaunchRequest{ConfigureOnly: true}); err != nil {
t.Fatal(err)
}
}
func TestOpenCodeRunForwardsArgsWithoutPreload(t *testing.T) {
setTestHome(t, t.TempDir())
bin := t.TempDir()
writeFakeBinary(t, bin, "opencode")
output := filepath.Join(bin, "env-and-args")
t.Setenv("OPENCODE_LAUNCH_TEST_OUTPUT", output)
if runtime.GOOS != "windows" {
if err := os.WriteFile(filepath.Join(bin, "opencode"), []byte("#!/bin/sh\nprintf '%s\\n' \"$OPENCODE_CONFIG_CONTENT\" \"$@\" > \"$OPENCODE_LAUNCH_TEST_OUTPUT\"\n"), 0o755); err != nil {
t.Fatal(err)
}
}
t.Setenv("PATH", bin)
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(model string) (int, error) {
t.Errorf("unexpected load of %q", model)
return 0, errors.New("model does not fit in memory")
}
previousReadConfig := openCodeReadConfig
t.Cleanup(func() {
openCodeLoadedContextLength = previous
openCodeReadConfig = previousReadConfig
})
models := []LaunchModel{{Name: "local"}, {Name: "other"}}
o := &OpenCode{}
before := o.resolveContent("local", models)
checkChild := func(content string, args []string) {
t.Helper()
if runtime.GOOS == "windows" {
return
}
got, err := os.ReadFile(output)
if err != nil {
t.Fatal(err)
}
want := strings.Join(append([]string{content}, args...), "\n") + "\n"
if string(got) != want {
t.Fatalf("child environment and arguments = %q, want %q", got, want)
}
}
for _, args := range [][]string{
{"--help"},
{"--version"},
{"serve"},
{"debug", "config"},
{"run", "hello"},
{"--model", "ollama/other"},
{"run", "-m", "other/model", "hello"},
{"--continue"},
{"--session", "session-id"},
{"--agent", "custom"},
{"project"},
{"--new-option"},
} {
t.Run(strings.Join(args, " "), func(t *testing.T) {
original := append([]string(nil), args...)
content, err := o.runContent("local", models, args...)
if err != nil || content != before {
t.Fatalf("forwarded arguments changed the configuration: %q, %v", content, err)
}
if err := o.Run("local", models, args); err != nil {
t.Fatal(err)
}
checkChild(before, args)
if !reflect.DeepEqual(args, original) {
t.Fatal("modified caller-owned arguments")
}
})
}
openCodeLoadedContextLength = func(string) (int, error) { return 8192, nil }
openCodeReadConfig = func() ([]byte, error) { return []byte(`{}`), nil }
models[0].Name = "local:latest"
content, err := o.runContent("local", models)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(content, `"model":"ollama/local:latest"`) {
t.Fatalf("selected model missing from inline config: %s", content)
}
if err := o.Run("local", models, nil); err != nil {
t.Fatal(err)
}
checkChild(content, nil)
}
func TestOpenCodeRunArgsByVersion(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a POSIX shell fake executable")
}
setTestHome(t, t.TempDir())
bin := t.TempDir()
output := filepath.Join(bin, "env-and-args")
t.Setenv("OPENCODE_LAUNCH_TEST_OUTPUT", output)
t.Setenv("PATH", bin)
script := `#!/bin/sh
if [ "$1" = "--version" ]; then
if [ "$OPENCODE_LAUNCH_TEST_VERSION_EXIT" = "timeout" ]; then
exec /bin/sleep 10
fi
if [ -n "$OPENCODE_LAUNCH_TEST_VERSION_DELAY" ]; then
/bin/sleep "$OPENCODE_LAUNCH_TEST_VERSION_DELAY"
fi
printf '%s\n' "$OPENCODE_LAUNCH_TEST_VERSION"
exit "$OPENCODE_LAUNCH_TEST_VERSION_EXIT"
fi
printf '%s\n' "$OPENCODE_CONFIG_CONTENT" "$@" > "$OPENCODE_LAUNCH_TEST_OUTPUT"
`
if err := os.WriteFile(filepath.Join(bin, "opencode"), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
models := []LaunchModel{{Name: "selected:latest", Remote: true}}
o := &OpenCode{}
content := o.resolveContent("selected", models)
for _, tt := range []struct {
name, version, versionExit, versionDelay string
args []string
}{
{"v1", "1.18.35", "0", "", []string{"--model", "ollama/selected:latest"}},
{"v1 branded", "opencode v1.19.4", "0", "", []string{"--model", "ollama/selected:latest"}},
{"v2", "2.1.4", "0", "", []string{"--standalone"}},
{"v2 branded", "opencode v2.1.4", "0", "", []string{"--standalone"}},
{"v2 prerelease", "opencode v2.1.4-beta.1\n", "0", "", []string{"--standalone"}},
{"slow v2 probe", "2.1.4", "0", "2", []string{"--standalone"}},
{"empty version", "", "0", "", nil},
{"unknown version", "unknown", "0", "", nil},
{"future version", "3.0.0", "0", "", nil},
{"failed v1 probe", "opencode v1.19.4", "1", "", nil},
{"failed v2 probe", "opencode v2.1.4", "1", "", nil},
{"probe timeout", "", "timeout", "", nil},
} {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("OPENCODE_LAUNCH_TEST_VERSION", tt.version)
t.Setenv("OPENCODE_LAUNCH_TEST_VERSION_EXIT", tt.versionExit)
t.Setenv("OPENCODE_LAUNCH_TEST_VERSION_DELAY", tt.versionDelay)
if err := o.Run("selected", models, nil); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(output)
if err != nil {
t.Fatal(err)
}
want := strings.Join(append([]string{content}, tt.args...), "\n") + "\n"
if string(got) != want {
t.Fatalf("child environment and arguments = %q, want %q", got, want)
}
})
}
}
type openCodeContentRunner struct {
OpenCode
content string
}
func (o *openCodeContentRunner) Run(model string, models []LaunchModel, args []string) (err error) {
o.content, err = o.runContent(model, models, args...)
return err
}
func TestOpenCodeLaunchRecommendationOutputCeiling(t *testing.T) {
for _, metadataAvailable := range []bool{true, false} {
t.Run(fmt.Sprintf("context metadata available=%t", metadataAvailable), func(t *testing.T) {
setTestHome(t, t.TempDir())
bin := t.TempDir()
writeFakeBinary(t, bin, "opencode")
t.Setenv("PATH", bin)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"local","context_length":131072,"max_output_tokens":1024}]}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"local:latest","details":{"context_length":131072}}]}`)
case "/api/show":
fmt.Fprint(w, `{}`)
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/generate":
fmt.Fprint(w, `{"done":true,"done_reason":"load"}`)
case "/api/ps":
if !metadataAvailable {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
fmt.Fprint(w, `{"models":[{"name":"local:latest","context_length":65536}]}`)
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer server.Close()
t.Setenv("OLLAMA_HOST", server.URL)
client, err := newLauncherClient(defaultLaunchPolicy(false, false))
if err != nil {
t.Fatal(err)
}
o := &openCodeContentRunner{}
if err := client.launchEditorIntegration(t.Context(), "opencode", o, o, nil, IntegrationLaunchRequest{ModelOverride: "local"}); err != nil {
t.Fatal(err)
}
var cfg map[string]any
if err := json.Unmarshal([]byte(o.content), &cfg); err != nil {
t.Fatal(err)
}
entry := cfg["provider"].(map[string]any)["ollama"].(map[string]any)["models"].(map[string]any)["local:latest"].(map[string]any)
if metadataAvailable {
limit := entry["limit"].(map[string]any)
if limit["context"] != float64(65536) || limit["output"] != float64(1024) {
t.Fatalf("lost the known smaller output ceiling: %s", o.content)
}
} else if o.content != o.configContent || entry["limit"] != nil {
t.Fatalf("recommendations altered fallback configuration: %s", o.content)
}
if client.inventory.models[0].ContextLength != 131072 || client.inventory.models[0].MaxOutputTokens != 0 {
t.Fatal("runtime output ceiling mutated the original inventory")
}
})
}
}
+11 -2
View File
@@ -247,11 +247,20 @@ func TestBuildModelEntries(t *testing.T) {
}
})
t.Run("omits context-only limits", func(t *testing.T) {
t.Run("omits context-only limits for local models", func(t *testing.T) {
models := buildModelEntries([]LaunchModel{{Name: "qwen2.5:0.5b", ContextLength: 32768}})
entry, _ := models["qwen2.5:0.5b"].(map[string]any)
if _, ok := entry["limit"]; ok {
t.Fatalf("limit should be omitted when output limit is unknown, got %v", entry["limit"])
t.Fatalf("limit should be omitted for a local model, got %v", entry["limit"])
}
})
t.Run("fills in a default output limit for cloud models with unknown output", func(t *testing.T) {
models := buildModelEntries([]LaunchModel{{Name: "glm-5.3:cloud", Remote: true, ContextLength: 1_048_576}})
entry, _ := models["glm-5.3:cloud"].(map[string]any)
limit, _ := entry["limit"].(map[string]any)
if limit["context"] != 1_048_576 || limit["output"] != openCodeDefaultMaxOutputTokens {
t.Fatalf("limit = %v, want context 1048576 and output %d", limit, openCodeDefaultMaxOutputTokens)
}
})
}
+428 -53
View File
@@ -3,6 +3,7 @@ package launch
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
@@ -12,9 +13,11 @@ import (
"runtime"
"slices"
"strings"
"sync"
"time"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/cmd/config"
"github.com/ollama/ollama/cmd/internal/fileutil"
"github.com/ollama/ollama/envconfig"
)
@@ -31,9 +34,355 @@ const (
func (p *Pi) String() string { return "Pi" }
var npmRegistryBaseURL = "https://registry.npmjs.org"
var (
npmRegistryBaseURL = "https://registry.npmjs.org"
piModelDiscoveryTimeout = 10 * time.Second
)
func (p *Pi) Run(_ string, _ []LaunchModel, args []string) error {
func piHasModelArgs(args []string) bool {
for i := 0; i < len(args); i++ {
switch args[i] {
case "--provider", "--model":
return i+1 < len(args)
case "--mode", "--api-key", "--system-prompt", "--append-system-prompt",
"--session", "--fork", "--session-dir", "--models", "--tools", "-t",
"--thinking", "--export", "--extension", "-e", "--skill", "--prompt-template", "--theme":
// These Pi options consume a value, even when it looks like a flag.
i++
}
}
return false
}
// launchPiIntegration saves one starting model and synchronizes Pi's catalog
// independently of that choice. Only the starting model needs readiness checks.
func (c *launcherClient) launchPiIntegration(ctx context.Context, pi *Pi, saved *config.IntegrationConfig, req IntegrationLaunchRequest) error {
current := primaryModelFromConfig(saved)
if model, err := pi.currentModel(); err != nil {
return err
} else if model != "" {
current = model
}
target := req.ModelOverride
if target == "" && !req.ForceConfigure && !req.ConfigureOnly {
target = current
}
discoveryCtx, cancelDiscovery := context.WithTimeout(ctx, piModelDiscoveryTimeout)
defer cancelDiscovery()
if isCloudModelName(target) && !req.ForceConfigure && !req.ConfigureOnly {
if disabled, _ := cloudStatusDisabled(discoveryCtx, c.apiClient); disabled {
return fmt.Errorf("cloud is disabled; enable cloud to use %s", target)
}
}
// Resolve an explicit model before spending the discovery budget on the catalog.
if req.ModelOverride == "" {
if _, err := c.modelInventory().Load(discoveryCtx); err != nil && !errors.Is(err, context.DeadlineExceeded) {
return err
}
}
if target == "" {
target = current
}
pick := req.ForceConfigure || req.ConfigureOnly || target == ""
picked := false
var models []LaunchModel
for {
if pick {
cancelDiscovery()
var err error
target, err = c.selectSingleModelWithSelectorReady(ctx, "Select model for Pi:", target, DefaultSingleSelector, false, "Pi", "pi")
if err != nil {
return err
}
picked = true
discoveryCtx, cancelDiscovery = context.WithTimeout(ctx, piModelDiscoveryTimeout)
defer cancelDiscovery()
}
remaining := piModelDiscoveryTimeout
model, err := c.piTargetModel(discoveryCtx, target, &remaining)
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
err = nil
}
var status api.StatusError
if errors.As(err, &status) && status.StatusCode == http.StatusNotFound {
if !picked && req.ModelOverride == "" {
pick = true
continue
}
if model.Remote {
return err
}
if err := pullMissingModelWithPolicy(ctx, c.apiClient, target, c.policy.missingModelPolicy()); err != nil {
return err
}
model, err = c.piTargetModel(ctx, target, &remaining)
}
if err != nil {
return err
}
if !piSupportsChat(model) {
if !picked && req.ModelOverride == "" {
pick = true
continue
}
return fmt.Errorf("model %q does not support chat; choose a chat model", target)
}
if target != current {
paymentTarget := target
if model.RemoteModel != "" {
paymentTarget = model.RemoteModel
if !isCloudModelName(paymentTarget) {
paymentTarget = strings.TrimSuffix(paymentTarget, ":latest") + ":cloud"
}
}
if err := c.confirmCloudModelPayment(discoveryCtx, paymentTarget); err != nil {
if errors.Is(err, errModelPaymentDeclined) {
pick = true
continue
}
return err
}
}
cloudRec, localRec := c.agentCapableRecommendations(discoveryCtx)
err = confirmDeprecatedLaunchModel(target, "Pi", "pi", cloudRec, localRec)
if errors.Is(err, errDeprecatedLaunchModelDeclined) {
pick = true
continue
}
if err != nil {
return err
}
if model.Remote {
if err := ensureCloudAuth(ctx, c.apiClient, target); err != nil {
return err
}
if len(model.Capabilities) == 0 {
// Authentication may make previously unavailable metadata readable.
model, err = c.piTargetModel(discoveryCtx, target, &remaining)
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
err = nil
}
if err != nil {
return err
}
}
}
models, err = c.piModelCatalog(discoveryCtx, model, remaining)
if err != nil {
return err
}
if err := ctx.Err(); err != nil {
return err
}
break
}
configured, err := pi.writeConfig(models, discoveryCtx.Err() != nil)
if err != nil {
return fmt.Errorf("setup failed: %w", err)
}
if err := config.SaveIntegration("pi", []string{configured}); err != nil {
return fmt.Errorf("failed to save: %w", err)
}
runtimeModel := ""
if req.ModelOverride != "" || picked {
runtimeModel = configured
}
return launchAfterConfiguration("pi", pi, runtimeModel, models, req)
}
func (p *Pi) currentModel() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
path := filepath.Join(home, ".pi", "agent", "settings.json")
settings, err := fileutil.ReadJSON(path)
if os.IsNotExist(err) {
return "", nil
}
if err != nil {
return "", fmt.Errorf("read Pi config %s: %w", path, err)
}
if provider, _ := settings["defaultProvider"].(string); provider != "ollama" {
return "", nil
}
model, _ := settings["defaultModel"].(string)
return model, nil
}
// piTargetModel retains remote routing metadata even when /show requires sign-in.
func (c *launcherClient) piTargetModel(ctx context.Context, name string, budget *time.Duration) (LaunchModel, error) {
var inventory []LaunchModel
if c.inventory != nil {
inventory = c.inventory.snapshot()
}
model, _ := findLaunchModel(inventory, name)
model.Name = name
model.Remote = model.Remote || isCloudModelName(name)
if model.Remote {
if disabled, _ := cloudStatusDisabled(ctx, c.apiClient); disabled {
return model, fmt.Errorf("cloud is disabled; enable cloud to use %s", name)
}
}
if model.ContextLength > 0 && len(model.Capabilities) > 0 {
return model, nil
}
showCtx, cancel := context.WithTimeout(ctx, *budget)
defer cancel()
started := time.Now()
show, err := c.apiClient.Show(showCtx, &api.ShowRequest{Model: name})
*budget -= time.Since(started)
if err != nil {
if showCtx.Err() != nil {
return model, showCtx.Err()
}
if len(inventory) == 0 {
inventory, _ = c.modelInventory().Load(ctx)
if listed, ok := findLaunchModel(inventory, name); ok {
model = listed
model.Name = name
model.Remote = model.Remote || isCloudModelName(name)
}
}
var status api.StatusError
if model.Remote && !(errors.As(err, &status) && status.StatusCode == http.StatusNotFound) {
return model, nil
}
return model, err
}
if show.RemoteModel != "" {
model.RemoteModel = show.RemoteModel
}
if !model.Remote && (show.RemoteModel != "" || show.RemoteHost != "") {
model.Remote = true
if disabled, _ := cloudStatusDisabled(ctx, c.apiClient); disabled {
return model, fmt.Errorf("cloud is disabled; enable cloud to use %s", name)
}
}
if len(show.Capabilities) > 0 {
model.Capabilities = slices.Clone(show.Capabilities)
}
if model.ContextLength <= 0 {
model.ContextLength, _ = modelInfoContextLength(show.ModelInfo)
}
return model, nil
}
func piSupportsChat(model LaunchModel) bool {
return len(model.Capabilities) == 0 || model.HasCapability("completion") || model.HasCapability("tools")
}
func (c *launcherClient) piSelectableModels(ctx context.Context, items []ModelItem) []ModelItem {
inventory, _ := c.modelInventory().Load(ctx)
cloudDisabled, _ := cloudStatusDisabled(ctx, c.apiClient)
return slices.DeleteFunc(items, func(item ModelItem) bool {
model, _ := findLaunchModel(inventory, item.Name)
return !piSupportsChat(LaunchModel{Capabilities: item.Capabilities}) || (cloudDisabled && (model.Remote || isCloudModelName(item.Name)))
})
}
func (c *launcherClient) piModelCatalog(ctx context.Context, primary LaunchModel, budget time.Duration) ([]LaunchModel, error) {
inventory, err := c.modelInventory().Load(ctx)
if errors.Is(err, context.DeadlineExceeded) {
return []LaunchModel{primary}, nil
}
if err != nil {
return nil, err
}
cloudDisabled, _ := cloudStatusDisabled(ctx, c.apiClient)
if model, ok := findLaunchModel(inventory, primary.Name); ok {
if primary.ContextLength <= 0 {
primary.ContextLength = model.ContextLength
}
if len(primary.Capabilities) == 0 {
primary.Capabilities = model.Capabilities
}
primary.Remote = primary.Remote || model.Remote
}
primary.Remote = primary.Remote || isCloudModelName(primary.Name)
models := []LaunchModel{primary}
seen := map[string]bool{launchModelRecommendationKey(primary.Name): true}
for _, model := range inventory {
key := launchModelRecommendationKey(model.Name)
if seen[key] || isDeprecatedLaunchModel(model.Name) || (cloudDisabled && (model.Remote || isCloudModelName(model.Name))) {
continue
}
seen[key] = true
models = append(models, model)
}
for _, rec := range c.recommendations(ctx) {
key := launchModelRecommendationKey(rec.Name)
if seen[key] || cloudDisabled || !isCloudModelName(rec.Name) || isDeprecatedLaunchModel(rec.Name) {
continue
}
seen[key] = true
models = append(models, LaunchModel{Name: rec.Name, Remote: true, ContextLength: rec.Details.ContextLength, MaxOutputTokens: rec.MaxOutputTokens})
}
// Discovery is best effort: some models may be missing when the timeout expires.
// TODO: Use a more narrowly scoped model metadata API instead of /show here.
showCtx, cancel := context.WithTimeout(ctx, budget)
defer cancel()
for i := range models {
models[i] = models[i].WithCloudLimits()
}
var wg sync.WaitGroup
jobs := make(chan int)
for range min(4, len(models)) {
wg.Go(func() {
for i := range jobs {
model := &models[i]
if model.ContextLength > 0 && len(model.Capabilities) > 0 {
continue
}
show, err := c.apiClient.Show(showCtx, &api.ShowRequest{Model: model.Name})
if err != nil {
var status api.StatusError
if errors.As(err, &status) && status.StatusCode == http.StatusNotFound {
model.Name = ""
}
continue
}
if model.ContextLength <= 0 {
model.ContextLength, _ = modelInfoContextLength(show.ModelInfo)
}
if len(model.Capabilities) == 0 {
model.Capabilities = slices.Clone(show.Capabilities)
}
model.Remote = model.Remote || show.RemoteModel != "" || show.RemoteHost != ""
}
})
}
queue:
for i := 1; i < len(models); i++ {
select {
case jobs <- i:
case <-showCtx.Done():
break queue
}
}
close(jobs)
wg.Wait()
if err := ctx.Err(); err != nil && !errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
if !piSupportsChat(models[0]) {
return nil, fmt.Errorf("model %q does not support chat; choose a chat model", primary.Name)
}
if cloudDisabled && models[0].Remote {
return nil, fmt.Errorf("cloud is disabled; enable cloud to use %s", primary.Name)
}
if models[0].Name == "" {
return nil, fmt.Errorf("model %q is no longer available", primary.Name)
}
models = slices.DeleteFunc(models, func(model LaunchModel) bool {
return model.Name == "" || !piSupportsChat(model) || (cloudDisabled && model.Remote)
})
return models, nil
}
func (p *Pi) Run(model string, _ []LaunchModel, args []string) error {
fmt.Fprintf(os.Stderr, "\n%sPreparing Pi...%s\n", ansiGray, ansiReset)
if err := ensureNpmInstalled(); err != nil {
return err
@@ -49,6 +398,9 @@ func (p *Pi) Run(_ string, _ []LaunchModel, args []string) error {
fmt.Fprintf(os.Stderr, "\n%sLaunching Pi...%s\n\n", ansiGray, ansiReset)
if model != "" && !piHasModelArgs(args) {
args = append([]string{"--provider", "ollama", "--model", model}, args...)
}
cmd := exec.Command(bin, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
@@ -535,24 +887,38 @@ func piBaseURL() string {
}
func (p *Pi) Edit(models []LaunchModel) error {
_, err := p.writeConfig(models, false)
return err
}
func (p *Pi) writeConfig(models []LaunchModel, preserveCatalog bool) (string, error) {
if len(models) == 0 {
return nil
return "", nil
}
primary := models[0].Name
home, err := os.UserHomeDir()
if err != nil {
return err
return "", err
}
configPath := filepath.Join(home, ".pi", "agent", "models.json")
settingsPath := filepath.Join(home, ".pi", "agent", "settings.json")
configs := make([]map[string]any, 2)
for i, path := range []string{configPath, settingsPath} {
data, err := fileutil.ReadJSON(path)
if err != nil && !os.IsNotExist(err) {
return "", fmt.Errorf("read Pi config %s: %w", path, err)
}
if data == nil {
data = make(map[string]any)
}
configs[i] = data
}
if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil {
return err
}
config := make(map[string]any)
if data, err := os.ReadFile(configPath); err == nil {
_ = json.Unmarshal(data, &config)
return "", err
}
config, settings := configs[0], configs[1]
providers, ok := config["providers"].(map[string]any)
if !ok {
@@ -578,44 +944,55 @@ func (p *Pi) Edit(models []LaunchModel) error {
existingModels = make([]any, 0)
}
// Build set of selected models to track which need to be added
selectedSet := make(map[string]bool, len(models))
for _, m := range models {
selectedSet[m.Name] = true
}
// Build new models list:
// 1. Keep user-managed models (no _launch marker) - untouched
// 2. Keep ollama-managed models (_launch marker) that are still selected,
// except stale cloud entries that should be rebuilt below
// 3. Add new ollama-managed models
// Only launch-owned entries are replaced by the current catalog.
var newModels []any
for _, m := range existingModels {
if modelObj, ok := m.(map[string]any); ok {
if id, ok := modelObj["id"].(string); ok {
// User-managed model (no _launch marker) - always preserve
if !isPiOllamaModel(modelObj) {
newModels = append(newModels, m)
} else if selectedSet[id] {
// Rebuild stale managed cloud entries so createConfig refreshes
// the whole entry instead of patching it in place.
if !hasContextWindow(modelObj) {
if _, ok := lookupCloudModelLimit(id); ok {
continue
}
}
newModels = append(newModels, m)
selectedSet[id] = false
}
manual := make(map[string]string)
managed := make(map[string]map[string]any)
found := make(map[string]bool, len(models))
for _, model := range models {
found[launchModelRecommendationKey(model.Name)] = true
}
for _, entry := range existingModels {
model, _ := entry.(map[string]any)
id, _ := model["id"].(string)
if !isPiOllamaModel(model) {
newModels = append(newModels, entry)
key := launchModelRecommendationKey(id)
if manual[key] == "" || id == models[0].Name {
manual[key] = id
}
} else {
key := launchModelRecommendationKey(id)
managed[key] = model
if preserveCatalog && !found[key] {
newModels = append(newModels, entry)
}
}
}
// Add newly selected models that weren't already in the list
for _, model := range models {
if selectedSet[model.Name] {
newModels = append(newModels, createConfig(model))
key := launchModelRecommendationKey(model.Name)
if id := manual[key]; id != "" {
if key == launchModelRecommendationKey(models[0].Name) {
primary = id
}
continue
}
entry := createConfig(model)
// A failed metadata lookup must not erase previously known limits or
// capabilities for a model that remains in the inventory.
if old := managed[key]; old != nil {
if model.ContextLength <= 0 && hasContextWindow(old) {
entry["contextWindow"] = old["contextWindow"]
}
if len(model.Capabilities) == 0 {
for _, key := range []string{"input", "reasoning"} {
if value, ok := old[key]; ok {
entry[key] = value
}
}
}
}
newModels = append(newModels, entry)
}
ollama["models"] = newModels
@@ -624,27 +1001,25 @@ func (p *Pi) Edit(models []LaunchModel) error {
configData, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
return "", err
}
if err := fileutil.WriteWithBackup(configPath, configData, "pi"); err != nil {
return err
return "", err
}
// Update settings.json with default provider and model
settingsPath := filepath.Join(home, ".pi", "agent", "settings.json")
settings := make(map[string]any)
if data, err := os.ReadFile(settingsPath); err == nil {
_ = json.Unmarshal(data, &settings)
}
// The first catalog entry is the separately selected starting model.
settings["defaultProvider"] = "ollama"
settings["defaultModel"] = models[0].Name
settings["defaultModel"] = primary
settingsData, err := json.MarshalIndent(settings, "", " ")
if err != nil {
return err
return "", err
}
return fileutil.WriteWithBackup(settingsPath, settingsData, "pi")
if err := fileutil.WriteWithBackup(settingsPath, settingsData, "pi"); err != nil {
return "", err
}
return primary, nil
}
func (p *Pi) Models() []string {
+720
View File
@@ -0,0 +1,720 @@
package launch
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/ollama/ollama/cmd/config"
"github.com/ollama/ollama/cmd/internal/fileutil"
modelpkg "github.com/ollama/ollama/types/model"
)
func TestPiPrimaryMetadataBudget(t *testing.T) {
for _, complete := range []bool{false, true} {
t.Run(fmt.Sprint(complete), func(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
withLauncherHooks(t)
oldTimeout := piModelDiscoveryTimeout
piModelDiscoveryTimeout = 50 * time.Millisecond
t.Cleanup(func() { piModelDiscoveryTimeout = oldTimeout })
if err := config.SaveIntegration("pi", []string{"primary"}); err != nil {
t.Fatal(err)
}
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
original := `{"providers":{"ollama":{"models":[{"id":"primary","_launch":true,"contextWindow":8192}]}}}`
path := filepath.Join(dir, "models.json")
if err := os.WriteFile(path, []byte(original), 0o644); err != nil {
t.Fatal(err)
}
DefaultSingleSelector = func(string, []SelectionItem, string) (string, error) { return "primary", nil }
DefaultConfirmPrompt = func(string, ConfirmOptions) (bool, error) { return false, nil }
stop := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"primary"}]}`)
case "/api/tags":
if complete {
fmt.Fprint(w, `{"models":[{"name":"primary","details":{"context_length":8192},"capabilities":["completion","tools"]}]}`)
} else {
fmt.Fprint(w, `{"models":[{"name":"primary"}]}`)
}
case "/api/show":
select {
case <-r.Context().Done():
case <-stop:
}
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
defer close(stop)
t.Setenv("OLLAMA_HOST", srv.URL)
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
finished := make(chan error, 1)
go func() {
saved, _ := config.LoadIntegration("pi")
finished <- c.launchPiIntegration(ctx, &Pi{}, saved, IntegrationLaunchRequest{ConfigureOnly: true})
}()
select {
case err := <-finished:
if err != nil {
t.Fatalf("partial discovery should succeed: %v", err)
}
case <-time.After(time.Second):
cancel()
<-finished
t.Fatal("primary /show exceeded the metadata budget")
}
if !complete {
data, err := fileutil.ReadJSON(path)
if err != nil {
t.Fatal(err)
}
models := data["providers"].(map[string]any)["ollama"].(map[string]any)["models"].([]any)
if len(models) != 1 || models[0].(map[string]any)["contextWindow"] != float64(8192) {
t.Fatalf("known metadata changed on timeout: %v", models)
}
}
})
}
}
func TestPiCatalogSync(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
withLauncherHooks(t)
withInteractiveSession(t, true)
if err := config.SaveIntegration("pi", []string{"primary", "gone", "unused"}); err != nil {
t.Fatal(err)
}
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
for name, content := range map[string]string{
"models.json": `{"providers":{"ollama":{"models":[{"id":"gone","_launch":true},{"id":"manual","contextWindow":8192},{"id":"secondary","contextWindow":2048,"custom":true}]},"other":{"models":[{"id":"keep"}]}}}`,
"settings.json": `{"defaultProvider":"ollama","defaultModel":"primary","editorPaddingX":3}`,
"history.jsonl": "preserve history exactly\n",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
DefaultSingleSelector = func(string, []SelectionItem, string) (string, error) {
return "primary", nil
}
DefaultConfirmPrompt = func(prompt string, _ ConfirmOptions) (bool, error) {
if prompt != "Launch Pi now?" {
t.Errorf("unexpected confirmation: %s", prompt)
}
return false, nil
}
var shown []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"not-downloaded"}]}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"primary:latest","details":{"context_length":65536},"capabilities":["completion","tools"]},{"name":"secondary","details":{"context_length":32768},"capabilities":["completion","vision"]},{"name":"embeddings","details":{"context_length":8192},"capabilities":["embedding"]},{"name":"legacy-remote"}]}`)
case "/api/show":
var req apiShowRequest
_ = json.NewDecoder(r.Body).Decode(&req)
shown = append(shown, req.Model)
if req.Model == "legacy-remote" {
fmt.Fprint(w, `{"remote_model":"hidden","capabilities":["completion","tools"],"model_info":{"test.context_length":8192}}`)
return
}
if req.Model != "primary" {
t.Errorf("unexpected lookup for a catalog model: %s", req.Model)
}
fmt.Fprint(w, `{}`)
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
saved, _ := config.LoadIntegration("pi")
if err := c.launchPiIntegration(t.Context(), &Pi{}, saved, IntegrationLaunchRequest{ConfigureOnly: true, ModelOverride: "remote:cloud"}); err != nil {
t.Fatal(err)
}
if len(shown) == 0 || slices.ContainsFunc(shown, func(name string) bool { return name != "primary" && name != "legacy-remote" }) {
t.Fatalf("unexpected metadata lookups: %v", shown)
}
saved, _ = config.LoadIntegration("pi")
if !slices.Equal(saved.Models, []string{"primary"}) {
t.Fatalf("saved models = %v", saved.Models)
}
models, _ := fileutil.ReadJSON(filepath.Join(dir, "models.json"))
providers := models["providers"].(map[string]any)
entries := providers["ollama"].(map[string]any)["models"].([]any)
if len(entries) != 3 {
t.Fatalf("catalog = %v; want primary and the two manual entries", entries)
}
byID := make(map[string]map[string]any)
for _, entry := range entries {
model := entry.(map[string]any)
byID[model["id"].(string)] = model
}
if byID["primary"]["contextWindow"] != float64(65536) || byID["secondary"]["contextWindow"] != float64(2048) || byID["secondary"]["custom"] != true {
t.Fatalf("unexpected metadata/manual override: %v", entries)
}
if providers["other"].(map[string]any)["models"].([]any)[0].(map[string]any)["id"] != "keep" {
t.Fatal("unrelated provider changed")
}
settings, _ := fileutil.ReadJSON(filepath.Join(dir, "settings.json"))
if settings["defaultModel"] != "primary" || settings["editorPaddingX"] != float64(3) {
t.Fatalf("unexpected settings: %v", settings)
}
history, _ := os.ReadFile(filepath.Join(dir, "history.jsonl"))
if string(history) != "preserve history exactly\n" {
t.Fatal("history changed")
}
}
func TestPiLauncherStateUsesOnlyStartingModel(t *testing.T) {
for _, tc := range []struct {
primary string
cloudDisabled bool
usable bool
}{
{primary: "primary", usable: true},
{primary: "missing"},
{primary: "embeddings"},
{primary: "remote:cloud", cloudDisabled: true},
{primary: "remote:cloud", usable: true},
{primary: "alias", cloudDisabled: true},
{primary: "alias", usable: true},
} {
t.Run(fmt.Sprintf("%s/cloud-disabled=%t", tc.primary, tc.cloudDisabled), func(t *testing.T) {
setLaunchTestHome(t, t.TempDir())
if err := config.SaveIntegration("pi", []string{tc.primary, "secondary"}); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
fmt.Fprintf(w, `{"cloud":{"disabled":%t}}`, tc.cloudDisabled)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"primary","capabilities":["completion","tools"]},{"name":"secondary","capabilities":["completion","tools"]},{"name":"embeddings","capabilities":["embedding"]},{"name":"alias","remote_model":"remote","capabilities":["completion","tools"]}]}`)
case "/api/show":
var req apiShowRequest
_ = json.NewDecoder(r.Body).Decode(&req)
switch req.Model {
case "missing":
http.Error(w, `{"error":"missing"}`, http.StatusNotFound)
case "embeddings":
fmt.Fprint(w, `{"capabilities":["embedding"]}`)
case "alias", "remote:cloud":
fmt.Fprint(w, `{"remote_model":"remote","capabilities":["completion","tools"]}`)
default:
fmt.Fprint(w, `{"capabilities":["completion","tools"]}`)
}
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
current, usable, err := c.launcherModelState(t.Context(), "pi", true)
if err != nil || current != tc.primary || usable != tc.usable {
t.Fatalf("launcher state = %s/%t, %v; want %s/%t", current, usable, err, tc.primary, tc.usable)
}
})
}
}
func TestPiRemoteAliasAuthAndPayment(t *testing.T) {
for _, payment := range []bool{false, true} {
t.Run(fmt.Sprint(payment), func(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
withLauncherHooks(t)
if err := config.SaveIntegration("pi", []string{"primary"}); err != nil {
t.Fatal(err)
}
requestedAuth, requestedPayment := false, false
DefaultSignIn = func(model, _ string) (string, error) {
requestedAuth = true
if model != "alias" {
t.Errorf("sign-in target = %s", model)
}
return "", ErrCancelled
}
DefaultConfirmPrompt = func(prompt string, _ ConfirmOptions) (bool, error) {
requestedPayment = true
if !strings.Contains(prompt, "paid:cloud") || !strings.Contains(prompt, "usage credits") {
t.Errorf("unexpected payment prompt: %s", prompt)
}
return false, nil
}
DefaultSingleSelector = func(string, []SelectionItem, string) (string, error) {
return "", ErrCancelled
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":false}}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"primary","capabilities":["completion","tools"]},{"name":"alias","remote_model":"paid","capabilities":["completion","tools"]}]}`)
case "/api/show":
fmt.Fprint(w, `{"remote_model":"paid","capabilities":["completion","tools"]}`)
case "/api/experimental/model-recommendations":
if payment {
fmt.Fprint(w, `{"recommendations":[{"model":"paid:cloud","context_length":65536,"max_output_tokens":8192,"required_plan":"pro"}]}`)
} else {
fmt.Fprint(w, `{"recommendations":[{"model":"primary"}]}`)
}
case "/api/me":
if payment {
fmt.Fprint(w, `{"name":"fixture","plan":"free"}`)
} else {
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, `{"error":"unauthorized","signin_url":"https://example.com/signin"}`)
}
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
saved, _ := config.LoadIntegration("pi")
err = c.launchPiIntegration(t.Context(), &Pi{}, saved, IntegrationLaunchRequest{ModelOverride: "alias"})
if !errors.Is(err, ErrCancelled) || requestedPayment != payment || requestedAuth == payment {
t.Fatalf("auth=%v, payment=%v, error=%v", requestedAuth, requestedPayment, err)
}
saved, _ = config.LoadIntegration("pi")
if !slices.Equal(saved.Models, []string{"primary"}) {
t.Fatalf("saved model changed after cancellation: %v", saved.Models)
}
if _, err := os.Stat(filepath.Join(home, ".pi")); !os.IsNotExist(err) {
t.Fatalf("Pi config written after cancellation: %v", err)
}
})
}
}
func TestPiCatalogInventoryErrorPreservesConfig(t *testing.T) {
for _, corrupt := range []bool{false, true} {
t.Run(fmt.Sprint(corrupt), func(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
withLauncherHooks(t)
if err := config.SaveIntegration("pi", []string{"primary", "secondary"}); err != nil {
t.Fatal(err)
}
if corrupt {
if err := os.WriteFile(filepath.Join(home, ".ollama", "config.json"), []byte("{invalid"), 0o644); err != nil {
t.Fatal(err)
}
}
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
original := map[string]string{
"models.json": `{"providers":{"ollama":{"models":[{"id":"primary","_launch":true},{"id":"secondary","_launch":true}]}}}`,
"settings.json": `{"defaultProvider":"ollama","defaultModel":"secondary","theme":"dark"}`,
}
for name, content := range original {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
selected := false
DefaultSingleSelector = func(string, []SelectionItem, string) (string, error) {
selected = true
return "primary", nil
}
DefaultConfirmPrompt = func(string, ConfirmOptions) (bool, error) { return false, nil }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !corrupt {
http.Error(w, `{"error":"unavailable"}`, http.StatusServiceUnavailable)
return
}
switch r.URL.Path {
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"primary"}]}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"primary","details":{"context_length":8192},"capabilities":["completion","tools"]}]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
if err := LaunchIntegration(t.Context(), IntegrationLaunchRequest{Name: "pi", ConfigureOnly: true}); err == nil {
t.Fatal("expected config or inventory error")
}
for name, want := range original {
data, err := os.ReadFile(filepath.Join(dir, name))
if err != nil || string(data) != want {
t.Errorf("%s changed after failed setup: %s, %v", name, data, err)
}
}
if corrupt {
data, err := os.ReadFile(filepath.Join(home, ".ollama", "config.json"))
if err != nil || string(data) != "{invalid" || selected {
t.Fatalf("invalid config changed or picker opened: %s, %v, selected=%t", data, err, selected)
}
} else {
saved, _ := config.LoadIntegration("pi")
if !slices.Equal(saved.Models, []string{"primary", "secondary"}) {
t.Fatalf("saved models changed: %v", saved.Models)
}
}
})
}
}
func TestPiShowBudgetDoesNotChargeStatus(t *testing.T) {
setLaunchTestHome(t, t.TempDir())
withLauncherHooks(t)
oldTimeout := modelShowTimeout
modelShowTimeout = 40 * time.Millisecond
t.Cleanup(func() { modelShowTimeout = oldTimeout })
if err := config.SaveIntegration("pi", []string{"alias"}); err != nil {
t.Fatal(err)
}
DefaultSingleSelector = func(string, []SelectionItem, string) (string, error) { return "alias", nil }
DefaultConfirmPrompt = func(string, ConfirmOptions) (bool, error) { return false, nil }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
time.Sleep(100 * time.Millisecond)
fmt.Fprint(w, `{"cloud":{"disabled":false}}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"alias","remote_model":"remote","capabilities":["completion","tools"]}]}`)
case "/api/show":
fmt.Fprint(w, `{"remote_model":"remote","capabilities":["completion","tools"],"model_info":{"test.context_length":8192}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"alias"}]}`)
case "/api/me":
fmt.Fprint(w, `{"name":"fixture"}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
current, usable, stateErr := c.launcherModelState(ctx, "pi", true)
if stateErr != nil || current != "alias" || !usable {
t.Errorf("status latency made the root primary unusable: %s/%t, %v", current, usable, stateErr)
}
if err := LaunchIntegration(ctx, IntegrationLaunchRequest{Name: "pi", ConfigureOnly: true}); err != nil {
t.Fatalf("status latency was charged to /show: %v", err)
}
}
func TestPiCatalogMetadataFallback(t *testing.T) {
for _, status := range []int{http.StatusNotFound, http.StatusUnauthorized, http.StatusServiceUnavailable} {
t.Run(fmt.Sprint(status), func(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
original := `{"providers":{"ollama":{"models":[{"id":"secondary:cloud","_launch":true,"contextWindow":8192,"input":["text","image"],"reasoning":true}]}}}`
if err := os.WriteFile(filepath.Join(dir, "models.json"), []byte(original), 0o644); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":false}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"primary"}]}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"primary","details":{"context_length":32768},"capabilities":["completion","tools"]},{"name":"secondary:cloud","remote_model":"secondary"},{"name":"legacy"}]}`)
case "/api/show":
var req apiShowRequest
_ = json.NewDecoder(r.Body).Decode(&req)
if req.Model == "legacy" {
fmt.Fprint(w, `{"capabilities":["completion","tools","vision"],"model_info":{"test.context_length":16384}}`)
} else {
http.Error(w, `{"error":"fixture"}`, status)
}
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
models, err := c.piModelCatalog(t.Context(), LaunchModel{Name: "primary"}, modelShowTimeout)
if err != nil {
t.Fatal(err)
}
if err := (&Pi{}).Edit(models); err != nil {
t.Fatal(err)
}
cfg, _ := fileutil.ReadJSON(filepath.Join(dir, "models.json"))
entries := cfg["providers"].(map[string]any)["ollama"].(map[string]any)["models"].([]any)
byID := make(map[string]map[string]any)
for _, raw := range entries {
entry := raw.(map[string]any)
byID[entry["id"].(string)] = entry
}
if entry := byID["legacy"]; entry["contextWindow"] != float64(16384) || !slices.Equal([]any{"text", "image"}, entry["input"].([]any)) {
t.Fatalf("legacy metadata fallback = %v", entry)
}
entry := byID["secondary:cloud"]
if status == http.StatusNotFound {
if entry != nil {
t.Fatalf("confirmed missing model remains: %v", entry)
}
} else if entry["contextWindow"] != float64(8192) || entry["reasoning"] != true || !slices.Equal([]any{"text", "image"}, entry["input"].([]any)) {
t.Fatalf("known metadata lost after %d: %v", status, entry)
}
})
}
}
func TestPiEditPreservesInvalidConfig(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
models := `{"providers":{"ollama":{"models":[{"id":"missing","_launch":true}]}}}`
if err := os.WriteFile(filepath.Join(dir, "models.json"), []byte(models), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "settings.json"), []byte("{invalid"), 0o644); err != nil {
t.Fatal(err)
}
if err := (&Pi{}).Edit([]LaunchModel{{Name: "chosen"}}); err == nil {
t.Fatal("expected invalid settings error")
}
data, err := os.ReadFile(filepath.Join(dir, "models.json"))
if err != nil || string(data) != models {
t.Fatalf("models changed before invalid settings were detected: %s, %v", data, err)
}
}
// A selected primary that was already resolved must not be looked up again by
// catalog enrichment. The second response deliberately changes to 404 to make
// the duplicate RPC's user-visible consequence deterministic.
func TestPiResolvedPrimaryIsNotShownTwice(t *testing.T) {
setLaunchTestHome(t, t.TempDir())
var showCalls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"primary"}]}`)
case "/api/show":
if showCalls.Add(1) == 1 {
fmt.Fprint(w, `{"capabilities":["completion"]}`)
return
}
http.Error(w, `{"error":"gone"}`, http.StatusNotFound)
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"primary"}]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
remaining := modelShowTimeout
primary, err := c.piTargetModel(t.Context(), "primary", &remaining)
if err != nil || !primary.HasCapability(modelpkg.CapabilityCompletion) {
t.Fatalf("target resolution = %+v, %v", primary, err)
}
models, err := c.piModelCatalog(t.Context(), primary, remaining)
if err != nil {
t.Fatalf("resolved primary was invalidated by catalog enrichment: %v", err)
}
if showCalls.Load() != 1 || len(models) == 0 || models[0].Name != "primary" {
t.Fatalf("show calls=%d models=%v", showCalls.Load(), models)
}
}
// launchModelMatches and catalog de-duplication treat id and id:latest as the
// same model. Metadata preservation must use the same identity rule.
func TestPiMetadataFallbackNormalizesLatest(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "models.json"), []byte(`{"providers":{"ollama":{"models":[{"id":"secondary","_launch":true,"contextWindow":8192,"input":["text","image"],"reasoning":true}]}}}`), 0o644); err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"primary","details":{"context_length":32768},"capabilities":["completion"]},{"name":"secondary:latest"}]}`)
case "/api/show":
var req apiShowRequest
_ = json.NewDecoder(r.Body).Decode(&req)
if req.Model == "secondary:latest" {
http.Error(w, `{"error":"temporary"}`, http.StatusServiceUnavailable)
return
}
http.NotFound(w, r)
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"primary"}]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
models, err := c.piModelCatalog(t.Context(), LaunchModel{Name: "primary", ContextLength: 32768, Capabilities: []modelpkg.Capability{modelpkg.CapabilityCompletion}}, modelShowTimeout)
if err != nil {
t.Fatal(err)
}
if err := (&Pi{}).Edit(models); err != nil {
t.Fatal(err)
}
cfg, err := fileutil.ReadJSON(filepath.Join(dir, "models.json"))
if err != nil {
t.Fatal(err)
}
entries := cfg["providers"].(map[string]any)["ollama"].(map[string]any)["models"].([]any)
var secondary map[string]any
for _, raw := range entries {
entry := raw.(map[string]any)
if strings.TrimSuffix(entry["id"].(string), ":latest") == "secondary" {
secondary = entry
}
}
if secondary == nil || secondary["contextWindow"] != float64(8192) || secondary["reasoning"] != true {
t.Fatalf("known fields were not preserved across :latest identity: %v", secondary)
}
input, _ := secondary["input"].([]any)
if len(input) != 2 || input[1] != "image" {
t.Fatalf("known input capability was not preserved: %v", secondary)
}
}
// Both gpt-oss:20b:cloud and gpt-oss:20b-cloud are supported spellings for
// the same cloud source. Required-plan guidance must not depend on spelling.
func TestPiTaggedAliasRetainsPlanGuidance(t *testing.T) {
withLauncherHooks(t)
prompted := false
DefaultConfirmPrompt = func(prompt string, _ ConfirmOptions) (bool, error) {
prompted = true
if !strings.Contains(prompt, "usage credits") {
t.Fatalf("unexpected prompt: %s", prompt)
}
return false, nil
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"gpt-oss:20b-cloud","context_length":131072,"max_output_tokens":131072,"required_plan":"pro"}]}`)
case "/api/me":
fmt.Fprint(w, `{"name":"fixture","plan":"free"}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
c, err := newLauncherClient(defaultLaunchPolicy(true, false))
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"gpt-oss:20b:cloud", "gpt-oss:20b-cloud"} {
prompted = false
err = c.confirmCloudModelPayment(t.Context(), name)
if !errors.Is(err, errModelPaymentDeclined) || !prompted {
t.Fatalf("equivalent tagged cloud name skipped plan guidance: name=%s prompted=%t err=%v", name, prompted, err)
}
}
}
func TestPiManualEquivalentPrimaryKeepsItsID(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "models.json"), []byte(`{"providers":{"ollama":{"models":[{"id":"primary:latest","contextWindow":4096,"custom":true}]}}}`), 0o644); err != nil {
t.Fatal(err)
}
primary, err := (&Pi{}).writeConfig([]LaunchModel{{Name: "primary", ContextLength: 32768}}, false)
if err != nil || primary != "primary:latest" {
t.Fatalf("configured primary = %q, %v", primary, err)
}
settings, _ := fileutil.ReadJSON(filepath.Join(dir, "settings.json"))
if settings["defaultModel"] != primary {
t.Fatalf("Pi default does not name the preserved entry: %v", settings)
}
cfg, _ := fileutil.ReadJSON(filepath.Join(dir, "models.json"))
entries := cfg["providers"].(map[string]any)["ollama"].(map[string]any)["models"].([]any)
if len(entries) != 1 || entries[0].(map[string]any)["custom"] != true {
t.Fatalf("manual equivalent was duplicated or rewritten: %v", entries)
}
}
+414
View File
@@ -0,0 +1,414 @@
package launch
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"time"
"github.com/ollama/ollama/cmd/config"
"github.com/spf13/cobra"
)
func TestLaunchCmdPiPickerPolicy(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a POSIX shell test binary")
}
for _, tc := range []struct {
name string
saved []string
args []string
wantPicker int
wantModel string
wantError string
wantPiArgs []string
runtimeOverride bool
corruptConfig bool
}{
{name: "available saved model", saved: []string{"keep-model"}, wantModel: "keep-model"},
{name: "legacy selection migrates to one starting model", saved: []string{"keep-model", "remote:cloud"}, wantModel: "keep-model"},
{name: "first setup", wantPicker: 1, wantModel: "chosen"},
{name: "missing saved default", saved: []string{"missing", "keep-model"}, wantPicker: 1, wantModel: "chosen"},
{name: "explicit configuration", saved: []string{"keep-model"}, args: []string{"--config"}, wantPicker: 1, wantModel: "chosen"},
{name: "disabled saved cloud default", saved: []string{"remote:cloud", "keep-model"}, wantError: "cloud is disabled"},
{name: "disabled explicit cloud override", saved: []string{"keep-model"}, args: []string{"--model", "remote:cloud"}, wantError: "cloud is disabled"},
{name: "configure replaces disabled cloud default", saved: []string{"remote:cloud", "keep-model"}, args: []string{"--config"}, wantPicker: 1, wantModel: "chosen"},
{name: "configure replaces disabled explicit cloud target", saved: []string{"keep-model"}, args: []string{"--config", "--model", "remote:cloud"}, wantPicker: 1, wantModel: "chosen"},
{name: "saved embedding model requires a chat model", saved: []string{"embeddings", "keep-model"}, wantPicker: 1, wantModel: "chosen"},
{name: "short model flag", saved: []string{"keep-model"}, args: []string{"-m", "chosen"}, wantModel: "chosen", wantPiArgs: []string{"--provider", "ollama", "--model", "chosen"}},
{name: "explicit embedding model is rejected", saved: []string{"keep-model"}, args: []string{"--model", "embeddings"}, wantError: "does not support chat"},
{name: "legacy saved embedding model requires a chat model", saved: []string{"legacy-embedding"}, wantPicker: 1, wantModel: "chosen"},
{name: "disabled saved cloud alias", saved: []string{"remote-alias", "keep-model"}, wantError: "cloud is disabled"},
{name: "disabled explicit cloud alias", saved: []string{"keep-model"}, args: []string{"--model", "remote-alias"}, wantError: "cloud is disabled"},
{name: "cloud alias identified by show", saved: []string{"keep-model"}, args: []string{"--model", "hidden-alias"}, wantError: "cloud is disabled"},
{name: "forwarded qualified model", runtimeOverride: true, saved: []string{"remote:cloud", "keep-model"}, args: []string{"--", "--model", "fixture-user/user-choice"}, wantPiArgs: []string{"--model", "fixture-user/user-choice"}},
{name: "native override ignores unused malformed launch config", runtimeOverride: true, corruptConfig: true, saved: []string{"keep-model"}, args: []string{"--", "--model", "fixture-user/user-choice"}, wantPiArgs: []string{"--model", "fixture-user/user-choice"}},
{name: "forwarded provider and model", runtimeOverride: true, saved: []string{"remote:cloud", "keep-model"}, args: []string{"--", "--provider", "fixture-user", "--model", "user-choice"}, wantPiArgs: []string{"--provider", "fixture-user", "--model", "user-choice"}},
{name: "forwarded model replaces explicit cloud target", runtimeOverride: true, saved: []string{"keep-model"}, args: []string{"--model", "remote:cloud", "--", "--model", "fixture-user/user-choice"}, wantPiArgs: []string{"--model", "fixture-user/user-choice"}},
{name: "model flag inside a prompt is not an override", wantModel: "keep-model", saved: []string{"keep-model"}, args: []string{"--", "--system-prompt", "--model", "probe"}, wantPiArgs: []string{"--system-prompt", "--model", "probe"}},
} {
t.Run(tc.name, func(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
withLauncherHooks(t)
withInteractiveSession(t, true)
if tc.saved != nil {
if err := config.SaveIntegration("pi", tc.saved); err != nil {
t.Fatal(err)
}
}
if tc.corruptConfig {
if err := os.WriteFile(filepath.Join(home, ".ollama", "config.json"), []byte("{invalid"), 0o644); err != nil {
t.Fatal(err)
}
}
binDir := t.TempDir()
t.Setenv("PATH", binDir)
argsPath := filepath.Join(home, "pi-args")
for name, data := range map[string]string{
"pi": fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$@\" > %q\n", argsPath),
"npm": "#!/bin/sh\nexit 1\n",
"package.json": `{"name":"@earendil-works/pi-coding-agent"}`,
} {
if err := os.WriteFile(filepath.Join(binDir, name), []byte(data), 0o755); err != nil {
t.Fatal(err)
}
}
pickerCalls := 0
DefaultSingleSelector = func(_ string, items []SelectionItem, _ string) (string, error) {
pickerCalls++
for _, item := range items {
if item.Name == "embeddings" || item.Name == "remote-alias" {
t.Errorf("unusable model appears in Pi picker: %s", item.Name)
}
}
return "chosen", nil
}
DefaultMultiSelector = func(_ string, _ []SelectionItem, _ []string) ([]string, error) {
t.Fatal("Pi must select only its starting model")
return nil, ErrCancelled
}
DefaultConfirmPrompt = func(prompt string, _ ConfirmOptions) (bool, error) {
if prompt != "Launch Pi now?" || len(tc.args) == 0 {
t.Errorf("unexpected confirmation: %s", prompt)
}
return true, nil
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"chosen"}]}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"chosen","details":{"context_length":65536},"capabilities":["completion","tools"]},{"name":"keep-model","details":{"context_length":32768},"capabilities":["completion","tools","vision"]},{"name":"embeddings","details":{"context_length":8192},"capabilities":["embedding"]},{"name":"remote-alias","remote_model":"remote","details":{"context_length":32768},"capabilities":["completion","tools"]}]}`)
case "/api/show":
var req apiShowRequest
_ = json.NewDecoder(r.Body).Decode(&req)
if req.Model == "remote:cloud" {
http.Error(w, `{"error":"cloud is disabled"}`, http.StatusForbidden)
} else if req.Model == "remote-alias" || req.Model == "hidden-alias" {
fmt.Fprint(w, `{"remote_model":"remote","capabilities":["completion","tools"]}`)
} else if req.Model == "embeddings" || req.Model == "legacy-embedding" {
fmt.Fprint(w, `{"capabilities":["embedding"]}`)
} else if req.Model == "missing" {
http.Error(w, `{"error":"missing"}`, http.StatusNotFound)
} else {
fmt.Fprint(w, `{}`)
}
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
cmd := LaunchCmd(func(*cobra.Command, []string) error { return nil }, nil)
cmd.SetArgs(append([]string{"pi"}, tc.args...))
err := cmd.Execute()
if tc.wantError != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantError) {
t.Fatalf("launch error = %v, want %q", err, tc.wantError)
}
if pickerCalls != 0 {
t.Fatal("disabled cloud target unexpectedly opened the picker")
}
if _, err := os.Stat(argsPath); !os.IsNotExist(err) {
t.Fatalf("Pi started despite unavailable cloud target: %v", err)
}
saved, err := config.LoadIntegration("pi")
if err != nil || !slices.Equal(saved.Models, tc.saved) {
t.Fatalf("saved choices changed on disabled cloud failure: %v, %v", saved, err)
}
return
}
if err != nil {
t.Fatal(err)
}
if pickerCalls != tc.wantPicker {
t.Fatalf("picker called %d times, want %d", pickerCalls, tc.wantPicker)
}
wantSaved := []string{tc.wantModel}
if tc.runtimeOverride {
wantSaved = tc.saved
}
saved, err := config.LoadIntegration("pi")
if tc.corruptConfig {
data, readErr := os.ReadFile(filepath.Join(home, ".ollama", "config.json"))
if readErr != nil || string(data) != "{invalid" {
t.Fatalf("unused malformed config changed: %s, %v", data, readErr)
}
} else if err != nil || !slices.Equal(saved.Models, wantSaved) {
t.Fatalf("saved starting model = %v, %v; want %v", saved, err, wantSaved)
}
if !tc.runtimeOverride {
models := (&Pi{}).Models()
if !slices.Equal(models, []string{"chosen", "keep-model"}) {
t.Fatalf("Pi catalog = %v, want all available models", models)
}
}
data, err := os.ReadFile(argsPath)
var want []string
if tc.wantPicker > 0 {
want = []string{"--provider", "ollama", "--model", tc.wantModel}
}
if tc.wantPiArgs != nil {
want = tc.wantPiArgs
}
if err != nil || !slices.Equal(strings.Fields(string(data)), want) {
t.Fatalf("Pi arguments = %q, %v; want %v", data, err, want)
}
})
}
}
func TestLaunchIntegration_PiDownloadPromptCancellationPreservesConfig(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
withLauncherHooks(t)
withInteractiveSession(t, true)
if err := config.SaveIntegration("pi", []string{"previous"}); err != nil {
t.Fatal(err)
}
DefaultSingleSelector = func(_ string, _ []SelectionItem, _ string) (string, error) {
return "missing-new", nil
}
DefaultConfirmPrompt = func(prompt string, _ ConfirmOptions) (bool, error) {
if prompt != "Download missing-new?" {
t.Errorf("unexpected prompt: %s", prompt)
}
return false, ErrCancelled
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"missing-new"}]}`)
case "/api/tags":
fmt.Fprint(w, `{"models":[{"name":"previous"}]}`)
case "/api/show":
var req apiShowRequest
_ = json.NewDecoder(r.Body).Decode(&req)
if req.Model == "previous" {
fmt.Fprint(w, `{}`)
} else {
http.Error(w, `{"error":"missing"}`, http.StatusNotFound)
}
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
err := LaunchIntegration(context.Background(), IntegrationLaunchRequest{
Name: "pi", ForceConfigure: true, ConfigureOnly: true,
})
if !errors.Is(err, ErrCancelled) {
t.Fatalf("launch error = %v, want cancellation", err)
}
saved, err := config.LoadIntegration("pi")
if err != nil || !slices.Equal(saved.Models, []string{"previous"}) {
t.Fatalf("saved config changed on cancellation: %v, %v", saved, err)
}
if _, err := os.Stat(filepath.Join(home, ".pi")); !os.IsNotExist(err) {
t.Fatalf("Pi config was written on cancellation: %v", err)
}
}
func TestPiRun_PassesSelectedModelToClient(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a POSIX shell test binary")
}
dir := t.TempDir()
setTestHome(t, dir)
t.Setenv("PATH", dir)
argsPath := filepath.Join(dir, "args")
for name, content := range map[string]string{
"pi": fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$@\" > %q\n", argsPath),
"npm": "#!/bin/sh\nexit 1\n",
"package.json": `{"name":"@earendil-works/pi-coding-agent"}`,
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o755); err != nil {
t.Fatal(err)
}
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
if err := (&Pi{}).Run("chosen:latest", nil, []string{"--offline", "--print", "probe"}); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(argsPath)
if err != nil {
t.Fatal(err)
}
want := []string{"--provider", "ollama", "--model", "chosen:latest", "--offline", "--print", "probe"}
if got := strings.Split(strings.TrimSpace(string(data)), "\n"); !slices.Equal(got, want) {
t.Fatalf("Pi process arguments = %v, want %v", got, want)
}
}
func TestLaunchIntegrationPiPreservesModelChoice(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a POSIX shell test binary")
}
for _, tc := range []struct {
name string
current string
override string
configure bool
stallCatalog bool
extra []string
want string
wantArgs []string
}{
{name: "saved Pi default", current: "model-b", want: "model-b"},
{name: "resume restores its own model", current: "model-a", extra: []string{"--continue"}, want: "model-a", wantArgs: []string{"--continue"}},
{name: "explicit override wins", current: "model-b", override: "model-a", extra: []string{"--continue"}, want: "model-a", wantArgs: []string{"--provider", "ollama", "--model", "model-a", "--continue"}},
{name: "explicit lookup precedes timed out catalog", current: "model-b", override: "model-a", stallCatalog: true, want: "model-a", wantArgs: []string{"--provider", "ollama", "--model", "model-a"}},
{name: "explicit configuration wins", current: "model-b", configure: true, want: "model-a", wantArgs: []string{"--provider", "ollama", "--model", "model-a"}},
} {
t.Run(tc.name, func(t *testing.T) {
home := t.TempDir()
setLaunchTestHome(t, home)
withLauncherHooks(t)
withInteractiveSession(t, true)
if err := config.SaveIntegration("pi", []string{"model-a", "stale"}); err != nil {
t.Fatal(err)
}
dir := filepath.Join(home, ".pi", "agent")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if tc.stallCatalog {
oldTimeout := piModelDiscoveryTimeout
piModelDiscoveryTimeout = 50 * time.Millisecond
t.Cleanup(func() { piModelDiscoveryTimeout = oldTimeout })
if err := os.WriteFile(filepath.Join(dir, "models.json"), []byte(`{"providers":{"ollama":{"models":[{"id":"model-b","_launch":true,"contextWindow":8192}]}}}`), 0o644); err != nil {
t.Fatal(err)
}
}
firstLookup := make(chan string, 1)
settingsPath := filepath.Join(dir, "settings.json")
settings := fmt.Sprintf(`{"defaultProvider":"ollama","defaultModel":%q,"editorPaddingX":7}`, tc.current)
if err := os.WriteFile(settingsPath, []byte(settings), 0o644); err != nil {
t.Fatal(err)
}
bin := t.TempDir()
argsPath := filepath.Join(home, "pi-args")
for name, content := range map[string]string{
"pi": fmt.Sprintf("#!/bin/sh\nprintf '%%s\\n' \"$@\" > %q\n", argsPath),
"npm": "#!/bin/sh\nexit 1\n",
"package.json": `{"name":"@earendil-works/pi-coding-agent"}`,
} {
if err := os.WriteFile(filepath.Join(bin, name), []byte(content), 0o755); err != nil {
t.Fatal(err)
}
}
t.Setenv("PATH", bin)
DefaultSingleSelector = func(string, []SelectionItem, string) (string, error) {
if !tc.configure {
t.Fatal("ordinary launch unexpectedly opened the picker")
}
return "model-a", nil
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/status":
fmt.Fprint(w, `{"cloud":{"disabled":true}}`)
case "/api/tags":
if tc.stallCatalog {
select {
case firstLookup <- "tags":
default:
}
<-r.Context().Done()
return
}
fmt.Fprint(w, `{"models":[{"name":"model-a","capabilities":["completion"],"details":{"context_length":32768}},{"name":"model-b","capabilities":["completion"],"details":{"context_length":32768}}]}`)
case "/api/show":
select {
case firstLookup <- "show":
default:
}
fmt.Fprint(w, `{"capabilities":["completion"],"model_info":{"test.context_length":32768}}`)
case "/api/experimental/model-recommendations":
fmt.Fprint(w, `{"recommendations":[{"model":"model-a"}]}`)
default:
t.Errorf("unexpected request: %s", r.URL.Path)
http.NotFound(w, r)
}
}))
defer server.Close()
t.Setenv("OLLAMA_HOST", server.URL)
for range 2 {
select {
case <-firstLookup:
default:
}
err := LaunchIntegration(t.Context(), IntegrationLaunchRequest{Name: "pi", ModelOverride: tc.override, ForceConfigure: tc.configure, ExtraArgs: tc.extra})
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(settingsPath)
if err != nil {
t.Fatal(err)
}
var settings map[string]any
if err := json.Unmarshal(data, &settings); err != nil {
t.Fatal(err)
}
if settings["defaultModel"] != tc.want || settings["editorPaddingX"] != float64(7) {
t.Errorf("Pi settings = %s, want default %s and preserved padding", data, tc.want)
}
if tc.stallCatalog {
if lookup := <-firstLookup; lookup != "show" {
t.Errorf("first model lookup = %s, want show", lookup)
}
data, err := os.ReadFile(filepath.Join(dir, "models.json"))
if err != nil || !strings.Contains(string(data), `"model-b"`) {
t.Errorf("partial discovery discarded known catalog: %s, %v", data, err)
}
}
args, err := os.ReadFile(argsPath)
if err != nil || !slices.Equal(strings.Fields(string(args)), tc.wantArgs) {
t.Errorf("Pi args = %q, %v; want %v", args, err, tc.wantArgs)
}
}
})
}
}
+59 -46
View File
@@ -12,6 +12,7 @@ import (
"strings"
"testing"
"github.com/ollama/ollama/api"
"github.com/ollama/ollama/cmd/internal/fileutil"
"github.com/ollama/ollama/types/model"
)
@@ -916,6 +917,12 @@ func TestPiEdit(t *testing.T) {
// Mock Ollama server for createConfig calls during Edit
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/show" {
var req api.ShowRequest
json.NewDecoder(r.Body).Decode(&req)
if req.Model == "deepseek-v4-pro:cloud" {
fmt.Fprintf(w, `{"capabilities":[],"model_info":{"deepseek4.context_length":1048576}}`)
return
}
fmt.Fprintf(w, `{"capabilities":[],"model_info":{}}`)
return
}
@@ -1083,6 +1090,44 @@ func TestPiEdit(t *testing.T) {
}
})
t.Run("rebuilds managed cloud model missing from limits with server context", func(t *testing.T) {
useServerContextLookup(t)
cleanup()
os.MkdirAll(configDir, 0o755)
existingConfig := `{
"providers": {
"ollama": {
"baseUrl": "http://localhost:11434/v1",
"api": "openai-completions",
"apiKey": "ollama",
"models": [
{"id": "deepseek-v4-pro:cloud", "_launch": true, "input": ["text"]}
]
}
}
}`
if err := os.WriteFile(configPath, []byte(existingConfig), 0o644); err != nil {
t.Fatal(err)
}
if err := pi.Edit(launchModelsFromNames([]string{"deepseek-v4-pro:cloud"})); err != nil {
t.Fatalf("Edit() error = %v", err)
}
cfg := readConfig()
providers := cfg["providers"].(map[string]any)
ollama := providers["ollama"].(map[string]any)
modelsArray := ollama["models"].([]any)
if len(modelsArray) != 1 {
t.Fatalf("models = %v, want one entry", modelsArray)
}
modelEntry := modelsArray[0].(map[string]any)
if modelEntry["contextWindow"] != float64(1_048_576) {
t.Errorf("contextWindow = %v, want 1048576", modelEntry["contextWindow"])
}
})
t.Run("replaces old models with new ones", func(t *testing.T) {
cleanup()
os.MkdirAll(configDir, 0o755)
@@ -1185,35 +1230,19 @@ func TestPiEdit(t *testing.T) {
}
})
t.Run("handles corrupt config gracefully", func(t *testing.T) {
t.Run("preserves corrupt config", func(t *testing.T) {
cleanup()
os.MkdirAll(configDir, 0o755)
if err := os.WriteFile(configPath, []byte("{invalid json}"), 0o644); err != nil {
original := "{invalid json}"
if err := os.WriteFile(configPath, []byte(original), 0o644); err != nil {
t.Fatal(err)
}
models := []string{"test-model"}
if err := pi.Edit(launchModelsFromNames(models)); err != nil {
t.Fatalf("Edit() should not fail with corrupt config, got %v", err)
if err := pi.Edit(launchModelsFromNames([]string{"test-model"})); err == nil {
t.Fatal("expected invalid config error")
}
data, err := os.ReadFile(configPath)
if err != nil {
t.Fatalf("Failed to read config: %v", err)
}
var cfg map[string]any
if err := json.Unmarshal(data, &cfg); err != nil {
t.Fatalf("Config should be valid after Edit, got parse error: %v", err)
}
providers := cfg["providers"].(map[string]any)
ollama := providers["ollama"].(map[string]any)
modelsArray := ollama["models"].([]any)
if len(modelsArray) != 1 {
t.Errorf("Expected 1 model, got %d", len(modelsArray))
if err != nil || string(data) != original {
t.Fatalf("invalid config changed: %s, %v", data, err)
}
})
@@ -1365,36 +1394,20 @@ func TestPiEdit(t *testing.T) {
}
})
t.Run("handles corrupt settings.json gracefully", func(t *testing.T) {
t.Run("preserves corrupt settings.json", func(t *testing.T) {
cleanup()
os.MkdirAll(configDir, 0o755)
// Create corrupt settings
settingsPath := filepath.Join(configDir, "settings.json")
if err := os.WriteFile(settingsPath, []byte("{invalid"), 0o644); err != nil {
original := "{invalid"
if err := os.WriteFile(settingsPath, []byte(original), 0o644); err != nil {
t.Fatal(err)
}
models := []string{"test-model"}
if err := pi.Edit(launchModelsFromNames(models)); err != nil {
t.Fatalf("Edit() should not fail with corrupt settings, got %v", err)
if err := pi.Edit(launchModelsFromNames([]string{"test-model"})); err == nil {
t.Fatal("expected invalid settings error")
}
data, err := os.ReadFile(settingsPath)
if err != nil {
t.Fatalf("Failed to read settings: %v", err)
}
var settings map[string]any
if err := json.Unmarshal(data, &settings); err != nil {
t.Fatalf("settings.json should be valid after Edit, got parse error: %v", err)
}
if settings["defaultProvider"] != "ollama" {
t.Errorf("defaultProvider = %v, want ollama", settings["defaultProvider"])
}
if settings["defaultModel"] != "test-model" {
t.Errorf("defaultModel = %v, want test-model", settings["defaultModel"])
if err != nil || string(data) != original {
t.Fatalf("invalid settings changed: %s, %v", data, err)
}
})
}
+2 -2
View File
@@ -113,14 +113,14 @@ var integrationSpecs = []*IntegrationSpec{
Hidden: true,
Install: IntegrationInstallSpec{
CheckInstalled: func() bool {
_, err := exec.LookPath("kimi")
_, err := findKimiBinary()
return err == nil
},
EnsureInstalled: func() error {
_, err := ensureKimiInstalled()
return err
},
URL: "https://moonshotai.github.io/kimi-cli/en/guides/getting-started.html",
URL: "https://moonshotai.github.io/kimi-code/en/guides/getting-started.html",
},
},
{
+5
View File
@@ -79,6 +79,11 @@ func TestEditorRunsDoNotRewriteConfig(t *testing.T) {
home := t.TempDir()
setTestHome(t, home)
if tt.name == "opencode" {
previous := openCodeLoadedContextLength
openCodeLoadedContextLength = func(string) (int, error) { return 8192, nil }
t.Cleanup(func() { openCodeLoadedContextLength = previous })
}
binDir := t.TempDir()
writeFakeBinary(t, binDir, tt.binary)
+15
View File
@@ -16,6 +16,18 @@ var (
func init() {
integrations = buildTestIntegrations()
integrationAliases = buildTestIntegrationAliases()
lookupServerModelMetadata = func(string) (serverModelMetadata, bool) { return serverModelMetadata{}, false }
}
func useServerContextLookup(t *testing.T) {
old := lookupServerModelMetadata
lookupServerModelMetadata = cachedServerModelMetadata
serverModelMetadataCache.Clear()
serverModelMetadataUnavailable.Store(false)
t.Cleanup(func() {
lookupServerModelMetadata = old
serverModelMetadataUnavailable.Store(false)
})
}
func buildTestIntegrations() map[string]Runner {
@@ -43,8 +55,11 @@ func setTestHome(t *testing.T, dir string) {
codexAppNativeCatalog = func(string) ([]byte, error) {
return []byte(`{"models":[{"slug":"gpt-5.6-sol","display_name":"GPT-5.6-Sol","description":"Native Codex test model","priority":10,"supported_in_api":true,"base_instructions":"You are Codex, an agent based on GPT-5. Work carefully."}]}`), nil
}
oldOpenCodeReadConfig := openCodeReadConfig
openCodeReadConfig = func() ([]byte, error) { return []byte(`{}`), nil }
t.Cleanup(func() {
codexAppNativeCatalog = oldNativeCatalog
openCodeReadConfig = oldOpenCodeReadConfig
})
}
+324
View File
@@ -0,0 +1,324 @@
package cmd
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"os/signal"
"runtime"
"strings"
"unicode/utf8"
"golang.org/x/term"
"github.com/ollama/ollama/envconfig"
"github.com/ollama/ollama/readline"
)
// runSpeech reads text aloud: piped input as it arrives followed by any
// text arguments, the text arguments alone, or each line typed at the prompt.
func runSpeech(ctx context.Context, model, voice, text string, input io.Reader, interactive bool) error {
if input != nil {
return speak(ctx, model, voice, io.MultiReader(input, strings.NewReader(" "+text)))
}
if text != "" || !interactive {
return speak(ctx, model, voice, strings.NewReader(text))
}
if _, err := player(model, ""); err != nil {
return err
}
scanner, err := readline.New(readline.Prompt{
Prompt: ">>> ",
Placeholder: "Enter text to speak (/bye to exit)",
})
if err != nil {
return err
}
if envconfig.NoHistory() {
scanner.HistoryDisable()
}
for {
// Clear anything typed while audio played; readline redraws it.
fmt.Print(readline.CursorBOL + readline.ClearToEOL)
line, err := scanner.Readline()
switch {
case errors.Is(err, io.EOF):
fmt.Println()
return nil
case errors.Is(err, readline.ErrInterrupt):
if line == "" {
fmt.Println("\nUse Ctrl + d or /bye to exit.")
}
continue
case errors.Is(err, readline.ErrEditPrompt):
continue
case err != nil:
return err
}
text := strings.TrimSpace(line)
if text == "/bye" {
return nil
}
if text == "" {
continue
}
// Ctrl+C stops speaking and returns to the prompt.
speakCtx, stop := signal.NotifyContext(ctx, os.Interrupt)
if err := speak(speakCtx, model, voice, strings.NewReader(text)); err != nil && speakCtx.Err() == nil {
fmt.Fprintln(os.Stderr, "Error:", err)
}
stop()
}
}
// speak plays text from r a few sentences at a time as it arrives, so a chat
// model piped into a speech model is heard while it is still writing. When
// stdout is not a terminal it writes one WAV instead, for example
// `ollama run model "text" > speech.wav` on a machine without speakers.
func speak(ctx context.Context, model, voice string, r io.Reader) error {
toTerminal := term.IsTerminal(int(os.Stdout.Fd()))
if toTerminal {
if _, err := player(model, ""); err != nil {
return err
}
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Generate the next piece while the current one plays.
type result struct {
wav []byte
err error
}
audio := make(chan result, 1)
go func() {
defer close(audio)
for piece := range speechPieces(ctx, r) {
wav, err := synthesize(ctx, model, voice, piece)
select {
case audio <- result{wav, err}:
case <-ctx.Done():
return
}
if err != nil {
return
}
}
}()
var out []byte
spoken := false
for res := range audio {
if res.err != nil {
return res.err
}
spoken = true
switch {
case toTerminal:
if err := play(ctx, model, res.wav); err != nil {
return err
}
case out == nil:
out = res.wav
default:
out = append(out, res.wav[44:]...)
}
}
if !spoken {
return fmt.Errorf("speech models require input text. Usage: ollama run %s \"your text here\"", model)
}
if toTerminal {
return nil
}
setWAVSizes(out)
_, err := os.Stdout.Write(out)
return err
}
// minSpeechPiece is how much text speechPieces gathers before it sends a
// sentence on, so speech starts quickly without many tiny requests.
const minSpeechPiece = 100
// speechPieces sends text from r on as soon as it ends at a sentence or
// paragraph break, sized for /v1/audio/speech, and the rest when r ends.
func speechPieces(ctx context.Context, r io.Reader) <-chan string {
pieces := make(chan string)
go func() {
defer close(pieces)
send := func(text string) bool {
for _, piece := range speechChunks(text, maxSpeechInput) {
select {
case pieces <- piece:
case <-ctx.Done():
return false
}
}
return true
}
var pending string
buf := make([]byte, 4096)
for {
n, err := r.Read(buf)
pending += string(buf[:n])
if cut := speechCut(pending); cut > 0 {
if !send(pending[:cut]) {
return
}
pending = pending[cut:]
}
if err != nil {
send(pending)
return
}
}
}()
return pieces
}
// speechCut returns where text can be cut so the part before it is spoken
// now: after the last paragraph break or sentence end, once a paragraph or at
// least minSpeechPiece characters have arrived. It returns 0 to wait.
func speechCut(text string) int {
para := strings.LastIndex(text, "\n\n")
cut := max(para, lastSentenceEnd(text))
if para > 0 || (cut > 0 && utf8.RuneCountInString(text[:cut]) >= minSpeechPiece) {
return cut
}
return 0
}
// maxSpeechInput is the most characters /v1/audio/speech accepts at once.
const maxSpeechInput = 4096
// speechChunks splits text into one piece per paragraph, cutting paragraphs
// longer than limit characters at the last sentence end or space that fits.
func speechChunks(text string, limit int) []string {
var chunks []string
for para := range strings.SplitSeq(strings.ReplaceAll(text, "\r\n", "\n"), "\n\n") {
for p := strings.TrimSpace(para); p != ""; p = strings.TrimSpace(p) {
end := len(p)
if utf8.RuneCountInString(p) > limit {
end = 0
for range limit {
_, size := utf8.DecodeRuneInString(p[end:])
end += size
}
if i := lastSentenceEnd(p[:end]); i > 0 {
end = i
} else if i := strings.LastIndexAny(p[:end], " \t\n"); i > 0 {
end = i
}
}
chunks = append(chunks, strings.TrimSpace(p[:end]))
p = p[end:]
}
}
return chunks
}
// lastSentenceEnd returns the index just past the last '.', '!' or '?' in s
// that is followed by whitespace, or -1.
func lastSentenceEnd(s string) int {
for i := len(s) - 2; i > 0; i-- {
if strings.IndexByte(".!?", s[i]) >= 0 && (s[i+1] == ' ' || s[i+1] == '\n') {
return i + 1
}
}
return -1
}
func synthesize(ctx context.Context, model, voice, text string) ([]byte, error) {
body, err := json.Marshal(map[string]string{"model": model, "voice": voice, "input": text, "response_format": "wav"})
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, envconfig.Host().JoinPath("v1/audio/speech").String(), bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
var e struct{ Error struct{ Message string } }
if json.Unmarshal(data, &e) == nil && e.Error.Message != "" {
return nil, errors.New(e.Error.Message)
}
return nil, fmt.Errorf("speech request failed: %s", res.Status)
}
if len(data) <= 44 {
return nil, errors.New("speech response contained no audio")
}
setWAVSizes(data)
return data, nil
}
// setWAVSizes records the length of a WAV the server streamed as unknown,
// for players that need it.
func setWAVSizes(wav []byte) {
binary.LittleEndian.PutUint32(wav[4:], uint32(len(wav)-8))
binary.LittleEndian.PutUint32(wav[40:], uint32(len(wav)-44))
}
// play uses the system's built-in WAV player.
func play(ctx context.Context, model string, wav []byte) error {
f, err := os.CreateTemp("", "ollama-*.wav")
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(wav); err != nil {
f.Close()
return err
}
if err := f.Close(); err != nil {
return err
}
p, err := player(model, f.Name())
if err != nil {
return err
}
c := exec.CommandContext(ctx, p[0], p[1:]...)
c.Stderr = os.Stderr
if err := c.Run(); err != nil {
return fmt.Errorf("%s failed: %w. %s", p[0], err, saveHint(model))
}
return nil
}
// player returns the command that plays the WAV file at path.
func player(model, path string) ([]string, error) {
players := [][]string{{"paplay", path}, {"pw-play", path}, {"aplay", "-q", path}, {"ffplay", "-nodisp", "-autoexit", "-loglevel", "error", path}}
switch runtime.GOOS {
case "darwin":
players = [][]string{{"afplay", path}}
case "windows":
players = [][]string{{"powershell", "-NoProfile", "-Command", "(New-Object Media.SoundPlayer '" + strings.ReplaceAll(path, "'", "''") + "').PlaySync()"}}
}
for _, p := range players {
if _, err := exec.LookPath(p[0]); err == nil {
return p, nil
}
}
return nil, errors.New("no audio player found. " + saveHint(model))
}
func saveHint(model string) string {
return fmt.Sprintf(`To save the audio instead, run: ollama run %s "text" > speech.wav`, model)
}
+102
View File
@@ -0,0 +1,102 @@
package cmd
import (
"encoding/binary"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
)
func TestSpeechCut(t *testing.T) {
long := strings.Repeat("This sentence is long enough to say. ", 3)
for _, tc := range []struct {
text string
want int
}{
{"Too short to say yet. ", 0},
{"Heading\n\nBody", 7},
{long + "And then", len(long) - 1},
{"no sentence end yet " + strings.Repeat("words ", 20), 0},
} {
if got := speechCut(tc.text); got != tc.want {
t.Errorf("speechCut(%q) = %d, want %d", tc.text, got, tc.want)
}
}
}
// Speech starts once a few sentences arrive, before the input ends.
func TestSpeechPiecesStream(t *testing.T) {
r, w := io.Pipe()
pieces := speechPieces(t.Context(), r)
go w.Write([]byte(strings.Repeat("This sentence is long enough to say. ", 3) + "Unfinished"))
select {
case p := <-pieces:
if !strings.HasSuffix(p, "to say.") {
t.Errorf("first piece = %q", p)
}
case <-time.After(5 * time.Second):
t.Fatal("speech waited for the end of the input")
}
go func() {
w.Write([]byte(" tail"))
w.Close()
}()
var rest []string
for p := range pieces {
rest = append(rest, p)
}
if !slices.Equal(rest, []string{"Unfinished tail"}) {
t.Errorf("rest = %q", rest)
}
}
func TestSpeechChunks(t *testing.T) {
for _, tc := range []struct {
text string
limit int
want []string
}{
{"Hello.", 100, []string{"Hello."}},
{"One.\n\n Two.\r\n\r\nThree.", 100, []string{"One.", "Two.", "Three."}},
{"One two. Three four. Five six.", 21, []string{"One two. Three four.", "Five six."}},
{"one two three four", 10, []string{"one two", "three four"}},
{"abcdefghijkl", 5, []string{"abcde", "fghij", "kl"}},
{"ééééé", 2, []string{"éé", "éé", "é"}},
{" \n\n ", 100, nil},
} {
if got := speechChunks(tc.text, tc.limit); !slices.Equal(got, tc.want) {
t.Errorf("speechChunks(%q, %d) = %q, want %q", tc.text, tc.limit, got, tc.want)
}
}
}
func TestSynthesize(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req struct{ Input, Voice string }
if r.URL.Path != "/v1/audio/speech" || json.NewDecoder(r.Body).Decode(&req) != nil || req.Input == "" || req.Voice != "Toby" {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":{"message":"input is required"}}`))
return
}
wav := make([]byte, 48)
binary.LittleEndian.PutUint32(wav[4:], 0xffffffff)
binary.LittleEndian.PutUint32(wav[40:], 0xffffffff)
copy(wav[44:], []byte{1, 0, 2, 0})
w.Write(wav)
}))
defer srv.Close()
t.Setenv("OLLAMA_HOST", srv.URL)
wav, err := synthesize(t.Context(), "phonon", "Toby", "hello")
if err != nil || binary.LittleEndian.Uint32(wav[4:]) != 40 || binary.LittleEndian.Uint32(wav[40:]) != 4 {
t.Fatalf("WAV lengths not recorded: %x, %v", wav, err)
}
if _, err := synthesize(t.Context(), "phonon", "Toby", ""); err == nil || err.Error() != "input is required" {
t.Fatalf("server error lost: %v", err)
}
}
+30 -17
View File
@@ -42,9 +42,16 @@ type menuItem struct {
title string
description string
integration string
isRunModel bool
isOthers bool
}
var runModelMenuItem = menuItem{
title: "Chat with a model",
description: "Start an interactive chat with a model",
isRunModel: true,
}
var othersMenuItem = menuItem{
title: "More...",
description: "Show additional integrations",
@@ -52,11 +59,11 @@ var othersMenuItem = menuItem{
}
// launcherMenuIntegrations defines the default priority before the additional
// integrations in registry order. Installed apps are promoted above missing
// apps, with only the first five shown before More.
// integrations in registry order. Chat with a model comes first, then installed
// apps are promoted above missing apps, with only the first four shown before More.
var launcherMenuIntegrations = []string{"claude", "opencode", "hermes", "openclaw"}
const launcherMenuLimit = 5
const launcherMenuLimit = 4
type model struct {
state *launch.LauncherState
@@ -96,10 +103,10 @@ func shouldExpandOthers(state *launch.LauncherState) bool {
func buildMenuItems(state *launch.LauncherState, showOthers bool) []menuItem {
items := orderedIntegrationItems(state)
if showOthers || len(items) <= launcherMenuLimit {
return items
if !showOthers && len(items) > launcherMenuLimit {
items = append(items[:launcherMenuLimit], othersMenuItem)
}
return append(items[:launcherMenuLimit], othersMenuItem)
return append([]menuItem{runModelMenuItem}, items...)
}
func integrationMenuItem(state launch.LauncherIntegrationState) menuItem {
@@ -181,7 +188,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if m.cursor > 0 {
m.cursor--
}
if m.showOthers && m.cursor < launcherMenuLimit {
if m.showOthers && m.cursor <= launcherMenuLimit {
m.showOthers = false
m.items = buildMenuItems(m.state, false)
m.cursor = min(m.cursor, len(m.items)-1)
@@ -199,9 +206,6 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
case "enter", " ":
if len(m.items) == 0 {
return m, nil
}
if m.selectableItem(m.items[m.cursor]) {
m.selected = true
m.action = actionForMenuItem(m.items[m.cursor], false)
@@ -211,9 +215,6 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, nil
case "right", "l":
if len(m.items) == 0 {
return m, nil
}
item := m.items[m.cursor]
if m.changeableItem(item) {
m.selected = true
@@ -229,6 +230,9 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
func (m model) selectableItem(item menuItem) bool {
if item.isRunModel {
return true
}
if item.integration == "" || m.state == nil {
return false
}
@@ -237,6 +241,9 @@ func (m model) selectableItem(item menuItem) bool {
}
func (m model) changeableItem(item menuItem) bool {
if item.isRunModel {
return true
}
if item.integration == "" || m.state == nil {
return false
}
@@ -254,9 +261,6 @@ func (m model) View() string {
for i, item := range m.items {
s += m.renderMenuItem(i, item)
}
if len(m.items) == 0 {
s += "No apps available.\n"
}
s += "\n" + selectorHelpStyle.Render("↑/↓ navigate • enter launch • → configure • esc quit")
@@ -277,7 +281,14 @@ func (m model) renderMenuItem(index int, item menuItem) string {
cursor = "▸ "
}
if item.isOthers {
if item.isRunModel {
if m.cursor == index {
style = menuSelectedItemStyle
if m.state.RunModel != "" {
modelSuffix = " " + modelStyle.Render("("+m.state.RunModel+")")
}
}
} else if item.isOthers {
// More immediately expands when reached, so it always uses the default style.
} else {
integrationState := m.state.Integrations[item.integration]
@@ -354,6 +365,8 @@ func (a TUIAction) IntegrationLaunchRequest() launch.IntegrationLaunchRequest {
func actionForMenuItem(item menuItem, forceConfigure bool) TUIAction {
switch {
case item.isRunModel:
return TUIAction{Kind: TUIActionRunModel, ForceConfigure: forceConfigure}
case item.integration != "":
return TUIAction{Kind: TUIActionLaunchIntegration, Integration: item.integration, ForceConfigure: forceConfigure}
default:
+55 -31
View File
@@ -89,6 +89,8 @@ func integrationSequence(items []menuItem) []string {
sequence := make([]string, 0, len(items))
for _, item := range items {
switch {
case item.isRunModel:
sequence = append(sequence, "run")
case item.isOthers:
sequence = append(sequence, "more")
case item.integration != "":
@@ -109,10 +111,10 @@ func TestMenuPromotesInstalledAppsInDefaultPriorityOrder(t *testing.T) {
want []string
wantOverflow []string
}{
{"none installed", nil, []string{"claude", "opencode", "hermes", "openclaw", "codex", "more"}, []string{"droid", "pi"}},
{"only OpenClaw", []string{"openclaw"}, []string{"openclaw", "claude", "opencode", "hermes", "codex", "more"}, []string{"droid", "pi"}},
{"installed primary and additional apps", []string{"pi", "codex", "openclaw"}, []string{"openclaw", "codex", "pi", "claude", "opencode", "more"}, []string{"hermes", "droid"}},
{"more than five installed", []string{"pi", "droid", "codex", "openclaw", "hermes", "opencode"}, []string{"opencode", "hermes", "openclaw", "codex", "droid", "more"}, []string{"pi", "claude"}},
{"none installed", nil, []string{"run", "claude", "opencode", "hermes", "openclaw", "more"}, []string{"codex", "droid", "pi"}},
{"only OpenClaw", []string{"openclaw"}, []string{"run", "openclaw", "claude", "opencode", "hermes", "more"}, []string{"codex", "droid", "pi"}},
{"installed primary and additional apps", []string{"pi", "codex", "openclaw"}, []string{"run", "openclaw", "codex", "pi", "claude", "more"}, []string{"opencode", "hermes", "droid"}},
{"more than four installed", []string{"pi", "droid", "codex", "openclaw", "hermes", "opencode"}, []string{"run", "opencode", "hermes", "openclaw", "codex", "more"}, []string{"droid", "pi", "claude"}},
} {
t.Run(tc.name, func(t *testing.T) {
state := launcherTestState()
@@ -128,7 +130,7 @@ func TestMenuPromotesInstalledAppsInDefaultPriorityOrder(t *testing.T) {
t.Fatalf("wrong installed-first order: %s", diff)
}
expanded := buildMenuItems(state, true)
if diff := compareStrings(integrationSequence(expanded[launcherMenuLimit:]), tc.wantOverflow); diff != "" {
if diff := compareStrings(integrationSequence(expanded[1+launcherMenuLimit:]), tc.wantOverflow); diff != "" {
t.Fatalf("remaining apps should stay under More in priority order: %s", diff)
}
})
@@ -142,34 +144,36 @@ func TestMenuRemembersPromotedAppWithoutOpeningMore(t *testing.T) {
state.Integrations["codex"] = app
state.LastSelection = "codex"
menu := newModel(state)
if menu.showOthers || menu.cursor != 0 || menu.items[menu.cursor].integration != "codex" {
if menu.showOthers || menu.cursor != 1 || menu.items[menu.cursor].integration != "codex" {
t.Fatal("previously selected installed app should be recalled in its promoted position")
}
}
func TestMenuEmptyStateDoesNotPanic(t *testing.T) {
func TestMenuWithoutAppsOnlyOffersChat(t *testing.T) {
menu := newModel(nil)
if len(menu.items) != 0 {
t.Fatal("empty state must not create selectable menu items")
if diff := compareStrings(integrationSequence(menu.items), []string{"run"}); diff != "" {
t.Fatalf("menu without apps should only offer chat: %s", diff)
}
_ = menu.View() // Rendering an empty menu must not panic, regardless of its copy.
for _, key := range []tea.KeyType{tea.KeyEnter, tea.KeyRight, tea.KeyUp, tea.KeyDown} {
updated, cmd := menu.Update(tea.KeyMsg{Type: key})
if view := menu.View(); !strings.Contains(view, "Chat with a model") {
t.Fatalf("expected chat item in view\n%s", view)
}
for _, key := range []tea.KeyType{tea.KeyUp, tea.KeyDown} {
updated, _ := menu.Update(tea.KeyMsg{Type: key})
menu = updated.(model)
if menu.selected || menu.action.Kind != TUIActionNone || menu.cursor != 0 || cmd != nil {
t.Fatal("empty menu must not select an action")
if menu.cursor != 0 {
t.Fatal("cursor must stay on chat")
}
_ = menu.View()
}
if updated, quit := menu.Update(tea.KeyMsg{Type: tea.KeyEsc}); !updated.(model).quitting || quit == nil {
t.Fatal("Escape must still exit an empty menu")
updated, _ := menu.Update(tea.KeyMsg{Type: tea.KeyEnter})
if got := updated.(model); !got.selected || got.action != (TUIAction{Kind: TUIActionRunModel}) {
t.Fatalf("enter should start a chat, got selected=%v action=%v", got.selected, got.action)
}
}
func TestMenuUpToFiveAppsDoesNotNeedMore(t *testing.T) {
func TestMenuUpToFourAppsDoesNotNeedMore(t *testing.T) {
for _, names := range [][]string{
{"claude", "opencode", "hermes"},
{"claude", "opencode", "hermes", "openclaw", "codex"},
{"claude", "opencode", "hermes", "openclaw"},
} {
state := launcherTestState()
apps := make(map[string]launch.LauncherIntegrationState)
@@ -178,8 +182,8 @@ func TestMenuUpToFiveAppsDoesNotNeedMore(t *testing.T) {
}
state.Integrations = apps
menu := newModel(state)
if diff := compareStrings(integrationSequence(menu.items), names); diff != "" {
t.Fatalf("up to five apps should appear directly without More: %s", diff)
if diff := compareStrings(integrationSequence(menu.items), append([]string{"run"}, names...)); diff != "" {
t.Fatalf("up to four apps should appear directly without More: %s", diff)
}
}
}
@@ -190,17 +194,17 @@ func TestMenuExpandsAndCollapsesMoreAfterPromotion(t *testing.T) {
app.Installed = true
state.Integrations["codex"] = app
menu := newModel(state)
menu.cursor = launcherMenuLimit - 1
menu.cursor = launcherMenuLimit
root := integrationSequence(menu.items)
updated, _ := menu.Update(tea.KeyMsg{Type: tea.KeyDown})
expanded := updated.(model)
if !expanded.showOthers || expanded.cursor != launcherMenuLimit || expanded.items[expanded.cursor].integration == "" {
if !expanded.showOthers || expanded.cursor != launcherMenuLimit+1 || expanded.items[expanded.cursor].integration == "" {
t.Fatal("Down must expand More and select the first overflow app")
}
updated, _ = expanded.Update(tea.KeyMsg{Type: tea.KeyUp})
collapsed := updated.(model)
if collapsed.showOthers || collapsed.cursor != launcherMenuLimit-1 {
if collapsed.showOthers || collapsed.cursor != launcherMenuLimit {
t.Fatal("Up must return to the last primary app")
}
if diff := compareStrings(integrationSequence(collapsed.items), root); diff != "" {
@@ -210,7 +214,7 @@ func TestMenuExpandsAndCollapsesMoreAfterPromotion(t *testing.T) {
func TestMenuStartsExpandedForPreviousOverflowSelection(t *testing.T) {
state := launcherTestState()
overflow := buildMenuItems(state, true)[launcherMenuLimit:]
overflow := buildMenuItems(state, true)[1+launcherMenuLimit:]
if len(overflow) < 2 {
t.Fatal("expected at least two additional integrations")
}
@@ -230,12 +234,32 @@ func TestMenuStartsExpandedForPreviousOverflowSelection(t *testing.T) {
}
}
func TestMenuPreviousRunSelectionFallsBackToFirstApp(t *testing.T) {
func TestMenuRemembersChat(t *testing.T) {
state := launcherTestState()
state.LastSelection = "run"
menu := newModel(state)
if menu.cursor != 0 || menu.items[menu.cursor].integration != "claude" {
t.Fatal("previous chat selection must fall back to the first app")
if menu.cursor != 0 || !menu.items[menu.cursor].isRunModel {
t.Fatal("previous chat selection should start on Chat with a model")
}
}
func TestMenuEnterOnRunSelectsRun(t *testing.T) {
menu := newModel(launcherTestState())
updated, _ := menu.Update(tea.KeyMsg{Type: tea.KeyEnter})
got := updated.(model)
want := TUIAction{Kind: TUIActionRunModel}
if !got.selected || got.action != want {
t.Fatalf("expected enter on run to select run action, got selected=%v action=%v", got.selected, got.action)
}
}
func TestMenuRightOnRunSelectsChangeRun(t *testing.T) {
menu := newModel(launcherTestState())
updated, _ := menu.Update(tea.KeyMsg{Type: tea.KeyRight})
got := updated.(model)
want := TUIAction{Kind: TUIActionRunModel, ForceConfigure: true}
if !got.selected || got.action != want {
t.Fatalf("expected right on run to select change-run action, got selected=%v action=%v", got.selected, got.action)
}
}
@@ -291,14 +315,14 @@ func TestMenuIgnoresDisabledActions(t *testing.T) {
}
}
func TestMenuShowsOnlySelectedAppsCurrentModel(t *testing.T) {
func TestMenuShowsOnlySelectedItemsCurrentModel(t *testing.T) {
state := launcherTestState()
menu := newModel(state)
for i, item := range menu.items {
menu.cursor = i
view := menu.View()
if strings.Contains(view, state.RunModel) {
t.Fatalf("removed chat model must not appear at cursor %d", i)
if got, want := strings.Contains(view, state.RunModel), item.isRunModel; got != want {
t.Fatalf("chat model visibility at cursor %d = %v, want %v", i, got, want)
}
if got, want := strings.Contains(view, state.Integrations["claude"].CurrentModel), item.integration == "claude"; got != want {
t.Fatalf("current model visibility at cursor %d = %v, want %v", i, got, want)
+52
View File
@@ -0,0 +1,52 @@
package create
import (
"context"
"os"
"path/filepath"
"testing"
st "github.com/ollama/ollama/fs/safetensors"
)
func TestAutoTrustDecisionImportExcludesBuildNotes(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["AutoTrustDecision"],"model_type":"qwen3_5_text"}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{8, 8}, make([]byte, 128)),
})
for name, data := range map[string]string{
"decision_head.json": `{"slots":{}}`,
"calibration.json": `{"version":1}`,
"preprocessor_config.json": `{}`,
"video_preprocessor_config.json": `{}`,
"hf_quant_config.json": `{"quantization":{"quant_algo":"W4A16_NVFP4"}}`,
"build-notes.json": `{"source":"/tank/private-models","token":"fixture-secret"}`,
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0o600); err != nil {
t.Fatal(err)
}
}
store := newCaptureStore()
var renderer string
err := Create(t.Context(), "autotrust-decision-fixture", dir, testPipelineOptions(), store,
func(_ context.Context, _ string, info ManifestInfo) error {
renderer = info.ModelConfig.Renderer
return nil
}, func(string) {})
if err != nil {
t.Fatal(err)
}
if renderer != "autotrust-decision" {
t.Fatalf("renderer = %q, want autotrust-decision", renderer)
}
if _, ok := store.blobs["build-notes.json"]; ok {
t.Fatal("internal source notes were packaged")
}
for _, name := range []string{"config.json", "decision_head.json", "calibration.json", "preprocessor_config.json", "video_preprocessor_config.json", "hf_quant_config.json"} {
if _, ok := store.blobs[name]; !ok {
t.Errorf("required AutoTrust decision metadata %s was omitted", name)
}
}
}
+8 -7
View File
@@ -121,7 +121,7 @@ func normalizeRequested(requested string) (string, error) {
// missing (e.g. a ModelOpt checkpoint without hf_quant_config.json) is still
// recognized as already-quantized and not mistaken for a float model.
func detectKind(inv Inventory) SourceKind {
var hasMLXScales, hasPacked, hasNVFP4Scale, hasFP8Weight bool
var hasMLXScales, hasPacked, hasPrequantScale, hasFP8Weight bool
for name, t := range inv.Tensors {
switch {
case strings.HasSuffix(name, ".scales"):
@@ -129,11 +129,12 @@ func detectKind(inv Inventory) SourceKind {
case strings.HasSuffix(name, ".weight_packed"):
hasPacked = true
case strings.HasSuffix(name, ".weight_scale"):
// An NVFP4 per-block scale sits on a packed (U8) weight. A
// block-FP8 source also has a scale companion, but its weight is
// F8_E4M3 — so the base weight's dtype disambiguates the two.
if bt, ok := inv.Tensors[strings.TrimSuffix(name, "_scale")]; ok && isPackedDtype(bt.Dtype) {
hasNVFP4Scale = true
// ModelOpt NVFP4 uses a packed weight with an FP8 scale; its
// MXFP8 uses an FP8 weight with a U8 scale. HF block-FP8 also
// has a scale companion but is decoded through a separate path.
if bt, ok := inv.Tensors[strings.TrimSuffix(name, "_scale")]; ok &&
(isPackedDtype(bt.Dtype) || isE4M3Dtype(bt.Dtype) && strings.EqualFold(t.Dtype, "U8")) {
hasPrequantScale = true
}
}
if strings.HasSuffix(name, ".weight") && isE4M3Dtype(t.Dtype) {
@@ -142,7 +143,7 @@ func detectKind(inv Inventory) SourceKind {
}
switch {
case hasMLXScales || hasPacked || hasNVFP4Scale:
case hasMLXScales || hasPacked || hasPrequantScale:
return SourcePrequantized
case hasFP8Weight:
return SourceBlockFP8
-20
View File
@@ -78,23 +78,3 @@ func prepareClefInventory(inv Inventory) (Inventory, error) {
inv.Config.Architectures = []string{"ClefForDecision"}
return inv, nil
}
// The publisher's head is not in the shard index. Transfer it without using
// its presence to select a model architecture.
func clefWeightFiles(dir string, files []string) ([]string, error) {
info, err := os.Stat(filepath.Join(dir, "joint_head.safetensors"))
if os.IsNotExist(err) {
return files, nil
}
if err != nil {
return nil, err
}
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("Clef joint_head.safetensors must be a regular file")
}
if !slices.Contains(files, "joint_head.safetensors") {
files = append(files, "joint_head.safetensors")
slices.Sort(files)
}
return files, nil
}
+42 -12
View File
@@ -23,6 +23,10 @@ import (
// safetensors-backed models.
const SafetensorsMinOllamaVersion = "0.19.0"
// phononMinOllamaVersion is the first Ollama release that runs Phonon speech
// models.
const phononMinOllamaVersion = "0.40.9"
// IsSafetensorsLLMModel checks for a safetensors completion or decision model.
func IsSafetensorsLLMModel(modelName string) bool {
name := model.ParseName(modelName)
@@ -423,7 +427,9 @@ func (cfg sourceModelConfig) HFFP8WeightBlockSize() (rows, cols int32, ok bool)
type tensorImportTransformFactory func(rawConfig json.RawMessage) (quantizePolicy, error)
var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
"Qwen3_5Model": newPplxImportTransform,
"KevForDecision": newQwen35DecisionImportTransform,
"AutoTrustDecision": newQwen35DecisionImportTransform,
"StrandsDeciderForDecision": newQwen35DecisionImportTransform,
"ClefForDecision": newQwen35DecisionImportTransform,
"Qwen3_5ForCausalLM": newQwen35ImportTransform,
@@ -449,8 +455,13 @@ var tensorImportTransformRegistry = map[string]tensorImportTransformFactory{
"gemma4_unified_assistant": newGemma4ImportTransform,
"NemotronH_Nano_VL_V2": newNemotronHImportTransform,
"NemotronH_Nano_Omni_Reasoning_V3": newNemotronHImportTransform,
"NemotronH_Omni_Reasoning_V3": newNemotronHImportTransform,
"NemotronHForCausalLM": newNemotronHImportTransform,
"EmbeddingGemma2Model": newGemma4EmbeddingImportTransform,
"Lfm3VlForConditionalGeneration": newLFM3ImportTransform,
"Lfm3OmniForConditionalGeneration": newLFM3OmniImportTransform,
"Lfm3AudioForConditionalGeneration": newLFM3AudioImportTransform,
"D1Model": newLFM3ImportTransform,
}
func newTensorImportTransform(inv Inventory) (quantizePolicy, error) {
@@ -469,6 +480,24 @@ func buildSourceFP8Reader(weightTD, scaleTD *safetensors.TensorData) io.Reader {
}
func validateScalarFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {
validated, err := validateFloat32TensorData(td, name)
if err != nil || validated == nil {
if err != nil && td != nil && strings.EqualFold(td.Dtype, "F32") {
return nil, fmt.Errorf("expected scalar F32 tensor, got shape %v", td.Shape)
}
return validated, err
}
n := int64(1)
for _, dim := range validated.Shape {
n *= int64(dim)
}
if n != 1 {
return nil, fmt.Errorf("expected scalar F32 tensor, got shape %v", validated.Shape)
}
return validated, nil
}
func validateFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {
if td == nil {
return nil, nil
}
@@ -478,35 +507,36 @@ func validateScalarFloat32TensorData(td *safetensors.TensorData, name string) (*
n := int64(1)
for _, dim := range td.Shape {
if dim <= 0 || n > math.MaxInt64/int64(dim) {
return nil, fmt.Errorf("expected scalar F32 tensor, got shape %v", td.Shape)
return nil, fmt.Errorf("expected non-empty F32 tensor, got shape %v", td.Shape)
}
n *= int64(dim)
}
if n != 1 || td.Size != 4 {
return nil, fmt.Errorf("expected scalar F32 tensor, got shape %v", td.Shape)
if n > math.MaxInt64/4 || td.Size != n*4 {
return nil, fmt.Errorf("expected non-empty F32 tensor, got shape %v", td.Shape)
}
return td.WithName(name), nil
}
func invertScalarFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {
td, err := validateScalarFloat32TensorData(td, name)
if err != nil {
return nil, err
func invertFloat32TensorData(td *safetensors.TensorData, name string) (*safetensors.TensorData, error) {
td, err := validateFloat32TensorData(td, name)
if err != nil || td == nil {
return td, err
}
raw, err := io.ReadAll(td.Reader())
if err != nil {
return nil, err
}
if len(raw)%4 != 0 {
return nil, fmt.Errorf("invalid F32 tensor byte length %d", len(raw))
if int64(len(raw)) != td.Size {
return nil, fmt.Errorf("invalid F32 tensor byte length %d, expected %d", len(raw), td.Size)
}
out := make([]byte, len(raw))
for i := 0; i < len(raw); i += 4 {
v := math.Float32frombits(binary.LittleEndian.Uint32(raw[i : i+4]))
if v == 0 {
return nil, fmt.Errorf("cannot invert zero F32 scale")
inverse := 1 / v
if !(v > 0) || math.IsInf(float64(v), 0) || math.IsInf(float64(inverse), 0) {
return nil, fmt.Errorf("cannot invert F32 scale %v: expected a finite positive scale with a finite reciprocal", v)
}
binary.LittleEndian.PutUint32(out[i:i+4], math.Float32bits(1/v))
binary.LittleEndian.PutUint32(out[i:i+4], math.Float32bits(inverse))
}
return safetensors.NewTensorDataFromBytes(name, td.Dtype, td.Shape, out), nil
}
+12 -3
View File
@@ -63,12 +63,21 @@ func TestValidateScalarFloat32TensorDataRejectsShapeOverflow(t *testing.T) {
}
}
func TestInvertScalarFloat32TensorDataRejectsNonF32(t *testing.T) {
func TestInvertFloat32TensorDataRejectsNonF32(t *testing.T) {
td := st.NewTensorDataFromBytes("linear.weight_global_scale", "BF16", []int32{}, []byte{0, 0})
_, err := invertScalarFloat32TensorData(td, "linear.weight.global_scale")
_, err := invertFloat32TensorData(td, "linear.weight.global_scale")
if err == nil || !strings.Contains(err.Error(), "expected F32 tensor") {
t.Fatalf("invertScalarFloat32TensorData error = %v, want dtype failure", err)
t.Fatalf("invertFloat32TensorData error = %v, want dtype failure", err)
}
}
func TestInvertFloat32TensorDataRejectsInvalidScales(t *testing.T) {
for _, value := range []float32{0, -1, float32(math.NaN()), float32(math.Inf(1)), math.SmallestNonzeroFloat32} {
td := st.NewTensorDataFromBytes("experts.weight_global_scale", "F32", []int32{2}, encodeFloat32s(2, value))
if _, err := invertFloat32TensorData(td, "experts.weight.global_scale"); err == nil {
t.Errorf("inverting scale bank [2, %v] succeeded, want invalid-scale error", value)
}
}
}
+82
View File
@@ -0,0 +1,82 @@
package create
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/ollama/ollama/fs/safetensors"
)
const d3FormatID = "d3-code-readout-v1"
func qwenDecisionFormat(dir string) (string, error) {
data, err := os.ReadFile(filepath.Join(dir, "decision_config.json"))
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
if err != nil {
return "", err
}
var cfg struct {
FormatID string `json:"format_id"`
}
if err := json.Unmarshal(data, &cfg); err != nil {
return "", fmt.Errorf("parse decision_config.json: %w", err)
}
if cfg.FormatID != "" && cfg.FormatID != d3FormatID {
return "", fmt.Errorf("unsupported Qwen decision format %q", cfg.FormatID)
}
return cfg.FormatID, nil
}
func prepareD3Inventory(inv Inventory) (Inventory, error) {
var backbone struct {
TextConfig struct {
HiddenSize int32 `json:"hidden_size"`
} `json:"text_config"`
}
if err := json.Unmarshal(inv.RawConfig, &backbone); err != nil {
return Inventory{}, fmt.Errorf("parse d3 backbone config: %w", err)
}
data, err := os.ReadFile(filepath.Join(inv.Dir, "decision_config.json"))
if err != nil {
return Inventory{}, fmt.Errorf("read d3 decision config: %w", err)
}
var decision struct {
FormatVersion int `json:"format_version"`
FormatID string `json:"format_id"`
Prompt string `json:"prompt"`
Codes []string `json:"codes"`
TokenIDs []int32 `json:"token_ids"`
AttentionMode string `json:"attention_mode"`
Pooling string `json:"pooling"`
ReadoutDType string `json:"readout_dtype"`
}
if err := json.Unmarshal(data, &decision); err != nil {
return Inventory{}, fmt.Errorf("parse d3 decision config: %w", err)
}
if backbone.TextConfig.HiddenSize <= 0 || decision.FormatVersion != 1 || decision.FormatID != d3FormatID || decision.Prompt != "d3" || len(decision.Codes) != 255 || len(decision.TokenIDs) != 255 || decision.AttentionMode != "noncausal_full_attention" || decision.Pooling != "last" || decision.ReadoutDType != "float32" {
return Inventory{}, fmt.Errorf("unsupported d3 decision config (format %q, attention %q)", decision.FormatID, decision.AttentionMode)
}
reader, err := safetensors.OpenForExtraction(filepath.Join(inv.Dir, "readout.safetensors"))
if err != nil {
return Inventory{}, fmt.Errorf("open d3 readout: %w", err)
}
defer reader.Close()
if names := reader.ListTensors(); !slices.Equal(names, []string{"weight"}) {
return Inventory{}, fmt.Errorf("d3 readout must contain only weight")
}
weight, err := reader.GetTensor("weight")
if err != nil || weight.Dtype != "F32" || !slices.Equal(weight.Shape, []int32{255, backbone.TextConfig.HiddenSize}) {
return Inventory{}, fmt.Errorf("d3 requires an FP32 readout of shape [255,%d]", backbone.TextConfig.HiddenSize)
}
if inv.Has("weight") {
return Inventory{}, fmt.Errorf("d3 readout weight collides with a backbone tensor")
}
inv.Tensors["weight"] = SourceTensor{Name: "weight", Dtype: weight.Dtype, Shape: weight.Shape, File: "readout.safetensors"}
return inv, nil
}
+88
View File
@@ -0,0 +1,88 @@
package create
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"
st "github.com/ollama/ollama/fs/safetensors"
)
func writeD3Source(t *testing.T, dir string) {
t.Helper()
writeConfigJSON(t, dir, `{"architectures":["Qwen3_5Model"],"model_type":"qwen3_5","text_config":{"hidden_size":4},"vision_config":{}}`)
decision := `{"format_version":1,"format_id":"d3-code-readout-v1","prompt":"d3","attention_mode":"noncausal_full_attention","pooling":"last","readout_dtype":"float32","temperature":1,"codes":[` + strings.TrimSuffix(strings.Repeat(`"A",`, 255), ",") + `],"token_ids":[` + strings.TrimSuffix(strings.Repeat(`32,`, 255), ",") + `]}`
if err := os.WriteFile(filepath.Join(dir, "decision_config.json"), []byte(decision), 0o600); err != nil {
t.Fatal(err)
}
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{8, 4}, make([]byte, 64)),
})
createTestSafetensors(t, filepath.Join(dir, "readout.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("weight", "F32", []int32{255, 4}, make([]byte, 4080)),
})
}
func TestD3ImportRetainsFP32ReadoutAndExcludesPublisherManifest(t *testing.T) {
dir := t.TempDir()
writeD3Source(t, dir)
if err := os.WriteFile(filepath.Join(dir, "MODEL_MANIFEST.json"), []byte(`{"publisher":"vllm-sr"}`), 0o600); err != nil {
t.Fatal(err)
}
files, err := SafetensorsConfigFiles(dir)
if err != nil || slices.Contains(files, "MODEL_MANIFEST.json") {
t.Fatalf("imported publisher manifest: %v, %v", files, err)
}
store := newCaptureStore()
var renderer string
err = Create(t.Context(), "d3-mini-test", dir, testPipelineOptions(), store, func(_ context.Context, _ string, info ManifestInfo) error {
renderer = info.ModelConfig.Renderer
return nil
}, func(string) {})
if err != nil {
t.Fatal(err)
}
if renderer != "d3" || store.blobs["decision_config.json"] == nil || store.blobs["MODEL_MANIFEST.json"] != nil {
t.Fatalf("renderer = %q; blobs = %v", renderer, store.names())
}
inv, err := ReadInventory(dir)
if err != nil {
t.Fatal(err)
}
inv, err = prepareD3Inventory(inv)
if err != nil {
t.Fatal(err)
}
if got := inv.Tensors["weight"].Dtype; got != "F32" {
t.Fatalf("readout dtype = %q", got)
}
}
func TestD3RejectsNonFP32ReadoutBeforeWriting(t *testing.T) {
dir := t.TempDir()
writeD3Source(t, dir)
createTestSafetensors(t, filepath.Join(dir, "readout.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("weight", "BF16", []int32{255, 4}, make([]byte, 2040)),
})
store := newCaptureStore()
err := Create(t.Context(), "d3-mini-test", dir, testPipelineOptions(), store, func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
if err == nil || !strings.Contains(err.Error(), "FP32 readout") || len(store.blobs) != 0 {
t.Fatalf("import error = %v; blobs = %v", err, store.names())
}
}
func TestD3RejectsUnknownDecisionFormatBeforeWriting(t *testing.T) {
dir := t.TempDir()
writeD3Source(t, dir)
if err := os.WriteFile(filepath.Join(dir, "decision_config.json"), []byte(`{"format_id":"future-format"}`), 0o600); err != nil {
t.Fatal(err)
}
store := newCaptureStore()
err := Create(t.Context(), "d3-mini-test", dir, testPipelineOptions(), store, func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
if err == nil || !strings.Contains(err.Error(), `unsupported Qwen decision format "future-format"`) || len(store.blobs) != 0 {
t.Fatalf("import error = %v; blobs = %v", err, store.names())
}
}
+29
View File
@@ -0,0 +1,29 @@
package create
import "strings"
// sourceFloatFileType names the float dtype holding most of an unquantized
// source's weight elements, in the spelling Kev and GGUF imports record, so
// the package states its precision rather than relying on config.json's
// optional (and sometimes wrong) dtype field.
func sourceFloatFileType(inv Inventory) string {
elements := map[string]int64{}
for _, t := range inv.Tensors {
n := int64(1)
for _, d := range t.Shape {
n *= int64(d)
}
elements[strings.ToUpper(t.Dtype)] += n
}
var best string
for dtype, n := range elements {
if n > elements[best] || (n == elements[best] && dtype < best) {
best = dtype
}
}
switch best {
case "BF16", "F16", "F32":
return best
}
return ""
}
+26
View File
@@ -0,0 +1,26 @@
package create
import "testing"
func TestSourceFloatFileType(t *testing.T) {
for _, tc := range []struct {
name string
tensors map[string]SourceTensor
want string
}{
{"bf16 weights with f32 norms", map[string]SourceTensor{
"w": {Dtype: "BF16", Shape: []int32{2048, 2048}},
"norm": {Dtype: "F32", Shape: []int32{2048}},
"bias": {Dtype: "F32", Shape: []int32{2048}},
}, "BF16"},
{"f16", map[string]SourceTensor{"w": {Dtype: "F16", Shape: []int32{4, 4}}}, "F16"},
{"f32", map[string]SourceTensor{"w": {Dtype: "F32", Shape: []int32{4}}}, "F32"},
{"empty", map[string]SourceTensor{}, ""},
} {
t.Run(tc.name, func(t *testing.T) {
if got := sourceFloatFileType(Inventory{Tensors: tc.tensors}); got != tc.want {
t.Errorf("sourceFloatFileType = %q, want %q", got, tc.want)
}
})
}
}
+135 -2
View File
@@ -2,9 +2,11 @@ package create
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/ollama/ollama/fs/safetensors"
@@ -119,7 +121,75 @@ func SafetensorsWeightFiles(dir string) ([]string, error) {
if err != nil {
return nil, err
}
return clefWeightFiles(dir, files)
// Clef selects its separate head through RENDERER, so its sidecar is
// included whenever present. The Perplexity readout belongs only to its
// Qwen3_5Model checkpoint.
files, err = appendWeightSidecar(dir, files, "joint_head.safetensors", "Clef")
if err != nil {
return nil, err
}
if _, err := os.Stat(filepath.Join(dir, "config.json")); err == nil {
cfg, _, err := readSourceModelConfig(dir)
if err != nil {
return nil, err
}
if cfg.Architecture() == gradiumPhononArchitecture {
files, err = appendWeightSidecar(dir, files, "default-voice.safetensors", "Phonon")
if err != nil {
return nil, err
}
if !slices.Contains(files, "default-voice.safetensors") {
return nil, fmt.Errorf("Phonon checkpoint requires default-voice.safetensors")
}
voices, err := phononVoiceFiles(dir)
if err != nil {
return nil, err
}
files = append(files, voices...)
}
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
if codecDir, err := lfm3CodecDir(dir); err != nil {
return nil, err
} else if codecDir != "" {
file, err := lfm3CodecFile(dir, codecDir, "model.safetensors")
if err != nil {
return nil, err
}
files = append(files, file)
}
if _, err := os.Stat(filepath.Join(dir, "readout.safetensors")); errors.Is(err, os.ErrNotExist) {
return files, nil
} else if err != nil {
return nil, err
}
cfg, _, err := readSourceModelConfig(dir)
if err != nil {
return nil, err
}
if cfg.Architecture() != "Qwen3_5Model" {
return files, nil
}
return appendWeightSidecar(dir, files, "readout.safetensors", "Qwen decision")
}
func appendWeightSidecar(dir string, files []string, name, modelName string) ([]string, error) {
info, err := os.Stat(filepath.Join(dir, name))
if errors.Is(err, os.ErrNotExist) {
return files, nil
}
if err != nil {
return nil, err
}
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("%s %s must be a regular file", modelName, name)
}
if !slices.Contains(files, name) {
files = append(files, name)
slices.Sort(files)
}
return files, nil
}
// SafetensorsConfigFiles lists source metadata for remote transfer and local
@@ -153,7 +223,70 @@ func SafetensorsConfigFiles(dir string) ([]string, error) {
names = append(names, name)
}
}
return names, nil
if codecDir, err := lfm3CodecDir(dir); err != nil {
return nil, err
} else if codecDir != "" {
name, err := lfm3CodecFile(dir, codecDir, "config.json")
if err != nil {
return nil, err
}
names = append(names, name)
}
hasSidecar, err := hasPplxSidecar(dir)
if err != nil {
return nil, err
}
hasAutoTrustDecisionSidecar := slices.Contains(names, "decision_head.json")
if !hasSidecar && !hasAutoTrustDecisionSidecar {
return names, nil
}
cfg, _, err := readSourceModelConfig(dir)
if err != nil {
return nil, err
}
autoTrustDecisionSource := cfg.Architecture() == "AutoTrustDecision"
qwenDecisionSource := hasSidecar && cfg.Architecture() == "Qwen3_5Model"
if !autoTrustDecisionSource && !qwenDecisionSource {
return names, nil
}
// These decision checkpoints may have extra JSON that does not configure
// inference. Keep only the files the importer or runner consumes.
modelMetadata := map[string]bool{
"config.json": true,
"decision_config.json": true,
"joint_config.json": true,
"generation_config.json": true,
"model.safetensors.index.json": true,
"processor_config.json": true,
"tokenizer.json": true,
"tokenizer_config.json": true,
"special_tokens_map.json": true,
"added_tokens.json": true,
"hf_quant_config.json": true,
"quantization_config.json": true,
}
if autoTrustDecisionSource {
modelMetadata["adapter_config.json"] = true
modelMetadata["calibration.json"] = true
modelMetadata["decision_head.json"] = true
modelMetadata["preprocessor_config.json"] = true
modelMetadata["video_preprocessor_config.json"] = true
modelMetadata["vocab.json"] = true
}
if qwenDecisionSource {
format, err := qwenDecisionFormat(dir)
if err != nil {
return nil, err
}
if format == d3FormatID {
modelMetadata["preprocessor_config.json"] = true
modelMetadata["video_preprocessor_config.json"] = true
modelMetadata["vocab.json"] = true
}
}
return slices.DeleteFunc(names, func(name string) bool {
return filepath.Ext(name) == ".json" && !modelMetadata[name]
}), nil
}
func safetensorsWeightFiles(dir string) (map[string]string, []string, error) {
+70
View File
@@ -0,0 +1,70 @@
package create
import (
"encoding/json"
"fmt"
"strings"
"github.com/ollama/ollama/model/renderers"
"github.com/ollama/ollama/types/model"
)
// lfm3ImportTransform quantizes only the language backbone of the multimodal
// LFM3 checkpoints; vision, audio encoder, projectors, and the speech decoder
// stay at source precision.
type lfm3ImportTransform struct {
backbone string
// Audio nests its language model config under "lfm", where shared
// config inference doesn't look; the manifest records it instead.
contextLen, embedLen int
// speech models' voices are prompt descriptions, not voice tensors, so
// the manifest names them.
speech bool
}
func newLFM3ImportTransform(json.RawMessage) (quantizePolicy, error) {
return lfm3ImportTransform{backbone: "model.language_model."}, nil
}
func newLFM3OmniImportTransform(json.RawMessage) (quantizePolicy, error) {
return lfm3ImportTransform{backbone: "model.language_model.", speech: true}, nil
}
func newLFM3AudioImportTransform(raw json.RawMessage) (quantizePolicy, error) {
var cfg struct {
LFM struct {
HiddenSize int `json:"hidden_size"`
MaxPositionEmbeddings int `json:"max_position_embeddings"`
} `json:"lfm"`
}
if err := json.Unmarshal(raw, &cfg); err != nil {
return nil, err
}
if cfg.LFM.HiddenSize <= 0 || cfg.LFM.MaxPositionEmbeddings <= 0 {
return nil, fmt.Errorf("missing lfm.hidden_size or lfm.max_position_embeddings")
}
return lfm3ImportTransform{
backbone: "lfm.model.",
contextLen: cfg.LFM.MaxPositionEmbeddings,
embedLen: cfg.LFM.HiddenSize,
speech: true,
}, nil
}
func (t lfm3ImportTransform) augmentConfig(cfg *model.ConfigV2) error {
if t.contextLen > 0 {
cfg.ContextLen = t.contextLen
cfg.EmbedLen = t.embedLen
}
if t.speech {
cfg.Voices = renderers.LFM3SpeechVoices()
}
return nil
}
func (t lfm3ImportTransform) quantizationType(name string, shape []int32, quantize string) string {
if !strings.HasPrefix(name, t.backbone) {
return ""
}
return GetTensorQuantization(name, shape, quantize)
}
+90
View File
@@ -0,0 +1,90 @@
package create
import (
"slices"
"testing"
"github.com/ollama/ollama/types/model"
)
func TestLFM3VLImportKeepsVisionAndProjector(t *testing.T) {
inv := newInventory(sourceModelConfig{Architectures: []string{"Lfm3VlForConditionalGeneration"}}, map[string]string{})
policy, err := newTensorImportTransform(inv)
if err != nil {
t.Fatal(err)
}
shape := []int32{2048, 2048}
for _, name := range []string{
"model.multi_modal_projector.linear_1.weight",
"model.multi_modal_projector.linear_2.weight",
"model.vision_tower.layers.0.self_attn.q_proj.weight",
} {
if got := policy.quantizationType(name, shape, "mxfp8"); got != "" {
t.Errorf("quantizationType(%q) = %q, want source precision", name, got)
}
}
if got := policy.quantizationType("model.language_model.layers.0.feed_forward.w1.weight", shape, "mxfp8"); got != "mxfp8" {
t.Errorf("language linear quantization = %q, want mxfp8", got)
}
var cfg model.ConfigV2
if err := policy.(interface{ augmentConfig(*model.ConfigV2) error }).augmentConfig(&cfg); err != nil || cfg.Voices != nil {
t.Errorf("VL voices %v (%v), want none", cfg.Voices, err)
}
}
func TestLFM3SpeechImportQuantizesOnlyBackbone(t *testing.T) {
shape := []int32{2048, 2048}
for arch, cases := range map[string]map[string]bool{
"Lfm3OmniForConditionalGeneration": {
"model.language_model.layers.0.feed_forward.w1.weight": true,
"model.audio_encoder.lfm.layers.0.feed_forward.w1.weight": false,
"model.audio_projector.linear_1.weight": false,
"model.depth_decoder.model.layers.0.self_attn.q_proj.weight": false,
"model.multi_modal_projector.linear_1.weight": false,
},
"Lfm3AudioForConditionalGeneration": {
"lfm.model.layers.0.feed_forward.w1.weight": true,
"encoder.lfm.lfm.layers.0.feed_forward.w1.weight": false,
"mlp.model.1.weight": false,
"depthformer.model.layers.0.self_attn.q_proj.weight": false,
},
} {
inv := newInventory(sourceModelConfig{Architectures: []string{arch}}, map[string]string{})
inv.RawConfig = []byte(`{"lfm":{"hidden_size":2048,"max_position_embeddings":128000}}`)
policy, err := newTensorImportTransform(inv)
if err != nil {
t.Fatal(err)
}
var cfg model.ConfigV2
if err := policy.(interface{ augmentConfig(*model.ConfigV2) error }).augmentConfig(&cfg); err != nil {
t.Fatal(err)
}
if !slices.Contains(cfg.Voices, "female-japanese") {
t.Errorf("%s voices %v, want the LFM3 speech voices", arch, cfg.Voices)
}
for name, want := range cases {
if got := policy.quantizationType(name, shape, "mxfp8") != ""; got != want {
t.Errorf("%s %s quantized = %v, want %v", arch, name, got, want)
}
}
}
}
func TestD1ImportQuantizesOnlyBackbone(t *testing.T) {
shape := []int32{2048, 2048}
policy, err := newTensorImportTransform(newInventory(sourceModelConfig{Architectures: []string{"D1Model"}}, map[string]string{}))
if err != nil {
t.Fatal(err)
}
for name, want := range map[string]bool{
"model.language_model.layers.0.feed_forward.w1.weight": true,
"model.vision_tower.layers.0.mlp.fc1.weight": false,
"model.audio_encoder.lfm.layers.0.feed_forward.w1.weight": false,
"model.depth_decoder.model.layers.0.self_attn.q_proj.weight": false,
"model.multi_modal_projector.linear_1.weight": false,
} {
if got := policy.quantizationType(name, shape, "mxfp8") != ""; got != want {
t.Errorf("%s quantized = %v, want %v", name, got, want)
}
}
}
+85
View File
@@ -0,0 +1,85 @@
package create
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"github.com/ollama/ollama/fs/safetensors"
)
// lfm3CodecPrefix names the imported speech codec tensors; the runner loads
// the codec from this prefix and the subfolder's config.json.
const lfm3CodecPrefix = "codec."
// lfm3CodecDirs maps the LFM3 speech-output architectures to the subfolder
// holding their LiquidCodec checkpoint.
var lfm3CodecDirs = map[string]string{
"Lfm3OmniForConditionalGeneration": "audio_tokenizer",
"Lfm3AudioForConditionalGeneration": "audio_tokenizer",
}
// lfm3CodecDir returns the codec subfolder of dir's checkpoint, or "" when
// the checkpoint does not speak.
func lfm3CodecDir(dir string) (string, error) {
if _, err := os.Stat(filepath.Join(dir, "config.json")); errors.Is(err, os.ErrNotExist) {
return "", nil
} else if err != nil {
return "", err
}
cfg, _, err := readSourceModelConfig(dir)
if err != nil {
return "", err
}
return lfm3CodecDirs[cfg.Architecture()], nil
}
// lfm3CodecFile is the codec subfolder's file name, slash-separated as
// transfer lists and manifest config names are.
func lfm3CodecFile(dir, codecDir, name string) (string, error) {
file := path.Join(codecDir, name)
info, err := os.Stat(filepath.Join(dir, filepath.FromSlash(file)))
if err != nil {
return "", fmt.Errorf("LFM3 speech output requires %s: %w", file, err)
}
if !info.Mode().IsRegular() {
return "", fmt.Errorf("LFM3 speech codec %s must be a regular file", file)
}
return file, nil
}
// prepareLFM3SpeechInventory adds the codec checkpoint, kept in its own
// subfolder by the publisher, under lfm3CodecPrefix.
func prepareLFM3SpeechInventory(inv Inventory) (Inventory, error) {
codecDir := lfm3CodecDirs[inv.Config.Architecture()]
if codecDir == "" {
return inv, nil
}
file, err := lfm3CodecFile(inv.Dir, codecDir, "model.safetensors")
if err != nil {
return Inventory{}, err
}
reader, err := safetensors.OpenForExtraction(filepath.Join(inv.Dir, filepath.FromSlash(file)))
if err != nil {
return Inventory{}, fmt.Errorf("open LFM3 speech codec: %w", err)
}
defer reader.Close()
names := reader.ListTensors()
if len(names) == 0 {
return Inventory{}, fmt.Errorf("LFM3 speech codec %s has no tensors", file)
}
for _, name := range names {
td, err := reader.GetTensor(name)
if err != nil {
return Inventory{}, fmt.Errorf("read LFM3 speech codec tensor %s: %w", name, err)
}
key := lfm3CodecPrefix + name
if inv.Has(key) {
return Inventory{}, fmt.Errorf("LFM3 checkpoint already defines %s", key)
}
inv.Tensors[key] = SourceTensor{Name: name, Dtype: td.Dtype, Shape: td.Shape, File: file}
}
return inv, nil
}
+114
View File
@@ -0,0 +1,114 @@
package create
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"
st "github.com/ollama/ollama/fs/safetensors"
)
func writeLFM3AudioSource(t *testing.T, dir string) {
t.Helper()
writeConfigJSON(t, dir, `{"architectures":["Lfm3AudioForConditionalGeneration"],"model_type":"lfm3_audio","lfm":{"hidden_size":2048,"max_position_embeddings":128000}}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("lfm.model.layers.0.feed_forward.w1.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),
st.NewTensorDataFromBytes("depth_linear.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),
})
codec := filepath.Join(dir, "audio_tokenizer")
if err := os.Mkdir(codec, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(codec, "config.json"), []byte(`{"model_type":"liquid_codec"}`), 0o644); err != nil {
t.Fatal(err)
}
createTestSafetensors(t, filepath.Join(codec, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("decoder.lin.weight", "BF16", []int32{64, 64}, make([]byte, 64*64*2)),
st.NewTensorDataFromBytes("decoder.istft.window", "F32", []int32{4}, make([]byte, 16)),
})
}
func TestLFM3SpeechImportsCodecSubfolder(t *testing.T) {
dir := t.TempDir()
writeLFM3AudioSource(t, dir)
files, err := SafetensorsWeightFiles(dir)
if err != nil || !slices.Contains(files, "audio_tokenizer/model.safetensors") {
t.Fatalf("weight files = %v, %v", files, err)
}
configs, err := SafetensorsConfigFiles(dir)
if err != nil || !slices.Contains(configs, "audio_tokenizer/config.json") {
t.Fatalf("config files = %v, %v", configs, err)
}
inv, err := ReadInventory(dir)
if err != nil {
t.Fatal(err)
}
if inv, err = prepareLFM3SpeechInventory(inv); err != nil {
t.Fatal(err)
}
if got := inv.Tensors["codec.decoder.lin.weight"]; got.Name != "decoder.lin.weight" || got.File != "audio_tokenizer/model.safetensors" {
t.Fatalf("codec tensor = %+v", got)
}
policy, err := newTensorImportTransform(inv)
if err != nil {
t.Fatal(err)
}
specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "mxfp8"}, policy)
if err != nil {
t.Fatal(err)
}
for _, spec := range specs {
for _, ts := range spec.Tensors {
if want := strings.HasPrefix(ts.Name, "lfm.model."); (ts.Quantize != "") != want {
t.Errorf("%s quantize = %q", ts.Name, ts.Quantize)
}
}
}
store := newCaptureStore()
var got ManifestInfo
err = Create(t.Context(), "lfm3-audio-test", dir, testPipelineOptions(), store, func(_ context.Context, _ string, info ManifestInfo) error {
got = info
return nil
}, func(string) {})
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"codec.decoder.lin.weight", "codec.decoder.istft.window", "audio_tokenizer/config.json"} {
if store.blobs[name] == nil {
t.Errorf("missing blob %s: %v", name, store.names())
}
}
if !slices.Contains(got.ModelConfig.Capabilities, "speech") || !slices.Contains(got.ModelConfig.Capabilities, "completion") {
t.Errorf("capabilities = %v", got.ModelConfig.Capabilities)
}
// The language model config is nested under "lfm"; the manifest records it.
if !slices.Contains(got.ModelConfig.Voices, "default") || !slices.Contains(got.ModelConfig.Voices, "male-french") {
t.Errorf("voices %v, want the LFM3 speech voices", got.ModelConfig.Voices)
}
if got.ModelConfig.ContextLen != 128000 || got.ModelConfig.EmbedLen != 2048 {
t.Errorf("context length %d, embedding length %d, want 128000 and 2048", got.ModelConfig.ContextLen, got.ModelConfig.EmbedLen)
}
}
func TestLFM3SpeechRequiresCodec(t *testing.T) {
dir := t.TempDir()
writeLFM3AudioSource(t, dir)
if err := os.Remove(filepath.Join(dir, "audio_tokenizer", "model.safetensors")); err != nil {
t.Fatal(err)
}
if _, err := SafetensorsWeightFiles(dir); err == nil || !strings.Contains(err.Error(), "audio_tokenizer/model.safetensors") {
t.Fatalf("transfer list error = %v", err)
}
store := newCaptureStore()
err := Create(t.Context(), "lfm3-audio-test", dir, testPipelineOptions(), store,
func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
if err == nil || !strings.Contains(err.Error(), "audio_tokenizer/model.safetensors") || len(store.blobs) != 0 {
t.Fatalf("import error = %v; blobs = %v", err, store.names())
}
}
+111 -33
View File
@@ -15,30 +15,88 @@ import (
// inferSafetensorsConfig derives the manifest config shared by local and
// server-side safetensors imports. Explicit parser and renderer values take
// precedence over the inferred values.
// precedence when compatible with the source model's scoring format.
func inferSafetensorsConfig(modelDir string, cfg sourceModelConfig, parserOverride, rendererOverride string) (model.ConfigV2, error) {
chatTemplate, err := readChatTemplateStrict(modelDir)
if err != nil {
return model.ConfigV2{}, err
}
parserName, err := parserNameForConfig(modelDir, cfg, chatTemplate)
if err != nil {
return model.ConfigV2{}, err
var parserName, rendererName, sourceDecisionRenderer string
var decisionModel, decisionVision bool
switch cfg.Architecture() {
case "Qwen3_5Model":
hasSidecar, err := hasPplxSidecar(modelDir)
if err != nil {
return model.ConfigV2{}, err
}
if !hasSidecar {
return model.ConfigV2{}, fmt.Errorf("Qwen3_5Model requires decision sidecars")
}
format, err := qwenDecisionFormat(modelDir)
if err != nil {
return model.ConfigV2{}, err
}
rendererName = "pplx"
if format == d3FormatID {
rendererName = "d3"
}
sourceDecisionRenderer = rendererName
decisionModel = true
decisionVision = cfg.VisionConfig != nil
case "ClefForDecision":
rendererName, decisionModel = "clef", true
decisionVision = cfg.VisionConfig != nil
case "StrandsDeciderForDecision":
rendererName, decisionModel = "strands", true
case "KevForDecision":
rendererName, decisionModel = "kev", true
// The staged architecture ID selects AutoTrust's decision runner for the
// publisher's Qwen3.5 checkpoint.
case "AutoTrustDecision":
rendererName, decisionModel = "autotrust-decision", true
decisionVision = cfg.VisionConfig != nil
case "LayaForDecision":
decisionModel = true
case "D1Model":
rendererName, decisionModel, decisionVision = "d1", true, true
default:
parserName, err = parserNameForConfig(modelDir, cfg, chatTemplate)
if err != nil {
return model.ConfigV2{}, err
}
rendererName, err = rendererNameForConfig(modelDir, cfg, chatTemplate)
if err != nil {
return model.ConfigV2{}, err
}
}
if parserOverride != "" {
parserName = parserOverride
}
rendererName, err := rendererNameForConfig(modelDir, cfg, chatTemplate)
if err != nil {
return model.ConfigV2{}, err
}
if rendererOverride != "" {
rendererName = rendererOverride
}
if cfg.Architecture() == "Qwen3_5Model" && (rendererName != sourceDecisionRenderer || parserName != "") {
return model.ConfigV2{}, fmt.Errorf("Qwen3.5 decision models require renderer %q and no parser (got renderer %q, parser %q)", sourceDecisionRenderer, rendererName, parserName)
}
capabilities := inferSafetensorsCapabilitiesFromConfig(cfg, chatTemplate, parserName)
var capabilities []string
if decisionModel {
capabilities = []string{"decision"}
if decisionVision {
capabilities = append(capabilities, "vision")
}
if cfg.Architecture() == "D1Model" && cfg.ModelType == "lfm3_omni" {
capabilities = append(capabilities, "audio")
}
} else if isPhononArchitecture(cfg.Architecture()) {
capabilities = []string{"speech"}
} else {
capabilities = inferCompletionCapabilitiesFromConfig(cfg, chatTemplate, parserName)
}
if rendererName == "lfm3-omni" || rendererName == "lfm3-audio" {
capabilities = lfm3AudioCapabilities(capabilities)
}
generationDefaults, err := readHFGenerationDefaults(modelDir)
if err != nil {
return model.ConfigV2{}, err
@@ -97,17 +155,7 @@ func readChatTemplateStrict(modelDir string) (string, error) {
return "", fmt.Errorf("read %s: %w", chatTemplatePath, err)
}
func inferSafetensorsCapabilitiesFromConfig(cfg sourceModelConfig, chatTemplate, parserName string) []string {
if cfg.Architecture() == "ClefForDecision" {
capabilities := []string{"decision"}
if cfg.VisionConfig != nil {
capabilities = append(capabilities, "vision")
}
return capabilities
}
if cfg.Architecture() == "LayaForDecision" || cfg.Architecture() == "StrandsDeciderForDecision" || cfg.Architecture() == "KevForDecision" {
return []string{"decision"}
}
func inferCompletionCapabilitiesFromConfig(cfg sourceModelConfig, chatTemplate, parserName string) []string {
capabilities := []string{"completion"}
caps := detectCapabilitiesFromConfig(cfg, chatTemplate)
@@ -195,7 +243,11 @@ func lagunaRendererParserNameFromTemplate(modelDir, chatTemplate string) (string
return "laguna", nil
}
func nemotronRendererParserNameFromTemplate(modelDir, chatTemplate string) (string, error) {
// Nemotron 3.5 replaces inline /think toggles with request-controlled thinking
// and adds a reasoning-effort marker. The architecture names do not distinguish
// these prompt formats, but both use the same thinking/tool-call output syntax
// and therefore the nemotron-3-nano parser.
func nemotronRendererNameFromTemplate(modelDir, chatTemplate string) (string, error) {
const v35Marker = "{reasoning effort: efficient}"
chatTemplatePath := filepath.Join(modelDir, "chat_template.jinja")
@@ -218,9 +270,6 @@ func sourceConfigIdentifiers(cfg sourceModelConfig) []string {
}
func parserNameForConfig(modelDir string, cfg sourceModelConfig, chatTemplate string) (string, error) {
if cfg.Architecture() == "ClefForDecision" || cfg.Architecture() == "StrandsDeciderForDecision" || cfg.Architecture() == "KevForDecision" {
return "", nil
}
for _, id := range sourceConfigIdentifiers(cfg) {
name, err := parserNameForIdentifier(modelDir, id, chatTemplate)
if err != nil || name != "" {
@@ -233,6 +282,10 @@ func parserNameForConfig(modelDir string, cfg sourceModelConfig, chatTemplate st
func parserNameForIdentifier(modelDir, s, chatTemplate string) (string, error) {
s = strings.ToLower(s)
switch {
case strings.Contains(s, "flint"):
return "flint", nil
case strings.HasPrefix(s, "lfm3"):
return lfm3RendererParserName(s), nil
case strings.HasPrefix(s, "museglimmer") || s == "muse_glimmer":
return "glimmer", nil
case strings.Contains(s, "laguna"):
@@ -250,7 +303,7 @@ func parserNameForIdentifier(modelDir, s, chatTemplate string) (string, error) {
case strings.Contains(s, "qwen3"):
return "qwen3", nil
case strings.Contains(s, "nemotronh") || strings.Contains(s, "nemotron_h"):
return nemotronRendererParserNameFromTemplate(modelDir, chatTemplate)
return "nemotron-3-nano", nil
default:
return "", nil
}
@@ -269,12 +322,10 @@ func rendererNameForConfig(modelDir string, cfg sourceModelConfig, chatTemplate
func rendererNameForIdentifier(modelDir, s, chatTemplate string) (string, error) {
s = strings.ToLower(s)
switch {
case s == "kevfordecision":
return "kev", nil
case s == "strandsdeciderfordecision":
return "strands", nil
case s == "cleffordecision":
return "clef", nil
case strings.Contains(s, "flint"):
return "flint", nil
case strings.HasPrefix(s, "lfm3"):
return lfm3RendererParserName(s), nil
case strings.HasPrefix(s, "museglimmer") || s == "muse_glimmer":
return "glimmer", nil
case strings.Contains(s, "laguna"):
@@ -293,9 +344,36 @@ func rendererNameForIdentifier(modelDir, s, chatTemplate string) (string, error)
return qwen35RendererNameFromTemplate(chatTemplate), nil
case strings.Contains(s, "qwen3"):
return "qwen3-coder", nil
case s == "nemotronh_omni_reasoning_v3":
return "nemotron-3.5-super", nil
case strings.Contains(s, "nemotronh") || strings.Contains(s, "nemotron_h"):
return nemotronRendererParserNameFromTemplate(modelDir, chatTemplate)
return nemotronRendererNameFromTemplate(modelDir, chatTemplate)
default:
return "", nil
}
}
// lfm3RendererParserName maps an LFM3 identifier to its template branch.
func lfm3RendererParserName(s string) string {
switch {
case strings.Contains(s, "omni"):
return "lfm3-omni"
case strings.Contains(s, "audio"):
return "lfm3-audio"
default:
return "lfm3"
}
}
// lfm3AudioCapabilities marks LFM3 Audio and Omni as audio-input models served
// without thinking (their templates mention <think>) that also speak through
// /v1/audio/speech.
func lfm3AudioCapabilities(caps []string) []string {
out := []string{}
for _, c := range caps {
if c != "audio" && c != "thinking" {
out = append(out, c)
}
}
return append(out, "audio", "speech")
}
+101 -8
View File
@@ -93,13 +93,14 @@ func TestInferSafetensorsConfigIncludesGenerationDefaults(t *testing.T) {
func TestInferSafetensorsConfigFamilies(t *testing.T) {
tests := []struct {
name string
config string
chatTemplate string
standalone bool
wantParser string
wantRenderer string
wantCaps []string
name string
config string
chatTemplate string
standalone bool
decisionSidecar bool
wantParser string
wantRenderer string
wantCaps []string
}{
{
name: "qwen3",
@@ -107,6 +108,41 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
wantParser: "qwen3",
wantRenderer: "qwen3-coder",
},
{
name: "lfm3 text architecture",
config: `{"architectures":["Lfm3ForCausalLM"],"model_type":"lfm3"}`,
wantParser: "lfm3",
wantRenderer: "lfm3",
wantCaps: []string{"completion", "tools", "thinking"},
},
{
name: "lfm3 vision architecture",
config: `{"architectures":["Lfm3VlForConditionalGeneration"],"model_type":"lfm3_vl","vision_config":{}}`,
wantParser: "lfm3",
wantRenderer: "lfm3",
wantCaps: []string{"completion", "vision", "tools", "thinking"},
},
{
name: "lfm3 omni architecture",
config: `{"architectures":["Lfm3OmniForConditionalGeneration"],"model_type":"lfm3_omni","vision_config":{}}`,
wantParser: "lfm3-omni",
wantRenderer: "lfm3-omni",
wantCaps: []string{"completion", "vision", "tools", "audio", "speech"},
},
{
name: "lfm3 audio architecture",
config: `{"architectures":["Lfm3AudioForConditionalGeneration"],"model_type":"lfm3_audio"}`,
wantParser: "lfm3-audio",
wantRenderer: "lfm3-audio",
wantCaps: []string{"completion", "tools", "audio", "speech"},
},
{
name: "lfm3 model type fallback",
config: `{"model_type":"lfm3"}`,
wantParser: "lfm3",
wantRenderer: "lfm3",
wantCaps: []string{"completion", "tools", "thinking"},
},
{
name: "qwen3.5 text",
config: `{"architectures":["Qwen3_5ForCausalLM"],"model_type":"qwen3"}`,
@@ -121,6 +157,20 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
wantRenderer: "qwen3.5",
wantCaps: []string{"completion", "vision", "tools", "thinking"},
},
{
name: "pplx decision text",
config: `{"architectures":["Qwen3_5Model"]}`,
decisionSidecar: true,
wantRenderer: "pplx",
wantCaps: []string{"decision"},
},
{
name: "pplx decision vision",
config: `{"architectures":["Qwen3_5Model"],"vision_config":{}}`,
decisionSidecar: true,
wantRenderer: "pplx",
wantCaps: []string{"decision", "vision"},
},
{
name: "qwen3.8 embedded template",
config: `{"architectures":["Qwen3_5ForConditionalGeneration"]}`,
@@ -182,7 +232,7 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
config: `{"architectures":["NemotronHForCausalLM"],"model_type":"nemotron_h"}`,
chatTemplate: "{reasoning effort: efficient}",
standalone: true,
wantParser: "nemotron-3.5-nano",
wantParser: "nemotron-3-nano",
wantRenderer: "nemotron-3.5-nano",
},
{
@@ -192,6 +242,13 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
wantRenderer: "nemotron-3-nano",
wantCaps: []string{"completion", "vision", "audio", "tools", "thinking"},
},
{
name: "nemotron super published architecture",
config: `{"architectures":["NemotronH_Omni_Reasoning_V3"],"model_type":"nemotron_h_omni","vision_config":{},"sound_config":null,"llm_config":{"model_type":"nemotron_h"}}`,
wantParser: "nemotron-3-nano",
wantRenderer: "nemotron-3.5-super",
wantCaps: []string{"completion", "vision", "tools", "thinking"},
},
{
name: "deepseek",
config: `{"architectures":["DeepseekV3ForCausalLM"]}`,
@@ -208,6 +265,18 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
name: "llama",
config: `{"architectures":["LlamaForCausalLM"]}`,
},
{
name: "flint",
config: `{"architectures":["FlintForCausalLM"],"model_type":"flint"}`,
wantParser: "flint",
wantRenderer: "flint",
wantCaps: []string{"completion", "tools", "thinking"},
},
{
name: "phonon",
config: `{"architectures":["GradiumPhononTTSForConditionalGeneration"],"model_type":"gradium_phonon_tts"}`,
wantCaps: []string{"speech"},
},
{
name: "nested llm config",
config: `{"model_type":"nemotron_h_omni","llm_config":{"model_type":"nemotron_h"}}`,
@@ -222,6 +291,11 @@ func TestInferSafetensorsConfigFamilies(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "config.json"), []byte(tt.config), 0o600); err != nil {
t.Fatal(err)
}
if tt.decisionSidecar {
if err := os.WriteFile(filepath.Join(dir, "decision_config.json"), []byte(`{}`), 0o600); err != nil {
t.Fatal(err)
}
}
if tt.chatTemplate != "" {
name := "tokenizer_config.json"
data, err := json.Marshal(map[string]string{"chat_template": tt.chatTemplate})
@@ -295,3 +369,22 @@ func TestStrandsDecisionMetadata(t *testing.T) {
t.Fatalf("unexpected Strands metadata: %+v", got)
}
}
func TestD1DecisionMetadata(t *testing.T) {
for _, tc := range []struct {
modelType string
want []string
}{
{"lfm3_vl", []string{"decision", "vision"}},
{"lfm3_omni", []string{"decision", "vision", "audio"}},
} {
cfg := sourceModelConfig{Architectures: []string{"D1Model"}, ModelType: tc.modelType}
got, err := inferSafetensorsConfig(t.TempDir(), cfg, "", "")
if err != nil {
t.Fatal(err)
}
if got.Parser != "" || got.Renderer != "d1" || !slices.Equal(got.Capabilities, tc.want) {
t.Fatalf("%s: unexpected d1 metadata: %+v", tc.modelType, got)
}
}
}
+5
View File
@@ -17,6 +17,11 @@ var (
return err
}
if mlx.GPUIsAvailable() {
if mlx.CUDAIsAvailable() {
if err := mlx.CheckCUDADeviceSupport(); err != nil {
return err
}
}
mlx.SetDefaultDeviceGPU()
}
return nil
+19 -2
View File
@@ -12,9 +12,11 @@ type nemotronHImportTransform struct {
func newNemotronHImportTransform(rawConfig json.RawMessage) (quantizePolicy, error) {
var cfg struct {
NumHiddenLayers int `json:"num_hidden_layers"`
NumHiddenLayers int `json:"num_hidden_layers"`
LayersBlockType []string `json:"layers_block_type"`
LLMConfig struct {
NumHiddenLayers int `json:"num_hidden_layers"`
NumHiddenLayers int `json:"num_hidden_layers"`
LayersBlockType []string `json:"layers_block_type"`
} `json:"llm_config"`
}
if err := json.Unmarshal(rawConfig, &cfg); err != nil {
@@ -24,12 +26,19 @@ func newNemotronHImportTransform(rawConfig json.RawMessage) (quantizePolicy, err
if numLayers == 0 {
numLayers = cfg.LLMConfig.NumHiddenLayers
}
if numLayers == 0 {
numLayers = len(cfg.LayersBlockType)
}
if numLayers == 0 {
numLayers = len(cfg.LLMConfig.LayersBlockType)
}
return nemotronHImportTransform{numLayers: numLayers}, nil
}
// Nemotron's modality tower names do not match the shared predicates.
func nemotronHIsVisionTower(name string) bool {
return strings.HasPrefix(name, "vision_model.") ||
strings.HasPrefix(name, "vision_projector.") ||
strings.HasPrefix(name, "mlp1.")
}
@@ -44,6 +53,8 @@ func nemotronHShouldKeepBF16ForDirectNonAffine(name string) bool {
return true
case strings.HasSuffix(name, ".mixer.conv1d.weight"):
return true
case strings.HasSuffix(name, ".mixer.fc1_latent_proj.weight"), strings.HasSuffix(name, ".mixer.fc2_latent_proj.weight"):
return true
default:
return false
}
@@ -64,6 +75,12 @@ func (t nemotronHImportTransform) promoteSensitive(name string) bool {
if nemotronHIsAttentionProjection(name) {
return true
}
// The detached MTP module is a one-layer assistant, not layer zero of the
// target stack. Do not apply the target's early/late promotion schedule to
// its expert projections.
if strings.HasPrefix(name, "mtp.") || strings.HasPrefix(name, "language_model.mtp.") {
return false
}
layerIdx := layerIndex(name)
return layerIdx < 0 || useMoreBits(layerIdx, t.numLayers)
}
+51 -13
View File
@@ -7,21 +7,55 @@ import (
)
func TestNemotronHImportTransformRegistration(t *testing.T) {
inv := Inventory{
Config: sourceModelConfig{Architectures: []string{"NemotronH_Nano_Omni_Reasoning_V3"}},
RawConfig: json.RawMessage(`{"architectures":["NemotronH_Nano_Omni_Reasoning_V3"],"llm_config":{"num_hidden_layers":52}}`),
}
for _, tt := range []struct {
name string
rawConfig string
want int
}{
{"nested layer count", `{"architectures":["NemotronH_Nano_Omni_Reasoning_V3"],"llm_config":{"num_hidden_layers":52}}`, 52},
{"layer block types", `{"architectures":["NemotronHForCausalLM"],"layers_block_type":["linear_attention","moe","linear_attention"]}`, 3},
{"published super config", `{"architectures":["NemotronH_Omni_Reasoning_V3"],"llm_config":{"layers_block_type":["mamba","moe","attention"]}}`, 3},
} {
t.Run(tt.name, func(t *testing.T) {
inv := Inventory{
RawConfig: json.RawMessage(tt.rawConfig),
}
if err := json.Unmarshal(inv.RawConfig, &inv.Config); err != nil {
t.Fatal(err)
}
policy, err := newTensorImportTransform(inv)
if err != nil {
t.Fatalf("newTensorImportTransform() error = %v", err)
policy, err := newTensorImportTransform(inv)
if err != nil {
t.Fatalf("newTensorImportTransform() error = %v", err)
}
transform, ok := policy.(nemotronHImportTransform)
if !ok {
t.Fatalf("newTensorImportTransform() = %T, want nemotronHImportTransform", policy)
}
if transform.numLayers != tt.want {
t.Fatalf("numLayers = %d, want %d", transform.numLayers, tt.want)
}
})
}
transform, ok := policy.(nemotronHImportTransform)
if !ok {
t.Fatalf("newTensorImportTransform() = %T, want nemotronHImportTransform", policy)
}
if transform.numLayers != 52 {
t.Fatalf("numLayers = %d, want 52", transform.numLayers)
}
func TestNemotronHImportTransformDoesNotApplyTargetLayerScheduleToMTP(t *testing.T) {
policy := nemotronHImportTransform{numLayers: 52}
shape := []int32{128, 128}
for _, tt := range []struct {
name string
want string
}{
{"language_model.backbone.layers.0.mixer.experts.down_proj.weight", "mxfp8"},
{"mtp.layers.0.mixer.experts.down_proj.weight", "nvfp4"},
{"mtp.layers.0.mixer.q_proj.weight", "mxfp8"},
{"language_model.mtp.layers.1.mixer.experts.down_proj.weight", "nvfp4"},
{"language_model.mtp.layers.0.mixer.q_proj.weight", "mxfp8"},
} {
if got := policy.quantizationType(tt.name, shape, "nvfp4"); got != tt.want {
t.Errorf("quantizationType(%q) = %q, want %q", tt.name, got, tt.want)
}
}
}
@@ -93,6 +127,9 @@ func TestNemotronHImportTransformQuantizationPolicy(t *testing.T) {
{"middle dense down_proj stays nvfp4", "language_model.backbone.layers.16.mixer.down_proj.weight", []int32{32, 32}, "nvfp4", "nvfp4"},
{"router gate kept bf16", "language_model.backbone.layers.2.mixer.gate.weight", []int32{8, 32}, "nvfp4", ""},
{"conv kept bf16", "language_model.backbone.layers.0.mixer.conv1d.weight", []int32{96, 32}, "nvfp4", ""},
{"latent input kept bf16", "language_model.backbone.layers.1.mixer.fc1_latent_proj.weight", []int32{1024, 4096}, "nvfp4", ""},
{"latent output kept bf16", "language_model.backbone.layers.1.mixer.fc2_latent_proj.weight", []int32{4096, 1024}, "mxfp8", ""},
{"draft latent input kept bf16", "language_model.mtp.layers.1.mixer.fc1_latent_proj.weight", []int32{1024, 4096}, "int4", ""},
{"embedding promoted to mxfp8", "language_model.backbone.embeddings.weight", []int32{4096, 32}, "mxfp8", "mxfp8"},
{"embedding promoted to mxfp8 from nvfp4", "language_model.backbone.embeddings.weight", []int32{4096, 32}, "nvfp4", "mxfp8"},
{"embedding promoted to int8 from int4", "language_model.backbone.embeddings.weight", []int32{4096, 64}, "int4", "int8"},
@@ -104,6 +141,7 @@ func TestNemotronHImportTransformQuantizationPolicy(t *testing.T) {
{"lm head unaligned kept bf16", "language_model.lm_head.weight", []int32{4096, 31}, "nvfp4", ""},
{"vision kept bf16", "vision_model.radio_model.model.patch_generator.proj.weight", []int32{32, 32}, "nvfp4", ""},
{"vision projector kept bf16", "mlp1.0.weight", []int32{32, 32}, "nvfp4", ""},
{"vision final norm kept bf16", "vision_projector.vision_final_layernorm.weight", []int32{1280}, "nvfp4", ""},
{"sound encoder kept bf16", "sound_encoder.encoder.layers.0.self_attn.q_proj.weight", []int32{32, 32}, "nvfp4", ""},
{"sound projector kept bf16", "sound_projection.adapter.weight", []int32{32, 32}, "nvfp4", ""},
}
+85
View File
@@ -0,0 +1,85 @@
package create
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"slices"
"strings"
"github.com/ollama/ollama/fs/safetensors"
)
const gradiumPhononArchitecture = "GradiumPhononTTSForConditionalGeneration"
func isPhononArchitecture(architecture string) bool {
return architecture == gradiumPhononArchitecture
}
// The publisher keeps its default speaker latents beside the model weights
// and any other voices in voices/NAME.safetensors. Import each as a separate
// tensor so the runner can project them with the checkpoint's own speaker
// projection at load time.
func prepareGradiumPhononInventory(inv Inventory) (Inventory, error) {
if !inv.Has("flow_lm.condition_provider.conditioners.speaker_wavs.output_proj.weight") {
return Inventory{}, fmt.Errorf("Phonon checkpoint has no speaker projection")
}
files, err := phononVoiceFiles(inv.Dir)
if err != nil {
return Inventory{}, err
}
if err := addPhononVoice(inv, "default", "default-voice.safetensors"); err != nil {
return Inventory{}, err
}
for _, file := range files {
if err := addPhononVoice(inv, strings.TrimSuffix(path.Base(file), ".safetensors"), file); err != nil {
return Inventory{}, err
}
}
return inv, nil
}
func addPhononVoice(inv Inventory, name, file string) error {
reader, err := safetensors.OpenForExtraction(filepath.Join(inv.Dir, file))
if err != nil {
return fmt.Errorf("open Phonon %s voice: %w", name, err)
}
defer reader.Close()
if names := reader.ListTensors(); !slices.Equal(names, []string{"speaker_wavs"}) {
return fmt.Errorf("Phonon %s voice must contain only speaker_wavs, got %v", name, names)
}
voice, err := reader.GetTensor("speaker_wavs")
if err != nil {
return fmt.Errorf("read Phonon %s voice: %w", name, err)
}
if voice.Dtype != "F32" || len(voice.Shape) != 3 || voice.Shape[0] != 1 || voice.Shape[1] != 512 || voice.Shape[2] <= 0 {
return fmt.Errorf("unsupported Phonon %s voice: %s %v", name, voice.Dtype, voice.Shape)
}
if inv.Has("voices." + name) {
return fmt.Errorf("Phonon checkpoint already defines voices.%s", name)
}
inv.Tensors["voices."+name] = SourceTensor{
Name: "speaker_wavs", Dtype: voice.Dtype, Shape: voice.Shape, File: file,
}
return nil
}
// phononVoiceFiles lists a checkpoint's voices/NAME.safetensors files.
func phononVoiceFiles(dir string) ([]string, error) {
entries, err := os.ReadDir(filepath.Join(dir, "voices"))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var files []string
for _, entry := range entries {
if name, ok := strings.CutSuffix(entry.Name(), ".safetensors"); ok && name != "" && !entry.IsDir() {
files = append(files, path.Join("voices", entry.Name()))
}
}
return files, nil
}
+88
View File
@@ -0,0 +1,88 @@
package create
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"
st "github.com/ollama/ollama/fs/safetensors"
)
func writeGradiumPhononSource(t *testing.T, dir string, voiceShape []int32) {
t.Helper()
writeConfigJSON(t, dir, `{"architectures":["GradiumPhononTTSForConditionalGeneration"],"model_type":"gradium_phonon_tts"}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("flow_lm.condition_provider.conditioners.speaker_wavs.output_proj.weight", "BF16", []int32{512, 512}, make([]byte, 512*512*2)),
})
voiceBytes := 4
for _, size := range voiceShape {
voiceBytes *= int(size)
}
createTestSafetensors(t, filepath.Join(dir, "default-voice.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("speaker_wavs", "F32", voiceShape, make([]byte, voiceBytes)),
})
}
func TestGradiumPhononImportsPublisherVoices(t *testing.T) {
dir := t.TempDir()
writeGradiumPhononSource(t, dir, []int32{1, 512, 2})
if err := os.Mkdir(filepath.Join(dir, "voices"), 0o755); err != nil {
t.Fatal(err)
}
createTestSafetensors(t, filepath.Join(dir, "voices", "Zoey.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("speaker_wavs", "F32", []int32{1, 512, 2}, make([]byte, 4*512*2)),
})
files, err := SafetensorsWeightFiles(dir)
if err != nil || !slices.Contains(files, "default-voice.safetensors") || !slices.Contains(files, "voices/Zoey.safetensors") {
t.Fatalf("weight files = %v, %v", files, err)
}
store := newCaptureStore()
var got ManifestInfo
err = Create(t.Context(), "phonon-test", dir, testPipelineOptions(), store, func(_ context.Context, _ string, info ManifestInfo) error {
got = info
return nil
}, func(string) {})
if err != nil {
t.Fatal(err)
}
if !slices.Equal(got.ModelConfig.Capabilities, []string{"speech"}) || got.ModelConfig.Requires != phononMinOllamaVersion {
t.Fatalf("model config = %+v", got.ModelConfig)
}
if store.blobs["voices.default"] == nil || store.blobs["voices.Zoey"] == nil {
t.Fatalf("missing voice blobs: %v", store.names())
}
}
func TestGradiumPhononRejectsBadVoiceBeforeWriting(t *testing.T) {
dir := t.TempDir()
writeGradiumPhononSource(t, dir, []int32{1, 256, 2})
store := newCaptureStore()
err := Create(t.Context(), "phonon-test", dir, testPipelineOptions(), store,
func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
if err == nil || !strings.Contains(err.Error(), "unsupported Phonon default voice") || len(store.blobs) != 0 {
t.Fatalf("import error = %v; blobs = %v", err, store.names())
}
if err := os.Remove(filepath.Join(dir, "default-voice.safetensors")); err != nil {
t.Fatal(err)
}
if _, err := SafetensorsWeightFiles(dir); err == nil || !strings.Contains(err.Error(), "requires default-voice.safetensors") {
t.Fatalf("missing voice transfer error = %v", err)
}
}
func TestPrereleasePhononImportRejected(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["Phonon"],"model_type":"phonon"}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("flow_lm.bos_emb", "F32", []int32{4}, make([]byte, 16)),
})
store := newCaptureStore()
err := Create(t.Context(), "phonon-legacy", dir, PipelineOptions{}, store,
func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
if err == nil || !strings.Contains(err.Error(), "unsupported MLX architecture") || len(store.blobs) != 0 {
t.Fatalf("import error = %v; blobs = %v", err, store.names())
}
}
+36
View File
@@ -10,6 +10,8 @@ import (
"path/filepath"
"strings"
"golang.org/x/mod/semver"
"github.com/ollama/ollama/types/model"
)
@@ -40,12 +42,36 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if err != nil {
return fmt.Errorf("read model: %w", err)
}
if inv.Config.Architecture() == gradiumPhononArchitecture {
inv, err = prepareGradiumPhononInventory(inv)
if err != nil {
return err
}
}
inv, err = prepareLFM3SpeechInventory(inv)
if err != nil {
return err
}
if opts.Renderer == "clef" {
inv, err = prepareClefInventory(inv)
if err != nil {
return err
}
}
if inv.Config.Architecture() == "Qwen3_5Model" {
format, formatErr := qwenDecisionFormat(modelDir)
if formatErr != nil {
return formatErr
}
if format == d3FormatID {
inv, err = prepareD3Inventory(inv)
} else {
inv, err = preparePplxInventory(inv)
}
if err != nil {
return err
}
}
modelConfig, err := inferSafetensorsConfig(modelDir, inv.Config, opts.Parser, opts.Renderer)
if err != nil {
return err
@@ -56,6 +82,10 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
return err
}
}
// Older releases can't run Phonon, whatever the Modelfile or client says.
if isPhononArchitecture(inv.Config.Architecture()) && semver.Compare("v"+modelConfig.Requires, "v"+phononMinOllamaVersion) < 0 {
modelConfig.Requires = phononMinOllamaVersion
}
if err := validateMLXSource(inv.Config, false, opts.Validation); err != nil {
return err
}
@@ -65,6 +95,9 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
if inv.Config.Architecture() == "LayaForDecision" && opts.Quantize != "" {
return fmt.Errorf("Laya currently requires unquantized weights")
}
if isPhononArchitecture(inv.Config.Architecture()) && opts.Quantize != "" {
return fmt.Errorf("Phonon currently requires unquantized weights")
}
class, err := Classify(inv, opts.Quantize)
if err != nil {
return err
@@ -75,6 +108,9 @@ func Create(ctx context.Context, modelName, modelDir string, opts PipelineOption
return err
}
}
if class.Kind == SourceFloat && class.Quantize == "" && modelConfig.FileType == "" {
modelConfig.FileType = sourceFloatFileType(inv)
}
policy, err := newTensorImportTransform(inv)
if err != nil {
return fmt.Errorf("build quantization policy for %q: %w", inv.Config.Architecture(), err)
+20 -2
View File
@@ -59,8 +59,8 @@ func TestCreatePipeline(t *testing.T) {
if gotModelConfig.Requires != "0.20.0" {
t.Errorf("requires = %q, want 0.20.0", gotModelConfig.Requires)
}
if gotModelConfig.FileType != "" {
t.Errorf("file type = %q, want empty for non-Kev source", gotModelConfig.FileType)
if gotModelConfig.FileType != "BF16" {
t.Errorf("file type = %q, want BF16 from the stored weights", gotModelConfig.FileType)
}
if gotClass.Kind != SourceFloat || gotClass.Quantize != "" {
t.Errorf("classification = {%s %q}, want {float %q}", gotClass.Kind, gotClass.Quantize, "")
@@ -75,6 +75,24 @@ func TestCreatePipeline(t *testing.T) {
}
}
func TestCreatePipelinePhononRequires(t *testing.T) {
dir := t.TempDir()
writeGradiumPhononSource(t, dir, []int32{1, 512, 2})
// Remote creates send the generic safetensors minimum; it must not win.
for requires, want := range map[string]string{"": phononMinOllamaVersion, "0.19.0": phononMinOllamaVersion, "0.41.0": "0.41.0"} {
var got string
opts := testPipelineOptions()
opts.Requires = requires
err := Create(context.Background(), "phonon", dir, opts, newCaptureStore(), func(_ context.Context, _ string, info ManifestInfo) error {
got = info.ModelConfig.Requires
return nil
}, func(string) {})
if err != nil || got != want {
t.Errorf("requires %q: got %q, %v; want %q", requires, got, err, want)
}
}
}
func TestCreatePipelineRejectsUnsupportedArchitectureBeforeWriting(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["UnsupportedForCausalLM"]}`)
+9 -2
View File
@@ -20,6 +20,10 @@ const (
// and last dimension are relabeled.
TransformRepackFP4 Transform = "repack_fp4"
// TransformRepackFP8 reinterprets four FP8 values as one U32 word for
// MLX's mxfp8 matrix multiplication. The bytes are unchanged.
TransformRepackFP8 Transform = "repack_fp8"
// TransformRelabelU8 relabels an F8_E4M3 scale as U8 so the loader reads
// its raw bytes; the bytes themselves are unchanged.
TransformRelabelU8 Transform = "relabel_u8"
@@ -28,8 +32,11 @@ const (
// it through (a global scale stored as-is).
TransformScalarF32 Transform = "scalar_f32"
// TransformReciprocalF32 validates a scalar F32 and stores its reciprocal
// (a global scale the producer stored inverted).
// TransformF32 preserves an F32 vector scale bank with one value per expert.
TransformF32 Transform = "f32"
// TransformReciprocalF32 validates an F32 scale tensor and stores each
// element's reciprocal (global scales the producer stored inverted).
TransformReciprocalF32 Transform = "reciprocal_f32"
// TransformStackExperts concatenates N per-expert source tensors (in
+13
View File
@@ -23,6 +23,19 @@ func TestPlanRejectsOutputNameCollision(t *testing.T) {
}
}
func TestPlanDirectFlintNVFP4(t *testing.T) {
inv := newInventory(sourceModelConfig{Architectures: []string{"FlintForCausalLM"}}, map[string]string{
"model.layers.2.mlp.experts.0.gate_proj.weight": "BF16",
})
specs, err := Plan(inv, Classification{Kind: SourceFloat, Quantize: "nvfp4"}, defaultQuantPolicy{})
if err != nil {
t.Fatalf("Plan() error = %v", err)
}
if len(specs) != 1 || len(specs[0].Tensors) != 1 || specs[0].Tensors[0].Quantize != "nvfp4" {
t.Fatalf("Plan() = %+v, want an NVFP4 expert bank", specs)
}
}
func TestPlanFloat(t *testing.T) {
inv := newInventory(sourceModelConfig{}, map[string]string{
"model.embed_tokens.weight": "BF16",
+107
View File
@@ -0,0 +1,107 @@
package create
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"github.com/ollama/ollama/fs/safetensors"
)
// Qwen3_5Model names the publisher's backbone, not a decision-model class.
// Either decision sidecar identifies a checkpoint that needs full validation;
// preparePplxInventory checks that both files are present and compatible.
func hasPplxSidecar(dir string) (bool, error) {
for _, name := range []string{"decision_config.json", "readout.safetensors"} {
if _, err := os.Stat(filepath.Join(dir, name)); err == nil {
return true, nil
} else if !errors.Is(err, os.ErrNotExist) {
return false, fmt.Errorf("check Perplexity sidecar %s: %w", name, err)
}
}
return false, nil
}
// The decision readout is a separate safetensors file outside the backbone's
// shard index. Inventory must include it explicitly before planning blobs.
func preparePplxInventory(inv Inventory) (Inventory, error) {
var backbone struct {
TextConfig struct {
HiddenSize int32 `json:"hidden_size"`
} `json:"text_config"`
}
if err := json.Unmarshal(inv.RawConfig, &backbone); err != nil {
return Inventory{}, fmt.Errorf("parse Perplexity backbone config: %w", err)
}
var decision struct {
FormatVersion int `json:"format_version"`
Codes []string `json:"codes"`
TokenIDs []int32 `json:"token_ids"`
AttentionMode string `json:"attention_mode"`
Pooling string `json:"pooling"`
}
data, err := os.ReadFile(filepath.Join(inv.Dir, "decision_config.json"))
if err != nil {
return Inventory{}, fmt.Errorf("read Perplexity decision config: %w", err)
}
if err := json.Unmarshal(data, &decision); err != nil {
return Inventory{}, fmt.Errorf("parse Perplexity decision config: %w", err)
}
if backbone.TextConfig.HiddenSize <= 0 || decision.FormatVersion != 2 || len(decision.Codes) != 255 || len(decision.TokenIDs) != 255 {
return Inventory{}, fmt.Errorf("invalid Perplexity decision readout configuration")
}
var joint struct {
Version int `json:"version"`
Template string `json:"template"`
Marker string `json:"marker"`
ReadoutOffset int `json:"readout_offset"`
}
data, err = os.ReadFile(filepath.Join(inv.Dir, "joint_config.json"))
if err != nil {
return Inventory{}, fmt.Errorf("read Perplexity joint config: %w", err)
}
if err := json.Unmarshal(data, &joint); err != nil {
return Inventory{}, fmt.Errorf("parse Perplexity joint config: %w", err)
}
if joint.Version != 3 || joint.Template != "joint-question-inline-readout-v1" || joint.Marker != "<|fim_suffix|>" || joint.ReadoutOffset != 0 {
return Inventory{}, fmt.Errorf("unsupported Perplexity joint protocol")
}
if decision.AttentionMode != "noncausal_full_attention" || decision.Pooling != "last" {
return Inventory{}, fmt.Errorf("unsupported Perplexity decision attention mode %q or pooling %q", decision.AttentionMode, decision.Pooling)
}
reader, err := safetensors.OpenForExtraction(filepath.Join(inv.Dir, "readout.safetensors"))
if err != nil {
return Inventory{}, fmt.Errorf("open Perplexity readout: %w", err)
}
defer reader.Close()
if names := reader.ListTensors(); !slices.Equal(names, []string{"weight"}) {
return Inventory{}, fmt.Errorf("Perplexity readout must contain only weight")
}
weight, err := reader.GetTensor("weight")
if err != nil || weight.Dtype != "BF16" || !slices.Equal(weight.Shape, []int32{255, backbone.TextConfig.HiddenSize}) {
return Inventory{}, fmt.Errorf("Perplexity requires a BF16 readout of shape [255,%d]", backbone.TextConfig.HiddenSize)
}
if inv.Has("weight") {
return Inventory{}, fmt.Errorf("Perplexity readout weight collides with a backbone tensor")
}
inv.Tensors["weight"] = SourceTensor{Name: "weight", Dtype: weight.Dtype, Shape: weight.Shape, File: "readout.safetensors"}
return inv, nil
}
type pplxImportTransform struct{}
func newPplxImportTransform(json.RawMessage) (quantizePolicy, error) {
return pplxImportTransform{}, nil
}
func (pplxImportTransform) quantizationType(name string, shape []int32, requested string) string {
// Keep the decision readout at its publisher dtype (BF16 for Perplexity,
// FP32 for d3). Apply the backbone's Qwen3.5 policy to everything else.
if name == "weight" {
return ""
}
return qwen35ImportTransform{}.quantizationType(name, shape, requested)
}
+232
View File
@@ -0,0 +1,232 @@
package create
import (
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"
st "github.com/ollama/ollama/fs/safetensors"
)
func writePplxSource(t *testing.T, dir string) {
t.Helper()
writeConfigJSON(t, dir, `{"architectures":["Qwen3_5Model"],"model_type":"qwen3_5","text_config":{"hidden_size":4},"vision_config":{}}`)
if err := os.WriteFile(filepath.Join(dir, "decision_config.json"), []byte(`{"format_version":2,"attention_mode":"noncausal_full_attention","pooling":"last","codes":[`+strings.TrimSuffix(strings.Repeat(`"A",`, 255), ",")+`],"token_ids":[`+strings.TrimSuffix(strings.Repeat(`32,`, 255), ",")+`]}`), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "joint_config.json"), []byte(`{"version":3,"template":"joint-question-inline-readout-v1","marker":"<|fim_suffix|>","readout_offset":0}`), 0o600); err != nil {
t.Fatal(err)
}
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{8, 4}, make([]byte, 64)),
})
createTestSafetensors(t, filepath.Join(dir, "readout.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("weight", "BF16", []int32{255, 4}, make([]byte, 2040)),
})
}
func TestPplxMetadataFilterNeedsDecisionSidecar(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["Qwen3_5Model"]}`)
if err := os.WriteFile(filepath.Join(dir, "custom_config.json"), []byte(`{}`), 0o600); err != nil {
t.Fatal(err)
}
files, err := SafetensorsConfigFiles(dir)
if err != nil {
t.Fatal(err)
}
if !slices.Contains(files, "custom_config.json") {
t.Fatalf("bare Qwen backbone lost metadata: %v", files)
}
}
func TestPplxSidecarCheckReportsFilesystemErrors(t *testing.T) {
if _, err := hasPplxSidecar("\x00"); err == nil {
t.Fatal("sidecar stat error was treated as an absent sidecar")
}
}
func TestPplxBareBackboneRejectedBeforeImport(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["Qwen3_5Model"]}`)
cfg, _, err := readSourceModelConfig(dir)
if err != nil {
t.Fatal(err)
}
if _, err := inferSafetensorsConfig(dir, cfg, "", ""); err == nil || !strings.Contains(err.Error(), "requires decision sidecars") {
t.Fatalf("bare backbone import error = %v", err)
}
}
func TestPplxInventoryAndImport(t *testing.T) {
dir := t.TempDir()
writePplxSource(t, dir)
if err := os.WriteFile(filepath.Join(dir, "release-manifest.json"), []byte(`{"verified_upstream":"full"}`), 0o600); err != nil {
t.Fatal(err)
}
inv, err := ReadInventory(dir)
if err != nil {
t.Fatal(err)
}
if inv.Has("weight") {
t.Fatal("readout was unexpectedly in the backbone shard inventory")
}
inv, err = preparePplxInventory(inv)
if err != nil {
t.Fatal(err)
}
if inv.Tensors["weight"].File != "readout.safetensors" {
t.Fatalf("readout source = %+v", inv.Tensors["weight"])
}
files, err := SafetensorsWeightFiles(dir)
if err != nil || !slices.Equal(files, []string{"model.safetensors", "readout.safetensors"}) {
t.Fatalf("source files = %v, %v", files, err)
}
store := newCaptureStore()
var result ManifestInfo
err = Create(t.Context(), "pplx-test", dir, testPipelineOptions(), store, func(_ context.Context, _ string, info ManifestInfo) error {
result = info
return nil
}, func(string) {})
if err != nil {
t.Fatal(err)
}
if result.ModelConfig.Renderer != "pplx" || result.ModelConfig.Parser != "" || !slices.Equal(result.ModelConfig.Capabilities, []string{"decision", "vision"}) {
t.Fatalf("model config = %+v", result.ModelConfig)
}
if _, ok := store.blobs["decision_config.json"]; !ok {
t.Fatal("decision_config.json not imported")
}
if _, ok := store.blobs["joint_config.json"]; !ok {
t.Fatal("joint_config.json not imported")
}
if _, ok := store.blobs["release-manifest.json"]; ok {
t.Fatal("release metadata was imported as model configuration")
}
}
func TestPplxMissingDecisionConfigRejectedBeforeWriting(t *testing.T) {
dir := t.TempDir()
writePplxSource(t, dir)
if err := os.Remove(filepath.Join(dir, "decision_config.json")); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "release-manifest.json"), []byte(`{"review":"local"}`), 0o600); err != nil {
t.Fatal(err)
}
files, err := SafetensorsConfigFiles(dir)
if err != nil || slices.Contains(files, "release-manifest.json") {
t.Fatalf("source metadata files = %v, %v", files, err)
}
store := newCaptureStore()
err = Create(t.Context(), "pplx-test", dir, testPipelineOptions(), store, func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
if err == nil || !strings.Contains(err.Error(), "read Perplexity decision config") {
t.Fatalf("Create() error = %v, want missing decision config", err)
}
if len(store.blobs) != 0 {
t.Fatal("incomplete decision checkpoint wrote blobs")
}
}
func TestPplxMissingReadoutRejectedBeforeWriting(t *testing.T) {
dir := t.TempDir()
writePplxSource(t, dir)
if err := os.Remove(filepath.Join(dir, "readout.safetensors")); err != nil {
t.Fatal(err)
}
store := newCaptureStore()
err := Create(t.Context(), "pplx-test", dir, testPipelineOptions(), store, func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
if err == nil || !strings.Contains(err.Error(), "open Perplexity readout") {
t.Fatalf("Create() error = %v", err)
}
if len(store.blobs) != 0 {
t.Fatal("incomplete model wrote blobs")
}
}
func TestPplxUnsupportedDecisionModeRejectedBeforeWriting(t *testing.T) {
dir := t.TempDir()
writePplxSource(t, dir)
path := filepath.Join(dir, "decision_config.json")
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
data = []byte(strings.Replace(string(data), `"noncausal_full_attention"`, `"causal"`, 1))
if err := os.WriteFile(path, data, 0o600); err != nil {
t.Fatal(err)
}
store := newCaptureStore()
err = Create(t.Context(), "pplx-test", dir, testPipelineOptions(), store, func(context.Context, string, ManifestInfo) error { return nil }, func(string) {})
if err == nil || !strings.Contains(err.Error(), "unsupported Perplexity decision attention mode") {
t.Fatalf("Create() error = %v, want unsupported-mode rejection", err)
}
if len(store.blobs) != 0 {
t.Fatal("unsupported decision mode wrote blobs")
}
}
func TestPplxReadoutTransferIsArchitectureScoped(t *testing.T) {
dir := t.TempDir()
writeConfigJSON(t, dir, `{"architectures":["LlamaForCausalLM"],"model_type":"llama"}`)
createTestSafetensors(t, filepath.Join(dir, "model.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("model.embed_tokens.weight", "BF16", []int32{1, 1}, make([]byte, 2)),
})
createTestSafetensors(t, filepath.Join(dir, "readout.safetensors"), []*st.TensorData{
st.NewTensorDataFromBytes("weight", "BF16", []int32{1, 1}, make([]byte, 2)),
})
files, err := SafetensorsWeightFiles(dir)
if err != nil || !slices.Equal(files, []string{"model.safetensors"}) {
t.Fatalf("unrelated source files = %v, %v", files, err)
}
}
func TestPplxQuantizationPreservesReadout(t *testing.T) {
policy, err := newPplxImportTransform(nil)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
want string
}{
{"weight", ""},
{"language_model.layers.0.mlp.up_proj.weight", "nvfp4"},
{"language_model.layers.0.linear_attn.in_proj_a.weight", ""},
{"visual.blocks.0.mlp.fc1.weight", ""},
} {
if got := policy.quantizationType(tc.name, []int32{5120, 5120}, "nvfp4"); got != tc.want {
t.Errorf("%s quantization = %q, want %q", tc.name, got, tc.want)
}
}
}
func TestPplxRejectsIncompatibleParserAndRenderer(t *testing.T) {
for _, tc := range []struct {
name string
set func(*PipelineOptions)
}{
{"renderer", func(opts *PipelineOptions) { opts.Renderer = "qwen3.8" }},
{"parser", func(opts *PipelineOptions) { opts.Parser = "qwen3.5" }},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
writePplxSource(t, dir)
opts := testPipelineOptions()
tc.set(&opts)
store := newCaptureStore()
err := Create(t.Context(), "pplx-test", dir, opts, store, func(context.Context, string, ManifestInfo) error {
return nil
}, func(string) {})
if err == nil || !strings.Contains(err.Error(), "require renderer") {
t.Fatalf("Create() error = %v, want incompatible override rejection", err)
}
if len(store.blobs) != 0 {
t.Fatal("invalid metadata wrote blobs")
}
})
}
}
+194 -16
View File
@@ -1,6 +1,12 @@
package create
import "strings"
import (
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
)
// prequantPattern describes how one producer packs an already-quantized weight
// and its scale companions into safetensors files, and how to fuse them into
@@ -16,8 +22,10 @@ import "strings"
type prequantPattern struct {
name string
weightSuffix string // source suffix identifying the weight (".weight" or ".weight_packed")
repackWeight bool // repack a U8 fp4 weight into U32 words
weightSuffix string // source suffix identifying the weight (".weight" or ".weight_packed")
weightDtypes []string // accepted source dtypes; empty accepts any dtype
scaleDtypes []string // accepted scale dtypes; empty accepts any dtype
repackWeight bool // reinterpret four one-byte weight values as one U32 word
scaleSuffix string // required per-block / affine scale companion
scaleRelabelU8 bool // relabel an F8_E4M3 scale as U8 for the loader
@@ -25,9 +33,9 @@ type prequantPattern struct {
biasSuffix string // optional bias / zero-point companion ("" if none)
globalSuffix string // optional global-scale companion ("" if none)
globalReciprocal bool // store the global scale as its reciprocal
globalReciprocal bool // producer stores the weight global scale inverted
ignoreSuffixes []string // companions consumed but not written (e.g. activation scales)
ignoreSuffixes []string // activation scales unused by weight-only inference
forceQuantType string // override the blob's quant_type metadata
defaultGroupSize string // set group_size metadata only when the config did not
@@ -56,9 +64,20 @@ var prequantPatterns = []prequantPattern{
forceQuantType: "nvfp4",
defaultGroupSize: "16",
},
{
name: "modelopt-mxfp8",
weightSuffix: ".weight",
weightDtypes: []string{"F8_E4M3", "F8_E4M3FN"},
repackWeight: true,
scaleSuffix: ".weight_scale",
scaleDtypes: []string{"U8"},
forceQuantType: "mxfp8",
defaultGroupSize: "32",
},
{
name: "modelopt-nvfp4",
weightSuffix: ".weight",
weightDtypes: []string{"U8", "U32"},
repackWeight: true,
scaleSuffix: ".weight_scale",
scaleRelabelU8: true,
@@ -85,22 +104,153 @@ func planPrequantized(inv Inventory) ([]BlobSpec, error) {
consumed[s] = true
}
}
if slices.Contains(inv.Config.Architectures, "FlintForCausalLM") {
const embedding = "model.embed_tokens.weight"
if spec, ok := fused[embedding]; ok && spec.Metadata["quant_type"] == "int4" {
var config struct {
MLXExport struct {
EmbeddingBits int `json:"embedding_bits"`
} `json:"mlx_export"`
}
if err := json.Unmarshal(inv.RawConfig, &config); err != nil {
return nil, fmt.Errorf("Flint embedding quantization: %w", err)
}
// The packed embedding has the same shape at INT8/group64 as at
// INT4/group128; only the publisher's export metadata identifies it.
bits := config.MLXExport.EmbeddingBits
if bits != 4 && bits != 8 {
return nil, fmt.Errorf("Flint embedding quantization: unsupported mlx_export.embedding_bits %d", bits)
}
if bits == 8 {
spec.Metadata["quant_type"] = "int8"
}
fused[embedding] = spec
}
}
// Model Optimizer keeps Flint's publisher-native per-expert tensor names.
// As with float imports, the Ollama artifact needs one bank per projection.
// Stack its packed words and calibrated scales without requantizing them.
expertGroups := make(map[string][]SourceTensor)
if slices.Contains(inv.Config.Architectures, "FlintForCausalLM") {
for _, name := range sortedTensorNames(inv) {
if group, ok := perExpertGroup(name); ok && strings.HasSuffix(name, ".weight") {
expertGroups[group] = append(expertGroups[group], inv.Tensors[name])
}
}
}
var specs []BlobSpec
for _, group := range sortedKeys(expertGroups) {
experts := expertGroups[group]
quantized := 0
for _, weight := range experts {
if _, ok := fused[weight.Name]; ok {
quantized++
}
}
if quantized != 0 && quantized != len(experts) {
return nil, fmt.Errorf("prequantized expert group %s has %d of %d projections with scales", group, quantized, len(experts))
}
var groupSpecs []BlobSpec
var err error
if quantized == 0 {
groupSpecs, err = planExpertGroup(group, experts, "", defaultQuantPolicy{})
} else {
groupSpecs, err = planPrequantExpertGroup(group, experts, fused)
}
if err != nil {
return nil, err
}
specs = append(specs, groupSpecs...)
for _, weight := range experts {
consumed[weight.Name] = true
}
}
specs := make([]BlobSpec, 0, len(inv.Tensors))
for _, name := range sortedTensorNames(inv) {
if consumed[name] {
continue
}
if spec, ok := fused[name]; ok {
specs = append(specs, spec)
continue
}
if consumed[name] {
continue
}
t := inv.Tensors[name]
specs = append(specs, BlobSpec{Name: name, Tensors: []TensorSpec{{Name: name, Sources: []SourceTensor{t}}}})
}
return specs, nil
}
func planPrequantExpertGroup(group string, weights []SourceTensor, fused map[string]BlobSpec) ([]BlobSpec, error) {
// The float importer's expert planner validates contiguous indices. Stacking
// copies the source bytes, so the output dtype and shape also perform the
// header-only U8 weight repack and FP8 scale relabeling.
specs, err := planExpertGroup(group, weights, "", defaultQuantPolicy{})
if err != nil {
return nil, err
}
bank := &specs[0]
weightsByProjection := bank.Tensors
bank.Tensors = nil
for _, packed := range weightsByProjection {
count := len(packed.Sources)
scaleSources := make([]SourceTensor, count)
globalSources := make([]SourceTensor, count)
for index, weight := range packed.Sources {
part, ok := fused[weight.Name]
if !ok || part.Metadata["quant_type"] != "nvfp4" || len(part.Tensors) != 3 ||
len(weight.Shape) != 2 {
return nil, fmt.Errorf("prequantized expert %s has unsupported NVFP4 layout", weight.Name)
}
wordShape := weight.Shape
normalized := part.Tensors[0]
switch weight.Dtype {
case "U32":
if normalized.Transform != TransformNone {
return nil, fmt.Errorf("prequantized expert %s has unsupported NVFP4 weight transform", weight.Name)
}
case "U8":
if normalized.Transform != TransformRepackFP4 || normalized.OutDtype != "U32" ||
len(normalized.OutShape) != 2 || weight.Shape[1]%4 != 0 {
return nil, fmt.Errorf("prequantized expert %s has unsupported NVFP4 weight transform", weight.Name)
}
wordShape = normalized.OutShape
default:
return nil, fmt.Errorf("prequantized expert %s has unsupported NVFP4 weight dtype %s", weight.Name, weight.Dtype)
}
if index == 0 {
packed.OutDtype = "U32"
packed.OutShape = append([]int32{int32(count)}, wordShape...)
} else if !slices.Equal(wordShape, packed.OutShape[1:]) {
return nil, fmt.Errorf("prequantized expert %s differs from the NVFP4 bank layout", weight.Name)
}
scale, global := part.Tensors[1], part.Tensors[2]
if scale.Name != weight.Name+".scale" || global.Name != weight.Name+".global_scale" ||
len(scale.Sources) != 1 || len(global.Sources) != 1 ||
global.Transform != TransformScalarF32 {
return nil, fmt.Errorf("prequantized expert %s has unsupported NVFP4 companions", weight.Name)
}
s, g := scale.Sources[0], global.Sources[0]
scaleIsU8 := s.Dtype == "U8" && scale.Transform == TransformNone
scaleIsFP8 := isE4M3Dtype(s.Dtype) && scale.Transform == TransformRelabelU8 && scale.OutDtype == "U8"
if (!scaleIsU8 && !scaleIsFP8) || len(s.Shape) != 2 || g.Dtype != "F32" || !slices.Equal(g.Shape, []int32{1}) ||
(index > 0 && (s.Dtype != scaleSources[0].Dtype || !slices.Equal(s.Shape, scaleSources[0].Shape) || !slices.Equal(g.Shape, globalSources[0].Shape))) {
return nil, fmt.Errorf("prequantized expert %s differs from the NVFP4 bank layout", weight.Name)
}
if bank.Metadata != nil && !maps.Equal(bank.Metadata, part.Metadata) {
return nil, fmt.Errorf("prequantized expert %s has different quantization metadata", weight.Name)
}
bank.Metadata = part.Metadata
scaleSources[index], globalSources[index] = s, g
}
bank.Tensors = append(bank.Tensors, packed,
TensorSpec{Name: packed.Name + ".scale", Sources: scaleSources, Transform: TransformStackExperts, OutDtype: "U8", OutShape: append([]int32{int32(count)}, scaleSources[0].Shape...)},
TensorSpec{Name: packed.Name + ".global_scale", Sources: globalSources, Transform: TransformStackExperts, OutDtype: "F32", OutShape: []int32{int32(count)}},
)
}
return specs, nil
}
// matchPrequant returns the fused blob for a weight tensor if it matches a
// prequantized producer, along with the source names it consumes. It returns
// ok=false when name is not a prequantized weight (a companion or a plain
@@ -115,21 +265,27 @@ func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
if !inv.Has(scaleSrc) {
continue
}
weight := inv.Tensors[name]
scale := inv.Tensors[scaleSrc]
if !matchesDtype(weight.Dtype, p.weightDtypes) || !matchesDtype(scale.Dtype, p.scaleDtypes) {
continue
}
outWeight := base + ".weight"
weight := inv.Tensors[name]
var tensors []TensorSpec
var consumed []string
weightTensor := TensorSpec{Name: outWeight, Sources: []SourceTensor{weight}}
if p.repackWeight && strings.EqualFold(weight.Dtype, "U8") && len(weight.Shape) == 2 {
if p.repackWeight && len(weight.Shape) == 2 && (strings.EqualFold(weight.Dtype, "U8") || isE4M3Dtype(weight.Dtype)) {
weightTensor.Transform = TransformRepackFP4
if isE4M3Dtype(weight.Dtype) {
weightTensor.Transform = TransformRepackFP8
}
weightTensor.OutDtype = "U32"
weightTensor.OutShape = []int32{weight.Shape[0], weight.Shape[1] / 4}
}
tensors = append(tensors, weightTensor)
scale := inv.Tensors[scaleSrc]
scaleTensor := TensorSpec{Name: outWeight + ".scale", Sources: []SourceTensor{scale}}
if p.scaleRelabelU8 && isE4M3Dtype(scale.Dtype) {
scaleTensor.Transform = TransformRelabelU8
@@ -147,7 +303,8 @@ func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
if p.globalSuffix != "" {
if gSrc := base + p.globalSuffix; inv.Has(gSrc) {
global := TensorSpec{Name: outWeight + ".global_scale", Sources: []SourceTensor{inv.Tensors[gSrc]}, Transform: TransformScalarF32}
globalSource := inv.Tensors[gSrc]
global := TensorSpec{Name: outWeight + ".global_scale", Sources: []SourceTensor{globalSource}, Transform: f32ScaleTransform(globalSource)}
if p.globalReciprocal {
global.Transform = TransformReciprocalF32
}
@@ -156,9 +313,9 @@ func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
}
}
for _, suf := range p.ignoreSuffixes {
if s := base + suf; inv.Has(s) {
consumed = append(consumed, s)
for _, suffix := range p.ignoreSuffixes {
if source := base + suffix; inv.Has(source) {
consumed = append(consumed, source)
}
}
@@ -167,6 +324,27 @@ func matchPrequant(name string, inv Inventory) (BlobSpec, []string, bool) {
return BlobSpec{}, nil, false
}
func f32ScaleTransform(t SourceTensor) Transform {
for _, dim := range t.Shape {
if dim != 1 {
return TransformF32
}
}
return TransformScalarF32
}
func matchesDtype(dtype string, allowed []string) bool {
if len(allowed) == 0 {
return true
}
for _, want := range allowed {
if strings.EqualFold(dtype, want) {
return true
}
}
return false
}
// prequantMetadata builds the fused blob's metadata: the source config's quant
// metadata, with the pattern's quant_type override and group_size default
// applied. Returns nil when there is nothing to record.
+248 -1
View File
@@ -2,6 +2,7 @@ package create
import (
"slices"
"strings"
"testing"
)
@@ -78,12 +79,60 @@ func TestPlanPrequantizedMLX(t *testing.T) {
}
}
func TestPlanPrequantizedFlintEmbeddingBits(t *testing.T) {
for _, tc := range []struct {
name string
raw string
want string
}{
{name: "int8 embedding", raw: `{"mlx_export":{"embedding_bits":8}}`, want: "int8"},
{name: "int4 embedding", raw: `{"mlx_export":{"embedding_bits":4}}`, want: "int4"},
{name: "missing bit width", raw: `{"mlx_export":{}}`},
} {
t.Run(tc.name, func(t *testing.T) {
inv := newInventory(sourceModelConfig{
Architectures: []string{"FlintForCausalLM"},
Quantization: sourceQuantization{Bits: 4, Mode: "affine", GroupSize: 64},
}, map[string]string{
"model.embed_tokens.weight": "U32",
"model.embed_tokens.scales": "BF16",
"model.embed_tokens.biases": "BF16",
"model.layers.0.self_attn.q_proj.weight": "U32",
"model.layers.0.self_attn.q_proj.scales": "BF16",
"model.layers.0.self_attn.q_proj.biases": "BF16",
})
inv.RawConfig = []byte(tc.raw)
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if tc.want == "" {
if err == nil || !strings.Contains(err.Error(), "mlx_export.embedding_bits") {
t.Fatalf("Plan() error = %v, want missing embedding bit width", err)
}
return
}
if err != nil {
t.Fatal(err)
}
embedding, ok := specByName(specs, "model.embed_tokens.weight")
if !ok || embedding.Metadata["quant_type"] != tc.want {
t.Errorf("embedding quant_type = %q, want %q", embedding.Metadata["quant_type"], tc.want)
}
projection, ok := specByName(specs, "model.layers.0.self_attn.q_proj.weight")
if !ok || projection.Metadata["quant_type"] != "int4" {
t.Errorf("projection quant_type = %q, want int4", projection.Metadata["quant_type"])
}
})
}
}
func TestPlanPrequantizedModelOptNVFP4(t *testing.T) {
inv := newInventory(sourceModelConfig{}, map[string]string{
"l.weight": "U8",
"l.weight_scale": "F8_E4M3",
"l.weight_scale_2": "F32",
})
global := inv.Tensors["l.weight_scale_2"]
global.Shape = nil
inv.Tensors[global.Name] = global
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err != nil {
@@ -117,6 +166,143 @@ func TestPlanPrequantizedModelOptNVFP4(t *testing.T) {
}
}
func TestPlanPrequantizedModelOptExpertBank(t *testing.T) {
inv := newInventory(sourceModelConfig{Architectures: []string{"FlintForCausalLM"}}, map[string]string{
"model.layers.2.mlp.experts.0.gate_proj.weight": "U32",
"model.layers.2.mlp.experts.0.gate_proj.weight_scale": "U8",
"model.layers.2.mlp.experts.0.gate_proj.weight_scale_2": "F32",
"model.layers.2.mlp.experts.1.gate_proj.weight": "U32",
"model.layers.2.mlp.experts.1.gate_proj.weight_scale": "U8",
"model.layers.2.mlp.experts.1.gate_proj.weight_scale_2": "F32",
})
for name, tensor := range inv.Tensors {
if slices.Contains([]string{"model.layers.2.mlp.experts.0.gate_proj.weight_scale_2", "model.layers.2.mlp.experts.1.gate_proj.weight_scale_2"}, name) {
tensor.Shape = []int32{1}
}
inv.Tensors[name] = tensor
}
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err != nil {
t.Fatalf("Plan() error = %v", err)
}
if len(specs) != 1 {
t.Fatalf("got blobs %v, want one expert bank", specNames(specs))
}
name := "model.layers.2.mlp.experts.gate_proj.weight"
bank := specs[0]
if bank.Name != "model.layers.2.mlp.experts" || bank.Metadata["quant_type"] != "nvfp4" {
t.Fatalf("expert bank = %+v", bank)
}
for _, tc := range []struct {
name string
shape []int32
}{
{name, []int32{2, 128, 128}},
{name + ".scale", []int32{2, 128, 128}},
{name + ".global_scale", []int32{2}},
} {
tensor, ok := inputByOutput(bank, tc.name)
if !ok || tensor.Transform != TransformStackExperts || !slices.Equal(tensor.OutShape, tc.shape) || len(tensor.Sources) != 2 {
t.Errorf("%s = %+v, want stacked %v", tc.name, tensor, tc.shape)
}
}
}
func TestPlanPrequantizedModelOptExpertBankRejectsIncompleteScale(t *testing.T) {
inv := newInventory(sourceModelConfig{Architectures: []string{"FlintForCausalLM"}}, map[string]string{
"model.layers.2.mlp.experts.0.gate_proj.weight": "U32",
"model.layers.2.mlp.experts.0.gate_proj.weight_scale": "U8",
"model.layers.2.mlp.experts.0.gate_proj.weight_scale_2": "F32",
"model.layers.2.mlp.experts.1.gate_proj.weight": "U32",
"model.layers.2.mlp.experts.1.gate_proj.weight_scale": "U8",
})
global := inv.Tensors["model.layers.2.mlp.experts.0.gate_proj.weight_scale_2"]
global.Shape = []int32{1}
inv.Tensors[global.Name] = global
_, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err == nil || !strings.Contains(err.Error(), "model.layers.2.mlp.experts") {
t.Fatalf("Plan() error = %v, want named incomplete expert bank", err)
}
}
func TestPlanPrequantizedModelOptMixedPrecision(t *testing.T) {
inv := newInventory(sourceModelConfig{}, map[string]string{
"fp4.weight": "U8",
"fp4.weight_scale": "F8_E4M3",
"fp4.weight_scale_2": "F32",
"fp8.weight": "F8_E4M3",
"fp8.weight_scale": "U8",
})
classification, err := Classify(inv, "")
if err != nil || classification.Kind != SourcePrequantized || classification.Quantize != "" {
t.Fatalf("mixed ModelOpt classification = %+v, %v", classification, err)
}
specs, err := Plan(inv, classification, defaultQuantPolicy{})
if err != nil {
t.Fatalf("Plan() error = %v", err)
}
if len(specs) != 2 {
t.Fatalf("got %d specs %v, want two fused weights", len(specs), specNames(specs))
}
fp4, _ := specByName(specs, "fp4.weight")
if fp4.Metadata["quant_type"] != "nvfp4" {
t.Errorf("FP4 metadata = %v", fp4.Metadata)
}
fp8, _ := specByName(specs, "fp8.weight")
if fp8.Metadata["quant_type"] != "mxfp8" || fp8.Metadata["group_size"] != "32" {
t.Errorf("FP8 metadata = %v", fp8.Metadata)
}
weight, _ := inputByOutput(fp8, "fp8.weight")
scale, _ := inputByOutput(fp8, "fp8.weight.scale")
if weight.Transform != TransformRepackFP8 || weight.OutDtype != "U32" || !slices.Equal(weight.OutShape, []int32{128, 32}) || scale.Transform != TransformNone || scale.OutDtype != "" {
t.Errorf("FP8 weight must pack into U32 and exponent scale must keep source bytes: weight=%+v scale=%+v", weight, scale)
}
if q := detectPrequantizedQuantization(inv); q != "" {
t.Errorf("mixed precision classification = %q, want no single file type", q)
}
}
func TestClassifyModelOptMXFP8WithoutNVFP4(t *testing.T) {
inv := newInventory(sourceModelConfig{}, map[string]string{
"l.weight": "F8_E4M3",
"l.weight_scale": "U8",
})
classification, err := Classify(inv, "")
if err != nil || classification.Kind != SourcePrequantized || classification.Quantize != "mxfp8" {
t.Fatalf("ModelOpt MXFP8 classification = %+v, %v", classification, err)
}
specs, err := Plan(inv, classification, defaultQuantPolicy{})
if err != nil || len(specs) != 1 || specs[0].Metadata["quant_type"] != "mxfp8" {
t.Fatalf("ModelOpt MXFP8 plan = %+v, %v", specs, err)
}
}
func TestPlanPrequantizedModelOptPackedNVFP4(t *testing.T) {
inv := newInventory(sourceModelConfig{}, map[string]string{
"l.weight": "U32",
"l.weight_scale": "F8_E4M3",
"l.weight_scale_2": "F32",
})
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err != nil {
t.Fatalf("Plan() error = %v", err)
}
if len(specs) != 1 {
t.Fatalf("got %d specs %v, want one fused weight", len(specs), specNames(specs))
}
weight, ok := inputByOutput(specs[0], "l.weight")
if !ok || weight.Transform != TransformNone || weight.OutDtype != "" || len(weight.OutShape) != 0 {
t.Errorf("already-packed U32 weight must keep its source shape: %+v ok=%v", weight, ok)
}
if specs[0].Metadata["quant_type"] != "nvfp4" {
t.Errorf("quant_type = %q, want nvfp4", specs[0].Metadata["quant_type"])
}
}
func TestPlanPrequantizedModelOptDropsActivationScale(t *testing.T) {
// ModelOpt ships per-weight activation scales (.input_scale and, in some
// variants, .input_global_scale) that are unused for weight-only
@@ -155,14 +341,20 @@ func TestPlanPrequantizedCompressedNVFP4(t *testing.T) {
"l.weight_scale": "F8_E4M3",
"l.weight_global_scale": "F32",
"l.input_global_scale": "F32",
"l.input_scale": "F32",
})
for _, name := range []string{"l.weight_global_scale", "l.input_global_scale", "l.input_scale"} {
scale := inv.Tensors[name]
scale.Shape = nil
inv.Tensors[name] = scale
}
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err != nil {
t.Fatalf("Plan() error = %v", err)
}
if len(specs) != 1 {
t.Fatalf("got %d specs %v, want 1 (input_global_scale must be consumed)", len(specs), specNames(specs))
t.Fatalf("got %d specs %v, want 1", len(specs), specNames(specs))
}
w := specs[0]
if w.Name != "l.weight" {
@@ -177,7 +369,62 @@ func TestPlanPrequantizedCompressedNVFP4(t *testing.T) {
if !ok || globalIn.Transform != TransformReciprocalF32 {
t.Errorf("global_scale input = %+v ok=%v, want reciprocal_f32", globalIn, ok)
}
if len(w.Tensors) != 3 {
t.Errorf("fused tensors = %v, want only weight, block scale and global scale", w.Tensors)
}
if w.Metadata["quant_type"] != "nvfp4" || w.Metadata["group_size"] != "16" {
t.Errorf("metadata = %v, want quant_type=nvfp4 group_size=16", w.Metadata)
}
}
func TestPlanPrequantizedModelOptRetainsExpertScaleBanks(t *testing.T) {
inv := newInventory(sourceModelConfig{}, map[string]string{
"l.weight": "U32",
"l.weight_scale": "U8",
"l.weight_scale_2": "F32",
"l.input_scale": "F32",
})
for _, name := range []string{"l.weight_scale_2", "l.input_scale"} {
scale := inv.Tensors[name]
scale.Shape = []int32{128}
inv.Tensors[name] = scale
}
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err != nil {
t.Fatalf("Plan() error = %v", err)
}
w, ok := specByName(specs, "l.weight")
if !ok {
t.Fatal("missing l.weight blob")
}
scale, ok := inputByOutput(w, "l.weight.global_scale")
if !ok || scale.Transform != TransformF32 || !slices.Equal(scale.Sources[0].Shape, []int32{128}) {
t.Errorf("global scale = %+v ok=%v, want F32 expert scale bank", scale, ok)
}
if len(specs) != 1 || len(w.Tensors) != 3 {
t.Errorf("specs = %v, want only fused weight, block scale and global scale", specs)
}
}
func TestPlanPrequantizedRetainsKVCacheScales(t *testing.T) {
inv := newInventory(sourceModelConfig{}, map[string]string{
"l.k_proj.weight": "U8",
"l.k_proj.weight_scale": "F8_E4M3",
"l.k_proj.k_scale": "F32",
"l.v_proj.weight": "U8",
"l.v_proj.weight_scale": "F8_E4M3",
"l.v_proj.v_scale": "F32",
})
specs, err := Plan(inv, Classification{Kind: SourcePrequantized}, defaultQuantPolicy{})
if err != nil {
t.Fatalf("Plan() error = %v", err)
}
for _, name := range []string{"l.k_proj.k_scale", "l.v_proj.v_scale"} {
spec, ok := specByName(specs, name)
if !ok || len(spec.Tensors) != 1 || sourceName(spec.Tensors[0]) != name {
t.Errorf("%s = %+v ok=%v, want unchanged standalone tensor", name, spec, ok)
}
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ package create
import "testing"
func TestQwen35DecisionQuantizationPolicy(t *testing.T) {
for _, arch := range []string{"ClefForDecision", "StrandsDeciderForDecision", "KevForDecision"} {
for _, arch := range []string{"ClefForDecision", "StrandsDeciderForDecision", "KevForDecision", "AutoTrustDecision"} {
inv := Inventory{Config: sourceModelConfig{Architectures: []string{arch}}}
policy, err := newTensorImportTransform(inv)
if err != nil {
+38 -3
View File
@@ -12,11 +12,12 @@ func newQwen4ExpImportTransform(_ json.RawMessage) (quantizePolicy, error) {
}
func (qwen4ExpImportTransform) quantizationType(name string, shape []int32, quantize string) string {
quantize = normalizeQuantType(quantize)
// PLE is a hashed n-gram feature table rather than the model's token
// embedding. It dominates the checkpoint size, and its lookup path supports
// row-wise dequantization, so quantize its shards at the requested type.
// embedding. Its lookup path dequantizes selected rows, so quantize its
// shards at the requested type.
if qwen4ExpIsPLEEmbeddingShard(name) {
quantize = normalizeQuantType(quantize)
if len(shape) == 2 && isAligned(shape, quantize) {
return quantize
}
@@ -28,6 +29,25 @@ func (qwen4ExpImportTransform) quantizationType(name string, shape []int32, quan
if qwen35IsLowRankProjection(name) {
return ""
}
if quantize == "nvfp4" {
// Keep QSA Q/K/V and the indexer projection on the validated BF16 path.
// Keep the whole draft-side control path at source precision as well.
if qwen4ExpIsSensitiveQSA(name) ||
(strings.HasPrefix(name, "mtp.") && !qwen4ExpIsRoutedExpert(name)) {
return ""
}
if isEmbedTokensWeight(name) {
return promoteEmbedding(shape, quantize)
}
// Routed experts dominate the remaining model size and have validated NVFP4
// kernels. Use MXFP8 for the other eligible target weights to avoid the
// long-context quality loss seen with blanket NVFP4.
if !qwen4ExpIsRoutedExpert(name) {
return GetTensorQuantization(name, shape, "mxfp8")
}
}
return GetTensorQuantization(name, shape, quantize)
}
@@ -35,3 +55,18 @@ func qwen4ExpIsPLEEmbeddingShard(name string) bool {
return strings.Contains(name, ".ple.ple_embedding.ngram_embedding.shard_") &&
strings.HasSuffix(name, ".weight")
}
func qwen4ExpIsRoutedExpert(name string) bool {
return (strings.HasPrefix(name, "model.language_model.layers.") ||
strings.HasPrefix(name, "mtp.layers.")) &&
strings.Contains(name, ".mlp.experts.")
}
func qwen4ExpIsSensitiveQSA(name string) bool {
return strings.HasPrefix(name, "model.language_model.layers.") &&
strings.Contains(name, ".self_attn.") &&
(strings.HasSuffix(name, ".q_proj.weight") ||
strings.HasSuffix(name, ".k_proj.weight") ||
strings.HasSuffix(name, ".v_proj.weight") ||
strings.HasSuffix(name, ".indexer.index_qk_proj.weight"))
}
+51 -2
View File
@@ -13,18 +13,25 @@ func TestQwen4ExpQuantizationType(t *testing.T) {
want string
}{
{
name: "PLE shard",
name: "PLE shard uses requested NVFP4",
tensor: "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_0.weight",
shape: []int32{156250, 2560},
quantize: "nvfp4",
want: "nvfp4",
},
{
name: "PLE shard preserves explicit MXFP8 request",
tensor: "model.language_model.layers.1.ple.ple_embedding.ngram_embedding.shard_0.weight",
shape: []int32{156250, 2560},
quantize: "mxfp8",
want: "mxfp8",
},
{
name: "token embedding",
tensor: "model.language_model.embed_tokens.weight",
shape: []int32{248320, 2560},
quantize: "nvfp4",
want: "",
want: "mxfp8",
},
{
name: "low rank projection",
@@ -38,8 +45,50 @@ func TestQwen4ExpQuantizationType(t *testing.T) {
tensor: "model.language_model.layers.0.linear_attn.out_proj.weight",
shape: []int32{5120, 3072},
quantize: "nvfp4",
want: "mxfp8",
},
{
name: "QSA query projection",
tensor: "model.language_model.layers.3.self_attn.q_proj.weight",
shape: []int32{12288, 2560},
quantize: "nvfp4",
want: "",
},
{
name: "MTP routed expert",
tensor: "mtp.layers.0.mlp.experts.0.down_proj.weight",
shape: []int32{2560, 1024},
quantize: "nvfp4",
want: "nvfp4",
},
{
name: "MTP control path",
tensor: "mtp.layers.0.self_attn.q_proj.weight",
shape: []int32{12288, 2560},
quantize: "nvfp4",
want: "",
},
{
name: "main routed expert",
tensor: "model.language_model.layers.0.mlp.experts.0.down_proj.weight",
shape: []int32{2560, 1024},
quantize: "nvfp4",
want: "nvfp4",
},
{
name: "QSA query projection mxfp8",
tensor: "model.language_model.layers.3.self_attn.q_proj.weight",
shape: []int32{12288, 2560},
quantize: "mxfp8",
want: "mxfp8",
},
{
name: "hyperconnection projection",
tensor: "model.language_model.layers.0.attn_hyper_connection.block_inject_weight.weight",
shape: []int32{2560, 2560},
quantize: "nvfp4",
want: "mxfp8",
},
}
for _, tt := range tests {
+9 -3
View File
@@ -19,8 +19,8 @@ func applyByteTransform(ts TensorSpec, sources []*safetensors.TensorData) (*safe
}
return sources[0].WithName(ts.Name), nil
case TransformRepackFP4, TransformRelabelU8:
// Both relabel the header (dtype, and for the fp4 repack the last
case TransformRepackFP4, TransformRepackFP8, TransformRelabelU8:
// These relabel the header (dtype, and for packed weights the last
// dimension); the bytes are unchanged, so the reader is reused.
if len(sources) != 1 {
return nil, fmt.Errorf("transform %s expects 1 source, got %d", ts.Transform, len(sources))
@@ -40,11 +40,17 @@ func applyByteTransform(ts TensorSpec, sources []*safetensors.TensorData) (*safe
}
return validateScalarFloat32TensorData(sources[0], ts.Name)
case TransformF32:
if len(sources) != 1 {
return nil, fmt.Errorf("transform f32 expects 1 source, got %d", len(sources))
}
return validateFloat32TensorData(sources[0], ts.Name)
case TransformReciprocalF32:
if len(sources) != 1 {
return nil, fmt.Errorf("transform reciprocal_f32 expects 1 source, got %d", len(sources))
}
return invertScalarFloat32TensorData(sources[0], ts.Name)
return invertFloat32TensorData(sources[0], ts.Name)
case TransformStackExperts:
return stackExpertTensors(ts.Name, ts.OutDtype, ts.OutShape, sources)
Loaded 100 of 410 files, more files were not shown because too many files have changed in this diff. Show more