Function Calling API

Enable Large Language Models to intelligently call your defined functions, implementing seamless integration with external systems

Advanced FeatureTool IntegrationAutomation

What is Function Calling?

Function Calling allows Large Language Models to understand user intent and intelligently select and call your predefined functions, converting natural language into structured function call parameters.

🎯

Intelligent Recognition

Automatically recognize when to call functions

🔧

Parameter Extraction

Extract function parameters from conversations

🔄

Result Integration

Integrate function results into the response

Workflow

  1. 1

    Define Functions

    Describe available functions and their parameters in API requests

  2. 2

    Model Judgment

    AI analyzes whether function calls are needed

  3. 3

    Return Call Information

    Return function name and parameters

  4. 4

    Execute Function

    Your code executes the actual function

  5. 5

    Return Results

    Send function results back to the model to generate final response

Complete Example

Step 1: Define Function Structure

Function Definition
const functions = [
  {
    "name": "get_weather",
    "description": "Get weather information for a specified city",
    "parameters": {
      "type": "object",
      "properties": {
        "location": {
          "type": "string",
          "description": "City name, e.g.: Beijing, Shanghai"
        },
        "unit": {
          "type": "string",
          "enum": ["celsius", "fahrenheit"],
          "description": "Temperature unit"
        }
      },
      "required": ["location"]
    }
  },
  {
    "name": "search_product",
    "description": "Search product information",
    "parameters": {
      "type": "object",
      "properties": {
        "query": {
          "type": "string",
          "description": "Search keywords"
        },
        "category": {
          "type": "string",
          "description": "Product category"
        },
        "max_price": {
          "type": "number",
          "description": "Maximum price"
        }
      },
      "required": ["query"]
    }
  }
];

Step 2: Send Request with Functions

const response = await fetch('https://api.n1n.ai/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  body: JSON.stringify({
    model: "gpt-3.5-turbo",
    messages: [
      {
        role: "user",
        content: "What's the weather like in Beijing today?"
      }
    ],
    functions: functions,
    function_call: "auto"  // auto | none | {"name": "function_name"}
  })
});

const data = await response.json();

Step 3: Handle Function Call Response

// APIResponse Example
{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": null,
      "function_call": {
        "name": "get_weather",
        "arguments": "{\"location\": \"Beijing\", \"unit\": \"celsius\"}"
      }
    }
  }]
}

// Parse and execute function
const functionCall = data.choices[0].message.function_call;
if (functionCall) {
  const functionName = functionCall.name;
  const functionArgs = JSON.parse(functionCall.arguments);
  
  // Execute actual function
  let functionResult;
  if (functionName === 'get_weather') {
    functionResult = await getWeather(functionArgs.location, functionArgs.unit);
  }
  
  console.log(`Calling function: ${functionName}`);
  console.log(`Parameters: `, functionArgs);
}

Step 4: Return Function Results to Model

// Function execution result
const functionResult = {
  temperature: 22,
  condition: "Sunny",
  humidity: 45,
  wind_speed: 10
};

// Send second request, including function results
const finalResponse = await fetch('https://api.n1n.ai/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  body: JSON.stringify({
    model: "gpt-3.5-turbo",
    messages: [
      { role: "user", content: "What's the weather like in Beijing today?" },
      { 
        role: "assistant",
        content: null,
        function_call: {
          name: "get_weather",
          arguments: "{\"location\": \"Beijing\", \"unit\": \"celsius\"}"
        }
      },
      {
        role: "function",
        name: "get_weather",
        content: JSON.stringify(functionResult)
      }
    ]
  })
});

// Final response: "The weather in Beijing today is sunny, temperature 22°C, humidity 45%, wind speed 10km/h, suitable for going out."

Practical Applications

📱 Intelligent Assistant

Available functions:

  • • send_email() - Send email
  • • schedule_meeting() - Schedule meeting
  • • set_reminder() - Set reminder
  • • search_files() - Search files

User: "Help me send an email to Zhang San to remind about tomorrow's meeting"

AI: Calls send_email() function ✓

🛍️ E-commerce Bot

Available functions:

  • • search_products() - Search products
  • • check_inventory() - Check inventory
  • • calculate_discount() - Calculate discount
  • • create_order() - Create order

User: "Do you have red sneakers?"

AI: Calls search_products() function ✓

Advanced Techniques

Parallel Function Calls

GPT-4 supports calling multiple functions in one response:

// User: "Check the weather in Beijing and Shanghai" // AI may return: { "function_calls": [ { "name": "get_weather", "arguments": "{\"location\": \"Beijing\"}" }, { "name": "get_weather", "arguments": "{\"location\": \"Shanghai\"}" } ] }

Conditional Function Calls

Use function_call parameter to control function call behavior:

// Force call specific function "function_call": {"name": "get_weather"} // Disable function calls "function_call": "none" // Auto determine (default) "function_call": "auto"

Error Handling

try { const args = JSON.parse(functionCall.arguments); const result = await executeFunction(functionCall.name, args); return result; } catch (error) { // Return error information to model return { error: true, message: `Function execution failed: ${error.message}` }; }

Best Practices

✅ Recommended Practices

  • Function descriptions should be clear and accurate
  • Parameter type definitions should be complete
  • Provide parameter examples and descriptions
  • Implement function result validation
  • Handle exceptions and edge cases

❌ Practices to Avoid

  • Unclear function names
  • Overly complex nested parameters
  • Ignoring parameter validation
  • Function execution takes too long
  • Inconsistent return formats

Important Reminders

  • • Function calls consume additional tokens
  • • Not all models support function calling (requires gpt-3.5-turbo-0613 or newer versions)
  • • You are responsible for function execution security
  • • Implement access control for function calls
  • • Function results have size limits (recommended not to exceed 1000 tokens)