Publicado

Function calling y uso de herramientas: conectar los LLM con sus sistemas empresariales

Permita que los LLM consulten un ERP, creen tickets o actualicen el CRM con herramientas tipadas: esquemas, bucle, salida estructurada y validación.

Escrito por
Ali ÖzdurmuşFundador, Veni AI
Actualizado
Tiempo de lectura
6 min de lectura

El function calling (también llamado tool use) permite que un modelo de lenguaje pida a su código que ejecute una función concreta con unos argumentos concretos. Es el puente entre un modelo y sus sistemas empresariales: el modelo decide que necesita el nivel de stock del artículo 4471, su código llama al ERP y el modelo redacta la respuesta a partir de datos reales. El modelo nunca toca el sistema directamente; el control sigue en manos de su código.

Los ejemplos de código son Python ilustrativo. client es un cliente de SDK ya inicializado y MODEL es un marcador de posición para el ID de modelo que elija.

¿Qué es el function calling?

Tradicional:
Usuario: "¿Qué tiempo hace en Estambul?"
LLM: "No sé qué tiempo hace" (riesgo de alucinación)

Function calling:
Usuario: "¿Qué tiempo hace en Estambul?"
LLM: {"function": "get_weather", "args": {"city": "Istanbul"}}
Sistema: get_weather("Istanbul") → 15°C
LLM: "En Estambul hace 15°C"

Function calling al estilo OpenAI

Uso básico

python
from openai import OpenAI

client = OpenAI()
MODEL = "your-model-id"

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the weather for a specific city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City name, e.g. Istanbul"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["city"]
            }
        }
    }
]

response = client.chat.completions.create(
    model=MODEL,
    messages=[{"role": "user", "content": "How is the weather in Istanbul?"}],
    tools=tools,
    tool_choice="auto"
)

Function calling en paralelo

Varias funciones a la vez:

python
tools = [
    {"type": "function", "function": weather_function},
    {"type": "function", "function": stock_function},
    {"type": "function", "function": news_function}
]

response = client.chat.completions.create(
    model=MODEL,
    messages=[{
        "role": "user", 
        "content": "Istanbul weather, TSLA stock and current news?"
    }],
    tools=tools,
    tool_choice="auto"
)

# Response can contain multiple tool calls
for tool_call in response.choices[0].message.tool_calls:
    print(f"Function: {tool_call.function.name}")
    print(f"Args: {tool_call.function.arguments}")

Bucle de ejecución de funciones

python
def execute_function_call(tool_call):
    name = tool_call.function.name
    args = json.loads(tool_call.function.arguments)
    
    if name == "get_weather":
        return get_weather(**args)
    elif name == "get_stock_price":
        return get_stock_price(**args)
    else:
        return f"Unknown function: {name}"

def chat_with_functions(user_message, tools):
    messages = [{"role": "user", "content": user_message}]
    
    while True:
        response = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=tools
        )
        
        assistant_message = response.choices[0].message
        messages.append(assistant_message)
        
        if not assistant_message.tool_calls:
            # No tool call, exit loop
            return assistant_message.content
        
        # Execute functions
        for tool_call in assistant_message.tool_calls:
            result = execute_function_call(tool_call)
            messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": str(result)
            })

Tool use en Claude

Tool use con la API de Anthropic

python
from anthropic import Anthropic

client = Anthropic()
MODEL = "your-model-id"

tools = [
    {
        "name": "get_weather",
        "description": "Get weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name"
                }
            },
            "required": ["city"]
        }
    }
]

response = client.messages.create(
    model=MODEL,
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "How is the weather in Ankara?"}]
)

# Tool use response handling
if response.stop_reason == "tool_use":
    tool_use = next(
        block for block in response.content 
        if block.type == "tool_use"
    )
    
    # Execute tool
    result = execute_tool(tool_use.name, tool_use.input)
    
    # Continue conversation
    response = client.messages.create(
        model=MODEL,
        max_tokens=1024,
        messages=[
            {"role": "user", "content": "How is the weather in Ankara?"},
            {"role": "assistant", "content": response.content},
            {
                "role": "user",
                "content": [
                    {
                        "type": "tool_result",
                        "tool_use_id": tool_use.id,
                        "content": result
                    }
                ]
            }
        ]
    )

Salida estructurada (modo JSON)

Modo JSON

Muchos proveedores ofrecen ahora también salidas estructuradas con esquema obligatorio, en las que se garantiza que la respuesta se ajusta a un esquema JSON que usted proporciona. Prefiéralas cuando estén disponibles; el modo JSON simple solo garantiza un JSON válido, no su estructura.

python
response = client.chat.completions.create(
    model=MODEL,
    response_format={"type": "json_object"},
    messages=[
        {
            "role": "system",
            "content": "Respond in JSON format."
        },
        {
            "role": "user",
            "content": "Suggest me 3 programming languages."
        }
    ]
)

data = json.loads(response.choices[0].message.content)
# {"languages": ["Python", "JavaScript", "Go"]}

Validación con Pydantic

python
from pydantic import BaseModel
from typing import List

class ProgrammingLanguage(BaseModel):
    name: str
    use_case: str
    difficulty: str

class LanguageRecommendation(BaseModel):
    languages: List[ProgrammingLanguage]
    reasoning: str

def get_structured_response(prompt: str, model: BaseModel):
    schema = model.model_json_schema()
    
    response = client.chat.completions.create(
        model=MODEL,
        response_format={"type": "json_object"},
        messages=[
            {
                "role": "system",
                "content": f"JSON schema: {json.dumps(schema)}"
            },
            {"role": "user", "content": prompt}
        ]
    )
    
    return model.model_validate_json(
        response.choices[0].message.content
    )

La biblioteca Instructor

Integración sencilla con Pydantic + OpenAI:

python
import instructor
from pydantic import BaseModel
from openai import OpenAI

client = instructor.from_openai(OpenAI())

class UserInfo(BaseModel):
    name: str
    age: int
    email: str

user = client.chat.completions.create(
    model=MODEL,
    response_model=UserInfo,
    messages=[
        {"role": "user", "content": "John Doe, 25 years old, john@email.com"}
    ]
)

print(user.name)  # John Doe
print(user.age)   # 25

Definiciones de herramientas complejas

Parámetros anidados

python
{
    "name": "create_calendar_event",
    "description": "Create a calendar event",
    "parameters": {
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "datetime": {
                "type": "object",
                "properties": {
                    "date": {"type": "string", "format": "date"},
                    "time": {"type": "string", "format": "time"},
                    "timezone": {"type": "string"}
                },
                "required": ["date", "time"]
            },
            "attendees": {
                "type": "array",
                "items": {
                    "type": "object",
                    "properties": {
                        "email": {"type": "string"},
                        "role": {"type": "string", "enum": ["required", "optional"]}
                    }
                }
            },
            "reminder": {
                "type": "object",
                "properties": {
                    "minutes_before": {"type": "integer"},
                    "method": {"type": "string", "enum": ["email", "popup"]}
                }
            }
        },
        "required": ["title", "datetime"]
    }
}

Gestión de errores

python
class FunctionCallError(Exception):
    pass

def safe_execute_function(tool_call, available_functions):
    try:
        name = tool_call.function.name
        args = json.loads(tool_call.function.arguments)
        
        if name not in available_functions:
            raise FunctionCallError(f"Unknown function: {name}")
        
        # Parameter validation
        func = available_functions[name]
        sig = inspect.signature(func)
        
        for param in sig.parameters.values():
            if param.default is inspect.Parameter.empty:
                if param.name not in args:
                    raise FunctionCallError(
                        f"Missing required parameter: {param.name}"
                    )
        
        # Execute with timeout
        with timeout(30):
            result = func(**args)
        
        return {"success": True, "result": result}
        
    except json.JSONDecodeError as e:
        return {"success": False, "error": f"Invalid JSON: {e}"}
    except FunctionCallError as e:
        return {"success": False, "error": str(e)}
    except TimeoutError:
        return {"success": False, "error": "Function timeout"}
    except Exception as e:
        return {"success": False, "error": f"Execution error: {e}"}

Buenas prácticas

1. Descripciones claras

python
# Bad
{"name": "search", "description": "Searches"}

# Good
{
    "name": "search_products",
    "description": "Searches in e-commerce product database. "
                   "Can search by product name, category or brand. "
                   "Returns maximum 20 results."
}

2. Uso de enums

python
"payment_method": {
    "type": "string",
    "enum": ["credit_card", "bank_transfer", "crypto"],
    "description": "Payment method"
}

3. Valores por defecto

python
"limit": {
    "type": "integer",
    "default": 10,
    "description": "Result limit (default: 10)"
}

Conclusión

El function calling convierte un modelo de lenguaje en un componente capaz de trabajar con sus sistemas reales. Unas descripciones de herramientas precisas, esquemas estrictos, validación y timeouts lo hacen fiable. Por seguridad, empiece con herramientas de solo lectura, exija aprobación para todo lo que escriba o envíe y registre cada llamada.

Veni AI conecta las aplicaciones de IA con sistemas ERP, CRM, de correo y de documentos mediante herramientas bien definidas, con control de acceso y registros de auditoría. Conozca nuestros servicios o hable con nosotros sobre sus sistemas.

Siga leyendo

¿Tiene un proceso que debería funcionar con IA?

Describa un proceso tal como funciona hoy y le mostraremos qué pasos repetitivos podría asumir una aplicación o un agente de IA.