@bernierllc/ai-provider-anthropic 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +34 -0
- package/README.md +310 -0
- package/__tests__/AnthropicProvider.test.ts +655 -0
- package/__tests__/error-handling.test.ts +208 -0
- package/__tests__/message-conversion.test.ts +161 -0
- package/__tests__/model-registry.test.ts +150 -0
- package/dist/AnthropicProvider.d.ts +54 -0
- package/dist/AnthropicProvider.js +337 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +34 -0
- package/dist/models/model-registry.d.ts +31 -0
- package/dist/models/model-registry.js +113 -0
- package/dist/types/anthropic-types.d.ts +46 -0
- package/dist/types/anthropic-types.js +9 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.js +24 -0
- package/dist/utils/error-handling.d.ts +12 -0
- package/dist/utils/error-handling.js +67 -0
- package/dist/utils/index.d.ts +2 -0
- package/dist/utils/index.js +25 -0
- package/dist/utils/message-conversion.d.ts +17 -0
- package/dist/utils/message-conversion.js +65 -0
- package/jest.config.js +30 -0
- package/package.json +59 -0
- package/src/AnthropicProvider.ts +392 -0
- package/src/index.ts +19 -0
- package/src/models/model-registry.ts +120 -0
- package/src/types/anthropic-types.ts +60 -0
- package/src/types/index.ts +9 -0
- package/src/utils/error-handling.ts +71 -0
- package/src/utils/index.ts +10 -0
- package/src/utils/message-conversion.ts +78 -0
- package/tsconfig.json +29 -0
package/.eslintrc.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/*
|
|
2
|
+
Copyright (c) 2025 Bernier LLC
|
|
3
|
+
|
|
4
|
+
This file is licensed to the client under a limited-use license.
|
|
5
|
+
The client may use and modify this code only within the scope of the project it was delivered for.
|
|
6
|
+
Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
module.exports = {
|
|
10
|
+
parser: '@typescript-eslint/parser',
|
|
11
|
+
parserOptions: {
|
|
12
|
+
ecmaVersion: 2020,
|
|
13
|
+
sourceType: 'module',
|
|
14
|
+
project: './tsconfig.json'
|
|
15
|
+
},
|
|
16
|
+
extends: [
|
|
17
|
+
'eslint:recommended',
|
|
18
|
+
'plugin:@typescript-eslint/recommended',
|
|
19
|
+
'plugin:@typescript-eslint/recommended-requiring-type-checking'
|
|
20
|
+
],
|
|
21
|
+
plugins: ['@typescript-eslint'],
|
|
22
|
+
env: {
|
|
23
|
+
node: true,
|
|
24
|
+
jest: true,
|
|
25
|
+
es6: true
|
|
26
|
+
},
|
|
27
|
+
rules: {
|
|
28
|
+
'@typescript-eslint/explicit-function-return-type': 'warn',
|
|
29
|
+
'@typescript-eslint/no-explicit-any': 'error',
|
|
30
|
+
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
|
31
|
+
'@typescript-eslint/no-floating-promises': 'error',
|
|
32
|
+
'no-console': 'off'
|
|
33
|
+
}
|
|
34
|
+
};
|
package/README.md
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
# @bernierllc/ai-provider-anthropic
|
|
2
|
+
|
|
3
|
+
Anthropic Claude API adapter implementing the unified AI provider interface from `@bernierllc/ai-provider-core`.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **All Claude 3 Models**: Full support for Opus, Sonnet, and Haiku
|
|
8
|
+
- **Streaming**: Async generator-based streaming completions
|
|
9
|
+
- **Vision Analysis**: Image analysis with all Claude 3 models
|
|
10
|
+
- **Extended Context**: Support for 200K token context windows
|
|
11
|
+
- **Cost Estimation**: Accurate cost calculation with model-specific pricing
|
|
12
|
+
- **TypeScript**: Full type safety with strict mode
|
|
13
|
+
- **Error Handling**: Comprehensive error handling with retry support
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @bernierllc/ai-provider-anthropic
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Basic Usage
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { AnthropicProvider } from '@bernierllc/ai-provider-anthropic';
|
|
25
|
+
|
|
26
|
+
const provider = new AnthropicProvider({
|
|
27
|
+
providerName: 'anthropic',
|
|
28
|
+
apiKey: process.env.ANTHROPIC_API_KEY!,
|
|
29
|
+
defaultModel: 'claude-3-opus-20240229'
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Generate completion
|
|
33
|
+
const response = await provider.complete({
|
|
34
|
+
messages: [
|
|
35
|
+
{ role: 'system', content: 'You are a helpful assistant.' },
|
|
36
|
+
{ role: 'user', content: 'Explain TypeScript generics in simple terms.' }
|
|
37
|
+
],
|
|
38
|
+
maxTokens: 500,
|
|
39
|
+
temperature: 0.7
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
if (response.success) {
|
|
43
|
+
console.log(response.content);
|
|
44
|
+
console.log(`Tokens used: ${response.usage?.totalTokens}`);
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## API Reference
|
|
49
|
+
|
|
50
|
+
### Constructor
|
|
51
|
+
|
|
52
|
+
```typescript
|
|
53
|
+
new AnthropicProvider(config: AnthropicProviderConfig)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
**Config Options:**
|
|
57
|
+
- `providerName`: Must be `'anthropic'`
|
|
58
|
+
- `apiKey`: Anthropic API key (required)
|
|
59
|
+
- `defaultModel`: Default model to use (optional, defaults to `claude-3-opus-20240229`)
|
|
60
|
+
- `baseURL`: Custom API base URL (optional)
|
|
61
|
+
- `timeout`: Request timeout in milliseconds (optional, defaults to 60000)
|
|
62
|
+
- `maxRetries`: Maximum number of retries (optional, defaults to 3)
|
|
63
|
+
|
|
64
|
+
### Methods
|
|
65
|
+
|
|
66
|
+
#### `complete(request: CompletionRequest): Promise<CompletionResponse>`
|
|
67
|
+
|
|
68
|
+
Generate a text completion.
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
const response = await provider.complete({
|
|
72
|
+
messages: [
|
|
73
|
+
{ role: 'user', content: 'Hello!' }
|
|
74
|
+
],
|
|
75
|
+
maxTokens: 100,
|
|
76
|
+
temperature: 0.7
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
#### `streamComplete(request: CompletionRequest): AsyncGenerator<StreamChunk>`
|
|
81
|
+
|
|
82
|
+
Generate a streaming text completion.
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
for await (const chunk of provider.streamComplete({
|
|
86
|
+
messages: [
|
|
87
|
+
{ role: 'user', content: 'Write a short poem about coding' }
|
|
88
|
+
]
|
|
89
|
+
})) {
|
|
90
|
+
process.stdout.write(chunk.delta);
|
|
91
|
+
|
|
92
|
+
if (chunk.finishReason) {
|
|
93
|
+
console.log(`\n\nFinished: ${chunk.finishReason}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
#### `analyzeImage(imageData, prompt, model?, maxTokens?, temperature?): Promise<CompletionResponse>`
|
|
99
|
+
|
|
100
|
+
Analyze an image using Claude's vision capabilities.
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
const imageBuffer = fs.readFileSync('diagram.png');
|
|
104
|
+
|
|
105
|
+
const analysis = await provider.analyzeImage(
|
|
106
|
+
imageBuffer,
|
|
107
|
+
'Describe this architecture diagram in detail',
|
|
108
|
+
'claude-3-opus-20240229'
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
if (analysis.success) {
|
|
112
|
+
console.log(analysis.content);
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
#### `extendedContextCompletion(request): Promise<CompletionResponse>`
|
|
117
|
+
|
|
118
|
+
Process requests with extended context (200K tokens).
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
const longDocument = fs.readFileSync('very-long-document.txt', 'utf-8');
|
|
122
|
+
|
|
123
|
+
const response = await provider.extendedContextCompletion({
|
|
124
|
+
messages: [
|
|
125
|
+
{ role: 'user', content: `Summarize this document:\n\n${longDocument}` }
|
|
126
|
+
],
|
|
127
|
+
enableExtendedContext: true
|
|
128
|
+
});
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
#### `estimateCost(request: CompletionRequest): CostEstimate`
|
|
132
|
+
|
|
133
|
+
Estimate the cost of a request before sending it.
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
const cost = provider.estimateCost({
|
|
137
|
+
messages: [{ role: 'user', content: 'Hello world!' }],
|
|
138
|
+
model: 'claude-3-opus-20240229',
|
|
139
|
+
maxTokens: 100
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
console.log(`Estimated cost: $${cost.estimatedCostUSD.toFixed(4)}`);
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
#### `getAvailableModels(): Promise<ModelInfo[]>`
|
|
146
|
+
|
|
147
|
+
Get information about all available Claude models.
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
const models = await provider.getAvailableModels();
|
|
151
|
+
|
|
152
|
+
models.forEach(model => {
|
|
153
|
+
console.log(`${model.name}: ${model.contextWindow} tokens`);
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
#### `checkHealth(): Promise<HealthStatus>`
|
|
158
|
+
|
|
159
|
+
Check if the Anthropic API is available.
|
|
160
|
+
|
|
161
|
+
```typescript
|
|
162
|
+
const health = await provider.checkHealth();
|
|
163
|
+
|
|
164
|
+
if (health.status === 'healthy') {
|
|
165
|
+
console.log(`API is healthy (latency: ${health.latency}ms)`);
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Available Models
|
|
170
|
+
|
|
171
|
+
| Model | ID | Context | Output | Cost (Input/Output per 1M tokens) |
|
|
172
|
+
|-------|-----|---------|--------|-----------------------------------|
|
|
173
|
+
| **Claude 3 Opus** | `claude-3-opus-20240229` | 200K | 4096 | $15 / $75 |
|
|
174
|
+
| **Claude 3 Sonnet** | `claude-3-sonnet-20240229` | 200K | 4096 | $3 / $15 |
|
|
175
|
+
| **Claude 3 Haiku** | `claude-3-haiku-20240307` | 200K | 4096 | $0.25 / $1.25 |
|
|
176
|
+
|
|
177
|
+
All models support:
|
|
178
|
+
- Text completion
|
|
179
|
+
- Streaming
|
|
180
|
+
- Vision analysis
|
|
181
|
+
- Extended context (200K tokens)
|
|
182
|
+
|
|
183
|
+
## Error Handling
|
|
184
|
+
|
|
185
|
+
The provider returns structured error responses:
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
const response = await provider.complete({
|
|
189
|
+
messages: [{ role: 'user', content: 'Test' }]
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
if (!response.success) {
|
|
193
|
+
console.error('Error:', response.error);
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## Limitations
|
|
198
|
+
|
|
199
|
+
### Embeddings
|
|
200
|
+
Anthropic does not provide an embeddings API. Use `@bernierllc/ai-provider-openai` for embeddings:
|
|
201
|
+
|
|
202
|
+
```typescript
|
|
203
|
+
const embeddingResponse = await provider.generateEmbeddings({
|
|
204
|
+
input: 'test text'
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// Returns: { success: false, error: 'Anthropic does not provide an embeddings API...' }
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
### Content Moderation
|
|
211
|
+
Claude has built-in safety features (Constitutional AI), so no separate moderation API is needed:
|
|
212
|
+
|
|
213
|
+
```typescript
|
|
214
|
+
const moderation = await provider.moderate('content');
|
|
215
|
+
|
|
216
|
+
// Always returns: { success: true, flagged: false, ... }
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
## Integration Status
|
|
220
|
+
|
|
221
|
+
- **Logger**: ✅ Integrated - Uses `@bernierllc/logger` for error logging
|
|
222
|
+
- **Docs-Suite**: ✅ Ready - Full TypeDoc/JSDoc documentation
|
|
223
|
+
- **NeverHub**: ⚠️ Optional - Can integrate for monitoring and metrics
|
|
224
|
+
|
|
225
|
+
## Advanced Usage
|
|
226
|
+
|
|
227
|
+
### Model Comparison
|
|
228
|
+
|
|
229
|
+
```typescript
|
|
230
|
+
const models = await provider.getAvailableModels();
|
|
231
|
+
|
|
232
|
+
models.forEach(model => {
|
|
233
|
+
console.log(`${model.name}:`);
|
|
234
|
+
console.log(` Context: ${model.contextWindow.toLocaleString()} tokens`);
|
|
235
|
+
console.log(` Capabilities: ${model.capabilities.join(', ')}`);
|
|
236
|
+
if (model.pricing) {
|
|
237
|
+
console.log(` Input: $${model.pricing.inputPricePerToken * 1000000}/M tokens`);
|
|
238
|
+
console.log(` Output: $${model.pricing.outputPricePerToken * 1000000}/M tokens`);
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
### Complex Reasoning Task
|
|
244
|
+
|
|
245
|
+
```typescript
|
|
246
|
+
// Claude excels at complex reasoning and analysis
|
|
247
|
+
const response = await provider.complete({
|
|
248
|
+
messages: [
|
|
249
|
+
{
|
|
250
|
+
role: 'user',
|
|
251
|
+
content: `Analyze this code architecture and suggest improvements:
|
|
252
|
+
|
|
253
|
+
[Large codebase content...]
|
|
254
|
+
|
|
255
|
+
Consider: scalability, maintainability, security, performance`
|
|
256
|
+
}
|
|
257
|
+
],
|
|
258
|
+
model: 'claude-3-opus-20240229',
|
|
259
|
+
maxTokens: 4096,
|
|
260
|
+
temperature: 0.3 // Lower temperature for analytical tasks
|
|
261
|
+
});
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
### Vision with Multiple Images
|
|
265
|
+
|
|
266
|
+
```typescript
|
|
267
|
+
// Analyze multiple images in sequence
|
|
268
|
+
const images = ['image1.png', 'image2.png', 'image3.png'];
|
|
269
|
+
|
|
270
|
+
for (const imagePath of images) {
|
|
271
|
+
const imageBuffer = fs.readFileSync(imagePath);
|
|
272
|
+
|
|
273
|
+
const analysis = await provider.analyzeImage(
|
|
274
|
+
imageBuffer,
|
|
275
|
+
'What do you see in this image?'
|
|
276
|
+
);
|
|
277
|
+
|
|
278
|
+
console.log(`${imagePath}: ${analysis.content}`);
|
|
279
|
+
}
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
## TypeScript Types
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
import type {
|
|
286
|
+
AnthropicProviderConfig,
|
|
287
|
+
AnthropicVisionRequest,
|
|
288
|
+
AnthropicExtendedContextRequest
|
|
289
|
+
} from '@bernierllc/ai-provider-anthropic';
|
|
290
|
+
|
|
291
|
+
import type {
|
|
292
|
+
CompletionRequest,
|
|
293
|
+
CompletionResponse,
|
|
294
|
+
StreamChunk,
|
|
295
|
+
ModelInfo,
|
|
296
|
+
HealthStatus,
|
|
297
|
+
CostEstimate
|
|
298
|
+
} from '@bernierllc/ai-provider-core';
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
## License
|
|
302
|
+
|
|
303
|
+
Copyright (c) 2025 Bernier LLC. All rights reserved.
|
|
304
|
+
|
|
305
|
+
## See Also
|
|
306
|
+
|
|
307
|
+
- [@bernierllc/ai-provider-core](../ai-provider-core) - Abstract provider interface
|
|
308
|
+
- [@bernierllc/ai-provider-openai](../ai-provider-openai) - OpenAI provider implementation
|
|
309
|
+
- [@bernierllc/retry-policy](../retry-policy) - Retry logic used by this package
|
|
310
|
+
- [@bernierllc/logger](../logger) - Logging used by this package
|