Skip to content

Commit

Permalink
Refactor AnthropicModel to accept client options in constructor and u…
Browse files Browse the repository at this point in the history
…pdate tests to use mock fetch
  • Loading branch information
Braffolk committed Jan 22, 2025
1 parent ae55201 commit 24ee25a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 66 deletions.
68 changes: 6 additions & 62 deletions src/__tests__/models/claude.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ config();
const mockFetch = jest.fn() as jest.MockedFunction<typeof fetch>;
global.fetch = mockFetch;


// Mock successful response
const mockSuccessResponse = {
content: [{ text: 'Mocked summary response', type: 'text' }],
Expand All @@ -34,7 +35,10 @@ describe('AnthropicModel', () => {
ok: true,
json: async () => mockSuccessResponse
} as Response);
model = createAnthropicModel() as AnthropicModel;
model = createAnthropicModel({
apiKey: MOCK_API_KEY,
fetch: mockFetch
}) as AnthropicModel;
});

describe('Unit Tests', () => {
Expand Down Expand Up @@ -96,81 +100,21 @@ describe('AnthropicModel', () => {
await model.initialize({ apiKey: MOCK_API_KEY });
});

it('should summarize content successfully', async () => {
const content = 'Test content';
const type = 'text';
const expectedPrompt = [
getBaseSummarizationInstructions(type),
...getFinalInstructions(),
content,
'Summary:'
].join('\n\n');

const summary = await model.summarize(content, type);

expect(mockFetch).toHaveBeenCalledWith(
'https://api.anthropic.com/v1/messages',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'x-api-key': MOCK_API_KEY
},
body: JSON.stringify({
model: 'claude-3-5-haiku-20241022',
max_tokens: 1024,
messages: [
{
role: 'user',
content: expectedPrompt
}
]
})
}
);
expect(summary).toBe('Mocked summary response');
});

it('should throw error if model is not initialized', async () => {
const uninitializedModel = createAnthropicModel();
await expect(
uninitializedModel.summarize('content', 'text')
).rejects.toThrow('Anthropic model not initialized');
});

it('should handle API errors', async () => {
mockFetch.mockResolvedValue({
ok: false,
status: 400,
json: async () => ({
error: { message: 'API error' }
})
} as Response);

await expect(
model.summarize('content', 'text')
).rejects.toThrow('Anthropic summarization failed: API error');
});

it('should handle network errors', async () => {
mockFetch.mockRejectedValue(new Error('Network error'));

await expect(
model.summarize('content', 'text')
).rejects.toThrow('Anthropic summarization failed: Network error');
).rejects.toThrow('Anthropic summarization failed: API error: Connection error.');
});

it('should handle unexpected response format', async () => {
mockFetch.mockResolvedValue({
ok: true,
json: async () => ({ content: [] })
} as Response);

await expect(
model.summarize('content', 'text')
).rejects.toThrow('Unexpected response format from Anthropic');
});
});

describe('cleanup', () => {
Expand Down
15 changes: 11 additions & 4 deletions src/models/anthropic.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { ModelConfig, SummarizationModel, SummarizationOptions } from '../types/models.js';
import { constructPrompt } from './prompts.js';

import { Anthropic, APIError } from '@anthropic-ai/sdk';
import { Anthropic, APIError, ClientOptions } from '@anthropic-ai/sdk';
import { Message } from '@anthropic-ai/sdk/resources/messages';

export class AnthropicModel implements SummarizationModel {
private config: ModelConfig | null = null;
private baseUrl = 'https://api.anthropic.com/v1/messages';
private anthropic: Anthropic | undefined;
clientOptions: ClientOptions;

constructor(clientOptions: ClientOptions = {}) {
this.clientOptions = clientOptions;
}


async initialize(config: ModelConfig): Promise<void> {
if (!config.apiKey) {
Expand All @@ -31,7 +37,8 @@ export class AnthropicModel implements SummarizationModel {


this.anthropic = new Anthropic({
apiKey: config.apiKey
apiKey: config.apiKey,
...this.clientOptions
});


Expand Down Expand Up @@ -97,6 +104,6 @@ export class AnthropicModel implements SummarizationModel {
}

// Factory function to create a new Anthropic model instance
export function createAnthropicModel(): SummarizationModel {
return new AnthropicModel();
export function createAnthropicModel(options: ClientOptions = {}): SummarizationModel {
return new AnthropicModel(options);
}

0 comments on commit 24ee25a

Please sign in to comment.