11import { describe , expect , it } from 'vitest' ;
2- import { messagesFromParams , shouldInstrument } from '../../../src/tracing/anthropic-ai/utils' ;
2+ import { messagesFromParams , setMessagesAttribute , shouldInstrument } from '../../../src/tracing/anthropic-ai/utils' ;
3+ import type { Span } from '../../../src/types-hoist/span' ;
34
45describe ( 'anthropic-ai-utils' , ( ) => {
56 describe ( 'shouldInstrument' , ( ) => {
@@ -25,6 +26,19 @@ describe('anthropic-ai-utils', () => {
2526 ] ) ;
2627 } ) ;
2728
29+ it ( 'looks to params.input ahead of params.messages' , ( ) => {
30+ expect (
31+ messagesFromParams ( {
32+ input : [ { role : 'user' , content : 'input' } ] ,
33+ messages : [ { role : 'user' , content : 'hello' } ] ,
34+ system : 'You are a friendly robot awaiting a greeting.' ,
35+ } ) ,
36+ ) . toStrictEqual ( [
37+ { role : 'system' , content : 'You are a friendly robot awaiting a greeting.' } ,
38+ { role : 'user' , content : 'input' } ,
39+ ] ) ;
40+ } ) ;
41+
2842 it ( 'includes system message along with non-array messages' , ( ) => {
2943 expect (
3044 messagesFromParams ( {
@@ -53,4 +67,42 @@ describe('anthropic-ai-utils', () => {
5367 ) . toStrictEqual ( [ { role : 'user' , content : 'hello' } ] ) ;
5468 } ) ;
5569 } ) ;
70+
71+ describe ( 'setMessagesAtribute' , ( ) => {
72+ const mock = {
73+ attributes : { } as Record < string , any > ,
74+ setAttributes ( kv : Record < string , any > ) {
75+ for ( const [ key , val ] of Object . entries ( kv ) ) {
76+ // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
77+ if ( val === undefined ) delete this . attributes [ key ] ;
78+ else this . attributes [ key ] = val ;
79+ }
80+ } ,
81+ } ;
82+ const span = mock as unknown as Span ;
83+
84+ it ( 'sets length along with truncated value' , ( ) => {
85+ const content = 'A' . repeat ( 200_000 ) ;
86+ setMessagesAttribute ( span , [ { role : 'user' , content } ] ) ;
87+ const result = [ { role : 'user' , content : 'A' . repeat ( 19972 ) } ] ;
88+ expect ( mock . attributes ) . toStrictEqual ( {
89+ "gen_ai.request.messages.original_length" : 1 ,
90+ 'gen_ai.request.messages' : JSON . stringify ( result ) ,
91+ } ) ;
92+ } ) ;
93+
94+ it ( 'removes length when setting new value ' , ( ) => {
95+ setMessagesAttribute ( span , { content : 'hello, world' } ) ;
96+ expect ( mock . attributes ) . toStrictEqual ( {
97+ 'gen_ai.request.messages' : '{"content":"hello, world"}' ,
98+ } ) ;
99+ } ) ;
100+
101+ it ( 'ignores empty array' , ( ) => {
102+ setMessagesAttribute ( span , [ ] ) ;
103+ expect ( mock . attributes ) . toStrictEqual ( {
104+ 'gen_ai.request.messages' : '{"content":"hello, world"}' ,
105+ } ) ;
106+ } ) ;
107+ } ) ;
56108} ) ;
0 commit comments