🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: add prompt_cache_key for OpenAI chat requests (#14349)
sxjeru1d2db96a38d5
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex 4a3f4bbacc3..19de492f940 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -460,6 +460,143 @@ describe('LobeOpenAICompatibleFactory', () => {expect.anything(),);});++ it('should add prompt_cache_key for OpenAI chat requests with user', async () => {+ const LobeOpenAIProvider = createOpenAICompatibleRuntime({+ baseURL: 'https://api.openai.com/v1',+ provider: ModelProvider.OpenAI,+ });++ const instance = new LobeOpenAIProvider({ apiKey: 'test' });+ const mockCreateMethod = vi+ .spyOn(instance['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ await instance.chat(+ {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4o',+ temperature: 0,+ },+ { user: 'testUser' },+ );++ expect(mockCreateMethod).toHaveBeenCalledWith(+ expect.objectContaining({+ prompt_cache_key: 'lobe:testUser:gpt-4o',+ }),+ expect.anything(),+ );+ });++ it('should not add prompt_cache_key for non-GPT models', async () => {+ const mockCreateMethod = vi.spyOn(instance['client'].chat.completions, 'create');++ await instance.chat(+ {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'llama-3.1-8b-instant',+ temperature: 0,+ },+ { user: 'testUser' },+ );++ expect(mockCreateMethod).toHaveBeenCalledWith(+ expect.not.objectContaining({+ prompt_cache_key: expect.anything(),+ }),+ expect.anything(),+ );+ });++ it('should not add prompt_cache_key for GPT chat requests without user', async () => {+ const LobeOpenAIProvider = createOpenAICompatibleRuntime({+ baseURL: 'https://api.openai.com/v1',+ provider: ModelProvider.OpenAI,+ });+ const instance = new LobeOpenAIProvider({ apiKey: 'test' });+ const mockCreateMethod = vi+ .spyOn(instance['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4o',+ temperature: 0,+ });++ expect(mockCreateMethod).toHaveBeenCalledWith(+ expect.not.objectContaining({+ prompt_cache_key: expect.anything(),+ }),+ expect.anything(),+ );+ });++ it('should add prompt_cache_key for GPT models from any provider (including new-api/aihubmix)', async () => {+ // Test with non-OpenAI provider but GPT model+ const LobeCustomOpenAICompatibleProvider = createOpenAICompatibleRuntime({+ baseURL: 'https://custom-proxy.new-api.com/v1',+ provider: 'custom-openai-compatible',+ });++ const instance = new LobeCustomOpenAICompatibleProvider({ apiKey: 'test' });+ const mockCreateMethod = vi+ .spyOn(instance['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ await instance.chat(+ {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4o-mini',+ temperature: 0,+ },+ { user: 'testUser' },+ );++ expect(mockCreateMethod).toHaveBeenCalledWith(+ expect.objectContaining({+ prompt_cache_key: 'lobe:testUser:gpt-4o-mini',+ }),+ expect.anything(),+ );+ });++ it('should not override custom prompt_cache_key from handlePayload', async () => {+ const LobeOpenAIProvider = createOpenAICompatibleRuntime({+ baseURL: 'https://api.openai.com/v1',+ chatCompletion: {+ handlePayload: (payload) =>+ ({+ ...payload,+ prompt_cache_key: 'custom-cache-key',+ stream: true,+ }) as OpenAI.ChatCompletionCreateParamsStreaming,+ },+ provider: ModelProvider.OpenAI,+ });++ const instance = new LobeOpenAIProvider({ apiKey: 'test' });+ const mockCreateMethod = vi+ .spyOn(instance['client'].chat.completions, 'create')+ .mockResolvedValue(new ReadableStream() as any);++ await instance.chat(+ {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4o',+ temperature: 0,+ },+ { user: 'testUser' },+ );++ expect(mockCreateMethod).toHaveBeenCalledWith(+ expect.objectContaining({+ prompt_cache_key: 'custom-cache-key',+ }),+ expect.anything(),+ );+ });});describe('noUserId option', () => {@@ -1128,7 +1265,7 @@ describe('LobeOpenAICompatibleFactory', () => {model: 'any-model',temperature: 0,});- } catch (e) {+ } catch {// Catch errors from incomplete mocking, we only care that responses.create was called}@@ -1212,7 +1349,7 @@ describe('LobeOpenAICompatibleFactory', () => {model: 'prefix-special-model-suffix',temperature: 0,});- } catch (e) {+ } catch {// Catch errors from incomplete mocking}expect(spy).toHaveBeenCalledTimes(1);@@ -1232,7 +1369,7 @@ describe('LobeOpenAICompatibleFactory', () => {model: 'special-xyz',temperature: 0,});- } catch (e) {+ } catch {// Catch errors from incomplete mocking}expect(spy).toHaveBeenCalledTimes(2);@@ -1244,7 +1381,7 @@ describe('LobeOpenAICompatibleFactory', () => {model: 'unrelated-model',temperature: 0,});- } catch (e) {+ } catch {// Catch errors}expect(spy).toHaveBeenCalledTimes(2); // Ensure no additional calls were made@@ -1791,6 +1928,7 @@ describe('LobeOpenAICompatibleFactory', () => {{input: payload.messages,model: payload.model,+ prompt_cache_key: 'lobe:test-user:gpt-4o',// @ts-ignoretext: { format: { strict: true, type: 'json_schema', ...payload.schema } },safety_identifier: options.user,@@ -1801,6 +1939,39 @@ describe('LobeOpenAICompatibleFactory', () => {expect(result).toEqual({ status: 'success' });});+ it('should add prompt_cache_key for OpenAI generateObject responses requests with user', async () => {+ const LobeOpenAIProvider = createOpenAICompatibleRuntime({+ baseURL: 'https://api.openai.com/v1',+ provider: ModelProvider.OpenAI,+ });++ const instance = new LobeOpenAIProvider({ apiKey: 'test' });+ const mockResponse = {+ output_text: '{"status": "success"}',+ };++ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);++ const payload = {+ messages: [{ content: 'Generate status', role: 'user' as const }],+ model: 'gpt-4o',+ responseApi: true,+ schema: {+ name: 'status_extractor',+ schema: { properties: { status: { type: 'string' } }, type: 'object' as const },+ },+ };++ await instance.generateObject(payload, { user: 'testUser' });++ expect(instance['client'].responses.create).toHaveBeenCalledWith(+ expect.objectContaining({+ prompt_cache_key: 'lobe:testUser:gpt-4o',+ }),+ expect.anything(),+ );+ });+it('should return undefined when JSON parsing fails', async () => {const mockResponse = {output_text: 'invalid json string',@@ -2047,6 +2218,7 @@ describe('LobeOpenAICompatibleFactory', () => {{messages: payload.messages,model: payload.model,+ prompt_cache_key: 'lobe:test-user-123:gpt-4o',response_format: { json_schema: payload.schema, type: 'json_schema' },user: options.user,},@@ -2056,6 +2228,47 @@ describe('LobeOpenAICompatibleFactory', () => {expect(result).toEqual({ status: 'completed' });});+ it('should add prompt_cache_key for OpenAI generateObject chat completion requests with user', async () => {+ const LobeOpenAIProvider = createOpenAICompatibleRuntime({+ baseURL: 'https://api.openai.com/v1',+ provider: ModelProvider.OpenAI,+ });++ const instance = new LobeOpenAIProvider({ apiKey: 'test' });+ const mockResponse = {+ choices: [+ {+ message: {+ content: '{"status": "completed"}',+ },+ },+ ],+ };++ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ mockResponse as any,+ );++ const payload = {+ messages: [{ content: 'Generate status', role: 'user' as const }],+ model: 'gpt-4o',+ responseApi: false,+ schema: {+ name: 'status_extractor',+ schema: { properties: { status: { type: 'string' } }, type: 'object' as const },+ },+ };++ await instance.generateObject(payload, { user: 'testUser' });++ expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(+ expect.objectContaining({+ prompt_cache_key: 'lobe:testUser:gpt-4o',+ }),+ expect.anything(),+ );+ });+it('should return undefined when JSON parsing fails with chat completions API', async () => {const mockResponse = {choices: [diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 50a340f0c2d..9b4402cbb9c 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -74,6 +74,12 @@ export const CHAT_MODELS_BLOCK_LIST = [];type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions & T;+type OpenAIExtraParams = { prompt_cache_key?: string; safety_identifier?: string };+type ResponseCreateParamsWithPromptCacheKey = (+ | OpenAI.Responses.ResponseCreateParamsStreaming+ | OpenAI.Responses.ResponseCreateParams+) &+ OpenAIExtraParams;export type CreateImageOptions = Omit<ClientOptions, 'apiKey'> & {apiKey: string;provider: string;@@ -346,6 +352,27 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anreturn false;}+ private resolvePromptCacheKey(model?: string, user?: string) {+ if (!user) return;++ // Keep the default key at {userId}:{model}; {agentId} can be added later if a narrower cache bucket is needed.+ if (model?.startsWith('gpt-') || /^o\d/.test(model || '') || model === 'chat-latest') {+ return `lobe:${user}:${model}`;+ }+ }++ private resolvePromptCacheKeyParams(+ model?: string,+ user?: string,+ existingPromptCacheKey?: string,+ ) {+ if (existingPromptCacheKey !== undefined) return {};++ const promptCacheKey = this.resolvePromptCacheKey(model, user);++ return promptCacheKey ? { prompt_cache_key: promptCacheKey } : {};+ }+async chat({ responseMode, ...payload }: ChatStreamPayload, options?: ChatMethodOptions) {try {const log = debug(`${this.logPrefix}:chat`);@@ -484,6 +511,11 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an...cleanedPayload,messages,...(chatCompletion?.noUserId ? {} : { user: options?.user }),+ ...this.resolvePromptCacheKeyParams(+ cleanedPayload.model,+ options?.user,+ cleanedPayload.prompt_cache_key,+ ),stream_options:postPayload.stream && !chatCompletion?.excludeUsage? { include_usage: true }@@ -746,6 +778,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an{messages,model,+ ...this.resolvePromptCacheKeyParams(model, options?.user),tool_choice: { function: { name: tool.function.name }, type: 'function' },tools: [tool],user: options?.user,@@ -800,6 +833,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an{input: messages,model,+ ...this.resolvePromptCacheKeyParams(model, options?.user),text: { format: { strict: true, type: 'json_schema', ...processedSchema } },// Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`safety_identifier: options?.user,@@ -830,6 +864,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anmessages,model,response_format: { json_schema: processedSchema, type: 'json_schema' },+ ...this.resolvePromptCacheKeyParams(model, options?.user),user: options?.user,},{ headers: options?.headers, signal: options?.signal },@@ -1107,8 +1142,13 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = aninput,...(max_tokens && { max_output_tokens: max_tokens }),store: false,- stream: !isStreaming ? undefined : isStreaming,+ stream: isStreaming || undefined,tools: tools?.map((tool) => this.convertChatCompletionToolToResponseTool(tool)),+ ...this.resolvePromptCacheKeyParams(+ res.model,+ options?.user,+ (res as OpenAIExtraParams).prompt_cache_key,+ ),// Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`safety_identifier: options?.user,// Sanitize sampling params for Responses API path@@ -1116,7 +1156,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = annormalizeTemperature: false,preferTemperature: true,}),- } as OpenAI.Responses.ResponseCreateParamsStreaming | OpenAI.Responses.ResponseCreateParams;+ } as ResponseCreateParamsWithPromptCacheKey;if (debugParams?.responses?.()) {// eslint-disable-next-line no-console@@ -1233,6 +1273,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an{input,model,+ ...this.resolvePromptCacheKeyParams(model, options?.user),tool_choice: 'required',tools: tools!.map((tool) => this.convertChatCompletionToolToResponseTool(tool)),// Responses API replaced `user` with `safety_identifier`; some endpoints reject `user`@@ -1274,6 +1315,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an{messages: msgs,model,+ ...this.resolvePromptCacheKeyParams(model, options?.user),tool_choice: 'required',tools,user: options?.user,