Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .claude/skills/nexus-llm-adapters/references/local-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,31 @@ Not wired for local providers, deliberately. See `reasoning-rendering.md`.
## Verification
Local servers are not covered by the live smoke lane. Verify them by hand through
all three paths in `protocols/verify-adapter.md`.

## Where an OpenAI-compatible server says its context
`/v1/models` has no standard limit field. Read, in order: `max_model_len`
(vLLM, SGLang), `context_length` (OpenRouter, Together, Bifrost),
`context_window` (Groq, Bifrost's OpenAI route), `max_context_length`
(Mistral, LM Studio native), `top_provider.context_length`. llama.cpp's
`meta.n_ctx_train` is the trained maximum; the allocated per-slot context is
`default_generation_settings.n_ctx` on `/props`, served beside `/v1`, not under
it. Gateways can strip all of this: Bifrost re-serves custom upstreams as bare
`{id, created, owned_by}`, so a user-entered value must always be possible.

Over-long prompts fail fast and name the limit. vLLM: HTTP 400 "This model's
maximum context length is N tokens". llama.cpp: HTTP 400 with
`error.type: exceed_context_size_error`, `error.n_ctx`, and the message
"request (X tokens) exceeds the available context size (N tokens)". A server
that truncates instead of refusing shows up only as a low
`usage.prompt_tokens`, and that count is not its context: Ollama 0.40 (llama.cpp
runner, `num_ctx` 32,768) kept 16,386 tokens of any longer prompt, so never offer
it as the size. Ollama's `/v1/models` reports no context at all, and its MLX
runner accepted 49,140 tokens with `num_ctx` 32,768. `tests/debug/openai-compatible-context-live.test.ts`
exercises all of this against a real server; for Ollama set
`COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none`.

A chat stores its budget beside the model's whole window at that time
(`chatSettings.modelContextWindow`). When the window later grows, a budget equal
to the old window follows it, on reopen and in an open chat; a smaller one stays.
Chats saved before that field existed are treated as "whole window" only at the
OpenAI-compatible 4,096 fallback.
28 changes: 28 additions & 0 deletions .cline/skills/nexus-llm-adapters/references/local-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,31 @@ Not wired for local providers, deliberately. See `reasoning-rendering.md`.
## Verification
Local servers are not covered by the live smoke lane. Verify them by hand through
all three paths in `protocols/verify-adapter.md`.

## Where an OpenAI-compatible server says its context
`/v1/models` has no standard limit field. Read, in order: `max_model_len`
(vLLM, SGLang), `context_length` (OpenRouter, Together, Bifrost),
`context_window` (Groq, Bifrost's OpenAI route), `max_context_length`
(Mistral, LM Studio native), `top_provider.context_length`. llama.cpp's
`meta.n_ctx_train` is the trained maximum; the allocated per-slot context is
`default_generation_settings.n_ctx` on `/props`, served beside `/v1`, not under
it. Gateways can strip all of this: Bifrost re-serves custom upstreams as bare
`{id, created, owned_by}`, so a user-entered value must always be possible.

Over-long prompts fail fast and name the limit. vLLM: HTTP 400 "This model's
maximum context length is N tokens". llama.cpp: HTTP 400 with
`error.type: exceed_context_size_error`, `error.n_ctx`, and the message
"request (X tokens) exceeds the available context size (N tokens)". A server
that truncates instead of refusing shows up only as a low
`usage.prompt_tokens`, and that count is not its context: Ollama 0.40 (llama.cpp
runner, `num_ctx` 32,768) kept 16,386 tokens of any longer prompt, so never offer
it as the size. Ollama's `/v1/models` reports no context at all, and its MLX
runner accepted 49,140 tokens with `num_ctx` 32,768. `tests/debug/openai-compatible-context-live.test.ts`
exercises all of this against a real server; for Ollama set
`COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none`.

A chat stores its budget beside the model's whole window at that time
(`chatSettings.modelContextWindow`). When the window later grows, a budget equal
to the old window follows it, on reopen and in an open chat; a smaller one stays.
Chats saved before that field existed are treated as "whole window" only at the
OpenAI-compatible 4,096 fallback.
28 changes: 28 additions & 0 deletions .codex/skills/nexus-llm-adapters/references/local-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,31 @@ Not wired for local providers, deliberately. See `reasoning-rendering.md`.
## Verification
Local servers are not covered by the live smoke lane. Verify them by hand through
all three paths in `protocols/verify-adapter.md`.

## Where an OpenAI-compatible server says its context
`/v1/models` has no standard limit field. Read, in order: `max_model_len`
(vLLM, SGLang), `context_length` (OpenRouter, Together, Bifrost),
`context_window` (Groq, Bifrost's OpenAI route), `max_context_length`
(Mistral, LM Studio native), `top_provider.context_length`. llama.cpp's
`meta.n_ctx_train` is the trained maximum; the allocated per-slot context is
`default_generation_settings.n_ctx` on `/props`, served beside `/v1`, not under
it. Gateways can strip all of this: Bifrost re-serves custom upstreams as bare
`{id, created, owned_by}`, so a user-entered value must always be possible.

Over-long prompts fail fast and name the limit. vLLM: HTTP 400 "This model's
maximum context length is N tokens". llama.cpp: HTTP 400 with
`error.type: exceed_context_size_error`, `error.n_ctx`, and the message
"request (X tokens) exceeds the available context size (N tokens)". A server
that truncates instead of refusing shows up only as a low
`usage.prompt_tokens`, and that count is not its context: Ollama 0.40 (llama.cpp
runner, `num_ctx` 32,768) kept 16,386 tokens of any longer prompt, so never offer
it as the size. Ollama's `/v1/models` reports no context at all, and its MLX
runner accepted 49,140 tokens with `num_ctx` 32,768. `tests/debug/openai-compatible-context-live.test.ts`
exercises all of this against a real server; for Ollama set
`COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none`.

A chat stores its budget beside the model's whole window at that time
(`chatSettings.modelContextWindow`). When the window later grows, a budget equal
to the old window follows it, on reopen and in an open chat; a smaller one stays.
Chats saved before that field existed are treated as "whole window" only at the
OpenAI-compatible 4,096 fallback.
28 changes: 28 additions & 0 deletions .skills/nexus-llm-adapters/references/local-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,31 @@ Not wired for local providers, deliberately. See `reasoning-rendering.md`.
## Verification
Local servers are not covered by the live smoke lane. Verify them by hand through
all three paths in `protocols/verify-adapter.md`.

## Where an OpenAI-compatible server says its context
`/v1/models` has no standard limit field. Read, in order: `max_model_len`
(vLLM, SGLang), `context_length` (OpenRouter, Together, Bifrost),
`context_window` (Groq, Bifrost's OpenAI route), `max_context_length`
(Mistral, LM Studio native), `top_provider.context_length`. llama.cpp's
`meta.n_ctx_train` is the trained maximum; the allocated per-slot context is
`default_generation_settings.n_ctx` on `/props`, served beside `/v1`, not under
it. Gateways can strip all of this: Bifrost re-serves custom upstreams as bare
`{id, created, owned_by}`, so a user-entered value must always be possible.

Over-long prompts fail fast and name the limit. vLLM: HTTP 400 "This model's
maximum context length is N tokens". llama.cpp: HTTP 400 with
`error.type: exceed_context_size_error`, `error.n_ctx`, and the message
"request (X tokens) exceeds the available context size (N tokens)". A server
that truncates instead of refusing shows up only as a low
`usage.prompt_tokens`, and that count is not its context: Ollama 0.40 (llama.cpp
runner, `num_ctx` 32,768) kept 16,386 tokens of any longer prompt, so never offer
it as the size. Ollama's `/v1/models` reports no context at all, and its MLX
runner accepted 49,140 tokens with `num_ctx` 32,768. `tests/debug/openai-compatible-context-live.test.ts`
exercises all of this against a real server; for Ollama set
`COMPATIBLE_CONTEXT_OVERSIZE=truncated COMPATIBLE_CONTEXT_REPORTED=none`.

A chat stores its budget beside the model's whole window at that time
(`chatSettings.modelContextWindow`). When the window later grows, a budget equal
to the old window follows it, on reopen and in an open chat; a smaller one stays.
Chats saved before that field existed are treated as "whole window" only at the
OpenAI-compatible 4,096 fallback.
2 changes: 2 additions & 0 deletions docs/plans/openai-compatible-provider-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ Model discovery commonly gives IDs without reliable limits or prices. Keep this

Use one internal metadata resolver keyed by endpoint and model. Accept only validated, documented server metadata with the correct meaning: for example, vLLM's `max_model_len` describes its configured limit, whereas llama.cpp's `meta.n_ctx_train` describes training context, not necessarily the allocated runtime context. Otherwise use an internal budget assumption of 4096 context tokens and 1024 maximum output tokens. These are heuristics, not guaranteed server limits; the tested Ollama process itself reported a 4096-token runtime context. Keep fallback budgeting consistent across dropdowns, pre-send budgeting and compaction rather than inheriting an unrelated static 128K fallback. Output budgeting does not require sending a token-limit field unless normal generation settings request one.

**Revised November 2026 for [#439](https://github.com/ProfSynapse/nexus/issues/439).** A fixed 4096 fallback cannot be raised, and gateways such as Bifrost strip the metadata above, so a 128K model was compacted at about 4K. Each saved model now carries an optional context window. The user's value wins, then the server's report (refreshed on every Connect), then 4096. Discovery reads `max_model_len`, `context_length`, `context_window`, `max_context_length` and `top_provider.context_length`. For a single-model llama.cpp server, which marks its entry with `meta`, discovery asks `/props` for the allocated `n_ctx` rather than using `n_ctx_train`. A **Check** button sends one prompt of the chosen size with `max_tokens: 1` and reports one of: fits, refused (with the limit the server named), or silently shortened (detected from `usage.prompt_tokens`). It never runs automatically, because a prompt that fits is read in full, which takes time locally and is billed by hosted endpoints. The 1024 output assumption is unchanged.

The generic contract supports standard text and tool calling and prefers streaming. Optional image/structured-output capabilities use reliable metadata or existing established capability rules; do not invent support from model names. Unsupported requests fail visibly. Reasoning display follows the normal chat path, with no endpoint-specific control.

Unknown pricing remains unknown, not zero. Preserve token usage and adapt touched cost consumers to tolerate missing prices without inventing a custom pricing editor. Keep this change narrow; existing known-price providers retain their behavior.
Expand Down
70 changes: 60 additions & 10 deletions src/components/openai-compatible/OpenAICompatibleEditSession.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import type { LLMProviderConfig } from '../../types/llm/ProviderTypes';
import type { LLMProviderConfig, OpenAICompatibleModelDefinition } from '../../types/llm/ProviderTypes';
import {
discoverOpenAICompatibleModels,
isOpenAICompatibleContextWindow,
isOpenAICompatibleModelId,
normalizeOpenAICompatibleBaseUrl,
OPENAI_COMPATIBLE_MAX_CONTEXT_WINDOW,
OPENAI_COMPATIBLE_MIN_CONTEXT_WINDOW,
resolveOpenAICompatibleContextWindow,
} from '../../services/llm/adapters/openai-compatible/OpenAICompatibleConfig';
import {
checkOpenAICompatibleContextWindow,
type OpenAICompatibleContextCheckResult,
} from '../../services/llm/adapters/openai-compatible/OpenAICompatibleContextCheck';

export type CompatibleEndpointConfig = LLMProviderConfig & {
driverKind: 'openai-compatible';
openaiCompatible: {
schemaVersion: 1;
displayName: string;
baseUrl: string;
models: Record<string, { source: 'discovered' | 'manual' }>;
models: Record<string, OpenAICompatibleModelDefinition>;
};
};

Expand Down Expand Up @@ -42,6 +50,7 @@ export class OpenAICompatibleEditSession {
config: CompatibleEndpointConfig,
private readonly persist: (id: string, config: CompatibleEndpointConfig) => Promise<void>,
private readonly discover = discoverOpenAICompatibleModels,
private readonly check = checkOpenAICompatibleContextWindow,
) {
this.draft = copyEndpoint(config);
}
Expand All @@ -67,6 +76,43 @@ export class OpenAICompatibleEditSession {
this.draft.models = { ...this.draft.models, [id]: { ...this.draft.models?.[id], enabled } };
}

/** Undefined clears the user's value, so the server's report or the default applies again. */
setContextWindow(id: string, value: number | undefined): void {
const definition = this.draft.openaiCompatible.models[id];
if (!definition) throw new Error('This model is not in the list.');
if (value !== undefined && !isOpenAICompatibleContextWindow(value)) {
throw new Error(`Enter a whole number of tokens from ${OPENAI_COMPATIBLE_MIN_CONTEXT_WINDOW.toLocaleString()} to ${OPENAI_COMPATIBLE_MAX_CONTEXT_WINDOW.toLocaleString()}.`);
}
const next = { ...definition };
if (value === undefined) delete next.contextWindow;
else next.contextWindow = value;
this.draft.openaiCompatible.models = { ...this.draft.openaiCompatible.models, [id]: next };
}

/**
* Adopts a size a check revealed. When the server reports that same size,
* the user's value is cleared so the model follows the server's report
* instead of pinning a copy that would outlive a later server change.
* Returns the value the field should show ('' when following the server).
*/
useContextWindow(id: string, value: number): string {
const followsServer = this.draft.openaiCompatible.models[id]?.reportedContextWindow === value;
this.setContextWindow(id, followsServer ? undefined : value);
return followsServer ? '' : String(value);
}

/** Sends one prompt of the model's current context size; the caller saves nothing on its behalf. */
async checkContextWindow(id: string, signal?: AbortSignal): Promise<OpenAICompatibleContextCheckResult> {
const error = this.validationError();
if (error) throw new Error(error);
const definition = this.draft.openaiCompatible.models[id];
if (!definition) throw new Error('This model is not in the list.');
return this.check({
baseUrl: this.draft.openaiCompatible.baseUrl, apiKey: this.draft.apiKey, model: id,
contextWindow: resolveOpenAICompatibleContextWindow(definition).contextWindow, signal,
});
}

validationError(): string | null {
if (!this.draft.openaiCompatible.displayName.trim()) return 'Enter a name for this endpoint.';
try {
Expand Down Expand Up @@ -106,17 +152,21 @@ export class OpenAICompatibleEditSession {
const baseUrl = normalizeOpenAICompatibleBaseUrl(this.draft.openaiCompatible.baseUrl);
const key = this.draft.apiKey;
try {
const ids = await this.discover(baseUrl, key);
const discovered = await this.discover(baseUrl, key);
if (this.closed || revision !== this.revision) return 'stale';
for (const id of new Set(ids)) {
if (!Object.prototype.hasOwnProperty.call(this.draft.openaiCompatible.models, id)) {
this.draft.openaiCompatible.models = { ...this.draft.openaiCompatible.models, [id]: { source: 'discovered' } };
this.setModelEnabled(id, true);
}
for (const { id, contextWindow } of discovered) {
const existing = Object.prototype.hasOwnProperty.call(this.draft.openaiCompatible.models, id)
? this.draft.openaiCompatible.models[id] : undefined;
// The report is refreshed on every Connect; the user's own value is never touched.
const next = { ...(existing ?? { source: 'discovered' as const }) };
if (contextWindow === undefined) delete next.reportedContextWindow;
else next.reportedContextWindow = contextWindow;
this.draft.openaiCompatible.models = { ...this.draft.openaiCompatible.models, [id]: next };
if (!existing) this.setModelEnabled(id, true);
}
if (ids.length > 0) this.draft.enabled = true;
if (discovered.length > 0) this.draft.enabled = true;
await this.save();
return this.closed || revision !== this.revision ? 'stale' : ids.length ? 'connected' : 'empty';
return this.closed || revision !== this.revision ? 'stale' : discovered.length ? 'connected' : 'empty';
} catch (error) {
if (this.closed || revision !== this.revision) return 'stale';
throw error;
Expand Down
Loading
Loading