Hello there,
i was trying to utilize tool calling function feature, so i will execute a certain function that will return some values knowing that I’m using ai assistance.
what i want to do is taking the output of my function and send it back to my ai assistant with certain content message i have tried several way of using nested thread and run creation but seems I’m missing something down below is a snippet, in case you could suggest any help or idea .
The calling function is working successfully but not sure what next to do to send it back to the AI assistance and get back. the response.
async function handleUserMessage(userMessage, model, res, threadId = null) {
try {
if (!threadId) {
const thread = await openai.beta.threads.create();
threadId = thread.id;
}
await openai.beta.threads.messages.create(threadId, {
role: "user",
content: userMessage,
});
const run = openai.beta.threads.runs.stream(threadId, {
assistant_id: "asst_lec9aDPSIBAELd",
model: model,
tool_choice: "auto",
tools: tools,
});
let runId;
let fullResponse = "";
run
.on("event", async (event) => {
runId = await event.data.id;
console.log("Run ID captured:", runId);
})
.on("textDelta", (textDelta) => {
fullResponse += textDelta.value;
})
.on("toolCallDone", async (toolCallDone) => {
if (toolCallDone.type === "function") {
const toolOutputs = [];
const args = JSON.parse(toolCallDone.function.arguments);
const toolCallId = toolCallDone.id;
const funcOutput = await fetchIssues(args);
console.log("Function Output:", funcOutput);
toolOutputs.push({
tool_call_id: toolCallId,
output: JSON.stringify(funcOutput),
});
// Submit tool outputs
const x = openai.beta.threads.runs.submitToolOutputsStream(
threadId,
runId,
{
tool_outputs: toolOutputs,
}
);
x.on("textDelta", (textDelta) => {
fullResponse += textDelta.value;
});
console.log("Tool outputs submitted successfully.");
}
})
.on("end", () => {
if (!res.headersSent) {
res.status(200).json({ message: fullResponse, threadId });
}
})
.on("error", (error) => {
console.error("Stream error:", error);
if (!res.headersSent) {
res.status(500).send("Error streaming response from OpenAI");
}
});
} catch (error) {
console.error("Error handling user message:", error);
if (!res.headersSent) {
res.status(500).send("Error communicating with OpenAI");
}
}
}