Skip to content
Closed
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
127 changes: 127 additions & 0 deletions src/__tests__/split-image-turns.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import { afterEach, describe, expect, it } from "vitest";
import type { ChatCompletionRequest, Fixture } from "../types.js";
import { createServer, type ServerInstance } from "../server.js";
import { claudeToCompletionRequest } from "../messages.js";
import { geminiToCompletionRequest } from "../gemini.js";
import { geminiInteractionsToCompletionRequest } from "../gemini-interactions.js";
import { bedrockToCompletionRequest } from "../bedrock.js";
import { converseToCompletionRequest } from "../bedrock-converse.js";
import { cohereToCompletionRequest } from "../cohere.js";

const PROMPT = "what is in this image";
const PNG = "iVBORw0KGgo=";
const DATA_URL = `data:image/png;base64,${PNG}`;
const claudeImage = {
type: "image",
source: { type: "base64", media_type: "image/png", data: PNG },
};
const interactionsImage = { type: "image", data: PNG, mime_type: "image/png" };

interface Wire {
name: string;
path: string;
body: (...messages: unknown[]) => Record<string, unknown>;
text: (text: string) => unknown;
image: unknown;
convert: (body: never) => ChatCompletionRequest;
}

const anthropicMessages = (...messages: unknown[]) => ({
model: "claude-sonnet-4-5",
max_tokens: 64,
messages,
});
const claudeText = (text: string) => ({ role: "user", content: [{ type: "text", text }] });

const wires: Wire[] = [
{
name: "Anthropic Messages",
path: "/v1/messages",
body: anthropicMessages,
text: claudeText,
image: { role: "user", content: [claudeImage] },
convert: claudeToCompletionRequest,
},
{
name: "Gemini generateContent",
path: "/v1beta/models/gemini-2.5-flash:generateContent",
body: (...contents) => ({ contents }),
text: (text) => ({ role: "user", parts: [{ text }] }),
image: { role: "user", parts: [{ inlineData: { mimeType: "image/png", data: PNG } }] },
convert: (b) => geminiToCompletionRequest(b, "gemini-2.5-flash", false),
},
{
name: "Gemini Interactions steps",
path: "/v1beta/interactions",
body: (...input) => ({ model: "gemini-2.5-flash", stream: false, input }),
text: (text) => ({ type: "user_input", content: [{ type: "text", text }] }),
image: { type: "user_input", content: [interactionsImage] },
convert: geminiInteractionsToCompletionRequest,
},
{
name: "Gemini Interactions turns",
path: "/v1beta/interactions",
body: (...input) => ({ model: "gemini-2.5-flash", stream: false, input }),
text: (text) => ({ role: "user", content: [{ type: "text", text }] }),
image: { role: "user", content: [interactionsImage] },
convert: geminiInteractionsToCompletionRequest,
},
{
name: "Bedrock invoke",
path: "/model/claude/invoke",
body: (...messages) => ({ anthropic_version: "bedrock-2023-05-31", max_tokens: 64, messages }),
text: claudeText,
image: { role: "user", content: [claudeImage] },
convert: (b) => bedrockToCompletionRequest(b, "claude"),
},
{
name: "Bedrock Converse",
path: "/model/claude/converse",
body: (...messages) => ({ messages }),
text: (text) => ({ role: "user", content: [{ text }] }),
image: { role: "user", content: [{ image: { format: "png", source: { bytes: PNG } } }] },
convert: (b) => converseToCompletionRequest(b, "claude"),
},
{
name: "Cohere v2",
path: "/v2/chat",
body: (...messages) => ({ model: "command-a-vision", messages }),
text: (text) => ({ role: "user", content: [{ type: "text", text }] }),
image: { role: "user", content: [{ type: "image_url", image_url: { url: DATA_URL } }] },
convert: cohereToCompletionRequest,
},
];

const fixtures: Fixture[] = [{ match: { userMessage: PROMPT }, response: { content: "A logo." } }];

let instance: ServerInstance | null = null;

afterEach(async () => {
if (instance) {
await new Promise<void>((resolve) => instance!.server.close(() => resolve()));
instance = null;
}
});

describe.each(wires)("$name: prompt split from its image", (wire) => {
it("matches the prompt when an image only user message follows it", async () => {
instance = await createServer(fixtures, { strict: true });
const res = await fetch(`${instance.url}${wire.path}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(wire.body(wire.text(PROMPT), wire.image)),
});
expect(res.status).toBe(200);
expect(await res.text()).toContain("A logo.");
});

it("leaves an image only user message text less (null)", () => {
const { messages } = wire.convert(wire.body(wire.text(PROMPT), wire.image) as never);
expect(messages.map((m) => m.content)).toEqual([PROMPT, null]);
});

it("keeps an explicit empty text part as an empty string", () => {
const { messages } = wire.convert(wire.body(wire.text(""), wire.image) as never);
expect(messages.at(0)?.content).toBe("");
});
});
3 changes: 2 additions & 1 deletion src/bedrock-converse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,8 @@ export function converseToCompletionRequest(
.filter((b) => b.text !== undefined && b.text !== "")
.map((b) => b.text ?? "")
.join("");
messages.push({ role: "user", content: text });
const hasText = msg.content.length === 0 || msg.content.some((b) => "text" in b);
messages.push({ role: "user", content: hasText ? text : null });
} else if (msg.role === "assistant") {
const toolUseBlocks = msg.content.filter((b) => b.toolUse);
const textContent = msg.content
Expand Down
12 changes: 11 additions & 1 deletion src/bedrock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,16 @@ function extractTextContent(content: string | BedrockContentBlock[] | null | und
.join("");
}

function extractUserContent(
content: string | BedrockContentBlock[] | null | undefined,
): string | null {
const hasText =
!Array.isArray(content) ||
content.length === 0 ||
content.some((b) => b !== null && b !== undefined && b.type === "text");
return hasText ? extractTextContent(content) : null;
}

export function bedrockToCompletionRequest(
req: BedrockRequest,
modelId: string,
Expand Down Expand Up @@ -201,7 +211,7 @@ export function bedrockToCompletionRequest(
}
messages.push({
role: "user",
content: extractTextContent(msg.content),
content: extractUserContent(msg.content),
});
} else if (msg.role === "assistant") {
if (typeof msg.content === "string") {
Expand Down
12 changes: 11 additions & 1 deletion src/cohere.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,16 @@ function extractTextContent(content: string | CohereContentPart[] | null | undef
.join("");
}

function extractUserContent(
content: string | CohereContentPart[] | null | undefined,
): string | null {
const hasText =
!Array.isArray(content) ||
content.length === 0 ||
content.some((part) => part !== null && part !== undefined && part.type === "text");
return hasText ? extractTextContent(content) : null;
}

/** Type guard: is this an OpenAI-style tool definition (has `function` key)? */
function isOpenAIToolDef(t: CohereToolDef): t is CohereToolDefOpenAI {
return "function" in t && typeof (t as CohereToolDefOpenAI).function === "object";
Expand All @@ -168,7 +178,7 @@ export function cohereToCompletionRequest(req: CohereRequest): ChatCompletionReq
if (msg.role === "system") {
messages.push({ role: "system", content: textContent });
} else if (msg.role === "user") {
messages.push({ role: "user", content: textContent });
messages.push({ role: "user", content: extractUserContent(msg.content) });
} else if (msg.role === "assistant") {
if (msg.tool_calls && msg.tool_calls.length > 0) {
messages.push({
Expand Down
14 changes: 8 additions & 6 deletions src/gemini-interactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,9 @@ export function geminiInteractionsToCompletionRequest(
} else {
// Text-only turn
const text = textParts.map((p) => p.text ?? "").join("");
if (role === "user" || role === "assistant" || role === "system") {
if (role === "user" && textParts.length === 0) {
messages.push({ role: "user", content: null });
} else if (role === "user" || role === "assistant" || role === "system") {
messages.push({
role: role as "user" | "assistant" | "system",
content: text,
Expand All @@ -267,11 +269,11 @@ export function geminiInteractionsToCompletionRequest(
// Step[] format — the wire contract Google's /v1beta/interactions accepts.
for (const step of req.input as InteractionsStep[]) {
if (step.type === "user_input") {
const text = (step.content ?? [])
.filter((p) => p.type === "text")
.map((p) => p.text ?? "")
.join("");
messages.push({ role: "user", content: text });
const parts = step.content ?? [];
const textParts = parts.filter((p) => p.type === "text");
const text = textParts.map((p) => p.text ?? "").join("");
const hasText = textParts.length > 0 || parts.length === 0;
messages.push({ role: "user", content: hasText ? text : null });
} else if (step.type === "model_output") {
const blocks = step.content ?? [];
const funcCallParts = blocks.filter((p) => p.type === "function_call");
Expand Down
3 changes: 2 additions & 1 deletion src/gemini.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,8 @@ export function geminiToCompletionRequest(
} else {
// Regular user text
const text = textParts.map((p) => p.text!).join("");
messages.push({ role: "user", content: text });
const hasText = textParts.length > 0 || parts.length === 0;
messages.push({ role: "user", content: hasText ? text : null });
}
} else if (role === "model") {
// Check for functionCall parts
Expand Down
10 changes: 9 additions & 1 deletion src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,14 @@ function extractClaudeTextContent(content: string | ClaudeContentBlock[]): strin
.join("");
}

function extractClaudeUserContent(content: string | ClaudeContentBlock[]): string | null {
const hasText =
!Array.isArray(content) ||
content.length === 0 ||
content.some((b) => b != null && typeof b === "object" && b.type === "text");
return hasText ? extractClaudeTextContent(content) : null;
}

export function claudeToCompletionRequest(req: ClaudeRequest): ChatCompletionRequest {
const messages: ChatMessage[] = [];

Expand Down Expand Up @@ -231,7 +239,7 @@ export function claudeToCompletionRequest(req: ClaudeRequest): ChatCompletionReq
// Regular user message
messages.push({
role: "user",
content: extractClaudeTextContent(msg.content),
content: extractClaudeUserContent(msg.content),
});
} else if (msg.role === "assistant") {
if (typeof msg.content === "string") {
Expand Down
Loading