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
5 changes: 5 additions & 0 deletions docs-site/src/content/docs/fr/guides/ollama-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ Tous les autres chemins `/api/*` restent dans l'API de gestion d'opencodex.
- `options` : `temperature`, `top_p`, `num_predict` et `stop`.
- `format` : uniquement `"json"`.

Chaque requête `/api/chat` accepte au maximum **1 024 appels d’outils au total** dans l’ensemble des messages
assistant, y compris ceux qui ont déjà un résultat. Au-delà, elle renvoie HTTP 400 avant d’atteindre
un fournisseur. Raccourcissez l’historique de la conversation et renvoyez-le, en conservant chaque
résultat d’outil avec l’appel correspondant dans le message assistant.

Tout le reste est refusé avec un HTTP 400 au lieu d'être ignoré : `think`, `keep_alive`, `suffix`, `raw`,
`template`, `context`, les autres `options`, un `format` en schéma JSON et les URL d'images. Les points de
terminaison Ollama de gestion des modèles et d'embeddings ne sont pas fournis.
Expand Down
5 changes: 5 additions & 0 deletions docs-site/src/content/docs/guides/ollama-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ Every other `/api/*` path stays part of the opencodex management API.
- `options`: `temperature`, `top_p`, `num_predict` and `stop`.
- `format`: `"json"` only.

Each `/api/chat` request accepts at most **1,024 tool calls in total** across all assistant messages,
including calls that already have tool results. Above this limit, the request returns HTTP 400
before reaching a provider. Shorten the conversation history and resend it, keeping each retained
tool result together with its corresponding assistant tool call.

Anything else is rejected with HTTP 400 instead of being ignored. That includes `think`,
`keep_alive`, `suffix`, `raw`, `template`, `context`, other `options`, JSON-schema `format` and image
URLs. Ollama's model-management and embedding endpoints are not provided.
Expand Down
4 changes: 4 additions & 0 deletions docs-site/src/content/docs/ja/guides/ollama-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ curl "$OLLAMA_HOST/api/tags"
- `options`: `temperature`、`top_p`、`num_predict`、`stop`。
- `format`: `"json"` のみ。

各 `/api/chat` リクエストでは、すべての assistant メッセージを合わせて **ツール呼び出しは最大 1,024 件**です。
結果がすでに返された呼び出しも含みます。上限を超えると、プロバイダーに送信される前に HTTP 400 が返されます。
会話履歴を短くして再送してください。残すツール結果と、それに対応する assistant のツール呼び出しは必ず一緒に残します。

それ以外は無視されず、HTTP 400 で拒否されます。`think`、`keep_alive`、`suffix`、`raw`、`template`、
`context`、その他の `options`、JSON スキーマ形式の `format`、画像 URL が該当します。Ollama のモデル管理および
埋め込みエンドポイントは提供されません。
Expand Down
4 changes: 4 additions & 0 deletions docs-site/src/content/docs/ko/guides/ollama-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ curl "$OLLAMA_HOST/api/tags"
- `options`: `temperature`, `top_p`, `num_predict`, `stop`.
- `format`: `"json"`만 지원합니다.

각 `/api/chat` 요청은 모든 assistant 메시지에 걸쳐 **도구 호출을 합계 1,024개까지** 허용합니다.
이미 결과가 있는 호출도 합계에 포함됩니다. 한도를 넘으면 프로바이더로 보내기 전에 HTTP 400을 반환합니다.
대화 이력을 줄인 뒤 다시 보내세요. 남겨 둔 도구 결과에는 해당 assistant 도구 호출도 함께 남겨야 합니다.

그 밖의 항목은 무시되지 않고 HTTP 400으로 거부됩니다. `think`, `keep_alive`, `suffix`, `raw`,
`template`, `context`, 기타 `options`, JSON 스키마 `format`, 이미지 URL이 여기에 해당합니다. Ollama의 모델
관리 및 임베딩 엔드포인트는 제공되지 않습니다.
Expand Down
5 changes: 5 additions & 0 deletions docs-site/src/content/docs/ru/guides/ollama-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ curl "$OLLAMA_HOST/api/tags"
- `options`: `temperature`, `top_p`, `num_predict` и `stop`.
- `format`: только `"json"`.

Каждый запрос `/api/chat` допускает **не более 1 024 вызовов инструментов суммарно** во всех сообщениях
assistant, включая вызовы, для которых уже есть результаты. При превышении лимита запрос возвращает
HTTP 400 до отправки провайдеру. Сократите историю диалога и отправьте её снова, сохраняя каждый
оставленный результат инструмента вместе с соответствующим вызовом в сообщении assistant.

Всё остальное отклоняется с HTTP 400, а не игнорируется: `think`, `keep_alive`, `suffix`, `raw`,
`template`, `context`, прочие `options`, `format` в виде JSON-схемы и URL изображений. Конечные точки Ollama для
управления моделями и эмбеддингов не предоставляются.
Expand Down
5 changes: 5 additions & 0 deletions docs-site/src/content/docs/tr/guides/ollama-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ Diğer tüm `/api/*` yolları opencodex yönetim API'sinin parçası olarak kal
- `options`: `temperature`, `top_p`, `num_predict` ve `stop`.
- `format`: yalnızca `"json"`.

Her `/api/chat` isteği, tüm assistant mesajlarında **toplam en fazla 1.024 araç çağrısı** kabul eder;
sonucu zaten bulunan çağrılar da bu sayıya dahildir. Sınır aşılırsa istek sağlayıcıya ulaşmadan HTTP 400
döndürür. Konuşma geçmişini kısaltıp yeniden gönderin; tuttuğunuz her araç sonucuyla birlikte ilgili
assistant araç çağrısını da koruyun.

Bunların dışındaki her şey yok sayılmak yerine HTTP 400 ile reddedilir: `think`, `keep_alive`, `suffix`,
`raw`, `template`, `context`, diğer `options`, JSON şeması biçimindeki `format` ve görsel URL'leri. Ollama'nın
model yönetimi ve embedding uç noktaları sağlanmaz.
Expand Down
4 changes: 4 additions & 0 deletions docs-site/src/content/docs/zh-cn/guides/ollama-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ curl "$OLLAMA_HOST/api/tags"
- `options`:`temperature`、`top_p`、`num_predict` 和 `stop`。
- `format`:仅支持 `"json"`。

每个 `/api/chat` 请求中,所有 assistant 消息的**工具调用总数最多为 1,024 次**,已返回结果的调用也计入总数。
超过上限时,请求会在发送给提供商之前返回 HTTP 400。请缩短对话历史后重试,并将保留的工具结果与对应的
assistant 工具调用一起保留。

其他内容会以 HTTP 400 拒绝,而不是被忽略,包括 `think`、`keep_alive`、`suffix`、`raw`、
`template`、`context`、其他 `options`、JSON Schema 形式的 `format` 以及图片 URL。不提供 Ollama 的模型管理和
嵌入端点。
Expand Down
4 changes: 4 additions & 0 deletions docs-site/src/content/docs/zh-tw/guides/ollama-clients.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ curl "$OLLAMA_HOST/api/tags"
- `options`:`temperature`、`top_p`、`num_predict` 與 `stop`。
- `format`:僅支援 `"json"`。

每個 `/api/chat` 請求中,所有 assistant 訊息的**工具呼叫總數最多為 1,024 次**,已傳回結果的呼叫也計入總數。
超過上限時,請求會在傳送給供應商之前回傳 HTTP 400。請縮短對話歷史後重試,並將保留的工具結果與對應的
assistant 工具呼叫一起保留。

其他內容會以 HTTP 400 拒絕,而不是被忽略,包括 `think`、`keep_alive`、`suffix`、`raw`、
`template`、`context`、其他 `options`、JSON Schema 形式的 `format` 以及圖片 URL。不提供 Ollama 的模型管理與
嵌入端點。
Expand Down
34 changes: 22 additions & 12 deletions src/protocols/codecs/ollama.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/** Pure Ollama native request and Chat response projections. */
type Obj = Record<string, unknown>;
export type OllamaKind = "chat" | "generate";
export const MAX_OLLAMA_TOOL_CALLS = 1_024;
type PendingCall = { id: string; name: string; group: Set<PendingCall>; matched: boolean };
export class OllamaCodecError extends Error {
readonly status = 400;
readonly code = "invalid_ollama_request";
Expand Down Expand Up @@ -63,7 +65,9 @@ export function ollamaToChat(kind: OllamaKind, input: unknown): Obj {
messages.push({ role: "user", content: content(body.prompt, body.images) });
} else {
if (!Array.isArray(body.messages)) fail("Invalid messages");
const pending: { id: string; name: string; message: number; matched: boolean }[] = [];
const pendingById = new Map<string, PendingCall>();
const pendingByName = new Map<string, Set<PendingCall>[]>();
let callCount = 0;
body.messages.forEach((raw, mi) => {
const msg = object(raw, "message");
const role = string(msg.role, "role");
Expand All @@ -72,30 +76,36 @@ export function ollamaToChat(kind: OllamaKind, input: unknown): Obj {
const projected: Obj = { role, content: content(msg.content, role === "user" ? msg.images : undefined) };
if (role === "assistant" && msg.tool_calls !== undefined) {
if (!Array.isArray(msg.tool_calls)) fail("Invalid tool calls");
if (callCount + msg.tool_calls.length > MAX_OLLAMA_TOOL_CALLS) fail("Too many tool calls");
callCount += msg.tool_calls.length;
const groups = new Map<string, Set<PendingCall>>();
projected.tool_calls = msg.tool_calls.map((rawCall, ci) => {
// A replayed response call keeps the id this proxy returned for it; older clients send none.
const call = object(rawCall, "tool call"); keys(call, ["id", "function"], "tool call");
const fn = object(call.function, "tool call function"); keys(fn, ["name", "arguments"], "tool call function");
const name = string(fn.name, "tool name", true); const args = object(fn.arguments, "tool arguments");
const id = call.id === undefined ? `call_ollama_${mi}_${ci}` : string(call.id, "tool call id", true);
if (pending.some(p => p.id === id)) fail("Duplicate tool call id");
pending.push({ id, name, message: mi, matched: false });
if (pendingById.has(id)) fail("Duplicate tool call id");
const group = groups.get(name) ?? new Set<PendingCall>(); groups.set(name, group);
const pending: PendingCall = { id, name, group, matched: false }; group.add(pending); pendingById.set(id, pending);
return { id, type: "function", function: { name, arguments: JSON.stringify(args) } };
});
for (const [name, group] of groups) {
const named = pendingByName.get(name) ?? []; named.push(group); pendingByName.set(name, named);
}
}
if (role === "tool") {
const id = msg.tool_call_id === undefined ? undefined : string(msg.tool_call_id, "tool call id", true);
const name = msg.tool_name === undefined ? undefined : string(msg.tool_name, "tool name", true);
const candidates = pending.filter(p => !p.matched && (id ? p.id === id && (!name || p.name === name) : name && p.name === name));
if (!id && name && candidates.length) {
const latestMessage = candidates[candidates.length - 1]!.message;
const latest = candidates.filter(p => p.message === latestMessage);
if (latest.length !== 1) fail("Ambiguous tool result");
latest[0]!.matched = true; projected.tool_call_id = latest[0]!.id;
} else {
if (candidates.length !== 1) fail("Unmatched tool result");
candidates[0]!.matched = true; projected.tool_call_id = candidates[0]!.id;
let candidate: PendingCall | undefined;
if (id) candidate = pendingById.get(id);
else if (name) {
const groups = pendingByName.get(name); while (groups?.length && !groups.at(-1)!.size) groups.pop();
const group = groups?.at(-1); if (group && group.size !== 1) fail("Ambiguous tool result");
candidate = group?.values().next().value;
}
if (!candidate || candidate.matched || (name && candidate.name !== name)) fail("Unmatched tool result");
candidate.matched = true; candidate.group.delete(candidate); projected.tool_call_id = candidate.id;
}
messages.push(projected);
});
Expand Down
4 changes: 3 additions & 1 deletion structure/data-planes/ollama-inbound.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ key's model scope. Show returns no file, digest, template or license facts.

`src/protocols/codecs/ollama.ts` validates the native body (unknown fields and options, `think`,
`keep_alive`, non-JSON formats and remote images are 400s) and projects it to Chat; base64 images
become Chat `image_url` data URLs with the sniffed media type. `src/server/ollama-inbound.ts` calls
become Chat `image_url` data URLs with the sniffed media type. Chat requests accept at most 1,024
tool calls in aggregate, and tool-call IDs and pending results are indexed so validation work stays
linear in the request size. `src/server/ollama-inbound.ts` calls
`handleChatCompletions` with a synthesized request carrying only the content type, caller session
and workflow identity headers (`session_id`, `session-id`, `thread-id`, `x-session-id`,
`x-codex-parent-thread-id`, so the workflow root's spend ceiling still applies) and the client
Expand Down
43 changes: 42 additions & 1 deletion tests/responses/responses-ollama-codec.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { ollamaToChat, ollamaBufferedResponse, createOllamaStreamState, consumeOllamaChatChunk, ollamaStreamTerminal, OllamaCodecError } from "../../src/protocols/codecs/ollama";
import { ollamaToChat, ollamaBufferedResponse, createOllamaStreamState, consumeOllamaChatChunk, ollamaStreamTerminal, OllamaCodecError, MAX_OLLAMA_TOOL_CALLS } from "../../src/protocols/codecs/ollama";

const png = "iVBORw0KGgo=";
const schema = { type: "object", properties: { q: { type: "string", enum: ["a", "b"] } }, required: ["q"], additionalProperties: false };
Expand Down Expand Up @@ -40,6 +40,47 @@ describe("Ollama codec", () => {
expect(() => ollamaToChat("chat", { model: "m", messages: duplicate })).toThrow(OllamaCodecError);
expect(() => ollamaToChat("chat", { model: "m", messages: [{ role: "assistant", content: "", tool_calls: [{ id: 7, function: { name: "f", arguments: {} } }] }] })).toThrow(OllamaCodecError);
});
test("bounds aggregate tool-call validation work", () => {
expect(MAX_OLLAMA_TOOL_CALLS).toBe(1_024);
const calls = Array.from({ length: MAX_OLLAMA_TOOL_CALLS }, (_, i) => ({ id: `id${i}`, function: { name: "f", arguments: {} } }));
expect((ollamaToChat("chat", { model: "m", messages: [{ role: "assistant", content: "", tool_calls: calls }] }).messages as any[])[0].tool_calls).toHaveLength(MAX_OLLAMA_TOOL_CALLS);
calls.push({ id: "overflow", function: { name: "f", arguments: {} } });
expect(() => ollamaToChat("chat", { model: "m", messages: [{ role: "assistant", content: "", tool_calls: calls }] })).toThrow("Too many tool calls");
});
test("counts calls across assistant messages even after their results are matched", () => {
const calls = Array.from({ length: 1_024 }, (_, i) => ({ id: `id${i}`, function: { name: "f", arguments: {} } }));
const laterCalls = calls.slice(512);
const messages = [
{ role: "assistant", content: "", tool_calls: calls.slice(0, 512) },
...calls.slice(0, 512).map(call => ({ role: "tool", content: "done", tool_call_id: call.id })),
{ role: "assistant", content: "", tool_calls: laterCalls },
];
const accepted = ollamaToChat("chat", { model: "m", messages }).messages as { tool_calls?: unknown[] }[];
expect(accepted.at(-1)!.tool_calls).toHaveLength(512);
laterCalls.push({ id: "overflow", function: { name: "f", arguments: {} } });
expect(() => ollamaToChat("chat", { model: "m", messages })).toThrow("Too many tool calls");
});
test("matches the latest unambiguous name group before falling back to earlier calls", () => {
const call = (id: string) => ({ id, function: { name: "f", arguments: {} } });
const history = [
{ role: "assistant", content: "", tool_calls: [call("older")] },
{ role: "assistant", content: "", tool_calls: [call("newer-a"), call("newer-b")] },
];
const byName = { role: "tool", content: "done", tool_name: "f" };
expect(() => ollamaToChat("chat", { model: "m", messages: [...history, byName] })).toThrow("Ambiguous tool result");
const messages = [...history, { role: "tool", content: "done", tool_call_id: "newer-b" }, byName, byName];
const matched = ollamaToChat("chat", { model: "m", messages }).messages as { tool_call_id?: string }[];
expect(matched.slice(2).map(message => message.tool_call_id)).toEqual(["newer-b", "newer-a", "older"]);
});
test("keeps duplicate IDs reserved after a result and refuses mismatched explicit IDs", () => {
const assistant = { role: "assistant", content: "", tool_calls: [{ id: "stable", function: { name: "f", arguments: {} } }] };
const result = { role: "tool", content: "done", tool_call_id: "stable" };
expect(() => ollamaToChat("chat", { model: "m", messages: [assistant, result, assistant] })).toThrow("Duplicate tool call id");
for (const unmatched of [
{ ...result, tool_name: "other" },
{ ...result, tool_call_id: "missing", tool_name: "f" },
]) expect(() => ollamaToChat("chat", { model: "m", messages: [assistant, unmatched] })).toThrow("Unmatched tool result");
});
test("rejects unsupported and malformed shapes with bounded errors", () => {
for (const body of [
{ model: "m", prompt: "x", suffix: "y" }, { model: "m", prompt: "x", think: false },
Expand Down
17 changes: 17 additions & 0 deletions tests/server/server-ollama-inbound.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,23 @@ describe("Ollama-compatible inbound routes", () => {
});
}

test("chat refuses aggregate tool-call overflow before any upstream send", async () => {
const calls = Array.from({ length: 1_025 }, (_, i) => ({ id: `call_${i}`, function: { name: "lookup", arguments: {} } }));
await withServer(async base => {
for (const stream of [false, true]) {
const res = await post(base, "/api/chat", { model: "fx/m1", stream, messages: [
{ role: "assistant", content: "", tool_calls: calls.slice(0, 512) },
{ role: "assistant", content: "", tool_calls: calls.slice(512) },
] });
expect(res.status).toBe(400);
expect(await res.json()).toEqual({ error: "Too many tool calls" });
expect(rowFor(res)!.status).toBe(400);
}
expect(seen).toHaveLength(0);
expect(newRows()).toHaveLength(2);
});
});

test("chat tools round trip with stable call ids", async () => {
mode = "tools";
await withServer(async base => {
Expand Down
Loading