Skip to content

Commit 4bb2ff0

Browse files
committed
Simpler loop
1 parent f057aca commit 4bb2ff0

File tree

2 files changed

+15
-14
lines changed

2 files changed

+15
-14
lines changed

packages/mcp-client/cli.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ if (process.env.EXPERIMENTAL_HF_MCP_SERVER) {
3535
});
3636
}
3737

38+
let SAMPLE_INPUT = process.env.USE_SAMPLE_INPUT
39+
? `generate a haiku about Hugging Face and save it to a file name hf.txt on my Desktop`
40+
: undefined;
41+
3842
async function main() {
3943
if (!process.env.HF_TOKEN) {
4044
console.error(`a valid HF_TOKEN must be present in the env`);

packages/mcp-client/src/McpClient.ts

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -84,31 +84,24 @@ export class McpClient {
8484
tool_choice: "auto",
8585
});
8686

87-
const firstChunkResult = await stream.next();
88-
if (firstChunkResult.done) {
89-
return;
90-
}
91-
const firstChunk = firstChunkResult.value;
92-
const firstToolCalls = firstChunk.choices[0]?.delta.tool_calls;
93-
if ((!firstToolCalls || firstToolCalls.length === 0) && opts.exitIfFirstChunkNoTool) {
94-
return;
95-
}
96-
yield firstChunk;
97-
debug(firstChunk.choices[0]);
9887
const message = {
99-
role: firstChunk.choices[0].delta.role,
100-
content: firstChunk.choices[0].delta.content,
88+
role: "unknown",
89+
content: "",
10190
} satisfies ChatCompletionInputMessage;
102-
10391
const finalToolCalls: Record<number, ChatCompletionStreamOutputDeltaToolCall> = {};
92+
let numOfChunks = 0;
10493

10594
for await (const chunk of stream) {
10695
yield chunk;
10796
debug(chunk.choices[0]);
97+
numOfChunks++;
10898
const delta = chunk.choices[0]?.delta;
10999
if (!delta) {
110100
continue;
111101
}
102+
if (delta.role) {
103+
message.role = delta.role;
104+
}
112105
if (delta.content) {
113106
message.content += delta.content;
114107
}
@@ -124,6 +117,10 @@ export class McpClient {
124117
finalToolCalls[toolCall.index].function.arguments += toolCall.function.arguments;
125118
}
126119
}
120+
if (opts.exitIfFirstChunkNoTool && numOfChunks <= 2 && Object.keys(finalToolCalls).length === 0) {
121+
/// If no tool is present in chunk number 1 or 2, exit.
122+
return;
123+
}
127124
}
128125

129126
messages.push(message);

0 commit comments

Comments
 (0)