🤯 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: stabilize xAI Responses API tools (#14462)
YuTengjingc51835193f58
diff --git a/packages/model-runtime/src/providers/xai/index.test.ts b/packages/model-runtime/src/providers/xai/index.test.tsindex 4b5d072fcf1..01ac155fa15 100644--- a/packages/model-runtime/src/providers/xai/index.test.ts+++ b/packages/model-runtime/src/providers/xai/index.test.ts@@ -28,8 +28,8 @@ describe('LobeXAI - custom features', () => {vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(new ReadableStream() as any);});- describe('chatCompletion.handlePayload', () => {- it('should remove camelCase penalty parameters for grok-4.20 reasoning variants', async () => {+ describe('Responses API routing', () => {+ it('should ignore chatCompletion apiMode and remove camelCase penalty parameters', async () => {await instance.chat({apiMode: 'chatCompletion',frequencyPenalty: 0.4,@@ -38,14 +38,15 @@ describe('LobeXAI - custom features', () => {presencePenalty: 0.6,} as any);- const createCall = (instance['client'].chat.completions.create as Mock).mock.calls[0][0];+ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];expect(createCall.frequencyPenalty).toBeUndefined();expect(createCall.presencePenalty).toBeUndefined();expect(createCall.stream).toBe(true);+ expect(instance['client'].chat.completions.create).not.toHaveBeenCalled();});- it('should remove penalty parameters for Grok 4 non-reasoning variants', async () => {+ it('should remove snake_case penalty parameters via forced Responses API', async () => {await instance.chat({apiMode: 'chatCompletion',frequency_penalty: 0.4,@@ -54,13 +55,13 @@ describe('LobeXAI - custom features', () => {presence_penalty: 0.6,} as any);- const createCall = (instance['client'].chat.completions.create as Mock).mock.calls[0][0];+ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];expect(createCall.frequency_penalty).toBeUndefined();expect(createCall.presence_penalty).toBeUndefined();});- it('should preserve penalty parameters for Grok 3 models', async () => {+ it('should remove penalty parameters for Grok 3 models via Responses API', async () => {await instance.chat({apiMode: 'chatCompletion',frequency_penalty: 0.4,@@ -69,10 +70,48 @@ describe('LobeXAI - custom features', () => {presence_penalty: 0.6,} as any);- const createCall = (instance['client'].chat.completions.create as Mock).mock.calls[0][0];+ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.frequency_penalty).toBeUndefined();+ expect(createCall.presence_penalty).toBeUndefined();+ });++ it('should map chat response_format to Responses API text.format', async () => {+ await instance.chat({+ apiMode: 'chatCompletion',+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'grok-4',+ response_format: {+ json_schema: {+ name: 'answer',+ schema: {+ additionalProperties: false,+ properties: { answer: { type: 'string' } },+ required: ['answer'],+ type: 'object',+ },+ strict: true,+ },+ type: 'json_schema',+ },+ } as any);++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];- expect(createCall.frequency_penalty).toBe(0.4);- expect(createCall.presence_penalty).toBe(0.6);+ expect(createCall.response_format).toBeUndefined();+ expect(createCall.text).toEqual({+ format: {+ name: 'answer',+ schema: {+ additionalProperties: false,+ properties: { answer: { type: 'string' } },+ required: ['answer'],+ type: 'object',+ },+ strict: true,+ type: 'json_schema',+ },+ });});});@@ -134,6 +173,66 @@ describe('LobeXAI - custom features', () => {const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];expect(createCall.tools).toEqual([{ type: 'web_search' }, { type: 'x_search' }]);});++ it('should sanitize slash-delimited enum values from function tool schemas', async () => {+ await instance.chat({+ enabledSearch: true,+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'grok-4.20-beta-0309-reasoning',+ tools: [+ {+ function: {+ description: 'Send an email',+ name: 'gmail____gmail_send_email',+ parameters: {+ additionalProperties: false,+ properties: {+ mimeType: {+ default: 'text/plain',+ enum: ['text/plain', 'text/html', 'multipart/alternative'],+ type: 'string',+ },+ mode: {+ enum: ['plain', 'html'],+ type: 'string',+ },+ },+ required: ['mimeType'],+ type: 'object',+ },+ },+ type: 'function' as const,+ },+ ],+ });++ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];++ expect(createCall.tools).toEqual([+ {+ description: 'Send an email',+ name: 'gmail____gmail_send_email',+ parameters: {+ additionalProperties: false,+ properties: {+ mimeType: {+ default: 'text/plain',+ type: 'string',+ },+ mode: {+ enum: ['plain', 'html'],+ type: 'string',+ },+ },+ required: ['mimeType'],+ type: 'object',+ },+ type: 'function',+ },+ { type: 'web_search' },+ { type: 'x_search' },+ ]);+ });});describe('models', () => {diff --git a/packages/model-runtime/src/providers/xai/index.ts b/packages/model-runtime/src/providers/xai/index.tsindex 9d19bcdeb2f..371382fcfad 100644--- a/packages/model-runtime/src/providers/xai/index.ts+++ b/packages/model-runtime/src/providers/xai/index.ts@@ -1,7 +1,7 @@import { ModelProvider } from 'model-bank';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';-import type { ChatStreamPayload } from '../../types';+import type { ChatCompletionTool, ChatResponseFormat, ChatStreamPayload } from '../../types';import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';import { createXAIImage } from './createImage';import { createXAIVideo } from './createVideo';@@ -39,12 +39,78 @@ const pruneUnsupportedChatCompletionParameters = (payload: ChatStreamPayload) =>return stripUnsupportedPenaltyParameters(payload);};+const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const hasSlashDelimitedEnumValue = (value: unknown) =>+ Array.isArray(value) && value.some((item) => typeof item === 'string' && item.includes('/'));++/**+ * xAI Responses rejects some otherwise valid JSON Schema constraints in function tools.+ * Keep the tool usable by removing only slash-delimited enum constraints, such as MIME+ * values (`text/plain`) from Gmail MCP schemas.+ */+const sanitizeXAIToolSchema = (schema: unknown): unknown => {+ if (Array.isArray(schema)) return schema.map((item) => sanitizeXAIToolSchema(item));++ if (!isRecord(schema)) return schema;++ const sanitized: Record<string, unknown> = {};++ for (const [key, value] of Object.entries(schema)) {+ if (key === 'enum' && hasSlashDelimitedEnumValue(value)) continue;++ sanitized[key] = sanitizeXAIToolSchema(value);+ }++ return sanitized;+};++const sanitizeXAITools = (tools?: ChatCompletionTool[]) =>+ tools?.map((tool) => {+ if (!tool.function.parameters) return tool;++ return {+ ...tool,+ function: {+ ...tool.function,+ parameters: sanitizeXAIToolSchema(+ tool.function.parameters,+ ) as ChatCompletionTool['function']['parameters'],+ },+ };+ });++/**+ * xAI Responses API accepts structured output constraints under `text.format`,+ * while callers still send OpenAI Chat Completions compatible `response_format`.+ */+const mapResponseFormatToResponsesText = (+ responseFormat?: ChatResponseFormat,+ text?: ChatStreamPayload['text'],+) => {+ if (!responseFormat) return text;++ if (responseFormat.type === 'json_schema') {+ return {+ ...text,+ format: { type: 'json_schema', ...responseFormat.json_schema },+ };+ }++ return {+ ...text,+ format: { type: responseFormat.type },+ };+};+export const LobeXAI = createOpenAICompatibleRuntime({baseURL: 'https://api.x.ai/v1',chatCompletion: {handlePayload: (payload) =>({...pruneUnsupportedChatCompletionParameters(payload),+ apiMode: 'responses',stream: payload.stream ?? true,}) as any,useResponse: true,@@ -71,15 +137,18 @@ export const LobeXAI = createOpenAICompatibleRuntime({provider: ModelProvider.XAI,responses: {handlePayload: (payload) => {- const { enabledSearch, tools, ...rest } = stripUnsupportedPenaltyParameters(payload);+ const { enabledSearch, response_format, text, tools, ...rest } =+ stripUnsupportedPenaltyParameters(payload);+ const sanitizedTools = sanitizeXAITools(tools);const xaiTools = enabledSearch- ? [...(tools || []), { type: 'web_search' }, { type: 'x_search' }]- : tools;+ ? [...(sanitizedTools || []), { type: 'web_search' }, { type: 'x_search' }]+ : sanitizedTools;return {...rest,tools: xaiTools,+ text: mapResponseFormatToResponsesText(response_format, text),include: ['reasoning.encrypted_content'],} as any;},diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.tsindex 570d664e565..666eea7b414 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts@@ -248,19 +248,23 @@ describe('StreamingExecutor actions', () => {useChatStore.setState({ executeClientAgent: realExecAgentRuntime });});- const agentConfig = createMockAgentConfig();-useAiInfraStore.setState({enabledAiModels: [{abilities: { functionCall: true },contextWindowTokens: 200_000,- id: agentConfig.model,- providerId: agentConfig.provider,+ id: 'gpt-4o-mini',+ providerId: 'openai',type: 'chat',} as EnabledAiModel,],});+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({+ agentConfig: createMockAgentConfig({ model: 'gpt-4o-mini', provider: 'openai' }),+ chatConfig: createMockChatConfig(),+ isBuiltinAgent: false,+ plugins: [],+ });const stepSpy = vi.spyOn(agentRuntime.AgentRuntime.prototype, 'step');const { result } = renderHook(() => useChatStore());