(model: TypeChatLanguageModel, schema: string, typeName: string)
| 13 | } |
| 14 | |
| 15 | export function createAgentRouter<T extends object>(model: TypeChatLanguageModel, schema: string, typeName: string): AgentRouter<T> { |
| 16 | const validator = createTypeScriptJsonValidator<TaskClassificationResponse>(schema, typeName) |
| 17 | const taskClassifier = createJsonTranslator<TaskClassificationResponse>(model, validator); |
| 18 | const router: AgentRouter<T> = { |
| 19 | _taskTypes: [], |
| 20 | _agentMap: {}, |
| 21 | _taskClassifier: taskClassifier, |
| 22 | _handlerUnknownTask: handlerUnknownTask, |
| 23 | registerAgent, |
| 24 | routeRequest: routeRequest, |
| 25 | }; |
| 26 | |
| 27 | router._taskTypes.push({ |
| 28 | name: "No Match", |
| 29 | description: "Handles all unrecognized requests" |
| 30 | }); |
| 31 | |
| 32 | return router; |
| 33 | |
| 34 | async function handlerUnknownTask(request: string): Promise<Result<T>> { |
| 35 | console.log(`🤖The request "${request}" was not recognized by any agent.`); |
| 36 | return { success: false, message: `The request "${request}" was not recognized by any agent.` }; |
| 37 | } |
| 38 | |
| 39 | async function registerAgent(name: string, agent: Agent<T>): Promise<void> { |
| 40 | if (!router._agentMap[name]) { |
| 41 | router._agentMap[name] = agent; |
| 42 | |
| 43 | // Add the agent's task type to the list of task types |
| 44 | router._taskTypes.push({name: name, description: agent.description}); |
| 45 | } |
| 46 | return; |
| 47 | } |
| 48 | |
| 49 | async function routeRequest(request:string): Promise<void> { |
| 50 | const initClasses = JSON.stringify(router._taskTypes, undefined, 2); |
| 51 | const fullRequest = ` |
| 52 | Classify "${request}" using the following classification table:\n |
| 53 | ${initClasses}\n`; |
| 54 | const response = await router._taskClassifier.translate(request, [{ |
| 55 | role: "assistant", content: `${fullRequest}` |
| 56 | }]); |
| 57 | |
| 58 | if (response.success) { |
| 59 | if (response.data.taskType != "No Match") { |
| 60 | const agentName = response.data.taskType; |
| 61 | console.log(`🤖 The task will be handled by the ${agentName} Agent.`); |
| 62 | const agent = router._agentMap[agentName]; |
| 63 | await agent.handleMessage(request); |
| 64 | } |
| 65 | else { |
| 66 | router._handlerUnknownTask(request); |
| 67 | } |
| 68 | } |
| 69 | else { |
| 70 | console.log("🙈 Sorry, we could not find an agent to handle your request.\n") |
| 71 | console.log(`Context: ${response.message}`) |
| 72 | } |
no test coverage detected