Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Merge #7356: custom request headers on OpenAI-compatible servers

milind-soni8e7fe516f233
diff --cc server/config.ts
index 6d51d04ebd,504b38dccf..8b4053cdbb
--- a/server/config.ts
+++ b/server/config.ts
@@@ -30,9 -30,9 +30,10 @@@ import { settledFileCache, settledFileS
import { isRemoteMcpServer, mcpServerServes, parseStoredMcpServer } from "./mcp-registry.ts"; import { postizKeyHeaders } from "./postiz/connection.ts";
import { parseJson, schemaIssue, type JsonObject, type JsonValue } from "./schema.ts";
import { deciderConfigSchema, type DeciderConfig } from "./decider/config.ts";
+ import { applyOpenAiCompatHeaderDefaults, openAiCompatConfigHeadersSchema, type OpenAICompatCustomHeadersConfig } from "./drivers/openai-compat-headers.ts";
import { fishKeyFromLiveKey, liveConfigSchema, liveConfigWithEnv, liveSettingEnv, type LiveConfig } from "./live-config.ts"; import { hearingConfigShape } from "./tts/hearing-config.ts";
-import { browserEngineConfigSchema, isValidCdpTarget, type BrowserEngineConfig } from "./browser/config.ts";
+import { browserEngineConfigSchema, browserEnginePatchSchema, browserProfileSchema, isValidCdpTarget, legacyBrowserProfileSchema, type BrowserEngineConfig, type BrowserProfile } from "./browser/config.ts";
+export type { BrowserProfile } from "./browser/config.ts";
import { roomContextSettings } from "./room-context-settings.ts"; import { usageCapsSchema, type UsageCapsConfig } from "./usage-caps-config.ts";
import { localVmConfigSchema } from "./local-vm-settings.ts";
export * from "./local-vm-settings.ts";
diff --cc server/drivers/openai-chat.ts
index 41672cdd74,3cab94e43e..f018873703
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@@ -257,7 -246,7 +251,7 @@@ export function createOpenAIChatRuntime
signal?: AbortSignal,
onDelta?: (delta: string, kind: "assistant_text" | "reasoning_text") => void,
tools: ChatToolDefinition[] = [],
- variant?: string, threadId?: string, { onUsage, maxOutputTokens }: Pick<TextGenerationOptions, "onUsage" | "maxOutputTokens"> = {},
- onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string, headerContext?: RuntimeHeaderContext,
++ variant?: string, threadId?: string, { onUsage, maxOutputTokens, headerContext }: Pick<TextGenerationOptions, "onUsage" | "maxOutputTokens"> & { headerContext?: RuntimeHeaderContext } = {},
): Promise<Completion> => {
const timeoutController = new AbortController();
let idleTimer: NodeJS.Timeout | null = null;
@@@ -458,7 -452,7 +453,7 @@@
signal?: AbortSignal,
onDelta?: (delta: string, kind: "assistant_text" | "reasoning_text") => void,
tools: ChatToolDefinition[] = [],
- variant?: string, threadId?: string,
- onUsage?: TextGenerationOptions["onUsage"], variant?: string, threadId?: string, headerContext?: RuntimeHeaderContext,
++ variant?: string, threadId?: string, extras: { headerContext?: RuntimeHeaderContext } = {},
): Promise<Completion> => {
for (;;) {
const attemptedRoute = routes.routeFor(model, tools.length > 0); let replied = false;
@@@ -466,7 -460,7 +461,7 @@@
return await completeOn(attemptedRoute, messages, model, stream, signal, onDelta && ((text, kind) => {
replied = true;
onDelta(text, kind);
- }), tools, variant, threadId);
- }), tools, onUsage, variant, threadId, headerContext);
++ }), tools, variant, threadId, extras);
} catch (error) {
if (!(error instanceof ModelRouteRefused) || replied || signal?.aborted) throw error;
if (routes.routeFor(model, tools.length > 0) === attemptedRoute && !routes.advance(model, error.refusal)) throw new ChatProtocolError(noRouteLeft(error.message));
@@@ -649,7 -640,7 +641,7 @@@
if (streamKind === "assistant_text") answerStreamed = true;
const shown = holdback && streamKind === "assistant_text" ? holdback.feed(text) : text;
if (shown) delta(shown, streamKind);
- }, tools.definitions, turn.variant, turn.threadId);
- }, tools.definitions, undefined, turn.variant, turn.threadId, headerContext);
++ }, tools.definitions, turn.variant, turn.threadId, { headerContext });
// A reply cut off at the token limit may be a call cut short; running half of one is worse than saying so.
const written = holdback && !completion.toolCalls.length && completion.finishReason !== "length" ? textToolCalls(completion.text, tools.definitions) : null;
unreadable = written?.kind === "unreadable" && !askedAgain;
@@@ -979,16 -971,19 +972,22 @@@
return () => listeners.delete(listener);
},
},
- generateText: async (prompt, { signal, onUsage, model: named, checkModel, maxOutputTokens, finalTextOnly } = {}) => {
- generateText: async (prompt, { signal, onUsage, model: named, checkModel, threadId } = {}) => {
++ generateText: async (prompt, { signal, onUsage, model: named, checkModel, maxOutputTokens, finalTextOnly, threadId } = {}) => {
const model = named ?? options.generateModel?.() ?? options.models().default;
signal?.throwIfAborted();
checkModel?.(model);
- const route = finalTextOnly && routes.routeFor(model, true) === "responses" ? "responses" : "chat";
- const { text, reasoning, toolCalls, responseOutput } = await completeOn(route,
- [{ role: "user", content: prompt }], model, false, signal, undefined, [], undefined, undefined, { onUsage, maxOutputTokens });
- if (toolCalls.length) throw new ChatProtocolError("provider returned tool calls to a text-only helper");
- if (finalTextOnly && responseOutput) return finalResponseText(responseOutput);
- return finalTextOnly || text.trim() ? text : reasoning;
+ const headerContext: RuntimeHeaderContext = { ...(threadId ? { threadId } : {}), providerInstanceId: input.instanceId };
+ const headerSecrets = customHeaderSecrets(options.customHeaders, headerContext);
+ try {
- const { text, reasoning, toolCalls } = await complete([{ role: "user", content: prompt }], model, false, signal, undefined, [], onUsage, undefined, threadId, headerContext);
++ const route = finalTextOnly && routes.routeFor(model, true) === "responses" ? "responses" : "chat";
++ const { text, reasoning, toolCalls, responseOutput } = await completeOn(route,
++ [{ role: "user", content: prompt }], model, false, signal, undefined, [], undefined, threadId, { onUsage, maxOutputTokens, headerContext });
+ if (toolCalls.length) throw new ChatProtocolError("provider returned tool calls to a text-only helper");
- return maskCustomSecrets(text.trim() ? text : reasoning, headerSecrets);
++ const answer = finalTextOnly && responseOutput ? finalResponseText(responseOutput) : finalTextOnly || text.trim() ? text : reasoning;
++ return maskCustomSecrets(answer, headerSecrets);
+ } catch (error) {
+ throw scrubErrorSecrets(error, headerSecrets);
+ }
},
dispose: async () => {
const turns = [...active.values()];
diff --cc server/drivers/openai-compat.ts
index dd7d80a172,f451ac57e3..9960c95f53
--- a/server/drivers/openai-compat.ts
+++ b/server/drivers/openai-compat.ts
@@@ -106,15 -107,8 +107,17 @@@ export interface OpenAICompatConfig
reasoningEfforts?: Record<string, string[]>;
/** How long a turn waits for the next piece of a reply before giving up; unset follows the server's default. */
replyWaitMinutes?: number;
+ /** Opt-in outbound HTTP headers with trusted runtime variables such as {threadId}. */
+ customHeaders?: OpenAICompatCustomHeadersConfig;
+ /** The server serves a local model from an address that is not on this machine or network: a tunnel, a VPN
+ * hostname or a reverse proxy in front of Ollama, LM Studio or llama.cpp. Local-model turn handling applies. */
+ local?: boolean;
+}
+
+/** Whether a turn on this server gets local-model handling: text-form tool-call recovery, the repeat guard and
+ * corrective rounds. An address on this network says yes on its own; `local` opts in one that is not. */
+export function servesLocalModel(config: Pick<OpenAICompatConfig, "url" | "local">): boolean {
+ return config.local === true || onThisNetwork(config.url);
}
const CATALOGS = ["openai", "lmstudio", "ollama"] as const;
@@@ -180,7 -173,7 +183,8 @@@ function decodeConfig(raw: unknown): Op
...(config.managedModels ? { managedModels: config.managedModels as string[] } : {}),
...(reasoningEfforts ? { reasoningEfforts } : {}),
...(isReplyWait(config.replyWaitMinutes) ? { replyWaitMinutes: config.replyWaitMinutes } : {}),
+ ...(config.local === true ? { local: true } : {}),
+ ...(config.customHeaders !== undefined ? { customHeaders: decodeCustomHeaders(config.customHeaders) } : {}),
url: (typeof config.url === "string" && config.url ? config.url : envUrl || "https://openrouter.ai/api/v1")
.replace(/\/+$/, ""),
apiKeyEnv: typeof config.apiKeyEnv === "string" && config.apiKeyEnv
@@@ -444,7 -437,8 +448,8 @@@ export const OpenAICompatDriver: Provid
missingKeyError: missingKey,
unavailableReason: missingKey,
timeoutMs: config.replyWaitMinutes ? config.replyWaitMinutes * 60_000 : idleTimeoutMs(),
+ ...(config.customHeaders ? { customHeaders: config.customHeaders } : {}),
- ...(onThisNetwork(config.url) ? { livenessEveryMs: livenessEveryMs(), localModel: true } : {}),
+ ...(servesLocalModel(config) ? { livenessEveryMs: livenessEveryMs(), localModel: true } : {}),
reasoning: true,
billing: "metered",
includeUsageInCompleted: true,
diff --cc server/openai-compat-endpoints.ts
index 9982f79f17,c7517949a8..1da4b31a0e
--- a/server/openai-compat-endpoints.ts
+++ b/server/openai-compat-endpoints.ts
@@@ -32,7 -35,7 +35,8 @@@ export const addEndpointSchema = z.obje
key: z.string().trim().min(1).max(4096),
models: z.array(z.string().trim().min(1).max(200)).max(64).optional(),
catalog: z.enum(["lmstudio", "ollama"]).optional(),
+ local: z.boolean().optional(),
+ customHeaders: customHeadersPatchSchema.optional(),
}).strict();
export type AddEndpoint = z.infer<typeof addEndpointSchema>;
@@@ -54,9 -57,10 +58,10 @@@ export function addEndpoint(instances:
if (/^https?:\/\//i.test(body.key)) return { error: "That API key looks like a URL. Paste the secret key itself, not a web address." };
const instanceId = `${ADDED_ENDPOINT_PREFIX}${randomUUID()}`;
const models = [...new Set(body.models ?? [])];
+ const customHeaders = body.customHeaders !== undefined ? decodeCustomHeaders(body.customHeaders) : undefined;
instances[instanceId] = {
driver: "openai-compat", displayName: body.displayName, access: "api",
- config: { key: body.key, url, ...(models.length ? { managedModels: models } : {}), ...(body.catalog ? { catalog: body.catalog } : {}), ...(body.local === true ? { local: true } : {}) },
- config: { key: body.key, url, ...(models.length ? { managedModels: models } : {}), ...(body.catalog ? { catalog: body.catalog } : {}), ...(customHeaders ? { customHeaders } : {}) },
++ config: { key: body.key, url, ...(models.length ? { managedModels: models } : {}), ...(body.catalog ? { catalog: body.catalog } : {}), ...(body.local === true ? { local: true } : {}), ...(customHeaders ? { customHeaders } : {}) },
};
return { instanceId };
}
diff --cc src/components/OpenAiCompatServers.tsx
index b420bf63b2,55d4e89099..53f51cd552
--- a/src/components/OpenAiCompatServers.tsx
+++ b/src/components/OpenAiCompatServers.tsx
@@@ -5,8 -5,8 +5,9 @@@ import { t } from "@/lib/i18n"
import { keySaved } from "@/lib/product-events";
import { addedServers } from "@/lib/openai-compat-endpoints";
import { cn } from "@/lib/cn";
+import { useAdvancedMode } from "@/lib/interface-mode";
import { KEY_FIELD } from "./keys/KeyRow";
+ import { OpenAiCompatCustomHeaders } from "./OpenAiCompatCustomHeaders";
import { Select } from "./Select";
export function modelIds(text: string): string[] {