1+ import { trackEvent } from '@codebuff/common/analytics'
2+ import { Model } from '@codebuff/common/constants'
3+ import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
14import {
25 endsAgentStepParam ,
36 endToolTag ,
@@ -37,7 +40,12 @@ export async function* processStreamWithTags(
3740 onTagEnd : ( tagName : string , params : Record < string , any > ) => void
3841 }
3942 > ,
40- onError : ( tagName : string , errorMessage : string ) => void
43+ onError : ( tagName : string , errorMessage : string ) => void ,
44+ loggerOptions ?: {
45+ userId ?: string
46+ model ?: Model
47+ agentName ?: string
48+ }
4149) : AsyncGenerator < string > {
4250 let streamCompleted = false
4351 let buffer = ''
@@ -62,16 +70,49 @@ export async function* processStreamWithTags(
6270 try {
6371 parsedParams = JSON . parse ( contents )
6472 } catch ( error : any ) {
65- onError ( 'parse_error' , error . message )
73+ trackEvent (
74+ AnalyticsEvent . MALFORMED_TOOL_CALL_JSON ,
75+ loggerOptions ?. userId ?? '' ,
76+ {
77+ contents,
78+ model : loggerOptions ?. model ,
79+ agent : loggerOptions ?. agentName ,
80+ }
81+ )
82+ const shortenedContents =
83+ contents . length < 50
84+ ? contents
85+ : contents . slice ( 0 , 20 ) + '...' + contents . slice ( - 20 )
86+ onError (
87+ 'parse_error' ,
88+ `Invalid JSON: ${ JSON . stringify ( shortenedContents ) } \nError: ${ error . message } `
89+ )
6690 return
6791 }
6892
6993 const toolName = parsedParams [ toolNameParam ] as keyof typeof processors
7094 if ( ! processors [ toolName ] ) {
95+ trackEvent (
96+ AnalyticsEvent . UNKNOWN_TOOL_CALL ,
97+ loggerOptions ?. userId ?? '' ,
98+ {
99+ contents,
100+ toolName,
101+ model : loggerOptions ?. model ,
102+ agent : loggerOptions ?. agentName ,
103+ }
104+ )
71105 onError ( toolName , `Tool not found: ${ toolName } ` )
72106 return
73107 }
74108
109+ trackEvent ( AnalyticsEvent . TOOL_USE , loggerOptions ?. userId ?? '' , {
110+ toolName,
111+ contents,
112+ parsedParams,
113+ model : loggerOptions ?. model ,
114+ agent : loggerOptions ?. agentName ,
115+ } )
75116 delete parsedParams [ toolNameParam ]
76117
77118 processors [ toolName ] . onTagStart ( toolName , { } )
0 commit comments