Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): send open-weight helper prompts to Go as chat completions (#112724)

Brandon27c6d35f4091
diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts
index e304014bfe55..89847414961a 100644
--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts
+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.test.ts
@@ -119,6 +119,20 @@ const SUCCESS_BODY = {
usage: { input_tokens: 12, output_tokens: 7 },
};
+const CHAT_SUCCESS_BODY = {
+ id: "chatcmpl_1",
+ object: "chat.completion",
+ model: "zai-org/glm-5.2",
+ choices: [
+ {
+ index: 0,
+ message: { role: "assistant", content: "glm says hi" },
+ finish_reason: "stop",
+ },
+ ],
+ usage: { prompt_tokens: 9, completion_tokens: 4, total_tokens: 13 },
+};
+
const MODEL_GATE_BODY = {
error: {
message:
@@ -583,12 +597,14 @@ describe("LlmGatewayService.prompt on the Go gateway", () => {
});
it("picks the free-tier model from the pin without a round trip", async () => {
- const goFetch = vi.fn().mockResolvedValue(createJsonResponse(SUCCESS_BODY));
+ const goFetch = vi
+ .fn()
+ .mockResolvedValue(createJsonResponse(CHAT_SUCCESS_BODY));
const { service } = createService(vi.fn(), {
route: {
...GO_ROUTE,
plan: "free",
- allowedModels: ["zai-org/glm-5.3", "@cf/zai-org/glm-5.2"],
+ allowedModels: ["zai-org/glm-5.3", "zai-org/glm-5.2"],
},
fetch: goFetch,
});
@@ -599,12 +615,123 @@ describe("LlmGatewayService.prompt on the Go gateway", () => {
expect(goFetch).toHaveBeenCalledTimes(1);
expect(JSON.parse(goFetch.mock.calls[0][1].body).model).toBe(
- "@cf/zai-org/glm-5.2",
+ "zai-org/glm-5.2",
);
});
- it("falls back to the first allowed model when the free model is not pinned", async () => {
+ it("sends a chat prompt with no system message when the caller passes none, and tolerates null content and no usage", async () => {
+ const goFetch = vi.fn().mockResolvedValue(
+ createJsonResponse({
+ model: "zai-org/glm-5.2",
+ choices: [{ message: { content: null }, finish_reason: "length" }],
+ }),
+ );
+ const { service } = createService(vi.fn(), {
+ route: { ...GO_ROUTE, plan: "free", allowedModels: ["zai-org/glm-5.2"] },
+ fetch: goFetch,
+ });
+
+ const result = await service.prompt([{ role: "user", content: "hi" }]);
+
+ expect(JSON.parse(goFetch.mock.calls[0][1].body).messages).toEqual([
+ { role: "user", content: "hi" },
+ ]);
+ expect(result).toEqual({
+ content: "",
+ model: "zai-org/glm-5.2",
+ stopReason: "length",
+ usage: { inputTokens: 0, outputTokens: 0 },
+ });
+ });
+
+ it("keeps a re-minted retry on chat completions", async () => {
+ const goFetch = vi
+ .fn()
+ .mockResolvedValueOnce(
+ createJsonResponse({ error: { message: "bad token" } }, 401),
+ )
+ .mockResolvedValue(createJsonResponse(CHAT_SUCCESS_BODY));
+ const freeRoute = {
+ ...GO_ROUTE,
+ plan: "free" as const,
+ allowedModels: ["zai-org/glm-5.2"],
+ };
+ const remint = vi
+ .fn()
+ .mockResolvedValue({ ...freeRoute, token: "phe_two" });
+ const { service } = createService(vi.fn(), {
+ route: freeRoute,
+ fetch: goFetch,
+ remint,
+ });
+
+ const result = await service.prompt([{ role: "user", content: "hi" }]);
+
+ expect(result.content).toBe("glm says hi");
+ expect(remint).toHaveBeenCalledWith("unauthorized", "phe_one", 42);
+ const [retryUrl, retryInit] = goFetch.mock.calls[1];
+ expect(retryUrl).toBe(
+ "https://ai-gateway.us.posthog.com/v1/chat/completions",
+ );
+ expect(retryInit.headers.Authorization).toBe("Bearer phe_two");
+ });
+
+ it("sends an open-weight helper prompt as chat completions with the system prompt first", async () => {
+ const goFetch = vi
+ .fn()
+ .mockResolvedValue(createJsonResponse(CHAT_SUCCESS_BODY));
+ const { service } = createService(vi.fn(), {
+ route: { ...GO_ROUTE, plan: "free", allowedModels: ["zai-org/glm-5.2"] },
+ fetch: goFetch,
+ });
+
+ const result = await service.prompt([{ role: "user", content: "hi" }], {
+ system: "be brief",
+ maxTokens: 64,
+ });
+
+ const [url, init] = goFetch.mock.calls[0];
+ expect(url).toBe("https://ai-gateway.us.posthog.com/v1/chat/completions");
+ expect(init.headers.Authorization).toBe("Bearer phe_one");
+ expect(JSON.parse(init.body)).toEqual({
+ model: "zai-org/glm-5.2",
+ messages: [
+ { role: "system", content: "be brief" },
+ { role: "user", content: "hi" },
+ ],
+ stream: false,
+ // The chat floor, above the caller's 64.
+ max_tokens: 1024,
+ });
+ expect(result).toEqual({
+ content: "glm says hi",
+ model: "zai-org/glm-5.2",
+ stopReason: "stop",
+ usage: { inputTokens: 9, outputTokens: 4 },
+ });
+ });
+
+ it("keeps a Claude helper prompt on the Messages API", async () => {
const goFetch = vi.fn().mockResolvedValue(createJsonResponse(SUCCESS_BODY));
+ const { service } = createService(vi.fn(), {
+ route: GO_ROUTE,
+ fetch: goFetch,
+ });
+
+ await service.prompt([{ role: "user", content: "hi" }], {
+ model: "claude-haiku-4-5",
+ system: "be brief",
+ });
+
+ const [url, init] = goFetch.mock.calls[0];
+ expect(url).toBe("https://ai-gateway.us.posthog.com/v1/messages");
+ expect(JSON.parse(init.body).system).toBe("be brief");
+ });
+
+ it("falls back to the first allowed model when the free model is not pinned", async () => {
+ const goFetch = vi
+ .fn()
+ .mockResolvedValue(createJsonResponse(CHAT_SUCCESS_BODY));
const { service } = createService(vi.fn(), {
route: { ...GO_ROUTE, plan: "free", allowedModels: ["zai-org/glm-5.3"] },
fetch: goFetch,
diff --git a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts b/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
index 04bcfca6ca28..5d14f7dd4300 100644
--- a/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
+++ b/products/desktop/packages/core/src/llm-gateway/llm-gateway.ts
@@ -3,6 +3,7 @@ import {
aiGatewayDenialCode,
aiGatewayRemintReason,
classifyGatewayLimitError,
+ isAnthropicModelId,
} from "@posthog/shared";
import {
buildPosthogProjectHeaderRecord,
@@ -27,6 +28,8 @@ import {
type AnthropicErrorResponse,
type AnthropicMessagesRequest,
type AnthropicMessagesResponse,
+ type ChatCompletionsRequest,
+ type ChatCompletionsResponse,
type GatewayRoute,
type LlmMessage,
type PromptOutput,
@@ -39,12 +42,23 @@ import {
export const HELPER_GATEWAY_MODEL = "claude-haiku-4-5";
const FREE_TIER_GATEWAY_MODEL = "@cf/zai-org/glm-5.2";
+// The same model in the Go gateway's spelling; Go does not resolve `@cf/`.
+const GO_FREE_TIER_GATEWAY_MODEL = "zai-org/glm-5.2";
// The Messages API requires max_tokens; the Go gateway forwards the body as sent.
const HELPER_DEFAULT_MAX_TOKENS = 4096;
+// Open-weight reasoning spends max_tokens, so a Claude-sized budget can end before any content.
+const CHAT_MIN_MAX_TOKENS = 1024;
type GoRoute = Extract<GatewayRoute, { mode: "go" }>;
+type PromptShape = "anthropic-messages" | "openai-chat";
+
+// Go serves only Claude models on the Messages API.
+function goPromptShape(model: string): PromptShape {
+ return isAnthropicModelId(model) ? "anthropic-messages" : "openai-chat";
+}
+
export function desktopUsageUrl(apiHost: string, projectId: number): string {
return `${apiHost}/api/projects/${projectId}/desktop/usage/`;
}
@@ -71,8 +85,8 @@ function pickGoModel(route: GoRoute, requested: string): string {
) {
return requested;
}
- if (route.plan === "free" && allowed.includes(FREE_TIER_GATEWAY_MODEL)) {
- return FREE_TIER_GATEWAY_MODEL;
+ if (route.plan === "free" && allowed.includes(GO_FREE_TIER_GATEWAY_MODEL)) {
+ return GO_FREE_TIER_GATEWAY_MODEL;
}
return allowed[0] ?? requested;
}
@@ -191,11 +205,14 @@ export class LlmGatewayService {
options: SendOptions,
route: GoRoute,
): Promise<PromptOutput> {
+ const shape = goPromptShape(options.model);
+ const path =
+ shape === "anthropic-messages" ? "/v1/messages" : "/v1/chat/completions";
const send = (current: GoRoute) =>
this.executePrompt(
messages,
options,
- `${current.gatewayUrl}/v1/messages`,
+ `${current.gatewayUrl}${path}`,
(url, init) =>
(this.auth.fetch ?? fetch)(url, {
...init,
@@ -210,6 +227,7 @@ export class LlmGatewayService {
ai_product: "posthog_code",
team_id: current.teamId,
}),
+ shape,
);
try {
return await send(route);
@@ -259,18 +277,33 @@ export class LlmGatewayService {
messagesUrl: string,
fetchImpl: (url: string, init: RequestInit) => Promise<Response>,
extraHeaders: Record<string, string>,
+ shape: PromptShape = "anthropic-messages",
): Promise<PromptOutput> {
const { system, maxTokens, model, signal, timeoutMs = 60_000 } = options;
- const requestBody: AnthropicMessagesRequest = {
- model,
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
- stream: false,
- max_tokens: maxTokens ?? HELPER_DEFAULT_MAX_TOKENS,
- };
-
- if (system) {
- requestBody.system = system;
+ const turns = messages.map((m) => ({ role: m.role, content: m.content }));
+ const maxTokensOrDefault = maxTokens ?? HELPER_DEFAULT_MAX_TOKENS;
+ let requestBody: AnthropicMessagesRequest | ChatCompletionsRequest;
+ if (shape === "openai-chat") {
+ requestBody = {
+ model,
+ messages: system
+ ? [{ role: "system", content: system }, ...turns]
+ : turns,
+ stream: false,
+ max_tokens: Math.max(maxTokensOrDefault, CHAT_MIN_MAX_TOKENS),
+ };
+ } else {
+ const anthropicBody: AnthropicMessagesRequest = {
+ model,
+ messages: turns,
+ stream: false,
+ max_tokens: maxTokensOrDefault,
+ };
+ if (system) {
+ anthropicBody.system = system;
+ }
+ requestBody = anthropicBody;
}
this.log.debug("Sending request to LLM gateway", {
@@ -355,6 +388,26 @@ export class LlmGatewayService {
);
}
+ if (shape === "openai-chat") {
+ const chat = (await response.json()) as ChatCompletionsResponse;
+ const choice = chat.choices[0];
+ this.log.debug("LLM gateway response received", {
+ model: chat.model,
+ stopReason: choice?.finish_reason ?? null,
+ inputTokens: chat.usage?.prompt_tokens ?? 0,
+ outputTokens: chat.usage?.completion_tokens ?? 0,
+ });
+ return {
+ content: choice?.message.content ?? "",
+ model: chat.model,
+ stopReason: choice?.finish_reason ?? null,
+ usage: {
+ inputTokens: chat.usage?.prompt_tokens ?? 0,
+ outputTokens: chat.usage?.completion_tokens ?? 0,
+ },
+ };
+ }
+
const data = (await response.json()) as AnthropicMessagesResponse;
const textContent = data.content.find((c) => c.type === "text");
diff --git a/products/desktop/packages/core/src/llm-gateway/schemas.ts b/products/desktop/packages/core/src/llm-gateway/schemas.ts
index 97c8207229aa..4d40f5a922ec 100644
--- a/products/desktop/packages/core/src/llm-gateway/schemas.ts
+++ b/products/desktop/packages/core/src/llm-gateway/schemas.ts
@@ -47,6 +47,28 @@ export interface AnthropicMessagesResponse {
};
}
+export interface ChatCompletionsRequest {
+ model: string;
+ messages: Array<{
+ role: "system" | "user" | "assistant";
+ content: string;
+ }>;
+ max_tokens?: number;
+ stream?: boolean;
+}
+
+export interface ChatCompletionsResponse {
+ model: string;
+ choices: Array<{
+ message: { content: string | null };
+ finish_reason: string | null;
+ }>;
+ usage?: {
+ prompt_tokens: number;
+ completion_tokens: number;
+ };
+}
+
export interface AnthropicErrorResponse {
error?: {
message: string;