Skip to content

🤯 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.

🐛 fix: support Bedrock structured generation (#15174)

YuTengjingbe62847e0073
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.ts
index 7bd04372fba..7c1ef545aeb 100644
--- a/packages/model-runtime/src/core/ModelRuntime.test.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts
@@ -697,6 +697,41 @@ describe('ModelRuntime', () => {
expect(callOrder).toEqual(['existing', 'hook']);
});
+ it('onGenerateObjectFinal receives synthetic speed metrics', async () => {
+ const nowSpy = vi
+ .spyOn(Date, 'now')
+ .mockReturnValueOnce(1000)
+ .mockReturnValueOnce(2000)
+ .mockReturnValueOnce(2500);
+ const onGenerateObjectFinal = vi.fn();
+ const { runtime, mockRuntimeAI } = createMockRuntime({ onGenerateObjectFinal });
+ const usage = { totalInputTokens: 100, totalOutputTokens: 20, totalTokens: 120 };
+
+ mockRuntimeAI.generateObject.mockImplementation(async (_p: any, opts: any) => {
+ await opts?.onUsage?.(usage);
+ return { result: 'ok' };
+ });
+
+ try {
+ await runtime.generateObject(genObjPayload);
+
+ expect(onGenerateObjectFinal).toHaveBeenCalledWith(
+ {
+ speed: {
+ duration: 500,
+ latency: 500,
+ tps: 40,
+ ttft: 0,
+ },
+ usage,
+ },
+ { options: undefined, payload: genObjPayload },
+ );
+ } finally {
+ nowSpy.mockRestore();
+ }
+ });
+
it('onGenerateObjectError is called when generateObject throws, error is re-thrown', async () => {
const genError = { errorType: 'ProviderBizError', error: new Error('fail') };
const onGenerateObjectError = vi.fn();
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index e1145dbb1c4..edbc8d19b4f 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -1,4 +1,4 @@
-import type { ModelUsage, TracePayload } from '@lobechat/types';
+import type { ModelPerformance, ModelUsage, TracePayload } from '@lobechat/types';
import { createTimingHelpers, getDurationMs } from '@lobechat/utils';
import type { ClientOptions } from 'openai';
@@ -40,6 +40,20 @@ const getLobeHubTimingMetadata = (options?: {
}): Record<string, unknown> | undefined =>
options?.metadata?.provider === 'lobehub' ? options.metadata : undefined;
+const buildGenerateObjectSpeed = (startedAt: number, usage: ModelUsage): ModelPerformance => {
+ const latency = Math.max(Date.now() - startedAt, 0);
+ const totalOutputTokens = usage.totalOutputTokens ?? usage.outputTextTokens ?? 0;
+ const tps =
+ latency > 0 && totalOutputTokens > 0 ? totalOutputTokens / (latency / 1000) : undefined;
+
+ return {
+ duration: latency,
+ latency,
+ tps,
+ ttft: 0,
+ };
+};
+
export interface AgentChatOptions {
enableTrace?: boolean;
provider: string;
@@ -109,7 +123,7 @@ export interface ModelRuntimeHooks {
) => void | Promise<void>;
onGenerateObjectFinal?: (
- data: { usage?: ModelUsage },
+ data: { speed?: ModelPerformance; usage?: ModelUsage },
context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },
) => void | Promise<void>;
}
@@ -333,6 +347,7 @@ export class ModelRuntime {
try {
await this._hooks?.beforeGenerateObject?.(payload, options);
+ const runtimeStartedAt = Date.now();
const needsUsageCapture =
this._hooks?.onGenerateObjectFinal || this._hooks?.onGenerateObjectComplete;
@@ -342,9 +357,10 @@ export class ModelRuntime {
...options,
onUsage: async (usage: ModelUsage) => {
usageCapture = usage;
+ const speed = buildGenerateObjectSpeed(runtimeStartedAt, usage);
await options?.onUsage?.(usage);
try {
- await this._hooks?.onGenerateObjectFinal?.({ usage }, { options, payload });
+ await this._hooks?.onGenerateObjectFinal?.({ speed, usage }, { options, payload });
} catch (e) {
// Hook failures (billing, tracing) must not interfere with response completion
console.error('[ModelRuntime] onGenerateObjectFinal hook error:', e);
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
index 9c91cc6b36a..0eac7369cab 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
@@ -10,20 +10,30 @@ import { withUsageCost } from '../usageConverters/utils/withUsageCost';
const log = debug('lobe-model-runtime:anthropic:generate-object');
export interface AnthropicGenerateObjectConfig {
- requestParams?: Pick<Anthropic.MessageCreateParams, 'output_config' | 'thinking'>;
+ maxTokens?: number;
+ requestParams?: Pick<Anthropic.MessageCreateParamsNonStreaming, 'output_config' | 'thinking'>;
schemaToolChoice?: 'any' | 'tool';
+ schemaToolStrict?: boolean;
}
-/**
- * Generate structured output using Anthropic Claude API with Function Calling
- */
-export const createAnthropicGenerateObject = async (
- client: Anthropic,
+interface AnthropicToolUseLike {
+ input?: unknown;
+ name?: string;
+ type?: string;
+}
+
+export interface AnthropicGenerateObjectResponse {
+ content?: AnthropicToolUseLike[];
+ usage?: Anthropic.Messages.Usage | null;
+}
+
+export const buildAnthropicGenerateObjectRequest = async (
payload: GenerateObjectPayload,
- options?: GenerateObjectOptions,
- pricing?: Pricing,
config?: AnthropicGenerateObjectConfig,
-) => {
+): Promise<{
+ requestParams: Anthropic.MessageCreateParamsNonStreaming;
+ schemaToolName?: string;
+}> => {
const { schema, messages, model, tools } = payload;
log('generateObject called with model: %s', model);
@@ -60,8 +70,9 @@ export const createAnthropicGenerateObject = async (
const tool: Anthropic.ToolUnion = {
description:
schema.description || 'Generate structured output according to the provided schema',
- input_schema: schema.schema as any,
+ input_schema: schema.schema as Anthropic.Tool.InputSchema,
name: schema.name || 'structured_output',
+ ...(config?.schemaToolStrict && schema.strict !== undefined ? { strict: schema.strict } : {}),
};
log('converted tool: %O', tool);
@@ -73,48 +84,82 @@ export const createAnthropicGenerateObject = async (
throw new Error('tools or schema is required');
}
- try {
- log('calling Anthropic API with max_tokens: %d', 64_000);
-
- const response = await client.messages.create(
- {
- max_tokens: 64_000,
- messages: anthropicMessages,
- model,
- system: systemPrompts,
- ...config?.requestParams,
- tool_choice,
- tools: finalTools,
- },
- { signal: options?.signal },
- );
+ return {
+ requestParams: {
+ max_tokens: config?.maxTokens ?? 64_000,
+ messages: anthropicMessages,
+ model,
+ system: systemPrompts,
+ ...config?.requestParams,
+ tool_choice,
+ tools: finalTools,
+ },
+ schemaToolName,
+ };
+};
- log('received response with %d content blocks', response.content.length);
- log('response: %O', response);
+export const emitAnthropicGenerateObjectUsage = async (
+ response: AnthropicGenerateObjectResponse,
+ options?: GenerateObjectOptions,
+ pricing?: Pricing,
+) => {
+ const initialUsage = buildAnthropicInitialUsage(response.usage);
+ if (initialUsage) {
+ await options?.onUsage?.(withUsageCost(initialUsage, pricing));
+ }
+};
+
+export const parseAnthropicGenerateObjectResponse = (
+ response: AnthropicGenerateObjectResponse,
+ schemaToolName?: string,
+) => {
+ const content = response.content ?? [];
+
+ if (schemaToolName) {
+ const toolUseBlock = content.find(
+ (block) => block.type === 'tool_use' && block.name === schemaToolName,
+ );
- const initialUsage = buildAnthropicInitialUsage(response.usage);
- if (initialUsage) {
- await options?.onUsage?.(withUsageCost(initialUsage, pricing));
+ if (!toolUseBlock || toolUseBlock.type !== 'tool_use') {
+ log('no tool use found in response (expected tool: %s)', schemaToolName);
+ return undefined;
}
- // Extract the tool use result
- if (schemaToolName) {
- const toolUseBlock = response.content.find(
- (block) => block.type === 'tool_use' && block.name === schemaToolName,
- );
+ log('extracted tool input: %O', toolUseBlock.input);
+ return toolUseBlock.input;
+ }
- if (!toolUseBlock || toolUseBlock.type !== 'tool_use') {
- log('no tool use found in response (expected tool: %s)', schemaToolName);
- return undefined;
- }
+ return content
+ .filter((block) => block.type === 'tool_use')
+ .map((block) => ({ arguments: block.input, name: block.name }));
+};
- log('extracted tool input: %O', toolUseBlock.input);
- return toolUseBlock.input;
- }
+/**
+ * Generate structured output using Anthropic Claude API with Function Calling
+ */
+export const createAnthropicGenerateObject = async (
+ client: Anthropic,
+ payload: GenerateObjectPayload,
+ options?: GenerateObjectOptions,
+ pricing?: Pricing,
+ config?: AnthropicGenerateObjectConfig,
+) => {
+ const { requestParams, schemaToolName } = await buildAnthropicGenerateObjectRequest(
+ payload,
+ config,
+ );
+
+ try {
+ log('calling Anthropic API with max_tokens: %d', requestParams.max_tokens);
+
+ const response = await client.messages.create(requestParams, { signal: options?.signal });
+
+ log('received response with %d content blocks', response.content.length);
+ log('response: %O', response);
+
+ await emitAnthropicGenerateObjectUsage(response, options, pricing);
- return response.content
- .filter((block) => block.type === 'tool_use')
- .map((block) => ({ arguments: block.input, name: block.name }));
+ return parseAnthropicGenerateObjectResponse(response, schemaToolName);
} catch (error) {
log('generateObject error: %O', error);
throw error;
diff --git a/packages/model-runtime/src/providers/bedrock/index.test.ts b/packages/model-runtime/src/providers/bedrock/index.test.ts
index c941693e88c..09e7532a755 100644
--- a/packages/model-runtime/src/providers/bedrock/index.test.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.test.ts
@@ -11,9 +11,15 @@ import { AgentRuntimeErrorType } from '../../types/error';
import * as debugStreamModule from '../../utils/debugStream';
import { experimental_buildLlama2Prompt, LobeBedrockAI } from './index';
+const loadModelsMock = vi.hoisted(() => vi.fn().mockResolvedValue([]));
+
// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ loadModels: loadModelsMock,
+}));
+
vi.mock('@aws-sdk/client-bedrock-runtime', async (importOriginal) => {
const module = await importOriginal();
return {
@@ -1014,6 +1020,184 @@ describe('LobeBedrockAI', () => {
});
});
+ describe('generateObject', () => {
+ it('should generate a schema object through Anthropic tool use', async () => {
+ const mockResponse = {
+ body: new TextEncoder().encode(
+ JSON.stringify({
+ content: [
+ {
+ input: { summary: 'Done', title: 'Task summary' },
+ name: 'task_topic_handoff',
+ type: 'tool_use',
+ },
+ ],
+ usage: {
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ input_tokens: 100,
+ output_tokens: 50,
+ },
+ }),
+ ),
+ };
+ const abortController = new AbortController();
+ const onUsage = vi.fn();
+ const sendSpy = vi.spyOn(instance['client'], 'send').mockResolvedValue(mockResponse as any);
+
+ const result = await instance.generateObject(
+ {
+ messages: [
+ { content: 'You create compact summaries.', role: 'system' },
+ { content: 'Summarize this task topic.', role: 'user' },
+ ],
+ model: 'global.anthropic.claude-sonnet-4-6',
+ schema: {
+ name: 'task_topic_handoff',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ summary: { type: 'string' },
+ title: { type: 'string' },
+ },
+ required: ['title', 'summary'],
+ type: 'object',
+ },
+ strict: true,
+ },
+ },
+ { onUsage, signal: abortController.signal },
+ );
+
+ const commandInput = (InvokeModelCommand as unknown as Mock).mock.calls[0][0];
+ const body = JSON.parse(commandInput.body);
+
+ expect(result).toEqual({ summary: 'Done', title: 'Task summary' });
+ expect(commandInput.modelId).toBe('global.anthropic.claude-sonnet-4-6');
+ expect(body).toEqual({
+ anthropic_version: 'bedrock-2023-05-31',
+ max_tokens: 64_000,
+ messages: [{ content: 'Summarize this task topic.', role: 'user' }],
+ system: [{ text: 'You create compact summaries.', type: 'text' }],
+ tool_choice: { name: 'task_topic_handoff', type: 'tool' },
+ tools: [
+ {
+ description: 'Generate structured output according to the provided schema',
+ input_schema: {
+ additionalProperties: false,
+ properties: {
+ summary: { type: 'string' },
+ title: { type: 'string' },
+ },
+ required: ['title', 'summary'],
+ type: 'object',
+ },
+ name: 'task_topic_handoff',
+ },
+ ],
+ });
+ expect(body.tools[0]).not.toHaveProperty('strict');
+ expect(sendSpy).toHaveBeenCalledWith(expect.any(InvokeModelCommand), {
+ abortSignal: abortController.signal,
+ });
+ expect(onUsage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ inputCacheMissTokens: 100,
+ totalInputTokens: 100,
+ totalOutputTokens: 50,
+ totalTokens: 150,
+ }),
+ );
+ });
+
+ it('should return tool calls when tools are provided', async () => {
+ const mockResponse = {
+ body: new TextEncoder().encode(
+ JSON.stringify({
+ content: [
+ {
+ input: { query: 'status' },
+ name: 'search_task',
+ type: 'tool_use',
+ },
+ ],
+ }),
+ ),
+ };
+ (instance['client'].send as Mock).mockResolvedValue(mockResponse);
+
+ const result = await instance.generateObject({
+ messages: [{ content: 'Find the current task status.', role: 'user' }],
+ model: 'global.anthropic.claude-sonnet-4-6',
+ tools: [
+ {
+ function: {
+ description: 'Search task data',
+ name: 'search_task',
+ parameters: {
+ properties: { query: { type: 'string' } },
+ required: ['query'],
+ type: 'object',
+ },
+ },
+ type: 'function',
+ },
+ ],
+ });
+
+ const commandInput = (InvokeModelCommand as unknown as Mock).mock.calls[0][0];
+ const body = JSON.parse(commandInput.body);
+
+ expect(result).toEqual([{ arguments: { query: 'status' }, name: 'search_task' }]);
+ expect(body.tool_choice).toEqual({ type: 'any' });
+ expect(body.tools).toEqual([
+ {
+ description: 'Search task data',
+ input_schema: {
+ properties: { query: { type: 'string' } },
+ required: ['query'],
+ type: 'object',
+ },
+ name: 'search_task',
+ },
+ ]);
+ });
+
+ it('should throw AgentRuntimeError on API error', async () => {
+ const errorMessage = 'Generate object API error';
+ const errorMetadata = { statusCode: 400 };
+ const mockError = new Error(errorMessage);
+ (mockError as any).$metadata = errorMetadata;
+ (instance['client'].send as Mock).mockRejectedValue(mockError);
+
+ await expect(
+ instance.generateObject({
+ messages: [{ content: 'Summarize this task topic.', role: 'user' }],
+ model: 'global.anthropic.claude-sonnet-4-6',
+ schema: {
+ name: 'task_topic_handoff',
+ schema: {
+ properties: { summary: { type: 'string' } },
+ required: ['summary'],
+ type: 'object',
+ },
+ },
+ }),
+ ).rejects.toThrow(
+ expect.objectContaining({
+ error: {
+ body: errorMetadata,
+ message: errorMessage,
+ type: 'Error',
+ },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: ModelProvider.Bedrock,
+ region: 'us-west-2',
+ }),
+ );
+ });
+ });
+
describe('embeddings', () => {
it('should handle single input string', async () => {
// Arrange
diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.ts
index b7d8dee0dbf..f700175be77 100644
--- a/packages/model-runtime/src/providers/bedrock/index.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.ts
@@ -8,6 +8,12 @@ import { cloudModelIdMapping } from '@lobechat/business-const';
import { ModelProvider } from 'model-bank';
import { shouldDropUnsupportedClaudeAssistantPrefill } from '../../const/models';
+import type { AnthropicGenerateObjectResponse } from '../../core/anthropicCompatibleFactory/generateObject';
+import {
+ buildAnthropicGenerateObjectRequest,
+ emitAnthropicGenerateObjectUsage,
+ parseAnthropicGenerateObjectResponse,
+} from '../../core/anthropicCompatibleFactory/generateObject';
import { resolveCacheTTL } from '../../core/anthropicCompatibleFactory/resolveCacheTTL';
import { resolveMaxTokens } from '../../core/anthropicCompatibleFactory/resolveMaxTokens';
import type { LobeRuntimeAI } from '../../core/BaseAI';
@@ -24,6 +30,8 @@ import type {
Embeddings,
EmbeddingsOptions,
EmbeddingsPayload,
+ GenerateObjectOptions,
+ GenerateObjectPayload,
} from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeError } from '../../utils/createError';
@@ -124,6 +132,71 @@ export class LobeBedrockAI implements LobeRuntimeAI {
return Promise.all(promises);
}
+ async generateObject(payload: GenerateObjectPayload, options?: GenerateObjectOptions) {
+ return this.invokeClaudeGenerateObject(payload, options);
+ }
+
+ private invokeClaudeGenerateObject = async (
+ payload: GenerateObjectPayload,
+ options?: GenerateObjectOptions,
+ ) => {
+ const { bedrock: bedrockModels } = await import('model-bank');
+ const resolvedMaxTokens = await resolveMaxTokens({
+ model: payload.model,
+ providerModels: bedrockModels,
+ thinking: payload.thinking,
+ });
+ const systemMessages = payload.messages.filter((m) => m.role === 'system');
+ const normalizedMessages = normalizeClaudeThinkingHistoryMessages(
+ payload.messages.filter((m) => m.role !== 'system') as ChatStreamPayload['messages'],
+ ) as GenerateObjectPayload['messages'];
+ const { requestParams, schemaToolName } = await buildAnthropicGenerateObjectRequest(
+ { ...payload, messages: [...systemMessages, ...normalizedMessages] },
+ { maxTokens: resolvedMaxTokens },
+ );
+ const bedrockRequestParams: Omit<Anthropic.MessageCreateParams, 'model'> & {
+ model?: Anthropic.MessageCreateParams['model'];
+ } = { ...requestParams };
+ delete bedrockRequestParams.model;
+
+ const command = new InvokeModelCommand({
+ accept: 'application/json',
+ body: JSON.stringify({
+ anthropic_version: 'bedrock-2023-05-31',
+ ...bedrockRequestParams,
+ }),
+ contentType: 'application/json',
+ modelId: cloudModelIdMapping[payload.model] || payload.model,
+ });
+
+ try {
+ const [res, pricing] = await Promise.all([
+ this.client.send(command, { abortSignal: options?.signal }),
+ getModelPricing(payload.model, this.id),
+ ]);
+ const responseBody = JSON.parse(
+ new TextDecoder().decode(res.body),
+ ) as AnthropicGenerateObjectResponse;
+
+ await emitAnthropicGenerateObjectUsage(responseBody, options, pricing);
+
+ return parseAnthropicGenerateObjectResponse(responseBody, schemaToolName);
+ } catch (e) {
+ const err = e as Error & { $metadata: any };
+
+ throw AgentRuntimeError.chat({
+ error: {
+ body: err.$metadata,
+ message: err.message,
+ type: err.name,
+ },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: this.id,
+ region: this.region,
+ });
+ }
+ };
+
private invokeEmbeddingModel = async (
payload: EmbeddingsPayload,
options?: EmbeddingsOptions,