Day 2 — Python for AI: type hints, Pydantic, async, APIs
Why / क्यों
English: LLM apps constantly pass data around. Type hints describe data, Pydantic validates it, async runs slow calls together, and APIs are how every AI app talks to models and tools.
Hindi: LLM apps में data लगातार आता-जाता है। Type hints data बताते हैं, Pydantic उसे check करता है, async धीमे काम साथ चलाता है, और APIs से हर AI app models और tools से बात करता है।
1. Type hints
def get_weather(city: str, days: int = 1) -> dict:
return {"city": city, "days": days, "temp": 25}
print(get_weather("Delhi", 3))
city: str = text, days: int = 1 = number with default 1, -> dict = returns a dictionary.
2. Pydantic — real validation
pip install pydantic
from pydantic import BaseModel, ValidationError
class WeatherRequest(BaseModel):
city: str
days: int
print(WeatherRequest(city="Delhi", days="3")) # "3" becomes 3
try:
WeatherRequest(city="Delhi", days="three")
except ValidationError as e:
print("Error caught:", e)
Interview
"How do you make LLM output reliable?" → structured output + Pydantic validation + retry.
3. Async — wait for many things together
flowchart LR
subgraph Sync["Sync: 6 seconds"]
A1[weather 2s] --> A2[news 2s] --> A3[llm 2s]
end
subgraph Async["Async: 2 seconds"]
B1[weather 2s]
B2[news 2s]
B3[llm 2s]
end
import asyncio
import time
async def fetch(name: str) -> str:
await asyncio.sleep(2)
return f"{name} done"
async def main():
start = time.time()
results = await asyncio.gather(fetch("weather"), fetch("news"), fetch("llm"))
print(results)
print(f"Total time: {time.time() - start:.1f} seconds")
asyncio.run(main())
async def = can pause while waiting · await = wait here, let other work run · asyncio.gather = run tasks together.
4. APIs — the waiter between you and the server
pip install requests
import requests
url = "https://api.open-meteo.com/v1/forecast"
params = {"latitude": 28.61, "longitude": 77.21, "current_weather": True}
response = requests.get(url, params=params)
print("Status:", response.status_code)
print("Temperature:", response.json()["current_weather"]["temperature"], "°C")
Status codes
200 = success · 4xx = client mistake (fix the request) · 5xx = server problem (retry).
Quiz / अपने आप को test करो
1. Type hints vs Pydantic — what is the difference?
Type hints only describe types; Pydantic actually checks and converts data at runtime.
2. What happens with days=\"3\" and days=\"three\" in Pydantic?
"3" is converted to 3; "three" raises a ValidationError.
3. Three 2-second API calls: how long sync vs async?
Sync ≈ 6 seconds, async ≈ 2 seconds.
4. What does asyncio.gather do?
Runs several async tasks at the same time and returns all results.
5. What does status code 200 mean, and 504?
200 = success; 504 = server timed out (server-side, retry).