import { SDK } from "@meetkai/mka1";
const sdk = new SDK({
bearerAuth: process.env.MKA1_API_KEY!,
});
const spawnSubagentTool = {
type: "function" as const,
name: "spawn_subagent",
description: "Delegate a focused task to a child response and return the result.",
strict: true,
parameters: {
type: "object",
properties: {
task: { type: "string" },
instructions: { type: "string" },
model: { type: "string" },
},
required: ["task"],
additionalProperties: false,
},
};
type SpawnSubagentArgs = {
task: string;
instructions?: string;
model?: string;
};
async function runChildResponse(args: SpawnSubagentArgs) {
const child = await sdk.llm.responses.create({
model: args.model ?? "meetkai:functionary-urdu-mini-pak",
instructions:
args.instructions ??
"You are a specialist assistant. Complete the task and return the result only.",
input: args.task,
store: true,
});
return {
response_id: child.id,
output_text: child.outputText,
};
}
export async function runDelegatingAgent(input: string) {
let response = await sdk.llm.responses.create({
model: "meetkai:functionary-urdu-mini-pak",
instructions:
"You are an orchestrator. Use spawn_subagent for focused side tasks. You may call it multiple times in one turn when tasks can be parallelized. After all tool results return, answer the user directly.",
input,
tools: [spawnSubagentTool],
tool_choice: "auto",
parallel_tool_calls: true,
max_tool_calls: 8,
store: true,
});
while (true) {
const toolCalls = response.output.filter(
(item): item is {
type: "function_call";
name: string;
call_id: string;
arguments: string;
} => item.type === "function_call" && item.name === "spawn_subagent",
);
if (toolCalls.length === 0) {
return response.outputText;
}
const toolOutputs = await Promise.all(
toolCalls.map(async (toolCall) => {
const args = JSON.parse(toolCall.arguments) as SpawnSubagentArgs;
const childResult = await runChildResponse(args);
return {
type: "function_call_output" as const,
call_id: toolCall.call_id,
output: JSON.stringify(childResult),
};
}),
);
response = await sdk.llm.responses.create({
model: response.model,
previous_response_id: response.id,
input: toolOutputs,
tools: [spawnSubagentTool],
parallel_tool_calls: true,
max_tool_calls: 8,
store: true,
});
}
}