|
| 1 | +import { |
| 2 | + addCompletion, |
| 3 | + type ICompletionArgs, |
| 4 | + type IModelMessage, |
| 5 | +} from "agent-swarm-kit"; |
| 6 | +import { CompletionName } from "../enum/CompletionName"; |
| 7 | +import { InferenceClient } from "@huggingface/inference"; |
| 8 | + |
| 9 | +const client = new InferenceClient(process.env.HF_API_KEY); |
| 10 | + |
| 11 | +addCompletion({ |
| 12 | + completionName: CompletionName.HfCompletion, |
| 13 | + getCompletion: async ({ |
| 14 | + agentName, |
| 15 | + messages: rawMessages, |
| 16 | + mode, |
| 17 | + tools: rawTools, |
| 18 | + }: ICompletionArgs): Promise<IModelMessage> => { |
| 19 | + const messages = rawMessages.map( |
| 20 | + ({ role, content, tool_calls, tool_call_id }) => { |
| 21 | + if (role === "tool") { |
| 22 | + return { |
| 23 | + role: "tool" as const, |
| 24 | + content, |
| 25 | + tool_call_id: tool_call_id!, |
| 26 | + }; |
| 27 | + } |
| 28 | + if (role === "assistant" && tool_calls) { |
| 29 | + return { |
| 30 | + role: "assistant" as const, |
| 31 | + content, |
| 32 | + tool_calls: tool_calls.map((tc) => ({ |
| 33 | + id: tc.id, |
| 34 | + type: tc.type, |
| 35 | + function: { |
| 36 | + name: tc.function.name, |
| 37 | + arguments: |
| 38 | + typeof tc.function.arguments === "string" |
| 39 | + ? tc.function.arguments |
| 40 | + : JSON.stringify(tc.function.arguments), |
| 41 | + }, |
| 42 | + })), |
| 43 | + }; |
| 44 | + } |
| 45 | + return { |
| 46 | + role: role as "user" | "assistant" | "system", |
| 47 | + content, |
| 48 | + }; |
| 49 | + } |
| 50 | + ); |
| 51 | + |
| 52 | + const tools = rawTools?.map(({ function: f }) => ({ |
| 53 | + type: "function" as const, |
| 54 | + function: { |
| 55 | + name: f.name, |
| 56 | + description: f.description, |
| 57 | + parameters: f.parameters, |
| 58 | + }, |
| 59 | + })); |
| 60 | + |
| 61 | + const completion = await client.chatCompletion({ |
| 62 | + model: "openai/gpt-oss-120b", |
| 63 | + messages, |
| 64 | + ...(tools && { tools }), |
| 65 | + }); |
| 66 | + |
| 67 | + const choice = completion.choices[0]; |
| 68 | + const text = choice.message.content || ""; |
| 69 | + const tool_calls = choice.message.tool_calls || []; |
| 70 | + |
| 71 | + const result = { |
| 72 | + content: text, |
| 73 | + mode, |
| 74 | + agentName: agentName!, |
| 75 | + role: "assistant" as const, |
| 76 | + tool_calls: tool_calls.map(({ id, type, function: f }) => ({ |
| 77 | + id: id!, |
| 78 | + type: type as "function", |
| 79 | + function: { |
| 80 | + name: f.name, |
| 81 | + arguments: |
| 82 | + typeof f.arguments === "string" |
| 83 | + ? JSON.parse(f.arguments) |
| 84 | + : f.arguments, |
| 85 | + }, |
| 86 | + })), |
| 87 | + }; |
| 88 | + |
| 89 | + return result; |
| 90 | + }, |
| 91 | +}); |
0 commit comments