Премини към основното съдържание
Български— Изберете език
Меню

Пълен агент за времето

Урок 12 от 14 Обновен 29 юли 2026 г. Програмист
На тази страница
  1. Изграждане на пълен агент за времето от нулата
  2. Архитектура на агента
  3. Имплементация на функциите
  4. Основен цикъл на агента
  5. Тестване на агента
  6. Възможни подобрения
  7. Ключови изводи

Изграждане на пълен агент за времето от нулата

В този урок ще обедините всичко научено дотук, за да изградите пълен агент за времето. Този агент илюстрира пълния цикъл на извикване на функции: дефиниране на инструменти, обработка на многократни размени (multi-turn), управление на грешки и генериране на отговори на естествен език.

Архитектура на агента

Агентът за времето разполага с три инструмента:

  1. get_weather — получава текущото време за даден град
  2. get_forecast — получава прогнози за няколко дни
  3. get_alerts — проверява активни предупреждения за времето
import json
from openai import OpenAI

client = OpenAI(
    api_key="your-xai-key",
    base_url="https://api.x.ai/v1"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a city. "
                          "Returns temperature, humidity, wind, and conditions.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City name (e.g., Paris, Lyon, Marseille)"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "default": "celsius"
                    }
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_forecast",
            "description": "Get weather forecasts for multiple days. "
                          "Returns day-by-day conditions.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City name"
                    },
                    "days": {
                        "type": "integer",
                        "description": "Number of forecast days (1-7)",
                        "default": 3
                    }
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_alerts",
            "description": "Check active weather alerts (storms, heatwaves, "
                          "floods) for a city or region.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City or region name"
                    }
                },
                "required": ["city"]
            }
        }
    }
]

Имплементация на функциите

В производствена среда тези функции биха извиквали реално API за време. Тук ние симулираме отговорите:

def get_weather(city, unit="celsius"):
    # In production: call OpenWeatherMap, WeatherAPI, etc.
    data = {
        "Paris": {"temp": 18, "humidity": 65, "wind": 12, "conditions": "Cloudy"},
        "Lyon": {"temp": 21, "humidity": 55, "wind": 8, "conditions": "Sunny"},
        "Marseille": {"temp": 24, "humidity": 70, "wind": 15, "conditions": "Clear"},
    }
    result = data.get(city, {"error": f"City {city} not found"})
    if "error" not in result:
        result["city"] = city
        result["unit"] = unit
    return result

def get_forecast(city, days=3):
    return {
        "city": city,
        "forecast": [
            {"day": f"Day+{i+1}", "temp_max": 20+i, "temp_min": 12+i,
             "conditions": "Variable"}
            for i in range(days)
        ]
    }

def get_alerts(city):
    alerts = {
        "Marseille": [{"type": "Strong Wind", "severity": "orange",
                       "message": "Gusts up to 90 km/h expected"}],
    }
    return {"city": city, "alerts": alerts.get(city, [])}

Основен цикъл на агента

def execute_function(name, args):
    functions = {
        "get_weather": get_weather,
        "get_forecast": get_forecast,
        "get_alerts": get_alerts,
    }
    fn = functions.get(name)
    if not fn:
        return {"error": f"Unknown function {name}"}
    try:
        return fn(**args)
    except Exception as e:
        return {"error": str(e)}

def weather_agent(user_message):
    messages = [
        {
            "role": "system",
            "content": "You are an expert weather assistant. "
                       "Use the available tools to provide "
                       "accurate weather information. Always "
                       "check alerts when asked about the "
                       "weather for a city."
        },
        {"role": "user", "content": user_message}
    ]

    for _ in range(5):  # Max 5 turns
        response = client.chat.completions.create(
            model="grok-4.5",
            messages=messages,
            tools=tools
        )

        message = response.choices[0].message
        messages.append(message)

        if not message.tool_calls:
            return message.content

        for tc in message.tool_calls:
            args = json.loads(tc.function.arguments)
            print(f"  → Calling: {tc.function.name}({args})")
            result = execute_function(tc.function.name, args)
            messages.append({
                "role": "tool",
                "tool_call_id": tc.id,
                "content": json.dumps(result, ensure_ascii=False)
            })

    return "Sorry, too many turns required."

Тестване на агента

# Test 1: simple question
print(weather_agent("What's the weather like in Paris?"))

# Test 2: forecast
print(weather_agent("Give me the forecast for Lyon for 5 days"))

# Test 3: multi-city (parallel calls)
print(weather_agent("Compare the weather between Paris, Lyon, and Marseille"))

# Test 4: complex question
print(weather_agent("I'm going to Marseille this weekend, what do you recommend?"))

Тест 3 задейства паралелни извиквания: моделът извиква get_weather три пъти едновременно. Тест 4 е най-интересен — моделът трябва да извика get_forecast И get_alerts за Марсилия, след което да синтезира резултатите в практически съвети.

Възможни подобрения

За агент, готов за производствена среда, добавете:

  • Кеширане: избягвайте извикването на API за времето за един и същи град в рамките на 10 минути
  • Геокодиране: конвертирайте имената на градовете в координати за по-голяма точност
  • История: запазвайте потребителските предпочитания (мерни единици, любими градове)
  • Интернационализация: поддръжка на имена на градове на всички езици

Ключови изводи

  • Един пълен агент комбинира множество инструменти с различни отговорности
  • Системният промпт насочва поведението на модела (систематична проверка на предупрежденията)
  • Цикълът с многократни размени (multi-turn) с max_iterations предотвратява безкрайните цикли
  • Диспечерът execute_function централизира изпълнението и обработката на грешки
  • Тествайте с разнообразни заявки: прости, за множество градове, сложни
  • В производствена среда добавете кеширане, геокодиране и история на потребителя