Runoob Tutorial ArchiveEnglish

Function Calling

Function Calling

Function Calling is the core mechanism that enables LLMs to use external tools.

Function Calling allows the model to decide when to call a tool, which tool to call, and what parameters to pass.

Why is Function Calling needed?

Imagine an LLM is a smart but unarmed consultant. It knows a lot of knowledge, but cannot:

Function Calling gives LLMs hands, allowing them to break free from their own limitations and perform actual tasks.

How Function Calling works

The basic workflow of Function Calling is as follows:

runoob funcall runoob scaled

Core concepts

Instance illustration

Assume we have a weather query tool, when the user asks "What is the weather like in Beijing today?":

  1. LLM identifies the need to call the weather query tool
  2. Extract parameters from the question:city="Beijing",date="今天"
  3. Call the weather API to get data
  4. Consolidate the weather data into a friendly response and return it to the user

Write tool definitions and descriptions

To make the LLM use the tool correctly, you first need to clearly define the tool. A good tool definition should be like a clear instruction manual, letting the LLM understand:

Tool definition structure

A complete tool definition usually includes the following parts:

Instance

Example structure of a tool definition

weather_tool

=

{

   

"name"

:

"get_weather"

,

 

Tool name

   

"description"

:

"Get weather information for a specified city"

,

 

Tool description

   

"parameters"

:

{

 

Parameter definition

       

"type"

:

"object"

,

       

"properties"

:

{

           

"city"

:

{

               

"type"

:

"string"

,

               

"description"

:

"City name, such as 'Beijing' or 'Shanghai'"

           

}

,

           

"date"

:

{

               

"type"

:

"string"

,

               

"description"

:

"Date, format 'YYYY-MM-DD', or 'today', 'tomorrow'"

,

               

"enum"

:

[

"Today"

,

"Tomorrow"

,

"Day after tomorrow"

]

           

}

       

}

,

       

"required"

:

[

"city"

]

 

Required parameters

   

}

}

Write a high-quality tool description

1. The description must be clear and specific

2. Parameter descriptions must be detailed

Bad parameter description:



"city": {"type": "string"}

Good parameter description:

Original prompt (Chinese, left untranslated)

"city": {

    "type": "string",

    "description": "完整的城市名称,如'北京市'、'上海市'。不要使用简称或拼音。"

}

3. Use enums to restrict options

For a finite set of options, use an enum to help the LLM understand:

Original prompt (Chinese, left untranslated)



"unit": {

    "type": "string",

    "description": "温度单位",

    "enum": ["celsius", "fahrenheit"],

    "default": "celsius"

}

4. Provide example values

Provide examples in the description to help the LLM understand the format:

Original prompt (Chinese, left untranslated)



"date": {

    "type": "string",

    "description": "日期,格式应为'YYYY-MM-DD',例如'2024-06-15'"

}

Example of a utility tool definition

1. Calculator tool

Original prompt (Chinese, left untranslated)



calculator_tool = {

    "name": "calculate",

    "description": "执行数学计算,支持加减乘除、幂运算等基本运算",

    "parameters": {

        "type": "object",

        "properties": {

            "expression": {

                "type": "string",

                "description": "数学表达式,如'2 + 3 * 4'、'sqrt(16)'、'sin(30)'"

            }

        },

        "required": ["expression"]

    }

}

2. Search tool

Original prompt (Chinese, left untranslated)

search_tool = {

    "name": "search_web",

    "description": "在互联网上搜索最新信息",

    "parameters": {

        "type": "object",

        "properties": {

            "query": {

                "type": "string",

                "description": "搜索关键词,尽量具体明确"

            },

            "num_results": {

                "type": "integer",

                "description": "返回结果数量,默认为5",

                "default": 5,

                "minimum": 1,

                "maximum": 10

            }

        },

        "required": ["query"]

    }

}

3. File operation tool

Original prompt (Chinese, left untranslated)



file_tool = {

    "name": "read_file",

    "description": "读取指定文件的内容",

    "parameters": {

        "type": "object",

        "properties": {

            "file_path": {

                "type": "string",

                "description": "文件的完整路径,如'/home/user/document.txt'"

            },

            "encoding": {

                "type": "string",

                "description": "文件编码,默认为'utf-8'",

                "default": "utf-8"

            }

        },

        "required": ["file_path"]

    }

}

Best practices for tool definitions

Tool definition validation

After defining a tool, validation tests should be performed:

Original prompt (Chinese, left untranslated)



def validate_tool_definition(tool_def):

    """验证工具定义是否完整"""

    required_fields = ["name", "description", "parameters"]



    for field in required_fields:

        if field not in tool_def:

            return False, f"缺少必要字段: {field}"



    # Check parameter structure

    if "properties" not in tool_def["parameters"]:

        return False, "参数定义缺少properties字段"



    return True, "工具定义完整"



# Test verification

is_valid, message = validate_tool_definition(weather_tool)

print(f"验证结果: {is_valid}, 消息: {message}")


Parameter extraction and validation

After extracting parameters from the user's question, these parameters need to be validated and processed to ensure the tool can execute correctly.

Parameter Extraction Process

When the LLM decides to call a tool, it analyzes the user input and extracts the parameters required by the tool:

Original prompt (Chinese, left untranslated)



用户输入: "查询北京明天的天气温度"

工具: get_weather

提取参数: {"city": "北京", "date": "明天"}

Challenges in Parameter Extraction

Parameter extraction may encounter the following issues:

Parameter validation methods

1. Type validation

Ensure that the parameter type meets the requirements:

Original prompt (Chinese, left untranslated)



def validate_parameters(params, tool_def):

    """验证参数类型"""

    errors = []



    for param_name, param_def in tool_def["parameters"]["properties"].items():

        if param_name in params:

            param_value = params[param_name]

            expected_type = param_def.get("type")



            # Type checking

            if expected_type == "string" and not isinstance(param_value, str):

                errors.append(f"参数'{param_name}'应为字符串类型")

            elif expected_type == "integer" and not isinstance(param_value, int):

                errors.append(f"参数'{param_name}'应为整数类型")

            elif expected_type == "number" and not isinstance(param_value, (int, float)):

                errors.append(f"参数'{param_name}'应为数字类型")

            elif expected_type == "boolean" and not isinstance(param_value, bool):

                errors.append(f"参数'{param_name}'应为布尔类型")



    return errors

Original prompt (Chinese, left untranslated)



#### 2. Range Validation



Check if parameter values are within the allowed range:



def validate_range(params, tool_def): """Validate parameter range""" errors = []

Original prompt (Chinese, left untranslated)

for param_name, param_def in tool_def["parameters"]["properties"].items():

    if param_name in params:

        param_value = params[param_name]



        # Check minimum

        if "minimum" in param_def and param_value < param_def["minimum"]:

            errors.append(f"参数'{param_name}'不能小于{param_def['minimum']}")



        # Check maximum value

        if "maximum" in param_def and param_value > param_def["maximum"]:

            errors.append(f"参数'{param_name}'不能大于{param_def['maximum']}")



        # Check enum values

        if "enum" in param_def and param_value not in param_def["enum"]:

            errors.append(f"参数'{param_name}'必须是{param_def['enum']}中的一个")



return errors

Original prompt (Chinese, left untranslated)



#### 3. Required parameter validation



Ensure all required parameters are provided:



def validate_required(params, tool_def): """Validate required parameters""" errors = [] required_params = tool_def["parameters"].get("required", [])

Original prompt (Chinese, left untranslated)

for param_name in required_params:

    if param_name not in params:

        errors.append(f"缺少必填参数: {param_name}")



return errors

Original prompt (Chinese, left untranslated)



### 完整的参数验证系统



## 实例



class



ParameterValidator:



  

   



"""参数验证器"""



  

  

   



def



__init__



(



self



,



tool_def



)



:



  

       



self



.



tool_def



=



tool_def



  

  

   



def



validate



(



self



,



params



)



:



  

       



"""执行完整的参数验证"""



  

        all_errors



=



[



]



  

  

       



# Check required parameters



  

        required_errors



=



self



.



validate_required



(



params



)



  

        all_errors.



extend



(



required_errors



)



  

  

       



# Check parameter types



  

        type_errors



=



self



.



validate_type



(



params



)



  

        all_errors.



extend



(



type_errors



)



  

  

       



# Check parameter range



  

        range_errors



=



self



.



validate_range



(



params



)



  

        all_errors.



extend



(



range_errors



)



  

  

       



# Check for extra arguments (undefined parameters)



  

        extra_errors



=



self



.



validate_extra



(



params



)



  

        all_errors.



extend



(



extra_errors



)



  

  

       



return



len



(



all_errors



)



==



0



,



all_errors



  

  

   



def



validate_required



(



self



,



params



)



:



  

       



"""验证必填参数"""



  

        errors



=



[



]



  

        required_params



=



self



.



tool_def



[



"parameters"



]



.



get



(



"required"



,



[



]



)



  

  

       



for



param_name



in



required_params:



  

           



if



param_name



not



in



params



or



params



[



param_name



]



is



None



:



  

                errors.



append



(



f



"缺少必填参数: {param_name}"



)



  

  

       



return



errors



  

  

   



def



validate_type



(



self



,



params



)



:



  

       



"""验证参数类型"""



  

        errors



=



[



]



  

  

       



for



param_name



,



param_value



in



params.



items



(



)



:



  

           



if



param_name



in



self



.



tool_def



[



"parameters"



]



[



"properties"



]



:



  

                param_def



=



self



.



tool_def



[



"parameters"



]



[



"properties"



]



[



param_name



]



  

                expected_type



=



param_def.



get



(



"type"



)



  

  

               



if



expected_type



==



"string"



and



not



isinstance



(



param_value



,



str



)



:



  

                    errors.



append



(



f



"参数'{param_name}'应为字符串类型,实际为{type(param_value).__name__}"



)



  

               



elif



expected_type



==



"integer"



and



not



isinstance



(



param_value



,



int



)



:



  

                    errors.



append



(



f



"参数'{param_name}'应为整数类型,实际为{type(param_value).__name__}"



)



  

               



elif



expected_type



==



"number"



and



not



isinstance



(



param_value



,



(



int



,



float



)



)



:



  

                    errors.



append



(



f



"参数'{param_name}'应为数字类型,实际为{type(param_value).__name__}"



)



  

               



elif



expected_type



==



"boolean"



and



not



isinstance



(



param_value



,



bool



)



:



  

                    errors.



append



(



f



"参数'{param_name}'应为布尔类型,实际为{type(param_value).__name__}"



)



  

  

       



return



errors



  

  

   



def



validate_range



(



self



,



params



)



:



  

       



"""验证参数范围"""



  

        errors



=



[



]



  

  

       



for



param_name



,



param_value



in



params.



items



(



)



:



  

           



if



param_name



in



self



.



tool_def



[



"parameters"



]



[



"properties"



]



:



  

                param_def



=



self



.



tool_def



[



"parameters"



]



[



"properties"



]



[



param_name



]



  

  

               



# Check minimum



  

               



if



"minimum"



in



param_def



and



param_value



<



param_def



[



"minimum"



]



:



  

                    errors.



append



(



f



"参数'{param_name}'不能小于{param_def['minimum']}"



)



  

  

               



# Check maximum value



  

               



if



"maximum"



in



param_def



and



param_value



>



param_def



[



"maximum"



]



:



  

                    errors.



append



(



f



"参数'{param_name}'不能大于{param_def['maximum']}"



)



  

  

               



# Check enum values



  

               



if



"enum"



in



param_def



and



param_value



not



in



param_def



[



"enum"



]



:



  

                    errors.



append



(



f



"参数'{param_name}'必须是{param_def['enum']}中的一个"



)



  

  

       



return



errors



  

  

   



def



validate_extra



(



self



,



params



)



:



  

       



"""检查未定义的额外参数"""



  

        errors



=



[



]



  

        defined_params



=



set



(



self



.



tool_def



[



"parameters"



]



[



"properties"



]



.



keys



(



)



)



  

        provided_params



=



set



(



params.



keys



(



)



)



  

  

        extra_params



=



provided_params - defined_params



  

       



if



extra_params:



  

            errors.



append



(



f



"提供了未定义的参数: {', '.join(extra_params)}"



)



  

  

       



return



errors



  

  

# Usage example



  

validator



=



ParameterValidator



(



weather_tool



)



  

params



=



{



"city"



:



"北京"



,



"date"



:



"明天"



,



"extra"



:



"不应该有的参数"



}



  

is_valid



,



errors



=



validator.



validate



(



params



)



  

  

if



is_valid:



  

   



print



(



"参数验证通过"



)



  

else



:



  

   



print



(



"参数验证失败:"



)



  

   



for



error



in



errors:



  

       



print



(



f



"  - {error}"



)



  

### Complete process of parameter extraction and validation



![](https://www.runoob.com/wp-content/uploads/2026/02/runoob-funcall-runoob-2-scaled.png)



### 参数修正策略



When parameter validation fails, the following strategies can be adopted:



- **询问用户**:直接向用户询问缺失或错误的参数

- **使用默认值**:对于可选参数,使用预定义的默认值

- **智能推断**:根据上下文推断合理的参数值

- **格式转换**:将用户提供的格式转换为工具要求的格式



def fix_parameters(params, errors, tool_def): """Attempt to fix parameter errors""" fixed_params = params.copy()

Original prompt (Chinese, left untranslated)

for error in errors:

    if "缺少必填参数" in error:

        param_name = error.split(": ")[1]

        # Try to infer from context or use default value

        if param_name == "date":

            fixed_params[param_name] = "今天"  # 使用当天作为默认值



    elif "应为字符串类型" in error:

        param_name = error.split("'")[1]

        # Try to convert to string

        fixed_params[param_name] = str(params[param_name])



return fixed_params

Original prompt (Chinese, left untranslated)



---



## Error Handling and Retry Mechanism



在实际应用中,工具调用可能会失败。健全的错误处理和重试机制是构建可靠 AI Agent 的关键。



### 

class ErrorHandler: """Error handler"""

Original prompt (Chinese, left untranslated)

def handle(self, error, context):

    """处理错误"""

    error_type = self.classify_error(error)



    if error_type == "network":

        return self.handle_network_error(error, context)

    elif error_type == "parameter":

        return self.handle_parameter_error(error, context)

    elif error_type == "authentication":

        return self.handle_auth_error(error, context)

    elif error_type == "resource":

        return self.handle_resource_error(error, context)

    else:

        return self.handle_unknown_error(error, context)



def classify_error(self, error):

    """分类错误类型"""

    error_str = str(error).lower()



    if any(word in error_str for word in ["timeout", "connection", "network"]):

        return "network"

    elif any(word in error_str for word in ["parameter", "invalid", "missing"]):

        return "parameter"

    elif any(word in error_str for word in ["auth", "key", "permission"]):

        return "authentication"

    elif any(word in error_str for word in ["limit", "quota", "unavailable"]):

        return "resource"

    else:

        return "unknown"



def handle_network_error(self, error, context):

    """处理网络错误"""

    return {

        "success": False,

        "error": "网络连接失败,请检查网络后重试",

        "retryable": True,

        "retry_after": 5  # 5秒后重试

    }



def handle_parameter_error(self, error, context):

    """处理参数错误"""

    return {

        "success": False,

        "error": f"参数错误: {str(error)}",

        "retryable": False,

        "suggestion": "请检查输入参数是否正确"

    }



# Other error handling methods are similar...

Original prompt (Chinese, left untranslated)



#### 2. 用户友好的错误消息



Convert technical errors into user-friendly messages:



def user_friendly_error(error): """Generate user-friendly error message""" error_map = { "timeout": "Request timed out, please try again later", "connection_error": "Network connection failed, please check your network", "invalid_api_key": "API key is invalid, please check the configuration", "rate_limit_exceeded": "Too many calls, please try again later", "invalid_parameters": "Input parameters are incorrect, please check and try again" }

Original prompt (Chinese, left untranslated)

error_str = str(error).lower()

for key, message in error_map.items():

    if key in error_str:

        return message



return "系统繁忙,请稍后重试"

Original prompt (Chinese, left untranslated)



### Retry Mechanism



For retryable errors, an intelligent retry strategy should be implemented:



#### 1. Exponential Backoff Retry



import time import random

class ExponentialBackoffRetry: """Exponential backoff retry"""

Original prompt (Chinese, left untranslated)

def __init__(self, max_retries=3, base_delay=1, max_delay=30):

    self.max_retries = max_retries

    self.base_delay = base_delay

    self.max_delay = max_delay



def retry(self, func, *args, **kwargs):

    """执行带重试的函数调用"""

    last_error = None



    for attempt in range(self.max_retries):

        try:

            return func(*args, **kwargs)



        except Exception as e:

            last_error = e



            # Check if retryable

            if not self.is_retryable(e):

                raise



            # Last attempt, no more retries

            if attempt == self.max_retries - 1:

                break



            # Calculate wait time (exponential backoff + random jitter)

            delay = min(

                self.base_delay * (2 ** attempt) + random.uniform(0, 1),

                self.max_delay

            )



            print(f"第{attempt + 1}次尝试失败,{delay:.1f}秒后重试...")

            time.sleep(delay)



    # All retries failed

    raise last_error



def is_retryable(self, error):

    """判断错误是否可重试"""

    error_str = str(error).lower()

    retryable_errors = ["timeout", "connection", "busy", "temporarily"]



    for retryable_error in retryable_errors:

        if retryable_error in error_str:

            return True



    return False

Usage example

retry = ExponentialBackoffRetry(max_retries=3)

def call_weather_api(city, date): """Calls the weather API (simulating potential failure)""" # Simulating API call if random.random() < 0.3: # 30% chance of failure raise ConnectionError("API connection timeout") return {"temperature": 25, "condition": "Sunny"}

try: result = retry.retry(call_weather_api, "Beijing", "today") print(f"Successfully retrieved weather: {result}") except Exception as e: print(f"Failed to retrieve weather: {e}")



2. Circuit Breaker Pattern

Prevents system collapse due to continuous failures:

Original prompt (Chinese, left untranslated)



class CircuitBreaker:

    """熔断器"""



    def __init__(self, failure_threshold=5, reset_timeout=60):

        self.failure_threshold = failure_threshold

        self.reset_timeout = reset_timeout

        self.failure_count = 0

        self.last_failure_time = None

        self.state = "closed"  # closed, open, half-open



    def execute(self, func, *args, **kwargs):

        """通过熔断器执行函数"""

        if self.state == "open":

            # Check if recovery should be attempted

            if self.should_try_reset():

                self.state = "half-open"

            else:

                raise Exception("熔断器开启,服务暂时不可用")



        try:

            result = func(*args, **kwargs)



            # Success call, reset state

            if self.state == "half-open":

                self.state = "closed"

                self.failure_count = 0



            return result



        except Exception as e:

            self.record_failure()

            raise e



    def record_failure(self):

        """记录失败"""

        self.failure_count += 1

        self.last_failure_time = time.time()



        if self.failure_count >= self.failure_threshold:

            self.state = "open"



    def should_try_reset(self):

        """检查是否应该尝试重置"""

        if self.last_failure_time is None:

            return True



        elapsed = time.time() - self.last_failure_time

        return elapsed > self.reset_timeout



# Usage example

breaker = CircuitBreaker(failure_threshold=3, reset_timeout=30)



def unreliable_service():

    """模拟不可靠的服务"""

    if random.random() < 0.5:

        raise Exception("服务异常")

    return "服务正常"



for i in range(10):

    try:

        result = breaker.execute(unreliable_service)

        print(f"调用{i+1}: {result}")

    except Exception as e:

        print(f"调用{i+1}: {e}")

        time.sleep(1)

Complete tool calling framework

By combining all the above components, we can build a complete tool calling framework:

Instance

class

ToolExecutor:

   

"""Tool executor"""

   

def

init

(

self

)

:

       

self

.

tools

=

{

}

 

Registered tools

       

self

.

validator

=

ParameterValidator

       

self

.

error_handler

=

ErrorHandler

(

)

       

self

.

retry

=

ExponentialBackoffRetry

(

)

       

self

.

breaker

=

CircuitBreaker

(

)

   

def

register_tool

(

self

,

name

,

tool_def

,

func

)

:

       

"""Registration Tool"""

       

self

.

tools

[

name

]

=

{

           

"definition"

: tool_def

,

           

"function"

: func

       

}

   

def

execute_tool

(

self

,

tool_name

,

params

)

:

       

"""Execute tool"""

       

if

tool_name

not

in

self

.

tools

:

           

return

{

               

"success"

:

False

,

               

"error"

: f

"Tool '{tool_name}' is not registered"

           

}

tool_info

=

self

.

tools

[

tool_name

]

        tool_def

=

tool_info

[

"definition"

]

tool_func

=

tool_info

[

"function"

]

       

Validate parameters

validator

=

self

.

validator

(

tool_def

)

is_valid

,

errors

=

validator.

validate

(

params

)

       

if

not

is_valid:

           

return

{

               

"success"

:

False

,

               

"error"

:

"Parameter validation failed"

,

               

"details"

: errors

           

}

       

Execute through the circuit breaker (with retry)

       

try

:

           

def

execute_with_retry

(

)

:

               

return

self

.

breaker

.

execute

(

                   

lambda

:

self

.

retry

.

retry

(

tool_func

,

**params

)

               

)

result

=

execute_with_retry

(

)

           

return

{

               

"success"

:

True

,

               

"result"

: result

,

               

"tool"

: tool_name

           

}

       

except

Exception

as

e:

           

Error Handling

error_response

=

self

.

error_handler

.

handle

(

e

,

{

               

"tool"

: tool_name

,

               

"params"

: params

           

}

)

           

return

{

               

"success"

:

False

,

               

"error"

: error_response

[

"error"

]

,

               

"retryable"

: error_response.

get

(

"retryable"

,

False

)

,

               

"suggestion"

: error_response.

get

(

"suggestion"

,

""

)

           

}

   

def

handle_user_request

(

self

,

user_input

)

:

       

"""Process user request (simplified version)"""

       

1. Let the LLM select tools and extract parameters (simplified here)

       

In practical applications, this will call the LLM for tool selection and parameter extraction

       

Simulate LLM output

       

if

"Weather"

in

user_input:

            tool_name

=

"get_weather"

           

Simple extraction of the city (LLM will do better in actual applications)

           

if

"Beijing"

in

user_input:

                params

=

{

"city"

:

"Beijing"

,

"date"

:

"today"

}

           

elif

"Shanghai"

in

user_input:

                params

=

{

"city"

:

"Shanghai"

,

"date"

:

"today"

}

           

else

:

params

=

{

"city"

:

"Beijing"

,

"date"

:

"today"

}

 

Default value

       

else

:

           

return

"Sorry, I cannot process this request"

       

2. Execute tool

result

=

self

.

execute_tool

(

tool_name

,

params

)

       

3. Generate final answer

       

if

result

[

"success"

]

:

weather

=

result

[

"result"

]

           

return

f

"{params['city']} today's weather: {weather['condition']}, temperature {weather['temperature']}°C"

       

else

:

           

return

f

"Failed to get weather information: {result['error']}"

Usage example

executor

=

ToolExecutor

(

)

Register weather tool

def

mock_weather_api

(

city

,

date

)

:

   

"""Simulate weather API"""

   

Simulate API call delay

   

time

.

sleep

(

0.1

)

   

return

{

"temperature"

:

22

,

"condition"

:

"Cloudy"

}

executor.

register_tool

(

"get_weather"

,

weather_tool

,

mock_weather_api

)

Process user request

response

=

executor.

handle_user_request

(

"What is the weather like in Beijing today?"

)

print

(

response

)