import OpenAI from "openai";
import { z } from "zod";
const openai = new OpenAI({
baseURL: "https://api.inference.net/v1",
apiKey: process.env.INFERENCE_API_KEY,
});
const Step = z.object({
explanation: z.string(),
output: z.string(),
});
const MathResponse = z.object({
steps: z.array(Step),
final_answer: z.string(),
});
try {
const completion = await openai.chat.completions.create({
model: "mistralai/mistral-nemo-12b-instruct/fp-8",
messages: [
{
role: "system",
content: "You are a helpful math tutor. Guide the user through the solution step by step. Respond in JSON format.",
},
{
role: "user",
content: "how can I solve 8x + 7 = -23"
},
],
response_format: {
type: "json_schema",
json_schema: {
name: "math_response",
schema: {
type: "object",
properties: {
steps: {
type: "array",
items: {
type: "object",
properties: {
explanation: { type: "string" },
output: { type: "string" },
},
required: ["explanation", "output"],
additionalProperties: false,
},
},
final_answer: { type: "string" },
},
required: ["steps", "final_answer"],
additionalProperties: false,
},
strict: true,
},
},
max_tokens: 20, // setting max_tokens to 20 to test the error handling
});
// Log the raw response for debugging
const math_response = completion.choices[0].message;
console.log("Raw response:", math_response);
// Check for incomplete response
if (completion.choices[0].finish_reason === "length") {
console.log("Model did not return a complete response so parsing failed.");
throw new Error("Incomplete response");
}
// Use zod to validate the response
try {
const parsed = MathResponse.parse(math_response);
console.log("Parsed math response:", parsed);
} catch (zodError) {
console.error("Response does not match the expected schema:", math_response);
}
} catch (e) {
// Handle edge cases
console.error(e);
}
// Raw response: {
// content: "{\n \"steps\": [\n {\n \"explanation\": \"Step 1: Subtract",
// reasoning_content: "",
// role: "assistant",
// tool_calls: [],
// }
// Response does not match the expected schema: {
// content: "{\n \"steps\": [\n {\n \"explanation\": \"Step 1: Subtract",
// reasoning_content: "",
// role: "assistant",
// tool_calls: [],
// }