/** * ============================================================================= * FUNCTION CALLING EXAMPLE - Tool Use with Mistral * ============================================================================= * * Demonstrates function calling (tool use) capabilities. * * INTERVIEW NOTES: * - Function calling lets the model invoke external functions * - Model decides when to call based on user input * - You execute the function and return results * - Useful for: APIs, databases, calculations, actions * - Requires mistral-large for best results */ import { useState } from 'react'; import { useMistralTools, type ToolDefinition } from '@/hooks'; // Define available tools/functions const TOOLS: ToolDefinition[] = [ { type: 'function', function: { name: 'get_weather', description: 'Get the current weather for a location', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city name, e.g., "Paris" or "New York"', }, unit: { type: 'string', description: 'Temperature unit', enum: ['celsius', 'fahrenheit'], }, }, required: ['location'], }, }, }, { type: 'function', function: { name: 'search_products', description: 'Search for products in the catalog', parameters: { type: 'object', properties: { query: { type: 'string', description: 'Search query', }, category: { type: 'string', description: 'Product category', enum: ['electronics', 'clothing', 'books', 'home'], }, max_price: { type: 'number', description: 'Maximum price filter', }, }, required: ['query'], }, }, }, { type: 'function', function: { name: 'calculate', description: 'Perform a mathematical calculation', parameters: { type: 'object', properties: { expression: { type: 'string', description: 'Math expression to evaluate, e.g., "2 + 2 * 3"', }, }, required: ['expression'], }, }, }, ]; // Mock function implementations function executeFunction(name: string, args: Record): string { switch (name) { case 'get_weather': { const temps: Record = { paris: 18, london: 14, 'new york': 22, tokyo: 25, }; const location = (args.location as string).toLowerCase(); const temp = temps[location] || Math.floor(Math.random() * 20) + 10; const unit = args.unit === 'fahrenheit' ? 'F' : 'C'; const displayTemp = unit === 'F' ? Math.round(temp * 9/5 + 32) : temp; return JSON.stringify({ location: args.location, temperature: displayTemp, unit, condition: 'Partly cloudy', humidity: '65%', }); } case 'search_products': { return JSON.stringify({ query: args.query, results: [ { name: `${args.query} Pro`, price: 99.99, rating: 4.5 }, { name: `${args.query} Basic`, price: 49.99, rating: 4.2 }, { name: `${args.query} Premium`, price: 149.99, rating: 4.8 }, ], }); } case 'calculate': { try { // Safe eval for simple math (in production, use a proper parser) const expr = (args.expression as string).replace(/[^0-9+\-*/().]/g, ''); const result = Function(`"use strict"; return (${expr})`)(); return JSON.stringify({ expression: args.expression, result }); } catch { return JSON.stringify({ error: 'Invalid expression' }); } } default: return JSON.stringify({ error: 'Unknown function' }); } } export default function FunctionCallingExample() { const [input, setInput] = useState('What is the weather in Paris?'); const { content, toolCalls, loading, error, call, reset } = useMistralTools(TOOLS); const [executionResults, setExecutionResults] = useState([]); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!input.trim()) return; setExecutionResults([]); await call([{ role: 'user', content: input }], { model: 'mistral-large-latest', // Best for function calling }); }; // Execute tool calls when they arrive const handleExecuteTools = () => { if (!toolCalls) return; const results = toolCalls.map((tc) => { const args = JSON.parse(tc.function.arguments); const result = executeFunction(tc.function.name, args); return `${tc.function.name}(${JSON.stringify(args)}): ${result}`; }); setExecutionResults(results); }; const exampleQueries = [ 'What is the weather in Paris?', 'Search for laptops under $500', 'Calculate 15% tip on $85.50', 'What is 24 * 7 + 168?', ]; return (

Function Calling (Tool Use)

The model can decide when to call external functions based on user input.

{/* Available tools */}

Available tools:

{TOOLS.map((tool) => ( {tool.function.name} ))}
{/* Example queries */}

Try:

{exampleQueries.map((query) => ( ))}
setInput(e.target.value)} placeholder="Ask something that might need a tool..." className="input" disabled={loading} />
{error && (
{error}
)} {/* Tool calls */} {toolCalls && toolCalls.length > 0 && (

Tool Calls Requested:

{toolCalls.map((tc, index) => (

{tc.function.name}

                  {JSON.stringify(JSON.parse(tc.function.arguments), null, 2)}
                
))}
{executionResults.length === 0 && ( )}
)} {/* Execution results */} {executionResults.length > 0 && (

Execution Results:

{executionResults.map((result, index) => (
                {result}
              
))}
)} {/* Direct response (if no tool call) */} {content && !toolCalls && (

Response:

{content}

)} {/* Code example */}
View code
{`const tools: ToolDefinition[] = [{
  type: 'function',
  function: {
    name: 'get_weather',
    description: 'Get weather for a location',
    parameters: {
      type: 'object',
      properties: {
        location: { type: 'string', description: 'City name' }
      },
      required: ['location']
    }
  }
}];

const { toolCalls, content, call } = useMistralTools(tools);

await call([{ role: 'user', content: 'Weather in Paris?' }]);

if (toolCalls) {
  // Model wants to call a function
  const result = executeFunction(toolCalls[0].function.name, args);
  // Send result back to continue conversation
}`}
        
); }