1
- import fetch from 'node-fetch ' ;
1
+ import { Anthropic } from '@anthropic-ai/sdk ' ;
2
2
import fs from 'fs/promises' ;
3
3
import path from 'path' ;
4
4
@@ -7,54 +7,27 @@ async function getAnthropicKey() {
7
7
return ( await fs . readFile ( keyPath , 'utf8' ) ) . trim ( ) ;
8
8
}
9
9
10
- export async function ask ( { system, prompt, model = 'claude-3-opus-20240229' , temperature = 1 , debug = true } ) {
11
- const anthropicKey = await getAnthropicKey ( ) ;
12
- const response = await fetch ( 'https://api.anthropic.com/v1/messages' , {
13
- method : 'POST' ,
14
- headers : {
15
- 'Content-Type' : 'application/json' ,
16
- 'X-API-Key' : anthropicKey ,
17
- 'anthropic-version' : '2023-06-01' ,
18
- } ,
19
- body : JSON . stringify ( {
10
+ export async function ask ( { system, prompt, max_tokens, model = 'claude-3-opus-20240229' , temperature = 1 , debug = true } ) {
11
+ const anthropic = new Anthropic ( { apiKey : await getAnthropicKey ( ) } ) ;
12
+ if ( debug ) {
13
+ const stream = anthropic . messages . stream ( {
20
14
model,
21
15
messages : [ { role : 'user' , content : prompt } ] ,
22
- max_tokens : 1000 ,
16
+ max_tokens : max_tokens || 4096 ,
23
17
temperature,
24
- stream : debug ,
25
18
...( system && { system } ) ,
26
- } ) ,
27
- } ) ;
28
-
29
- if ( ! response . ok ) {
30
- const errorBody = await response . text ( ) ;
31
- throw new Error ( `Anthropic API request failed with status ${ response . status } : ${ errorBody } ` ) ;
32
- }
33
-
34
- if ( debug ) {
35
- let result = '' ;
36
- for await ( const chunk of response . body ) {
37
- const textChunk = new TextDecoder ( ) . decode ( chunk ) ;
38
- const lines = textChunk . split ( '\n' ) ;
39
- for ( const line of lines ) {
40
- if ( line . startsWith ( 'data:' ) ) {
41
- try {
42
- const data = JSON . parse ( line . slice ( 5 ) ) ;
43
- if ( data . type === 'content_block_delta' && data . delta . type === 'text_delta' ) {
44
- process . stdout . write ( data . delta . text ) ;
45
- result += data . delta . text ;
46
- }
47
- } catch ( error ) {
48
- // Skip the line if JSON parsing fails
49
- console . error ( 'Error parsing JSON:' , error . message ) ;
50
- }
51
- }
52
- }
53
- }
19
+ } ) . on ( 'text' , ( text ) => process . stdout . write ( text ) ) ;
20
+ const message = await stream . finalMessage ( ) ;
54
21
console . log ( ) ; // Add a newline at the end
55
- return result ;
22
+ return message . content ;
56
23
} else {
57
- const { content } = await response . json ( ) ;
58
- return content [ 0 ] . text ;
24
+ const message = await anthropic . messages . create ( {
25
+ model,
26
+ messages : [ { role : 'user' , content : prompt } ] ,
27
+ max_tokens : max_tokens || 4096 ,
28
+ temperature,
29
+ ...( system && { system } ) ,
30
+ } ) ;
31
+ return message . content ;
59
32
}
60
33
}
0 commit comments