summaryrefslogtreecommitdiff
path: root/backend/instance/tools-utils.ts
diff options
context:
space:
mode:
Diffstat (limited to 'backend/instance/tools-utils.ts')
-rw-r--r--backend/instance/tools-utils.ts62
1 files changed, 62 insertions, 0 deletions
diff --git a/backend/instance/tools-utils.ts b/backend/instance/tools-utils.ts
new file mode 100644
index 0000000..c3a0778
--- /dev/null
+++ b/backend/instance/tools-utils.ts
@@ -0,0 +1,62 @@
+import fs from 'fs';
+
+import { ToolCall, ChatOptions, ChatMsg } from './api-defs.js';
+
+export type Call = ToolCall;
+
+let toolsList = JSON.parse( fs.readFileSync( "../data/modeltools.json", "utf8" ) );
+
+export function getPromptStr( options: ChatOptions ) {
+ let toolsArr: any[] = [];
+ for( let tool of toolsList ) {
+ for( let [capability, val] of Object.entries( options.model.capabilities ) ) {
+ if( val && capability.toString().toLowerCase() == tool.function.name.toLowerCase() )
+ toolsArr.push( tool );
+ }
+ }
+
+ return JSON.stringify( toolsArr );
+}
+
+export function isToolStr( buf: string ) {
+ let trimmed = buf.replace( /\s+/g, '' ).toLowerCase();
+ for( let tool of toolsList ) {
+ let name = tool.function.name.toLowerCase();
+ let str = `{"name":"${name}"`;
+
+ let notMatched = false;
+ for( let i = 0; i < Math.min( trimmed.length, str.length ); ++i ) {
+ if( trimmed[i] != str[i] ) {
+ notMatched = true;
+ break;
+ }
+ }
+
+ if( !notMatched )
+ return true;
+ }
+
+ return false;
+}
+
+export function getCall( msg: ChatMsg ) : Call | null {
+ let firstBracket = msg.content.indexOf( "{" );
+ let lastBracket = msg.content.lastIndexOf( "}" );
+ if( firstBracket == -1 || lastBracket == -1 )
+ return null;
+ let toolCall = msg.content.substring( firstBracket, lastBracket + 1 );
+ let json: Call;
+ try {
+ json = JSON.parse( toolCall );
+ } catch( e ) {
+ return null;
+ }
+
+ for( let tool of toolsList ) {
+ if( tool.function.name.toLowerCase() == json.name.toLowerCase() ) {
+ return json;
+ }
+ }
+
+ return null;
+}