
上一篇extensions看了三种extensions:
pi.registerTool
pi.registerCommand
pi.on
这篇看Provider,提到这部分我最感兴趣的是在模型/协议切换的时候,pi如何才能在旧的上下文上继续聊下去。
先看看 custom-provider.md 中的介绍,Provider在pi中也属于一种扩展:
# Custom Providers
A provider extension connects Pi to a model service that needs custom authentication, model discovery, request handling, or streaming. If the service already speaks a supported API, configure it in `models.json` instead.
Provider extensions run inside Pi and can inspect credentials, prompts, tool definitions, model responses, and usage. Treat them as trusted code and avoid logging secrets or provider payloads.
## Choose the smallest integration
| Requirement | Use |
|---|---|
| Add models behind a supported API | [`models.json`](models.md#configure-a-compatible-endpoint) |
| Change an existing provider endpoint or headers | `models.json` or a small provider extension |
| Discover models dynamically | A provider with `refreshModels` |
| Add a `/login` flow | A provider with native or legacy OAuth configuration |
| Implement an unsupported wire protocol | A provider with `stream` or `streamSimple` |
A provider extension is an [extension](extensions.md), so it follows the same loading, trust, reload, and error behavior.原来想自己写一个custom-proviers试试的,但是现在基本都是标准的anthropic ,completions,responses 协议,实在是写无可写。已支持的协议,配 models.json 就够了;只有动态发现模型(refreshModels)、加 /login 流程、实现不支持的线上协议(stream 或 streamSimple)这三种情况才需要写 provider。
还是直接看看调用侧的源码:
想不到支持的api还挺多。。
export type KnownApi =
| "openai-completions"
| "mistral-conversations"
| "openai-responses"
| "azure-openai-responses"
| "openai-codex-responses"
| "anthropic-messages"
| "bedrock-converse-stream"
| "google-generative-ai"
| "google-vertex"
| "pi-messages";
export type Api = KnownApi | (string & {});
export function getApiProvider(api: Api): ApiProviderInternal | undefined {
return apiProviderRegistry.get(api)?.provider;
}provider 只负责把模型服务接进来。旧上下文怎么继续聊,发生在每次请求发出之前,所以要看调用侧。
工具类 transcript.ts 里的函数单个都很短,是因为每个 API 实现都要用,所以抽成了公共函数。先看一下抽象出来的原子能力。
normalizeContext 是将Context转成TranscriptContext 的唯一入口,从功能上看就是 初始化SystemPrompt,放在messages第一条
/**
* Build the leading system message for a prompt and tool set. Returns undefined when
* both are empty, so an empty transcript stays empty.
*/
export function createInitialSystemMessage(
systemPrompt: string | undefined,
tools: Tool[] | undefined,
): SystemMessage | undefined {
const hasSystemPrompt = systemPrompt !== undefined && systemPrompt.length > 0;
const hasTools = tools !== undefined && tools.length > 0;
if (!hasSystemPrompt && !hasTools) return undefined;
return {
role: "system",
content: systemPrompt ?? "",
...(hasTools ? { toolsAdded: tools } : {}),
timestamp: 0,
};
}
/**
* Fold `Context.systemPrompt` and `Context.tools` into a leading system message.
* This is the only entry point that produces a {@link TranscriptContext}; every
* provider-facing function expects the result.
*/
export function normalizeContext(context: Context): TranscriptContext {
const initialMessage = createInitialSystemMessage(context.systemPrompt, context.tools);
const messages = initialMessage ? [initialMessage, ...context.messages] : context.messages;
return { messages } as TranscriptContext;
}collapseSystemMessages 是将 messages 中 role == 'system' 的 systemmessage (加减工具这类信息) 收集起来,统一移到 messages的最前面。
/**
* Replay every system message into one leading system message holding the current
* prompt and tools. Later `content` is appended to the base prompt, `sections` are
* patched by name, and tools are resolved with {@link getCurrentTools}.
*/
export function getCurrentSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {
const content: string[] = [];
const sections = new Map<string, string>();
let timestamp: number | undefined;
for (const message of messages) {
if (!isSystemMessage(message)) continue;
timestamp ??= message.timestamp;
const text = contentText(message.content);
if (text.length > 0) content.push(text);
for (const [name, value] of Object.entries(message.sections ?? {})) {
if (value === null) sections.delete(name);
else sections.set(name, value);
}
}
const tools = getCurrentTools(messages);
if (timestamp === undefined && tools.length === 0) return undefined;
return {
role: "system",
content: content.join("\n\n"),
...(sections.size > 0 ? { sections: Object.fromEntries(sections) } : {}),
...(tools.length > 0 ? { toolsAdded: tools } : {}),
timestamp: timestamp ?? 0,
};
}
/** Render the current system prompt text after replaying every system message. */
export function getCurrentSystemPrompt(messages: TranscriptMessages): string {
const message = getCurrentSystemMessage(messages);
return message ? getSystemMessageText(message) : "";
}
/**
* Rebuild the transcript for APIs without mid-conversation system messages: the replayed
* system message leads, and every later system message is dropped.
*/
export function collapseSystemMessages(context: TranscriptContext): TranscriptContext {
const head = getCurrentSystemMessage(context.messages);
const messages = context.messages.filter((message) => message.role !== "system");
return { messages: head ? [head, ...messages] : messages } as TranscriptContext;
}resolveTranscript:开关是supportsMidConvoSystemMessages, 取值顺序是先看模型目录里的 compat,没写再用 detectCompat 的默认值 false。 是否支持在消息中传入 SystemMessage。
/** Keep later system messages in place when the model accepts them; otherwise collapse them. */
export function resolveTranscript(
context: TranscriptContext,
supportsMidConvoSystemMessages: boolean | undefined,
): TranscriptContext {
return supportsMidConvoSystemMessages ? context : collapseSystemMessages(context);
}找到openai-completions.ts 中的 convertMessages。
看到开头其实pi的转换路径还是非常直接的。 所有的session projection messages 在pi内部时,均统一使用pi的标准格式。 只有在最后一步请求模型的时候在provider层进行协议格式的转换。
这样就无需考虑协议间转化的问题了,只要考虑pi和各协议的转化问题。
不过即使是这样看了几个转换方法之后也已经看晕了。 。
想不到就算是同一个协议不同的模型,中间也需要特殊处理。
先看一下最熟的completions 协议的转换过程
const isSameModel =
assistantMsg.provider === model.provider &&
assistantMsg.api === model.api &&
assistantMsg.model === model.id;/**
* Render a later system message for APIs that accept system messages mid-conversation.
* Section changes are framed by name so the model can relate them to the leading prompt.
* This framing is request-time only and may change between versions.
*/
export function renderSystemMessageUpdate(message: SystemMessage): string {
const parts: string[] = [];
const text = contentText(message.content);
if (text.length > 0) parts.push(text);
for (const [name, value] of Object.entries(message.sections ?? {})) {
parts.push(
value === null
? `Removed system prompt section "${name}".`
: `Updated system prompt section "${name}":\n\n${value}`,
);
}
return parts.join("\n\n");
}export function convertMessages(
model: Model<"openai-completions">,
context: TranscriptContext,
compat: ResolvedOpenAICompletionsCompat,
options?: ConvertCompletionsMessagesOptions,
): ChatCompletionMessageParam[] {
const normalizedContext = resolveTranscript(context, compat.supportsMidConvoSystemMessages);
const params: ChatCompletionMessageParam[] = [];
const normalizeToolCallId = (id: string): string => {
// Handle pipe-separated IDs from OpenAI Responses API
// Format: {call_id}|{id} where {id} can be 400+ chars with special chars (+, /, =)
// These come from providers like github-copilot, openai-codex, opencode
// Extract just the call_id part and normalize it
// Multiple tool calls in the same turn can share call_id but differ by item_id.
// Preserve item-level uniqueness when replaying into Chat Completions, which
// requires distinct tool call ids.
if (id.includes("|")) {
// Sanitize to allowed chars and truncate to 40 chars (OpenAI limit)
const separatorIndex = id.indexOf("|");
const callId = id.slice(0, separatorIndex).replace(/[^a-zA-Z0-9_-]/g, "_");
const itemId = id.slice(separatorIndex + 1).replace(/[^a-zA-Z0-9_-]/g, "_");
const combinedId = itemId.length > 0 ? `${callId}_${itemId}` : callId;
if (combinedId.length <= 40) {
return combinedId;
}
const hash = shortHash(id).slice(0, 8);
const prefix = callId.slice(0, Math.max(1, 40 - hash.length - 1));
return `${prefix}_${hash}`;
}
if (model.provider === "openai") return id.length > 40 ? id.slice(0, 40) : id;
return id;
};
const transformedMessages = transformMessages(normalizedContext.messages, model, (id) => normalizeToolCallId(id));
const transcriptTools = resolveTranscriptTools(
normalizedContext.messages,
compat.supportsMidConvoSystemMessages === true && compat.supportsMidConvoToolAdditions === true
? "additions"
: "none",
);
const instructionRole = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system";
let lastRole: string | null = null;
let systemIndex = 0;
for (let i = 0; i < transformedMessages.length; i++) {
const msg = transformedMessages[i];
// Some providers don't allow user messages directly after tool results
// Insert a synthetic assistant message to bridge the gap
if (compat.requiresAssistantAfterToolResult && lastRole === "toolResult" && msg.role === "user") {
params.push({
role: "assistant",
content: "I have processed the tool results.",
});
}
if (msg.role === "system") {
// transformMessages keeps system messages in order, so their position matches the transcript.
const addedTools = systemIndex++ >= transcriptTools.foldedSystemMessages ? (msg.toolsAdded ?? []) : [];
if (addedTools.length > 0) {
const kimiToolMessage: KimiToolSystemMessageParam = {
role: "system",
tools: convertTools(addedTools, compat),
};
params.push(kimiToolMessage as unknown as ChatCompletionMessageParam);
}
const text = i === 0 ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg);
if (text.length > 0) {
params.push({ role: instructionRole, content: sanitizeSurrogates(text) });
}
} else if (msg.role === "user") {
if (typeof msg.content === "string") {
params.push({
role: "user",
content: sanitizeSurrogates(msg.content),
});
} else {
const content: ChatCompletionContentPart[] = msg.content
.filter((item) => item.type !== "text" || item.text.length > 0)
.map((item): ChatCompletionContentPart => {
if (item.type === "text") {
return {
type: "text",
text: sanitizeSurrogates(item.text),
} satisfies ChatCompletionContentPartText;
} else {
return {
type: "image_url",
image_url: {
url: `data:${item.mimeType};base64,${item.data}`,
},
} satisfies ChatCompletionContentPartImage;
}
});
if (content.length === 0) continue;
params.push({
role: "user",
content,
});
}
} else if (msg.role === "assistant") {
// Some providers don't accept null content, use empty string instead
const assistantMsg: ChatCompletionAssistantMessageParamWithReasoning = {
role: "assistant",
content: compat.requiresAssistantAfterToolResult || compat.requiresNonNullAssistantContent ? "" : null,
};
const assistantTextParts = msg.content
.filter(isTextContentBlock)
.filter((block) => block.text.trim().length > 0)
.map(
(block) =>
({
type: "text",
text: sanitizeSurrogates(block.text),
}) satisfies ChatCompletionContentPartText,
);
const assistantText = assistantTextParts.map((part) => part.text).join("");
const thinkingBlocks = msg.content.filter(isThinkingContentBlock);
const toolCalls = msg.content.filter(isToolCallBlock);
const signedReasoningDetails = thinkingBlocks
.map((block) => parseOpenAIReasoningDetails(block.thinkingSignature))
.find((details) => details !== undefined);
const legacyReasoningDetails = toolCalls
.map((toolCall) => parseLegacyEncryptedReasoningDetail(toolCall.thoughtSignature))
.filter((detail): detail is OpenAIEncryptedReasoningDetail => detail !== undefined);
const preservedReasoningDetails =
signedReasoningDetails ?? (legacyReasoningDetails.length > 0 ? legacyReasoningDetails : undefined);
const nonEmptyThinkingBlocks = thinkingBlocks.filter((block) => block.thinking.trim().length > 0);
if (nonEmptyThinkingBlocks.length > 0) {
if (compat.requiresThinkingAsText) {
// Convert thinking blocks to plain text (no tags to avoid model mimicking them)
const thinkingText = nonEmptyThinkingBlocks
.map((block) => sanitizeSurrogates(block.thinking))
.join("\n\n");
assistantMsg.content = [{ type: "text", text: thinkingText }, ...assistantTextParts];
} else {
// Always send assistant content as a plain string (OpenAI Chat Completions
// API standard format). Sending as an array of {type:"text", text:"..."}
// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via
// NVIDIA NIM) to mirror the content-block structure literally in their
// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].
if (assistantText.length > 0) {
assistantMsg.content = assistantText;
}
// reasoning_details is the structured alternative to a raw reasoning field.
if (!preservedReasoningDetails) {
// Use the signature from the first thinking block if available (for llama.cpp server + gpt-oss)
let signature = nonEmptyThinkingBlocks[0].thinkingSignature;
if (model.provider === "opencode-go" && signature === "reasoning") {
signature = "reasoning_content";
}
if (signature && isOpenAICompletionsReasoningField(signature)) {
assistantMsg[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join("\n");
}
}
}
} else if (assistantText.length > 0) {
// Always send assistant content as a plain string (OpenAI Chat Completions
// API standard format). Sending as an array of {type:"text", text:"..."}
// objects is non-standard and causes some models (e.g. DeepSeek V3.2 via
// NVIDIA NIM) to mirror the content-block structure literally in their
// output, producing recursive nesting like [{'type':'text','text':'[{...}]'}].
assistantMsg.content = assistantText;
}
if (toolCalls.length > 0) {
assistantMsg.tool_calls = toolCalls.map((tc): ChatCompletionMessageToolCall => {
const customInputProperty = options?.grammarToolInputProperties?.get(tc.name);
if (customInputProperty !== undefined) {
return {
id: tc.id,
type: "custom",
custom: {
name: tc.name,
input: sanitizeSurrogates(getGrammarToolInput(tc.name, tc.arguments, customInputProperty)),
},
};
}
return {
id: tc.id,
type: "function",
function: {
name: tc.name,
arguments: JSON.stringify(tc.arguments),
},
};
});
}
if (preservedReasoningDetails) {
assistantMsg.reasoning_details = preservedReasoningDetails;
}
if (
compat.requiresReasoningContentOnAssistantMessages &&
model.reasoning &&
assistantMsg.reasoning_content === undefined
) {
assistantMsg.reasoning_content = "";
}
// Skip assistant messages that have no content and no tool calls.
// Some providers require "either content or tool_calls, but not none".
// Other providers also don't accept empty assistant messages.
// This handles aborted assistant responses that got no content.
const content = assistantMsg.content;
const hasContent =
content !== null &&
content !== undefined &&
(typeof content === "string" ? content.length > 0 : content.length > 0);
if (!hasContent && !assistantMsg.tool_calls) {
continue;
}
params.push(assistantMsg);
} else if (msg.role === "toolResult") {
const imageBlocks: Array<{ type: "image_url"; image_url: { url: string } }> = [];
let j = i;
for (; j < transformedMessages.length && transformedMessages[j].role === "toolResult"; j++) {
const toolMsg = transformedMessages[j] as ToolResultMessage;
// Extract text and image content
const textResult = toolMsg.content
.filter(isTextContentBlock)
.map((block) => block.text)
.join("\n");
const hasImages = toolMsg.content.some((c) => c.type === "image");
// Always send tool result with text (or placeholder if only images)
const hasText = textResult.trim().length > 0;
const toolResultText = hasText ? textResult : hasImages ? "(see attached image)" : "(no tool output)";
// Some providers require the 'name' field in tool results
const toolResultMsg: ChatCompletionToolMessageParam = {
role: "tool",
content: sanitizeSurrogates(toolResultText),
tool_call_id: toolMsg.toolCallId,
};
if (compat.requiresToolResultName && toolMsg.toolName) {
(toolResultMsg as any).name = toolMsg.toolName;
}
params.push(toolResultMsg);
if (hasImages && model.input.includes("image")) {
for (const block of toolMsg.content) {
if (isImageContentBlock(block)) {
imageBlocks.push({
type: "image_url",
image_url: {
url: `data:${block.mimeType};base64,${block.data}`,
},
});
}
}
}
}
i = j - 1;
if (imageBlocks.length > 0) {
if (compat.requiresAssistantAfterToolResult) {
params.push({
role: "assistant",
content: "I have processed the tool results.",
});
}
params.push({
role: "user",
content: [
{
type: "text",
text: "Attached image(s) from tool result:",
},
...imageBlocks,
],
});
lastRole = "user";
} else {
lastRole = "toolResult";
}
continue;
}
lastRole = msg.role;
}
return params;
}再看一个anthropic 协议的转换过程:
找到anthropic-messages.ts 的 stream
开头也是一样的:
function isSystemMessage(message: { role: string }): message is SystemMessage {
return message.role === "system";
}
/** Return the leading system message, if the transcript starts with one. */
export function getInitialSystemMessage(messages: TranscriptMessages): SystemMessage | undefined {
const first = messages[0];
return first && isSystemMessage(first) ? first : undefined;
}_,然后截取前64位。其他部分和completions规则一致:对!isSameModel(同provider,同api,同model)的情况:// Normalize tool call IDs to match Anthropic's required pattern and length
function normalizeToolCallId(id: string): string {
return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
}// Redacted thinking: pass the opaque payload back as redacted_thinking
if (block.redacted) {
blocks.push({
type: "redacted_thinking",
data: block.thinkingSignature!,
});
continue;
}在OAuthToken下:对toolcall如果匹配上claudeCodeTools,在发送请求时会伪装一下严格复刻 Claude Code 的工具命名。在收到回复时会匹配回原来的toolname。(轻松绷住)
const claudeCodeTools = [
"Read",
"Write",
"Edit",
"Bash",
"Grep",
"Glob",
"AskUserQuestion",
"EnterPlanMode",
"ExitPlanMode",
"KillShell",
"NotebookEdit",
"Skill",
"Task",
"TaskOutput",
"TodoWrite",
"WebFetch",
"WebSearch",
];
const ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));
// Convert tool name to CC canonical casing if it matches (case-insensitive)
const toClaudeCodeName = (name: string) => ccToolLookup.get(name.toLowerCase()) ?? name;{
role: "user",
content: [...toolResults, ...errorImages],
}toolResults: 是一条 type:"tool_result" 的对象,带上匹配toolCall的 toolCallId。 会记录tool的is_error。 content同样也兼容 text和image。 如果是纯image没有text的结果,会自动补充一条text: "(see attached image)"
{
type: "tool_result",
tool_use_id: msg.toolCallId,
content: convertContentBlocks(content),
is_error: msg.isError,
}可以看到一句硬编码的text:"You are Claude Code, Anthropic's official CLI for Claude." 还有一个大大的MUST注释。
因为这类 Claude Code 订阅 OAuth Token(Pro/Max/Team 订阅),后端网关有硬规则校验:第一条 system block 必须是这句原文。(就是这么草率没有办法)
// For OAuth tokens, we MUST include Claude Code identity
if (isOAuthToken) {
params.system = [
{
type: "text",
text: "You are Claude Code, Anthropic's official CLI for Claude.",
...(cacheControl ? { cache_control: cacheControl } : {}),
},
];
if (initialSystemText) {
params.system.push({
type: "text",
text: sanitizeSurrogates(initialSystemText),
...(cacheControl ? { cache_control: cacheControl } : {}),
});
}
} else if (initialSystemText) {
// Add cache control to system prompt for non-OAuth tokens
params.system = [
{
type: "text",
text: sanitizeSurrogates(initialSystemText),
...(cacheControl ? { cache_control: cacheControl } : {}),
},
];
}isOAuthToken 顺着这个校验朝上翻了一下,发现连header都要换成 claude code 的身份。 至于怎么判断是不是 OAuthToken。
apiKey.includes("sk-ant-oat")
// OAuth: Bearer auth, Claude Code identity headers instead of the client identity.
if (apiKey && isOAuthToken(apiKey)) {
const client = new PiAnthropic({
apiKey: null,
authToken: apiKey,
baseURL: model.baseUrl,
dangerouslyAllowBrowser: true,
fetch,
defaultHeaders: mergeHeaders(
{
accept: "application/json",
"anthropic-dangerous-direct-browser-access": "true",
"user-agent": `claude-cli/${claudeCodeVersion}`,
"x-app": "cli",
},
model.headers,
optionsHeaders,
),
});
return { client, isOAuthToken: true };
}
function isOAuthToken(apiKey: string): boolean {
return apiKey.includes("sk-ant-oat");
}顶层tool有两种模式:
nativeToolChanges:
!nativeToolChanges:初始工具+tool change = 当前轮可以生效的工具放在顶层。
// Initial tools stay active with the cache breakpoint on the last one, followed by the
// placeholder. The list never changes afterwards: later tools are defined by value in
// `tool_addition` blocks and withdrawn by `tool_removal`, so the cached prefix survives
// every tool change.
params.tools = [...convertToolDefinitions(initialTools, toolCacheControl), DEFERRED_TOOL_PLACEHOLDER];
/**
* Stable deferred tool declared whenever native tool changes are in use. Anthropic adds
* hidden prompt scaffolding for mid-conversation tool changes; declaring this placeholder
* from the first request keeps that scaffolding in the cached prefix, so the first tool
* change does not invalidate the cache (measured: full miss without it). It is never
* activated and the model cannot see it.
*/
const DEFERRED_TOOL_PLACEHOLDER: BetaTool = {
name: "__pi_deferred_placeholder__",
description: "Reserved placeholder. Never available. Never call this.",
input_schema: { type: "object", properties: {}, required: [] },
defer_loading: true,
};最后做一个comletions 和 anthropic 协议的对比吧:
对比点 | Chat Completions | Anthropic Messages |
|---|---|---|
在哪转 | convertMessages 一个函数里全做完 | buildParams 里切 system、拼顶层参数,再调 convertMessages |
开头的 system 消息 | 留在 messages 里当第一条,role: "system"(DeepSeek) | 从 messages 里切出去,进顶层 system,是一个 text block 数组 |
后面追加的 system 消息 | 开关开了:原位,各自一条 role: "system" 消息,文本用 renderSystemMessageUpdate 拼。没开:第一步就折叠进开头那条 | 开关开了:原位,一条 role: "system" 消息,内容是块,有 text,原生 tool changes 的模型再加 tool_addition、tool_removal。没开:同样第一步折叠 |
工具声明 | 顶层 tools,默认放当前工具集(DeepSeek) | 顶层 tools。默认放当前工具集;原生 tool changes 的模型只放初始工具加 DEFERRED_TOOL_PLACEHOLDER,之后不再变 |
user | 字符串,或 text + image_url(data URL)数组 | 字符串,或 text + image(base64)块数组 |
assistant 文本 | 合并成一个字符串放进 content | 一个 text 块 |
tool call | tool_calls[],function.arguments 是 JSON 字符串 | tool_use 块,input 是对象 |
thinking 回放 | thinkingSignature 是 reasoning 字段名才回放(DeepSeek 是 reasoning_content),缺字段时补空串 | 有签名:thinking 块连 signature 一起发。没签名:转成 text 块。被脱敏:redacted_thinking 块,data 放密文 |
tool result | 每条一条 role: "tool" 消息,带 tool_call_id,没有 is_error 字段;图片另补一条 user 消息 | 连续的合成一条 role: "user" 消息,每条一个 tool_result 块,带 tool_use_id 和 is_error;出错结果里的图片挪到所有 tool_result 之后 |
tool call id | 只在换了模型时处理:竖线分隔的拼成 call_id_item_id,超过 40 字符截到 40 位;DeepSeek 原样 | 只在换了模型时处理:非法字符换成 _,截到 64 位 |
一边独有的 | 补 assistant 桥接、developer 角色 | OAuth token:system 第一块写死 Claude Code 身份,工具名换成 Claude Code 的大小写,请求头也换 |
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。