Skip to content
Open
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
31 changes: 27 additions & 4 deletions src/adapter/openai-to-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* Converts OpenAI chat request format to Claude CLI input
*/

import type { OpenAIChatRequest } from "../types/openai.js";
import type { OpenAIChatRequest, OpenAIContentPart } from "../types/openai.js";

export type ClaudeModel = "opus" | "sonnet" | "haiku";

Expand Down Expand Up @@ -46,6 +46,28 @@ export function extractModel(model: string): ClaudeModel {
return "opus";
}

/**
* Extract text from an OpenAI content field.
*
* The OpenAI Chat API accepts `content` as either a plain string or an array
* of content parts (e.g. `[{ type: "text", text: "hello" }]`). Many upstream
* callers (OpenClaw, LiteLLM, …) send the array form even for text-only
* messages. This helper normalises both representations to a single string.
*/
function extractContent(content: string | OpenAIContentPart[]): string {
if (typeof content === "string") {
return content;
}
if (Array.isArray(content)) {
return content
.filter((part): part is OpenAIContentPart & { text: string } =>
part.type === "text" && typeof part.text === "string")
.map((part) => part.text)
.join("\n");
}
return String(content ?? "");
}

/**
* Convert OpenAI messages array to a single prompt string for Claude CLI
*
Expand All @@ -56,20 +78,21 @@ export function messagesToPrompt(messages: OpenAIChatRequest["messages"]): strin
const parts: string[] = [];

for (const msg of messages) {
const text = extractContent(msg.content);
switch (msg.role) {
case "system":
// System messages become context instructions
parts.push(`<system>\n${msg.content}\n</system>\n`);
parts.push(`<system>\n${text}\n</system>\n`);
break;

case "user":
// User messages are the main prompt
parts.push(msg.content);
parts.push(text);
break;

case "assistant":
// Previous assistant responses for context
parts.push(`<previous_response>\n${msg.content}\n</previous_response>\n`);
parts.push(`<previous_response>\n${text}\n</previous_response>\n`);
break;
}
}
Expand Down
8 changes: 7 additions & 1 deletion src/types/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@
* Used for Clawdbot integration
*/

export interface OpenAIContentPart {
type: "text" | "image_url";
text?: string;
image_url?: { url: string; detail?: string };
}

export interface OpenAIChatMessage {
role: "system" | "user" | "assistant";
content: string;
content: string | OpenAIContentPart[];
}

export interface OpenAIChatRequest {
Expand Down