skrypt-ai 0.7.0 → 0.8.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/dist/auth/index.js +3 -3
- package/dist/cli.js +1 -1
- package/dist/commands/cron.js +0 -4
- package/dist/commands/generate/index.d.ts +3 -0
- package/dist/commands/generate/index.js +393 -0
- package/dist/commands/generate/scan.d.ts +41 -0
- package/dist/commands/generate/scan.js +256 -0
- package/dist/commands/generate/verify.d.ts +14 -0
- package/dist/commands/generate/verify.js +122 -0
- package/dist/commands/generate/write.d.ts +25 -0
- package/dist/commands/generate/write.js +120 -0
- package/dist/commands/import.js +4 -1
- package/dist/commands/llms-txt.js +6 -4
- package/dist/config/loader.d.ts +0 -1
- package/dist/config/loader.js +1 -1
- package/dist/generator/agents-md.d.ts +25 -0
- package/dist/generator/agents-md.js +122 -0
- package/dist/generator/index.d.ts +2 -0
- package/dist/generator/index.js +2 -0
- package/dist/generator/mdx-serializer.d.ts +11 -0
- package/dist/generator/mdx-serializer.js +135 -0
- package/dist/generator/organizer.d.ts +1 -16
- package/dist/generator/organizer.js +0 -38
- package/dist/generator/writer.js +5 -4
- package/dist/llm/proxy-client.d.ts +32 -0
- package/dist/llm/proxy-client.js +103 -0
- package/dist/scanner/csharp.d.ts +0 -4
- package/dist/scanner/csharp.js +9 -49
- package/dist/scanner/go.d.ts +0 -3
- package/dist/scanner/go.js +8 -35
- package/dist/scanner/java.d.ts +0 -4
- package/dist/scanner/java.js +9 -49
- package/dist/scanner/kotlin.d.ts +0 -3
- package/dist/scanner/kotlin.js +6 -33
- package/dist/scanner/php.d.ts +0 -10
- package/dist/scanner/php.js +11 -55
- package/dist/scanner/ruby.d.ts +0 -3
- package/dist/scanner/ruby.js +8 -38
- package/dist/scanner/rust.d.ts +0 -3
- package/dist/scanner/rust.js +10 -37
- package/dist/scanner/swift.d.ts +0 -3
- package/dist/scanner/swift.js +8 -35
- package/dist/scanner/utils.d.ts +41 -0
- package/dist/scanner/utils.js +97 -0
- package/dist/template/docs.json +5 -2
- package/dist/template/next.config.mjs +31 -0
- package/dist/template/package.json +5 -3
- package/dist/template/src/app/layout.tsx +13 -13
- package/dist/template/src/app/llms-full.md/route.ts +29 -0
- package/dist/template/src/app/llms.txt/route.ts +29 -0
- package/dist/template/src/app/md/[...slug]/route.ts +174 -0
- package/dist/template/src/app/reference/route.ts +22 -18
- package/dist/template/src/app/sitemap.ts +1 -1
- package/dist/template/src/components/ai-chat-impl.tsx +206 -0
- package/dist/template/src/components/ai-chat.tsx +20 -193
- package/dist/template/src/components/mdx/index.tsx +27 -4
- package/dist/template/src/lib/fonts.ts +135 -0
- package/dist/template/src/middleware.ts +101 -0
- package/dist/template/src/styles/globals.css +28 -20
- package/dist/utils/files.d.ts +0 -8
- package/dist/utils/files.js +0 -33
- package/package.json +1 -1
- package/dist/autofix/autofix.test.d.ts +0 -1
- package/dist/autofix/autofix.test.js +0 -487
- package/dist/commands/generate.d.ts +0 -9
- package/dist/commands/generate.js +0 -739
- package/dist/generator/generator.test.d.ts +0 -1
- package/dist/generator/generator.test.js +0 -259
- package/dist/generator/writer.test.d.ts +0 -1
- package/dist/generator/writer.test.js +0 -411
- package/dist/llm/llm.manual-test.d.ts +0 -1
- package/dist/llm/llm.manual-test.js +0 -112
- package/dist/llm/llm.mock-test.d.ts +0 -4
- package/dist/llm/llm.mock-test.js +0 -79
- package/dist/plugins/index.d.ts +0 -47
- package/dist/plugins/index.js +0 -181
- package/dist/scanner/content-type.test.d.ts +0 -1
- package/dist/scanner/content-type.test.js +0 -231
- package/dist/scanner/integration.test.d.ts +0 -4
- package/dist/scanner/integration.test.js +0 -180
- package/dist/scanner/scanner.test.d.ts +0 -1
- package/dist/scanner/scanner.test.js +0 -210
- package/dist/scanner/typescript.manual-test.d.ts +0 -1
- package/dist/scanner/typescript.manual-test.js +0 -112
- package/dist/template/src/app/docs/auth/page.mdx +0 -589
- package/dist/template/src/app/docs/autofix/page.mdx +0 -624
- package/dist/template/src/app/docs/cli/page.mdx +0 -217
- package/dist/template/src/app/docs/config/page.mdx +0 -428
- package/dist/template/src/app/docs/configuration/page.mdx +0 -86
- package/dist/template/src/app/docs/deployment/page.mdx +0 -112
- package/dist/template/src/app/docs/generator/generator.md +0 -504
- package/dist/template/src/app/docs/generator/organizer.md +0 -779
- package/dist/template/src/app/docs/generator/page.mdx +0 -613
- package/dist/template/src/app/docs/github/page.mdx +0 -502
- package/dist/template/src/app/docs/llm/anthropic-client.md +0 -549
- package/dist/template/src/app/docs/llm/index.md +0 -471
- package/dist/template/src/app/docs/llm/page.mdx +0 -428
- package/dist/template/src/app/docs/plugins/page.mdx +0 -1793
- package/dist/template/src/app/docs/pro/page.mdx +0 -121
- package/dist/template/src/app/docs/quickstart/page.mdx +0 -93
- package/dist/template/src/app/docs/scanner/content-type.md +0 -599
- package/dist/template/src/app/docs/scanner/index.md +0 -212
- package/dist/template/src/app/docs/scanner/page.mdx +0 -307
- package/dist/template/src/app/docs/scanner/python.md +0 -469
- package/dist/template/src/app/docs/scanner/python_parser.md +0 -1056
- package/dist/template/src/app/docs/scanner/rust.md +0 -325
- package/dist/template/src/app/docs/scanner/typescript.md +0 -201
- package/dist/template/src/app/icon.tsx +0 -29
- package/dist/utils/validation.d.ts +0 -1
- package/dist/utils/validation.js +0 -12
|
@@ -1,549 +0,0 @@
|
|
|
1
|
-
# Anthropic-client.ts
|
|
2
|
-
|
|
3
|
-
## Classes
|
|
4
|
-
|
|
5
|
-
### `AnthropicClient`
|
|
6
|
-
|
|
7
|
-
```typescript
|
|
8
|
-
class AnthropicClient implements LLMClient
|
|
9
|
-
```
|
|
10
|
-
|
|
11
|
-
Use this to send completion requests to Anthropic's Claude models with automatic retry logic and a standardized LLM interface.
|
|
12
|
-
|
|
13
|
-
`AnthropicClient` wraps the Anthropic SDK and implements the `LLMClient` interface, giving you a consistent way to interact with Claude models alongside other LLM providers in your application.
|
|
14
|
-
|
|
15
|
-
## Constructor Parameters
|
|
16
|
-
|
|
17
|
-
| Name | Type | Required | Description |
|
|
18
|
-
|------|------|----------|-------------|
|
|
19
|
-
| `config.model` | `string` | Yes | The Claude model to use (e.g. `"claude-3-5-sonnet-20241022"`) |
|
|
20
|
-
| `config.maxRetries` | `number` | No | Number of times to retry failed requests. Defaults to `3` |
|
|
21
|
-
| `config.apiKey` | `string` | No | Anthropic API key. Falls back to `ANTHROPIC_API_KEY` environment variable |
|
|
22
|
-
|
|
23
|
-
## Properties
|
|
24
|
-
|
|
25
|
-
| Property | Type | Description |
|
|
26
|
-
|----------|------|-------------|
|
|
27
|
-
| `provider` | `'anthropic'` | Always `'anthropic'` — use this to identify the active LLM provider at runtime |
|
|
28
|
-
|
|
29
|
-
## Returns
|
|
30
|
-
|
|
31
|
-
- **`complete(request)`** — Returns a `Promise<CompletionResponse>` containing the model's reply, token usage, and finish reason
|
|
32
|
-
- **`provider`** — Static string `'anthropic'` identifying this client's backend
|
|
33
|
-
|
|
34
|
-
## When to Use
|
|
35
|
-
|
|
36
|
-
- You need Claude-specific capabilities (long context, vision, tool use) behind a shared `LLMClient` interface
|
|
37
|
-
- You want automatic retries without writing retry logic yourself
|
|
38
|
-
- You're building a multi-provider system and need to swap LLM backends without changing call sites
|
|
39
|
-
|
|
40
|
-
**Example:**
|
|
41
|
-
|
|
42
|
-
```typescript example.ts
|
|
43
|
-
// ─── Inline types (no imports from autodocs) ───────────────────────────────
|
|
44
|
-
|
|
45
|
-
type LLMProvider = 'anthropic' | 'openai' | 'gemini'
|
|
46
|
-
|
|
47
|
-
interface LLMClientConfig {
|
|
48
|
-
model: string
|
|
49
|
-
maxRetries?: number
|
|
50
|
-
apiKey?: string
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
interface CompletionRequest {
|
|
54
|
-
messages: Array<{ role: 'user' | 'assistant'; content: string }>
|
|
55
|
-
systemPrompt?: string
|
|
56
|
-
maxTokens?: number
|
|
57
|
-
temperature?: number
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
interface CompletionResponse {
|
|
61
|
-
content: string
|
|
62
|
-
usage: { inputTokens: number; outputTokens: number }
|
|
63
|
-
finishReason: 'stop' | 'max_tokens' | 'error'
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
interface LLMClient {
|
|
67
|
-
provider: LLMProvider
|
|
68
|
-
complete(request: CompletionRequest): Promise<CompletionResponse>
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// ─── Simulated AnthropicClient (mirrors real implementation behavior) ────────
|
|
72
|
-
|
|
73
|
-
class AnthropicClient implements LLMClient {
|
|
74
|
-
provider: LLMProvider = 'anthropic'
|
|
75
|
-
private model: string
|
|
76
|
-
private maxRetries: number
|
|
77
|
-
private apiKey: string
|
|
78
|
-
|
|
79
|
-
constructor(config: LLMClientConfig) {
|
|
80
|
-
this.model = config.model
|
|
81
|
-
this.maxRetries = config.maxRetries ?? 3
|
|
82
|
-
this.apiKey = config.apiKey || process.env.ANTHROPIC_API_KEY || 'your-anthropic-api-key'
|
|
83
|
-
|
|
84
|
-
if (!this.apiKey) {
|
|
85
|
-
throw new Error('Anthropic API key is required. Set ANTHROPIC_API_KEY or pass config.apiKey.')
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
async complete(request: CompletionRequest): Promise<CompletionResponse> {
|
|
90
|
-
// In production this calls the Anthropic SDK with retry logic.
|
|
91
|
-
// Here we simulate a successful response for demonstration.
|
|
92
|
-
console.log(`[AnthropicClient] Model: ${this.model}`)
|
|
93
|
-
console.log(`[AnthropicClient] Max retries: ${this.maxRetries}`)
|
|
94
|
-
console.log(`[AnthropicClient] Sending ${request.messages.length} message(s)...`)
|
|
95
|
-
|
|
96
|
-
if (request.systemPrompt) {
|
|
97
|
-
console.log(`[AnthropicClient] System prompt: "${request.systemPrompt}"`)
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// Simulated response — real client returns Claude's actual reply
|
|
101
|
-
return {
|
|
102
|
-
content: 'TypeScript is a statically typed superset of JavaScript that compiles to plain JS.',
|
|
103
|
-
usage: { inputTokens: 24, outputTokens: 18 },
|
|
104
|
-
finishReason: 'stop',
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
// ─── Usage ───────────────────────────────────────────────────────────────────
|
|
110
|
-
|
|
111
|
-
async function main() {
|
|
112
|
-
try {
|
|
113
|
-
const client = new AnthropicClient({
|
|
114
|
-
model: 'claude-3-5-sonnet-20241022',
|
|
115
|
-
maxRetries: 3,
|
|
116
|
-
apiKey: process.env.ANTHROPIC_API_KEY || 'sk-ant-your-key-here',
|
|
117
|
-
})
|
|
118
|
-
|
|
119
|
-
console.log('Provider:', client.provider) // Output: Provider: anthropic
|
|
120
|
-
|
|
121
|
-
const response = await client.complete({
|
|
122
|
-
systemPrompt: 'You are a concise technical assistant.',
|
|
123
|
-
messages: [
|
|
124
|
-
{ role: 'user', content: 'What is TypeScript in one sentence?' },
|
|
125
|
-
],
|
|
126
|
-
maxTokens: 256,
|
|
127
|
-
temperature: 0.3,
|
|
128
|
-
})
|
|
129
|
-
|
|
130
|
-
console.log('\n── Response ──────────────────────────────')
|
|
131
|
-
console.log('Content: ', response.content)
|
|
132
|
-
console.log('Finish reason:', response.finishReason)
|
|
133
|
-
console.log('Tokens used: ', response.usage)
|
|
134
|
-
// Output:
|
|
135
|
-
// Provider: anthropic
|
|
136
|
-
// [AnthropicClient] Model: claude-3-5-sonnet-20241022
|
|
137
|
-
// [AnthropicClient] Max retries: 3
|
|
138
|
-
// [AnthropicClient] Sending 1 message(s)...
|
|
139
|
-
// [AnthropicClient] System prompt: "You are a concise technical assistant."
|
|
140
|
-
// ── Response ──────────────────────────────
|
|
141
|
-
// Content: TypeScript is a statically typed superset of JavaScript...
|
|
142
|
-
// Finish reason: stop
|
|
143
|
-
// Tokens used: { inputTokens: 24, outputTokens: 18 }
|
|
144
|
-
|
|
145
|
-
} catch (error) {
|
|
146
|
-
if (error instanceof Error) {
|
|
147
|
-
console.error('LLM request failed:', error.message)
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
main()
|
|
153
|
-
```
|
|
154
|
-
|
|
155
|
-
### Methods
|
|
156
|
-
|
|
157
|
-
#### `constructor`
|
|
158
|
-
|
|
159
|
-
```typescript
|
|
160
|
-
constructor(config: LLMClientConfig)
|
|
161
|
-
```
|
|
162
|
-
|
|
163
|
-
Use this to create an Anthropic-backed LLM client for sending completion requests, with built-in retry logic and model configuration.
|
|
164
|
-
|
|
165
|
-
The `AnthropicClient` constructor initializes a client that wraps the Anthropic SDK, binding it to a specific model and API key. It defaults to 3 retries on failure unless overridden.
|
|
166
|
-
|
|
167
|
-
### Parameters
|
|
168
|
-
|
|
169
|
-
| Name | Type | Required | Description |
|
|
170
|
-
|------|------|----------|-------------|
|
|
171
|
-
| `config` | `LLMClientConfig` | ✅ | Configuration object for the client |
|
|
172
|
-
| `config.apiKey` | `string` | ✅ | Your Anthropic API key |
|
|
173
|
-
| `config.model` | `string` | ✅ | The Anthropic model to use (e.g. `"claude-3-5-sonnet-20241022"`) |
|
|
174
|
-
| `config.maxRetries` | `number` | ❌ | Number of retry attempts on failure. Defaults to `3` |
|
|
175
|
-
|
|
176
|
-
### Returns
|
|
177
|
-
|
|
178
|
-
An `AnthropicClient` instance with:
|
|
179
|
-
- `provider` set to `"anthropic"`
|
|
180
|
-
- An initialized Anthropic SDK client ready to send requests
|
|
181
|
-
- Retry logic applied to all completion calls
|
|
182
|
-
|
|
183
|
-
**Example:**
|
|
184
|
-
|
|
185
|
-
```typescript example.ts
|
|
186
|
-
// Inline types — no library imports needed
|
|
187
|
-
type LLMProvider = 'anthropic' | 'openai'
|
|
188
|
-
|
|
189
|
-
interface LLMClientConfig {
|
|
190
|
-
apiKey: string
|
|
191
|
-
model: string
|
|
192
|
-
maxRetries?: number
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
interface CompletionRequest {
|
|
196
|
-
prompt: string
|
|
197
|
-
maxTokens?: number
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
interface CompletionResponse {
|
|
201
|
-
text: string
|
|
202
|
-
model: string
|
|
203
|
-
usage: { inputTokens: number; outputTokens: number }
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// Simulated AnthropicClient — mirrors the real implementation
|
|
207
|
-
class AnthropicClient {
|
|
208
|
-
provider: LLMProvider = 'anthropic'
|
|
209
|
-
private model: string
|
|
210
|
-
private maxRetries: number
|
|
211
|
-
private apiKey: string
|
|
212
|
-
|
|
213
|
-
constructor(config: LLMClientConfig) {
|
|
214
|
-
this.model = config.model
|
|
215
|
-
this.maxRetries = config.maxRetries ?? 3
|
|
216
|
-
this.apiKey = config.apiKey
|
|
217
|
-
|
|
218
|
-
console.log(`AnthropicClient initialized`)
|
|
219
|
-
console.log(` Model: ${this.model}`)
|
|
220
|
-
console.log(` Max Retries: ${this.maxRetries}`)
|
|
221
|
-
console.log(` Provider: ${this.provider}`)
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
async complete(request: CompletionRequest): Promise<CompletionResponse> {
|
|
225
|
-
// Simulated response — real client calls Anthropic SDK here
|
|
226
|
-
return {
|
|
227
|
-
text: `Response to: "${request.prompt}"`,
|
|
228
|
-
model: this.model,
|
|
229
|
-
usage: { inputTokens: 12, outputTokens: 34 },
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// --- Usage ---
|
|
235
|
-
|
|
236
|
-
async function main() {
|
|
237
|
-
try {
|
|
238
|
-
// Basic setup with defaults (maxRetries defaults to 3)
|
|
239
|
-
const client = new AnthropicClient({
|
|
240
|
-
apiKey: process.env.ANTHROPIC_API_KEY || 'sk-ant-your-api-key-here',
|
|
241
|
-
model: 'claude-3-5-sonnet-20241022',
|
|
242
|
-
})
|
|
243
|
-
|
|
244
|
-
const response = await client.complete({
|
|
245
|
-
prompt: 'Summarize the benefits of TypeScript in one sentence.',
|
|
246
|
-
maxTokens: 100,
|
|
247
|
-
})
|
|
248
|
-
|
|
249
|
-
console.log('\nCompletion response:')
|
|
250
|
-
console.log(' Text: ', response.text)
|
|
251
|
-
console.log(' Model: ', response.model)
|
|
252
|
-
console.log(' Usage: ', response.usage)
|
|
253
|
-
// Output:
|
|
254
|
-
// AnthropicClient initialized
|
|
255
|
-
// Model: claude-3-5-sonnet-20241022
|
|
256
|
-
// Max Retries: 3
|
|
257
|
-
// Provider: anthropic
|
|
258
|
-
//
|
|
259
|
-
// Completion response:
|
|
260
|
-
// Text: Response to: "Summarize the benefits of TypeScript..."
|
|
261
|
-
// Model: claude-3-5-sonnet-20241022
|
|
262
|
-
// Usage: { inputTokens: 12, outputTokens: 34 }
|
|
263
|
-
|
|
264
|
-
// With custom retry count
|
|
265
|
-
const reliableClient = new AnthropicClient({
|
|
266
|
-
apiKey: process.env.ANTHROPIC_API_KEY || 'sk-ant-your-api-key-here',
|
|
267
|
-
model: 'claude-3-haiku-20240307',
|
|
268
|
-
maxRetries: 5,
|
|
269
|
-
})
|
|
270
|
-
|
|
271
|
-
console.log('\nReliable client provider:', reliableClient.provider)
|
|
272
|
-
// Output: anthropic
|
|
273
|
-
} catch (error) {
|
|
274
|
-
console.error('Failed to initialize AnthropicClient:', error)
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
main()
|
|
279
|
-
```
|
|
280
|
-
|
|
281
|
-
#### `isConfigured`
|
|
282
|
-
|
|
283
|
-
```typescript
|
|
284
|
-
isConfigured(): boolean
|
|
285
|
-
```
|
|
286
|
-
|
|
287
|
-
Use this to verify that an `AnthropicClient` instance is ready to make API calls before attempting completions.
|
|
288
|
-
|
|
289
|
-
This method acts as a readiness check — it confirms the client has been initialized and the underlying Anthropic SDK has taken responsibility for credential validation. Call it as a guard before submitting requests in workflows where client configuration may be conditional or deferred.
|
|
290
|
-
|
|
291
|
-
**Returns**
|
|
292
|
-
|
|
293
|
-
| Value | Condition |
|
|
294
|
-
|-------|-----------|
|
|
295
|
-
| `true` | Always — the client is initialized and the Anthropic SDK handles API key validation internally |
|
|
296
|
-
|
|
297
|
-
> **Note:** A return value of `true` does not guarantee the API key is valid or that requests will succeed. It confirms the client object is configured and ready to attempt calls. Authentication errors will surface when `complete()` is called.
|
|
298
|
-
|
|
299
|
-
**Parameters**
|
|
300
|
-
|
|
301
|
-
None.
|
|
302
|
-
|
|
303
|
-
**Example:**
|
|
304
|
-
|
|
305
|
-
```typescript example.ts
|
|
306
|
-
// Inline types to simulate AnthropicClient behavior
|
|
307
|
-
interface LLMClientConfig {
|
|
308
|
-
apiKey: string
|
|
309
|
-
model?: string
|
|
310
|
-
timeout?: number
|
|
311
|
-
maxRetries?: number
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
// Simulated AnthropicClient class
|
|
315
|
-
class AnthropicClient {
|
|
316
|
-
private apiKey: string
|
|
317
|
-
private model: string
|
|
318
|
-
private timeout: number
|
|
319
|
-
private maxRetries: number
|
|
320
|
-
|
|
321
|
-
constructor(config: LLMClientConfig) {
|
|
322
|
-
this.apiKey = config.apiKey
|
|
323
|
-
this.model = config.model ?? 'claude-3-5-sonnet-20241022'
|
|
324
|
-
this.timeout = config.timeout ?? 60000
|
|
325
|
-
this.maxRetries = config.maxRetries ?? 2
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
// Anthropic SDK handles credential validation internally —
|
|
329
|
-
// this method simply confirms the client is initialized.
|
|
330
|
-
isConfigured(): boolean {
|
|
331
|
-
return true
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
async complete(prompt: string): Promise<string> {
|
|
335
|
-
if (!this.isConfigured()) {
|
|
336
|
-
throw new Error('Client is not configured. Cannot send requests.')
|
|
337
|
-
}
|
|
338
|
-
// Real implementation would call Anthropic SDK here
|
|
339
|
-
return `Response from ${this.model}: (simulated)`
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
|
|
343
|
-
// --- Usage ---
|
|
344
|
-
|
|
345
|
-
async function runWithGuard(client: AnthropicClient, prompt: string) {
|
|
346
|
-
try {
|
|
347
|
-
// Guard: check configuration before making expensive API calls
|
|
348
|
-
if (!client.isConfigured()) {
|
|
349
|
-
console.warn('Client not ready — skipping request.')
|
|
350
|
-
return null
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
console.log('Client is configured:', client.isConfigured())
|
|
354
|
-
// Output: Client is configured: true
|
|
355
|
-
|
|
356
|
-
const response = await client.complete(prompt)
|
|
357
|
-
console.log('Response:', response)
|
|
358
|
-
// Output: Response: Response from claude-3-5-sonnet-20241022: (simulated)
|
|
359
|
-
|
|
360
|
-
return response
|
|
361
|
-
} catch (error) {
|
|
362
|
-
console.error('Request failed:', error instanceof Error ? error.message : error)
|
|
363
|
-
return null
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
const client = new AnthropicClient({
|
|
368
|
-
apiKey: process.env.ANTHROPIC_API_KEY || 'sk-ant-your-api-key-here',
|
|
369
|
-
model: 'claude-3-5-sonnet-20241022',
|
|
370
|
-
timeout: 30000,
|
|
371
|
-
maxRetries: 3,
|
|
372
|
-
})
|
|
373
|
-
|
|
374
|
-
runWithGuard(client, 'Explain recursion in one sentence.')
|
|
375
|
-
```
|
|
376
|
-
|
|
377
|
-
#### `complete`
|
|
378
|
-
|
|
379
|
-
```typescript
|
|
380
|
-
async complete(request: CompletionRequest): Promise<CompletionResponse>
|
|
381
|
-
```
|
|
382
|
-
|
|
383
|
-
Use this to send a conversation to Anthropic's Claude models and receive a completion response, handling system prompts and multi-turn message history automatically.
|
|
384
|
-
|
|
385
|
-
This method separates system messages from conversation messages internally, so you can pass a unified message array without pre-processing. It falls back to the client's default model if none is specified in the request.
|
|
386
|
-
|
|
387
|
-
## Parameters
|
|
388
|
-
|
|
389
|
-
| Name | Type | Required | Description |
|
|
390
|
-
|------|------|----------|-------------|
|
|
391
|
-
| `request` | `CompletionRequest` | Yes | The completion request object containing messages, optional model override, and generation settings |
|
|
392
|
-
| `request.messages` | `Message[]` | Yes | Array of messages with `role` (`"system"`, `"user"`, `"assistant"`) and `content` string fields |
|
|
393
|
-
| `request.model` | `string` | No | Model identifier (e.g. `"claude-3-5-sonnet-20241022"`). Falls back to the client's configured default model |
|
|
394
|
-
| `request.maxTokens` | `number` | No | Maximum number of tokens to generate in the response |
|
|
395
|
-
| `request.temperature` | `number` | No | Sampling temperature between 0 and 1. Lower = more deterministic |
|
|
396
|
-
|
|
397
|
-
## Returns
|
|
398
|
-
|
|
399
|
-
Returns a `Promise<CompletionResponse>` that resolves with:
|
|
400
|
-
|
|
401
|
-
| Field | Type | Description |
|
|
402
|
-
|-------|------|-------------|
|
|
403
|
-
| `content` | `string` | The generated text from the model |
|
|
404
|
-
| `model` | `string` | The model that was used to generate the response |
|
|
405
|
-
| `usage` | `object` | Token usage stats with `inputTokens` and `outputTokens` |
|
|
406
|
-
| `finishReason` | `string` | Why generation stopped (e.g. `"end_turn"`, `"max_tokens"`) |
|
|
407
|
-
|
|
408
|
-
Throws an error if the Anthropic API request fails or returns a non-successful status.
|
|
409
|
-
|
|
410
|
-
**Example:**
|
|
411
|
-
|
|
412
|
-
```typescript example.ts
|
|
413
|
-
// ── Inline types (no external imports needed) ──────────────────────────────
|
|
414
|
-
|
|
415
|
-
type MessageRole = 'system' | 'user' | 'assistant'
|
|
416
|
-
|
|
417
|
-
interface Message {
|
|
418
|
-
role: MessageRole
|
|
419
|
-
content: string
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
interface CompletionRequest {
|
|
423
|
-
messages: Message[]
|
|
424
|
-
model?: string
|
|
425
|
-
maxTokens?: number
|
|
426
|
-
temperature?: number
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
interface CompletionResponse {
|
|
430
|
-
content: string
|
|
431
|
-
model: string
|
|
432
|
-
usage: {
|
|
433
|
-
inputTokens: number
|
|
434
|
-
outputTokens: number
|
|
435
|
-
}
|
|
436
|
-
finishReason: string
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
// ── Simulated AnthropicClient (mirrors real implementation behavior) ────────
|
|
440
|
-
|
|
441
|
-
class AnthropicClient {
|
|
442
|
-
private model: string
|
|
443
|
-
private apiKey: string
|
|
444
|
-
|
|
445
|
-
constructor(config: { apiKey: string; model?: string }) {
|
|
446
|
-
this.apiKey = config.apiKey
|
|
447
|
-
this.model = config.model || 'claude-3-5-sonnet-20241022'
|
|
448
|
-
}
|
|
449
|
-
|
|
450
|
-
isConfigured(): boolean {
|
|
451
|
-
return true
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
async complete(request: CompletionRequest): Promise<CompletionResponse> {
|
|
455
|
-
const model = request.model || this.model
|
|
456
|
-
|
|
457
|
-
// Separate system message from conversation (mirrors real implementation)
|
|
458
|
-
const systemMessage = request.messages.find(m => m.role === 'system')
|
|
459
|
-
const conversationMessages = request.messages.filter(m => m.role !== 'system')
|
|
460
|
-
|
|
461
|
-
// Build the Anthropic API payload
|
|
462
|
-
const payload = {
|
|
463
|
-
model,
|
|
464
|
-
max_tokens: request.maxTokens ?? 1024,
|
|
465
|
-
temperature: request.temperature ?? 0.7,
|
|
466
|
-
...(systemMessage && { system: systemMessage.content }),
|
|
467
|
-
messages: conversationMessages.map(m => ({
|
|
468
|
-
role: m.role,
|
|
469
|
-
content: m.content,
|
|
470
|
-
})),
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
const response = await fetch('https://api.anthropic.com/v1/messages', {
|
|
474
|
-
method: 'POST',
|
|
475
|
-
headers: {
|
|
476
|
-
'Content-Type': 'application/json',
|
|
477
|
-
'x-api-key': this.apiKey,
|
|
478
|
-
'anthropic-version': '2023-06-01',
|
|
479
|
-
},
|
|
480
|
-
body: JSON.stringify(payload),
|
|
481
|
-
})
|
|
482
|
-
|
|
483
|
-
if (!response.ok) {
|
|
484
|
-
const error = await response.text()
|
|
485
|
-
throw new Error(`Anthropic API error ${response.status}: ${error}`)
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
const data = await response.json() as {
|
|
489
|
-
content: Array<{ type: string; text: string }>
|
|
490
|
-
model: string
|
|
491
|
-
usage: { input_tokens: number; output_tokens: number }
|
|
492
|
-
stop_reason: string
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
return {
|
|
496
|
-
content: data.content.find(b => b.type === 'text')?.text ?? '',
|
|
497
|
-
model: data.model,
|
|
498
|
-
usage: {
|
|
499
|
-
inputTokens: data.usage.input_tokens,
|
|
500
|
-
outputTokens: data.usage.output_tokens,
|
|
501
|
-
},
|
|
502
|
-
finishReason: data.stop_reason,
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
// ── Usage example ──────────────────────────────────────────────────────────
|
|
508
|
-
|
|
509
|
-
const client = new AnthropicClient({
|
|
510
|
-
apiKey: process.env.ANTHROPIC_API_KEY || 'your-anthropic-api-key',
|
|
511
|
-
model: 'claude-3-5-sonnet-20241022',
|
|
512
|
-
})
|
|
513
|
-
|
|
514
|
-
async function main() {
|
|
515
|
-
try {
|
|
516
|
-
const response = await client.complete({
|
|
517
|
-
messages: [
|
|
518
|
-
{
|
|
519
|
-
role: 'system',
|
|
520
|
-
content: 'You are a concise assistant. Reply in one sentence.',
|
|
521
|
-
},
|
|
522
|
-
{
|
|
523
|
-
role: 'user',
|
|
524
|
-
content: 'What is the capital of Japan?',
|
|
525
|
-
},
|
|
526
|
-
],
|
|
527
|
-
maxTokens: 256,
|
|
528
|
-
temperature: 0.3,
|
|
529
|
-
})
|
|
530
|
-
|
|
531
|
-
console.log('Reply: ', response.content)
|
|
532
|
-
console.log('Model used: ', response.model)
|
|
533
|
-
console.log('Tokens used: ', response.usage)
|
|
534
|
-
console.log('Finish reason:', response.finishReason)
|
|
535
|
-
|
|
536
|
-
// Expected output:
|
|
537
|
-
// Reply: The capital of Japan is Tokyo.
|
|
538
|
-
// Model used: claude-3-5-sonnet-20241022
|
|
539
|
-
// Tokens used: { inputTokens: 32, outputTokens: 10 }
|
|
540
|
-
// Finish reason: end_turn
|
|
541
|
-
} catch (error) {
|
|
542
|
-
console.error('Completion failed:', error)
|
|
543
|
-
process.exit(1)
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
main()
|
|
548
|
-
```
|
|
549
|
-
|