How do you use Mistral Function Calling and JSON mode via their official TypeScript client? | A1Lab@HamzaM to AI & LLMEnglish • 20 hours ago

How do you use Mistral Function Calling and JSON mode via their official TypeScript client?

message-square
0

Overview

With the official @mistralai/mistralai TypeScript client, you use Function Calling to let the AI run your local functions and JSON Mode to force the AI to reply only in valid JSON format. Everything is combined in one single copy-pasteable Markdown block with very simple English.

  • Function calling connects AI to your code: The AI asks to run your function, your code runs it, and you send the answer back to the AI.
  • JSON mode guarantees clean data: Setting responseFormat to json_object makes sure the AI replies with a valid JSON string you can safely parse.

Steps

  1. Create the Mistral client: Import Mistral from @mistralai/mistralai and pass your API key.
  2. Define your tool and send the first request: Give the AI a list of tools and set toolChoice: "auto" so it can call your function.
  3. Run the function and send the result back: Run your local function and send the output back using role: "tool" and the matching toolCallId.
  4. Get JSON output in the same flow: Call client.chat.complete() with responseFormat: { type: "json_object" } and parse the reply with JSON.parse().

Example

import { Mistral } from "@mistralai/mistralai";

// 1. Simple local function that the AI can call
function getOrderStatus(orderId: string): string {
  const fakeDatabase: Record<string, string> = {
    ORD_101: "Shipped - arriving tomorrow",
    ORD_102: "Processing in warehouse",
  };

  const status = fakeDatabase[orderId] ?? "Order not found";
  return JSON.stringify({ orderId, status });
}

// 2. One combined function for both Function Calling and JSON Mode
export async function runMistralCombined(apiKey: string) {
  const client = new Mistral({ apiKey });
  const model = "mistral-large-latest";

  // --- PART A: FUNCTION CALLING ---
  const tools = [
    {
      type: "function" as const,
      function: {
        name: "get_order_status",
        description: "Check the shipping status of an order using its ID.",
        parameters: {
          type: "object",
          properties: {
            orderId: {
              type: "string",
              description: "The order ID, for example ORD_101",
            },
          },
          required: ["orderId"],
        },
      },
    },
  ];

  const messages: Array<Record<string, unknown>> = [
    { role: "user", content: "Where is my order ORD_101?" },
  ];

  const firstReply = await client.chat.complete({
    model,
    messages: messages as never,
    tools,
    toolChoice: "auto",
  });

  const aiMessage = firstReply.choices?.[0]?.message;
  if (!aiMessage) throw new Error("No reply from Mistral");

  messages.push(aiMessage as unknown as Record<string, unknown>);

  if (aiMessage.toolCalls && aiMessage.toolCalls.length > 0) {
    for (const toolCall of aiMessage.toolCalls) {
      const args = JSON.parse(String(toolCall.function.arguments)) as { orderId: string };
      const result = getOrderStatus(args.orderId);

      messages.push({
        role: "tool",
        name: toolCall.function.name,
        toolCallId: toolCall.id,
        content: result,
      });
    }
  }

  const finalToolReply = await client.chat.complete({
    model,
    messages: messages as never,
    tools,
  });

  const toolAnswer = finalToolReply.choices?.[0]?.message?.content;

  // --- PART B: JSON MODE ---
  const jsonReply = await client.chat.complete({
    model,
    messages: [
      {
        role: "user",
        content:
          'Extract the order ID and city as JSON with keys "orderId" and "city". Text: Order ORD_101 is going to Lahore.',
      },
    ],
    responseFormat: { type: "json_object" },
  });

  const rawJsonText = String(jsonReply.choices?.[0]?.message?.content ?? "{}");
  const parsedJson = JSON.parse(rawJsonText) as { orderId: string; city: string };

  return {
    toolAnswer,
    parsedJson,
  };
}

Tips

  • Always mention JSON in your prompt: Even when responseFormat is set to json_object, clearly write the exact JSON key names in your prompt text.
  • Match the toolCallId: Always send back the exact toolCall.id when replying with role: "tool", otherwise Mistral will throw an error.
  • Check parsed data before using it: Always verify the fields after JSON.parse() so missing keys do not break your code.