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.

137 KB
Raw Blame
// @vitest-environment node
import { ModelProvider } from 'model-bank';
import OpenAI from 'openai';
import type { Stream } from 'openai/streaming';
import type { Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import type { ChatStreamCallbacks, ChatStreamPayload } from '../../types/chat';
import { AgentRuntimeErrorType } from '../../types/error';
import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import * as debugStreamModule from '../../utils/debugStream';
import {
  createSignatureChannelId,
  createSignatureScope,
  serializeScopedSignature,
} from '../../utils/signatureScope';
import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';
import type { LobeOpenAICompatibleRuntime } from '../BaseAI';
import * as openaiHelpers from '../contextBuilders/openai';
import { createOpenAICompatibleRuntime } from './index';

const createBasicChatPayload = (): ChatStreamPayload => ({
  messages: [{ content: 'Hello', role: 'user' }],
  model: 'mistralai/mistral-7b-instruct:free',
  temperature: 0,
});

const createEmptyToolSchema = () => ({
  name: 'test_tool',
  schema: { properties: {}, type: 'object' as const },
});

const createClosedResponseSource = () => ({
  toReadableStream: () =>
    new ReadableStream({
      start(controller) {
        controller.close();
      },
    }),
});

const createConstrainedPersonSchema = () => ({
  name: 'person',
  schema: {
    maxLength: 100,
    pattern: '^[a-z]+$',
    properties: {
      age: { type: 'number' },
      name: { type: 'string' },
    },
    type: 'object' as const,
  },
});

const createPersonExtractorSchema = () => ({
  name: 'person_extractor',
  schema: {
    properties: { age: { type: 'number' }, name: { type: 'string' } },
    type: 'object' as const,
  },
});

const createPersonToolResponse = () => ({
  choices: [
    {
      message: {
        tool_calls: [
          {
            function: {
              arguments: '{"name":"Alice","age":28}',
              name: 'person_extractor',
            },
            type: 'function' as const,
          },
        ],
      },
    },
  ],
});

const createImagePayload = () => ({
  model: 'dall-e-3',
  params: { prompt: 'Test prompt' },
});

const sleep = async (ms: number) =>
  await new Promise((resolve) => {
    setTimeout(resolve, ms);
  });

const provider = 'groq';
const defaultBaseURL = 'https://api.groq.com/openai/v1';
const bizErrorType = 'ProviderBizError';
const invalidErrorType = 'InvalidProviderAPIKey';

const createOpenAIThoughtSignatureScope = async ({
  apiKey = 'test',
  baseURL = defaultBaseURL,
  model = 'upstream-model',
  scopeProvider = 'mapped-provider',
}: {
  apiKey?: string;
  baseURL?: string;
  model?: string;
  scopeProvider?: string;
} = {}) =>
  createSignatureScope({
    kind: 'thought_signature',
    model,
    protocol: 'chat_completions',
    source: {
      apiType: 'openai',
      channelId: await createSignatureChannelId(baseURL, apiKey),
      provider: scopeProvider,
    },
  });

const createOpenAIReasoningSignatureScope = async ({
  apiKey = 'test',
  baseURL = 'https://api.test.com/v1',
  model = 'upstream-model',
  scopeProvider = 'mapped-provider',
}: {
  apiKey?: string;
  baseURL?: string;
  model?: string;
  scopeProvider?: string;
} = {}) =>
  createSignatureScope({
    kind: 'reasoning',
    model,
    protocol: 'responses',
    source: {
      apiType: 'openai',
      channelId: await createSignatureChannelId(baseURL, apiKey),
      provider: scopeProvider,
    },
  });

// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});
vi.mock('@lobechat/business-model-bank/model-config', () => ({
  loadModels: vi.fn().mockResolvedValue([]),
}));
// Mock getModelPricing to prevent async issues
vi.mock('../../utils/model', () => ({
  getModelPricing: vi.fn().mockResolvedValue({}),
}));

let instance: LobeOpenAICompatibleRuntime;

const LobeMockProvider = createOpenAICompatibleRuntime({
  baseURL: defaultBaseURL,
  chatCompletion: {
    handleError: (error) => {
      // 403 means the location is not supporteds
      if (error.status === 403)
        return { error, errorType: AgentRuntimeErrorType.LocationNotSupportError };
    },
  },
  debug: {
    chatCompletion: () => process.env.DEBUG_MOCKPROVIDER_CHAT_COMPLETION === '1',
  },
  provider: ModelProvider.Groq,
});

beforeEach(() => {
  instance = new LobeMockProvider({ apiKey: 'test' });

  // Use vi.spyOn to mock the chat.completions.create method
  vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
    new ReadableStream() as any,
  );
});

afterEach(() => {
  vi.clearAllMocks();
  vi.useRealTimers();
});

describe('LobeOpenAICompatibleFactory', () => {
  // Polyfill File for Node environment used in image tests
  if (typeof File === 'undefined') {
    // @ts-ignore
    global.File = class MockFile {
      constructor(
        public parts: any[],
        public name: string,
        public opts?: any,
      ) {}
    };
  }

  describe('init', () => {
    it('should correctly initialize with an API key', async () => {
      const instance = new LobeMockProvider({ apiKey: 'test_api_key' });
      expect(instance).toBeInstanceOf(LobeMockProvider);
      expect(instance.baseURL).toEqual(defaultBaseURL);
    });
  });

  describe('chat', () => {
    it('should retain the exact OpenAI Chat Completions request and raw chunks', async () => {
      const rawEvents: OpenAI.Chat.Completions.ChatCompletionChunk[] = [
        {
          choices: [
            {
              delta: { content: '', role: 'assistant' },
              finish_reason: null,
              index: 0,
              logprobs: null,
            },
          ],
          created: 1_785_670_000,
          id: 'chatcmpl_empty',
          model: 'glm-5.2',
          object: 'chat.completion.chunk',
        },
        {
          choices: [
            {
              delta: {},
              finish_reason: 'stop',
              index: 0,
              logprobs: null,
            },
          ],
          created: 1_785_670_001,
          id: 'chatcmpl_empty',
          model: 'glm-5.2',
          object: 'chat.completion.chunk',
          usage: { completion_tokens: 1, prompt_tokens: 100, total_tokens: 101 },
        },
      ];
      const rawResponseBody = rawEvents
        .map((event) => `data: ${JSON.stringify(event)}\n\n`)
        .join('');
      const rawStream = {
        async *[Symbol.asyncIterator]() {
          for (const event of rawEvents) yield event;
        },
      };
      const create = vi.fn(() => ({
        withResponse: vi.fn().mockResolvedValue({
          data: rawStream,
          request_id: 'req_openai_empty',
          response: new Response(rawResponseBody, {
            headers: {
              'cf-ray': 'ray-openai',
              'content-type': 'text/event-stream',
              'x-request-id': 'req-header-openai',
            },
            status: 200,
          }),
        }),
      }));
      const Runtime = createOpenAICompatibleRuntime({
        baseURL: 'https://api.test.com/v1',
        customClient: {
          createClient: () => ({ chat: { completions: { create } } }) as unknown as OpenAI,
        },
        provider: 'test-provider',
      });
      const runtime = new Runtime({ apiKey: 'test' });
      const diagnostics: ModelRuntimeDiagnostics = {};

      const response = await runtime.chat(
        {
          messages: [{ content: 'Question', role: 'user' }],
          model: 'glm-5.2',
          stream: true,
        },
        { diagnostics, user: 'user-1' },
      );
      await response.text();

      expect(diagnostics.providerRequest).toEqual(
        expect.objectContaining({
          apiMode: 'chat_completions',
          endpoint: 'https://api.***.com/v1',
          payload: expect.objectContaining({
            messages: [{ content: 'Question', role: 'user' }],
            model: 'glm-5.2',
            stream: true,
            user: 'user-1',
          }),
          sentAt: expect.any(Number),
        }),
      );
      expect(diagnostics.providerResponse).toEqual(
        expect.objectContaining({
          apiMode: 'chat_completions',
          completedAt: expect.any(Number),
          eventCount: 2,
          headers: {
            'cf-ray': 'ray-openai',
            'content-type': 'text/event-stream',
            'x-request-id': 'req-header-openai',
          },
          messageId: 'chatcmpl_empty',
          model: 'glm-5.2',
          rawEvents,
          rawResponse: {
            body: rawResponseBody,
            byteLength: new TextEncoder().encode(rawResponseBody).byteLength,
            status: 'captured',
          },
          requestId: 'req_openai_empty',
          status: 200,
          stopReason: 'stop',
          terminalEventReceived: true,
          textChars: 0,
          usage: { completion_tokens: 1, prompt_tokens: 100, total_tokens: 101 },
        }),
      );
    });

    it('should retain the exact OpenAI Responses request and raw events', async () => {
      const rawEvents = [
        {
          response: {
            id: 'resp_empty',
            model: 'gpt-5.4-mini',
            status: 'in_progress',
            usage: null,
          },
          sequence_number: 0,
          type: 'response.created',
        },
        {
          response: {
            id: 'resp_empty',
            model: 'gpt-5.4-mini',
            output: [],
            status: 'completed',
            usage: { input_tokens: 100, output_tokens: 1, total_tokens: 101 },
          },
          sequence_number: 1,
          type: 'response.completed',
        },
      ] as unknown as OpenAI.Responses.ResponseStreamEvent[];
      const rawResponseBody = rawEvents
        .map((event) => `data: ${JSON.stringify(event)}\n\n`)
        .join('');
      const rawStream = {
        async *[Symbol.asyncIterator]() {
          for (const event of rawEvents) yield event;
        },
      };
      const create = vi.fn(() => ({
        withResponse: vi.fn().mockResolvedValue({
          data: rawStream,
          request_id: 'req_responses_empty',
          response: new Response(rawResponseBody, {
            headers: {
              'content-type': 'text/event-stream',
              'openai-request-id': 'req-responses-header',
            },
            status: 200,
          }),
        }),
      }));
      const Runtime = createOpenAICompatibleRuntime({
        baseURL: 'https://api.test.com/v1',
        chatCompletion: { useResponse: true },
        customClient: {
          createClient: () => ({ responses: { create } }) as unknown as OpenAI,
        },
        provider: 'test-provider',
      });
      const runtime = new Runtime({ apiKey: 'test' });
      const diagnostics: ModelRuntimeDiagnostics = {};

      const response = await runtime.chat(
        {
          messages: [{ content: 'Question', role: 'user' }],
          model: 'gpt-5.4-mini',
          stream: true,
        },
        { diagnostics, user: 'user-1' },
      );
      await response.text();

      expect(diagnostics.providerRequest).toEqual(
        expect.objectContaining({
          apiMode: 'responses',
          endpoint: 'https://api.***.com/v1',
          payload: expect.objectContaining({
            input: expect.any(Array),
            model: 'gpt-5.4-mini',
            safety_identifier: 'user-1',
            store: false,
            stream: true,
          }),
          sentAt: expect.any(Number),
        }),
      );
      expect(diagnostics.providerResponse).toEqual(
        expect.objectContaining({
          apiMode: 'responses',
          completedAt: expect.any(Number),
          eventCount: 2,
          headers: {
            'content-type': 'text/event-stream',
            'openai-request-id': 'req-responses-header',
          },
          messageId: 'resp_empty',
          model: 'gpt-5.4-mini',
          rawEvents,
          rawResponse: {
            body: rawResponseBody,
            byteLength: new TextEncoder().encode(rawResponseBody).byteLength,
            status: 'captured',
          },
          requestId: 'req_responses_empty',
          status: 200,
          stopReason: 'completed',
          terminalEventReceived: true,
          usage: { input_tokens: 100, output_tokens: 1, total_tokens: 101 },
        }),
      );
    });

    it('should return a Response on successful API call', async () => {
      // Arrange
      const mockStream = new ReadableStream();
      const mockResponse = Promise.resolve(mockStream);

      (instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);

      // Act
      const result = await instance.chat(createBasicChatPayload());

      // Assert
      expect(result).toBeInstanceOf(Response);
    });

    it('should call chat API with corresponding options', async () => {
      // Arrange
      const mockStream = new ReadableStream();
      const mockResponse = Promise.resolve(mockStream);

      (instance['client'].chat.completions.create as Mock).mockResolvedValue(mockResponse);

      // Act
      const result = await instance.chat({
        max_tokens: 1024,
        messages: [{ content: 'Hello', role: 'user' }],
        model: 'mistralai/mistral-7b-instruct:free',
        temperature: 0.7,
        top_p: 1,
      });

      // Assert
      expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
        {
          max_tokens: 1024,
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'mistralai/mistral-7b-instruct:free',
          stream: true,
          stream_options: {
            include_usage: true,
          },
          temperature: 0.7,
          top_p: 1,
        },
        { headers: { Accept: '*/*' } },
      );
      expect(result).toBeInstanceOf(Response);
    });

    // MCP tool schemas with `items: true` or array props missing
    // `type` must be normalized before reaching the upstream validator.
    it('should normalize tool parameter schemas before sending to upstream', async () => {
      (instance['client'].chat.completions.create as Mock).mockResolvedValue(
        Promise.resolve(new ReadableStream()),
      );

      await instance.chat({
        messages: [{ content: 'Hello', role: 'user' }],
        model: 'mistralai/mistral-7b-instruct:free',
        temperature: 0.7,
        tools: [
          {
            function: {
              name: 'mcp_tool',
              parameters: {
                properties: {
                  ids: { items: true, type: 'array' },
                  sourceIds: { items: { type: 'string' } },
                },
                type: 'object',
              },
            },
            type: 'function',
          },
        ],
      });

      const callArgs = (instance['client'].chat.completions.create as Mock).mock.calls[0][0];
      const params = callArgs.tools[0].function.parameters;
      // `items: true` collapsed to `{}`
      expect(params.properties.ids.items).toEqual({});
      // array prop missing `type` gets backfilled
      expect(params.properties.sourceIds.type).toBe('array');
    });

    it('should keep logical model for provider payload handling while sending mapped model id', async () => {
      const handlePayload = vi.fn(
        (payload: ChatStreamPayload): OpenAI.ChatCompletionCreateParamsStreaming => ({
          messages: payload.messages as OpenAI.ChatCompletionCreateParamsStreaming['messages'],
          model: payload.model,
          stream: true,
        }),
      );
      const Runtime = createOpenAICompatibleRuntime({
        baseURL: defaultBaseURL,
        chatCompletion: { handlePayload },
        provider: 'mapped-provider',
      });
      const runtime = new Runtime({
        apiKey: 'test',
        modelIdMapping: { 'logical-model': 'upstream-model' },
      });
      vi.spyOn(runtime['client'].chat.completions, 'create').mockResolvedValue(
        new ReadableStream() as any,
      );

      await runtime.chat({
        messages: [{ content: 'Hello', role: 'user' }],
        model: 'logical-model',
        temperature: 0,
      });

      expect(handlePayload).toHaveBeenCalledWith(
        expect.objectContaining({ model: 'logical-model' }),
        expect.anything(),
      );
      expect(runtime['client'].chat.completions.create).toHaveBeenCalledWith(
        expect.objectContaining({ model: 'upstream-model' }),
        expect.anything(),
      );
    });

    it('should replay a thought signature scoped to the mapped upstream model', async () => {
      const Runtime = createOpenAICompatibleRuntime({
        baseURL: defaultBaseURL,
        provider: 'mapped-provider',
      });
      const runtime = new Runtime({
        apiKey: 'test',
        modelIdMapping: { 'logical-model': 'upstream-model' },
      });
      const create = vi
        .spyOn(runtime['client'].chat.completions, 'create')
        .mockResolvedValue(new ReadableStream() as any);
      const scope = await createOpenAIThoughtSignatureScope();

      await runtime.chat({
        messages: [
          {
            content: '',
            role: 'assistant',
            tool_calls: [
              {
                function: { arguments: '{}', name: 'search' },
                id: 'call-1',
                thoughtSignature: serializeScopedSignature(
                  'upstream-signature',
                  scope,
                  'thought_signature',
                ),
                type: 'function',
              },
            ],
          },
        ],
        model: 'logical-model',
        temperature: 0,
      });

      const request = create.mock.calls[0][0];
      expect(request.model).toBe('upstream-model');
      expect((request.messages[0] as any).tool_calls[0].thoughtSignature).toBe(
        'upstream-signature',
      );
    });

    it.each([
      { apiKey: 'another-key', baseURL: defaultBaseURL, label: 'credential' },
      { apiKey: 'test', baseURL: 'https://another.example.com/v1', label: 'endpoint' },
    ])('should reject a thought signature from another direct $label', async (source) => {
      const Runtime = createOpenAICompatibleRuntime({
        baseURL: defaultBaseURL,
        provider: 'mapped-provider',
      });
      const runtime = new Runtime({ apiKey: 'test' });
      const create = vi
        .spyOn(runtime['client'].chat.completions, 'create')
        .mockResolvedValue(new ReadableStream() as any);
      const sourceScope = await createOpenAIThoughtSignatureScope(source);

      await runtime.chat({
        messages: [
          {
            content: '',
            role: 'assistant',
            tool_calls: [
              {
                function: { arguments: '{}', name: 'search' },
                id: 'call-1',
                thoughtSignature: serializeScopedSignature(
                  'foreign-signature',
                  sourceScope,
                  'thought_signature',
                ),
                type: 'function',
              },
            ],
          },
        ],
        model: 'upstream-model',
        temperature: 0,
      });

      const request = create.mock.calls[0][0];
      expect((request.messages[0] as any).tool_calls[0].thoughtSignature).toBeUndefined();
    });

    describe('streaming response', () => {
      it('should handle multiple data chunks correctly', async () => {
        const mockStream = new ReadableStream({
          start(controller) {
            controller.enqueue({
              choices: [
                { delta: { content: 'hello' }, finish_reason: null, index: 0, logprobs: null },
              ],
              created: 1_709_125_675,
              id: 'a',
              model: 'mistralai/mistral-7b-instruct:free',
              object: 'chat.completion.chunk',
              system_fingerprint: 'fp_86156a94a0',
            });
            controller.close();
          },
        });
        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockStream as any,
        );

        const result = await instance.chat(createBasicChatPayload());

        const decoder = new TextDecoder();
        const reader = result.body!.getReader();

        // Collect all chunks
        const chunks = [];

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          chunks.push(decoder.decode(value));
        }
        // Assert that all expected chunk patterns are present
        expect(chunks).toEqual(
          expect.arrayContaining(['id: a\n', 'event: text\n', 'data: "hello"\n\n']),
        );
      });

      // https://github.com/lobehub/lobe-chat/issues/2752
      it('should handle burn hair data chunks correctly', async () => {
        const chunks = [
          {
            choices: [],
            created: 0,
            id: '',
            model: '',
            object: '',
            prompt_filter_results: [
              {
                content_filter_results: {
                  hate: { filtered: false, severity: 'safe' },
                  self_harm: { filtered: false, severity: 'safe' },
                  sexual: { filtered: false, severity: 'safe' },
                  violence: { filtered: false, severity: 'safe' },
                },
                prompt_index: 0,
              },
            ],
          },
          {
            choices: [
              {
                delta: { content: '', role: 'assistant' },
                finish_reason: null,
                index: 0,
                logprobs: null,
              },
            ],
            created: 1_717_249_403,
            id: 'chatcmpl-9VJIxA3qNM2C2YdAnNYA2KgDYfFnX',
            model: 'gpt-4o-2024-05-13',
            object: 'chat.completion.chunk',
            system_fingerprint: 'fp_5f4bad809a',
          },
          {
            choices: [{ delta: { content: '1' }, finish_reason: null, index: 0, logprobs: null }],
            created: 1_717_249_403,
            id: 'chatcmpl-9VJIxA3qNM2C2YdAnNYA2KgDYfFnX',
            model: 'gpt-4o-2024-05-13',
            object: 'chat.completion.chunk',
            system_fingerprint: 'fp_5f4bad809a',
          },
          {
            choices: [{ delta: {}, finish_reason: 'stop', index: 0, logprobs: null }],
            created: 1_717_249_403,
            id: 'chatcmpl-9VJIxA3qNM2C2YdAnNYA2KgDYfFnX',
            model: 'gpt-4o-2024-05-13',
            object: 'chat.completion.chunk',
            system_fingerprint: 'fp_5f4bad809a',
          },
          {
            choices: [
              {
                content_filter_offsets: { check_offset: 35, end_offset: 36, start_offset: 35 },
                content_filter_results: {
                  hate: { filtered: false, severity: 'safe' },
                  self_harm: { filtered: false, severity: 'safe' },
                  sexual: { filtered: false, severity: 'safe' },
                  violence: { filtered: false, severity: 'safe' },
                },
                finish_reason: null,
                index: 0,
              },
            ],
            created: 0,
            id: '',
            model: '',
            object: '',
          },
        ];
        const mockStream = new ReadableStream({
          start(controller) {
            chunks.forEach((item) => {
              controller.enqueue(item);
            });

            controller.close();
          },
        });
        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockStream as any,
        );

        const stream: string[] = [];
        const result = await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'gpt-3.5-turbo',
          temperature: 0,
        });
        const decoder = new TextDecoder();
        const reader = result.body!.getReader();

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          stream.push(decoder.decode(value));
        }

        expect(stream).toEqual(
          [
            'id: ',
            'event: data',
            'data: {"choices":[],"created":0,"id":"","model":"","object":"","prompt_filter_results":[{"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}},"prompt_index":0}]}\n',
            'id: chatcmpl-9VJIxA3qNM2C2YdAnNYA2KgDYfFnX',
            'event: text',
            'data: ""\n',
            'id: chatcmpl-9VJIxA3qNM2C2YdAnNYA2KgDYfFnX',
            'event: text',
            'data: "1"\n',
            'id: chatcmpl-9VJIxA3qNM2C2YdAnNYA2KgDYfFnX',
            'event: stop',
            'data: "stop"\n',
            'id: ',
            'event: data',
            'data: {"id":"","index":0}\n',
          ].map((item) => `${item}\n`),
        );
      });

      it('should transform non-streaming response to stream correctly', async () => {
        vi.useFakeTimers();

        const mockResponse = {
          choices: [
            {
              finish_reason: 'stop',
              index: 0,
              logprobs: null,
              message: { content: 'Hello', role: 'assistant' },
            },
          ],
          created: 123,
          id: 'a',
          model: 'mistralai/mistral-7b-instruct:free',
          object: 'chat.completion',
          usage: {
            completion_tokens: 5,
            prompt_tokens: 5,
            total_tokens: 10,
          },
        } as OpenAI.ChatCompletion;
        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const chatPromise = instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'mistralai/mistral-7b-instruct:free',
          stream: false,
          temperature: 0,
        });

        // Advance time to simulate processing delay
        vi.advanceTimersByTime(10);

        const result = await chatPromise;

        const decoder = new TextDecoder();
        const reader = result.body!.getReader();
        const stream: string[] = [];

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          stream.push(decoder.decode(value));
        }

        expect(stream).toEqual([
          'id: a\n',
          'event: text\n',
          'data: "Hello"\n\n',
          'id: a\n',
          'event: usage\n',
          'data: {"inputTextTokens":5,"outputTextTokens":5,"totalInputTokens":5,"totalOutputTokens":5,"totalTokens":10}\n\n',
          'id: output_speed\n',
          'event: speed\n',
          'data: {"latency":10}\n\n',
          'id: a\n',
          'event: stop\n',
          'data: "stop"\n\n',
        ]);

        const finalRead = await reader.read();
        expect(finalRead.done).toBe(true);

        vi.useRealTimers();
      });

      it('should transform non-streaming response to stream correctly with reasoning content', async () => {
        vi.useFakeTimers();

        const mockResponse = {
          choices: [
            {
              finish_reason: 'stop',
              index: 0,
              logprobs: null,
              message: {
                content: 'Hello',
                reasoning_content: 'Thinking content',
                role: 'assistant',
              },
            },
          ],
          created: 123,
          id: 'a',
          model: 'deepseek/deepseek-reasoner',
          object: 'chat.completion',
          usage: {
            completion_tokens: 5,
            prompt_tokens: 5,
            total_tokens: 10,
          },
        } as unknown as OpenAI.ChatCompletion;
        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const chatPromise = instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'deepseek/deepseek-reasoner',
          stream: false,
          temperature: 0,
        });

        // Advance time to simulate processing delay
        vi.advanceTimersByTime(10);

        const result = await chatPromise;

        const decoder = new TextDecoder();
        const reader = result.body!.getReader();
        const stream: string[] = [];

        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          stream.push(decoder.decode(value));
        }

        expect(stream).toEqual([
          'id: a\n',
          'event: reasoning\n',
          'data: "Thinking content"\n\n',
          'id: a\n',
          'event: text\n',
          'data: "Hello"\n\n',
          'id: a\n',
          'event: usage\n',
          'data: {"inputTextTokens":5,"outputTextTokens":5,"totalInputTokens":5,"totalOutputTokens":5,"totalTokens":10}\n\n',
          'id: output_speed\n',
          'event: speed\n',
          'data: {"latency":10}\n\n',
          'id: a\n',
          'event: stop\n',
          'data: "stop"\n\n',
        ]);

        const finalRead = await reader.read();
        expect(finalRead.done).toBe(true);

        vi.useRealTimers();
      });
    });

    describe('handlePayload option', () => {
      it('should add user in payload correctly', async () => {
        const mockCreateMethod = vi.spyOn(instance['client'].chat.completions, 'create');

        await instance.chat(createBasicChatPayload(), { user: 'abc' });

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.objectContaining({
            user: 'abc',
          }),
          expect.anything(),
        );
      });

      it('should add prompt_cache_key for OpenAI chat requests with user', async () => {
        const LobeOpenAIProvider = createOpenAICompatibleRuntime({
          baseURL: 'https://api.openai.com/v1',
          provider: ModelProvider.OpenAI,
        });

        const instance = new LobeOpenAIProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        await instance.chat(
          {
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'gpt-4o',
            temperature: 0,
          },
          { user: 'testUser' },
        );

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.objectContaining({
            prompt_cache_key: 'lobe:testUser:gpt-4o',
          }),
          expect.anything(),
        );
      });

      it('should not add prompt_cache_key for non-GPT models', async () => {
        const mockCreateMethod = vi.spyOn(instance['client'].chat.completions, 'create');

        await instance.chat(
          {
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'llama-3.1-8b-instant',
            temperature: 0,
          },
          { user: 'testUser' },
        );

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.not.objectContaining({
            prompt_cache_key: expect.anything(),
          }),
          expect.anything(),
        );
      });

      it('should not add prompt_cache_key for GPT chat requests without user', async () => {
        const LobeOpenAIProvider = createOpenAICompatibleRuntime({
          baseURL: 'https://api.openai.com/v1',
          provider: ModelProvider.OpenAI,
        });
        const instance = new LobeOpenAIProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'gpt-4o',
          temperature: 0,
        });

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.not.objectContaining({
            prompt_cache_key: expect.anything(),
          }),
          expect.anything(),
        );
      });

      it('should add prompt_cache_key for GPT models from any provider (including new-api/aihubmix)', async () => {
        // Test with non-OpenAI provider but GPT model
        const LobeCustomOpenAICompatibleProvider = createOpenAICompatibleRuntime({
          baseURL: 'https://custom-proxy.new-api.com/v1',
          provider: 'custom-openai-compatible',
        });

        const instance = new LobeCustomOpenAICompatibleProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        await instance.chat(
          {
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'gpt-4o-mini',
            temperature: 0,
          },
          { user: 'testUser' },
        );

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.objectContaining({
            prompt_cache_key: 'lobe:testUser:gpt-4o-mini',
          }),
          expect.anything(),
        );
      });

      it('should not override custom prompt_cache_key from handlePayload', async () => {
        const LobeOpenAIProvider = createOpenAICompatibleRuntime({
          baseURL: 'https://api.openai.com/v1',
          chatCompletion: {
            handlePayload: (payload) =>
              ({
                ...payload,
                prompt_cache_key: 'custom-cache-key',
                stream: true,
              }) as OpenAI.ChatCompletionCreateParamsStreaming,
          },
          provider: ModelProvider.OpenAI,
        });

        const instance = new LobeOpenAIProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        await instance.chat(
          {
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'gpt-4o',
            temperature: 0,
          },
          { user: 'testUser' },
        );

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.objectContaining({
            prompt_cache_key: 'custom-cache-key',
          }),
          expect.anything(),
        );
      });
    });

    describe('noUserId option', () => {
      it('should not add user to payload when noUserId is true', async () => {
        const LobeMockProvider = createOpenAICompatibleRuntime({
          baseURL: 'https://api.mistral.ai/v1',
          chatCompletion: {
            noUserId: true,
          },
          provider: ModelProvider.Mistral,
        });

        const instance = new LobeMockProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        await instance.chat(
          {
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'open-mistral-7b',
            temperature: 0,
          },
          { user: 'testUser' },
        );

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.not.objectContaining({
            user: 'testUser',
          }),
          expect.anything(),
        );
      });

      it('should add user to payload when noUserId is false', async () => {
        const LobeMockProvider = createOpenAICompatibleRuntime({
          baseURL: 'https://api.mistral.ai/v1',
          chatCompletion: {
            noUserId: false,
          },
          provider: ModelProvider.Mistral,
        });

        const instance = new LobeMockProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        await instance.chat(
          {
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'open-mistral-7b',
            temperature: 0,
          },
          { user: 'testUser' },
        );

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.objectContaining({
            user: 'testUser',
          }),
          expect.anything(),
        );
      });

      it('should add user to payload when noUserId is not set in chatCompletion', async () => {
        const LobeMockProvider = createOpenAICompatibleRuntime({
          baseURL: 'https://api.mistral.ai/v1',
          provider: ModelProvider.Mistral,
        });

        const instance = new LobeMockProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        await instance.chat(
          {
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'open-mistral-7b',
            temperature: 0,
          },
          { user: 'testUser' },
        );

        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.objectContaining({
            user: 'testUser',
          }),
          expect.anything(),
        );
      });
    });

    describe('contextPreFlight option', () => {
      const tightModel: any = {
        contextWindowTokens: 2000,
        displayName: 'Tight',
        id: 'tight-model',
        maxOutput: 8000,
        type: 'chat',
      };
      const roomyModel: any = {
        contextWindowTokens: 200_000,
        displayName: 'Roomy',
        id: 'roomy-model',
        maxOutput: 8000,
        type: 'chat',
      };

      it('aborts before dispatch with ExceededContextWindow when prompt exceeds ctx', async () => {
        const LobePreFlightProvider = createOpenAICompatibleRuntime({
          baseURL: defaultBaseURL,
          chatCompletion: {
            contextPreFlight: { models: [tightModel] },
          },
          provider: 'preflight-test',
        });

        const instance = new LobePreFlightProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        const longContent = 'a'.repeat(20_000);

        try {
          await instance.chat({
            messages: [{ content: longContent, role: 'user' }],
            model: 'tight-model',
            temperature: 0,
          });
          expect.fail('expected chat to reject');
        } catch (error) {
          expect((error as any).errorType).toBe(AgentRuntimeErrorType.ExceededContextWindow);
          expect((error as any).error.type).toBe('context_exceeded_pre_flight');
          expect((error as any).error.model).toBe('tight-model');
          expect((error as any).error.ctx).toBe(2000);
          expect((error as any).error.promptTokens).toBeGreaterThan(0);
          expect((error as any).error.shortBy).toBe(
            (error as any).error.promptTokens - (error as any).error.ctx,
          );
          expect((error as any).error.suggestions).toEqual([
            'fork_topic',
            'switch_to_larger_ctx_model',
          ]);
        }

        expect(mockCreateMethod).not.toHaveBeenCalled();
      });

      it('passes through when prompt fits comfortably', async () => {
        const LobePreFlightProvider = createOpenAICompatibleRuntime({
          baseURL: defaultBaseURL,
          chatCompletion: {
            contextPreFlight: { models: [roomyModel] },
          },
          provider: 'preflight-test',
        });

        const instance = new LobePreFlightProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        await instance.chat({
          messages: [{ content: 'hi', role: 'user' }],
          model: 'roomy-model',
          temperature: 0,
        });

        expect(mockCreateMethod).toHaveBeenCalledTimes(1);
      });

      it('skips when the model is unknown to the pre-flight list', async () => {
        const LobePreFlightProvider = createOpenAICompatibleRuntime({
          baseURL: defaultBaseURL,
          chatCompletion: {
            contextPreFlight: { models: [tightModel] },
          },
          provider: 'preflight-test',
        });

        const instance = new LobePreFlightProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        const longContent = 'a'.repeat(20_000);
        await instance.chat({
          messages: [{ content: longContent, role: 'user' }],
          model: 'unknown-model',
          temperature: 0,
        });

        expect(mockCreateMethod).toHaveBeenCalledTimes(1);
      });

      it('passes through a near-limit prompt that still fits the window', async () => {
        // Regression: prior implementation deducted a 1024 buffer + 1024
        // minOutputTokens before deciding, which rejected a ~198.5k-token
        // prompt against a 200k-token window. The corrected threshold
        // only fires on real overflow.
        const LobePreFlightProvider = createOpenAICompatibleRuntime({
          baseURL: defaultBaseURL,
          chatCompletion: {
            contextPreFlight: { models: [roomyModel] },
          },
          provider: 'preflight-test',
        });

        const instance = new LobePreFlightProvider({ apiKey: 'test' });
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);

        // ~4 chars/token, so this estimates around 198.5k tokens.
        const nearLimitContent = 'a'.repeat(794_000);

        await instance.chat({
          messages: [{ content: nearLimitContent, role: 'user' }],
          model: 'roomy-model',
          temperature: 0,
        });

        expect(mockCreateMethod).toHaveBeenCalledTimes(1);
      });
    });

    describe('cancel request', () => {
      it('should cancel ongoing request correctly', async () => {
        const controller = new AbortController();
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockImplementation(
            () =>
              new Promise((_, reject) => {
                setTimeout(() => {
                  reject(new DOMException('The user aborted a request.', 'AbortError'));
                }, 100);
              }) as any,
          );

        const chatPromise = instance.chat(createBasicChatPayload(), { signal: controller.signal });

        // Give some time for the request to start
        await sleep(50);

        controller.abort();

        // Wait and assert that Promise is rejected
        // Use try-catch to capture and verify errors
        try {
          await chatPromise;
          // If Promise is not rejected, test should fail
          expect.fail('Expected promise to be rejected');
        } catch (error) {
          expect((error as any).errorType).toBe('AgentRuntimeError');
          expect((error as any).error.name).toBe('AbortError');
          expect((error as any).error.message).toBe('The user aborted a request.');
        }
        expect(mockCreateMethod).toHaveBeenCalledWith(
          expect.anything(),
          expect.objectContaining({
            signal: controller.signal,
          }),
        );
      }, 10000);
    });

    describe('Error', () => {
      it('should return bizErrorType 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',
          new Headers(),
        );

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        // Act
        try {
          await instance.chat(createBasicChatPayload());
        } catch (e) {
          expect(e).toEqual({
            endpoint: defaultBaseURL,
            error: {
              error: { message: 'Bad Request' },
              status: 400,
            },
            errorType: bizErrorType,
            message: expect.any(String),
            provider,
          });
        }
      });

      it('should classify media download failures as InvalidRequestFormat', async () => {
        const apiError = new OpenAI.APIError(
          400,
          {
            error: {
              message: 'failed to download or process media content',
              type: 'invalid_request_error',
            },
            status: 400,
          },
          'failed to download or process media content',
          new Headers(),
        );

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        await expect(
          instance.chat({
            messages: [{ content: 'Describe this image', role: 'user' }],
            model: 'mimo-v2.5',
            temperature: 0,
          }),
        ).rejects.toMatchObject({
          errorType: AgentRuntimeErrorType.InvalidRequestFormat,
          provider,
        });
      });

      it('should classify a remote media download timeout as retryable', async () => {
        const message =
          'Unable to download content from the provided URL before the timeout. Check that the URL is publicly accessible and responds promptly, or upload the file and provide a file_id instead.';
        const apiError = new OpenAI.APIError(
          400,
          {
            code: 'invalid_value',
            error: {
              code: 'invalid_value',
              message,
              param: 'url',
              type: 'invalid_request_error',
            },
            param: 'url',
            status: 400,
            type: 'invalid_request_error',
          },
          message,
          new Headers(),
        );

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        await expect(
          instance.chat({
            messages: [{ content: 'Describe this image', role: 'user' }],
            model: 'gpt-4o',
            temperature: 0,
          }),
        ).rejects.toMatchObject({
          errorType: AgentRuntimeErrorType.RemoteMediaDownloadTimeout,
          provider,
        });
      });

      it('should classify an HTML 413 response as RequestBodyTooLarge', async () => {
        const apiError = new OpenAI.APIError(
          413,
          null as any,
          'Failed to buffer request body',
          new Headers({ 'content-type': 'text/html' }),
        );

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        await expect(
          instance.chat({
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'deepseek-chat',
            temperature: 0,
          }),
        ).rejects.toMatchObject({
          error: { status: 413 },
          errorType: AgentRuntimeErrorType.RequestBodyTooLarge,
          provider,
        });
      });

      it('should throw AgentRuntimeError with invalidErrorType if no apiKey is provided', async () => {
        try {
          new LobeMockProvider({});
        } catch (e) {
          expect(e).toEqual({ errorType: invalidErrorType });
        }
      });

      it('should return bizErrorType 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', new Headers());

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        // Act
        try {
          await instance.chat(createBasicChatPayload());
        } catch (e) {
          expect(e).toEqual({
            endpoint: defaultBaseURL,
            error: {
              cause: { message: 'api is undefined' },
            },
            errorType: bizErrorType,
            message: expect.any(String),
            provider,
          });
        }
      });

      it('should return bizErrorType 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', new Headers());

        instance = new LobeMockProvider({
          apiKey: 'test',

          baseURL: 'https://api.abc.com/v1',
        });

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        // Act
        try {
          await instance.chat(createBasicChatPayload());
        } catch (e) {
          expect(e).toEqual({
            endpoint: 'https://api.***.com/v1',
            error: {
              cause: { message: 'api is undefined' },
            },
            errorType: bizErrorType,
            message: expect.any(String),
            provider,
          });
        }
      });

      describe('handleError option', () => {
        it('should return correct error type for 403 status code', async () => {
          const error = { status: 403 };
          vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(error);

          try {
            await instance.chat(createBasicChatPayload());
          } catch (e) {
            expect(e).toEqual({
              error,
              errorType: AgentRuntimeErrorType.LocationNotSupportError,
              provider,
            });
          }
        });
      });

      it('should throw an InvalidOpenRouterAPIKey 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(createBasicChatPayload());
        } catch (e) {
          // Expect the chat method to throw an error with InvalidMoonshotAPIKey
          expect(e).toMatchObject({
            endpoint: defaultBaseURL,
            error,
            errorType: invalidErrorType,
            provider,
          });
        }
      });

      it('should return InsufficientQuota error when error message contains "Insufficient Balance"', async () => {
        const apiError = new OpenAI.APIError(
          400,
          {
            error: {
              message: 'Insufficient Balance: Your account balance is too low',
            },
            status: 400,
          },
          'Error message',
          new Headers(),
        );

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        try {
          await instance.chat(createBasicChatPayload());
        } catch (e) {
          expect(e).toEqual({
            endpoint: defaultBaseURL,
            error: {
              error: { message: 'Insufficient Balance: Your account balance is too low' },
              status: 400,
            },
            errorType: AgentRuntimeErrorType.InsufficientQuota,
            message: expect.any(String),
            provider,
          });
        }
      });

      it('should detect ExceededContextWindow from error message text', async () => {
        const apiError = new OpenAI.APIError(
          400,
          {
            error: {
              message:
                "This model's maximum context length is 131072 tokens. However, your messages resulted in 140000 tokens.",
            },
            status: 400,
          },
          'Error message',
          new Headers(),
        );

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        try {
          await instance.chat(createBasicChatPayload());
        } catch (e) {
          expect(e).toEqual({
            endpoint: defaultBaseURL,
            error: {
              error: {
                message:
                  "This model's maximum context length is 131072 tokens. However, your messages resulted in 140000 tokens.",
              },
              status: 400,
            },
            errorType: AgentRuntimeErrorType.ExceededContextWindow,
            message: expect.any(String),
            provider,
          });
        }
      });

      it('should detect RateLimitExceeded from error message text', async () => {
        const apiError = new OpenAI.APIError(
          429,
          {
            error: {
              message: 'Resource has been exhausted (e.g. check quota).',
            },
            status: 429,
          },
          'Error message',
          new Headers(),
        );

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        try {
          await instance.chat(createBasicChatPayload());
        } catch (e) {
          expect(e).toEqual({
            endpoint: defaultBaseURL,
            error: {
              error: {
                message: 'Resource has been exhausted (e.g. check quota).',
              },
              status: 429,
            },
            errorType: AgentRuntimeErrorType.RateLimitExceeded,
            message: expect.any(String),
            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(createBasicChatPayload());
        } catch (e) {
          expect(e).toEqual({
            endpoint: defaultBaseURL,
            error: {
              cause: genericError.cause,
              message: genericError.message,
              name: genericError.name,
            },
            errorType: 'AgentRuntimeError',
            message: expect.any(String),
            provider,
          });
        }
      });
    });

    describe('chat with callback and headers', () => {
      it('should handle callback and headers correctly', async () => {
        // Mock chat.completions.create method to return a readable stream
        const mockCreateMethod = vi
          .spyOn(instance['client'].chat.completions, 'create')
          .mockResolvedValue(
            new ReadableStream({
              start(controller) {
                controller.enqueue({
                  choices: [
                    { delta: { content: 'hello' }, finish_reason: null, index: 0, logprobs: null },
                  ],
                  created: 1_709_125_675,
                  id: 'chatcmpl-8xDx5AETP8mESQN7UB30GxTN2H1SO',
                  model: 'mistralai/mistral-7b-instruct:free',
                  object: 'chat.completion.chunk',
                  system_fingerprint: 'fp_86156a94a0',
                });
                controller.close();
              },
            }) as any,
          );

        // Prepare callback and headers
        const mockCallback: ChatStreamCallbacks = {
          onCompletion: vi.fn(),
          onStart: vi.fn(),
        };
        const mockHeaders = { 'Custom-Header': 'TestValue' };

        // Execute test
        const result = await instance.chat(createBasicChatPayload(), {
          callback: mockCallback,
          headers: mockHeaders,
        });

        // Verify callback is called
        await result.text(); // Ensure stream is consumed
        expect(mockCallback.onStart).toHaveBeenCalled();
        expect(mockCallback.onCompletion).toHaveBeenCalledWith({
          text: 'hello',
        });

        // Verify headers are correctly passed
        expect(result.headers.get('Custom-Header')).toEqual('TestValue');

        // Cleanup
        mockCreateMethod.mockRestore();
      });
    });

    it('should use custom stream handler when provided', async () => {
      // Create a custom stream handler that handles both ReadableStream and OpenAI Stream
      const customStreamHandler = vi.fn(
        (stream: ReadableStream | Stream<OpenAI.ChatCompletionChunk>, _options?: any) => {
          const readableStream =
            stream instanceof ReadableStream ? stream : stream.toReadableStream();
          return new ReadableStream({
            start(controller) {
              const reader = readableStream.getReader();
              const process = async () => {
                try {
                  while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    controller.enqueue(value);
                  }
                } finally {
                  controller.close();
                }
              };
              process();
            },
          });
        },
      );

      const LobeMockProvider = createOpenAICompatibleRuntime({
        baseURL: 'https://api.test.com/v1',
        chatCompletion: {
          handleStream: customStreamHandler,
        },
        provider: ModelProvider.OpenAI,
      });

      const instance = new LobeMockProvider({ apiKey: 'test' });

      // Create a mock stream
      const mockStream = new ReadableStream({
        start(controller) {
          controller.enqueue({
            choices: [{ delta: { content: 'Hello' }, index: 0 }],
            created: Date.now(),
            id: 'test-id',
            model: 'test-model',
            object: 'chat.completion.chunk',
          });
          controller.close();
        },
      });

      vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(mockStream as any);

      const payload: ChatStreamPayload = {
        messages: [{ content: 'Test', role: 'user' }],
        model: 'test-model',
        temperature: 0.7,
      };

      await instance.chat(payload);

      expect(customStreamHandler).toHaveBeenCalled();

      // Verify payload is passed to custom stream handler
      const handlerOptions = customStreamHandler.mock.calls[0][1];
      expect(handlerOptions.payload).toMatchObject({
        model: 'test-model',
        provider: ModelProvider.OpenAI,
      });
    });

    it('should use custom transform handler for non-streaming response', async () => {
      const customTransformHandler = vi.fn((data: OpenAI.ChatCompletion): ReadableStream => {
        return new ReadableStream({
          start(controller) {
            // Transform the completion to chunk format
            controller.enqueue({
              choices: data.choices.map((choice) => ({
                delta: { content: choice.message.content },
                index: choice.index,
              })),
              created: data.created,
              id: data.id,
              model: data.model,
              object: 'chat.completion.chunk',
            });
            controller.close();
          },
        });
      });

      const LobeMockProvider = createOpenAICompatibleRuntime({
        baseURL: 'https://api.test.com/v1',
        chatCompletion: {
          handleTransformResponseToStream: customTransformHandler,
        },
        provider: ModelProvider.OpenAI,
      });

      const instance = new LobeMockProvider({ apiKey: 'test' });

      const mockResponse: OpenAI.ChatCompletion = {
        choices: [
          {
            finish_reason: 'stop',
            index: 0,
            logprobs: null,
            message: {
              content: 'Test response',
              refusal: null,
              role: 'assistant',
            },
          },
        ],
        created: Date.now(),
        id: 'test-id',
        model: 'test-model',
        object: 'chat.completion',
        usage: { completion_tokens: 2, prompt_tokens: 1, total_tokens: 3 },
      };

      vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
        mockResponse as any,
      );

      const payload: ChatStreamPayload = {
        messages: [{ content: 'Test', role: 'user' }],
        model: 'test-model',
        stream: false,
        temperature: 0.7,
      };

      await instance.chat(payload);

      expect(customTransformHandler).toHaveBeenCalledWith(mockResponse);
    });

    describe('responses routing', () => {
      it(
        'should route to Responses API when chatCompletion.useResponse is true',
        { timeout: 10000 },
        async () => {
          const LobeMockProviderUseResponses = createOpenAICompatibleRuntime({
            baseURL: 'https://api.test.com/v1',
            chatCompletion: {
              useResponse: true,
            },
            provider: ModelProvider.OpenAI,
          });

          const inst = new LobeMockProviderUseResponses({ apiKey: 'test' });

          // Mock responses.create to return a proper stream-like object
          const mockResponsesCreate = vi
            .spyOn(inst['client'].responses, 'create')
            .mockResolvedValue(createClosedResponseSource() as any);

          // Mock getModelPricing to prevent async issues
          try {
            await inst.chat({
              messages: [{ content: 'hi', role: 'user' }],
              model: 'any-model',
              temperature: 0,
            });
          } catch {
            // Catch errors from incomplete mocking, we only care that responses.create was called
          }

          expect(mockResponsesCreate).toHaveBeenCalled();
        },
      );

      it('should replay encrypted reasoning scoped to the mapped upstream model', async () => {
        const Runtime = createOpenAICompatibleRuntime({
          baseURL: 'https://api.test.com/v1',
          chatCompletion: { useResponse: true },
          provider: 'mapped-provider',
        });
        const inst = new Runtime({
          apiKey: 'test',
          modelIdMapping: { 'logical-model': 'upstream-model' },
        });
        const create = vi
          .spyOn(inst['client'].responses, 'create')
          .mockResolvedValue(new ReadableStream() as any);
        const scope = await createOpenAIReasoningSignatureScope();

        await inst.chat({
          messages: [
            {
              content: 'Answer',
              reasoning: {
                content: 'Summary',
                signature: serializeScopedSignature(
                  'upstream-encrypted-content',
                  scope,
                  'reasoning',
                ),
              },
              role: 'assistant',
            },
          ],
          model: 'logical-model',
          temperature: 0,
        });

        const request = create.mock.calls[0][0];
        expect(request.model).toBe('upstream-model');
        expect(request.input?.[0]).toMatchObject({
          encrypted_content: 'upstream-encrypted-content',
          type: 'reasoning',
        });
      });

      it('should keep OpenRouter OpenAI slugs on chat completions for provider payload normalization', async () => {
        const LobeMockOpenRouter = createOpenAICompatibleRuntime({
          baseURL: 'https://openrouter.ai/api/v1',
          chatCompletion: {
            handlePayload: (payload) => {
              const { reasoning: _reasoning, thinking, ...rest } = payload;

              return {
                ...rest,
                ...(thinking?.type === 'disabled' && { reasoning: { enabled: false } }),
                stream: payload.stream ?? true,
              } as any;
            },
          },
          provider: ModelProvider.OpenRouter,
        });

        const inst = new LobeMockOpenRouter({ apiKey: 'test' });
        const chatSpy = vi
          .spyOn(inst['client'].chat.completions, 'create')
          .mockResolvedValue(new ReadableStream() as any);
        const responsesSpy = vi.spyOn(inst['client'].responses, 'create');

        await inst.chat({
          messages: [{ content: 'hi', role: 'user' }],
          model: 'openai/gpt-5.2',
          thinking: { type: 'disabled' },
        });

        expect(responsesSpy).not.toHaveBeenCalled();
        expect(chatSpy).toHaveBeenCalledWith(
          expect.objectContaining({
            model: 'openai/gpt-5.2',
            reasoning: { enabled: false },
            stream: true,
          }),
          expect.anything(),
        );
        expect(chatSpy.mock.calls[0][0]).not.toHaveProperty('thinking');
      });

      it(
        'should route to Responses API when model matches useResponseModels',
        { timeout: 10000 },
        async () => {
          const LobeMockProviderUseResponseModels = createOpenAICompatibleRuntime({
            baseURL: 'https://api.test.com/v1',
            chatCompletion: {
              useResponseModels: ['special-model', /special-\w+/],
            },
            provider: ModelProvider.OpenAI,
          });
          const inst = new LobeMockProviderUseResponseModels({ apiKey: 'test' });
          const spy = vi.spyOn(inst['client'].responses, 'create');
          // Prevent hanging by mocking normal chat completion stream
          vi.spyOn(inst['client'].chat.completions, 'create').mockResolvedValue(
            new ReadableStream() as any,
          );

          // First invocation: model contains the string
          spy.mockResolvedValueOnce(createClosedResponseSource() as any);
          try {
            await inst.chat({
              messages: [{ content: 'hi', role: 'user' }],
              model: 'prefix-special-model-suffix',
              temperature: 0,
            });
          } catch {
            // Catch errors from incomplete mocking
          }
          expect(spy).toHaveBeenCalledTimes(1);

          // Second invocation: model matches the RegExp
          spy.mockResolvedValueOnce(createClosedResponseSource() as any);
          try {
            await inst.chat({
              messages: [{ content: 'hi', role: 'user' }],
              model: 'special-xyz',
              temperature: 0,
            });
          } catch {
            // Catch errors from incomplete mocking
          }
          expect(spy).toHaveBeenCalledTimes(2);

          // Third invocation: model does not match any useResponseModels patterns
          try {
            await inst.chat({
              messages: [{ content: 'hi', role: 'user' }],
              model: 'unrelated-model',
              temperature: 0,
            });
          } catch {
            // Catch errors
          }
          expect(spy).toHaveBeenCalledTimes(2); // Ensure no additional calls were made
        },
      );
    });

    describe('DEBUG', () => {
      it('should call debugStream and return StreamingTextResponse when DEBUG_OPENROUTER_CHAT_COMPLETION is 1', async () => {
        // Arrange
        const mockProdStream = new ReadableStream() as any; // Mocked prod stream
        const mockDebugStream = new ReadableStream({
          start(controller) {
            controller.enqueue('Debug stream content');
            controller.close();
          },
        }) as any;
        mockDebugStream.toReadableStream = () => mockDebugStream; // Add toReadableStream method

        // Mock chat.completions.create return value, including mocked tee method
        (instance['client'].chat.completions.create as Mock).mockResolvedValue({
          tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
        });

        // Save original environment variable value
        const originalDebugValue = process.env.DEBUG_MOCKPROVIDER_CHAT_COMPLETION;

        // Mock environment variable
        process.env.DEBUG_MOCKPROVIDER_CHAT_COMPLETION = '1';
        vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());

        // Execute test
        // Run your test function, ensuring it calls debugStream when conditions are met
        // Hypothetical test function call, you may need to adjust based on actual situation
        await instance.chat(createBasicChatPayload());

        // Verify debugStream is called
        expect(debugStreamModule.debugStream).toHaveBeenCalled();

        // Restore original environment variable value
        process.env.DEBUG_MOCKPROVIDER_CHAT_COMPLETION = originalDebugValue;
      });
    });
  });

  describe('createImage', () => {
    beforeEach(() => {
      // Mock convertImageUrlToFile since it's already tested in openaiHelpers.test.ts
      vi.spyOn(openaiHelpers, 'convertImageUrlToFile').mockResolvedValue(
        new File(['mock-file-content'], 'test-image.jpg', { type: 'image/jpeg' }),
      );
    });

    describe('basic image generation', () => {
      it('should generate image successfully without imageUrls', async () => {
        const mockResponse = {
          data: [
            {
              b64_json:
                'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
            },
          ],
        };

        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'dall-e-3',
          params: {
            prompt: 'A beautiful sunset',
            quality: 'standard',
            size: '1024x1024',
          },
        };

        const result = await (instance as any).createImage(payload);

        expect(instance['client'].images.generate).toHaveBeenCalledWith({
          model: 'dall-e-3',
          prompt: 'A beautiful sunset',
          quality: 'standard',
          response_format: 'b64_json',
          size: '1024x1024',
        });

        expect(result).toEqual({
          imageUrl:
            'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
        });
      });

      it('should route mapped logical image-chat models through chat completions', async () => {
        const mappedInstance = new LobeMockProvider({
          apiKey: 'test',
          modelIdMapping: { 'logical-image-model:image': 'upstream-image-model' },
        });
        vi.spyOn(mappedInstance['client'].chat.completions, 'create').mockResolvedValue({
          choices: [
            {
              message: {
                images: [
                  {
                    image_url: {
                      url: 'data:image/png;base64,mapped-chat-image',
                    },
                  },
                ],
              },
            },
          ],
        } as any);
        vi.spyOn(mappedInstance['client'].images, 'generate').mockResolvedValue({} as any);

        const result = await (mappedInstance as any).createImage({
          model: 'logical-image-model:image',
          params: {
            prompt: 'A beautiful sunset',
          },
        });

        expect(mappedInstance['client'].chat.completions.create).toHaveBeenCalledWith(
          expect.objectContaining({ model: 'upstream-image-model' }),
        );
        expect(mappedInstance['client'].images.generate).not.toHaveBeenCalled();
        expect(result).toEqual({ imageUrl: 'data:image/png;base64,mapped-chat-image' });
      });

      it('should handle size auto parameter correctly', async () => {
        const mockResponse = {
          data: [{ b64_json: 'mock-base64-data' }],
        };

        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'dall-e-3',
          params: {
            prompt: 'A beautiful sunset',
            size: 'auto',
          },
        };

        await (instance as any).createImage(payload);

        // size: 'auto' should be removed from the options
        expect(instance['client'].images.generate).toHaveBeenCalledWith({
          model: 'dall-e-3',
          prompt: 'A beautiful sunset',
          response_format: 'b64_json',
        });
      });

      it('should not add response_format parameter for gpt-image-1 model', async () => {
        const mockResponse = {
          data: [{ b64_json: 'gpt-image-1-base64-data' }],
        };

        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'gpt-image-1',
          params: {
            prompt: 'A modern digital artwork',
            size: '1024x1024',
          },
        };

        const result = await (instance as any).createImage(payload);

        // gpt-image-1 model should not include response_format parameter
        expect(instance['client'].images.generate).toHaveBeenCalledWith({
          model: 'gpt-image-1',
          prompt: 'A modern digital artwork',
          size: '1024x1024',
        });

        expect(result).toEqual({
          imageUrl: 'data:image/png;base64,gpt-image-1-base64-data',
        });
      });
    });

    describe('image editing', () => {
      it('should edit image with single imageUrl', async () => {
        const mockResponse = {
          data: [{ b64_json: 'edited-image-base64' }],
        };

        vi.spyOn(instance['client'].images, 'edit').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'dall-e-2',
          params: {
            imageUrls: ['https://example.com/image1.jpg'],
            mask: 'https://example.com/mask.jpg',
            prompt: 'Add a rainbow to this image',
          },
        };

        const result = await (instance as any).createImage(payload);

        expect(openaiHelpers.convertImageUrlToFile).toHaveBeenCalledWith(
          'https://example.com/image1.jpg',
        );
        expect(instance['client'].images.edit).toHaveBeenCalledWith({
          image: expect.any(File),
          mask: 'https://example.com/mask.jpg',
          model: 'dall-e-2',
          prompt: 'Add a rainbow to this image',
          response_format: 'b64_json',
        });

        expect(result).toEqual({
          imageUrl: 'data:image/png;base64,edited-image-base64',
        });
      });

      it('should edit image with multiple imageUrls', async () => {
        const mockResponse = {
          data: [{ b64_json: 'edited-multiple-images-base64' }],
        };

        const mockFile1 = new File(['content1'], 'image1.jpg', { type: 'image/jpeg' });
        const mockFile2 = new File(['content2'], 'image2.jpg', { type: 'image/jpeg' });

        vi.mocked(openaiHelpers.convertImageUrlToFile)
          .mockResolvedValueOnce(mockFile1)
          .mockResolvedValueOnce(mockFile2);

        vi.spyOn(instance['client'].images, 'edit').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'dall-e-2',
          params: {
            imageUrls: ['https://example.com/image1.jpg', 'https://example.com/image2.jpg'],
            prompt: 'Merge these images',
          },
        };

        const result = await (instance as any).createImage(payload);

        expect(openaiHelpers.convertImageUrlToFile).toHaveBeenCalledTimes(2);
        expect(openaiHelpers.convertImageUrlToFile).toHaveBeenCalledWith(
          'https://example.com/image1.jpg',
        );
        expect(openaiHelpers.convertImageUrlToFile).toHaveBeenCalledWith(
          'https://example.com/image2.jpg',
        );

        expect(instance['client'].images.edit).toHaveBeenCalledWith({
          image: [mockFile1, mockFile2],
          model: 'dall-e-2',
          prompt: 'Merge these images',
          response_format: 'b64_json',
        });

        expect(result).toEqual({
          imageUrl: 'data:image/png;base64,edited-multiple-images-base64',
        });
      });

      it('should handle convertImageUrlToFile error', async () => {
        vi.mocked(openaiHelpers.convertImageUrlToFile).mockRejectedValue(
          new Error('Failed to download image'),
        );

        const payload = {
          model: 'dall-e-2',
          params: {
            imageUrls: ['https://invalid-url.com/image.jpg'],
            prompt: 'Edit this image',
          },
        };

        await expect((instance as any).createImage(payload)).rejects.toThrow(
          'Failed to convert image URLs to File objects: Error: Failed to download image',
        );
      });

      it('should include input_fidelity parameter for gpt-image-1 model', async () => {
        const mockResponse = {
          data: [{ b64_json: 'gpt-image-edited-base64' }],
        };

        const mockFile = new File(['content'], 'test-image.jpg', { type: 'image/jpeg' });

        vi.mocked(openaiHelpers.convertImageUrlToFile).mockResolvedValue(mockFile);
        vi.spyOn(instance['client'].images, 'edit').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'gpt-image-1',
          params: {
            imageUrl: 'https://example.com/image.jpg',
            prompt: 'Edit this image with gpt-image-1',
          },
        };

        const result = await (instance as any).createImage(payload);

        expect(instance['client'].images.edit).toHaveBeenCalledWith({
          image: expect.any(File),
          input_fidelity: 'high',
          model: 'gpt-image-1',
          prompt: 'Edit this image with gpt-image-1',
        });

        expect(result).toEqual({
          imageUrl: 'data:image/png;base64,gpt-image-edited-base64',
        });
      });

      it('should NOT send input_fidelity for gpt-image-2 (unsupported param)', async () => {
        const mockResponse = {
          data: [{ b64_json: 'gpt-image-2-edited-base64' }],
        };

        const mockFile = new File(['content'], 'test-image.jpg', { type: 'image/jpeg' });

        vi.mocked(openaiHelpers.convertImageUrlToFile).mockResolvedValue(mockFile);
        vi.spyOn(instance['client'].images, 'edit').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'gpt-image-2',
          params: {
            imageUrl: 'https://example.com/image.jpg',
            prompt: 'Edit this image with gpt-image-2',
          },
        };

        await (instance as any).createImage(payload);

        const editArgs = vi.mocked(instance['client'].images.edit).mock.calls[0][0];
        expect(editArgs).not.toHaveProperty('input_fidelity');
        expect(editArgs).toMatchObject({
          model: 'gpt-image-2',
        });
      });

      it.each([
        ['gpt-image-1.5', true],
        ['gpt-image-1-2026-01-15', true], // dated snapshot alias
        ['gpt-image-1.5-2026-03-01', true], // dated snapshot alias for the .5 variant
        ['gpt-image-1-mini', false], // mini tier explicitly excluded
        ['gpt-image-2', false], // gpt-image-2 dropped the param
        ['gpt-image-2-2026-04-21', false], // gpt-image-2 snapshot alias
      ])('should %s include input_fidelity for %s', async (model, shouldInclude) => {
        const mockResponse = { data: [{ b64_json: 'edited' }] };
        const mockFile = new File(['content'], 'test.jpg', { type: 'image/jpeg' });

        vi.mocked(openaiHelpers.convertImageUrlToFile).mockResolvedValue(mockFile);
        vi.spyOn(instance['client'].images, 'edit').mockResolvedValue(mockResponse as any);

        await (instance as any).createImage({
          model,
          params: { imageUrl: 'https://example.com/image.jpg', prompt: 'Edit' },
        });

        const editArgs = vi.mocked(instance['client'].images.edit).mock.calls[0][0];
        if (shouldInclude) {
          expect(editArgs).toMatchObject({ input_fidelity: 'high' });
        } else {
          expect(editArgs).not.toHaveProperty('input_fidelity');
        }
      });
    });

    describe('error handling', () => {
      it('should throw error when API response is invalid - no data', async () => {
        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue({} as any);

        const payload = createImagePayload();

        await expect((instance as any).createImage(payload)).rejects.toThrow(
          'Invalid image response: missing or empty data array',
        );
      });

      it('should throw error when API response is invalid - empty data array', async () => {
        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue({
          data: [],
        } as any);

        const payload = createImagePayload();

        await expect((instance as any).createImage(payload)).rejects.toThrow(
          'Invalid image response: missing or empty data array',
        );
      });

      it('should throw error when first data item is null', async () => {
        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue({
          data: [null],
        } as any);

        const payload = createImagePayload();

        await expect((instance as any).createImage(payload)).rejects.toThrow(
          'Invalid image response: first data item is null or undefined',
        );
      });

      it('should handle url format response successfully', async () => {
        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue({
          data: [{ url: 'https://example.com/generated-image.jpg' }],
        } as any);

        const payload = createImagePayload();

        const result = await (instance as any).createImage(payload);

        expect(result).toEqual({
          imageUrl: 'https://example.com/generated-image.jpg',
        });
      });

      it('should throw error when both b64_json and url are missing', async () => {
        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue({
          data: [{ some_other_field: 'value' }],
        } as any);

        const payload = createImagePayload();

        await expect((instance as any).createImage(payload)).rejects.toThrow(
          'Invalid image response: missing both b64_json and url fields',
        );
      });
    });

    describe('parameter mapping', () => {
      it('should map imageUrls parameter to image', async () => {
        const mockResponse = {
          data: [{ b64_json: 'test-base64' }],
        };

        vi.spyOn(instance['client'].images, 'edit').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'dall-e-2',
          params: {
            customParam: 'should remain unchanged',
            imageUrls: ['https://example.com/image.jpg'],
            prompt: 'Test prompt',
          },
        };

        await (instance as any).createImage(payload);

        expect(instance['client'].images.edit).toHaveBeenCalledWith({
          customParam: 'should remain unchanged',
          image: expect.any(File),
          model: 'dall-e-2',
          prompt: 'Test prompt',
          response_format: 'b64_json',
        });
      });

      it('should not inject `n` that the caller never sent', async () => {
        // Strict-schema OpenAI-compatible gateways (e.g. a custom provider fronting
        // flux-1-schnell) reject unknown root properties with
        // "Additional or unevaluated properties '/n' at '/' not allowed".
        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue({
          data: [{ url: 'https://example.com/flux.png' }],
        } as any);

        await (instance as any).createImage({
          model: 'flux-1-schnell',
          params: { prompt: 'A lighthouse at dusk', size: '1024x1024' },
        });

        expect(instance['client'].images.generate).toHaveBeenCalledWith({
          model: 'flux-1-schnell',
          prompt: 'A lighthouse at dusk',
          size: '1024x1024',
        });
      });

      it('should handle parameters without imageUrls', async () => {
        const mockResponse = {
          data: [{ b64_json: 'test-base64' }],
        };

        vi.spyOn(instance['client'].images, 'generate').mockResolvedValue(mockResponse as any);

        const payload = {
          model: 'dall-e-3',
          params: {
            prompt: 'Test prompt',
            quality: 'hd',
            style: 'vivid',
          },
        };

        await (instance as any).createImage(payload);

        expect(instance['client'].images.generate).toHaveBeenCalledWith({
          model: 'dall-e-3',
          prompt: 'Test prompt',
          quality: 'hd',
          response_format: 'b64_json',
          style: 'vivid',
        });
      });
    });
  });

  describe('generateObject', () => {
    it('should return parsed JSON object on successful API call', async () => {
      const mockResponse = {
        output_text: '{"name": "John", "age": 30}',
      };

      vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);

      const payload = {
        messages: [{ content: 'Generate a person object', role: 'user' as const }],
        model: 'gpt-4o',
        responseApi: true,
        schema: {
          description: 'Extract person information',
          name: 'person_extractor',
          schema: {
            properties: { age: { type: 'number' }, name: { type: 'string' } },
            type: 'object' as const,
          },
          strict: true,
        },
      };

      const result = await instance.generateObject(payload);

      expect(instance['client'].responses.create).toHaveBeenCalledWith(
        {
          input: payload.messages,
          model: payload.model,
          // @ts-ignore
          text: { format: { strict: true, type: 'json_schema', ...payload.schema } },
          safety_identifier: undefined,
        },
        { headers: undefined, signal: undefined },
      );

      expect(result).toEqual({ age: 30, name: 'John' });
    });

    it('should choose generateObject API by logical model while sending mapped model id', async () => {
      const Runtime = createOpenAICompatibleRuntime({
        baseURL: defaultBaseURL,
        generateObject: {
          useResponseModels: ['logical-response-model'],
        },
        provider: 'mapped-provider',
      });
      const runtime = new Runtime({
        apiKey: 'test',
        modelIdMapping: { 'logical-response-model': 'upstream-response-model' },
      });
      vi.spyOn(runtime['client'].responses, 'create').mockResolvedValue({
        output_text: '{"ok":true}',
      } as any);
      vi.spyOn(runtime['client'].chat.completions, 'create').mockResolvedValue({} as any);

      const result = await runtime.generateObject({
        messages: [{ content: 'Generate JSON', role: 'user' }],
        model: 'logical-response-model',
        schema: {
          name: 'result',
          schema: {
            properties: { ok: { type: 'boolean' } },
            type: 'object',
          },
        },
      });

      expect(runtime['client'].responses.create).toHaveBeenCalledWith(
        expect.objectContaining({ model: 'upstream-response-model' }),
        expect.anything(),
      );
      expect(runtime['client'].chat.completions.create).not.toHaveBeenCalled();
      expect(result).toEqual({ ok: true });
    });

    it('should map disabled thinking to no reasoning effort for GPT-5.4 Responses generateObject', async () => {
      const mockResponse = {
        output_text: '{"name": "John", "age": 30}',
      };

      vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);

      const payload = {
        messages: [{ content: 'Generate a person object', role: 'user' as const }],
        model: 'gpt-5.4-mini',
        schema: createPersonExtractorSchema(),
        thinking: { budget_tokens: 0, type: 'disabled' as const },
      };

      await instance.generateObject(payload);

      expect(instance['client'].responses.create).toHaveBeenCalledWith(
        expect.objectContaining({
          model: 'gpt-5.4-mini',
          reasoning: { effort: 'none' },
        }),
        expect.anything(),
      );
    });

    it('should normalize GPT-5 Pro-family Responses generateObject reasoning effort to high', async () => {
      const mockResponse = {
        output_text: '{"name": "John", "age": 30}',
      };

      vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);

      const payload = {
        messages: [{ content: 'Generate a person object', role: 'user' as const }],
        model: 'gpt-5.4-pro',
        reasoning_effort: 'medium' as const,
        schema: createPersonExtractorSchema(),
      };

      await instance.generateObject(payload);

      expect(instance['client'].responses.create).toHaveBeenCalledWith(
        expect.objectContaining({
          model: 'gpt-5.4-pro',
          reasoning: { effort: 'high' },
        }),
        expect.anything(),
      );
    });

    it('should handle options correctly', async () => {
      const mockResponse = {
        output_text: '{"status": "success"}',
      };

      vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);

      const payload = {
        messages: [{ content: 'Generate status', role: 'user' as const }],
        model: 'gpt-4o',
        responseApi: true,
        schema: {
          name: 'status_extractor',
          schema: { properties: { status: { type: 'string' } }, type: 'object' as const },
        },
      };

      const options = {
        headers: { 'Custom-Header': 'test-value' },
        signal: new AbortController().signal,
        user: 'test-user',
      };

      const result = await instance.generateObject(payload, options);

      expect(instance['client'].responses.create).toHaveBeenCalledWith(
        {
          input: payload.messages,
          model: payload.model,
          prompt_cache_key: 'lobe:test-user:gpt-4o',
          // @ts-ignore
          text: { format: { strict: true, type: 'json_schema', ...payload.schema } },
          safety_identifier: options.user,
        },
        { headers: options.headers, signal: options.signal },
      );

      expect(result).toEqual({ status: 'success' });
    });

    it('should add prompt_cache_key for OpenAI generateObject responses requests with user', async () => {
      const LobeOpenAIProvider = createOpenAICompatibleRuntime({
        baseURL: 'https://api.openai.com/v1',
        provider: ModelProvider.OpenAI,
      });

      const instance = new LobeOpenAIProvider({ apiKey: 'test' });
      const mockResponse = {
        output_text: '{"status": "success"}',
      };

      vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);

      const payload = {
        messages: [{ content: 'Generate status', role: 'user' as const }],
        model: 'gpt-4o',
        responseApi: true,
        schema: {
          name: 'status_extractor',
          schema: { properties: { status: { type: 'string' } }, type: 'object' as const },
        },
      };

      await instance.generateObject(payload, { user: 'testUser' });

      expect(instance['client'].responses.create).toHaveBeenCalledWith(
        expect.objectContaining({
          prompt_cache_key: 'lobe:testUser:gpt-4o',
        }),
        expect.anything(),
      );
    });

    it('should reject when JSON parsing fails', async () => {
      const mockResponse = {
        output_text: 'invalid json string',
      };

      vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);
      const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

      const payload = {
        messages: [{ content: 'Generate data', role: 'user' as const }],
        model: 'gpt-4o',
        responseApi: true,
        schema: createEmptyToolSchema(),
      };

      await expect(instance.generateObject(payload)).rejects.toMatchObject({
        name: 'StructuredOutputError',
      });
      expect(consoleSpy).not.toHaveBeenCalled();

      consoleSpy.mockRestore();
    });

    it('should handle empty response text', async () => {
      const mockResponse = {
        output_text: '',
      };

      vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);
      const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

      const payload = {
        messages: [{ content: 'Generate data', role: 'user' as const }],
        model: 'gpt-4o',
        responseApi: true,
        schema: createEmptyToolSchema(),
      };

      await expect(instance.generateObject(payload)).rejects.toMatchObject({
        name: 'StructuredOutputError',
      });
      expect(consoleSpy).not.toHaveBeenCalled();

      consoleSpy.mockRestore();
    });

    it('should handle complex nested JSON objects', async () => {
      const mockResponse = {
        output_text:
          '{"user": {"name": "Alice", "profile": {"age": 25, "preferences": ["music", "sports"]}}, "metadata": {"created": "2024-01-01"}}',
      };

      vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(mockResponse as any);

      const payload = {
        messages: [{ content: 'Generate complex user data', role: 'user' as const }],
        model: 'gpt-4o',
        responseApi: true,
        schema: {
          name: 'user_extractor',
          schema: {
            properties: {
              metadata: { type: 'object' },
              user: {
                properties: {
                  name: { type: 'string' },
                  profile: {
                    properties: {
                      age: { type: 'number' },
                      preferences: { items: { type: 'string' }, type: 'array' },
                    },
                    type: 'object',
                  },
                },
                type: 'object',
              },
            },
            type: 'object' as const,
          },
        },
      };

      const result = await instance.generateObject(payload);

      expect(result).toEqual({
        metadata: {
          created: '2024-01-01',
        },
        user: {
          name: 'Alice',
          profile: {
            age: 25,
            preferences: ['music', 'sports'],
          },
        },
      });
    });

    it('should propagate errors from responses API', async () => {
      const apiError = new Error('API Error: Invalid schema format');

      vi.spyOn(instance['client'].responses, 'create').mockRejectedValue(apiError);

      const payload = {
        messages: [{ content: 'Generate data', role: 'user' as const }],
        model: 'gpt-4o',
        responseApi: true,
        schema: createEmptyToolSchema(),
      };

      await expect(instance.generateObject(payload)).rejects.toThrow(
        'API Error: Invalid schema format',
      );
    });

    it('should detect ExceededContextWindow from responses API error message text', async () => {
      const apiError = new OpenAI.APIError(
        400,
        {
          error: {
            message:
              '400 Input tokens exceed the configured limit of 272000 tokens. Your messages resulted in 479832 tokens. Please reduce the length of the messages.',
          },
          status: 400,
        },
        'Error message',
        new Headers(),
      );

      vi.spyOn(instance['client'].responses, 'create').mockRejectedValue(apiError);

      const payload = {
        messages: [{ content: 'Generate data', role: 'user' as const }],
        model: 'gpt-5.4-mini',
        responseApi: true,
        schema: createEmptyToolSchema(),
      };

      await expect(instance.generateObject(payload)).rejects.toEqual({
        endpoint: defaultBaseURL,
        error: {
          error: {
            message:
              '400 Input tokens exceed the configured limit of 272000 tokens. Your messages resulted in 479832 tokens. Please reduce the length of the messages.',
          },
          status: 400,
        },
        errorType: AgentRuntimeErrorType.ExceededContextWindow,
        message: expect.any(String),
        provider,
      });
    });

    describe('chat completions API path', () => {
      it('should return parsed JSON object using chat completions API', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                content: '{"name": "Bob", "age": 25}',
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Generate a person object', role: 'user' as const }],
          model: 'gpt-4o',
          schema: createPersonExtractorSchema(),
          // responseApi: false or undefined - uses chat completions API
        };

        const result = await instance.generateObject(payload);

        expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
          {
            messages: payload.messages,
            model: payload.model,
            response_format: { json_schema: payload.schema, type: 'json_schema' },
            user: undefined,
          },
          { headers: undefined, signal: undefined },
        );

        expect(result).toEqual({ age: 25, name: 'Bob' });
      });

      it('should handle options correctly with chat completions API', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                content: '{"status": "completed"}',
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Generate status', role: 'user' as const }],
          model: 'gpt-4o',
          responseApi: false,
          schema: {
            name: 'status_extractor',
            schema: { properties: { status: { type: 'string' } }, type: 'object' as const },
          },
        };

        const options = {
          headers: { Authorization: 'Bearer token' },
          signal: new AbortController().signal,
          user: 'test-user-123',
        };

        const result = await instance.generateObject(payload, options);

        expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
          {
            messages: payload.messages,
            model: payload.model,
            prompt_cache_key: 'lobe:test-user-123:gpt-4o',
            response_format: { json_schema: payload.schema, type: 'json_schema' },
            user: options.user,
          },
          { headers: options.headers, signal: options.signal },
        );

        expect(result).toEqual({ status: 'completed' });
      });

      it('should add prompt_cache_key for OpenAI generateObject chat completion requests with user', async () => {
        const LobeOpenAIProvider = createOpenAICompatibleRuntime({
          baseURL: 'https://api.openai.com/v1',
          provider: ModelProvider.OpenAI,
        });

        const instance = new LobeOpenAIProvider({ apiKey: 'test' });
        const mockResponse = {
          choices: [
            {
              message: {
                content: '{"status": "completed"}',
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Generate status', role: 'user' as const }],
          model: 'gpt-4o',
          responseApi: false,
          schema: {
            name: 'status_extractor',
            schema: { properties: { status: { type: 'string' } }, type: 'object' as const },
          },
        };

        await instance.generateObject(payload, { user: 'testUser' });

        expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
          expect.objectContaining({
            prompt_cache_key: 'lobe:testUser:gpt-4o',
          }),
          expect.anything(),
        );
      });

      it('should reject when JSON parsing fails with chat completions API', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                content: 'This is not valid JSON',
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );
        const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

        const payload = {
          messages: [{ content: 'Generate data', role: 'user' as const }],
          model: 'gpt-4o',
          responseApi: false,
          schema: createEmptyToolSchema(),
        };

        await expect(instance.generateObject(payload)).rejects.toMatchObject({
          name: 'StructuredOutputError',
        });
        expect(consoleSpy).not.toHaveBeenCalled();

        consoleSpy.mockRestore();
      });

      it('should handle empty string content from chat completions API', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                content: '',
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );
        const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

        const payload = {
          messages: [{ content: 'Generate data', role: 'user' as const }],
          model: 'gpt-4o',
          responseApi: false,
          schema: createEmptyToolSchema(),
        };

        await expect(instance.generateObject(payload)).rejects.toMatchObject({
          name: 'StructuredOutputError',
        });
        expect(consoleSpy).not.toHaveBeenCalled();

        consoleSpy.mockRestore();
      });

      it('should handle complex arrays with chat completions API', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                content:
                  '{"items": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}], "total": 2}',
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Generate items list', role: 'user' as const }],
          model: 'gpt-4o',
          schema: {
            name: 'abc',
            schema: {
              properties: {
                items: {
                  items: {
                    properties: {
                      id: { type: 'number' },
                      name: { type: 'string' },
                    },
                    type: 'object',
                  },
                  type: 'array',
                },
                total: { type: 'number' },
              },
              type: 'object' as const,
            },
          },
        };

        const result = await instance.generateObject(payload);

        expect(result).toEqual({
          items: [
            { id: 1, name: 'Item 1' },
            { id: 2, name: 'Item 2' },
          ],
          total: 2,
        });
      });

      it('should propagate errors from chat completions API', async () => {
        const apiError = new Error('API Error: Rate limit exceeded');

        vi.spyOn(instance['client'].chat.completions, 'create').mockRejectedValue(apiError);

        const payload = {
          messages: [{ content: 'Generate data', role: 'user' as const }],
          model: 'gpt-4o',
          responseApi: false,
          schema: { name: 'abc', schema: { type: 'object' } as any },
        };

        await expect(instance.generateObject(payload)).rejects.toThrow(
          'API Error: Rate limit exceeded',
        );
      });
    });

    describe('tools parameter support', () => {
      it('preserves structured-output errors when a provider wraps generic errors', async () => {
        const handleError = vi.fn((error: any) => ({ error }));
        const Runtime = createOpenAICompatibleRuntime({
          provider: 'wrapped-provider',
          chatCompletion: { handleError },
        });
        const runtime = new Runtime({ apiKey: 'test' });
        vi.spyOn(runtime['client'].chat.completions, 'create').mockResolvedValue({
          choices: [],
        } as any);
        await expect(
          runtime.generateObject({
            messages: [{ role: 'user', content: 'Return a result' }],
            model: 'test-model',
            tools: [
              { type: 'function', function: { name: 'result', parameters: { type: 'object' } } },
            ],
          }),
        ).rejects.toMatchObject({
          name: 'StructuredOutputError',
          message: 'Invalid structured output: no tool calls returned',
        });
        expect(handleError).not.toHaveBeenCalled();
      });

      it.each([
        ['missing choices', {}, 'no tool calls'],
        ['empty choices', { choices: [] }, 'no tool calls'],
        ['missing message', { choices: [{}] }, 'no tool calls'],
        ['missing tools', { choices: [{ message: {} }] }, 'no tool calls'],
        ['empty tools', { choices: [{ message: { tool_calls: [] } }] }, 'no tool calls'],
        [
          'invalid JSON',
          {
            choices: [
              { message: { tool_calls: [{ function: { name: 'result', arguments: '{broken' } }] } },
            ],
          },
          'invalid JSON',
        ],
        [
          'null arguments',
          {
            choices: [
              { message: { tool_calls: [{ function: { name: 'result', arguments: 'null' } }] } },
            ],
          },
          'JSON object',
        ],
      ])(
        'rejects %s with an actionable structured-output error',
        async (_label, response, reason) => {
          vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
            response as any,
          );
          await expect(
            instance.generateObject({
              messages: [{ content: 'Return a result', role: 'user' }],
              model: 'test-model',
              tools: [
                { type: 'function', function: { name: 'result', parameters: { type: 'object' } } },
              ],
            }),
          ).rejects.toThrow(`Invalid structured output: ${reason}`);
        },
      );

      it.each([
        ['missing output', {}, 'no tool calls'],
        ['empty output', { output: [] }, 'no tool calls'],
        ['text output', { output: [{ type: 'message' }] }, 'no tool calls'],
        [
          'invalid JSON',
          { output: [{ type: 'function_call', name: 'result', arguments: '{broken' }] },
          'invalid JSON',
        ],
      ])('rejects Responses API %s', async (_label, response, reason) => {
        vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(response as any);
        await expect(
          instance.generateObject({
            messages: [{ content: 'Return a result', role: 'user' }],
            model: 'test-model',
            responseApi: true,
            tools: [
              { type: 'function', function: { name: 'result', parameters: { type: 'object' } } },
            ],
          }),
        ).rejects.toThrow(`Invalid structured output: ${reason}`);
      });

      it('should handle tools parameter with multiple tools', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                tool_calls: [
                  {
                    function: {
                      arguments: '{"city":"Tokyo","unit":"celsius"}',
                      name: 'get_weather',
                    },
                    type: 'function' as const,
                  },
                  {
                    function: {
                      arguments: '{"timezone":"Asia/Tokyo"}',
                      name: 'get_time',
                    },
                    type: 'function' as const,
                  },
                ],
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'What is the weather and time in Tokyo?', role: 'user' as const }],
          model: 'gpt-4o',
          tools: [
            {
              function: {
                description: 'Get weather information',
                name: 'get_weather',
                parameters: {
                  properties: {
                    city: { type: 'string' },
                    unit: { type: 'string' },
                  },
                  required: ['city'],
                  type: 'object' as const,
                },
              },
              type: 'function' as const,
            },
            {
              function: {
                description: 'Get current time',
                name: 'get_time',
                parameters: {
                  properties: {
                    timezone: { type: 'string' },
                  },
                  required: ['timezone'],
                  type: 'object' as const,
                },
              },
              type: 'function' as const,
            },
          ],
        };

        const result = await instance.generateObject(payload);

        expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
          {
            messages: payload.messages,
            model: payload.model,
            tool_choice: 'required',
            tools: [
              {
                function: {
                  description: 'Get weather information',
                  name: 'get_weather',
                  parameters: {
                    properties: {
                      city: { type: 'string' },
                      unit: { type: 'string' },
                    },
                    required: ['city'],
                    type: 'object',
                  },
                },
                type: 'function',
              },
              {
                function: {
                  description: 'Get current time',
                  name: 'get_time',
                  parameters: {
                    properties: {
                      timezone: { type: 'string' },
                    },
                    required: ['timezone'],
                    type: 'object',
                  },
                },
                type: 'function',
              },
            ],
            user: undefined,
          },
          { headers: undefined, signal: undefined },
        );

        expect(result).toEqual([
          { arguments: { city: 'Tokyo', unit: 'celsius' }, name: 'get_weather' },
          { arguments: { timezone: 'Asia/Tokyo' }, name: 'get_time' },
        ]);
      });

      it('should handle tools parameter with systemRole', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                tool_calls: [
                  {
                    function: {
                      arguments: '{"result":8}',
                      name: 'calculate',
                    },
                    type: 'function' as const,
                  },
                ],
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Add 5 and 3', role: 'user' as const }],
          model: 'gpt-4o',
          tools: [
            {
              function: {
                description: 'Perform calculation',
                name: 'calculate',
                parameters: {
                  properties: {
                    result: { type: 'number' },
                  },
                  required: ['result'],
                  type: 'object' as const,
                },
              },
              type: 'function' as const,
            },
          ],
        };

        const result = await instance.generateObject(payload);

        expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
          expect.objectContaining({
            messages: [{ content: 'Add 5 and 3', role: 'user' }],
          }),
          expect.any(Object),
        );

        expect(result).toEqual([{ arguments: { result: 8 }, name: 'calculate' }]);
      });

      it('should throw error when neither tools nor schema is provided', async () => {
        const payload = {
          messages: [{ content: 'Generate data', role: 'user' as const }],
          model: 'gpt-4o',
        };

        await expect(instance.generateObject(payload as any)).rejects.toThrow(
          'tools or schema is required',
        );
      });
    });

    describe('handleSchema option', () => {
      let instanceWithSchemaHandler: any;
      const mockSchemaHandler = vi.fn((schema: any) => {
        const filtered: any = {};
        for (const [key, value] of Object.entries(schema)) {
          if (key !== 'maxLength' && key !== 'pattern') {
            filtered[key] = value;
          }
        }
        return filtered;
      });

      beforeEach(() => {
        mockSchemaHandler.mockClear();
        const RuntimeClass = createOpenAICompatibleRuntime({
          baseURL: 'https://api.test.com',
          generateObject: {
            handleSchema: mockSchemaHandler,
          },
          provider: 'test-provider',
        });

        instanceWithSchemaHandler = new RuntimeClass({ apiKey: 'test-key' });
      });

      it('should apply schema transformation with Responses API', async () => {
        const mockResponse = {
          output_text: '{"name":"Alice","age":30}',
        };

        vi.spyOn(instanceWithSchemaHandler['client'].responses, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Extract person', role: 'user' as const }],
          model: 'gpt-4o',
          responseApi: true,
          schema: createConstrainedPersonSchema(),
        };

        await instanceWithSchemaHandler.generateObject(payload);

        expect(mockSchemaHandler).toHaveBeenCalledWith(payload.schema.schema);
        expect(instanceWithSchemaHandler['client'].responses.create).toHaveBeenCalledWith(
          expect.objectContaining({
            text: expect.objectContaining({
              format: expect.objectContaining({
                schema: {
                  properties: {
                    age: { type: 'number' },
                    name: { type: 'string' },
                  },
                  type: 'object',
                },
              }),
            }),
          }),
          expect.any(Object),
        );
      });

      it('should apply schema transformation with Chat Completions API', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                content: '{"name":"Bob","age":25}',
              },
            },
          ],
        };

        vi.spyOn(instanceWithSchemaHandler['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Extract person', role: 'user' as const }],
          model: 'test-model',
          schema: createConstrainedPersonSchema(),
        };

        await instanceWithSchemaHandler.generateObject(payload);

        expect(mockSchemaHandler).toHaveBeenCalledWith(payload.schema.schema);
        expect(instanceWithSchemaHandler['client'].chat.completions.create).toHaveBeenCalledWith(
          expect.objectContaining({
            response_format: expect.objectContaining({
              json_schema: expect.objectContaining({
                schema: {
                  properties: {
                    age: { type: 'number' },
                    name: { type: 'string' },
                  },
                  type: 'object',
                },
              }),
            }),
          }),
          expect.any(Object),
        );
      });

      it('should apply schema transformation with tool calling fallback', async () => {
        const RuntimeClass = createOpenAICompatibleRuntime({
          baseURL: 'https://api.test.com',
          generateObject: {
            handleSchema: mockSchemaHandler,
            useToolsCalling: true,
          },
          provider: 'test-provider',
        });

        const instance = new RuntimeClass({ apiKey: 'test-key' });

        const mockResponse = {
          choices: [
            {
              message: {
                tool_calls: [
                  {
                    function: {
                      arguments: '{"name":"Charlie","age":35}',
                      name: 'person',
                    },
                    type: 'function' as const,
                  },
                ],
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Extract person', role: 'user' as const }],
          model: 'test-model',
          schema: createConstrainedPersonSchema(),
        };

        await instance.generateObject(payload);

        expect(mockSchemaHandler).toHaveBeenCalledWith(payload.schema.schema);
        expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
          expect.objectContaining({
            tools: [
              expect.objectContaining({
                function: expect.objectContaining({
                  parameters: {
                    properties: {
                      age: { type: 'number' },
                      name: { type: 'string' },
                    },
                    type: 'object',
                  },
                }),
              }),
            ],
          }),
          expect.any(Object),
        );
      });

      it('should not apply schema transformation when handleSchema is not configured', async () => {
        const RuntimeClass = createOpenAICompatibleRuntime({
          baseURL: 'https://api.test.com',
          provider: 'test-provider',
        });

        const instance = new RuntimeClass({ apiKey: 'test-key' });

        const mockResponse = {
          choices: [
            {
              message: {
                content: '{"name":"Test"}',
              },
            },
          ],
        };

        vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Extract data', role: 'user' as const }],
          model: 'test-model',
          schema: {
            name: 'test',
            schema: {
              maxLength: 100,
              properties: {
                name: { type: 'string' },
              },
              type: 'object' as const,
            },
          },
        };

        await instance.generateObject(payload);

        expect(instance['client'].chat.completions.create).toHaveBeenCalledWith(
          expect.objectContaining({
            response_format: expect.objectContaining({
              json_schema: expect.objectContaining({
                schema: {
                  maxLength: 100,
                  properties: {
                    name: { type: 'string' },
                  },
                  type: 'object',
                },
              }),
            }),
          }),
          expect.any(Object),
        );
      });

      it('should preserve original schema properties while filtering', async () => {
        const mockResponse = {
          output_text: '{"result":"success"}',
        };

        vi.spyOn(instanceWithSchemaHandler['client'].responses, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Test', role: 'user' as const }],
          model: 'gpt-4o',
          responseApi: true,
          schema: {
            description: 'Test schema',
            name: 'test',
            schema: {
              description: 'Inner schema description',
              maxLength: 100,
              pattern: '^test$',
              properties: {
                result: { type: 'string' },
              },
              required: ['result'],
              type: 'object' as const,
            },
            strict: true,
          },
        };

        await instanceWithSchemaHandler.generateObject(payload);

        expect(mockSchemaHandler).toHaveBeenCalledWith(payload.schema.schema);
        expect(instanceWithSchemaHandler['client'].responses.create).toHaveBeenCalledWith(
          expect.objectContaining({
            text: expect.objectContaining({
              format: expect.objectContaining({
                description: 'Test schema',
                name: 'test',
                schema: {
                  description: 'Inner schema description',
                  properties: {
                    result: { type: 'string' },
                  },
                  required: ['result'],
                  type: 'object',
                },
                strict: true,
              }),
            }),
          }),
          expect.any(Object),
        );
      });
    });

    describe('tool calling fallback', () => {
      let instanceWithToolCalling: any;

      beforeEach(() => {
        const RuntimeClass = createOpenAICompatibleRuntime({
          baseURL: 'https://api.test.com',
          generateObject: {
            useToolsCalling: true,
          },
          provider: 'test-provider',
        });

        instanceWithToolCalling = new RuntimeClass({ apiKey: 'test-key' });
      });

      it('should use tool calling when configured', async () => {
        const mockResponse = createPersonToolResponse();

        vi.spyOn(instanceWithToolCalling['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Extract person info', role: 'user' as const }],
          model: 'test-model',
          schema: {
            description: 'Extract person information',
            name: 'person_extractor',
            schema: {
              properties: { age: { type: 'number' }, name: { type: 'string' } },
              type: 'object' as const,
            },
          },
        };

        const result = await instanceWithToolCalling.generateObject(payload);

        expect(instanceWithToolCalling['client'].chat.completions.create).toHaveBeenCalledWith(
          {
            messages: payload.messages,
            model: payload.model,
            tool_choice: { function: { name: 'person_extractor' }, type: 'function' },
            tools: [
              {
                function: {
                  description: 'Extract person information',
                  name: 'person_extractor',
                  parameters: payload.schema.schema,
                },
                type: 'function',
              },
            ],
            user: undefined,
          },
          { headers: undefined, signal: undefined },
        );

        // The fallback returns the parsed schema object, same shape as the
        // json_schema path
        expect(result).toEqual({ age: 28, name: 'Alice' });
      });

      it('should not forward internal thinking to generic OpenAI-compatible generateObject requests', async () => {
        const mockResponse = createPersonToolResponse();

        vi.spyOn(instanceWithToolCalling['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Extract person info', role: 'user' as const }],
          model: 'deepseek-v4-pro',
          reasoning_effort: 'high' as const,
          schema: createPersonExtractorSchema(),
          thinking: { budget_tokens: 0, type: 'disabled' as const },
        };

        await instanceWithToolCalling.generateObject(payload);

        const requestPayload =
          instanceWithToolCalling['client'].chat.completions.create.mock.calls[0]![0];
        expect(requestPayload).toEqual(
          expect.objectContaining({
            model: 'deepseek-v4-pro',
          }),
        );
        expect(requestPayload).not.toHaveProperty('thinking');
        expect(requestPayload).not.toHaveProperty('reasoning_effort');
      });

      it('should reject when no tool call found', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                content: 'Some text response',
              },
            },
          ],
        };

        vi.spyOn(instanceWithToolCalling['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );
        const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

        const payload = {
          messages: [{ content: 'Generate data', role: 'user' as const }],
          model: 'test-model',
          schema: createEmptyToolSchema(),
        };

        await expect(instanceWithToolCalling.generateObject(payload)).rejects.toThrow(
          'Invalid structured output: no tool calls',
        );
        expect(consoleSpy).not.toHaveBeenCalled();

        consoleSpy.mockRestore();
      });

      it('should reject when tool call arguments parsing fails', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                tool_calls: [
                  {
                    function: {
                      arguments: 'invalid json',
                      name: 'test_tool',
                    },
                    type: 'function' as const,
                  },
                ],
              },
            },
          ],
        };

        vi.spyOn(instanceWithToolCalling['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );
        const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

        const payload = {
          messages: [{ content: 'Generate data', role: 'user' as const }],
          model: 'test-model',
          schema: createEmptyToolSchema(),
        };

        await expect(instanceWithToolCalling.generateObject(payload)).rejects.toThrow(
          'Invalid structured output: invalid JSON',
        );
        expect(consoleSpy).not.toHaveBeenCalled();

        consoleSpy.mockRestore();
      });

      it('should handle options correctly with tool calling', async () => {
        const mockResponse = {
          choices: [
            {
              message: {
                tool_calls: [
                  {
                    function: {
                      arguments: '{"data":"test"}',
                      name: 'data_extractor',
                    },
                    type: 'function' as const,
                  },
                ],
              },
            },
          ],
        };

        vi.spyOn(instanceWithToolCalling['client'].chat.completions, 'create').mockResolvedValue(
          mockResponse as any,
        );

        const payload = {
          messages: [{ content: 'Extract data', role: 'user' as const }],
          model: 'test-model',
          schema: {
            name: 'data_extractor',
            schema: { properties: { data: { type: 'string' } }, type: 'object' as const },
          },
        };

        const options = {
          headers: { 'X-Custom': 'header' },
          signal: new AbortController().signal,
          user: 'test-user',
        };

        const result = await instanceWithToolCalling.generateObject(payload, options);

        expect(instanceWithToolCalling['client'].chat.completions.create).toHaveBeenCalledWith(
          expect.any(Object),
          { headers: options.headers, signal: options.signal },
        );

        expect(result).toEqual({ data: 'test' });
      });
    });
  });

  describe('models', () => {
    it('should get models with third party model list', async () => {
      vi.spyOn(instance['client'].models, 'list').mockResolvedValue({
        data: [
          { created: 1_698_218_177, id: 'gpt-4o', object: 'model' },
          { id: 'us.anthropic.claude-3-7-sonnet-20250219-v1:0', object: 'model' },
          { created: 1_698_318_177 * 1000, id: 'gpt-4o-mini', object: 'model' },
          { created: 1_736_499_509_125, id: 'gemini', object: 'model' },
        ],
      } as any);

      const list = await instance.models();

      expect(list).toEqual([
        {
          abilities: {
            functionCall: true,
            vision: true,
          },
          config: {
            deploymentName: 'gpt-4o',
          },
          contextWindowTokens: 128_000,
          description:
            'ChatGPT-4o is a dynamic model that updates in real time to stay current. It combines strong language understanding and generation, suitable for large-scale applications such as customer support, education, and technical support.',
          displayName: 'GPT-4o',
          enabled: true,
          family: 'gpt',
          generation: 'gpt-4o',
          id: 'gpt-4o',
          knowledgeCutoff: '2023-10',
          maxOutput: 4096,
          pricing: {
            units: [
              {
                name: 'textInput_cacheRead',
                rate: 1.25,
                strategy: 'fixed',
                unit: 'millionTokens',
              },
              {
                name: 'textInput',
                rate: 2.5,
                strategy: 'fixed',
                unit: 'millionTokens',
              },
              {
                name: 'textOutput',
                rate: 10,
                strategy: 'fixed',
                unit: 'millionTokens',
              },
            ],
          },
          providerId: 'azure',
          releasedAt: '2024-05-13',
          source: 'builtin',
          type: 'chat',
        },
        {
          abilities: {
            functionCall: true,
            reasoning: true,
            structuredOutput: true,
            vision: true,
          },
          contextWindowTokens: 200_000,
          description:
            "Claude 3.7 Sonnet is Anthropic's fastest next-gen model. Compared to Claude 3 Haiku, it improves across skills and surpasses the previous flagship Claude 3 Opus on many intelligence benchmarks.",
          displayName: 'Claude 3.7 Sonnet',
          enabled: false,
          family: 'claude-sonnet',
          generation: 'claude-3.7',
          id: 'us.anthropic.claude-3-7-sonnet-20250219-v1:0',
          knowledgeCutoff: '2024-10',
          maxOutput: 64_000,
          pricing: {
            units: [
              {
                name: 'textInput',
                rate: 3,
                strategy: 'fixed',
                unit: 'millionTokens',
              },
              {
                name: 'textOutput',
                rate: 15,
                strategy: 'fixed',
                unit: 'millionTokens',
              },
            ],
          },
          providerId: 'bedrock',
          releasedAt: '2025-02-24',
          settings: {
            extendParams: ['disableContextCaching', 'enableReasoning', 'reasoningBudgetToken'],
          },
          source: 'builtin',
          type: 'chat',
        },
        {
          abilities: {
            functionCall: true,
            vision: true,
          },
          config: {
            deploymentName: 'gpt-4o-mini',
          },
          contextWindowTokens: 128_000,
          description:
            'GPT-4o Mini is a small, efficient model with performance similar to GPT-4o.',
          displayName: 'GPT 4o Mini',
          enabled: false,
          family: 'gpt',
          generation: 'gpt-4o',
          id: 'gpt-4o-mini',
          knowledgeCutoff: '2023-10',
          maxOutput: 4096,
          pricing: {
            units: [
              {
                name: 'textInput_cacheRead',
                rate: 0.075,
                strategy: 'fixed',
                unit: 'millionTokens',
              },
              {
                name: 'textInput',
                rate: 0.15,
                strategy: 'fixed',
                unit: 'millionTokens',
              },
              {
                name: 'textOutput',
                rate: 0.6,
                strategy: 'fixed',
                unit: 'millionTokens',
              },
            ],
          },
          providerId: 'azure',
          releasedAt: '2023-10-26',
          source: 'builtin',
          type: 'chat',
        },
        {
          id: 'gemini',
          releasedAt: '2025-01-10',
          type: 'chat',
        },
      ]);
    });
  });

  describe('createVideo completion mode', () => {
    it('should default to polling and strip callback URLs', async () => {
      const createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-1' });
      const Runtime = createOpenAICompatibleRuntime({
        createVideo,
        provider: 'video-provider',
      });
      const runtime = new Runtime({ apiKey: 'test' });

      await expect(
        createVideoWithCompletionMode(
          runtime,
          {
            callbackUrl: 'https://example.com/webhook',
            model: 'video-model',
            params: { prompt: 'A cat' },
          },
          { preferredCompletionMode: 'webhook' },
        ),
      ).resolves.toEqual({
        completionMode: 'polling',
        inferenceId: 'video-1',
      });
      expect(createVideo).toHaveBeenCalledWith(
        {
          model: 'video-model',
          params: { prompt: 'A cat' },
        },
        expect.any(Object),
      );
    });

    it('should use webhook mode for a webhook-only runtime', async () => {
      const createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-2' });
      const Runtime = createOpenAICompatibleRuntime({
        createVideo,
        provider: 'webhook-video-provider',
        videoGenerationCapabilities: { completionModes: ['webhook'] },
      });
      const runtime = new Runtime({ apiKey: 'test' });
      const payload = {
        callbackUrl: 'https://example.com/webhook',
        model: 'video-model',
        params: { prompt: 'A cat' },
      };

      await expect(createVideoWithCompletionMode(runtime, payload)).resolves.toEqual({
        completionMode: 'webhook',
        inferenceId: 'video-2',
      });
      expect(createVideo).toHaveBeenCalledWith(payload, expect.any(Object));
    });

    it('should resolve model capabilities using the mapped upstream model', async () => {
      const createVideo = vi.fn().mockResolvedValue({ inferenceId: 'video-3' });
      const resolveCapabilities = vi
        .fn()
        .mockReturnValue({ completionModes: ['polling'] as const });
      const Runtime = createOpenAICompatibleRuntime({
        createVideo,
        provider: 'mapped-video-provider',
        videoGenerationCapabilities: resolveCapabilities,
      });
      const runtime = new Runtime({
        apiKey: 'test',
        modelIdMapping: { 'logical-video-model': 'upstream-video-model' },
      });

      await createVideoWithCompletionMode(runtime, {
        model: 'logical-video-model',
        params: { prompt: 'A cat' },
      });

      expect(resolveCapabilities).toHaveBeenCalledWith('upstream-video-model');
    });
  });

  describe('transcribe', () => {
    it('should report token usage of token-billed transcription models', async () => {
      vi.spyOn(instance['client'].audio.transcriptions, 'create').mockResolvedValue({
        text: 'hello world',
        usage: { input_tokens: 151, output_tokens: 0, total_tokens: 151 },
      } as any);
      const onUsage = vi.fn();

      const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
      await instance.transcribe!({ file, model: 'gpt-4o-transcribe' }, { onUsage });

      expect(onUsage).toHaveBeenCalledWith(
        expect.objectContaining({ inputAudioTokens: 151, totalInputTokens: 151 }),
      );
    });

    it('should not report usage for duration-billed transcription models', async () => {
      vi.spyOn(instance['client'].audio.transcriptions, 'create').mockResolvedValue({
        text: 'hello world',
        usage: { seconds: 6, type: 'duration' },
      } as any);
      const onUsage = vi.fn();

      const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });
      await instance.transcribe!({ file, model: 'whisper-1' }, { onUsage });

      expect(onUsage).not.toHaveBeenCalled();
    });

    it('should transcribe audio and return the text', async () => {
      const transcribeMock = vi
        .spyOn(instance['client'].audio.transcriptions, 'create')
        .mockResolvedValue({ text: 'hello world' } as any);

      const file = new File([new Uint8Array([1, 2, 3])], 'speech.mp3', { type: 'audio/mpeg' });

      const result = await instance.transcribe!({ file, model: 'whisper-1' });

      expect(result).toEqual({ text: 'hello world' });
      expect(transcribeMock).toHaveBeenCalledWith(
        expect.objectContaining({ file, model: 'whisper-1' }),
        expect.anything(),
      );
    });

    it('should forward language, prompt and responseFormat to the provider', async () => {
      const transcribeMock = vi
        .spyOn(instance['client'].audio.transcriptions, 'create')
        .mockResolvedValue({ text: '你好' } as any);

      const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });

      await instance.transcribe!(
        {
          file,
          language: 'zh',
          model: 'whisper-1',
          prompt: 'hint',
          responseFormat: 'verbose_json',
        },
        { signal: new AbortController().signal },
      );

      expect(transcribeMock).toHaveBeenCalledWith(
        expect.objectContaining({
          file,
          language: 'zh',
          model: 'whisper-1',
          prompt: 'hint',
          response_format: 'verbose_json',
        }),
        expect.objectContaining({ signal: expect.any(AbortSignal) }),
      );
    });

    it('should wrap a bare Blob into a File using fileName', async () => {
      const transcribeMock = vi
        .spyOn(instance['client'].audio.transcriptions, 'create')
        .mockResolvedValue({ text: 'ok' } as any);

      const blob = new Blob([new Uint8Array([1, 2, 3])], { type: 'audio/wav' });

      await instance.transcribe!({ file: blob, fileName: 'remote.wav', model: 'whisper-1' });

      const passedFile = (transcribeMock.mock.calls[0][0] as any).file as File;
      expect(passedFile).toBeInstanceOf(File);
      expect(passedFile.name).toBe('remote.wav');
    });

    it('should throw an error when transcription fails', async () => {
      vi.spyOn(instance['client'].audio.transcriptions, 'create').mockRejectedValue(
        new Error('boom'),
      );

      const file = new File([new Uint8Array([1, 2, 3])], 'speech.mp3', { type: 'audio/mpeg' });

      await expect(instance.transcribe!({ file, model: 'whisper-1' })).rejects.toBeDefined();
    });
  });
});

describe('schema response JSON fences', () => {
  it.each([false, true])('accepts one JSON fence through responseApi=%s', async (responseApi) => {
    const Runtime = createOpenAICompatibleRuntime({ provider: ModelProvider.OpenAI });
    const runtime = new Runtime({ apiKey: 'test' });
    const text = 'Analysis summary.\n```json\n{"ready":true}\n```';
    if (responseApi) {
      vi.spyOn(runtime['client'].responses, 'create').mockResolvedValue({
        output_text: text,
      } as any);
    } else {
      vi.spyOn(runtime['client'].chat.completions, 'create').mockResolvedValue({
        choices: [{ message: { content: text } }],
      } as any);
    }
    await expect(
      runtime.generateObject({
        model: 'gpt-4o',
        responseApi,
        messages: [{ role: 'user', content: 'Return ready' }],
        schema: {
          name: 'ready',
          schema: { type: 'object', properties: { ready: { type: 'boolean' } } },
        },
      }),
    ).resolves.toEqual({ ready: true });
  });
});