1
1
import { ToolResultStatus , type ToolCall , type ToolResult } from "$lib/types/Tool" ;
2
2
import { v4 as uuidV4 } from "uuid" ;
3
- import JSON5 from "json5" ;
4
3
import type { BackendTool , BackendToolContext } from "../tools" ;
5
4
import {
6
5
MessageToolUpdateType ,
@@ -15,7 +14,7 @@ import directlyAnswer from "../tools/directlyAnswer";
15
14
import websearch from "../tools/web/search" ;
16
15
import { z } from "zod" ;
17
16
import { logger } from "../logger" ;
18
- import { toolHasName } from "../tools/utils" ;
17
+ import { extractJson , toolHasName } from "../tools/utils" ;
19
18
import type { MessageFile } from "$lib/types/Message" ;
20
19
import { mergeAsyncGenerators } from "$lib/utils/mergeAsyncGenerators" ;
21
20
import { MetricsServer } from "../metrics" ;
@@ -143,33 +142,23 @@ export async function* runTools(
143
142
// look for a code blocks of ```json and parse them
144
143
// if they're valid json, add them to the calls array
145
144
if ( output . generated_text ) {
146
- if ( ! output . generated_text . endsWith ( "```" ) ) {
147
- output . generated_text = output . generated_text + "```" ;
148
- }
149
- const codeBlocks = Array . from ( output . generated_text . matchAll ( / ` ` ` j s o n \n ( .* ?) ` ` ` / gs) )
150
- . map ( ( [ , block ] ) => block )
151
- // remove trailing comma
152
- . map ( ( block ) => block . trim ( ) . replace ( / , $ / , "" ) ) ;
153
- if ( codeBlocks . length === 0 ) continue ;
154
- // grab only the capture group from the regex match
155
- for ( const block of codeBlocks ) {
156
- // make it an array if it's not already
157
- let call = JSON5 . parse ( block ) ;
158
- if ( ! Array . isArray ( call ) ) {
159
- call = [ call ] ;
160
- }
161
-
162
- try {
163
- calls . push ( ...call . filter ( isExternalToolCall ) . map ( externalToToolCall ) . filter ( Boolean ) ) ;
164
- } catch ( e ) {
165
- logger . error ( e , "Error while parsing tool calls, please retry" ) ;
166
- // error parsing the calls
167
- yield {
168
- type : MessageUpdateType . Status ,
169
- status : MessageUpdateStatus . Error ,
170
- message : "Error while parsing tool calls, please retry" ,
171
- } ;
172
- }
145
+ logger . info ( output . generated_text ) ;
146
+ try {
147
+ const rawCalls = await extractJson ( output . generated_text ) ;
148
+ const newCalls = rawCalls
149
+ . filter ( isExternalToolCall )
150
+ . map ( externalToToolCall )
151
+ . filter ( ( call ) => call !== undefined ) as ToolCall [ ] ;
152
+
153
+ calls . push ( ...newCalls ) ;
154
+ } catch ( e ) {
155
+ logger . error ( e , "Error while parsing tool calls, please retry" ) ;
156
+ // error parsing the calls
157
+ yield {
158
+ type : MessageUpdateType . Status ,
159
+ status : MessageUpdateStatus . Error ,
160
+ message : "Error while parsing tool calls, please retry" ,
161
+ } ;
173
162
}
174
163
}
175
164
}
0 commit comments