🤯 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
🔨 chore: add api for structure output (#9382)
Arvin Xu1a77d9f9c6e0
diff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.tsindex 2f312cec74b..89375dd29d1 100644--- a/packages/model-runtime/src/core/BaseAI.ts+++ b/packages/model-runtime/src/core/BaseAI.ts@@ -4,21 +4,25 @@ import OpenAI from 'openai';import {ChatMethodOptions,ChatStreamPayload,+ CreateImagePayload,+ CreateImageResponse,Embeddings,EmbeddingsOptions,EmbeddingsPayload,+ GenerateObjectOptions,+ GenerateObjectPayload,ModelRequestOptions,PullModelParams,TextToImagePayload,TextToSpeechOptions,TextToSpeechPayload,} from '../types';-import { CreateImagePayload, CreateImageResponse } from '../types/image';/* eslint-disable sort-keys-fix/sort-keys-fix , typescript-sort-keys/interface */export interface LobeRuntimeAI {baseURL?: string;chat?(payload: ChatStreamPayload, options?: ChatMethodOptions): Promise<Response>;+ generateObject?(payload: GenerateObjectPayload, options?: GenerateObjectOptions): Promise<any>;embeddings?(payload: EmbeddingsPayload, options?: EmbeddingsOptions): Promise<Embeddings[]>;@@ -43,6 +47,10 @@ export abstract class LobeOpenAICompatibleRuntime {abstract chat(payload: ChatStreamPayload, options?: ChatMethodOptions): Promise<Response>;abstract createImage(payload: CreateImagePayload): Promise<CreateImageResponse>;+ abstract generateObject(+ payload: GenerateObjectPayload,+ options?: GenerateObjectOptions,+ ): Promise<Record<string, any>>;abstract models(): Promise<AIBaseModelCard[]>;diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex 76c2b77eb9b..13181066f51 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -10,6 +10,7 @@ import {ChatStreamPayload,EmbeddingsOptions,EmbeddingsPayload,+ GenerateObjectPayload,ModelRequestOptions,PullModelParams,TextToImagePayload,@@ -64,6 +65,10 @@ export class ModelRuntime {return this._runtime.chat!(payload, options);}+ async generateObject(payload: GenerateObjectPayload) {+ return this._runtime.generateObject!(payload);+ }+async textToImage(payload: TextToImagePayload) {return this._runtime.textToImage?.(payload);}@@ -102,7 +107,7 @@ export class ModelRuntime {* - `src/app/api/chat/agentRuntime.ts: initAgentRuntimeWithUserPayload` on server* - `src/services/chat.ts: initializeWithClientStore` on client*/- static async initializeWithProvider(+ static initializeWithProvider(provider: string,params: Partial<ClientOptions &diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex e73408d44de..b19ddffc41d 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -6,7 +6,13 @@ import OpenAI, { ClientOptions } from 'openai';import { Stream } from 'openai/streaming';import { LobeOpenAI } from '../../providers/openai';-import { CreateImagePayload, CreateImageResponse, ILobeAgentRuntimeErrorType } from '../../types';+import {+ CreateImagePayload,+ CreateImageResponse,+ GenerateObjectOptions,+ GenerateObjectPayload,+ ILobeAgentRuntimeErrorType,+} from '../../types';import {type ChatCompletionErrorPayload,ChatMethodOptions,@@ -198,6 +204,11 @@ export const createRouterRuntime = ({}}+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {+ const runtime = await this.getRuntimeByModel(payload.model);+ return runtime.generateObject!(payload, options);+ }+async createImage(payload: CreateImagePayload) {const runtime = await this.getRuntimeByModel(payload.model);return runtime.createImage!(payload);diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex 1cce567a4eb..610a90d1971 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -295,82 +295,6 @@ describe('LobeOpenAICompatibleFactory', () => {);});- it.skip('should handle anthropic sonnet 3.5 tool calling chunks correctly', async () => {- const chunks = [- {- id: 'chatcmpl-b3f58dc5-0699-4b28-aefe-6624c2a68d51',- created: 1718909418,- model: 'claude-3-5-sonnet-20240620',- object: 'chat.completion.chunk',-- choices: [- {- index: 0,- delta: {- content:- '好的,我可以帮您查询杭州的天气情况。让我使用实时天气工具来获取杭州的当前天气信息。',- id: 'rolu_01JXyRw6Ti78mR2dn6U5h1pa',- function: {- arguments: '{"city": "杭州"}',- name: 'realtime-weather____fetchCurrentWeather',- },- type: 'function',- index: 0,- },- },- ],- },- {- id: 'chatcmpl-b3f58dc5-0699-4b28-aefe-6624c2a68d51',- choices: [{ finish_reason: 'stop', index: 0, delta: {} }],- created: 1718909418,- model: 'claude-3-5-sonnet-20240620',- object: 'chat.completion.chunk',- },- ];- const mockStream = new ReadableStream({- start(controller) {- chunks.forEach((item) => {- controller.enqueue(item);- });-- controller.close();- },- });- vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(- mockStream as any,- );-- const stream: string[] = [];- const result = await instance.chat({- messages: [{ content: 'Hello', role: 'user' }],- model: 'gpt-3.5-turbo',- temperature: 0,- });- const decoder = new TextDecoder();- const reader = result.body!.getReader();-- while (true) {- const { value, done } = await reader.read();- if (done) break;- stream.push(decoder.decode(value));- }-- expect(stream).toEqual(- [- 'id: chatcmpl-b3f58dc5-0699-4b28-aefe-6624c2a68d51',- 'event: text',- 'data: "好的,我可以帮您查询杭州的天气情况。让我使用实时天气工具来获取杭州的当前天气信息。"\n',- 'id: chatcmpl-b3f58dc5-0699-4b28-aefe-6624c2a68d51',- 'event: tool_calls',- 'data: ""\n',- 'id: chatcmpl-b3f58dc5-0699-4b28-aefe-6624c2a68d51',- 'event: stop',- 'data: "stop"\n',- ].map((item) => `${item}\n`),- );- });-it('should transform non-streaming response to stream correctly', async () => {const mockResponse = {id: 'a',@@ -1416,6 +1340,401 @@ describe('LobeOpenAICompatibleFactory', () => {});});+ describe('generateObject', () => {+ it('should return parsed JSON object on successful API call', async () => {+ const mockResponse = {+ output_text: '{"name": "John", "age": 30}',+ };++ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);++ const payload = {+ messages: [{ content: 'Generate a person object', role: 'user' as const }],+ schema: {+ type: 'object',+ properties: { name: { type: 'string' }, age: { type: 'number' } },+ },+ model: 'gpt-4o',+ responseApi: true,+ };++ const result = await instance.generateObject(payload);++ expect(instance['client'].responses.create).toHaveBeenCalledWith(+ {+ input: payload.messages,+ model: payload.model,+ // @ts-ignore+ text: { format: { strict: true, type: 'json_schema', ...payload.schema } },+ user: undefined,+ },+ { headers: undefined, signal: undefined },+ );++ expect(result).toEqual({ name: 'John', age: 30 });+ });++ it('should handle options correctly', async () => {+ 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 }],+ schema: { type: 'object', properties: { status: { type: 'string' } } },+ model: 'gpt-4o',+ responseApi: true,+ };++ const options = {+ headers: { 'Custom-Header': 'test-value' },+ user: 'test-user',+ signal: new AbortController().signal,+ };++ const result = await instance.generateObject(payload, options);++ expect(instance['client'].responses.create).toHaveBeenCalledWith(+ {+ input: payload.messages,+ model: payload.model,+ // @ts-ignore+ text: { format: { strict: true, type: 'json_schema', ...payload.schema } },+ user: options.user,+ },+ { headers: options.headers, signal: options.signal },+ );++ expect(result).toEqual({ status: 'success' });+ });++ it('should return undefined when JSON parsing fails', async () => {+ const mockResponse = {+ output_text: 'invalid json string',+ };++ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'gpt-4o',+ responseApi: true,+ };++ const result = await instance.generateObject(payload);++ expect(consoleSpy).toHaveBeenCalledWith('parse json error:', 'invalid json string');+ expect(result).toBeUndefined();++ consoleSpy.mockRestore();+ });++ it('should handle empty response text', async () => {+ const mockResponse = {+ output_text: '',+ };++ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'gpt-4o',+ responseApi: true,+ };++ const result = await instance.generateObject(payload);++ expect(consoleSpy).toHaveBeenCalledWith('parse json error:', '');+ expect(result).toBeUndefined();++ consoleSpy.mockRestore();+ });++ it('should handle complex nested JSON objects', async () => {+ const mockResponse = {+ output_text:+ '{"user": {"name": "Alice", "profile": {"age": 25, "preferences": ["music", "sports"]}}, "metadata": {"created": "2024-01-01"}}',+ };++ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);++ const payload = {+ messages: [{ content: 'Generate complex user data', role: 'user' as const }],+ schema: {+ type: 'object',+ properties: {+ user: {+ type: 'object',+ properties: {+ name: { type: 'string' },+ profile: {+ type: 'object',+ properties: {+ age: { type: 'number' },+ preferences: { type: 'array', items: { type: 'string' } },+ },+ },+ },+ },+ metadata: { type: 'object' },+ },+ },+ model: 'gpt-4o',+ responseApi: true,+ };++ const result = await instance.generateObject(payload);++ expect(result).toEqual({+ user: {+ name: 'Alice',+ profile: {+ age: 25,+ preferences: ['music', 'sports'],+ },+ },+ metadata: {+ created: '2024-01-01',+ },+ });+ });++ it('should propagate errors from responses API', async () => {+ const apiError = new Error('API Error: Invalid schema format');++ vi.spyOn(instance['client'].responses, 'create').mockRejectedValue(apiError);++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'gpt-4o',+ responseApi: true,+ };++ await expect(instance.generateObject(payload)).rejects.toThrow(+ 'API Error: Invalid schema format',+ );+ });++ describe('chat completions API path', () => {+ it('should return parsed JSON object using chat completions API', async () => {+ const mockResponse = {+ choices: [+ {+ message: {+ content: '{"name": "Bob", "age": 25}',+ },+ },+ ],+ };++ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ mockResponse as any,+ );++ const payload = {+ messages: [{ content: 'Generate a person object', role: 'user' as const }],+ schema: {+ type: 'object',+ properties: { name: { type: 'string' }, age: { type: 'number' } },+ },+ model: 'gpt-4o',+ // responseApi: false or undefined - uses chat completions API+ };++ const result = await instance.generateObject(payload);++ expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(+ {+ messages: payload.messages,+ model: payload.model,+ response_format: { json_schema: payload.schema, type: 'json_schema' },+ user: undefined,+ },+ { headers: undefined, signal: undefined },+ );++ expect(result).toEqual({ name: 'Bob', age: 25 });+ });++ it('should handle options correctly with chat completions API', async () => {+ 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 }],+ schema: { type: 'object', properties: { status: { type: 'string' } } },+ model: 'gpt-4o',+ responseApi: false,+ };++ const options = {+ headers: { Authorization: 'Bearer token' },+ user: 'test-user-123',+ signal: new AbortController().signal,+ };++ const result = await instance.generateObject(payload, options);++ expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(+ {+ messages: payload.messages,+ model: payload.model,+ response_format: { json_schema: payload.schema, type: 'json_schema' },+ user: options.user,+ },+ { headers: options.headers, signal: options.signal },+ );++ expect(result).toEqual({ status: 'completed' });+ });++ it('should return undefined when JSON parsing fails with chat completions API', async () => {+ const mockResponse = {+ choices: [+ {+ message: {+ content: 'This is not valid JSON',+ },+ },+ ],+ };++ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ mockResponse as any,+ );+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'gpt-4o',+ responseApi: false,+ };++ const result = await instance.generateObject(payload);++ expect(consoleSpy).toHaveBeenCalledWith('parse json error:', 'This is not valid JSON');+ expect(result).toBeUndefined();++ consoleSpy.mockRestore();+ });++ it('should handle empty string content from chat completions API', async () => {+ const mockResponse = {+ choices: [+ {+ message: {+ content: '',+ },+ },+ ],+ };++ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ mockResponse as any,+ );+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'gpt-4o',+ responseApi: false,+ };++ const result = await instance.generateObject(payload);++ expect(consoleSpy).toHaveBeenCalledWith('parse json error:', '');+ expect(result).toBeUndefined();++ consoleSpy.mockRestore();+ });++ it('should handle complex arrays with chat completions API', async () => {+ const mockResponse = {+ choices: [+ {+ message: {+ content:+ '{"items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}], "total": 2}',+ },+ },+ ],+ };++ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ mockResponse as any,+ );++ const payload = {+ messages: [{ content: 'Generate items list', role: 'user' as const }],+ schema: {+ type: 'object',+ properties: {+ items: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ id: { type: 'number' },+ name: { type: 'string' },+ },+ },+ },+ total: { type: 'number' },+ },+ },+ model: 'gpt-4o',+ };++ const result = await instance.generateObject(payload);++ expect(result).toEqual({+ items: [+ { id: 1, name: 'Item 1' },+ { id: 2, name: 'Item 2' },+ ],+ total: 2,+ });+ });++ it('should propagate errors from chat completions API', async () => {+ const apiError = new Error('API Error: Rate limit exceeded');++ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'gpt-4o',+ responseApi: false,+ };++ await expect(instance.generateObject(payload)).rejects.toThrow(+ 'API Error: Rate limit exceeded',+ );+ });+ });+ });+describe('models', () => {it('should get models with third party model list', async () => {vi.spyOn(instance['client'].models, 'list').mockResolvedValue({diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex d16635f9de7..9dc0bc73909 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -15,6 +15,8 @@ import {Embeddings,EmbeddingsOptions,EmbeddingsPayload,+ GenerateObjectOptions,+ GenerateObjectPayload,TextToImagePayload,TextToSpeechOptions,TextToSpeechPayload,@@ -339,6 +341,48 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an);}+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {+ const { messages, schema, model, responseApi } = payload;++ if (responseApi) {+ const res = await this.client!.responses.create(+ {+ input: messages,+ model,+ text: { format: { strict: true, type: 'json_schema', ...schema } },+ user: options?.user,+ },+ { headers: options?.headers, signal: options?.signal },+ );++ const text = res.output_text;+ try {+ return JSON.parse(text);+ } catch {+ console.error('parse json error:', text);+ return undefined;+ }+ }++ const res = await this.client.chat.completions.create(+ {+ messages,+ model,+ response_format: { json_schema: schema, type: 'json_schema' },+ user: options?.user,+ },+ { headers: options?.headers, signal: options?.signal },+ );+ const text = res.choices[0].message.content!;++ try {+ return JSON.parse(text);+ } catch {+ console.error('parse json error:', text);+ return undefined;+ }+ }+async embeddings(payload: EmbeddingsPayload,options?: EmbeddingsOptions,diff --git a/packages/model-runtime/src/providers/anthropic/generateObject.test.ts b/packages/model-runtime/src/providers/anthropic/generateObject.test.tsnew file mode 100644index 00000000000..53fa3b4b887--- /dev/null+++ b/packages/model-runtime/src/providers/anthropic/generateObject.test.ts@@ -0,0 +1,285 @@+// @vitest-environment edge-runtime+import { describe, expect, it, vi } from 'vitest';++import { createAnthropicGenerateObject } from './generateObject';++describe('Anthropic generateObject', () => {+ describe('createAnthropicGenerateObject', () => {+ it('should return structured data on successful API call', async () => {+ const mockClient = {+ messages: {+ create: vi.fn().mockResolvedValue({+ content: [+ {+ type: 'tool_use',+ name: 'structured_output',+ input: { name: 'John', age: 30 },+ },+ ],+ }),+ },+ };++ const payload = {+ messages: [{ content: 'Generate a person object', role: 'user' as const }],+ schema: {+ type: 'object',+ properties: { name: { type: 'string' }, age: { type: 'number' } },+ },+ model: 'claude-3-5-sonnet-20241022',+ };++ const result = await createAnthropicGenerateObject(mockClient as any, payload);++ expect(mockClient.messages.create).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'claude-3-5-sonnet-20241022',+ max_tokens: 8192,+ messages: [+ { content: 'Generate a person object', role: 'user' },+ {+ content:+ 'Please use the structured_output tool to provide your response in the required format.',+ role: 'user',+ },+ ],+ tools: [+ {+ name: 'structured_output',+ description: 'Generate structured output according to the provided schema',+ input_schema: {+ type: 'object',+ properties: {+ name: { type: 'string' },+ age: { type: 'number' },+ },+ },+ },+ ],+ tool_choice: {+ type: 'tool',+ name: 'structured_output',+ },+ }),+ expect.objectContaining({}),+ );++ expect(result).toEqual({ name: 'John', age: 30 });+ });++ it('should handle system messages correctly', async () => {+ const mockClient = {+ messages: {+ create: vi.fn().mockResolvedValue({+ content: [+ {+ type: 'tool_use',+ name: 'structured_output',+ input: { status: 'success' },+ },+ ],+ }),+ },+ };++ const payload = {+ messages: [+ { content: 'You are a helpful assistant', role: 'system' as const },+ { content: 'Generate status', role: 'user' as const },+ ],+ schema: { type: 'object', properties: { status: { type: 'string' } } },+ model: 'claude-3-5-sonnet-20241022',+ };++ const result = await createAnthropicGenerateObject(mockClient as any, payload);++ expect(mockClient.messages.create).toHaveBeenCalledWith(+ expect.objectContaining({+ system: [{ text: 'You are a helpful assistant', type: 'text' }],+ messages: expect.any(Array),+ }),+ expect.any(Object),+ );++ expect(result).toEqual({ status: 'success' });+ });++ it('should handle options correctly', async () => {+ const mockClient = {+ messages: {+ create: vi.fn().mockResolvedValue({+ content: [+ {+ type: 'tool_use',+ name: 'structured_output',+ input: { data: 'test' },+ },+ ],+ }),+ },+ };++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object', properties: { data: { type: 'string' } } },+ model: 'claude-3-5-sonnet-20241022',+ };++ const options = {+ signal: new AbortController().signal,+ };++ const result = await createAnthropicGenerateObject(mockClient as any, payload, options);++ expect(mockClient.messages.create).toHaveBeenCalledWith(+ expect.any(Object),+ expect.objectContaining({+ signal: options.signal,+ }),+ );++ expect(result).toEqual({ data: 'test' });+ });++ it('should return undefined when no tool use found in response', async () => {+ const mockClient = {+ messages: {+ create: vi.fn().mockResolvedValue({+ content: [+ {+ type: 'text',+ text: 'Some text response without tool use',+ },+ ],+ }),+ },+ };++ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'claude-3-5-sonnet-20241022',+ };++ const result = await createAnthropicGenerateObject(mockClient as any, payload);++ expect(consoleSpy).toHaveBeenCalledWith('No structured output tool use found in response');+ expect(result).toBeUndefined();++ consoleSpy.mockRestore();+ });++ it('should handle complex nested schemas', async () => {+ const mockClient = {+ messages: {+ create: vi.fn().mockResolvedValue({+ content: [+ {+ type: 'tool_use',+ name: 'structured_output',+ input: {+ user: {+ name: 'Alice',+ profile: {+ age: 25,+ preferences: ['music', 'sports'],+ },+ },+ metadata: {+ created: '2024-01-01',+ },+ },+ },+ ],+ }),+ },+ };++ const payload = {+ messages: [{ content: 'Generate complex user data', role: 'user' as const }],+ schema: {+ type: 'object',+ properties: {+ user: {+ type: 'object',+ properties: {+ name: { type: 'string' },+ profile: {+ type: 'object',+ properties: {+ age: { type: 'number' },+ preferences: { type: 'array', items: { type: 'string' } },+ },+ },+ },+ },+ metadata: { type: 'object' },+ },+ },+ model: 'claude-3-5-sonnet-20241022',+ };++ const result = await createAnthropicGenerateObject(mockClient as any, payload);++ expect(result).toEqual({+ user: {+ name: 'Alice',+ profile: {+ age: 25,+ preferences: ['music', 'sports'],+ },+ },+ metadata: {+ created: '2024-01-01',+ },+ });+ });++ it('should propagate API errors correctly', async () => {+ const apiError = new Error('API Error: Model not found');++ const mockClient = {+ messages: {+ create: vi.fn().mockRejectedValue(apiError),+ },+ };++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'claude-3-5-sonnet-20241022',+ };++ await expect(createAnthropicGenerateObject(mockClient as any, payload)).rejects.toThrow(+ 'API Error: Model not found',+ );+ });++ it('should handle abort signals correctly', async () => {+ const apiError = new Error('Request was cancelled');+ apiError.name = 'AbortError';++ const mockClient = {+ messages: {+ create: vi.fn().mockRejectedValue(apiError),+ },+ };++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ schema: { type: 'object' },+ model: 'claude-3-5-sonnet-20241022',+ };++ const options = {+ signal: new AbortController().signal,+ };++ await expect(+ createAnthropicGenerateObject(mockClient as any, payload, options),+ ).rejects.toThrow();+ });+ });+});diff --git a/packages/model-runtime/src/providers/anthropic/generateObject.ts b/packages/model-runtime/src/providers/anthropic/generateObject.tsnew file mode 100644index 00000000000..8cf2496114d--- /dev/null+++ b/packages/model-runtime/src/providers/anthropic/generateObject.ts@@ -0,0 +1,76 @@+import Anthropic from '@anthropic-ai/sdk';++import { GenerateObjectOptions, GenerateObjectPayload } from '../../types';+import { buildAnthropicMessages } from '../../utils/anthropicHelpers';++/**+ * Generate structured output using Anthropic Claude API with Function Calling+ */+export const createAnthropicGenerateObject = async (+ client: Anthropic,+ payload: GenerateObjectPayload,+ options?: GenerateObjectOptions,+) => {+ const { schema, messages, model } = payload;++ // Convert OpenAI schema to Anthropic tool format+ const tool = {+ description: 'Generate structured output according to the provided schema',+ input_schema: schema,+ name: 'structured_output',+ };+ // Convert messages to Anthropic format+ const system_message = messages.find((m) => m.role === 'system');+ const user_messages = messages.filter((m) => m.role !== 'system');+ const anthropicMessages = await buildAnthropicMessages(user_messages);++ // Add instruction to use the structured output tool+ const enhancedMessages = [+ ...anthropicMessages,+ {+ content:+ 'Please use the structured_output tool to provide your response in the required format.',+ role: 'user' as const,+ },+ ];++ const systemPrompts = system_message?.content+ ? [+ {+ text: system_message.content as string,+ type: 'text' as const,+ },+ ]+ : undefined;++ try {+ const response = await client.messages.create(+ {+ max_tokens: 8192,+ messages: enhancedMessages,+ model,+ system: systemPrompts,+ tool_choice: { name: 'structured_output', type: 'tool' },+ tools: [tool],+ },+ {+ signal: options?.signal,+ },+ );++ // Extract the tool use result+ const toolUseBlock = response.content.find(+ (block) => block.type === 'tool_use' && block.name === 'structured_output',+ );++ if (!toolUseBlock || toolUseBlock.type !== 'tool_use') {+ console.error('No structured output tool use found in response');+ return undefined;+ }++ return toolUseBlock.input;+ } catch (error) {+ console.error('Anthropic generateObject error:', error);+ throw error;+ }+};diff --git a/packages/model-runtime/src/providers/anthropic/index.ts b/packages/model-runtime/src/providers/anthropic/index.tsindex de66d377db8..996b4b5f9da 100644--- a/packages/model-runtime/src/providers/anthropic/index.ts+++ b/packages/model-runtime/src/providers/anthropic/index.ts@@ -3,7 +3,13 @@ import { ModelProvider } from 'model-bank';import { LobeRuntimeAI } from '../../core/BaseAI';import { AnthropicStream } from '../../core/streams';-import { type ChatCompletionErrorPayload, ChatMethodOptions, ChatStreamPayload } from '../../types';+import {+ type ChatCompletionErrorPayload,+ ChatMethodOptions,+ ChatStreamPayload,+ GenerateObjectOptions,+ GenerateObjectPayload,+} from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import { buildAnthropicMessages, buildAnthropicTools } from '../../utils/anthropicHelpers';import { AgentRuntimeError } from '../../utils/createError';@@ -11,6 +17,7 @@ import { debugStream } from '../../utils/debugStream';import { desensitizeUrl } from '../../utils/desensitizeUrl';import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';import { StreamingResponse } from '../../utils/response';+import { createAnthropicGenerateObject } from './generateObject';import { handleAnthropicError } from './handleAnthropicError';export interface AnthropicModelCard {@@ -103,6 +110,14 @@ export class LobeAnthropicAI implements LobeRuntimeAI {}}+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {+ try {+ return await createAnthropicGenerateObject(this.client, payload, options);+ } catch (error) {+ throw this.handleError(error);+ }+ }+private async buildAnthropicPayload(payload: ChatStreamPayload) {const {messages,diff --git a/packages/model-runtime/src/providers/google/generateObject.test.ts b/packages/model-runtime/src/providers/google/generateObject.test.tsnew file mode 100644index 00000000000..ee95405b779--- /dev/null+++ b/packages/model-runtime/src/providers/google/generateObject.test.ts@@ -0,0 +1,361 @@+// @vitest-environment edge-runtime+import { Type as SchemaType } from '@google/genai';+import { describe, expect, it, vi } from 'vitest';++import { convertOpenAISchemaToGoogleSchema, createGoogleGenerateObject } from './generateObject';++describe('Google generateObject', () => {+ describe('convertOpenAISchemaToGoogleSchema', () => {+ it('should convert basic types correctly', () => {+ const openAISchema = {+ type: 'object',+ properties: {+ name: { type: 'string' },+ age: { type: 'number' },+ isActive: { type: 'boolean' },+ count: { type: 'integer' },+ },+ };++ const result = convertOpenAISchemaToGoogleSchema(openAISchema);++ expect(result).toEqual({+ type: SchemaType.OBJECT,+ properties: {+ name: { type: SchemaType.STRING },+ age: { type: SchemaType.NUMBER },+ isActive: { type: SchemaType.BOOLEAN },+ count: { type: SchemaType.INTEGER },+ },+ });+ });++ it('should convert array schemas correctly', () => {+ const openAISchema = {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ recipeName: { type: 'string' },+ ingredients: {+ type: 'array',+ items: { type: 'string' },+ },+ },+ propertyOrdering: ['recipeName', 'ingredients'],+ },+ };++ const result = convertOpenAISchemaToGoogleSchema(openAISchema);++ expect(result).toEqual({+ type: SchemaType.ARRAY,+ items: {+ type: SchemaType.OBJECT,+ properties: {+ recipeName: { type: SchemaType.STRING },+ ingredients: {+ type: SchemaType.ARRAY,+ items: { type: SchemaType.STRING },+ },+ },+ propertyOrdering: ['recipeName', 'ingredients'],+ },+ });+ });++ it('should handle nested objects', () => {+ const openAISchema = {+ type: 'object',+ properties: {+ user: {+ type: 'object',+ properties: {+ profile: {+ type: 'object',+ properties: {+ preferences: {+ type: 'array',+ items: { type: 'string' },+ },+ },+ },+ },+ },+ },+ };++ const result = convertOpenAISchemaToGoogleSchema(openAISchema);++ expect(result).toEqual({+ type: SchemaType.OBJECT,+ properties: {+ user: {+ type: SchemaType.OBJECT,+ properties: {+ profile: {+ type: SchemaType.OBJECT,+ properties: {+ preferences: {+ type: SchemaType.ARRAY,+ items: { type: SchemaType.STRING },+ },+ },+ },+ },+ },+ },+ });+ });++ it('should preserve additional properties like description, enum, required', () => {+ const openAISchema = {+ type: 'object',+ description: 'A person object',+ properties: {+ status: {+ type: 'string',+ enum: ['active', 'inactive'],+ description: 'The status of the person',+ },+ },+ required: ['status'],+ };++ const result = convertOpenAISchemaToGoogleSchema(openAISchema);++ expect(result).toEqual({+ type: SchemaType.OBJECT,+ description: 'A person object',+ properties: {+ status: {+ type: SchemaType.STRING,+ enum: ['active', 'inactive'],+ description: 'The status of the person',+ },+ },+ required: ['status'],+ });+ });++ it('should handle unknown types by defaulting to STRING', () => {+ const openAISchema = {+ type: 'unknown-type',+ };++ const result = convertOpenAISchemaToGoogleSchema(openAISchema);++ expect(result).toEqual({+ type: SchemaType.STRING,+ });+ });+ });++ describe('createGoogleGenerateObject', () => {+ it('should return parsed JSON object on successful API call', async () => {+ const mockClient = {+ models: {+ generateContent: vi.fn().mockResolvedValue({+ text: '{"name": "John", "age": 30}',+ }),+ },+ };++ const contents = [{ role: 'user', parts: [{ text: 'Generate a person object' }] }];++ const payload = {+ contents,+ schema: {+ type: 'object',+ properties: { name: { type: 'string' }, age: { type: 'number' } },+ },+ model: 'gemini-2.5-flash',+ };++ const result = await createGoogleGenerateObject(mockClient as any, payload);++ expect(mockClient.models.generateContent).toHaveBeenCalledWith({+ config: expect.objectContaining({+ responseMimeType: 'application/json',+ responseSchema: expect.objectContaining({+ type: SchemaType.OBJECT,+ properties: expect.objectContaining({+ name: { type: SchemaType.STRING },+ age: { type: SchemaType.NUMBER },+ }),+ }),+ safetySettings: expect.any(Array),+ }),+ contents,+ model: 'gemini-2.5-flash',+ });++ expect(result).toEqual({ name: 'John', age: 30 });+ });++ it('should handle options correctly', async () => {+ const mockClient = {+ models: {+ generateContent: vi.fn().mockResolvedValue({+ text: '{"status": "success"}',+ }),+ },+ };++ const contents = [{ role: 'user', parts: [{ text: 'Generate status' }] }];++ const payload = {+ contents,+ schema: { type: 'object', properties: { status: { type: 'string' } } },+ model: 'gemini-2.5-flash',+ };++ const options = {+ signal: new AbortController().signal,+ };++ const result = await createGoogleGenerateObject(mockClient as any, payload, options);++ expect(mockClient.models.generateContent).toHaveBeenCalledWith({+ config: expect.objectContaining({+ abortSignal: options.signal,+ responseMimeType: 'application/json',+ responseSchema: expect.objectContaining({+ type: SchemaType.OBJECT,+ properties: expect.objectContaining({+ status: { type: SchemaType.STRING },+ }),+ }),+ }),+ contents,+ model: 'gemini-2.5-flash',+ });++ expect(result).toEqual({ status: 'success' });+ });++ it('should return undefined when JSON parsing fails', async () => {+ const mockClient = {+ models: {+ generateContent: vi.fn().mockResolvedValue({+ text: 'invalid json string',+ }),+ },+ };++ const contents: any[] = [];+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const payload = {+ contents,+ schema: { type: 'object' },+ model: 'gemini-2.5-flash',+ };++ const result = await createGoogleGenerateObject(mockClient as any, payload);++ expect(consoleSpy).toHaveBeenCalledWith('parse json error:', 'invalid json string');+ expect(result).toBeUndefined();++ consoleSpy.mockRestore();+ });++ it('should handle complex nested schemas', async () => {+ const mockClient = {+ models: {+ generateContent: vi.fn().mockResolvedValue({+ text: '{"user": {"name": "Alice", "profile": {"age": 25, "preferences": ["music", "sports"]}}, "metadata": {"created": "2024-01-01"}}',+ }),+ },+ };++ const contents: any[] = [];++ const payload = {+ contents,+ schema: {+ type: 'object',+ properties: {+ user: {+ type: 'object',+ properties: {+ name: { type: 'string' },+ profile: {+ type: 'object',+ properties: {+ age: { type: 'number' },+ preferences: { type: 'array', items: { type: 'string' } },+ },+ },+ },+ },+ metadata: { type: 'object' },+ },+ },+ model: 'gemini-2.5-flash',+ };++ const result = await createGoogleGenerateObject(mockClient as any, payload);++ expect(result).toEqual({+ user: {+ name: 'Alice',+ profile: {+ age: 25,+ preferences: ['music', 'sports'],+ },+ },+ metadata: {+ created: '2024-01-01',+ },+ });+ });++ it('should propagate API errors correctly', async () => {+ const apiError = new Error('API Error: Model not found');++ const mockClient = {+ models: {+ generateContent: vi.fn().mockRejectedValue(apiError),+ },+ };++ const contents: any[] = [];++ const payload = {+ contents,+ schema: { type: 'object' },+ model: 'gemini-2.5-flash',+ };++ await expect(createGoogleGenerateObject(mockClient as any, payload)).rejects.toThrow();+ });++ it('should handle abort signals correctly', async () => {+ const apiError = new Error('Request was cancelled');+ apiError.name = 'AbortError';++ const mockClient = {+ models: {+ generateContent: vi.fn().mockRejectedValue(apiError),+ },+ };++ const contents: any[] = [];++ const payload = {+ contents,+ schema: { type: 'object' },+ model: 'gemini-2.5-flash',+ };++ const options = {+ signal: new AbortController().signal,+ };++ await expect(+ createGoogleGenerateObject(mockClient as any, payload, options),+ ).rejects.toThrow();+ });+ });+});diff --git a/packages/model-runtime/src/providers/google/generateObject.ts b/packages/model-runtime/src/providers/google/generateObject.tsnew file mode 100644index 00000000000..53dc30f90fb--- /dev/null+++ b/packages/model-runtime/src/providers/google/generateObject.ts@@ -0,0 +1,152 @@+import { GenerateContentConfig, GoogleGenAI, Type as SchemaType } from '@google/genai';++import { GenerateObjectOptions } from '../../types';++enum HarmCategory {+ HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',+ HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',+ HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',+ HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',+}++enum HarmBlockThreshold {+ BLOCK_NONE = 'BLOCK_NONE',+}++const modelsOffSafetySettings = new Set(['gemini-2.0-flash-exp']);++function getThreshold(model: string): HarmBlockThreshold {+ if (modelsOffSafetySettings.has(model)) {+ return 'OFF' as HarmBlockThreshold; // https://discuss.ai.google.dev/t/59352+ }+ return HarmBlockThreshold.BLOCK_NONE;+}++const convertType = (type: string): SchemaType => {+ switch (type) {+ case 'string': {+ return SchemaType.STRING;+ }+ case 'number': {+ return SchemaType.NUMBER;+ }+ case 'integer': {+ return SchemaType.INTEGER;+ }+ case 'boolean': {+ return SchemaType.BOOLEAN;+ }+ case 'array': {+ return SchemaType.ARRAY;+ }+ case 'object': {+ return SchemaType.OBJECT;+ }+ default: {+ return SchemaType.STRING;+ }+ }+};++/**+ * Convert OpenAI JSON schema to Google Gemini schema format+ */+export const convertOpenAISchemaToGoogleSchema = (openAISchema: any): any => {+ const convertSchema = (schema: any): any => {+ if (!schema) return schema;++ const converted: any = {+ type: convertType(schema.type),+ };++ if (schema.description) {+ converted.description = schema.description;+ }++ if (schema.enum) {+ converted.enum = schema.enum;+ }++ if (schema.properties) {+ converted.properties = {};+ for (const [key, value] of Object.entries(schema.properties)) {+ converted.properties[key] = convertSchema(value);+ }+ }++ if (schema.items) {+ converted.items = convertSchema(schema.items);+ }++ if (schema.required) {+ converted.required = schema.required;+ }++ if (schema.propertyOrdering) {+ converted.propertyOrdering = schema.propertyOrdering;+ }++ return converted;+ };++ return convertSchema(openAISchema);+};++/**+ * Generate structured output using Google Gemini API+ * @see https://ai.google.dev/gemini-api/docs/structured-output+ */+export const createGoogleGenerateObject = async (+ client: GoogleGenAI,+ payload: {+ contents: any[];+ model: string;+ schema: any;+ },+ options?: GenerateObjectOptions,+) => {+ const { schema, contents, model } = payload;++ // Convert OpenAI schema to Google schema format+ const responseSchema = convertOpenAISchemaToGoogleSchema(schema);++ const config: GenerateContentConfig = {+ abortSignal: options?.signal,+ responseMimeType: 'application/json',+ responseSchema,+ // avoid wide sensitive words+ safetySettings: [+ {+ category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,+ threshold: getThreshold(model),+ },+ {+ category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,+ threshold: getThreshold(model),+ },+ {+ category: HarmCategory.HARM_CATEGORY_HARASSMENT,+ threshold: getThreshold(model),+ },+ {+ category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,+ threshold: getThreshold(model),+ },+ ],+ };++ const response = await client.models.generateContent({+ config,+ contents,+ model,+ });++ const text = response.text;++ try {+ return JSON.parse(text!);+ } catch {+ console.error('parse json error:', text);+ return undefined;+ }+};diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.tsindex 4ae333b1c8a..1595e0a8bd7 100644--- a/packages/model-runtime/src/providers/google/index.ts+++ b/packages/model-runtime/src/providers/google/index.ts@@ -18,6 +18,8 @@ import {ChatCompletionTool,ChatMethodOptions,ChatStreamPayload,+ GenerateObjectOptions,+ GenerateObjectPayload,OpenAIChatMessage,UserMessageContentPart,} from '../../types';@@ -31,6 +33,7 @@ import { StreamingResponse } from '../../utils/response';import { safeParseJSON } from '../../utils/safeParseJSON';import { parseDataUri } from '../../utils/uriParser';import { createGoogleImage } from './createImage';+import { createGoogleGenerateObject } from './generateObject';const log = debug('model-runtime:google');@@ -274,6 +277,21 @@ export class LobeGoogleAI implements LobeRuntimeAI {return createGoogleImage(this.client, this.provider, payload);}+ /**+ * Generate structured output using Google Gemini API+ * @see https://ai.google.dev/gemini-api/docs/structured-output+ */+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {+ // Convert OpenAI messages to Google format+ const contents = await this.buildGoogleMessages(payload.messages);++ return createGoogleGenerateObject(+ this.client,+ { contents, model: payload.model, schema: payload.schema },+ options,+ );+ }+private createEnhancedStream(originalStream: any, signal: AbortSignal): ReadableStream {// capture provider for error payloads inside the stream closureconst provider = this.provider;diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.tsindex 6a1f56fe90e..18e868317c9 100644--- a/packages/model-runtime/src/types/chat.ts+++ b/packages/model-runtime/src/types/chat.ts@@ -33,17 +33,8 @@ export type UserMessageContentPart =| UserMessageContentPartThinking;export interface OpenAIChatMessage {- /**- * @title 内容- * @description 消息内容- */content: string | UserMessageContentPart[];-name?: string;- /**- * 角色- * @description 消息发送者的角色- */role: LLMRoleType;tool_call_id?: string;tool_calls?: MessageToolCall[];diff --git a/packages/model-runtime/src/types/index.ts b/packages/model-runtime/src/types/index.tsindex 01e34b164a4..30172110302 100644--- a/packages/model-runtime/src/types/index.ts+++ b/packages/model-runtime/src/types/index.ts@@ -3,6 +3,7 @@ export * from './embeddings';export * from './error';export * from './image';export * from './model';+export * from './structureOutput';export * from './textToImage';export * from './toolsCalling';export * from './tts';diff --git a/packages/model-runtime/src/types/structureOutput.ts b/packages/model-runtime/src/types/structureOutput.tsnew file mode 100644index 00000000000..4ad29dd987c--- /dev/null+++ b/packages/model-runtime/src/types/structureOutput.ts@@ -0,0 +1,25 @@+interface GenerateObjectMessage {+ content: string;+ name?: string;+ role: 'user' | 'system' | 'assistant';+}++export interface GenerateObjectPayload {+ messages: GenerateObjectMessage[];+ model: string;+ responseApi?: boolean;+ schema: any;+}++export interface GenerateObjectOptions {+ /**+ * response headers+ */+ headers?: Record<string, any>;++ signal?: AbortSignal;+ /**+ * userId for the GenerateObject+ */+ user?: string;+}diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex b65c682f9b1..8ee78663363 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -53,3 +53,19 @@ export interface SendMessageServerResponse {topics?: ChatTopic[];userMessageId: string;}++export const StructureOutputSchema = z.object({+ keyVaultsPayload: z.string(),+ messages: z.array(z.any()),+ model: z.string(),+ provider: z.string(),+ schema: z.any(),+});++export interface StructureOutputParams {+ keyVaultsPayload: string;+ messages: ChatMessage[];+ model: string;+ provider: string;+ schema: any;+}diff --git a/src/server/routers/lambda/aiChat.test.ts b/src/server/routers/lambda/aiChat.test.tsindex f2494fab828..b255f543cf9 100644--- a/src/server/routers/lambda/aiChat.test.ts+++ b/src/server/routers/lambda/aiChat.test.ts@@ -1,3 +1,4 @@+// @vitest-environment nodeimport { describe, expect, it, vi } from 'vitest';import { MessageModel } from '@/database/models/message';diff --git a/src/server/routers/lambda/aiChat.ts b/src/server/routers/lambda/aiChat.tsindex 7144848e308..4f04f17ec24 100644--- a/src/server/routers/lambda/aiChat.ts+++ b/src/server/routers/lambda/aiChat.ts@@ -1,12 +1,19 @@-import { AiSendMessageServerSchema, SendMessageServerResponse } from '@lobechat/types';+import {+ AiSendMessageServerSchema,+ SendMessageServerResponse,+ StructureOutputSchema,+} from '@lobechat/types';+import { TRPCError } from '@trpc/server';import { LOADING_FLAT } from '@/const/message';import { MessageModel } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { initModelRuntimeWithUserPayload } from '@/server/modules/ModelRuntime';import { AiChatService } from '@/server/services/aiChat';import { FileService } from '@/server/services/file';+import { getXorPayload } from '@/utils/server';const aiChatProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -22,6 +29,28 @@ const aiChatProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>});export const aiChatRouter = router({+ outputJSON: aiChatProcedure.input(StructureOutputSchema).mutation(async ({ input }) => {+ let payload: object | undefined;++ try {+ payload = getXorPayload(input.keyVaultsPayload);+ } catch (e) {+ console.warn('user payload parse error', e);+ }++ if (!payload) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'keyVaultsPayload is not correct' });+ }++ const modelRuntime = initModelRuntimeWithUserPayload(input.provider, payload);++ return modelRuntime.generateObject({+ messages: input.messages,+ model: input.model,+ schema: input.schema,+ });+ }),+sendMessageInServer: aiChatProcedure.input(AiSendMessageServerSchema).mutation(async ({ input, ctx }) => {diff --git a/src/services/_auth.ts b/src/services/_auth.tsindex cbdf1d686c0..908eafd3ceb 100644--- a/src/services/_auth.ts+++ b/src/services/_auth.ts@@ -78,7 +78,7 @@ export const getProviderAuthPayload = (}};-const createAuthTokenWithPayload = async (payload = {}) => {+const createAuthTokenWithPayload = (payload = {}) => {const accessCode = keyVaultsConfigSelectors.password(useUserStore.getState());const userId = userProfileSelectors.userId(useUserStore.getState());@@ -107,6 +107,11 @@ export const createPayloadWithKeyVaults = (provider: string) => {return getProviderAuthPayload(provider, keyVaults);};+export const createXorKeyVaultsPayload = (provider: string) => {+ const payload = createPayloadWithKeyVaults(provider);+ return obfuscatePayloadWithXOR(payload);+};+// eslint-disable-next-line no-undefexport const createHeaderWithAuth = async (params?: AuthParams): Promise<HeadersInit> => {let payload = params?.payload || {};@@ -115,7 +120,7 @@ export const createHeaderWithAuth = async (params?: AuthParams): Promise<Headerspayload = { ...payload, ...createPayloadWithKeyVaults(params?.provider) };}- const token = await createAuthTokenWithPayload(payload);+ const token = createAuthTokenWithPayload(payload);// eslint-disable-next-line no-undefreturn { ...params?.headers, [LOBE_CHAT_AUTH_HEADER]: token };diff --git a/src/services/aiChat.ts b/src/services/aiChat.tsindex f2d7e9ade6f..5359276777d 100644--- a/src/services/aiChat.ts+++ b/src/services/aiChat.ts@@ -1,7 +1,8 @@-import { SendMessageServerParams } from '@lobechat/types';+import { SendMessageServerParams, StructureOutputParams } from '@lobechat/types';import { cleanObject } from '@lobechat/utils';import { lambdaClient } from '@/libs/trpc/client';+import { createXorKeyVaultsPayload } from '@/services/_auth';class AiChatService {sendMessageInServer = async (@@ -13,6 +14,19 @@ class AiChatService {signal: abortController?.signal,});};++ generateJSON = async (+ params: Omit<StructureOutputParams, 'keyVaultsPayload'>,+ abortController: AbortController,+ ) => {+ return lambdaClient.aiChat.outputJSON.mutate(+ { ...params, keyVaultsPayload: createXorKeyVaultsPayload(params.provider) },+ {+ context: { showNotification: false },+ signal: abortController?.signal,+ },+ );+ };}export const aiChatService = new AiChatService();