@@ -2,15 +2,20 @@ import {
2
2
LanguageModelV1Prompt ,
3
3
UnsupportedFunctionalityError ,
4
4
} from '@ai-sdk/provider' ;
5
- import { convertUint8ArrayToBase64 } from '@ai-sdk/provider-utils' ;
5
+ import { convertUint8ArrayToBase64 , download } from '@ai-sdk/provider-utils' ;
6
6
import {
7
7
AnthropicMessage ,
8
8
AnthropicMessagesPrompt ,
9
+ AnthropicUserMessage ,
9
10
} from './anthropic-messages-prompt' ;
10
11
11
- export function convertToAnthropicMessagesPrompt (
12
- prompt : LanguageModelV1Prompt ,
13
- ) : AnthropicMessagesPrompt {
12
+ export async function convertToAnthropicMessagesPrompt ( {
13
+ prompt,
14
+ downloadImplementation = download ,
15
+ } : {
16
+ prompt : LanguageModelV1Prompt ;
17
+ downloadImplementation ?: typeof download ;
18
+ } ) : Promise < AnthropicMessagesPrompt > {
14
19
let system : string | undefined = undefined ;
15
20
const messages : AnthropicMessage [ ] = [ ] ;
16
21
@@ -28,32 +33,45 @@ export function convertToAnthropicMessagesPrompt(
28
33
}
29
34
30
35
case 'user' : {
31
- messages . push ( {
32
- role : 'user' ,
33
- content : content . map ( part => {
34
- switch ( part . type ) {
35
- case 'text' : {
36
- return { type : 'text' , text : part . text } ;
37
- }
38
- case 'image' : {
39
- if ( part . image instanceof URL ) {
40
- throw new UnsupportedFunctionalityError ( {
41
- functionality : 'URL image parts' ,
42
- } ) ;
43
- } else {
44
- return {
45
- type : ' image' ,
46
- source : {
47
- type : 'base64' ,
48
- media_type : part . mimeType ?? 'image/jpeg' ,
49
- data : convertUint8ArrayToBase64 ( part . image ) ,
50
- } ,
51
- } ;
52
- }
36
+ const anthropicContent : AnthropicUserMessage [ 'content' ] = [ ] ;
37
+
38
+ for ( const part of content ) {
39
+ switch ( part . type ) {
40
+ case 'text' : {
41
+ anthropicContent . push ( { type : 'text' , text : part . text } ) ;
42
+ break ;
43
+ }
44
+ case ' image' : {
45
+ let data : Uint8Array ;
46
+ let mimeType : string | undefined ;
47
+
48
+ if ( part . image instanceof URL ) {
49
+ const downloadResult = await downloadImplementation ( {
50
+ url : part . image ,
51
+ } ) ;
52
+
53
+ data = downloadResult . data ;
54
+ mimeType = downloadResult . mimeType ;
55
+ } else {
56
+ data = part . image ;
57
+ mimeType = part . mimeType ;
53
58
}
59
+
60
+ anthropicContent . push ( {
61
+ type : 'image' ,
62
+ source : {
63
+ type : 'base64' ,
64
+ media_type : mimeType ?? 'image/jpeg' ,
65
+ data : convertUint8ArrayToBase64 ( data ) ,
66
+ } ,
67
+ } ) ;
68
+
69
+ break ;
54
70
}
55
- } ) ,
56
- } ) ;
71
+ }
72
+ }
73
+
74
+ messages . push ( { role : 'user' , content : anthropicContent } ) ;
57
75
break ;
58
76
}
59
77
0 commit comments