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.

✅ test: add tests for agent-runtime and mode-runtime (#9682)

Arvin Xu4b7e838008c1
diff --git a/packages/agent-runtime/examples/tools-calling.ts b/packages/agent-runtime/examples/tools-calling.ts
index cfabf320aee..7d359ad9fa1 100644
--- a/packages/agent-runtime/examples/tools-calling.ts
+++ b/packages/agent-runtime/examples/tools-calling.ts
@@ -2,7 +2,7 @@
import OpenAI from 'openai';
import { AgentRuntime } from '../src';
-import type { Agent, AgentState, RuntimeContext } from '../src';
+import type { Agent, AgentRuntimeContext, AgentState } from '../src';
// OpenAI 模型运行时
async function* openaiRuntime(payload: any) {
@@ -112,7 +112,7 @@ class SimpleAgent implements Agent {
}
// Agent 决策逻辑 - 基于执行阶段和上下文
- async runner(context: RuntimeContext, state: AgentState) {
+ async runner(context: AgentRuntimeContext, state: AgentState) {
console.log(`[${context.phase}] 对话状态: ${this.conversationState}`);
switch (context.phase) {
@@ -257,7 +257,7 @@ async function main() {
console.log('🤖 AI: ');
// 执行对话循环
- let nextContext: RuntimeContext | undefined = undefined;
+ let nextContext: AgentRuntimeContext | undefined = undefined;
while (state.status !== 'done' && state.status !== 'error') {
const result = await runtime.step(state, nextContext);
@@ -300,4 +300,5 @@ async function main() {
console.log(`\n📊 总共执行了 ${state.stepCount} 个步骤`);
}
+// eslint-disable-next-line unicorn/prefer-top-level-await
main().catch(console.error);
diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
index db95a0925b2..76e1ff29bfb 100644
--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
@@ -3,12 +3,12 @@ import { describe, expect, it, vi } from 'vitest';
import {
Agent,
AgentEventError,
+ AgentRuntimeContext,
AgentState,
Cost,
CostCalculationContext,
CostLimit,
RuntimeConfig,
- RuntimeContext,
ToolsCalling,
Usage,
} from '../../types';
@@ -20,7 +20,7 @@ class MockAgent implements Agent {
executors = {};
modelRuntime?: (payload: unknown) => AsyncIterable<any>;
- async runner(context: RuntimeContext, state: AgentState) {
+ async runner(context: AgentRuntimeContext, state: AgentState) {
switch (context.phase) {
case 'user_input':
return { type: 'call_llm' as const, payload: { messages: state.messages } };
@@ -43,17 +43,16 @@ class MockAgent implements Agent {
// Helper function to create test context
function createTestContext(
- phase: RuntimeContext['phase'],
+ phase: AgentRuntimeContext['phase'],
payload?: any,
sessionId: string = 'test-session',
-): RuntimeContext {
+): AgentRuntimeContext {
return {
phase,
payload,
session: {
sessionId,
messageCount: 1,
- eventCount: 0,
status: 'idle',
stepCount: 0,
},
@@ -695,13 +694,12 @@ describe('AgentRuntime', () => {
});
const interruptResult = runtime.interrupt(state, 'Test interruption');
- const resumeContext: RuntimeContext = {
+ const resumeContext: AgentRuntimeContext = {
phase: 'user_input',
payload: { message: { role: 'user', content: 'Hello' } },
session: {
sessionId: 'test-session',
messageCount: 1,
- eventCount: 2, // init + interrupt
status: 'interrupted',
stepCount: 0,
},
@@ -770,7 +768,7 @@ describe('AgentRuntime', () => {
test_tool: async () => ({ result: 'success' }),
};
- async runner(context: RuntimeContext, state: AgentState) {
+ async runner(context: AgentRuntimeContext, state: AgentState) {
switch (context.phase) {
case 'user_input':
return { type: 'call_llm' as const, payload: { messages: state.messages } };
@@ -837,7 +835,7 @@ describe('AgentRuntime', () => {
it('should respect cost limits with stop action', async () => {
class CostTrackingAgent implements Agent {
- async runner(context: RuntimeContext, state: AgentState) {
+ async runner(context: AgentRuntimeContext, state: AgentState) {
return { type: 'call_llm' as const, payload: { messages: state.messages } };
}
@@ -886,7 +884,7 @@ describe('AgentRuntime', () => {
it('should handle cost limit with interrupt action', async () => {
class CostTrackingAgent implements Agent {
- async runner(context: RuntimeContext, state: AgentState) {
+ async runner(context: AgentRuntimeContext, state: AgentState) {
return { type: 'call_llm' as const, payload: { messages: state.messages } };
}
@@ -943,25 +941,27 @@ describe('AgentRuntime', () => {
};
// Mock agent behavior for different states
- agent.runner = vi.fn().mockImplementation((context: RuntimeContext, state: AgentState) => {
- switch (context.phase) {
- case 'user_input':
- return Promise.resolve({ type: 'call_llm', payload: { messages: state.messages } });
- case 'llm_result':
- const llmPayload = context.payload as { result: any; hasToolCalls: boolean };
- if (llmPayload.hasToolCalls) {
- return Promise.resolve({
- type: 'request_human_approve',
- pendingToolsCalling: llmPayload.result.tool_calls,
- });
- }
- return Promise.resolve({ type: 'finish', reason: 'completed', reasonDetail: 'Done' });
- case 'tool_result':
- return Promise.resolve({ type: 'call_llm', payload: { messages: state.messages } });
- default:
- return Promise.resolve({ type: 'finish', reason: 'completed', reasonDetail: 'Done' });
- }
- });
+ agent.runner = vi
+ .fn()
+ .mockImplementation((context: AgentRuntimeContext, state: AgentState) => {
+ switch (context.phase) {
+ case 'user_input':
+ return Promise.resolve({ type: 'call_llm', payload: { messages: state.messages } });
+ case 'llm_result':
+ const llmPayload = context.payload as { result: any; hasToolCalls: boolean };
+ if (llmPayload.hasToolCalls) {
+ return Promise.resolve({
+ type: 'request_human_approve',
+ pendingToolsCalling: llmPayload.result.tool_calls,
+ });
+ }
+ return Promise.resolve({ type: 'finish', reason: 'completed', reasonDetail: 'Done' });
+ case 'tool_result':
+ return Promise.resolve({ type: 'call_llm', payload: { messages: state.messages } });
+ default:
+ return Promise.resolve({ type: 'finish', reason: 'completed', reasonDetail: 'Done' });
+ }
+ });
async function* mockModelRuntime(payload: unknown) {
const messages = (payload as any).messages;
@@ -1043,4 +1043,534 @@ describe('AgentRuntime', () => {
);
});
});
+
+ describe('Batch Tool Execution', () => {
+ it('should execute multiple tools concurrently with call_tools_batch instruction', async () => {
+ // Agent that returns multiple tool calls
+ class BatchToolAgent implements Agent {
+ tools = {
+ tool_a: vi.fn().mockResolvedValue({ result: 'result_a' }),
+ tool_b: vi.fn().mockResolvedValue({ result: 'result_b' }),
+ tool_c: vi.fn().mockResolvedValue({ result: 'result_c' }),
+ };
+
+ async runner(context: AgentRuntimeContext, _state: AgentState) {
+ if (context.phase === 'user_input') {
+ return {
+ payload: [
+ {
+ id: 'call_a',
+ type: 'function' as const,
+ function: { name: 'tool_a', arguments: '{}' },
+ },
+ {
+ id: 'call_b',
+ type: 'function' as const,
+ function: { name: 'tool_b', arguments: '{}' },
+ },
+ {
+ id: 'call_c',
+ type: 'function' as const,
+ function: { name: 'tool_c', arguments: '{}' },
+ },
+ ],
+ type: 'call_tools_batch' as const,
+ };
+ }
+ return { type: 'finish' as const, reason: 'completed' as const };
+ }
+ }
+
+ const agent = new BatchToolAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ sessionId: 'batch-test',
+ messages: [{ role: 'user', content: 'Execute tools' }],
+ });
+
+ const result = await runtime.step(state);
+
+ // Should have executed all 3 tools
+ expect(agent.tools.tool_a).toHaveBeenCalled();
+ expect(agent.tools.tool_b).toHaveBeenCalled();
+ expect(agent.tools.tool_c).toHaveBeenCalled();
+
+ // Should have 3 tool result events
+ expect(result.events.filter((e) => e.type === 'tool_result')).toHaveLength(3);
+
+ // Should have 3 tool messages in state
+ const toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(3);
+
+ // Should have tools_batch_result phase in nextContext
+ expect(result.nextContext?.phase).toBe('tools_batch_result');
+ expect(result.nextContext?.payload).toHaveProperty('toolCount', 3);
+ });
+
+ it('should support agent returning instruction array', async () => {
+ // Agent that returns array of instructions
+ class ArrayReturnAgent implements Agent {
+ tools = {
+ tool_1: vi.fn().mockResolvedValue({ result: 'tool_1_result' }),
+ tool_2: vi.fn().mockResolvedValue({ result: 'tool_2_result' }),
+ };
+
+ async runner(context: AgentRuntimeContext, _state: AgentState) {
+ if (context.phase === 'user_input') {
+ // Return array of instructions
+ return [
+ {
+ payload: {
+ id: 'call_1',
+ type: 'function' as const,
+ function: { name: 'tool_1', arguments: '{}' },
+ },
+ type: 'call_tool' as const,
+ },
+ {
+ payload: {
+ id: 'call_2',
+ type: 'function' as const,
+ function: { name: 'tool_2', arguments: '{}' },
+ },
+ type: 'call_tool' as const,
+ },
+ ];
+ }
+ return { type: 'finish' as const, reason: 'completed' as const };
+ }
+ }
+
+ const agent = new ArrayReturnAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ sessionId: 'array-test',
+ messages: [{ role: 'user', content: 'Execute tools' }],
+ });
+
+ const result = await runtime.step(state);
+
+ // Should have executed both tools sequentially
+ expect(agent.tools.tool_1).toHaveBeenCalled();
+ expect(agent.tools.tool_2).toHaveBeenCalled();
+
+ // Should have 2 tool result events
+ expect(result.events.filter((e) => e.type === 'tool_result')).toHaveLength(2);
+
+ // Should have 2 tool messages in state
+ const toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(2);
+ });
+
+ it('should stop execution when encountering blocking status', async () => {
+ // Agent that returns mixed instructions with approval
+ class BlockingAgent implements Agent {
+ tools = {
+ safe_tool: vi.fn().mockResolvedValue({ result: 'safe_result' }),
+ };
+
+ async runner(context: AgentRuntimeContext, _state: AgentState) {
+ if (context.phase === 'user_input') {
+ // Return array: safe tool + approval request
+ return [
+ {
+ payload: {
+ id: 'call_safe',
+ type: 'function' as const,
+ function: { name: 'safe_tool', arguments: '{}' },
+ },
+ type: 'call_tool' as const,
+ },
+ {
+ pendingToolsCalling: [
+ {
+ id: 'call_danger',
+ type: 'function' as const,
+ function: { name: 'danger_tool', arguments: '{}' },
+ },
+ ],
+ type: 'request_human_approve' as const,
+ },
+ ];
+ }
+ return { type: 'finish' as const, reason: 'completed' as const };
+ }
+ }
+
+ const agent = new BlockingAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ sessionId: 'blocking-test',
+ messages: [{ role: 'user', content: 'Execute' }],
+ });
+
+ const result = await runtime.step(state);
+
+ // Safe tool should have been executed
+ expect(agent.tools.safe_tool).toHaveBeenCalled();
+
+ // Should be in waiting state (blocked by approval request)
+ expect(result.newState.status).toBe('waiting_for_human_input');
+
+ // Should have pending tool calls
+ expect(result.newState.pendingToolsCalling).toHaveLength(1);
+ expect(result.newState.pendingToolsCalling![0].function.name).toBe('danger_tool');
+
+ // Should have both tool_result and human_approve_required events
+ expect(result.events).toContainEqual(expect.objectContaining({ type: 'tool_result' }));
+ expect(result.events).toContainEqual(
+ expect.objectContaining({ type: 'human_approve_required' }),
+ );
+ });
+
+ it('should merge tool results correctly', async () => {
+ // Agent that returns batch with tools that modify usage/cost
+ class UsageTrackingAgent implements Agent {
+ tools = {
+ expensive_tool: vi.fn().mockResolvedValue({ cost: 10 }),
+ cheap_tool: vi.fn().mockResolvedValue({ cost: 1 }),
+ };
+
+ calculateUsage(
+ operationType: 'llm' | 'tool' | 'human_interaction',
+ operationResult: any,
+ previousUsage: Usage,
+ ): Usage {
+ if (operationType === 'tool') {
+ return {
+ ...previousUsage,
+ tools: {
+ ...previousUsage.tools,
+ totalCalls: previousUsage.tools.totalCalls + 1,
+ totalTimeMs: previousUsage.tools.totalTimeMs + 100,
+ },
+ };
+ }
+ return previousUsage;
+ }
+
+ async runner(context: AgentRuntimeContext, _state: AgentState) {
+ if (context.phase === 'user_input') {
+ return {
+ payload: [
+ {
+ id: 'call_expensive',
+ type: 'function' as const,
+ function: { name: 'expensive_tool', arguments: '{}' },
+ },
+ {
+ id: 'call_cheap',
+ type: 'function' as const,
+ function: { name: 'cheap_tool', arguments: '{}' },
+ },
+ ],
+ type: 'call_tools_batch' as const,
+ };
+ }
+ return { type: 'finish' as const, reason: 'completed' as const };
+ }
+ }
+
+ const agent = new UsageTrackingAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ sessionId: 'merge-test',
+ messages: [{ role: 'user', content: 'Execute' }],
+ });
+
+ const result = await runtime.step(state);
+
+ // Both tools should have been called
+ expect(agent.tools.expensive_tool).toHaveBeenCalled();
+ expect(agent.tools.cheap_tool).toHaveBeenCalled();
+
+ // Usage should be merged (2 tools called)
+ expect(result.newState.usage.tools.totalCalls).toBe(2);
+ });
+ });
+
+ describe('Edge Cases and Error Handling', () => {
+ it('should handle unknown instruction type', async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockResolvedValue({ type: 'unknown_instruction_type' as any });
+
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+
+ const result = await runtime.step(state);
+
+ expect(result.events[0].type).toBe('error');
+ expect((result.events[0] as AgentEventError).error.message).toContain(
+ 'No executor found for instruction type',
+ );
+ });
+
+ it('should handle LLM errors', async () => {
+ const agent = new MockAgent();
+ agent.modelRuntime = async function* () {
+ throw new Error('LLM API error');
+ };
+
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ messages: [{ role: 'user', content: 'test' }],
+ sessionId: 'test-session',
+ });
+
+ const result = await runtime.step(state);
+
+ expect(result.events[0].type).toBe('error');
+ expect((result.events[0] as AgentEventError).error.message).toBe('LLM API error');
+ });
+
+ it('should handle cost limit with warn action', async () => {
+ class WarnCostAgent implements Agent {
+ async runner(context: AgentRuntimeContext, state: AgentState) {
+ return { type: 'call_llm' as const, payload: { messages: state.messages } };
+ }
+
+ calculateCost(context: CostCalculationContext): Cost {
+ return {
+ calculatedAt: new Date().toISOString(),
+ currency: 'USD',
+ llm: { byModel: {}, currency: 'USD', total: 15.0 },
+ tools: { byTool: {}, currency: 'USD', total: 0 },
+ total: 15.0,
+ };
+ }
+
+ modelRuntime = async function* () {
+ yield { content: 'test' };
+ };
+ }
+
+ const agent = new WarnCostAgent();
+ const runtime = new AgentRuntime(agent);
+
+ const costLimit: CostLimit = {
+ currency: 'USD',
+ maxTotalCost: 10.0,
+ onExceeded: 'warn',
+ };
+
+ const state = AgentRuntime.createInitialState({
+ costLimit,
+ messages: [{ role: 'user', content: 'test' }],
+ sessionId: 'test-session',
+ });
+
+ const result = await runtime.step(state);
+
+ expect(result.events[0]).toMatchObject({
+ type: 'error',
+ });
+ expect((result.events[0] as AgentEventError).error.message).toContain(
+ 'Warning: Cost limit exceeded',
+ );
+ expect(result.newState.status).toBe('running');
+ });
+
+ it('should track tool cost limits', async () => {
+ class ToolCostAgent implements Agent {
+ tools = {
+ expensive_tool: vi.fn().mockResolvedValue({ result: 'done' }),
+ };
+
+ async runner(context: AgentRuntimeContext, state: AgentState) {
+ if (context.phase === 'user_input') {
+ return {
+ payload: {
+ apiName: 'expensive_tool',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: 'expensive_tool',
+ type: 'default' as const,
+ },
+ type: 'call_tool' as const,
+ };
+ }
+ return { reason: 'completed' as const, type: 'finish' as const };
+ }
+
+ calculateCost(context: CostCalculationContext): Cost {
+ return {
+ calculatedAt: new Date().toISOString(),
+ currency: 'USD',
+ llm: { byModel: {}, currency: 'USD', total: 0 },
+ tools: { byTool: {}, currency: 'USD', total: 20.0 },
+ total: 20.0,
+ };
+ }
+ }
+
+ const agent = new ToolCostAgent();
+ const runtime = new AgentRuntime(agent);
+
+ const costLimit: CostLimit = {
+ currency: 'USD',
+ maxTotalCost: 10.0,
+ onExceeded: 'stop',
+ };
+
+ const state = AgentRuntime.createInitialState({
+ costLimit,
+ messages: [{ role: 'user', content: 'test' }],
+ sessionId: 'test-session',
+ });
+
+ const result = await runtime.step(state);
+
+ expect(result.newState.status).toBe('done');
+ expect(result.events[0]).toMatchObject({
+ reason: 'cost_limit_exceeded',
+ type: 'done',
+ });
+ });
+
+ it('should merge cost statistics in batch tool execution', async () => {
+ class BatchCostAgent implements Agent {
+ tools = {
+ tool_1: vi.fn().mockResolvedValue({ result: 'result_1' }),
+ tool_2: vi.fn().mockResolvedValue({ result: 'result_2' }),
+ };
+
+ calculateCost(context: CostCalculationContext): Cost {
+ const baseCost = context.previousCost || {
+ calculatedAt: new Date().toISOString(),
+ currency: 'USD',
+ llm: { byModel: {}, currency: 'USD', total: 0 },
+ tools: { byTool: {}, currency: 'USD', total: 0 },
+ total: 0,
+ };
+
+ return {
+ ...baseCost,
+ calculatedAt: new Date().toISOString(),
+ tools: {
+ byTool: {},
+ currency: 'USD',
+ total: baseCost.tools.total + 5.0,
+ },
+ total: baseCost.total + 5.0,
+ };
+ }
+
+ async runner(context: AgentRuntimeContext, _state: AgentState) {
+ if (context.phase === 'user_input') {
+ return {
+ payload: [
+ {
+ apiName: 'tool_1',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: 'tool_1',
+ type: 'default' as const,
+ },
+ {
+ apiName: 'tool_2',
+ arguments: '{}',
+ id: 'call_2',
+ identifier: 'tool_2',
+ type: 'default' as const,
+ },
+ ],
+ type: 'call_tools_batch' as const,
+ };
+ }
+ return { reason: 'completed' as const, type: 'finish' as const };
+ }
+ }
+
+ const agent = new BatchCostAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ messages: [{ role: 'user', content: 'Execute' }],
+ sessionId: 'cost-merge-test',
+ });
+
+ const result = await runtime.step(state);
+
+ // Cost should be merged from both tools
+ expect(result.newState.cost.tools.total).toBeGreaterThan(0);
+ expect(result.newState.cost.total).toBeGreaterThan(0);
+ });
+
+ it('should merge per-tool usage statistics in batch execution', async () => {
+ class DetailedUsageAgent implements Agent {
+ tools = {
+ analytics_tool: vi.fn().mockResolvedValue({ result: 'analytics_done' }),
+ logging_tool: vi.fn().mockResolvedValue({ result: 'logged' }),
+ };
+
+ calculateUsage(
+ operationType: 'llm' | 'tool' | 'human_interaction',
+ operationResult: any,
+ previousUsage: Usage,
+ ): Usage {
+ if (operationType === 'tool') {
+ const toolName = operationResult.toolCall.apiName;
+ const newUsage = structuredClone(previousUsage);
+
+ newUsage.tools.totalCalls += 1;
+ newUsage.tools.totalTimeMs += 100;
+
+ if (newUsage.tools.byTool[toolName]) {
+ newUsage.tools.byTool[toolName].calls += 1;
+ newUsage.tools.byTool[toolName].totalTimeMs += 100;
+ } else {
+ newUsage.tools.byTool[toolName] = {
+ calls: 1,
+ errors: 0,
+ totalTimeMs: 100,
+ };
+ }
+
+ return newUsage;
+ }
+ return previousUsage;
+ }
+
+ async runner(context: AgentRuntimeContext, _state: AgentState) {
+ if (context.phase === 'user_input') {
+ return {
+ payload: [
+ {
+ apiName: 'analytics_tool',
+ arguments: '{}',
+ id: 'call_analytics',
+ identifier: 'analytics_tool',
+ type: 'default' as const,
+ },
+ {
+ apiName: 'logging_tool',
+ arguments: '{}',
+ id: 'call_logging',
+ identifier: 'logging_tool',
+ type: 'default' as const,
+ },
+ ],
+ type: 'call_tools_batch' as const,
+ };
+ }
+ return { reason: 'completed' as const, type: 'finish' as const };
+ }
+ }
+
+ const agent = new DetailedUsageAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ messages: [{ role: 'user', content: 'Execute' }],
+ sessionId: 'usage-merge-test',
+ });
+
+ const result = await runtime.step(state);
+
+ // Should have per-tool statistics
+ expect(result.newState.usage.tools.totalCalls).toBe(2);
+ expect(result.newState.usage.tools.byTool.analytics_tool).toBeDefined();
+ expect(result.newState.usage.tools.byTool.analytics_tool.calls).toBe(1);
+ expect(result.newState.usage.tools.byTool.logging_tool).toBeDefined();
+ expect(result.newState.usage.tools.byTool.logging_tool.calls).toBe(1);
+ });
+ });
});
diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.ts
index a3121032ed4..defab1b8529 100644
--- a/packages/agent-runtime/src/core/runtime.ts
+++ b/packages/agent-runtime/src/core/runtime.ts
@@ -2,11 +2,11 @@ import type {
Agent,
AgentEvent,
AgentInstruction,
+ AgentRuntimeContext,
AgentState,
Cost,
InstructionExecutor,
RuntimeConfig,
- RuntimeContext,
ToolRegistry,
ToolsCalling,
Usage,
@@ -45,8 +45,8 @@ export class AgentRuntime {
*/
async step(
state: AgentState,
- context?: RuntimeContext,
- ): Promise<{ events: AgentEvent[]; newState: AgentState; nextContext?: RuntimeContext }> {
+ context?: AgentRuntimeContext,
+ ): Promise<{ events: AgentEvent[]; newState: AgentState; nextContext?: AgentRuntimeContext }> {
try {
// Increment step count and check limits
const newState = structuredClone(state);
@@ -63,7 +63,6 @@ export class AgentRuntime {
reasonDetail: `Maximum steps exceeded: ${newState.maxSteps}`,
type: 'done' as const,
};
- newState.events = [...newState.events, finishEvent];
return {
events: [finishEvent],
@@ -75,29 +74,69 @@ export class AgentRuntime {
// Use provided context or create initial context
const runtimeContext = context || this.createInitialContext(newState);
- let result: { events: AgentEvent[]; newState: AgentState; nextContext?: RuntimeContext };
+ // Get instructions from agent runner and normalize to array
+ let rawInstructions: any;
// Handle human approved tool calls
if (runtimeContext.phase === 'human_approved_tool') {
const approvedPayload = runtimeContext.payload as { approvedToolCall: ToolsCalling };
- result = await this.executors.call_tool(
- { toolCall: approvedPayload.approvedToolCall, type: 'call_tool' },
- newState,
- );
+ rawInstructions = { payload: approvedPayload.approvedToolCall, type: 'call_tool' };
} else {
// Standard flow: Plan -> Execute
- const instruction = await this.agent.runner(runtimeContext, newState);
- result = await this.executors[instruction.type](instruction, newState);
+ rawInstructions = await this.agent.runner(runtimeContext, newState);
}
- // Ensure stepCount is preserved in the result
- result.newState.stepCount = newState.stepCount;
- result.newState.lastModified = newState.lastModified;
+ // Normalize to array
+ const instructions = Array.isArray(rawInstructions) ? rawInstructions : [rawInstructions];
+
+ // Execute all instructions sequentially
+ let currentState = newState;
+ const allEvents: AgentEvent[] = [];
+ let finalNextContext: AgentRuntimeContext | undefined = undefined;
+
+ for (const instruction of instructions) {
+ let result;
+
+ // Special handling for batch tool execution
+ if (instruction.type === 'call_tools_batch') {
+ result = await this.executeToolsBatch(instruction as any, currentState);
+ } else {
+ const executor = this.executors[instruction.type as keyof typeof this.executors];
+ if (!executor) {
+ throw new Error(`No executor found for instruction type: ${instruction.type}`);
+ }
+ result = await executor(instruction, currentState);
+ }
- // Accumulate events to state history
- result.newState.events = [...result.newState.events, ...result.events];
+ // Accumulate events
+ allEvents.push(...result.events);
+
+ // Update state
+ currentState = result.newState;
+
+ // Keep the last nextContext
+ if (result.nextContext) {
+ finalNextContext = result.nextContext;
+ }
+
+ // Stop execution if blocked
+ if (
+ currentState.status === 'waiting_for_human_input' ||
+ currentState.status === 'interrupted'
+ ) {
+ break;
+ }
+ }
- return result;
+ // Ensure stepCount and lastModified are preserved
+ currentState.stepCount = newState.stepCount;
+ currentState.lastModified = newState.lastModified;
+
+ return {
+ events: allEvents,
+ newState: currentState,
+ nextContext: finalNextContext,
+ };
} catch (error) {
const errorState = structuredClone(state);
errorState.stepCount += 1;
@@ -111,9 +150,9 @@ export class AgentRuntime {
*/
async approveToolCall(
state: AgentState,
- approvedToolCall: ToolsCalling,
- ): Promise<{ events: AgentEvent[]; newState: AgentState; nextContext?: RuntimeContext }> {
- const context: RuntimeContext = {
+ approvedToolCall: any,
+ ): Promise<{ events: AgentEvent[]; newState: AgentState; nextContext?: AgentRuntimeContext }> {
+ const context: AgentRuntimeContext = {
payload: { approvedToolCall },
phase: 'human_approved_tool',
session: this.createSessionContext(state),
@@ -157,8 +196,6 @@ export class AgentRuntime {
type: 'interrupted',
};
- newState.events = [...newState.events, interruptEvent];
-
return {
events: [interruptEvent],
newState,
@@ -174,8 +211,8 @@ export class AgentRuntime {
async resume(
state: AgentState,
reason: string = 'User resumed execution',
- context?: RuntimeContext,
- ): Promise<{ events: AgentEvent[]; newState: AgentState; nextContext?: RuntimeContext }> {
+ context?: AgentRuntimeContext,
+ ): Promise<{ events: AgentEvent[]; newState: AgentState; nextContext?: AgentRuntimeContext }> {
if (state.status !== 'interrupted') {
throw new Error('Cannot resume: state is not interrupted');
}
@@ -200,8 +237,6 @@ export class AgentRuntime {
type: 'resumed',
};
- newState.events = [...newState.events, resumeEvent];
-
// If context is provided, continue with that context
if (context) {
const result = await this.step(newState, context);
@@ -269,7 +304,6 @@ export class AgentRuntime {
cost: defaultCost,
// Default values
createdAt: now,
- events: [],
lastModified: now,
messages: [],
status: 'idle',
@@ -308,6 +342,7 @@ export class AgentRuntime {
try {
// Stream LLM response
for await (const chunk of modelRuntime(payload)) {
+ // Emit individual stream events for each chunk
events.push({ chunk, type: 'llm_stream' });
// Accumulate content and tool calls from chunks
@@ -348,7 +383,7 @@ export class AgentRuntime {
}
// Provide next context based on LLM result
- const nextContext: RuntimeContext = {
+ const nextContext: AgentRuntimeContext = {
payload: {
hasToolCalls: toolCalls.length > 0,
result: { content: assistantContent, tool_calls: toolCalls },
@@ -368,7 +403,7 @@ export class AgentRuntime {
/** Create call_tool executor */
private createCallToolExecutor(): InstructionExecutor {
return async (instruction, state) => {
- const { toolCall } = instruction as Extract<AgentInstruction, { type: 'call_tool' }>;
+ const { payload: toolCall } = instruction as Extract<AgentInstruction, { type: 'call_tool' }>;
const newState = structuredClone(state);
const events: AgentEvent[] = [];
@@ -376,19 +411,25 @@ export class AgentRuntime {
newState.status = 'running';
const tools = this.agent.tools || ({} as ToolRegistry);
- const handler = tools[toolCall.function.name];
- if (!handler) throw new Error(`Tool not found: ${toolCall.function.name}`);
- const args = JSON.parse(toolCall.function.arguments);
+ // Support both ToolsCalling (OpenAI format) and CallingToolPayload formats
+ const toolName = toolCall.apiName || toolCall.function?.name;
+ const toolArgs = toolCall.arguments || toolCall.function?.arguments;
+ const toolId = toolCall.id;
+
+ const handler = tools[toolName];
+ if (!handler) throw new Error(`Tool not found: ${toolName}`);
+
+ const args = JSON.parse(toolArgs);
const result = await handler(args);
newState.messages.push({
content: JSON.stringify(result),
role: 'tool',
- tool_call_id: toolCall.id,
+ tool_call_id: toolId,
});
- events.push({ id: toolCall.id, result, type: 'tool_result' });
+ events.push({ id: toolId, result, type: 'tool_result' });
// Update usage and cost if agent provides calculation methods
if (this.agent.calculateUsage) {
@@ -413,7 +454,7 @@ export class AgentRuntime {
}
// Provide next context for tool result
- const nextContext: RuntimeContext = {
+ const nextContext: AgentRuntimeContext = {
payload: {
result,
toolCall,
@@ -530,13 +571,106 @@ export class AgentRuntime {
// ============ Helper Methods ============
+ /**
+ * Execute multiple tool calls concurrently
+ */
+ private async executeToolsBatch(
+ instruction: { payload: any[]; type: 'call_tools_batch' },
+ baseState: AgentState,
+ ): Promise<{
+ events: AgentEvent[];
+ newState: AgentState;
+ nextContext?: AgentRuntimeContext;
+ }> {
+ const { payload: toolsCalling } = instruction;
+
+ // Execute all tools concurrently based on the same state
+ const results = await Promise.all(
+ toolsCalling.map((toolCall) =>
+ this.executors.call_tool(
+ { payload: toolCall, type: 'call_tool' } as any,
+ structuredClone(baseState), // Each tool starts from the same base state
+ ),
+ ),
+ );
+
+ // Merge results
+ return this.mergeToolResults(results, baseState);
+ }
+
+ /**
+ * Merge multiple tool execution results
+ */
+ private mergeToolResults(
+ results: Array<{
+ events: AgentEvent[];
+ newState: AgentState;
+ nextContext?: AgentRuntimeContext;
+ }>,
+ baseState: AgentState,
+ ): {
+ events: AgentEvent[];
+ newState: AgentState;
+ nextContext?: AgentRuntimeContext;
+ } {
+ const newState = structuredClone(baseState);
+ const allEvents: AgentEvent[] = [];
+
+ // Merge all tool messages in order
+ for (const result of results) {
+ // Extract tool role messages
+ const toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ newState.messages.push(...toolMessages);
+
+ // Merge events
+ allEvents.push(...result.events);
+
+ // Merge usage statistics (if available)
+ if (result.newState.usage && newState.usage) {
+ newState.usage.tools.totalCalls += result.newState.usage.tools.totalCalls;
+ newState.usage.tools.totalTimeMs += result.newState.usage.tools.totalTimeMs;
+
+ // Merge per-tool statistics
+ Object.entries(result.newState.usage.tools.byTool).forEach(([tool, stats]) => {
+ if (newState.usage.tools.byTool[tool]) {
+ newState.usage.tools.byTool[tool].calls += stats.calls;
+ newState.usage.tools.byTool[tool].totalTimeMs += stats.totalTimeMs;
+ } else {
+ newState.usage.tools.byTool[tool] = { ...stats };
+ }
+ });
+ }
+
+ // Merge cost statistics (if available)
+ if (result.newState.cost && newState.cost) {
+ newState.cost.tools.total += result.newState.cost.tools.total;
+ newState.cost.total += result.newState.cost.tools.total;
+ }
+ }
+
+ newState.lastModified = new Date().toISOString();
+
+ return {
+ events: allEvents,
+ newState,
+ nextContext: {
+ payload: {
+ toolCount: results.length,
+ toolResults: results.map((r) => r.nextContext?.payload),
+ },
+ phase: 'tools_batch_result',
+ session: this.createSessionContext(newState),
+ },
+ };
+ }
+
/**
* Handle cost limit exceeded scenario
*/
private handleCostLimitExceeded(state: AgentState): {
events: AgentEvent[];
newState: AgentState;
- nextContext?: RuntimeContext;
+ nextContext?: AgentRuntimeContext;
} {
const newState = structuredClone(state);
const costLimit = newState.costLimit!;
@@ -550,7 +684,6 @@ export class AgentRuntime {
reasonDetail: `Cost limit exceeded: ${newState.cost.total} ${newState.cost.currency} > ${costLimit.maxTotalCost} ${costLimit.currency}`,
type: 'done' as const,
};
- newState.events = [...newState.events, finishEvent];
return {
events: [finishEvent],
newState,
@@ -582,7 +715,6 @@ export class AgentRuntime {
),
type: 'error' as const,
};
- newState.events = [...newState.events, warningEvent];
return {
events: [warningEvent],
newState,
@@ -601,7 +733,6 @@ export class AgentRuntime {
*/
private createSessionContext(state: AgentState) {
return {
- eventCount: state.events.length,
messageCount: state.messages.length,
sessionId: state.sessionId,
status: state.status,
@@ -612,7 +743,7 @@ export class AgentRuntime {
/**
* Create initial context for the first step (fallback for backward compatibility)
*/
- private createInitialContext(state: AgentState): RuntimeContext {
+ private createInitialContext(state: AgentState): AgentRuntimeContext {
const lastMessage = state.messages.at(-1);
if (lastMessage?.role === 'user') {
@@ -645,9 +776,6 @@ export class AgentRuntime {
const errorEvent = { error, type: 'error' } as const;
- // Accumulate error event to state history
- errorState.events = [...errorState.events, errorEvent];
-
return {
events: [errorEvent],
newState: errorState,
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 6030089607f..a2b3e9f59b6 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -5,7 +5,8 @@ import type { Cost, CostCalculationContext, Usage } from './usage';
/**
* Runtime execution context passed to Agent runner
*/
-export interface RuntimeContext {
+export interface AgentRuntimeContext {
+ metadata?: Record<string, unknown>;
/** Phase-specific payload/context */
payload?: unknown;
/** Current execution phase */
@@ -14,12 +15,12 @@ export interface RuntimeContext {
| 'user_input'
| 'llm_result'
| 'tool_result'
+ | 'tools_batch_result'
| 'human_response'
| 'human_approved_tool'
| 'error';
- /** Session metadata */
+ /** Session */
session: {
- eventCount: number;
messageCount: number;
sessionId: string;
status: AgentState['status'];
@@ -68,22 +69,46 @@ export interface Agent {
* @param context - Current runtime context with phase and payload
* @param state - Complete agent state for reference
*/
- runner(context: RuntimeContext, state: AgentState): Promise<AgentInstruction>;
+ runner(
+ context: AgentRuntimeContext,
+ state: AgentState,
+ ): Promise<AgentInstruction | AgentInstruction[]>;
/** Optional tools registry held by the agent */
tools?: ToolRegistry;
}
+export interface CallLLMPayload {
+ isFirstMessage?: boolean;
+ messages: any[];
+ model: string;
+ provider: string;
+ tools: any[];
+}
+
+export interface CallingToolPayload {
+ apiName: string;
+ arguments: string;
+ id: string;
+ identifier: string;
+ type: 'mcp' | 'default' | 'markdown' | 'standalone';
+}
+
export interface AgentInstructionCallLlm {
- payload: unknown;
+ payload: any;
type: 'call_llm';
}
export interface AgentInstructionCallTool {
- toolCall: ToolsCalling;
+ payload: any;
type: 'call_tool';
}
+export interface AgentInstructionCallToolsBatch {
+ payload: any[];
+ type: 'call_tools_batch';
+}
+
export interface AgentInstructionRequestHumanPrompt {
metadata?: Record<string, unknown>;
prompt: string;
@@ -119,6 +144,7 @@ export interface AgentInstructionFinish {
export type AgentInstruction =
| AgentInstructionCallLlm
| AgentInstructionCallTool
+ | AgentInstructionCallToolsBatch
| AgentInstructionRequestHumanPrompt
| AgentInstructionRequestHumanSelect
| AgentInstructionRequestHumanApprove
diff --git a/packages/agent-runtime/src/types/runtime.ts b/packages/agent-runtime/src/types/runtime.ts
index d86cdf01abd..371c41d2b2c 100644
--- a/packages/agent-runtime/src/types/runtime.ts
+++ b/packages/agent-runtime/src/types/runtime.ts
@@ -1,5 +1,5 @@
import type { AgentEvent } from './event';
-import { AgentInstruction, RuntimeContext } from './instruction';
+import { AgentInstruction, AgentRuntimeContext } from './instruction';
import { AgentState } from './state';
export type InstructionExecutor = (
@@ -9,7 +9,7 @@ export type InstructionExecutor = (
events: AgentEvent[];
newState: AgentState;
/** Next context to pass to Agent runner (if execution should continue) */
- nextContext?: RuntimeContext;
+ nextContext?: AgentRuntimeContext;
}>;
export interface RuntimeConfig {
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index d479552827b..e1c23f6f052 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -1,5 +1,4 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
-import type { AgentEvent } from './event';
import type { Cost, CostLimit, Usage } from './usage';
/**
@@ -13,15 +12,9 @@ export interface AgentState {
// --- Core Context ---
messages: any[];
+ tools?: any[];
systemRole?: string;
- // --- Event History ---
- /**
- * Complete event trace for this agent session.
- * Useful for debugging, auditing, and state replay.
- */
- events: AgentEvent[];
-
// --- Execution Tracking ---
/**
* Number of execution steps in this session.
diff --git a/packages/agent-runtime/vitest.config.mts b/packages/agent-runtime/vitest.config.mts
index e8dbea7a7c0..2102f31cba0 100644
--- a/packages/agent-runtime/vitest.config.mts
+++ b/packages/agent-runtime/vitest.config.mts
@@ -3,6 +3,20 @@ import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
coverage: {
+ exclude: [
+ // Default excludes
+ 'coverage/**',
+ 'dist/**',
+ '**/node_modules/**',
+ '**/*.d.ts',
+ '**/*.config.*',
+ '**/mockData',
+ '**/.{git,cache,output,temp}/**',
+ // Custom excludes
+ '**/examples/**', // Example files
+ '**/index.ts', // Export-only files
+ '**/types/**', // Type definition files
+ ],
reporter: ['text', 'json', 'lcov', 'text-summary'],
},
environment: 'happy-dom',
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index e669250c2f0..b76c829978e 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -66,7 +66,7 @@ type Routers =
},
) => RouterInstance[] | Promise<RouterInstance[]>);
-interface CreateRouterRuntimeOptions<T extends Record<string, any> = any> {
+export interface CreateRouterRuntimeOptions<T extends Record<string, any> = any> {
apiKey?: string;
chatCompletion?: {
excludeUsage?: boolean;
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index c0c12d9d10a..234ea88205f 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -67,7 +67,7 @@ export interface CustomClientOptions<T extends Record<string, any> = any> {
createClient?: (options: ConstructorOptions<T>) => any;
}
-interface OpenAICompatibleFactoryOptions<T extends Record<string, any> = any> {
+export interface OpenAICompatibleFactoryOptions<T extends Record<string, any> = any> {
apiKey?: string;
baseURL?: string;
chatCompletion?: {
diff --git a/packages/model-runtime/src/providerTestUtils.ts b/packages/model-runtime/src/providerTestUtils.ts
index 9a16fcea12a..cd045890217 100644
--- a/packages/model-runtime/src/providerTestUtils.ts
+++ b/packages/model-runtime/src/providerTestUtils.ts
@@ -14,6 +14,7 @@ interface TesstProviderParams {
provider: string;
test?: {
skipAPICall?: boolean;
+ skipErrorHandle?: boolean;
};
}
@@ -109,165 +110,167 @@ export const testProvider = ({
});
}
- describe('Error', () => {
- it('should return ProviderBizError with an openai error response when OpenAI.APIError is thrown', async () => {
- // Arrange
- const apiError = new OpenAI.APIError(
- 400,
- {
- error: {
- message: 'Bad Request',
- },
- status: 400,
- },
- 'Error message',
- {},
- );
-
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
-
- // Act
- try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: chatModel,
- temperature: 0,
- });
- } catch (e) {
- expect(e).toEqual({
- endpoint: defaultBaseURL,
- error: {
- error: { message: 'Bad Request' },
+ if (!test.skipErrorHandle) {
+ describe('Error', () => {
+ it('should return ProviderBizError with an openai error response when OpenAI.APIError is thrown', async () => {
+ // Arrange
+ const apiError = new OpenAI.APIError(
+ 400,
+ {
+ error: {
+ message: 'Bad Request',
+ },
status: 400,
},
- errorType: bizErrorType,
- provider,
- });
- }
- });
-
- it('should throw AgentRuntimeError with InvalidProviderAPIKey if no apiKey is provided', async () => {
- try {
- new Runtime({});
- } catch (e) {
- expect(e).toEqual({ errorType: invalidErrorType });
- }
- });
-
- it('should return ProviderBizError with the cause when OpenAI.APIError is thrown with cause', async () => {
- // Arrange
- const errorInfo = {
- cause: {
- message: 'api is undefined',
- },
- };
- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
+ 'Error message',
+ {},
+ );
+
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
+
+ // Act
+ try {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: chatModel,
+ temperature: 0,
+ });
+ } catch (e) {
+ expect(e).toEqual({
+ endpoint: defaultBaseURL,
+ error: {
+ error: { message: 'Bad Request' },
+ status: 400,
+ },
+ errorType: bizErrorType,
+ provider,
+ });
+ }
+ });
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
+ it('should throw AgentRuntimeError with InvalidProviderAPIKey if no apiKey is provided', async () => {
+ try {
+ new Runtime({});
+ } catch (e) {
+ expect(e).toEqual({ errorType: invalidErrorType });
+ }
+ });
- // Act
- try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: chatModel,
- temperature: 0,
- });
- } catch (e) {
- expect(e).toEqual({
- endpoint: defaultBaseURL,
- error: {
- cause: { message: 'api is undefined' },
+ it('should return ProviderBizError with the cause when OpenAI.APIError is thrown with cause', async () => {
+ // Arrange
+ const errorInfo = {
+ cause: {
+ message: 'api is undefined',
},
- errorType: bizErrorType,
- provider,
- });
- }
- });
-
- it('should return ProviderBizError with an cause response with desensitize Url', async () => {
- // Arrange
- const errorInfo = {
- cause: { message: 'api is undefined' },
- };
- const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
-
- instance = new Runtime({
- apiKey: 'test',
-
- baseURL: 'https://api.abc.com/v1',
+ };
+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
+
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
+
+ // Act
+ try {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: chatModel,
+ temperature: 0,
+ });
+ } catch (e) {
+ expect(e).toEqual({
+ endpoint: defaultBaseURL,
+ error: {
+ cause: { message: 'api is undefined' },
+ },
+ errorType: bizErrorType,
+ provider,
+ });
+ }
});
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
-
- // Act
- try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: chatModel,
- temperature: 0,
- });
- } catch (e) {
- expect(e).toEqual({
- endpoint: 'https://api.***.com/v1',
- error: {
- cause: { message: 'api is undefined' },
- },
- errorType: bizErrorType,
- provider,
- });
- }
- });
+ it('should return ProviderBizError with an cause response with desensitize Url', async () => {
+ // Arrange
+ const errorInfo = {
+ cause: { message: 'api is undefined' },
+ };
+ const apiError = new OpenAI.APIError(400, errorInfo, 'module error', {});
- it(`should throw an InvalidAPIKey error type on 401 status code`, async () => {
- // Mock the API call to simulate a 401 error
- const error = new Error('Unauthorized') as any;
- error.status = 401;
- vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
+ instance = new Runtime({
+ apiKey: 'test',
- try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: chatModel,
- temperature: 0,
- });
- } catch (e) {
- // Expect the chat method to throw an error with InvalidHunyuanAPIKey
- expect(e).toEqual({
- endpoint: defaultBaseURL,
- error: error,
- errorType: invalidErrorType,
- provider,
+ baseURL: 'https://api.abc.com/v1',
});
- }
- });
- it('should return AgentRuntimeError for non-OpenAI errors', async () => {
- // Arrange
- const genericError = new Error('Generic Error');
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);
+
+ // Act
+ try {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: chatModel,
+ temperature: 0,
+ });
+ } catch (e) {
+ expect(e).toEqual({
+ endpoint: 'https://api.***.com/v1',
+ error: {
+ cause: { message: 'api is undefined' },
+ },
+ errorType: bizErrorType,
+ provider,
+ });
+ }
+ });
- vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
+ it(`should throw an InvalidAPIKey error type on 401 status code`, async () => {
+ // Mock the API call to simulate a 401 error
+ const error = new Error('Unauthorized') as any;
+ error.status = 401;
+ vi.mocked(instance['client'].chat.completions.create).mockRejectedValue(error);
+
+ try {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: chatModel,
+ temperature: 0,
+ });
+ } catch (e) {
+ // Expect the chat method to throw an error with InvalidHunyuanAPIKey
+ expect(e).toEqual({
+ endpoint: defaultBaseURL,
+ error: error,
+ errorType: invalidErrorType,
+ provider,
+ });
+ }
+ });
- // Act
- try {
- await instance.chat({
- messages: [{ content: 'Hello', role: 'user' }],
- model: chatModel,
- temperature: 0,
- });
- } catch (e) {
- expect(e).toEqual({
- endpoint: defaultBaseURL,
- error: {
- cause: genericError.cause,
- message: genericError.message,
- name: genericError.name,
- },
- errorType: 'AgentRuntimeError',
- provider,
- });
- }
+ it('should return AgentRuntimeError for non-OpenAI errors', async () => {
+ // Arrange
+ const genericError = new Error('Generic Error');
+
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(genericError);
+
+ // Act
+ try {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: chatModel,
+ temperature: 0,
+ });
+ } catch (e) {
+ expect(e).toEqual({
+ endpoint: defaultBaseURL,
+ error: {
+ cause: genericError.cause,
+ message: genericError.message,
+ name: genericError.name,
+ },
+ errorType: 'AgentRuntimeError',
+ provider,
+ });
+ }
+ });
});
- });
+ }
describe('DEBUG', () => {
it(`should call debugStream and return StreamingTextResponse when ${chatDebugEnv} is 1`, async () => {
diff --git a/packages/model-runtime/src/providers/ai302/index.test.ts b/packages/model-runtime/src/providers/ai302/index.test.ts
new file mode 100644
index 00000000000..78811e33c76
--- /dev/null
+++ b/packages/model-runtime/src/providers/ai302/index.test.ts
@@ -0,0 +1,60 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { testProvider } from '../../providerTestUtils';
+import { AgentRuntimeErrorType } from '../../types/error';
+import { Lobe302AI, params } from './index';
+
+testProvider({
+ Runtime: Lobe302AI,
+ provider: ModelProvider.Ai302,
+ defaultBaseURL: 'https://api.302.ai/v1',
+ chatDebugEnv: 'DEBUG_AI302_CHAT_COMPLETION',
+ chatModel: 'gpt-3.5-turbo',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
+
+describe('Lobe302AI - params', () => {
+ it('should have correct baseURL', () => {
+ expect(params.baseURL).toBe('https://api.302.ai/v1');
+ expect(params.provider).toBe(ModelProvider.Ai302);
+ });
+
+ describe('handleError', () => {
+ it('should handle 401 error as InvalidProviderAPIKey', () => {
+ const error = new Response('Unauthorized', { status: 401 });
+ const result = params.chatCompletion?.handleError?.(error);
+
+ expect(result?.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ expect(result?.error).toBe(401);
+ });
+
+ it('should handle error with status property', () => {
+ const error = { status: 401, message: 'Unauthorized' };
+ const result = params.chatCompletion?.handleError?.(error);
+
+ expect(result?.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ });
+
+ it('should return error for non-401 status', () => {
+ const error = new Response('Bad Request', { status: 400 });
+ const result = params.chatCompletion?.handleError?.(error);
+
+ expect(result?.error).toBe(error);
+ expect(result?.errorType).toBeUndefined();
+ });
+
+ it('should return error for generic errors', () => {
+ const error = new Error('Network error');
+ const result = params.chatCompletion?.handleError?.(error);
+
+ expect(result?.error).toBe(error);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/ai302/index.ts b/packages/model-runtime/src/providers/ai302/index.ts
index 6e66d45640e..0007893a8b8 100644
--- a/packages/model-runtime/src/providers/ai302/index.ts
+++ b/packages/model-runtime/src/providers/ai302/index.ts
@@ -1,6 +1,9 @@
import { ModelProvider } from 'model-bank';
-import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import {
+ OpenAICompatibleFactoryOptions,
+ createOpenAICompatibleRuntime,
+} from '../../core/openaiCompatibleFactory';
import { ChatCompletionErrorPayload } from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
import { processMultiProviderModelList } from '../../utils/modelParse';
@@ -9,7 +12,7 @@ export interface Ai302ModelCard {
id: string;
}
-export const Lobe302AI = createOpenAICompatibleRuntime({
+export const params = {
baseURL: 'https://api.302.ai/v1',
chatCompletion: {
handleError: (error: any): Omit<ChatCompletionErrorPayload, 'provider'> | undefined => {
@@ -32,7 +35,7 @@ export const Lobe302AI = createOpenAICompatibleRuntime({
},
},
debug: {
- chatCompletion: () => process.env.DEBUG_SILICONCLOUD_CHAT_COMPLETION === '1',
+ chatCompletion: () => process.env.DEBUG_AI302_CHAT_COMPLETION === '1',
},
errorType: {
bizError: AgentRuntimeErrorType.ProviderBizError,
@@ -45,4 +48,6 @@ export const Lobe302AI = createOpenAICompatibleRuntime({
return processMultiProviderModelList(modelList, 'ai302');
},
provider: ModelProvider.Ai302,
-});
+} satisfies OpenAICompatibleFactoryOptions;
+
+export const Lobe302AI = createOpenAICompatibleRuntime(params);
diff --git a/packages/model-runtime/src/providers/ai360/index.test.ts b/packages/model-runtime/src/providers/ai360/index.test.ts
index bbfcb18338f..9add6df2d0b 100644
--- a/packages/model-runtime/src/providers/ai360/index.test.ts
+++ b/packages/model-runtime/src/providers/ai360/index.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { testProvider } from '../../providerTestUtils';
import { LobeAi360AI } from './index';
@@ -10,4 +11,70 @@ testProvider({
defaultBaseURL: 'https://api.360.cn/v1',
chatDebugEnv: 'DEBUG_AI360_CHAT_COMPLETION',
chatModel: 'deepseek-r1',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
+
+describe('LobeAi360AI - custom features', () => {
+ let instance: InstanceType<typeof LobeAi360AI>;
+
+ beforeEach(() => {
+ instance = new LobeAi360AI({ apiKey: 'test_api_key' });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ describe('handlePayload', () => {
+ it('should add web_search tool when enabledSearch is true', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: '360gpt-pro',
+ enabledSearch: true,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.tools).toBeDefined();
+ expect(calledPayload.tools?.some((tool: any) => tool.type === 'web_search')).toBe(true);
+ });
+
+ it('should disable stream when tools are present', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: '360gpt-pro',
+ tools: [{ type: 'function', function: { name: 'test' } }],
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.stream).toBe(false);
+ });
+
+ it('should enable stream when no tools', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: '360gpt-pro',
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.stream).not.toBe(false);
+ });
+
+ it('should merge tools with web_search when enabledSearch is true', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: '360gpt-pro',
+ enabledSearch: true,
+ tools: [{ type: 'function', function: { name: 'existing_tool' } }],
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.tools).toHaveLength(2);
+ expect(calledPayload.tools?.some((tool: any) => tool.type === 'function')).toBe(true);
+ expect(calledPayload.tools?.some((tool: any) => tool.type === 'web_search')).toBe(true);
+ });
+ });
});
diff --git a/packages/model-runtime/src/providers/ai360/index.ts b/packages/model-runtime/src/providers/ai360/index.ts
index e43c111e0c6..8c2b8eab563 100644
--- a/packages/model-runtime/src/providers/ai360/index.ts
+++ b/packages/model-runtime/src/providers/ai360/index.ts
@@ -1,7 +1,10 @@
import type { ChatModelCard } from '@lobechat/types';
import { ModelProvider } from 'model-bank';
-import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import {
+ OpenAICompatibleFactoryOptions,
+ createOpenAICompatibleRuntime,
+} from '../../core/openaiCompatibleFactory';
export interface Ai360ModelCard {
id: string;
@@ -9,7 +12,7 @@ export interface Ai360ModelCard {
total_tokens: number;
}
-export const LobeAi360AI = createOpenAICompatibleRuntime({
+export const params = {
baseURL: 'https://api.360.cn/v1',
chatCompletion: {
handlePayload: (payload) => {
@@ -68,4 +71,6 @@ export const LobeAi360AI = createOpenAICompatibleRuntime({
.filter(Boolean) as ChatModelCard[];
},
provider: ModelProvider.Ai360,
-});
+} satisfies OpenAICompatibleFactoryOptions;
+
+export const LobeAi360AI = createOpenAICompatibleRuntime(params);
diff --git a/packages/model-runtime/src/providers/aihubmix/index.test.ts b/packages/model-runtime/src/providers/aihubmix/index.test.ts
new file mode 100644
index 00000000000..7a5c5de0070
--- /dev/null
+++ b/packages/model-runtime/src/providers/aihubmix/index.test.ts
@@ -0,0 +1,73 @@
+// @vitest-environment edge-runtime
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LobeAiHubMixAI } from './index';
+
+describe('LobeAiHubMixAI', () => {
+ let instance: InstanceType<typeof LobeAiHubMixAI>;
+
+ beforeEach(() => {
+ instance = new LobeAiHubMixAI({ apiKey: 'test_api_key' });
+ });
+
+ describe('constructor', () => {
+ it('should initialize with correct provider', () => {
+ expect(instance).toBeDefined();
+ });
+
+ it('should set APP-Code header', () => {
+ // The RouterRuntime-based providers have different structure
+ // We just verify the instance is created correctly
+ expect(instance).toBeInstanceOf(LobeAiHubMixAI);
+ });
+ });
+
+ describe('chat', () => {
+ it('should support chat method', async () => {
+ vi.spyOn(instance as any, 'getRuntimeByModel').mockResolvedValue({
+ chat: vi.fn().mockResolvedValue(new Response()),
+ });
+
+ const payload = {
+ messages: [{ content: 'Hello', role: 'user' as const }],
+ model: 'gpt-4',
+ temperature: 0.7,
+ };
+
+ const result = await instance.chat(payload);
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('models', () => {
+ it('should return empty array on error', async () => {
+ // Mock the client to throw an error
+ const mockClient = {
+ models: {
+ list: vi.fn().mockRejectedValue(new Error('API Error')),
+ },
+ };
+
+ vi.spyOn(instance as any, 'getRuntimeByModel').mockResolvedValue({
+ models: async () => {
+ try {
+ await mockClient.models.list();
+ } catch (error) {
+ console.warn(
+ 'Failed to fetch AiHubMix models. Please ensure your AiHubMix API key is valid:',
+ error,
+ );
+ return [];
+ }
+ },
+ });
+
+ // The models method should return empty array on error
+ const models = await (instance as any)
+ .getRuntimeByModel('test-model')
+ .then((r: any) => r.models());
+ expect(models).toEqual([]);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/aihubmix/index.ts b/packages/model-runtime/src/providers/aihubmix/index.ts
index ecf2a4d49ec..49351df9748 100644
--- a/packages/model-runtime/src/providers/aihubmix/index.ts
+++ b/packages/model-runtime/src/providers/aihubmix/index.ts
@@ -3,7 +3,7 @@ import urlJoin from 'url-join';
import { responsesAPIModels } from '../../const/models';
import { createRouterRuntime } from '../../core/RouterRuntime';
-import { ChatStreamPayload } from '../../types/chat';
+import { CreateRouterRuntimeOptions } from '../../core/RouterRuntime/createRuntime';
import { detectModelProvider, processMultiProviderModelList } from '../../utils/modelParse';
export interface AiHubMixModelCard {
@@ -15,8 +15,7 @@ export interface AiHubMixModelCard {
const baseURL = 'https://aihubmix.com';
-
-export const LobeAiHubMixAI = createRouterRuntime({
+export const params: CreateRouterRuntimeOptions = {
debug: {
chatCompletion: () => process.env.DEBUG_AIHUBMIX_CHAT_COMPLETION === '1',
},
@@ -65,13 +64,11 @@ export const LobeAiHubMixAI = createRouterRuntime({
options: {
baseURL: urlJoin(baseURL, '/v1'),
chatCompletion: {
- useResponseModels: [
- ...Array.from(responsesAPIModels),
- /gpt-\d(?!\d)/,
- /^o\d/,
- ],
+ useResponseModels: [...Array.from(responsesAPIModels), /gpt-\d(?!\d)/, /^o\d/],
},
},
},
],
-});
+};
+
+export const LobeAiHubMixAI = createRouterRuntime(params);
diff --git a/packages/model-runtime/src/providers/azureai/index.test.ts b/packages/model-runtime/src/providers/azureai/index.test.ts
new file mode 100644
index 00000000000..1149a466814
--- /dev/null
+++ b/packages/model-runtime/src/providers/azureai/index.test.ts
@@ -0,0 +1,102 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentRuntimeErrorType } from '../../types/error';
+import { LobeAzureAI } from './index';
+
+describe('LobeAzureAI', () => {
+ describe('constructor', () => {
+ it('should throw error when apiKey is missing', () => {
+ expect(() => new LobeAzureAI({ baseURL: 'https://test.azure.com' })).toThrow();
+ });
+
+ it('should throw error when baseURL is missing', () => {
+ expect(() => new LobeAzureAI({ apiKey: 'test-key' })).toThrow();
+ });
+
+ it('should throw InvalidProviderAPIKey error when both apiKey and baseURL are missing', () => {
+ try {
+ new LobeAzureAI();
+ } catch (error: any) {
+ expect(error.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ }
+ });
+
+ it('should initialize successfully with valid params', () => {
+ const instance = new LobeAzureAI({
+ apiKey: 'test-key',
+ baseURL: 'https://test.cognitiveservices.azure.com/openai',
+ });
+
+ expect(instance).toBeDefined();
+ expect(instance.baseURL).toBe('https://test.cognitiveservices.azure.com/openai');
+ });
+ });
+
+ describe('chat', () => {
+ let instance: LobeAzureAI;
+
+ beforeEach(() => {
+ instance = new LobeAzureAI({
+ apiKey: 'test-key',
+ baseURL: 'https://test.cognitiveservices.azure.com/openai',
+ });
+ });
+
+ it('should handle non-streaming responses', async () => {
+ const mockResponse = {
+ choices: [
+ {
+ message: {
+ content: 'Hello, how can I help you?',
+ role: 'assistant',
+ },
+ },
+ ],
+ model: 'gpt-4',
+ };
+
+ vi.spyOn(instance.client.path('/chat/completions'), 'post').mockResolvedValue({
+ body: mockResponse,
+ } as any);
+
+ const result = await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ stream: false,
+ });
+
+ expect(result).toBeDefined();
+ });
+
+ it('should handle generic errors', async () => {
+ const mockError = new Error('Network error');
+
+ vi.spyOn(instance.client.path('/chat/completions'), 'post').mockRejectedValue(mockError);
+
+ try {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ });
+ } catch (error: any) {
+ expect(error.errorType).toBe(AgentRuntimeErrorType.AgentRuntimeError);
+ }
+ });
+ });
+
+ describe('maskSensitiveUrl', () => {
+ it('should mask subdomain in Azure URL', () => {
+ const instance = new LobeAzureAI({
+ apiKey: 'test-key',
+ baseURL: 'https://myresource.cognitiveservices.azure.com/openai',
+ });
+
+ const masked = (instance as any).maskSensitiveUrl(
+ 'https://myresource.cognitiveservices.azure.com/openai',
+ );
+ expect(masked).toBe('https://***.cognitiveservices.azure.com/openai');
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/baichuan/index.test.ts b/packages/model-runtime/src/providers/baichuan/index.test.ts
index 5d4a46ad5ea..6458ff07b98 100644
--- a/packages/model-runtime/src/providers/baichuan/index.test.ts
+++ b/packages/model-runtime/src/providers/baichuan/index.test.ts
@@ -12,8 +12,11 @@ testProvider({
defaultBaseURL: 'https://api.baichuan-ai.com/v1',
chatDebugEnv: 'DEBUG_BAICHUAN_CHAT_COMPLETION',
chatModel: 'hunyuan-lite',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
test: {
skipAPICall: true,
+ skipErrorHandle: true,
},
});
@@ -67,4 +70,69 @@ describe('specific LobeBaichuanAI tests', () => {
);
expect(result).toBeInstanceOf(Response);
});
+
+ describe('handlePayload - custom features', () => {
+ it('should add web_search tool when enabledSearch is true', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Baichuan3-Turbo',
+ enabledSearch: true,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.tools).toBeDefined();
+ expect(calledPayload.tools?.some((tool: any) => tool.type === 'web_search')).toBe(true);
+ expect(
+ calledPayload.tools?.find((tool: any) => tool.type === 'web_search')?.web_search?.enable,
+ ).toBe(true);
+ });
+
+ it('should use default search_mode performance_first', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Baichuan3-Turbo',
+ enabledSearch: true,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ const webSearchTool = calledPayload.tools?.find((tool: any) => tool.type === 'web_search');
+ expect(webSearchTool?.web_search?.search_mode).toBe('performance_first');
+ });
+
+ it('should normalize temperature - 0 stays 0', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Baichuan3-Turbo',
+ temperature: 0,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.temperature).toBe(0);
+ });
+
+ it('should normalize temperature by halving it', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Baichuan3-Turbo',
+ temperature: 0.5,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.temperature).toBe(0.25);
+ });
+
+ it('should merge tools with web_search when enabledSearch is true', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Baichuan3-Turbo',
+ enabledSearch: true,
+ tools: [{ type: 'function', function: { name: 'existing_tool' } }],
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.tools).toHaveLength(2);
+ expect(calledPayload.tools?.some((tool: any) => tool.type === 'function')).toBe(true);
+ expect(calledPayload.tools?.some((tool: any) => tool.type === 'web_search')).toBe(true);
+ });
+ });
});
diff --git a/packages/model-runtime/src/providers/baichuan/index.ts b/packages/model-runtime/src/providers/baichuan/index.ts
index 43726c3d493..f59d094cb68 100644
--- a/packages/model-runtime/src/providers/baichuan/index.ts
+++ b/packages/model-runtime/src/providers/baichuan/index.ts
@@ -1,7 +1,10 @@
import type { ChatModelCard } from '@lobechat/types';
import { ModelProvider } from 'model-bank';
-import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import {
+ OpenAICompatibleFactoryOptions,
+ createOpenAICompatibleRuntime,
+} from '../../core/openaiCompatibleFactory';
import { resolveParameters } from '../../core/parameterResolver';
import { ChatStreamPayload } from '../../types';
@@ -13,7 +16,7 @@ export interface BaichuanModelCard {
model_show_name: string;
}
-export const LobeBaichuanAI = createOpenAICompatibleRuntime({
+export const params = {
baseURL: 'https://api.baichuan-ai.com/v1',
chatCompletion: {
handlePayload: (payload: ChatStreamPayload) => {
@@ -71,4 +74,6 @@ export const LobeBaichuanAI = createOpenAICompatibleRuntime({
.filter(Boolean) as ChatModelCard[];
},
provider: ModelProvider.Baichuan,
-});
+} satisfies OpenAICompatibleFactoryOptions;
+
+export const LobeBaichuanAI = createOpenAICompatibleRuntime(params);
diff --git a/packages/model-runtime/src/providers/cerebras/index.test.ts b/packages/model-runtime/src/providers/cerebras/index.test.ts
new file mode 100644
index 00000000000..4ea38db7a0b
--- /dev/null
+++ b/packages/model-runtime/src/providers/cerebras/index.test.ts
@@ -0,0 +1,47 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { testProvider } from '../../providerTestUtils';
+import { LobeCerebrasAI } from './index';
+
+testProvider({
+ Runtime: LobeCerebrasAI,
+ provider: ModelProvider.Cerebras,
+ defaultBaseURL: 'https://api.cerebras.ai/v1',
+ chatDebugEnv: 'DEBUG_CEREBRAS_CHAT_COMPLETION',
+ chatModel: 'llama3.1-8b',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
+
+describe('LobeCerebrasAI - custom features', () => {
+ let instance: InstanceType<typeof LobeCerebrasAI>;
+
+ beforeEach(() => {
+ instance = new LobeCerebrasAI({ apiKey: 'test_api_key' });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ describe('handlePayload', () => {
+ it('should remove frequency_penalty and presence_penalty from payload', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'llama3.1-8b',
+ frequency_penalty: 0.5,
+ presence_penalty: 0.5,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.frequency_penalty).toBeUndefined();
+ expect(calledPayload.presence_penalty).toBeUndefined();
+ expect(calledPayload.model).toBe('llama3.1-8b');
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/higress/index.test.ts b/packages/model-runtime/src/providers/higress/index.test.ts
new file mode 100644
index 00000000000..751dae76ea1
--- /dev/null
+++ b/packages/model-runtime/src/providers/higress/index.test.ts
@@ -0,0 +1,142 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { testProvider } from '../../providerTestUtils';
+import { LobeHigressAI, params } from './index';
+
+testProvider({
+ Runtime: LobeHigressAI,
+ provider: ModelProvider.Higress,
+ defaultBaseURL: 'https://api.openai.com/v1',
+ chatDebugEnv: 'DEBUG_HIGRESS_CHAT_COMPLETION',
+ chatModel: 'gpt-3.5-turbo',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
+
+describe('LobeHigressAI - params', () => {
+ it('should have correct baseURL default', () => {
+ expect(params.provider).toBe(ModelProvider.Higress);
+ });
+
+ it('should have constructorOptions with default headers', () => {
+ expect(params.constructorOptions?.defaultHeaders).toHaveProperty('HTTP-Referer');
+ expect(params.constructorOptions?.defaultHeaders).toHaveProperty('X-Title');
+ expect(params.constructorOptions?.defaultHeaders).toHaveProperty('x-Request-Id');
+ });
+
+ describe('models function', () => {
+ it('should process model list correctly', async () => {
+ const mockClient = {
+ models: {
+ list: vi.fn().mockResolvedValue({
+ data: [
+ {
+ id: 'gpt-4',
+ name: 'GPT-4',
+ description: 'GPT-4 with vision and function calling support',
+ context_length: 8192,
+ top_provider: {
+ max_completion_tokens: 4096,
+ },
+ },
+ {
+ id: 'claude-3-opus',
+ name: 'Claude 3 Opus',
+ description: 'Claude 3 Opus supports multimodal and reasoning',
+ context_length: 200000,
+ top_provider: {
+ max_completion_tokens: 4096,
+ },
+ },
+ ],
+ }),
+ },
+ };
+
+ const models = await params.models!({ client: mockClient as any });
+
+ expect(models.length).toBeGreaterThan(0);
+ expect(models[0]).toHaveProperty('id');
+ expect(models[0]).toHaveProperty('displayName');
+ expect(models[0]).toHaveProperty('contextWindowTokens');
+ expect(models[0]).toHaveProperty('functionCall');
+ expect(models[0]).toHaveProperty('vision');
+ expect(models[0]).toHaveProperty('reasoning');
+ });
+
+ it('should detect functionCall from description', async () => {
+ const mockClient = {
+ models: {
+ list: vi.fn().mockResolvedValue({
+ data: [
+ {
+ id: 'test-model',
+ name: 'Test Model',
+ description: 'This model supports function calling',
+ context_length: 8192,
+ top_provider: {
+ max_completion_tokens: 4096,
+ },
+ },
+ ],
+ }),
+ },
+ };
+
+ const models = await params.models!({ client: mockClient as any });
+ expect(models[0].functionCall).toBe(true);
+ });
+
+ it('should detect vision from description', async () => {
+ const mockClient = {
+ models: {
+ list: vi.fn().mockResolvedValue({
+ data: [
+ {
+ id: 'test-model',
+ name: 'Test Model',
+ description: 'This model supports vision capabilities',
+ context_length: 8192,
+ top_provider: {
+ max_completion_tokens: 4096,
+ },
+ },
+ ],
+ }),
+ },
+ };
+
+ const models = await params.models!({ client: mockClient as any });
+ expect(models[0].vision).toBe(true);
+ });
+
+ it('should detect reasoning from description', async () => {
+ const mockClient = {
+ models: {
+ list: vi.fn().mockResolvedValue({
+ data: [
+ {
+ id: 'test-model',
+ name: 'Test Model',
+ description: 'This model supports reasoning',
+ context_length: 8192,
+ top_provider: {
+ max_completion_tokens: 4096,
+ },
+ },
+ ],
+ }),
+ },
+ };
+
+ const models = await params.models!({ client: mockClient as any });
+ expect(models[0].reasoning).toBe(true);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/higress/index.ts b/packages/model-runtime/src/providers/higress/index.ts
index 6508fab15ba..4fbb64bb925 100644
--- a/packages/model-runtime/src/providers/higress/index.ts
+++ b/packages/model-runtime/src/providers/higress/index.ts
@@ -2,7 +2,10 @@ import type { ChatModelCard } from '@lobechat/types';
import uniqueId from 'lodash-es/uniqueId';
import { ModelProvider } from 'model-bank';
-import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import {
+ OpenAICompatibleFactoryOptions,
+ createOpenAICompatibleRuntime,
+} from '../../core/openaiCompatibleFactory';
export interface HigressModelCard {
context_length: number;
@@ -14,7 +17,7 @@ export interface HigressModelCard {
};
}
-export const LobeHigressAI = createOpenAICompatibleRuntime({
+export const params = {
constructorOptions: {
defaultHeaders: {
'HTTP-Referer': 'https://lobehub.com',
@@ -62,4 +65,6 @@ export const LobeHigressAI = createOpenAICompatibleRuntime({
.filter(Boolean) as ChatModelCard[];
},
provider: ModelProvider.Higress,
-});
+} satisfies OpenAICompatibleFactoryOptions;
+
+export const LobeHigressAI = createOpenAICompatibleRuntime(params);
diff --git a/packages/model-runtime/src/providers/infiniai/index.test.ts b/packages/model-runtime/src/providers/infiniai/index.test.ts
new file mode 100644
index 00000000000..071f69674e8
--- /dev/null
+++ b/packages/model-runtime/src/providers/infiniai/index.test.ts
@@ -0,0 +1,71 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { testProvider } from '../../providerTestUtils';
+import { LobeInfiniAI } from './index';
+
+testProvider({
+ Runtime: LobeInfiniAI,
+ provider: ModelProvider.InfiniAI,
+ defaultBaseURL: 'https://cloud.infini-ai.com/maas/v1',
+ chatDebugEnv: 'DEBUG_INFINIAI_CHAT_COMPLETION',
+ chatModel: 'gpt-3.5-turbo',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
+
+describe('LobeInfiniAI - custom features', () => {
+ let instance: InstanceType<typeof LobeInfiniAI>;
+
+ beforeEach(() => {
+ instance = new LobeInfiniAI({ apiKey: 'test_api_key' });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ describe('handlePayload', () => {
+ it('should add enable_thinking when thinking is enabled', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-v3',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 1000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.enable_thinking).toBe(true);
+ });
+
+ it('should not add enable_thinking when thinking is disabled', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-v3',
+ thinking: {
+ budget_tokens: 1000,
+ type: 'disabled',
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.enable_thinking).toBe(false);
+ });
+
+ it('should set enable_thinking to false when thinking is undefined', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-v3',
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.enable_thinking).toBe(false);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/ollamacloud/index.test.ts b/packages/model-runtime/src/providers/ollamacloud/index.test.ts
new file mode 100644
index 00000000000..7317ea8e8be
--- /dev/null
+++ b/packages/model-runtime/src/providers/ollamacloud/index.test.ts
@@ -0,0 +1,19 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+
+import { testProvider } from '../../providerTestUtils';
+import { LobeOllamaCloudAI } from './index';
+
+testProvider({
+ Runtime: LobeOllamaCloudAI,
+ provider: ModelProvider.OllamaCloud,
+ defaultBaseURL: 'https://ollama.com/v1',
+ chatDebugEnv: 'DEBUG_OLLAMA_CLOUD_CHAT_COMPLETION',
+ chatModel: 'llama3.2',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
diff --git a/packages/model-runtime/src/providers/siliconcloud/index.test.ts b/packages/model-runtime/src/providers/siliconcloud/index.test.ts
new file mode 100644
index 00000000000..28ebf8245ef
--- /dev/null
+++ b/packages/model-runtime/src/providers/siliconcloud/index.test.ts
@@ -0,0 +1,196 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { testProvider } from '../../providerTestUtils';
+import { AgentRuntimeErrorType } from '../../types/error';
+import { LobeSiliconCloudAI, SiliconCloudModelCard } from './index';
+
+testProvider({
+ Runtime: LobeSiliconCloudAI,
+ provider: ModelProvider.SiliconCloud,
+ defaultBaseURL: 'https://api.siliconflow.cn/v1',
+ chatDebugEnv: 'DEBUG_SILICONCLOUD_CHAT_COMPLETION',
+ chatModel: 'Qwen/Qwen2.5-7B-Instruct',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
+
+describe('LobeSiliconCloudAI - custom features', () => {
+ let instance: InstanceType<typeof LobeSiliconCloudAI>;
+
+ beforeEach(() => {
+ instance = new LobeSiliconCloudAI({ apiKey: 'test_api_key' });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ describe('handlePayload', () => {
+ it('should limit max_tokens to 16384', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Qwen/Qwen2.5-7B-Instruct',
+ max_tokens: 20000,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.max_tokens).toBe(16384);
+ });
+
+ it('should ensure max_tokens is at least 1', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Qwen/Qwen2.5-7B-Instruct',
+ max_tokens: 0,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.max_tokens).toBe(1);
+ });
+
+ it('should handle thinking with enable_thinking for GLM-4.5 models', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'THUDM/GLM-4.5',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 1000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.enable_thinking).toBe(true);
+ expect(calledPayload.thinking_budget).toBe(1000);
+ });
+
+ it('should handle thinking with thinking_budget for Qwen3 models', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Qwen/Qwen3-8B',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 2000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.enable_thinking).toBe(true);
+ expect(calledPayload.thinking_budget).toBe(2000);
+ });
+
+ it('should handle thinking with thinking_budget for DeepSeek-V3.1', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-ai/DeepSeek-V3.1',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 3000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.enable_thinking).toBe(true);
+ expect(calledPayload.thinking_budget).toBe(3000);
+ });
+
+ it('should limit thinking_budget to 32768', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'THUDM/GLM-4.5',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 50000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.thinking_budget).toBe(32768);
+ });
+
+ it('should set thinking_budget to 1 when budget_tokens is 0', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'THUDM/GLM-4.5',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 0,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.thinking_budget).toBe(1);
+ });
+
+ it('should not add enable_thinking for non-hybrid models', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Qwen/Qwen2.5-7B-Instruct',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 1000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.enable_thinking).toBeUndefined();
+ expect(calledPayload.thinking_budget).toBe(1000);
+ });
+ });
+
+ describe('handleError', () => {
+ it('should handle 401 error as InvalidProviderAPIKey', async () => {
+ const error = new Response('Unauthorized', { status: 401 });
+
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(error);
+
+ try {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Qwen/Qwen2.5-7B-Instruct',
+ });
+ } catch (e: any) {
+ expect(e.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ }
+ });
+
+ it('should handle 403 error as ProviderBizError with custom message', async () => {
+ const error = new Response('Forbidden', { status: 403 });
+
+ vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(error);
+
+ try {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'Qwen/Qwen2.5-7B-Instruct',
+ });
+ } catch (e: any) {
+ expect(e.errorType).toBe(AgentRuntimeErrorType.ProviderBizError);
+ expect(e.message).toContain('请检查 API Key 余额是否充足');
+ }
+ });
+ });
+
+ describe('models', () => {
+ it('should fetch and process model list correctly', async () => {
+ const mockModelList: SiliconCloudModelCard[] = [
+ { id: 'Qwen/Qwen2.5-7B-Instruct' },
+ { id: 'deepseek-ai/DeepSeek-V3' },
+ { id: 'Pro/THUDM/glm-4.5' },
+ ];
+
+ vi.spyOn(instance['client'].models, 'list').mockResolvedValue({
+ data: mockModelList,
+ } as any);
+
+ const models = await instance.models();
+
+ expect(instance['client'].models.list).toHaveBeenCalled();
+ expect(models.length).toBeGreaterThan(0);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/siliconcloud/index.ts b/packages/model-runtime/src/providers/siliconcloud/index.ts
index b2ed133ace4..431f981205f 100644
--- a/packages/model-runtime/src/providers/siliconcloud/index.ts
+++ b/packages/model-runtime/src/providers/siliconcloud/index.ts
@@ -1,6 +1,9 @@
import { ModelProvider } from 'model-bank';
-import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import {
+ OpenAICompatibleFactoryOptions,
+ createOpenAICompatibleRuntime,
+} from '../../core/openaiCompatibleFactory';
import { ChatCompletionErrorPayload } from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
import { processMultiProviderModelList } from '../../utils/modelParse';
@@ -9,7 +12,7 @@ export interface SiliconCloudModelCard {
id: string;
}
-export const LobeSiliconCloudAI = createOpenAICompatibleRuntime({
+export const params: OpenAICompatibleFactoryOptions = {
baseURL: 'https://api.siliconflow.cn/v1',
chatCompletion: {
handleError: (error: any): Omit<ChatCompletionErrorPayload, 'provider'> | undefined => {
@@ -84,4 +87,6 @@ export const LobeSiliconCloudAI = createOpenAICompatibleRuntime({
return processMultiProviderModelList(modelList, 'siliconcloud');
},
provider: ModelProvider.SiliconCloud,
-});
+};
+
+export const LobeSiliconCloudAI = createOpenAICompatibleRuntime(params);
diff --git a/packages/model-runtime/src/providers/v0/index.test.ts b/packages/model-runtime/src/providers/v0/index.test.ts
new file mode 100644
index 00000000000..f37deb045c9
--- /dev/null
+++ b/packages/model-runtime/src/providers/v0/index.test.ts
@@ -0,0 +1,19 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+
+import { testProvider } from '../../providerTestUtils';
+import { LobeV0AI } from './index';
+
+testProvider({
+ Runtime: LobeV0AI,
+ provider: ModelProvider.V0,
+ defaultBaseURL: 'https://api.v0.dev/v1',
+ chatDebugEnv: 'DEBUG_V0_CHAT_COMPLETION',
+ chatModel: 'gpt-4o',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
diff --git a/packages/model-runtime/src/providers/vercelaigateway/index.test.ts b/packages/model-runtime/src/providers/vercelaigateway/index.test.ts
new file mode 100644
index 00000000000..7a13acce0e2
--- /dev/null
+++ b/packages/model-runtime/src/providers/vercelaigateway/index.test.ts
@@ -0,0 +1,58 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { testProvider } from '../../providerTestUtils';
+import { LobeVercelAIGatewayAI } from './index';
+
+testProvider({
+ Runtime: LobeVercelAIGatewayAI,
+ provider: ModelProvider.VercelAIGateway,
+ defaultBaseURL: 'https://ai-gateway.vercel.sh/v1',
+ chatDebugEnv: 'DEBUG_VERCELAIGATEWAY_CHAT_COMPLETION',
+ chatModel: 'gpt-4o',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
+
+describe('LobeVercelAIGatewayAI - custom features', () => {
+ let instance: InstanceType<typeof LobeVercelAIGatewayAI>;
+
+ beforeEach(() => {
+ instance = new LobeVercelAIGatewayAI({ apiKey: 'test_api_key' });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ describe('handlePayload', () => {
+ it('should add reasoning_effort to providerOptions.openai', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'o1-preview',
+ reasoning_effort: 'high',
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.providerOptions?.openai?.reasoningEffort).toBe('high');
+ expect(calledPayload.providerOptions?.openai?.reasoningSummary).toBe('auto');
+ });
+
+ it('should handle both reasoning_effort and verbosity', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'o1-preview',
+ reasoning_effort: 'medium',
+ verbosity: 'low',
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.providerOptions?.openai?.reasoningEffort).toBe('medium');
+ expect(calledPayload.providerOptions?.openai?.textVerbosity).toBe('low');
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/vercelaigateway/index.ts b/packages/model-runtime/src/providers/vercelaigateway/index.ts
index 57d990a8c0e..cf79621652b 100644
--- a/packages/model-runtime/src/providers/vercelaigateway/index.ts
+++ b/packages/model-runtime/src/providers/vercelaigateway/index.ts
@@ -12,9 +12,9 @@ export interface VercelAIGatewayModelCard {
name?: string;
pricing?: {
input?: string | number;
- output?: string | number;
input_cache_read?: string | number;
input_cache_write?: string | number;
+ output?: string | number;
};
tags?: string[];
type?: string;
diff --git a/packages/model-runtime/src/providers/vllm/index.test.ts b/packages/model-runtime/src/providers/vllm/index.test.ts
index 518fe450d82..bf319384b28 100644
--- a/packages/model-runtime/src/providers/vllm/index.test.ts
+++ b/packages/model-runtime/src/providers/vllm/index.test.ts
@@ -1,8 +1,9 @@
// @vitest-environment node
import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { testProvider } from '../../providerTestUtils';
-import { LobeVLLMAI } from './index';
+import { LobeVLLMAI, VLLMModelCard } from './index';
testProvider({
Runtime: LobeVLLMAI,
@@ -11,3 +12,46 @@ testProvider({
chatDebugEnv: 'DEBUG_VLLM_CHAT_COMPLETION',
chatModel: 'llama-2-7b-chat',
});
+
+describe('LobeVLLMAI - custom features', () => {
+ let instance: InstanceType<typeof LobeVLLMAI>;
+
+ beforeEach(() => {
+ instance = new LobeVLLMAI({ apiKey: 'test_api_key' });
+ });
+
+ describe('models', () => {
+ it('should fetch and process model list correctly', async () => {
+ const mockModelList: VLLMModelCard[] = [
+ { id: 'meta-llama/Llama-2-7b-chat-hf' },
+ { id: 'mistralai/Mistral-7B-Instruct-v0.1' },
+ { id: 'qwen/Qwen-7B-Chat' },
+ ];
+
+ vi.spyOn(instance['client'].models, 'list').mockResolvedValue({
+ data: mockModelList,
+ } as any);
+
+ const models = await instance.models();
+
+ expect(instance['client'].models.list).toHaveBeenCalled();
+ expect(models).toHaveLength(3);
+ expect(models[0]).toMatchObject({
+ id: 'meta-llama/Llama-2-7b-chat-hf',
+ });
+ expect(models[1]).toMatchObject({
+ id: 'mistralai/Mistral-7B-Instruct-v0.1',
+ });
+ });
+
+ it('should handle empty model list', async () => {
+ vi.spyOn(instance['client'].models, 'list').mockResolvedValue({
+ data: [],
+ } as any);
+
+ const models = await instance.models();
+
+ expect(models).toEqual([]);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/volcengine/index.test.ts b/packages/model-runtime/src/providers/volcengine/index.test.ts
new file mode 100644
index 00000000000..164a29f387d
--- /dev/null
+++ b/packages/model-runtime/src/providers/volcengine/index.test.ts
@@ -0,0 +1,75 @@
+// @vitest-environment node
+import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { testProvider } from '../../providerTestUtils';
+import { LobeVolcengineAI } from './index';
+
+testProvider({
+ Runtime: LobeVolcengineAI,
+ provider: ModelProvider.Volcengine,
+ defaultBaseURL: 'https://ark.cn-beijing.volces.com/api/v3',
+ chatDebugEnv: 'DEBUG_VOLCENGINE_CHAT_COMPLETION',
+ chatModel: 'doubao-pro-32k',
+ invalidErrorType: 'InvalidProviderAPIKey',
+ bizErrorType: 'ProviderBizError',
+ test: {
+ skipAPICall: true,
+ skipErrorHandle: true,
+ },
+});
+
+describe('LobeVolcengineAI - custom features', () => {
+ let instance: InstanceType<typeof LobeVolcengineAI>;
+
+ beforeEach(() => {
+ instance = new LobeVolcengineAI({ apiKey: 'test_api_key' });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ describe('handlePayload', () => {
+ it('should add thinking for thinking-vision-pro model', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'thinking-vision-pro',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 1000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.thinking).toEqual({ type: 'enabled' });
+ });
+
+ it('should add thinking for deepseek-v3-1 model', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'deepseek-v3-1',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 2000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.thinking).toEqual({ type: 'enabled' });
+ });
+
+ it('should not add thinking for non-thinking models', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'doubao-pro-32k',
+ thinking: {
+ type: 'enabled',
+ budget_tokens: 1000,
+ },
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.thinking).toBeUndefined();
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/xai/index.test.ts b/packages/model-runtime/src/providers/xai/index.test.ts
index cc4068ab426..20130e1dd1a 100644
--- a/packages/model-runtime/src/providers/xai/index.test.ts
+++ b/packages/model-runtime/src/providers/xai/index.test.ts
@@ -1,8 +1,9 @@
// @vitest-environment node
import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { testProvider } from '../../providerTestUtils';
-import { LobeXAI } from './index';
+import { LobeXAI, XAIModelCard, isGrokReasoningModel } from './index';
testProvider({
Runtime: LobeXAI,
@@ -11,3 +12,106 @@ testProvider({
chatDebugEnv: 'DEBUG_XAI_CHAT_COMPLETION',
chatModel: 'grok',
});
+
+describe('LobeXAI - custom features', () => {
+ let instance: InstanceType<typeof LobeXAI>;
+
+ beforeEach(() => {
+ instance = new LobeXAI({ apiKey: 'test_api_key' });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ describe('isGrokReasoningModel', () => {
+ it('should identify Grok reasoning models correctly', () => {
+ expect(isGrokReasoningModel('grok-3-mini')).toBe(true);
+ expect(isGrokReasoningModel('grok-4')).toBe(true);
+ expect(isGrokReasoningModel('grok-code')).toBe(true);
+ expect(isGrokReasoningModel('grok-2')).toBe(false);
+ expect(isGrokReasoningModel('other-model')).toBe(false);
+ });
+ });
+
+ describe('chat with handlePayload', () => {
+ it('should handle Grok reasoning models by removing frequency_penalty and presence_penalty', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'grok-4',
+ frequency_penalty: 0.5,
+ presence_penalty: 0.3,
+ temperature: 0.7,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.frequency_penalty).toBeUndefined();
+ expect(calledPayload.presence_penalty).toBeUndefined();
+ expect(calledPayload.model).toBe('grok-4');
+ });
+
+ it('should keep frequency_penalty and presence_penalty for non-reasoning models', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'grok-2',
+ frequency_penalty: 0.5,
+ presence_penalty: 0.3,
+ temperature: 0.7,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.frequency_penalty).toBe(0.5);
+ expect(calledPayload.presence_penalty).toBe(0.3);
+ });
+
+ it('should add search_parameters when enabledSearch is true', async () => {
+ process.env.XAI_MAX_SEARCH_RESULTS = '10';
+ process.env.XAI_SAFE_SEARCH = '1';
+
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'grok-2',
+ enabledSearch: true,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.search_parameters).toBeDefined();
+ expect(calledPayload.search_parameters.max_search_results).toBe(10);
+ expect(calledPayload.search_parameters.mode).toBe('auto');
+ expect(calledPayload.search_parameters.return_citations).toBe(true);
+ expect(calledPayload.search_parameters.sources).toHaveLength(3);
+
+ delete process.env.XAI_MAX_SEARCH_RESULTS;
+ delete process.env.XAI_SAFE_SEARCH;
+ });
+
+ it('should not add search_parameters when enabledSearch is false', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'grok-2',
+ enabledSearch: false,
+ });
+
+ const calledPayload = (instance['client'].chat.completions.create as any).mock.calls[0][0];
+ expect(calledPayload.search_parameters).toBeUndefined();
+ });
+ });
+
+ describe('models', () => {
+ it('should fetch and process model list correctly', async () => {
+ const mockModelList: XAIModelCard[] = [
+ { id: 'grok-2' },
+ { id: 'grok-3-mini' },
+ { id: 'grok-4' },
+ ];
+
+ vi.spyOn(instance['client'].models, 'list').mockResolvedValue({
+ data: mockModelList,
+ } as any);
+
+ const models = await instance.models();
+
+ expect(instance['client'].models.list).toHaveBeenCalled();
+ expect(models.length).toBeGreaterThan(0);
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/xinference/index.test.ts b/packages/model-runtime/src/providers/xinference/index.test.ts
index c9330091d52..6432a0703b7 100644
--- a/packages/model-runtime/src/providers/xinference/index.test.ts
+++ b/packages/model-runtime/src/providers/xinference/index.test.ts
@@ -1,8 +1,9 @@
// @vitest-environment node
import { ModelProvider } from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import { testProvider } from '../../providerTestUtils';
-import { LobeXinferenceAI } from './index';
+import { LobeXinferenceAI, XinferenceModelCard } from './index';
testProvider({
Runtime: LobeXinferenceAI,
@@ -11,3 +12,71 @@ testProvider({
chatDebugEnv: 'DEBUG_XINFERENCE_CHAT_COMPLETION',
chatModel: 'llama-2-7b-chat',
});
+
+describe('LobeXinferenceAI - custom features', () => {
+ let instance: InstanceType<typeof LobeXinferenceAI>;
+
+ beforeEach(() => {
+ instance = new LobeXinferenceAI({ apiKey: 'test_api_key' });
+ });
+
+ describe('models', () => {
+ it('should fetch and process model list correctly', async () => {
+ const mockModelList: XinferenceModelCard[] = [
+ {
+ context_length: 4096,
+ id: 'qwen-7b',
+ model_ability: ['chat', 'tools', 'vision'],
+ model_description: 'Qwen 7B model',
+ model_type: 'LLM',
+ name: 'Qwen 7B',
+ },
+ {
+ context_length: 8192,
+ id: 'llama-2-13b',
+ model_ability: ['chat', 'reasoning'],
+ model_description: 'Llama 2 13B model',
+ model_type: 'LLM',
+ name: 'Llama 2 13B',
+ },
+ ];
+
+ vi.spyOn(instance['client'].models, 'list').mockResolvedValue({
+ data: mockModelList,
+ } as any);
+
+ const models = await instance.models();
+
+ expect(instance['client'].models.list).toHaveBeenCalled();
+ expect(models).toHaveLength(2);
+ expect(models[0]).toMatchObject({
+ id: 'qwen-7b',
+ displayName: 'Qwen 7B',
+ contextWindowTokens: 4096,
+ description: 'Qwen 7B model',
+ functionCall: true,
+ vision: true,
+ reasoning: false,
+ });
+ expect(models[1]).toMatchObject({
+ id: 'llama-2-13b',
+ displayName: 'Llama 2 13B',
+ contextWindowTokens: 8192,
+ description: 'Llama 2 13B model',
+ functionCall: false,
+ vision: false,
+ reasoning: true,
+ });
+ });
+
+ it('should handle empty model list', async () => {
+ vi.spyOn(instance['client'].models, 'list').mockResolvedValue({
+ data: [],
+ } as any);
+
+ const models = await instance.models();
+
+ expect(models).toEqual([]);
+ });
+ });
+});
diff --git a/packages/model-runtime/vitest.config.mts b/packages/model-runtime/vitest.config.mts
index 0a3de8bc107..bb150d9c852 100644
--- a/packages/model-runtime/vitest.config.mts
+++ b/packages/model-runtime/vitest.config.mts
@@ -1,5 +1,5 @@
import { resolve } from 'node:path';
-import { defineConfig } from 'vitest/config';
+import { coverageConfigDefaults, defineConfig } from 'vitest/config';
export default defineConfig({
test: {
@@ -8,6 +8,7 @@ export default defineConfig({
'@': resolve(__dirname, '../../src'),
},
coverage: {
+ exclude: [...coverageConfigDefaults.exclude, '**/types/**'],
reporter: ['text', 'json', 'lcov', 'text-summary'],
},
environment: 'happy-dom',