Python for AI apps: async, typing & Pydantic
Write typed async Python and validate data with Pydantic models.
By Invicly Tech, , in AI Engineering with Python. About 11 minutes to read.
In short
LLM apps spend most of their time waiting on network calls, so async Python lets you run many at once. Type hints and Pydantic models make data shapes explicit and validate them at runtime.
Explained simply
An AI app spends most of its time waiting. It sends a question to a model and then waits a few seconds for the answer. If your code waits for each call before starting the next, ten calls take ten times as long. Async Python lets your program start many calls and wait for all of them at once.
async def creates a special function called a coroutine. Inside it, await means: pause here until this is ready, and let other work run meanwhile. A scheduler called the event loop switches between paused coroutines. It is still one thread; it just never sits idle while something else could run.
Type hints are labels that say what kind of data a variable holds, like name: str or scores: list[float]. Python does not enforce them while running, but your editor and tools like mypy use them to catch mistakes before you run the code.
Pydantic goes further: it checks data while the program runs. You describe the shape once in a class, and Pydantic converts and validates incoming data, such as JSON from a model, and raises a clear error if something is missing or wrong. That makes model output safe for the rest of your code to use.
Press Play on a diagram to walk through it one step at a time.
- One call at a time
- Total time is the sum
- Simple to reason about
- Calls overlap while waiting
- Total time near the slowest
- Needs a concurrency limit
- 1Request object
Pydantic model built from user input
- 2Async API call
await client call under a Semaphore
- 3Raw JSON text
Untrusted model output
- 4model_validate_json
Parse, convert and check types
- 5Typed result
Safe for the rest of the code
In depth
How the event loop really runs your code
asyncio runs on one thread. The event loop keeps a list of tasks that are ready to run. It runs one until that task reaches an await on something slow, such as a network reply. The task then gives control back, and the loop runs the next ready task. When the reply arrives, the paused task becomes ready again.
This only works if every slow step is awaitable. A normal blocking call such as time.sleep or requests.get does not give control back, so the whole loop freezes and every other task waits. Use async libraries instead: httpx.AsyncClient for HTTP, and the async client that most official LLM SDKs provide.
If you must call blocking code, run it in a worker thread with await asyncio.to_thread(func, args). CPU-heavy work, such as large parsing jobs, is better in a separate process pool.
- One thread, many tasks, switching at each await
- time.sleep blocks; await asyncio.sleep does not
- asyncio.to_thread wraps blocking calls
- asyncio.run(main()) starts the loop once at the top
- Event loop to Task A: Run A1Run A
- Task A to Event loop: await API reply: pause2await API reply: pause
- Event loop to Task B: Run B meanwhile3Run B meanwhile
- Task B to Event loop: await API reply: pause4await API reply: pause
- Event loop to Task A: A's reply arrived: resume5A's reply arrived: resume
- Task A to Event loop: A finished6A finished
- Event loop to Task B: B's reply arrived: resume7B's reply arrived: resume
Running many calls safely: gather, TaskGroup and Semaphore
asyncio.gather(*coros) runs coroutines concurrently and returns their results in the same order you passed them in. By default, the first exception is raised to you, but the other calls keep running in the background. With return_exceptions=True, errors are returned in the list instead, so one failure does not hide all the successes.
Python 3.11 added asyncio.TaskGroup. If one task fails, the group cancels the rest and raises an ExceptionGroup. Use it when partial results are useless.
Either way, cap concurrency. Firing 500 calls at once will hit the provider's rate limits. An asyncio.Semaphore(5) lets only five calls run at the same time; the rest wait their turn. asyncio.timeout(30), also new in 3.11, cancels a block that takes too long.
- Results in input order
- return_exceptions=True collects errors
- Other calls keep running after one fails
- Good for best-effort batches
- Tasks created with tg.create_task
- One failure cancels the others
- Raises an ExceptionGroup
- Good when all results are required
Type hints that pay off in AI code
Type hints are not checked at runtime; a type checker such as mypy or pyright reads them. They are most useful at boundaries: what a function takes and returns. Modern syntax is short: list[str], dict[str, float], str | None (Python 3.10 and newer).
A few types fit AI code well. Literal["low", "high"] restricts a value to fixed options, which matches labels a model must choose from. TypedDict describes the shape of a plain dict, such as a chat message with role and content keys. Protocol describes any object with certain methods, so you can write code against "anything with a complete() method" and swap providers or test fakes without changing callers.
Annotate async functions with their result type: async def ask(q: str) -> Answer. The checker then knows that await ask(q) gives an Answer.
- Literal for fixed label sets
- TypedDict for message dicts
- Protocol for swappable clients
- Run mypy or pyright in CI
Pydantic v2 features you will use daily
A Pydantic model is a class that inherits from BaseModel with typed fields. Model.model_validate(data) checks a dict, Model.model_validate_json(text) parses and checks a JSON string in one step, and obj.model_dump() turns it back into a dict. Model.model_json_schema() produces a JSON Schema you can send to an LLM API for structured output.
Field adds rules: Field(ge=1, le=5) for a 1 to 5 score, Field(min_length=1) for a non-empty string, and description="..." which also ends up in the schema. By default Pydantic is lenient and converts "3" to 3; set strict mode when you want exact types.
For app settings, the separate pydantic-settings package provides BaseSettings, which reads values from environment variables and .env files and validates them at startup, so a missing API key fails immediately instead of on the first request.
- model_validate_json: parse and validate in one step
- Field(ge=, le=, min_length=, description=)
- ValidationError.errors() lists every problem
- SecretStr hides keys when printed or logged
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Write async functions with asyncio~1h
- 2Add type hints throughout~1h
- 3Validate data with Pydantic models~1h
- 4Run concurrent API calls with gather~1h
Key points
- async def defines a coroutine; await pauses it while I/O happens.
- asyncio.gather runs several coroutines concurrently and collects results.
- Use a Semaphore to cap concurrency and stay under rate limits.
- Pydantic validates and converts data, raising clear errors on bad input.
Key terms
Tap a card to flip it. 0/5 known
Examples
import asyncio
from pydantic import BaseModel
class Answer(BaseModel):
question: str
text: str
async def ask(q: str) -> Answer:
await asyncio.sleep(1) # stands in for an API call
return Answer(question=q, text=f'Answer to {q}')
async def main() -> None:
answers = await asyncio.gather(*(ask(q) for q in ['a', 'b', 'c']))
print([a.text for a in answers]) # about 1s total, not 3s
asyncio.run(main())Three simulated calls run concurrently and return typed objects.
Summarise 100 documents without hitting rate limits
You must summarise 100 documents, and your provider allows only a handful of calls at once. Step 1: write one async function per document. Step 2: wrap the call in a Semaphore(5) so at most five run at the same time. Step 3: use gather with return_exceptions=True so one failure does not lose the other 99 results. Step 4: split successes from failures and retry only the failures later. With a 1 second call, this takes about 20 seconds instead of 100.
import asyncio
sem = asyncio.Semaphore(5)
async def summarise(doc: str) -> str:
async with sem: # at most 5 calls at once
await asyncio.sleep(1) # stands in for the API call
return doc[:20]
async def main() -> None:
docs = [f"document number {i}" for i in range(100)]
results = await asyncio.gather(*(summarise(d) for d in docs), return_exceptions=True)
ok = [r for r in results if not isinstance(r, Exception)]
print(len(ok), "done") # about 20 s total
asyncio.run(main())Validated settings that fail fast
Your app reads an API key, a model name and a concurrency limit from the environment. Step 1: install pydantic-settings. Step 2: describe the settings as a class with types and limits. Step 3: create Settings() at startup; it reads APP_LLM_API_KEY and the others from the environment or a .env file. Step 4: if the key is missing or max_concurrency is 500, startup fails with a clear ValidationError. SecretStr prints as stars, so the key does not leak into logs.
# pip install pydantic-settings
from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="APP_", env_file=".env")
llm_api_key: SecretStr
model_name: str = "small-model"
max_concurrency: int = Field(default=5, ge=1, le=50)
request_timeout_s: float = 30.0
settings = Settings() # raises ValidationError if invalid
print(settings.llm_api_key) # **********
key = settings.llm_api_key.get_secret_value()Quick reference
- asyncio.run(main()) starts the event loop once, at the top of the program
- Never use time.sleep or requests inside async code; use asyncio.sleep and httpx.AsyncClient
- await asyncio.to_thread(fn, arg) runs blocking code without freezing the loop
- asyncio.Semaphore(n) caps how many calls run at the same time
- gather(..., return_exceptions=True) keeps successes when some calls fail
- Model.model_validate_json(text) parses and validates JSON in one step
- Field(ge=1, le=5, description=...) adds rules that also appear in the JSON Schema
Common mistakes
- Calling blocking libraries inside async code, which stalls the event loop.
- Launching hundreds of concurrent calls and hitting rate limits.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write an async function fetch(i) that sleeps for 1 second and returns i * 2. Run it for i in 0..9 first one after another, then with gather, and time both.
- Exercise 2medium
Define a Pydantic model Review with rating (int, 1 to 5), sentiment (positive, negative or mixed) and summary (non-empty str). Validate one good and one bad JSON string and print the errors.
- Exercise 3hard
Build ask_all(questions, limit) that runs calls with at most limit at once, gives each call a 5 second timeout, and returns a list where failures are replaced by the string "error".
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is async Python faster than threads?
- For many waiting network calls, async is light and easy to scale to hundreds of tasks on one thread. It does not speed up CPU-heavy work; use processes for that.
- Can I use await in a normal script or Jupyter notebook?
- In a script, put your code in async def main() and call asyncio.run(main()). Jupyter already runs an event loop, so you can write await directly in a cell.
- What is the difference between Pydantic v1 and v2?
- v2 has a faster core and renamed methods: parse_raw became model_validate_json, dict became model_dump and schema became model_json_schema. New code should use v2.
- Do I need type hints if I use Pydantic?
- Pydantic reads the type hints on your model fields to know what to validate, so yes for models. Hints on ordinary functions are optional but help editors and type checkers catch bugs.