Usamos cookies para mejorar tu experiencia en el sitio
CodeWorlds

Function Calling - AI z narzędziami

Function Calling pozwala AI wywoływać funkcje i narzędzia! 🔧

Podstawy Function Calling

1from openai import OpenAI
2import json
3
4client = OpenAI()
5
6# Definiuj narzędzia (tools)
7tools = [
8    {
9        "type": "function",
10        "function": {
11            "name": "get_animal_info",
12            "description": "Pobiera informacje o zwierzęciu Safari",
13            "parameters": {
14                "type": "object",
15                "properties": {
16                    "animal_name": {
17                        "type": "string",
18                        "description": "Nazwa zwierzęcia, np. 'lew', 'słoń'"
19                    }
20                },
21                "required": ["animal_name"]
22            }
23        }
24    },
25    {
26        "type": "function",
27        "function": {
28            "name": "get_weather",
29            "description": "Pobiera pogodę dla lokalizacji Safari",
30            "parameters": {
31                "type": "object",
32                "properties": {
33                    "location": {
34                        "type": "string",
35                        "description": "Nazwa lokalizacji, np. 'Serengeti'"
36                    }
37                },
38                "required": ["location"]
39            }
40        }
41    }
42]
43
44# Wywołanie z narzędziami
45response = client.chat.completions.create(
46    model="gpt-5",
47    messages=[{"role": "user", "content": "Opowiedz mi o lwach i pogodzie w Serengeti"}],
48    tools=tools,
49    tool_choice="auto"
50)
51
52# Sprawdź czy model chce wywołać funkcję
53message = response.choices[0].message
54if message.tool_calls:
55    for tool_call in message.tool_calls:
56        function_name = tool_call.function.name
57        arguments = json.loads(tool_call.function.arguments)
58        print(f"Model chce wywołać: {function_name}({arguments})")

Implementacja funkcji

1# Implementacje naszych funkcji
2def get_animal_info(animal_name: str) -> dict:
3    animals_db = {
4        "lew": {
5            "name": "Lew afrykański",
6            "population": 20000,
7            "habitat": "Sawanna",
8            "diet": "Mięsożerca"
9        },
10        "słoń": {
11            "name": "Słoń afrykański",
12            "population": 415000,
13            "habitat": "Sawanna i lasy",
14            "diet": "Roślinożerca"
15        }
16    }
17    return animals_db.get(animal_name.lower(), {"error": "Nieznane zwierzę"})
18
19def get_weather(location: str) -> dict:
20    # W prawdziwej aplikacji - wywołanie API pogodowego
21    return {
22        "location": location,
23        "temperature": 28,
24        "conditions": "Słonecznie",
25        "humidity": 45
26    }
27
28# Mapowanie nazw funkcji
29available_functions = {
30    "get_animal_info": get_animal_info,
31    "get_weather": get_weather
32}

Pełny flow z function calling

1def chat_with_tools(user_message: str):
2    messages = [{"role": "user", "content": user_message}]
3
4    # Pierwsze wywołanie
5    response = client.chat.completions.create(
6        model="gpt-5",
7        messages=messages,
8        tools=tools
9    )
10
11    message = response.choices[0].message
12
13    # Jeśli model chce wywołać funkcje
14    if message.tool_calls:
15        messages.append(message)  # Dodaj odpowiedź asystenta
16
17        # Wykonaj wszystkie wywołania funkcji
18        for tool_call in message.tool_calls:
19            function_name = tool_call.function.name
20            arguments = json.loads(tool_call.function.arguments)
21
22            # Wywołaj funkcję
23            function_response = available_functions[function_name](**arguments)
24
25            # Dodaj wynik do messages
26            messages.append({
27                "role": "tool",
28                "tool_call_id": tool_call.id,
29                "content": json.dumps(function_response)
30            })
31
32        # Drugie wywołanie - model przetwarza wyniki
33        final_response = client.chat.completions.create(
34            model="gpt-5",
35            messages=messages
36        )
37
38        return final_response.choices[0].message.content
39
40    return message.content
41
42# Test
43result = chat_with_tools("Jakie zwierzę jest największe i jaka jest pogoda w Serengeti?")
44print(result)

LangChain Tools

1from langchain.tools import tool
2from langchain.agents import create_tool_calling_agent, AgentExecutor
3from langchain_openai import ChatOpenAI
4from langchain_core.prompts import ChatPromptTemplate
5
6@tool
7def search_safari_animals(query: str) -> str:
8    """Wyszukuje informacje o zwierzętach Safari."""
9    # Implementacja
10    return f"Informacje o: {query}"
11
12@tool
13def calculate_distance(from_loc: str, to_loc: str) -> str:
14    """Oblicza odległość między lokalizacjami Safari."""
15    return f"Odległość z {from_loc} do {to_loc}: 150 km"
16
17# Agent z narzędziami
18tools = [search_safari_animals, calculate_distance]
19llm = ChatOpenAI(model="gpt-5")
20
21prompt = ChatPromptTemplate.from_messages([
22    ("system", "Jesteś pomocnym asystentem Safari."),
23    ("human", "{input}"),
24    ("placeholder", "{agent_scratchpad}")
25])
26
27agent = create_tool_calling_agent(llm, tools, prompt)
28agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
29
30result = agent_executor.invoke({
31    "input": "Jak daleko jest z Nairobi do Serengeti?"
32})
Ir a CodeWorlds