🤯 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: output JSON support tools calling mode (#9696)
Arvin Xu1238d7fbd544
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.tsindex 7025e533c3c..57f9633f1bd 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts@@ -1857,6 +1857,185 @@ describe('LobeOpenAICompatibleFactory', () => {});});+ describe('tools parameter support', () => {+ it('should handle tools parameter with multiple tools', async () => {+ const mockResponse = {+ choices: [+ {+ message: {+ tool_calls: [+ {+ type: 'function' as const,+ function: {+ name: 'get_weather',+ arguments: '{"city":"Tokyo","unit":"celsius"}',+ },+ },+ {+ type: 'function' as const,+ function: {+ name: 'get_time',+ arguments: '{"timezone":"Asia/Tokyo"}',+ },+ },+ ],+ },+ },+ ],+ };++ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ mockResponse as any,+ );++ const payload = {+ messages: [{ content: 'What is the weather and time in Tokyo?', role: 'user' as const }],+ tools: [+ {+ name: 'get_weather',+ description: 'Get weather information',+ parameters: {+ type: 'object' as const,+ properties: {+ city: { type: 'string' },+ unit: { type: 'string' },+ },+ required: ['city'],+ },+ },+ {+ name: 'get_time',+ description: 'Get current time',+ parameters: {+ type: 'object' as const,+ properties: {+ timezone: { type: 'string' },+ },+ required: ['timezone'],+ },+ },+ ],+ model: 'gpt-4o',+ };++ const result = await instance.generateObject(payload);++ expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(+ {+ messages: payload.messages,+ model: payload.model,+ tool_choice: 'required',+ tools: [+ {+ type: 'function',+ function: {+ name: 'get_weather',+ description: 'Get weather information',+ parameters: {+ type: 'object',+ properties: {+ city: { type: 'string' },+ unit: { type: 'string' },+ },+ required: ['city'],+ },+ },+ },+ {+ type: 'function',+ function: {+ name: 'get_time',+ description: 'Get current time',+ parameters: {+ type: 'object',+ properties: {+ timezone: { type: 'string' },+ },+ required: ['timezone'],+ },+ },+ },+ ],+ user: undefined,+ },+ { headers: undefined, signal: undefined },+ );++ expect(result).toEqual([+ { arguments: { city: 'Tokyo', unit: 'celsius' }, name: 'get_weather' },+ { arguments: { timezone: 'Asia/Tokyo' }, name: 'get_time' },+ ]);+ });++ it('should handle tools parameter with systemRole', async () => {+ const mockResponse = {+ choices: [+ {+ message: {+ tool_calls: [+ {+ type: 'function' as const,+ function: {+ name: 'calculate',+ arguments: '{"result":8}',+ },+ },+ ],+ },+ },+ ],+ };++ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(+ mockResponse as any,+ );++ const payload = {+ messages: [{ content: 'Add 5 and 3', role: 'user' as const }],+ tools: [+ {+ name: 'calculate',+ description: 'Perform calculation',+ parameters: {+ type: 'object' as const,+ properties: {+ result: { type: 'number' },+ },+ required: ['result'],+ },+ },+ ],+ systemRole: 'You are a helpful calculator',+ model: 'gpt-4o',+ };++ const result = await instance.generateObject(payload);++ expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(+ expect.objectContaining({+ messages: [+ { content: 'Add 5 and 3', role: 'user' },+ { content: 'You are a helpful calculator', role: 'system' },+ ],+ }),+ expect.any(Object),+ );++ expect(result).toEqual([{ arguments: { result: 8 }, name: 'calculate' }]);+ });++ it('should throw error when neither tools nor schema is provided', async () => {+ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ model: 'gpt-4o',+ };++ await expect(instance.generateObject(payload as any)).rejects.toThrow(+ 'tools or schema is required',+ );+ });+ });+describe('tool calling fallback', () => {let instanceWithToolCalling: any;@@ -1930,7 +2109,9 @@ describe('LobeOpenAICompatibleFactory', () => {{ headers: undefined, signal: undefined },);- expect(result).toEqual({ name: 'Alice', age: 28 });+ expect(result).toEqual([+ { arguments: { name: 'Alice', age: 28 }, name: 'person_extractor' },+ ]);});it('should return undefined when no tool call found', async () => {@@ -1960,7 +2141,7 @@ describe('LobeOpenAICompatibleFactory', () => {const result = await instanceWithToolCalling.generateObject(payload);- expect(consoleSpy).toHaveBeenCalledWith('No tool call found in response');+ expect(consoleSpy).toHaveBeenCalledWith('parse tool call arguments error:', undefined);expect(result).toBeUndefined();consoleSpy.mockRestore();@@ -2001,7 +2182,10 @@ describe('LobeOpenAICompatibleFactory', () => {const result = await instanceWithToolCalling.generateObject(payload);- expect(consoleSpy).toHaveBeenCalledWith('parse tool call arguments error:', 'invalid json');+ expect(consoleSpy).toHaveBeenCalledWith(+ 'parse tool call arguments error:',+ mockResponse.choices[0].message.tool_calls,+ );expect(result).toBeUndefined();consoleSpy.mockRestore();@@ -2052,7 +2236,7 @@ describe('LobeOpenAICompatibleFactory', () => {{ headers: options.headers, signal: options.signal },);- expect(result).toEqual({ data: 'test' });+ expect(result).toEqual([{ arguments: { data: 'test' }, name: 'data_extractor' }]);});});});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 234ea88205f..a6a743b9951 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -396,7 +396,40 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an}async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {- const { messages, schema, model, responseApi } = payload;+ const { messages, schema, model, responseApi, tools, systemRole } = payload;++ if (tools) {+ const msgs = messages;++ if (!!systemRole) {+ msgs.push({ content: systemRole, role: 'system' });+ }++ const res = await this.client.chat.completions.create(+ {+ messages: msgs,+ model,+ tool_choice: 'required',+ tools: tools.map((tool) => ({ function: tool, type: 'function' })),+ user: options?.user,+ },+ { headers: options?.headers, signal: options?.signal },+ );++ const toolCalls = res.choices[0].message.tool_calls!;++ try {+ return toolCalls.map((item) => ({+ arguments: JSON.parse(item.function.arguments),+ name: item.function.name,+ }));+ } catch {+ console.error('parse tool call arguments error:', res);+ return undefined;+ }+ }++ if (!schema) throw new Error('tools or schema is required');// Use tool calling fallback if configuredif (generateObjectConfig?.useToolsCalling) {@@ -421,17 +454,15 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an{ headers: options?.headers, signal: options?.signal },);- const toolCall = res.choices[0].message.tool_calls?.[0];-- if (!toolCall || toolCall.type !== 'function') {- console.error('No tool call found in response');- return undefined;- }+ const toolCalls = res.choices[0].message.tool_calls!;try {- return JSON.parse(toolCall.function.arguments);+ return toolCalls.map((item) => ({+ arguments: JSON.parse(item.function.arguments),+ name: item.function.name,+ }));} catch {- console.error('parse tool call arguments error:', toolCall.function.arguments);+ console.error('parse tool call arguments error:', toolCalls);return undefined;}}diff --git a/packages/model-runtime/src/providers/anthropic/generateObject.test.ts b/packages/model-runtime/src/providers/anthropic/generateObject.test.tsindex 9ccefad3e15..a457068e135 100644--- a/packages/model-runtime/src/providers/anthropic/generateObject.test.ts+++ b/packages/model-runtime/src/providers/anthropic/generateObject.test.ts@@ -4,7 +4,24 @@ import { describe, expect, it, vi } from 'vitest';import { createAnthropicGenerateObject } from './generateObject';describe('Anthropic generateObject', () => {- describe('createAnthropicGenerateObject', () => {+ it('should throw error when neither tools nor schema is provided', async () => {+ const mockClient = {+ messages: {+ create: vi.fn(),+ },+ };++ const payload = {+ messages: [{ content: 'Generate data', role: 'user' as const }],+ model: 'claude-3-5-sonnet-20241022',+ };++ await expect(createAnthropicGenerateObject(mockClient as any, payload as any)).rejects.toThrow(+ 'tools or schema is required',+ );+ });++ describe('use struct output schema', () => {it('should return structured data on successful API call', async () => {const mockClient = {messages: {@@ -243,56 +260,193 @@ describe('Anthropic generateObject', () => {},});});+ });- it('should propagate API errors correctly', async () => {- const apiError = new Error('API Error: Model not found');-+ describe('tools calling', () => {+ it('should handle tools calling mode with multiple tools', async () => {const mockClient = {messages: {- create: vi.fn().mockRejectedValue(apiError),+ create: vi.fn().mockResolvedValue({+ content: [+ {+ type: 'tool_use',+ name: 'get_weather',+ input: { city: 'New York', unit: 'celsius' },+ },+ {+ type: 'tool_use',+ name: 'get_time',+ input: { timezone: 'America/New_York' },+ },+ ],+ }),},};const payload = {- messages: [{ content: 'Generate data', role: 'user' as const }],- schema: {- name: 'test_tool',- schema: { type: 'object' },- },+ messages: [{ content: 'What is the weather and time in New York?', role: 'user' as const }],+ tools: [+ {+ name: 'get_weather',+ description: 'Get weather information',+ parameters: {+ type: 'object' as const,+ properties: {+ city: { type: 'string' },+ unit: { type: 'string' },+ },+ required: ['city'],+ },+ },+ {+ name: 'get_time',+ description: 'Get current time',+ parameters: {+ type: 'object' as const,+ properties: {+ timezone: { type: 'string' },+ },+ required: ['timezone'],+ },+ },+ ],model: 'claude-3-5-sonnet-20241022',};- await expect(- createAnthropicGenerateObject(mockClient as any, payload as any),- ).rejects.toThrow('API Error: Model not found');- });+ const result = await createAnthropicGenerateObject(mockClient as any, payload as any);- it('should handle abort signals correctly', async () => {- const apiError = new Error('Request was cancelled');- apiError.name = 'AbortError';+ expect(mockClient.messages.create).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'claude-3-5-sonnet-20241022',+ max_tokens: 8192,+ messages: [{ content: 'What is the weather and time in New York?', role: 'user' }],+ tools: [+ {+ name: 'get_weather',+ description: 'Get weather information',+ input_schema: {+ type: 'object',+ properties: {+ city: { type: 'string' },+ unit: { type: 'string' },+ },+ required: ['city'],+ },+ },+ {+ name: 'get_time',+ description: 'Get current time',+ input_schema: {+ type: 'object',+ properties: {+ timezone: { type: 'string' },+ },+ required: ['timezone'],+ },+ },+ ],+ tool_choice: {+ type: 'any',+ },+ }),+ expect.objectContaining({}),+ );++ expect(result).toEqual([+ { arguments: { city: 'New York', unit: 'celsius' }, name: 'get_weather' },+ { arguments: { timezone: 'America/New_York' }, name: 'get_time' },+ ]);+ });+ it('should handle tools calling mode with single tool', async () => {const mockClient = {messages: {- create: vi.fn().mockRejectedValue(apiError),+ create: vi.fn().mockResolvedValue({+ content: [+ {+ type: 'tool_use',+ name: 'calculate',+ input: { operation: 'add', a: 5, b: 3 },+ },+ ],+ }),},};const payload = {- messages: [{ content: 'Generate data', role: 'user' as const }],- schema: {- name: 'test_tool',- schema: { type: 'object' },- },+ messages: [{ content: 'Add 5 and 3', role: 'user' as const }],+ tools: [+ {+ name: 'calculate',+ description: 'Perform mathematical calculation',+ parameters: {+ type: 'object' as const,+ properties: {+ operation: { type: 'string' },+ a: { type: 'number' },+ b: { type: 'number' },+ },+ required: ['operation', 'a', 'b'],+ },+ },+ ],model: 'claude-3-5-sonnet-20241022',};- const options = {- signal: new AbortController().signal,- };+ const result = await createAnthropicGenerateObject(mockClient as any, payload as any);- await expect(- createAnthropicGenerateObject(mockClient as any, payload as any, options),- ).rejects.toThrow();+ expect(result).toEqual([{ arguments: { operation: 'add', a: 5, b: 3 }, name: 'calculate' }]);});});++ 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: {+ name: 'test_tool',+ schema: { type: 'object' },+ },+ model: 'claude-3-5-sonnet-20241022',+ };++ await expect(createAnthropicGenerateObject(mockClient as any, payload as any)).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: {+ name: 'test_tool',+ schema: { type: 'object' },+ },+ model: 'claude-3-5-sonnet-20241022',+ };++ const options = {+ signal: new AbortController().signal,+ };++ await expect(+ createAnthropicGenerateObject(mockClient as any, payload as any, options),+ ).rejects.toThrow();+ });});diff --git a/packages/model-runtime/src/providers/anthropic/generateObject.ts b/packages/model-runtime/src/providers/anthropic/generateObject.tsindex 1defd30acf8..7dff5c4bc5b 100644--- a/packages/model-runtime/src/providers/anthropic/generateObject.ts+++ b/packages/model-runtime/src/providers/anthropic/generateObject.ts@@ -1,7 +1,7 @@import type Anthropic from '@anthropic-ai/sdk';import debug from 'debug';-import { buildAnthropicMessages } from '../../core/contextBuilders/anthropic';+import { buildAnthropicMessages, buildAnthropicTools } from '../../core/contextBuilders/anthropic';import { GenerateObjectOptions, GenerateObjectPayload } from '../../types';const log = debug('lobe-model-runtime:anthropic:generate-object');@@ -14,21 +14,12 @@ export const createAnthropicGenerateObject = async (payload: GenerateObjectPayload,options?: GenerateObjectOptions,) => {- const { schema, messages, model } = payload;+ const { schema, messages, model, tools } = payload;log('generateObject called with model: %s', model);log('schema: %O', schema);log('messages count: %d', messages.length);- // Convert OpenAI-style schema to Anthropic tool format- const tool: Anthropic.ToolUnion = {- description:- schema.description || 'Generate structured output according to the provided schema',- input_schema: schema.schema as any,- name: schema.name || 'structured_output',- };-- log('converted tool: %O', tool);// Convert messages to Anthropic formatconst system_message = messages.find((m) => m.role === 'system');const user_messages = messages.filter((m) => m.role !== 'system');@@ -45,6 +36,27 @@ export const createAnthropicGenerateObject = async (]: undefined;+ let finalTools;+ let tool_choice: Anthropic.ToolChoiceAny | Anthropic.ToolChoiceTool;+ if (tools) {+ finalTools = buildAnthropicTools(tools.map((item) => ({ function: item, type: 'function' })));+ tool_choice = { type: 'any' };+ } else if (schema) {+ // Convert OpenAI-style schema to Anthropic tool format+ const tool: Anthropic.ToolUnion = {+ description:+ schema.description || 'Generate structured output according to the provided schema',+ input_schema: schema.schema as any,+ name: schema.name || 'structured_output',+ };+ log('converted tool: %O', tool);++ finalTools = [tool];+ tool_choice = { name: tool.name, type: 'tool' };+ } else {+ throw new Error('tools or schema is required');+ }+try {log('calling Anthropic API with max_tokens: %d', 8192);@@ -54,29 +66,33 @@ export const createAnthropicGenerateObject = async (messages: anthropicMessages,model,system: systemPrompts,- tool_choice: { name: tool.name, type: 'tool' },- tools: [tool],- },- {- signal: options?.signal,+ tool_choice: tool_choice,+ tools: finalTools,},+ { signal: options?.signal },);log('received response with %d content blocks', response.content.length);log('response: %O', response);// Extract the tool use result- const toolUseBlock = response.content.find(- (block) => block.type === 'tool_use' && block.name === tool.name,- );+ if (tool_choice.type === 'tool') {+ const toolUseBlock = response.content.find(+ (block) => block.type === 'tool_use' && block.name === tool_choice.name,+ );++ if (!toolUseBlock || toolUseBlock.type !== 'tool_use') {+ log('no tool use found in response (expected tool: %s)', tool_choice.name);+ return undefined;+ }- if (!toolUseBlock || toolUseBlock.type !== 'tool_use') {- log('no tool use found in response (expected tool: %s)', tool.name);- return undefined;+ log('extracted tool input: %O', toolUseBlock.input);+ return toolUseBlock.input;}- log('extracted tool input: %O', toolUseBlock.input);- return toolUseBlock.input;+ return response.content+ .filter((block) => block.type === 'tool_use')+ .map((block) => ({ arguments: block.input, name: block.name }));} catch (error) {log('generateObject error: %O', error);throw error;diff --git a/packages/model-runtime/src/types/structureOutput.ts b/packages/model-runtime/src/types/structureOutput.tsindex fee503c8b11..40c7fa46795 100644--- a/packages/model-runtime/src/types/structureOutput.ts+++ b/packages/model-runtime/src/types/structureOutput.ts@@ -1,3 +1,5 @@+import { ChatCompletionFunctions } from './chat';+interface GenerateObjectMessage {content: string;name?: string;@@ -20,7 +22,9 @@ export interface GenerateObjectPayload {messages: GenerateObjectMessage[];model: string;responseApi?: boolean;- schema: GenerateObjectSchema;+ schema?: GenerateObjectSchema;+ systemRole?: string;+ tools?: ChatCompletionFunctions[];}export interface GenerateObjectOptions {diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex ef6ffa9b6e8..cd5932db896 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -1,6 +1,7 @@import { z } from 'zod';import { ChatMessage } from './message';+import { LobeUniformTool, LobeUniformToolSchema } from './tool';import { ChatTopic } from './topic';export interface SendNewMessage {@@ -58,6 +59,7 @@ export const StructureSchema = z.object({description: z.string().optional(),name: z.string(),schema: z.object({+ $defs: z.any().optional(),additionalProperties: z.boolean().optional(),properties: z.record(z.string(), z.any()),required: z.array(z.string()).optional(),@@ -71,13 +73,29 @@ export const StructureOutputSchema = z.object({messages: z.array(z.any()),model: z.string(),provider: z.string(),- schema: StructureSchema,+ schema: StructureSchema.optional(),+ systemRole: z.string().optional(),+ tools: z.array(LobeUniformToolSchema).optional(),});+interface IStructureSchema {+ description: string;+ name: string;+ schema: {+ additionalProperties?: boolean;+ properties: Record<string, any>;+ required?: string[];+ type: 'object';+ };+ strict?: boolean;+}+export interface StructureOutputParams {keyVaultsPayload: string;messages: ChatMessage[];model: string;provider: string;- schema: any;+ schema?: IStructureSchema;+ systemRole?: string;+ tools?: LobeUniformTool[];}diff --git a/packages/types/src/tool/index.ts b/packages/types/src/tool/index.tsindex 7001f14108e..1385a267cb0 100644--- a/packages/types/src/tool/index.ts+++ b/packages/types/src/tool/index.ts@@ -28,3 +28,4 @@ export * from './crawler';export * from './interpreter';export * from './plugin';export * from './search';+export * from './tool';diff --git a/packages/types/src/tool/tool.ts b/packages/types/src/tool/tool.tsindex 2c09ea01d9a..e77f96594da 100644--- a/packages/types/src/tool/tool.ts+++ b/packages/types/src/tool/tool.ts@@ -1,3 +1,5 @@+import { z } from 'zod';+import { MetaData } from '../meta';export type LobeToolType = 'builtin' | 'customPlugin' | 'plugin';@@ -11,3 +13,34 @@ export interface LobeToolMeta extends MetaData {meta: MetaData;type: LobeToolType;}++export interface LobeUniformTool {+ /**+ * The description of what the function does.+ */+ description?: string;+ /**+ * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.+ */+ name: string;+ /**+ * The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/gpt/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format.+ */+ parameters: {+ additionalProperties?: boolean;+ properties: Record<string, any>;+ required?: string[];+ type: 'object';+ };+}++export const LobeUniformToolSchema = z.object({+ description: z.string().optional(),+ name: z.string(),+ parameters: z.object({+ additionalProperties: z.boolean().optional(),+ properties: z.record(z.string(), z.any()),+ required: z.array(z.string()).optional(),+ type: z.literal('object'),+ }),+});diff --git a/src/server/routers/lambda/aiChat.ts b/src/server/routers/lambda/aiChat.tsindex d3774dd110c..453a88c0a55 100644--- a/src/server/routers/lambda/aiChat.ts+++ b/src/server/routers/lambda/aiChat.ts@@ -60,6 +60,8 @@ export const aiChatRouter = router({messages: input.messages,model: input.model,schema: input.schema,+ systemRole: input.systemRole,+ tools: input.tools,});log('generateObject completed, result: %O', result);