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.

51.1 KB
Raw Blame
// @vitest-environment node
import {
  InvokeModelCommand,
  InvokeModelWithResponseStreamCommand,
} from '@aws-sdk/client-bedrock-runtime';
import { ModelProvider } from 'model-bank';
import type { Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { createReadableStream } from '../../core/streams/utils';
import { AgentRuntimeErrorType } from '../../types/error';
import type { ModelRuntimeDiagnostics } from '../../types/providerDiagnostics';
import * as debugStreamModule from '../../utils/debugStream';
import { experimental_buildLlama2Prompt, LobeBedrockAI } from './index';

const loadModelsMock = vi.hoisted(() => vi.fn().mockResolvedValue([]));

// Mock the console.error to avoid polluting test output
vi.spyOn(console, 'error').mockImplementation(() => {});

vi.mock('@lobechat/business-model-bank/model-config', () => ({
  loadModels: loadModelsMock,
}));

vi.mock('@aws-sdk/client-bedrock-runtime', async (importOriginal) => {
  const module = await importOriginal();
  return {
    ...(module as any),
    InvokeModelCommand: vi.fn(),
    InvokeModelWithResponseStreamCommand: vi.fn(),
  };
});

let instance: LobeBedrockAI;

beforeEach(() => {
  instance = new LobeBedrockAI({
    region: 'us-west-2',
    accessKeyId: 'test-access-key-id',
    accessKeySecret: 'test-access-key-secret',
  });

  vi.spyOn(instance['client'], 'send').mockReturnValue(new ReadableStream() as any);
});

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

describe('LobeBedrockAI', () => {
  describe('init', () => {
    it('should correctly initialize with AWS credentials', async () => {
      const instance = new LobeBedrockAI({
        region: 'us-west-2',
        accessKeyId: 'test-access-key-id',
        accessKeySecret: 'test-access-key-secret',
      });
      expect(instance).toBeInstanceOf(LobeBedrockAI);
      expect(instance.region).toBe('us-west-2');
    });

    it('should use default region if not provided', () => {
      const instance = new LobeBedrockAI({
        accessKeyId: 'test-access-key-id',
        accessKeySecret: 'test-access-key-secret',
      });
      expect(instance.region).toBe('us-east-1');
    });

    it('should correctly initialize with session token', () => {
      const instance = new LobeBedrockAI({
        region: 'us-west-2',
        accessKeyId: 'test-access-key-id',
        accessKeySecret: 'test-access-key-secret',
        sessionToken: 'test-session-token',
      });
      expect(instance).toBeInstanceOf(LobeBedrockAI);
    });

    it('should correctly initialize with API key authentication', async () => {
      const instance = new LobeBedrockAI({
        apiKey: 'test-bedrock-api-key',
        region: 'us-west-2',
      });

      expect(instance).toBeInstanceOf(LobeBedrockAI);
      expect(instance.region).toBe('us-west-2');
      await expect(instance['client'].config.authSchemePreference()).resolves.toEqual([
        'httpBearerAuth',
      ]);
      await expect(instance['client'].config.token?.()).resolves.toEqual({
        token: 'test-bedrock-api-key',
      });
    });
    it('should throw InvalidBedrockCredentials if accessKeyId is missing', () => {
      expect(() => {
        new LobeBedrockAI({
          accessKeySecret: 'test-access-key-secret',
        });
      }).toThrow(
        expect.objectContaining({
          errorType: AgentRuntimeErrorType.InvalidBedrockCredentials,
        }),
      );
    });

    it('should throw InvalidBedrockCredentials if accessKeySecret is missing', () => {
      expect(() => {
        new LobeBedrockAI({
          accessKeyId: 'test-access-key-id',
        });
      }).toThrow(
        expect.objectContaining({
          errorType: AgentRuntimeErrorType.InvalidBedrockCredentials,
        }),
      );
    });

    it('should throw InvalidBedrockCredentials if both credentials are missing', () => {
      expect(() => {
        new LobeBedrockAI({});
      }).toThrow(
        expect.objectContaining({
          errorType: AgentRuntimeErrorType.InvalidBedrockCredentials,
        }),
      );
    });
  });

  describe('chat', () => {
    it('should call invokeLlamaModel when model starts with "meta"', async () => {
      // @ts-ignore
      const spy = vi.spyOn(instance, 'invokeLlamaModel');

      // Act
      await instance.chat({
        messages: [{ content: 'Hello', role: 'user' }],
        model: 'meta.llama:1',
        temperature: 0,
      });

      // Assert
      expect(spy).toHaveBeenCalled();
    });

    it('should call invokeClaudeModel when model does not start with "meta"', async () => {
      // @ts-ignore
      const spy = vi.spyOn(instance, 'invokeClaudeModel');

      // Act
      await instance.chat({
        messages: [{ content: 'Hello', role: 'user' }],
        model: 'anthropic.claude-v2:1',
        temperature: 0,
      });

      // Assert
      expect(spy).toHaveBeenCalled();
    });

    describe('Claude model', () => {
      it('should return a Response on successful API call', async () => {
        const result = await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'anthropic.claude-v2:1',
          temperature: 0,
        });

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

      it('captures decoded Bedrock events before protocol transformation', async () => {
        const providerChunks = [
          { generation: '', generation_token_count: 1 },
          { generation: '', generation_token_count: 1, stop_reason: 'stop' },
        ];
        (instance['client'].send as Mock).mockResolvedValue({
          $metadata: { httpStatusCode: 200, requestId: 'request-1' },
          body: {
            async *[Symbol.asyncIterator]() {
              for (const chunk of providerChunks) {
                yield { chunk: { bytes: new TextEncoder().encode(JSON.stringify(chunk)) } };
              }
            },
          },
        });
        const diagnostics: ModelRuntimeDiagnostics = {};

        const response = await instance.chat(
          {
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'meta.llama:1',
          },
          { diagnostics },
        );
        await response.text();

        expect(diagnostics.providerResponse).toMatchObject({
          apiMode: 'bedrock_llama',
          rawEvents: providerChunks,
          requestId: 'request-1',
          status: 200,
          stopReason: 'stop',
          terminalEventReceived: true,
        });
      });

      it('should handle text messages correctly', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        // Act
        const result = await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'anthropic.claude-v2:1',
          temperature: 0,
          top_p: 1,
        });

        // Assert
        expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
          accept: 'application/json',
          body: JSON.stringify({
            anthropic_version: 'bedrock-2023-05-31',
            max_tokens: 4096,
            messages: [
              {
                content: [
                  {
                    cache_control: { type: 'ephemeral' },
                    text: 'Hello',
                    type: 'text',
                  },
                ],
                role: 'user',
              },
            ],
            temperature: 0,
            top_p: 1,
          }),
          contentType: 'application/json',
          modelId: 'anthropic.claude-v2:1',
        });
        expect(result).toBeInstanceOf(Response);
      });

      it('should drop assistant prefill for Claude Opus 4.7', async () => {
        const mockStream = createReadableStream(['Hello, world!']);
        (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));

        await instance.chat({
          messages: [
            { content: 'Continue this answer', role: 'user' },
            { content: 'Partial assistant draft', role: 'assistant' },
          ],
          model: 'global.anthropic.claude-opus-4-7',
        });

        const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock
          .calls[0][0];
        const body = JSON.parse(commandInput.body);

        expect(body.messages).toEqual([
          {
            content: 'Continue this answer',
            role: 'user',
          },
        ]);
      });

      it('should drop ALL stacked trailing assistant messages', async () => {
        const mockStream = createReadableStream(['Hello, world!']);
        (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));

        // Failed-run placeholder rows can stack several assistant turns at the
        // payload tail; popping only one still triggers the prefill 400.
        await instance.chat({
          messages: [
            { content: 'Continue this answer', role: 'user' },
            { content: '...', role: 'assistant' },
            { content: '...', role: 'assistant' },
          ],
          model: 'global.anthropic.claude-opus-5',
        });

        const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock
          .calls[0][0];
        const body = JSON.parse(commandInput.body);

        expect(body.messages).toEqual([
          {
            content: 'Continue this answer',
            role: 'user',
          },
        ]);
      });

      it('should omit disabled thinking when the mapped Bedrock id always thinks', async () => {
        // Sonnet 5 accepts `disabled`; a channel redirect to Sonnet 5.5 rejects it with a 400.
        const mappedInstance = new LobeBedrockAI({
          accessKeyId: 'test-access-key-id',
          accessKeySecret: 'test-access-key-secret',
          modelIdMapping: { 'claude-sonnet-5': 'global.anthropic.claude-sonnet-5-5' },
          region: 'us-west-2',
        });
        const mockStream = createReadableStream(['Hello, world!']);
        vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(
          Promise.resolve(mockStream) as any,
        );

        await mappedInstance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'claude-sonnet-5',
          thinking: { type: 'disabled' },
        } as any);

        const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock
          .calls[0][0];
        expect(commandInput.modelId).toBe('global.anthropic.claude-sonnet-5-5');
        expect(JSON.parse(commandInput.body)).not.toHaveProperty('thinking');
      });

      it('should drop assistant prefill when a logical id maps to a Claude 5 Bedrock id', async () => {
        // The channel modelIdMapping resolves the actually-sent Bedrock model
        // id; the prefill guard must follow it, not the logical id.
        const mappedInstance = new LobeBedrockAI({
          accessKeyId: 'test-access-key-id',
          accessKeySecret: 'test-access-key-secret',
          modelIdMapping: { 'my-router-model': 'global.anthropic.claude-opus-5' },
          region: 'us-west-2',
        });
        const mockStream = createReadableStream(['Hello, world!']);
        vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(
          Promise.resolve(mockStream) as any,
        );

        await mappedInstance.chat({
          messages: [
            { content: 'Continue this answer', role: 'user' },
            { content: '...', role: 'assistant' },
          ],
          model: 'my-router-model',
        });

        const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock
          .calls[0][0];
        expect(commandInput.modelId).toBe('global.anthropic.claude-opus-5');
        expect(JSON.parse(commandInput.body).messages).toEqual([
          { content: 'Continue this answer', role: 'user' },
        ]);
      });

      it('should convert Claude assistant reasoning signatures to thinking content', async () => {
        const mockStream = createReadableStream(['Hello, world!']);
        (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));

        await instance.chat({
          messages: [
            { content: 'Hello', role: 'user' },
            {
              content: 'Here is my response.',
              model: 'claude-opus-4-7',
              reasoning: {
                content: 'Let me think about this...',
                signature: 'EuYBCkQYAiJAHnHRJG4nPBrdTlo6CmXoyE8WYoQ=',
              },
              role: 'assistant',
            } as any,
            { content: 'Continue', role: 'user' },
          ],
          model: 'anthropic.claude-sonnet-4-20250514-v1:0',
        });

        const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock
          .calls[0][0];
        const body = JSON.parse(commandInput.body);

        expect(body.messages[1]).toEqual({
          content: [
            {
              signature: 'EuYBCkQYAiJAHnHRJG4nPBrdTlo6CmXoyE8WYoQ=',
              thinking: 'Let me think about this...',
              type: 'thinking',
            },
            { text: 'Here is my response.', type: 'text' },
          ],
          role: 'assistant',
        });
      });

      it('should not convert non-Claude reasoning signatures to thinking content', async () => {
        const mockStream = createReadableStream(['Hello, world!']);
        (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));

        await instance.chat({
          messages: [
            { content: 'Hello', role: 'user' },
            {
              content: 'Here is my response.',
              model: 'deepseek-v4-pro',
              provider: 'lobehub',
              reasoning: {
                content: 'DeepSeek reasoning',
                signature: '340acffe-0000-4000-8000-000000000000',
              },
              role: 'assistant',
            } as any,
            { content: 'Continue', role: 'user' },
          ],
          model: 'anthropic.claude-sonnet-4-20250514-v1:0',
        });

        const commandInput = (InvokeModelWithResponseStreamCommand as unknown as Mock).mock
          .calls[0][0];
        const body = JSON.parse(commandInput.body);

        expect(body.messages[1]).toEqual({
          content: 'Here is my response.',
          role: 'assistant',
        });
      });

      it('should handle system prompt correctly', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        // Act
        const result = await instance.chat({
          messages: [
            { content: 'You are an awesome greeter', role: 'system' },
            { content: 'Hello', role: 'user' },
          ],
          model: 'anthropic.claude-v2:1',
          temperature: 0,
          top_p: 1,
        });

        // Assert
        expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
          accept: 'application/json',
          body: JSON.stringify({
            anthropic_version: 'bedrock-2023-05-31',
            max_tokens: 4096,
            messages: [
              {
                content: [
                  {
                    cache_control: { type: 'ephemeral' },
                    text: 'Hello',
                    type: 'text',
                  },
                ],
                role: 'user',
              },
            ],
            system: [
              {
                cache_control: { type: 'ephemeral' },
                text: 'You are an awesome greeter',
                type: 'text',
              },
            ],
            temperature: 0,
            top_p: 1,
          }),
          contentType: 'application/json',
          modelId: 'anthropic.claude-v2:1',
        });
        expect(result).toBeInstanceOf(Response);
      });

      it('should call Anthropic model with supported opions', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        // Act
        const result = await instance.chat({
          max_tokens: 2048,
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'anthropic.claude-v2:1',
          temperature: 0.5,
          top_p: 1,
        });

        // Assert
        expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
          accept: 'application/json',
          body: JSON.stringify({
            anthropic_version: 'bedrock-2023-05-31',
            max_tokens: 2048,
            messages: [
              {
                content: [
                  {
                    cache_control: { type: 'ephemeral' },
                    text: 'Hello',
                    type: 'text',
                  },
                ],
                role: 'user',
              },
            ],
            temperature: 0.25,
            top_p: 1,
          }),
          contentType: 'application/json',
          modelId: 'anthropic.claude-v2:1',
        });
        expect(result).toBeInstanceOf(Response);
      });

      it('should handle tools parameter', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        const tools = [
          {
            function: {
              description: 'Get weather information',
              name: 'get_weather',
              parameters: {
                properties: {
                  location: {
                    description: 'City name',
                    type: 'string',
                  },
                },
                required: ['location'],
                type: 'object',
              },
            },
            type: 'function' as const,
          },
        ];

        // Act
        await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'anthropic.claude-v2:1',
          temperature: 0.5,
          tools,
        });

        // Assert
        const callArgs = (InvokeModelWithResponseStreamCommand as any as Mock).mock.calls[0][0];
        const bodyContent = JSON.parse(callArgs.body);
        expect(bodyContent.tools).toBeDefined();
      });

      it('should use default max_tokens when not provided', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        // Act
        await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'anthropic.claude-v2:1',
          temperature: 0,
        });

        // Assert
        expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
          accept: 'application/json',
          body: JSON.stringify({
            anthropic_version: 'bedrock-2023-05-31',
            max_tokens: 4096,
            messages: [
              {
                content: [
                  {
                    cache_control: { type: 'ephemeral' },
                    text: 'Hello',
                    type: 'text',
                  },
                ],
                role: 'user',
              },
            ],
            temperature: 0,
          }),
          contentType: 'application/json',
          modelId: 'anthropic.claude-v2:1',
        });
      });

      it('should call Anthropic model without unsupported opions', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        // Act
        const result = await instance.chat({
          frequency_penalty: 0.5, // Unsupported option
          max_tokens: 2048,
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'anthropic.claude-v2:1',
          presence_penalty: 0.5,
          temperature: 0.5,
          top_p: 1,
        });

        // Assert
        expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
          accept: 'application/json',
          body: JSON.stringify({
            anthropic_version: 'bedrock-2023-05-31',
            max_tokens: 2048,
            messages: [
              {
                content: [
                  {
                    cache_control: { type: 'ephemeral' },
                    text: 'Hello',
                    type: 'text',
                  },
                ],
                role: 'user',
              },
            ],
            temperature: 0.25,
            top_p: 1,
          }),
          contentType: 'application/json',
          modelId: 'anthropic.claude-v2:1',
        });
        expect(result).toBeInstanceOf(Response);
      });

      it('should call debugStream when DEBUG_BEDROCK_CHAT_COMPLETION is set to "1"', async () => {
        // Arrange
        process.env.DEBUG_BEDROCK_CHAT_COMPLETION = '1';
        const spy = vi.spyOn(debugStreamModule, 'debugStream');

        // Act
        await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'anthropic.claude-v2:1',
          temperature: 0,
        });

        // Assert
        expect(spy).toHaveBeenCalled();

        // Clean up
        delete process.env.DEBUG_BEDROCK_CHAT_COMPLETION;
      });

      describe('Parameter conflict handling for Claude 4+ models', () => {
        it('should forward effort and visible thinking when Claude Opus 5 uses default adaptive thinking', async () => {
          const mockStream = createReadableStream(['Hello, world!']);
          (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));

          await instance.chat({
            effort: 'xhigh',
            max_tokens: 64_000,
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'global.anthropic.claude-opus-5',
          });

          const commandInput = (
            InvokeModelWithResponseStreamCommand as unknown as Mock
          ).mock.calls.at(-1)?.[0];
          const body = JSON.parse(commandInput.body);

          expect(body).toEqual({
            anthropic_version: 'bedrock-2023-05-31',
            max_tokens: 64_000,
            messages: [
              {
                content: [
                  {
                    cache_control: { type: 'ephemeral' },
                    text: 'Hello',
                    type: 'text',
                  },
                ],
                role: 'user',
              },
            ],
            output_config: { effort: 'xhigh' },
            // Opus 5 thinks even without a `thinking` config, and defaults `display` to
            // `omitted` — without this the reasoning comes back empty.
            thinking: { display: 'summarized', type: 'adaptive' },
          });
        });

        it('should forward disabled thinking without effort for Claude Opus 5', async () => {
          const mockStream = createReadableStream(['Hello, world!']);
          (instance['client'].send as Mock).mockResolvedValue(Promise.resolve(mockStream));

          await instance.chat({
            effort: 'xhigh',
            max_tokens: 64_000,
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'global.anthropic.claude-opus-5',
            thinking: { budget_tokens: 0, type: 'disabled' },
          });

          const commandInput = (
            InvokeModelWithResponseStreamCommand as unknown as Mock
          ).mock.calls.at(-1)?.[0];
          const body = JSON.parse(commandInput.body);

          expect(body).toEqual({
            anthropic_version: 'bedrock-2023-05-31',
            max_tokens: 64_000,
            messages: [
              {
                content: [
                  {
                    cache_control: { type: 'ephemeral' },
                    text: 'Hello',
                    type: 'text',
                  },
                ],
                role: 'user',
              },
            ],
            thinking: { type: 'disabled' },
          });
        });

        [
          {
            caseName:
              'should send only temperature for Claude 4+ models when both temperature and top_p are provided',
            input: {
              model: 'anthropic.claude-opus-4-1-20250805-v1:0',
              temperature: 0.8,
              top_p: 0.9,
            },
            expectedMaxTokens: 64_000,
            expectedModel: 'anthropic.claude-opus-4-1-20250805-v1:0',
            expectedSampling: { temperature: 0.4 },
          },
          {
            caseName:
              'should send only top_p for Claude 4+ models when temperature is not provided',
            input: { model: 'anthropic.claude-sonnet-4-20250514-v1:0', top_p: 0.9 },
            expectedMaxTokens: 64_000,
            expectedModel: 'anthropic.claude-sonnet-4-20250514-v1:0',
            expectedSampling: { top_p: 0.9 },
          },
          {
            caseName: 'should send both temperature and top_p for non-Claude-4+ models',
            input: {
              model: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
              temperature: 0.8,
              top_p: 0.9,
            },
            expectedMaxTokens: 8192,
            expectedModel: 'anthropic.claude-3-5-sonnet-20241022-v2:0',
            expectedSampling: { temperature: 0.4, top_p: 0.9 },
          },
          {
            caseName: 'should handle US region Claude 4+ model IDs correctly',
            input: {
              model: 'us.anthropic.claude-sonnet-4-5-20250929-v1:0',
              temperature: 0.6,
              top_p: 0.8,
            },
            expectedMaxTokens: 64_000,
            expectedModel: 'us.anthropic.claude-sonnet-4-5-20250929-v1:0',
            expectedSampling: { temperature: 0.3 },
          },
          {
            caseName: 'should handle standard Claude 4+ model IDs (non-Bedrock format)',
            input: { model: 'claude-opus-4-1', temperature: 0.7, top_p: 0.95 },
            expectedMaxTokens: 64_000,
            expectedModel: 'claude-opus-4-1',
            expectedSampling: { temperature: 0.35 },
          },
        ].forEach(({ caseName, input, expectedMaxTokens, expectedModel, expectedSampling }) => {
          it(caseName, async () => {
            // Arrange
            const mockStream = createReadableStream(['Hello, world!']);
            const mockResponse = Promise.resolve(mockStream);
            (instance['client'].send as Mock).mockResolvedValue(mockResponse);

            // Act
            await instance.chat({
              messages: [{ content: 'Hello', role: 'user' }],
              ...input,
            });

            // Assert
            expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
              accept: 'application/json',
              body: JSON.stringify({
                anthropic_version: 'bedrock-2023-05-31',
                max_tokens: expectedMaxTokens,
                messages: [
                  {
                    content: [
                      {
                        cache_control: { type: 'ephemeral' },
                        text: 'Hello',
                        type: 'text',
                      },
                    ],
                    role: 'user',
                  },
                ],
                ...expectedSampling,
              }),
              contentType: 'application/json',
              modelId: expectedModel,
            });
          });
        });

        it('should resolve Claude model IDs from channel modelIdMapping', async () => {
          // Arrange
          const mappedInstance = new LobeBedrockAI({
            region: 'us-east-1',
            accessKeyId: 'test-access-key-id',
            accessKeySecret: 'test-access-key-secret',
            modelIdMapping: {
              'claude-opus-4-8': 'us.anthropic.claude-opus-4-8',
            },
          });
          const mockStream = createReadableStream(['Hello, world!']);
          const mockResponse = Promise.resolve(mockStream);
          vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(mockResponse as any);

          // Act
          await mappedInstance.chat({
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'claude-opus-4-8',
            temperature: 0.7,
          });

          // Assert
          expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith(
            expect.objectContaining({
              modelId: 'us.anthropic.claude-opus-4-8',
            }),
          );
        });
      });

      it('should handle errors and throw AgentRuntimeError', async () => {
        // Arrange
        const errorMessage = 'An error occurred';
        const errorMetadata = { statusCode: 500 };
        const mockError = new Error(errorMessage);
        (mockError as any).$metadata = errorMetadata;
        (instance['client'].send as Mock).mockRejectedValue(mockError);

        // Act & Assert
        await expect(
          instance.chat({
            max_tokens: 100,
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'anthropic.claude-v2:1',
            temperature: 0,
          }),
        ).rejects.toThrow(
          expect.objectContaining({
            error: {
              body: errorMetadata,
              message: errorMessage,
              type: 'Error',
            },
            errorType: AgentRuntimeErrorType.ProviderBizError,
            provider: ModelProvider.Bedrock,
            region: 'us-west-2',
          }),
        );
      });

      it('should throw ExceededContextWindow when error message indicates context window exceeded', async () => {
        const errorMessage =
          'Too many input tokens. Max input tokens for this model is 200000, but 250000 were provided.';
        const errorMetadata = { statusCode: 400 };
        const mockError = new Error(errorMessage);
        (mockError as any).$metadata = errorMetadata;
        (instance['client'].send as Mock).mockRejectedValue(mockError);

        await expect(
          instance.chat({
            max_tokens: 100,
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'anthropic.claude-v2:1',
            temperature: 0,
          }),
        ).rejects.toThrow(
          expect.objectContaining({
            errorType: AgentRuntimeErrorType.ExceededContextWindow,
            provider: ModelProvider.Bedrock,
          }),
        );
      });
    });

    describe('Llama Model', () => {
      it('should return a Response on successful API call', async () => {
        const result = await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'meta.llama:1',
          temperature: 0,
        });

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

      it('should call Llama model with valid payload', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        // Act
        const result = await instance.chat({
          temperature: 0,
          max_tokens: 100,
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'meta.llama:1',
        });

        // Assert
        expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
          accept: 'application/json',
          body: JSON.stringify({
            max_gen_len: 100,
            prompt: '<s>[INST] Hello [/INST]',
          }),
          contentType: 'application/json',
          modelId: 'meta.llama:1',
        });
        expect(result).toBeInstanceOf(Response);
      });

      it('should handle errors and throw AgentRuntimeError', async () => {
        // Arrange
        const errorMessage = 'An error occurred';
        const errorMetadata = { statusCode: 500 };
        const mockError = new Error(errorMessage);
        (mockError as any).$metadata = errorMetadata;
        (instance['client'].send as Mock).mockRejectedValue(mockError);

        // Act & Assert
        await expect(
          instance.chat({
            max_tokens: 100,
            messages: [{ content: 'Hello', role: 'user' }],
            model: 'meta.llama:1',
            temperature: 0,
          }),
        ).rejects.toThrow(
          expect.objectContaining({
            error: {
              body: errorMetadata,
              message: errorMessage,
              region: 'us-west-2',
              type: 'Error',
            },
            errorType: AgentRuntimeErrorType.ProviderBizError,
            provider: ModelProvider.Bedrock,
            region: 'us-west-2',
          }),
        );
      });

      it('should call debugStream when DEBUG_BEDROCK_CHAT_COMPLETION is set to "1"', async () => {
        // Arrange
        process.env.DEBUG_BEDROCK_CHAT_COMPLETION = '1';
        const spy = vi.spyOn(debugStreamModule, 'debugStream');

        // Act
        await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'meta.llama:1',
          temperature: 0,
        });

        // Assert
        expect(spy).toHaveBeenCalled();

        // Clean up
        delete process.env.DEBUG_BEDROCK_CHAT_COMPLETION;
      });

      it('should use default max_tokens (400) when not provided', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        // Act
        await instance.chat({
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'meta.llama:1',
          temperature: 0,
        });

        // Assert
        expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
          accept: 'application/json',
          body: JSON.stringify({
            max_gen_len: 400,
            prompt: '<s>[INST] Hello [/INST]',
          }),
          contentType: 'application/json',
          modelId: 'meta.llama:1',
        });
      });

      it('should handle system message in Llama prompt', async () => {
        // Arrange
        const mockStream = createReadableStream(['Hello, world!']);
        const mockResponse = Promise.resolve(mockStream);
        (instance['client'].send as Mock).mockResolvedValue(mockResponse);

        // Act
        await instance.chat({
          messages: [
            { content: 'You are a helpful assistant', role: 'system' },
            { content: 'Hello', role: 'user' },
          ],
          model: 'meta.llama2-70b-chat-v1',
          temperature: 0,
        });

        // Assert
        expect(InvokeModelWithResponseStreamCommand).toHaveBeenCalledWith({
          accept: 'application/json',
          body: JSON.stringify({
            max_gen_len: 400,
            prompt: '<s>[INST] <<SYS>>\nYou are a helpful assistant\n<</SYS>>\n\nHello [/INST]',
          }),
          contentType: 'application/json',
          modelId: 'meta.llama2-70b-chat-v1',
        });
      });
    });

    it('should call options.callback when provided', async () => {
      // Arrange
      const onStart = vi.fn();

      // Act
      await instance.chat(
        {
          messages: [{ content: 'Hello', role: 'user' }],
          model: 'anthropic.claude-v2:1',
          temperature: 0,
        },
        { callback: { onStart } },
      );

      // Assert
      expect(onStart).toHaveBeenCalled();
    });
  });

  describe('generateObject', () => {
    it('should generate a schema object through Anthropic tool use', async () => {
      const mockResponse = {
        body: new TextEncoder().encode(
          JSON.stringify({
            content: [
              {
                input: { summary: 'Done', title: 'Task summary' },
                name: 'task_topic_handoff',
                type: 'tool_use',
              },
            ],
            usage: {
              cache_creation_input_tokens: 0,
              cache_read_input_tokens: 0,
              input_tokens: 100,
              output_tokens: 50,
            },
          }),
        ),
      };
      const abortController = new AbortController();
      const onUsage = vi.fn();
      const sendSpy = vi.spyOn(instance['client'], 'send').mockResolvedValue(mockResponse as any);

      const result = await instance.generateObject(
        {
          messages: [
            { content: 'You create compact summaries.', role: 'system' },
            { content: 'Summarize this task topic.', role: 'user' },
          ],
          model: 'global.anthropic.claude-sonnet-4-6',
          schema: {
            name: 'task_topic_handoff',
            schema: {
              additionalProperties: false,
              properties: {
                summary: { type: 'string' },
                title: { type: 'string' },
              },
              required: ['title', 'summary'],
              type: 'object',
            },
            strict: true,
          },
        },
        { onUsage, signal: abortController.signal },
      );

      const commandInput = (InvokeModelCommand as unknown as Mock).mock.calls[0][0];
      const body = JSON.parse(commandInput.body);

      expect(result).toEqual({ summary: 'Done', title: 'Task summary' });
      expect(commandInput.modelId).toBe('global.anthropic.claude-sonnet-4-6');
      expect(body).toEqual({
        anthropic_version: 'bedrock-2023-05-31',
        max_tokens: 64_000,
        messages: [{ content: 'Summarize this task topic.', role: 'user' }],
        system: [{ text: 'You create compact summaries.', type: 'text' }],
        tool_choice: { name: 'task_topic_handoff', type: 'tool' },
        tools: [
          {
            description: 'Generate structured output according to the provided schema',
            input_schema: {
              additionalProperties: false,
              properties: {
                summary: { type: 'string' },
                title: { type: 'string' },
              },
              required: ['title', 'summary'],
              type: 'object',
            },
            name: 'task_topic_handoff',
          },
        ],
      });
      expect(body.tools[0]).not.toHaveProperty('strict');
      expect(sendSpy).toHaveBeenCalledWith(expect.any(InvokeModelCommand), {
        abortSignal: abortController.signal,
      });
      expect(onUsage).toHaveBeenCalledWith(
        expect.objectContaining({
          inputCacheMissTokens: 100,
          totalInputTokens: 100,
          totalOutputTokens: 50,
          totalTokens: 150,
        }),
      );
    });

    it('should resolve generateObject model IDs from channel modelIdMapping', async () => {
      const mappedInstance = new LobeBedrockAI({
        region: 'us-east-1',
        accessKeyId: 'test-access-key-id',
        accessKeySecret: 'test-access-key-secret',
        modelIdMapping: {
          'claude-opus-4-8': 'us.anthropic.claude-opus-4-8',
        },
      });
      const mockResponse = {
        body: new TextEncoder().encode(
          JSON.stringify({
            content: [
              {
                input: { title: 'Mapped' },
                name: 'mapped_schema',
                type: 'tool_use',
              },
            ],
          }),
        ),
      };
      vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(mockResponse as any);

      await mappedInstance.generateObject({
        messages: [{ content: 'Create a title.', role: 'user' }],
        model: 'claude-opus-4-8',
        schema: {
          name: 'mapped_schema',
          schema: {
            additionalProperties: false,
            properties: {
              title: { type: 'string' },
            },
            required: ['title'],
            type: 'object',
          },
          strict: true,
        },
      });

      const commandInput = (InvokeModelCommand as unknown as Mock).mock.calls.at(-1)?.[0];
      expect(commandInput.modelId).toBe('us.anthropic.claude-opus-4-8');
    });

    it('should drop assistant prefill in generateObject when a logical id maps to Claude 5', async () => {
      // The prefill guard must follow the resolved Bedrock model id, not the
      // logical alias the channel mapping hides it behind.
      const mappedInstance = new LobeBedrockAI({
        accessKeyId: 'test-access-key-id',
        accessKeySecret: 'test-access-key-secret',
        modelIdMapping: { 'my-router-model': 'global.anthropic.claude-opus-5' },
        region: 'us-east-1',
      });
      const mockResponse = {
        body: new TextEncoder().encode(
          JSON.stringify({
            content: [{ input: { title: 'Mapped' }, name: 'mapped_schema', type: 'tool_use' }],
          }),
        ),
      };
      vi.spyOn(mappedInstance['client'], 'send').mockResolvedValue(mockResponse as any);

      await mappedInstance.generateObject({
        messages: [
          { content: 'Create a title.', role: 'user' },
          { content: '...', role: 'assistant' },
        ],
        model: 'my-router-model',
        schema: {
          name: 'mapped_schema',
          schema: {
            additionalProperties: false,
            properties: { title: { type: 'string' } },
            required: ['title'],
            type: 'object',
          },
          strict: true,
        },
      });

      const commandInput = (InvokeModelCommand as unknown as Mock).mock.calls.at(-1)?.[0];
      expect(commandInput.modelId).toBe('global.anthropic.claude-opus-5');
      expect(JSON.parse(commandInput.body).messages).toEqual([
        { content: 'Create a title.', role: 'user' },
      ]);
    });

    it('should return tool calls when tools are provided', async () => {
      const mockResponse = {
        body: new TextEncoder().encode(
          JSON.stringify({
            content: [
              {
                input: { query: 'status' },
                name: 'search_task',
                type: 'tool_use',
              },
            ],
          }),
        ),
      };
      (instance['client'].send as Mock).mockResolvedValue(mockResponse);

      const result = await instance.generateObject({
        messages: [{ content: 'Find the current task status.', role: 'user' }],
        model: 'global.anthropic.claude-sonnet-4-6',
        tools: [
          {
            function: {
              description: 'Search task data',
              name: 'search_task',
              parameters: {
                properties: { query: { type: 'string' } },
                required: ['query'],
                type: 'object',
              },
            },
            type: 'function',
          },
        ],
      });

      const commandInput = (InvokeModelCommand as unknown as Mock).mock.calls[0][0];
      const body = JSON.parse(commandInput.body);

      expect(result).toEqual([{ arguments: { query: 'status' }, name: 'search_task' }]);
      expect(body.tool_choice).toEqual({ type: 'any' });
      expect(body.tools).toEqual([
        {
          description: 'Search task data',
          input_schema: {
            properties: { query: { type: 'string' } },
            required: ['query'],
            type: 'object',
          },
          name: 'search_task',
        },
      ]);
    });

    it('should throw AgentRuntimeError on API error', async () => {
      const errorMessage = 'Generate object API error';
      const errorMetadata = { statusCode: 400 };
      const mockError = new Error(errorMessage);
      (mockError as any).$metadata = errorMetadata;
      (instance['client'].send as Mock).mockRejectedValue(mockError);

      await expect(
        instance.generateObject({
          messages: [{ content: 'Summarize this task topic.', role: 'user' }],
          model: 'global.anthropic.claude-sonnet-4-6',
          schema: {
            name: 'task_topic_handoff',
            schema: {
              properties: { summary: { type: 'string' } },
              required: ['summary'],
              type: 'object',
            },
          },
        }),
      ).rejects.toThrow(
        expect.objectContaining({
          error: {
            body: errorMetadata,
            message: errorMessage,
            type: 'Error',
          },
          errorType: AgentRuntimeErrorType.ProviderBizError,
          provider: ModelProvider.Bedrock,
          region: 'us-west-2',
        }),
      );
    });
  });

  describe('embeddings', () => {
    it('should handle single input string', async () => {
      // Arrange
      const mockEmbedding = [0.1, 0.2, 0.3];
      const mockResponse = {
        body: new TextEncoder().encode(JSON.stringify({ embedding: mockEmbedding })),
      };
      (instance['client'].send as Mock).mockResolvedValue(mockResponse);

      // Act
      const result = await instance.embeddings({
        input: 'test input',
        model: 'amazon.titan-embed-text-v1',
      });

      // Assert
      expect(result).toHaveLength(1);
      expect(result[0]).toEqual(mockEmbedding);
      expect(InvokeModelCommand).toHaveBeenCalledWith({
        accept: 'application/json',
        body: JSON.stringify({
          inputText: 'test input',
          normalize: true,
        }),
        contentType: 'application/json',
        modelId: 'amazon.titan-embed-text-v1',
      });
    });

    it('should handle multiple input strings', async () => {
      // Arrange
      const mockEmbedding1 = [0.1, 0.2, 0.3];
      const mockEmbedding2 = [0.4, 0.5, 0.6];
      const mockResponse1 = {
        body: new TextEncoder().encode(JSON.stringify({ embedding: mockEmbedding1 })),
      };
      const mockResponse2 = {
        body: new TextEncoder().encode(JSON.stringify({ embedding: mockEmbedding2 })),
      };
      (instance['client'].send as Mock)
        .mockResolvedValueOnce(mockResponse1)
        .mockResolvedValueOnce(mockResponse2);

      // Act
      const result = await instance.embeddings({
        input: ['test input 1', 'test input 2'],
        model: 'amazon.titan-embed-text-v1',
      });

      // Assert
      expect(result).toHaveLength(2);
      expect(result[0]).toEqual(mockEmbedding1);
      expect(result[1]).toEqual(mockEmbedding2);
      expect(InvokeModelCommand).toHaveBeenCalledTimes(2);
    });

    it('should handle dimensions parameter', async () => {
      // Arrange
      const mockEmbedding = [0.1, 0.2, 0.3];
      const mockResponse = {
        body: new TextEncoder().encode(JSON.stringify({ embedding: mockEmbedding })),
      };
      (instance['client'].send as Mock).mockResolvedValue(mockResponse);

      // Act
      const result = await instance.embeddings({
        dimensions: 512,
        input: 'test input',
        model: 'amazon.titan-embed-text-v1',
      });

      // Assert
      expect(result).toHaveLength(1);
      expect(InvokeModelCommand).toHaveBeenCalledWith({
        accept: 'application/json',
        body: JSON.stringify({
          dimensions: 512,
          inputText: 'test input',
          normalize: true,
        }),
        contentType: 'application/json',
        modelId: 'amazon.titan-embed-text-v1',
      });
    });

    it('should handle abort signal', async () => {
      // Arrange
      const mockEmbedding = [0.1, 0.2, 0.3];
      const mockResponse = {
        body: new TextEncoder().encode(JSON.stringify({ embedding: mockEmbedding })),
      };
      const sendSpy = vi.spyOn(instance['client'], 'send').mockResolvedValue(mockResponse as any);
      const abortController = new AbortController();

      // Act
      await instance.embeddings(
        {
          input: 'test input',
          model: 'amazon.titan-embed-text-v1',
        },
        { signal: abortController.signal },
      );

      // Assert
      expect(sendSpy).toHaveBeenCalledWith(expect.any(InvokeModelCommand), {
        abortSignal: abortController.signal,
      });
    });

    it('should throw AgentRuntimeError on API error', async () => {
      // Arrange
      const errorMessage = 'Embedding API error';
      const errorMetadata = { statusCode: 400 };
      const mockError = new Error(errorMessage);
      (mockError as any).$metadata = errorMetadata;
      (instance['client'].send as Mock).mockRejectedValue(mockError);

      // Act & Assert
      await expect(
        instance.embeddings({
          input: 'test input',
          model: 'amazon.titan-embed-text-v1',
        }),
      ).rejects.toThrow(
        expect.objectContaining({
          error: {
            body: errorMetadata,
            message: errorMessage,
            type: 'Error',
          },
          errorType: AgentRuntimeErrorType.ProviderBizError,
          provider: ModelProvider.Bedrock,
          region: 'us-west-2',
        }),
      );
    });
  });

  describe('experimental_buildLlama2Prompt', () => {
    it('should build prompt with user message only', () => {
      const messages = [{ content: 'Hello', role: 'user' }];
      const result = experimental_buildLlama2Prompt(messages);
      expect(result).toBe('<s>[INST] Hello [/INST]');
    });

    it('should build prompt with system and user messages', () => {
      const messages = [
        { content: 'You are a helpful assistant', role: 'system' },
        { content: 'Hello', role: 'user' },
      ];
      const result = experimental_buildLlama2Prompt(messages);
      expect(result).toBe(
        '<s>[INST] <<SYS>>\nYou are a helpful assistant\n<</SYS>>\n\nHello [/INST]',
      );
    });

    it('should build prompt with conversation history', () => {
      const messages = [
        { content: 'Hello', role: 'user' },
        { content: 'Hi there!', role: 'assistant' },
        { content: 'How are you?', role: 'user' },
      ];
      const result = experimental_buildLlama2Prompt(messages);
      expect(result).toBe('<s>[INST] Hello [/INST] Hi there!</s><s>[INST] How are you? [/INST]');
    });

    it('should build prompt with system, user, and assistant messages', () => {
      const messages = [
        { content: 'You are a helpful assistant', role: 'system' },
        { content: 'Hello', role: 'user' },
        { content: 'Hi there!', role: 'assistant' },
        { content: 'How are you?', role: 'user' },
      ];
      const result = experimental_buildLlama2Prompt(messages);
      expect(result).toBe(
        '<s>[INST] <<SYS>>\nYou are a helpful assistant\n<</SYS>>\n\nHello [/INST] Hi there!</s><s>[INST] How are you? [/INST]',
      );
    });

    it('should trim user messages', () => {
      const messages = [{ content: '  Hello  ', role: 'user' }];
      const result = experimental_buildLlama2Prompt(messages);
      expect(result).toBe('<s>[INST] Hello [/INST]');
    });

    it('should throw error for function messages', () => {
      const messages = [{ content: 'function call', role: 'function' }];
      expect(() => experimental_buildLlama2Prompt(messages)).toThrow(
        'Llama 2 does not support function calls.',
      );
    });

    it('should throw error for invalid role', () => {
      const messages = [{ content: 'invalid', role: 'invalid' }];
      expect(() => experimental_buildLlama2Prompt(messages)).toThrow(
        'Invalid message role: invalid',
      );
    });

    it('should throw error for system message not at index 0', () => {
      const messages = [
        { content: 'Hello', role: 'user' },
        { content: 'You are a helpful assistant', role: 'system' },
      ];
      expect(() => experimental_buildLlama2Prompt(messages)).toThrow(
        'Invalid message role: system',
      );
    });
  });
});