
Every reliable project starts with knowing exactly which Python you are running and where its packages live. In this opening lecture you will inspect your Python interpreter and your virtual environment so that the AI gateway you build in this course rests on a clean, predictable foundation.
You will begin by asking Python about itself. You will read the interpreter version, its executable path and the prefix that tells you whether you are inside a virtual environment or using the system installation. Comparing these values shows you immediately whether your environment is isolated.
Next you will learn why isolation matters. A virtual environment keeps the packages for this project separate from everything else on your computer, which prevents version clashes and makes your results repeatable. You will see how to create one with the standard venv module, how to activate it on Windows, macOS and Linux, and how to confirm that activation worked by checking the paths again.
You will also inspect the list of installed packages and see how a new environment starts nearly empty. This gives you a baseline that you can compare against later when dependencies are added.
Finally you will write a small script that prints a short environment report. You will reuse this idea throughout the course whenever you need to confirm what is running.
By the end of this lecture you will be able to inspect an interpreter, create and activate a virtual environment, and verify that your gateway project is isolated and ready for development.
A gateway that works on your machine but fails on someone else's is a frustrating thing to ship. The usual cause is dependency drift, where different versions of the same package are installed in different places. In this lecture you will learn how to pin dependencies so that every installation of your project behaves the same way.
You will begin by looking at what happens when requirements are loose. A line that simply names a package can resolve to a different version next month, and a small change in a library can quietly alter behaviour. You will see why this is risky for infrastructure that sits in front of every AI request.
Next you will create a requirements file with exact version numbers using the double equals syntax. You will learn how to capture the currently installed versions with pip freeze, how to review the output and how to trim it down to the packages your project actually needs.
You will then practise installing from the pinned file into a fresh virtual environment and confirm that the resulting versions match. You will also discuss the difference between direct and transitive dependencies, and why a separate file for development tools keeps production installs small.
You will write a short check in Python that compares installed versions against the pinned list.
By the end of this lecture you will be able to pin dependencies, reproduce an environment from a requirements file and detect version drift in your gateway project.
An AI gateway spends most of its time waiting: waiting for a client to send a request, waiting for a provider to answer, waiting for a stream to produce the next token. Asynchronous programming lets one process handle many of these waits at once. In this lecture you will write your first coroutine with asyncio, the foundation for everything that follows.
You will begin with the difference between synchronous and asynchronous code. In a synchronous program, a slow call blocks everything else. In an asynchronous one, a coroutine can pause at an await point and let other work run, which is exactly what a gateway handling many clients needs.
Next you will define a coroutine with async def and see that calling it does not run it but returns a coroutine object. You will run it with asyncio.run, use await to call another coroutine and see the order in which messages appear.
You will then use asyncio.sleep to simulate a slow upstream call and run several coroutines together with asyncio.gather. By timing the result, you will see that three one-second waits finish in about one second rather than three. This is the core benefit you will rely on later.
You will also look at common mistakes, such as forgetting to await a coroutine, and read the warning that Python prints.
By the end of this lecture you will be able to write coroutines, run them with asyncio, await other coroutines and run tasks concurrently.
Now that you understand coroutines, you will use them to create the heart of your gateway: a minimal asynchronous HTTP application. In this lecture you will write a small ASGI app that receives a request and sends back a response, with no web framework doing the work for you.
You will begin by learning what ASGI is. It is a standard interface between a Python web server and an application, built around an async callable that receives a scope, a receive function and a send function. Understanding this contract gives you full control, and it explains what the frameworks you may know are doing underneath.
Next you will write the app as an async function. You will inspect the scope to read the request path and method, then send a response start message with a status code and headers, followed by a response body message. You will see exactly how bytes and header pairs are expected to look.
You will then add simple routing for a health endpoint that returns a small JSON document and a fallback that returns a not found response. You will test the app by calling it directly with fake receive and send functions, so no network or paid service is needed.
By the end of this lecture you will be able to explain the ASGI interface, write a minimal async application and return JSON responses, giving your gateway a working core to extend.
A gateway has to understand what clients are asking for. In this lecture you will parse a chat completion request body out of ASGI messages, which is the first step in proxying a call to a language model provider.
You will begin by looking at the shape of a typical chat completion request: a model name, a list of messages with roles and content, and optional settings such as temperature. These fields are the contract your gateway will receive from clients.
Next you will learn how ASGI delivers the body. It arrives as one or more http.request messages, each with a chunk of bytes and a flag that says whether more data is coming. You will write an async helper that keeps calling receive until the body is complete and joins the chunks together.
You will then decode the bytes, parse the JSON and validate the result. You will check that the model is present, that messages is a non-empty list and that each message has a role and some content. When something is wrong, you will return a clear 400 response with a helpful explanation instead of letting an exception escape.
You will test the parser with a well formed request, a request split across several chunks and a malformed one, using synthetic data and fake receive functions.
By the end of this lecture you will be able to read a request body from ASGI, parse and validate a chat completion payload and reject bad input with a useful error.
Once the gateway understands the incoming request, it must create the request it will send upstream. A gateway rarely forwards the client's body untouched, because it may need to change the model name, add settings or attach its own metadata. In this lecture you will learn how to build an upstream request payload from a parsed client request.
You will begin by deciding what belongs in the outgoing request: the target URL, the HTTP method, the headers and the JSON body. You will represent these in a small structure so that the rest of the gateway can pass them around without confusion.
Next you will write a function that copies the relevant fields from the client request and applies gateway rules. You will substitute a configured upstream model for a public alias, set a default value for missing options and make sure that fields the provider does not expect are left out.
You will also handle headers with care. You will add the provider credential from gateway configuration, set the content type and avoid blindly passing along every client header. This shows why a gateway is a useful security boundary.
You will test the builder with several synthetic requests and print the resulting payloads to check that they match your expectations, without contacting any real service.
By the end of this lecture you will be able to construct upstream requests from client input, apply gateway defaults and keep credentials and headers under your control.
You have a parsed request and a payload ready to send. Before you connect to a real provider, you need a safe way to test the forwarding step. In this lecture you will forward requests through a mock upstream transport, which lets you develop and test the whole proxy path without paying for API calls or needing a network.
You will begin by defining what a transport is in your gateway: an async callable that takes an upstream request and returns an upstream response. Because it is just a function with a clear signature, you can swap a real one for a fake one without changing the rest of the code.
Next you will write a mock transport that returns a canned chat completion response. You will make it record the requests it receives so that your tests can inspect them, and you will give it options to simulate a delay or a failure status.
You will then write the forwarding function that builds the request, calls the transport with await and returns the result. You will test that the mock receives the correct model, messages and headers.
You will also discuss why this design, known as dependency injection, makes later features such as retries and fallbacks much easier to build and test.
By the end of this lecture you will be able to define a transport interface, build a mock upstream and forward requests through it in a repeatable way.
The final step in a basic proxy is giving the upstream answer back to the client. In this lecture you will connect the pieces you have built so far and return the upstream response through your gateway endpoint, completing your first end-to-end request.
You will begin by reviewing the flow: the endpoint receives an ASGI request, parses the body, builds the upstream payload, forwards it through the transport and then needs to translate the result into an ASGI response. You will write this flow as a single async handler.
Next you will convert the upstream response into response messages. You will copy the status code, choose which headers to pass through and send the body bytes. You will see why some headers, such as those describing connection details or the original length, should not simply be copied.
You will then handle failure cases. If the upstream returns an error status, you will decide whether to pass it on or wrap it in a gateway error message. If the transport raises an exception, you will return a 502 response with a clear message rather than leaking internal details.
You will test the whole path with a fake client, using a mock upstream, and compare the response you receive with what the mock produced.
By the end of this lecture you will be able to return upstream responses through an ASGI endpoint, manage headers and status codes carefully and handle upstream failures gracefully.
Different AI providers describe the same idea in different ways, and a gateway that exposes all of them directly forces every client to learn each format. A better approach is to define one common request shape inside your gateway. In this lecture you will build that schema using Python dataclasses.
You will begin by listing what every chat request needs: a model, a list of messages and a few common options such as temperature and a maximum number of tokens. You will separate what is truly universal from what is specific to one provider, since the common schema should only contain what you can support everywhere.
Next you will write dataclasses for a message and for the request. You will use type hints, default values and frozen instances so that the objects are clear and safe from accidental changes. You will see how dataclasses give you an init method, a readable representation and equality for free.
You will then add validation in the post-init step, checking that roles are allowed, that the message list is not empty and that numeric options fall in a sensible range. You will also write a helper that builds the common request from a parsed client body.
You will test valid and invalid examples using synthetic data and read the error messages.
By the end of this lecture you will be able to design a provider-neutral request schema, validate it and convert raw client data into well typed objects.
With a common request schema in place, the gateway needs translators that convert it into what each provider expects. In this lecture you will write the first translator, which turns your common request into an OpenAI-style chat completion payload.
You will begin by reviewing the OpenAI-style format: a model field, a messages list with role and content, and optional fields such as temperature, max tokens and a stream flag. Because this format is close to your common schema, it makes a good first example of the translator pattern.
Next you will write a function that takes a common request and returns a plain dictionary ready to be serialised as JSON. You will map each field carefully, leave out options that were not set rather than sending nulls and convert the message objects into dictionaries.
You will also decide how to handle values that need adjusting. For example, you will apply the provider's model name from configuration and make sure token limits use the correct field name.
You will test the translator with several synthetic requests, print the resulting payloads and compare them to expected dictionaries, using assertions. You will also check that the original request object is not changed by the translation.
By the end of this lecture you will be able to write a pure translation function, map schema fields to an OpenAI-style payload and verify it with simple tests.
Not every provider uses the same format as the one you just translated into. Anthropic-style APIs, for example, treat the system prompt differently and use different field names. In this lecture you will write a second translator, which turns the common request into an Anthropic-style payload and shows why a translation layer is so valuable.
You will begin by comparing the two formats side by side. You will notice that a system instruction is a separate top-level field rather than a message with a system role, that a maximum token value is required and that some option names differ. These differences are exactly what a gateway hides from its clients.
Next you will write the translator function. You will separate system messages from conversation messages, join multiple system messages into one piece of text and keep the remaining messages in order. You will supply a sensible default for the required token limit when the client did not provide one.
You will then handle edge cases, such as requests with no system message or with consecutive messages from the same role, and you will decide how to report problems that cannot be translated.
You will test the translator with synthetic conversations and compare the output with the expected structure, without contacting any service.
By the end of this lecture you will be able to map one common schema to a second provider format, handle system prompts correctly and appreciate how translators isolate provider differences.
Translating requests is only half of the job. The answers that come back also differ between providers, and clients should not need to care. In this lecture you will normalise provider responses into one common response schema so that your gateway always returns the same structure.
You will begin by designing the common response. It should contain an identifier, the model that answered, the generated text, a finish reason and token usage counts for input and output. These are the facts that almost every client and every later feature, such as cost tracking, will need.
Next you will study how the two provider styles describe their results. One places the text inside a list of choices, and the other returns a list of content blocks. Usage fields also have different names. You will write one normaliser function for each style that extracts the information into your dataclass.
You will handle missing and unexpected data carefully. If a field is absent, you will fill in a safe default or raise a clear error, and you will make sure that finish reasons are mapped to a small set of consistent values.
You will test each normaliser with synthetic provider responses and confirm that both produce identical structures for equivalent content.
By the end of this lecture you will be able to normalise differing response formats, extract usage data reliably and give clients one consistent response shape.
You now have request translators and response normalisers for two providers. The last step in building a unified API is a single entry point that chooses the right pair automatically. In this lecture you will build a translator registry and route calls through it to one simple interface.
You will begin by thinking about the problem a registry solves. Without it, the gateway would need a growing chain of if statements, one for every provider, and each new provider would force changes in several places.
Next you will define a small structure that groups a provider's translate function and its normalise function. You will store these in a dictionary keyed by provider name and write functions to register and look up entries. If a name is not found, you will raise a clear error that lists the available choices.
You will then write a single function, such as complete, that accepts a common request and a provider name. It will look up the translator, build the payload, send it through the transport and normalise the response. You will test it with the mock upstream for both providers and confirm that the caller sees the same interface each time.
You will also see how adding a third provider would only require writing its two functions and registering them.
By the end of this lecture you will be able to build and use a registry, route calls by provider name and extend your gateway without changing existing code.
Streaming lets a client see a model's answer as it is produced instead of waiting for the whole reply. The most common way to deliver it over HTTP is Server-Sent Events, usually shortened to SSE. In this lecture you will learn the SSE format and write a function that formats event frames correctly.
You will begin with what SSE is: a simple text protocol in which the server keeps a response open and sends small messages, each made of lines such as data, event and id, ending with a blank line. You will learn why that blank line matters, because it is what tells the client that one event is complete.
Next you will write a small formatter that takes a payload and returns bytes ready to send. You will serialise dictionaries to JSON, prefix the data line properly and handle text that contains newlines by splitting it into several data lines, as the specification requires. You will add optional event names and identifiers.
You will also write the special final marker that many chat APIs use to signal that a stream has finished, and you will discuss how a client recognises it.
You will test the formatter with synthetic chunks and compare the exact bytes produced, so you can see every character, including the trailing blank line. You will also check that unusual characters are encoded as UTF-8 correctly.
By the end of this lecture you will be able to describe the SSE wire format, format event frames precisely and signal the end of a stream.
Formatting events is one thing, and sending them to a client over time is another. In this lecture you will stream an ASGI response in chunks, which is how your gateway will push tokens to a client as they become available.
You will begin by reviewing how ASGI sends a response. The start message carries the status and headers, and the body can then be sent as several messages, each with a chunk of bytes and a flag called more body that says whether another chunk will follow. When the last chunk is sent with that flag set to false, the response is complete.
Next you will write an async handler that sends the start message with the right content type for event streams and with headers that discourage caching. You will then loop over a simple async generator that yields frames and send each one as soon as it is produced.
You will use asyncio.sleep to simulate a delay between chunks, and a test client that records each message together with its arrival order. This lets you confirm that data is delivered incrementally rather than all at once at the end.
You will also make sure that the final empty chunk is sent so that the connection closes properly.
By the end of this lecture you will be able to send chunked ASGI responses, set streaming headers and test that data arrives progressively.
With the streaming plumbing ready, you can connect it to a source of tokens. In this lecture you will relay a mock provider token stream through your gateway, turning a sequence of small pieces of text into a stream that clients can read.
You will begin by building the mock provider as an async generator. It will yield small pieces of a sentence one at a time, with a short delay between them, and finish with a final chunk that includes a finish reason. Using synthetic text keeps the exercise free of any paid service.
Next you will write the relay. It will read each provider chunk, translate it into your common chunk format and wrap it as an SSE frame. You will send the frames through the chunked ASGI response from the previous lecture, followed by the final done marker.
You will think about the details that make streaming feel smooth. You will avoid collecting the full answer in memory before sending, you will flush each frame immediately and you will keep the chunk format stable so that clients can parse it reliably.
You will test by collecting all the frames sent, joining the text pieces and checking that they reproduce the full original sentence in the correct order.
By the end of this lecture you will be able to relay an async token stream, convert provider chunks into SSE frames and verify that streamed content is complete.
Streams do not always end neatly. A client might close the connection halfway through, or the upstream provider might fail after sending a few tokens. In this lecture you will make your streaming code robust by handling cancellation and upstream errors.
You will begin with the problem. If a client disconnects and your gateway keeps reading from the provider, it wastes time and money on tokens that nobody will see. You will learn how ASGI tells you about a disconnect through a receive message and how asyncio signals that a task has been cancelled with a CancelledError.
Next you will write the relay so that it listens for disconnects while it streams. When one occurs, you will stop reading from the upstream generator and close it properly so that its resources are released. You will use try and finally blocks to guarantee that cleanup code always runs.
You will then handle errors that occur after streaming has already started. Because the status code has been sent, you can no longer change it, so you will send a final error event in the stream and end the response in an orderly way.
You will test both situations with synthetic generators, one that is cancelled partway and one that raises an exception, and check that cleanup ran and that clients receive a clear signal.
By the end of this lecture you will be able to detect disconnects, release upstream resources and report mid-stream failures properly.
Any gateway that sits in front of valuable AI services needs to know who is calling it. Instead of sharing the provider's own credentials, you will issue separate API keys for each client. In this lecture you will learn how to generate gateway API keys safely.
You will begin with the requirements of a good key. It must be unpredictable, long enough to resist guessing and easy to recognise. You will use Python's secrets module, which draws from a cryptographically secure source, and you will see why the random module is not suitable for this job.
Next you will design a key format with a readable prefix, which makes keys easy to identify in logs and configuration, followed by a random portion encoded in a URL-safe way. You will write a function that creates a new key and a short identifier that can be used for display without revealing the secret.
You will then discuss how keys should be handled. The full value should be shown to the owner only once, and the gateway should store only a hash of it, which you will implement in the next lecture. You will also look at attaching metadata such as an owner name, a creation time and an optional expiry.
You will test that generated keys are unique, have the expected format and length, and that the identifier does not expose the secret, using synthetic names only.
By the end of this lecture you will be able to generate secure API keys, design a recognisable format and understand how keys should be stored and displayed.
Generating keys is only useful if the gateway can check them later. In this lecture you will build a key store that validates API keys without ever keeping the real secrets on disk or in memory longer than needed.
You will begin with the danger of storing keys in plain text. If the store were leaked, every key would be exposed at once. You will learn why a fast, one-way hash of a high-entropy key is a sensible approach and how it differs from the slower hashing used for human chosen passwords.
Next you will write a key store class. When a key is added, it will hash the value with SHA-256 and save only the hash together with the owner and other metadata. When a key is presented, it will hash the incoming value and look up the result.
You will use a constant time comparison from the standard library when comparing hashes, to avoid leaking information through timing differences. You will also handle revoked and expired keys, returning clear results that explain why validation failed.
You will test the store with synthetic keys. You will confirm that a valid key is accepted, that a modified key is rejected, that a revoked key stops working and that the stored data never contains the original secret.
By the end of this lecture you will be able to hash and store keys safely, validate them with constant time comparison and manage revocation and expiry.
With a key store ready, the gateway can finally protect its endpoints. In this lecture you will authenticate ASGI requests by reading the key from the request headers, checking it against the store and rejecting callers who are not allowed in.
You will begin with the standard way to present a credential, the Authorization header using the Bearer scheme. You will learn how ASGI exposes headers as a list of byte pairs, and you will write a helper that finds the header, decodes it safely and extracts the token.
Next you will write an authentication step that runs before any request handling. It will return the key record when validation succeeds and produce a 401 response when the header is missing, malformed or invalid. You will include a WWW-Authenticate header in the response, as the HTTP rules suggest.
You will think carefully about the messages you return. The response should tell the client what to fix without revealing whether a key once existed or which part of the check failed. You will also make sure that keys never appear in logs or error messages.
You will then wrap the handler so that authenticated information, such as the key owner, is passed along to later steps. You will test with synthetic keys and fake requests.
By the end of this lecture you will be able to read bearer tokens, authenticate requests, return correct 401 responses and pass identity information to the rest of the gateway.
Knowing who a caller is leads to the next question: what are they allowed to do? A free trial key might only use a small model, while an internal key may reach everything. In this lecture you will add per-key permissions for models and routes.
You will begin by designing a permission model that is simple and clear. Each key record will carry a list of allowed models and a list of allowed route patterns. You will decide how to represent a wildcard so that an administrator can grant access to a whole family of models without listing each one.
Next you will write a function that checks a request against the key's permissions. It will read the model name from the parsed request body and the path from the ASGI scope, and return a result that says whether access is allowed and, if not, which rule blocked it.
You will return a 403 response for requests that are authenticated but not permitted, and you will explain the difference between 401 and 403 so that you use each correctly. You will keep the error message helpful without revealing the full list of what other keys can do.
You will test several synthetic keys with different permissions and confirm that allowed requests pass, blocked models are rejected, wildcards work as intended and unknown routes are denied by default.
By the end of this lecture you will be able to model permissions, enforce them per request and follow a deny by default approach.
Rate limiting protects your gateway and your budget from overuse, whether it is accidental or deliberate. One of the most popular techniques is the token bucket. In this lecture you will build its core logic and learn how an injected clock makes it easy to test.
You will begin with the idea. Imagine a bucket that holds a fixed number of tokens and refills at a steady rate. Each request removes a token, and when the bucket is empty, further requests must wait or be refused. This allows short bursts while still enforcing an average rate.
Next you will write a TokenBucket class with a capacity, a refill rate and a current level. You will calculate refills lazily from the time elapsed since the last check, rather than running a background timer, which keeps the design simple and efficient.
A key lesson is how to handle time. Instead of calling the system clock inside the class, you will pass in a clock function. In production it returns the real time, and in tests it returns a fake value that you control. This lets you test refills precisely without waiting.
You will write tests that drain the bucket, advance the fake clock and confirm that tokens return at the expected speed, that the level never exceeds capacity and that fractional refills work.
By the end of this lecture you will be able to implement a token bucket, calculate lazy refills and use an injected clock to write fast, deterministic tests.
A single global limit is rarely what you want. Each client should have its own allowance so that one busy user cannot starve everyone else. In this lecture you will build per-key rate limiters on top of the token bucket from the previous lecture.
You will begin by designing a limiter manager. It will hold a dictionary that maps each key identifier to its own bucket, and it will create a bucket the first time a key is seen. You will give the manager default settings and allow individual keys to override them, so that a premium key can have a larger capacity.
Next you will write a method that checks whether a request is allowed for a given key. It will find the right bucket, try to take a token and return a result that includes whether it succeeded, how many tokens remain and how long the caller should wait before trying again.
You will consider memory use. Because a gateway may see many keys over time, you will discuss removing buckets for keys that have been idle and refilled completely, since a full bucket can be recreated at any time without any loss of information.
You will test with a fake clock and several synthetic keys, confirming that one key's usage does not affect another and that overrides apply correctly.
By the end of this lecture you will be able to manage independent limiters, apply per-key settings and report remaining capacity and wait times.
When a client goes over its limit, the gateway must say so in a clear and standard way. The correct response is HTTP status 429, Too Many Requests. In this lecture you will connect your limiter to the request path and reject excess traffic properly.
You will begin by deciding where the check belongs. It should run after authentication, so that you know which key to charge, and before any expensive upstream work. You will place it in the handler chain you have been building and make sure that rejected requests never reach the provider.
Next you will write the 429 response. You will include a JSON error body with a clear message and add a Retry-After header calculated from the limiter's wait time, rounded up to whole seconds. You will also add helpful headers that report the limit and the remaining allowance on successful responses, which lets well behaved clients slow down before they are blocked.
You will think about fairness and safety. You will make sure that the limiter state is updated atomically within the event loop, so that two concurrent requests cannot both take the last token.
You will test with a fake clock by sending a burst of synthetic requests, checking that the first ones pass, the extra ones receive 429 with a sensible wait and that requests succeed again after time advances.
By the end of this lecture you will be able to enforce limits in the request path, return correct 429 responses and communicate retry timing to clients.
Language model providers charge by tokens, so a gateway that cannot measure usage cannot control cost. In this lecture you will record token usage and calculate the cost of each request, giving you the data behind quotas, reports and budgeting.
You will begin by reviewing where usage numbers come from. The normalised response you built earlier already carries the count of input and output tokens. For streamed responses, you will see how the final chunk can carry the totals, and how an estimate may be needed when a provider does not report them.
Next you will create a price table that maps each model to a price per thousand input tokens and a price per thousand output tokens. You will use the Decimal type rather than floats so that money calculations do not suffer from rounding surprises, and you will learn why that matters in financial code.
You will write a function that turns usage into a cost and a usage recorder that stores one entry per request with the key identifier, model, token counts, cost and timestamp. You will add methods to summarise usage per key and per model.
You will test the calculations with synthetic usage figures and hand-checked answers, including very small and very large requests and models missing from the price table, which should produce a clear error.
By the end of this lecture you will be able to capture token usage, calculate costs accurately with Decimal and summarise spending by key and model.
Recording cost is useful, but controlling it is better. A spending quota stops a key from exceeding a budget, whether that budget is daily, monthly or a fixed credit. In this lecture you will enforce spending quotas for each key using the usage data you are already collecting.
You will begin by defining a quota. Each key gets a limit, a period and a running total for the current period. You will decide how periods reset, for example at the start of each calendar day, and you will use the injected clock again so that you can test resets without waiting.
Next you will write a check that runs before a request is forwarded. It will compare the spend so far with the limit and reject the call with a clear error if the budget is already used up. You will use a 402 or 429 style response with a message that explains the quota and when it resets, and you will discuss which status suits your policy.
You will also deal with a practical challenge: the exact cost is only known after the response arrives. You will see two strategies, allowing a request that starts below the limit and charging afterwards, or reserving an estimated amount first and adjusting it later.
You will test with synthetic usage, confirming that spending accumulates, that requests are blocked at the limit and that totals reset in the next period.
By the end of this lecture you will be able to define spending quotas, enforce them before forwarding and reset them by period.
A gateway becomes truly useful when it can decide which model should answer each request. Sending every call to the largest model is expensive, while sending everything to the cheapest one hurts quality. In this lecture you will build rule-based model routing that makes this decision automatically.
You will begin by thinking about the signals available. The requested model alias, the key's permissions, the length of the prompt, a header chosen by the client and the presence of certain options can all influence the choice. You will decide which of these your routing rules will inspect.
Next you will design a simple rule structure. Each rule has a condition, written as a small function or a set of fields to match, and a target that names a provider and model. You will keep the rules in an ordered list, so that the first match wins, and a default rule at the end guarantees that every request has somewhere to go.
You will write the router function that walks the list and returns the chosen target together with the name of the rule that matched, which is helpful for logs and debugging. You will implement examples such as sending short prompts to a small model, sending requests that mention a long context to a larger one and mapping friendly aliases to real model names.
You will test with synthetic requests, checking order, defaults and the case where no rule matches.
By the end of this lecture you will be able to write ordered routing rules, select targets and explain routing decisions clearly.
Provider calls fail for many temporary reasons: a brief network problem, a busy server or a rate limit. Many of these errors disappear if you simply try again after a short wait. In this lecture you will add retries with exponential backoff to your gateway.
You will begin by deciding which failures deserve a retry. Timeouts, connection problems and server errors such as 502, 503 and 429 are usually temporary, whereas a 400 or 401 will fail every time and retrying wastes effort. You will write a small function that classifies a result or exception as retryable or not.
Next you will learn the backoff idea. Instead of retrying immediately, you wait a short time, then double it after each failure, up to a maximum. This gives the struggling service time to recover and avoids overwhelming it. You will add jitter, a small random variation, so that many clients do not all retry at exactly the same moment.
You will write an async retry helper that accepts a callable, a maximum number of attempts and the delay settings. To keep tests fast and exact, you will inject the sleep function and the random source, as you did with the clock earlier.
You will test with a mock transport that fails a set number of times before succeeding, checking the number of attempts and the delays that would have been used.
By the end of this lecture you will be able to classify retryable errors, implement exponential backoff with jitter and test retry behaviour deterministically.
A slow provider can be just as damaging as a failing one. If a call hangs for a minute, your gateway holds resources and the client waits with no answer. In this lecture you will add per-request timeouts so that no request can run forever.
You will begin with the problem of unbounded waiting. Without a limit, a stalled upstream connection can accumulate until your gateway runs out of capacity. You will see why a timeout is a basic form of protection for every network call.
Next you will use asyncio.wait_for, or the timeout context manager in newer versions of Python, to cap how long an awaited call may take. You will wrap the forwarding function so that it cancels the upstream task and raises a timeout error when the limit is reached. You will check that cancellation really stops the work and releases resources.
You will then make timeouts configurable. Different models and routes may need different limits, so you will let the routing rule or the key settings supply a value, with a sensible default. You will translate the timeout error into a 504 Gateway Timeout response with a clear message.
You will also think about how timeouts interact with retries. The time budget should cover the whole operation, not just one attempt, so you will discuss and implement an overall deadline.
You will test using a mock transport that sleeps longer than the limit, and you will check the response status.
By the end of this lecture you will be able to apply timeouts to async calls, return 504 responses and combine timeouts with retries sensibly.
Retries help when a provider recovers quickly, but sometimes a provider stays down. A resilient gateway can then try a different one. In this lecture you will build fallback provider chains, so that a request moves to the next option when the first fails.
You will begin by defining a chain as an ordered list of targets, each pairing a provider with a model. A primary target comes first, followed by alternatives that you consider acceptable substitutes. You will discuss how to choose them, since a fallback must offer similar capability or the answer may change in unexpected ways.
Next you will write a function that tries each target in order. For each one it will translate the request with the correct translator, send it through the transport, normalise the answer and return it as soon as one succeeds. When a target fails with a retryable error, it moves on to the next. When every target has failed, it raises a clear error that lists the attempts.
You will include the details that make a chain trustworthy. You will record which target actually answered and expose it in a response header, you will avoid trying a target that is known to be unavailable and you will respect the overall deadline so that a long chain cannot exceed the timeout.
You will test with mock transports that fail in different patterns, checking the order of attempts and the final result.
By the end of this lecture you will be able to implement fallback chains, record which provider answered and fail clearly when all options are exhausted.
Trying a provider that is clearly broken, again and again, wastes time and can make the problem worse. A circuit breaker solves this by temporarily stopping calls to a failing service. In this lecture you will model a circuit breaker as a small state machine.
You will begin with the three states and the idea behind them. In the closed state, calls pass through normally and failures are counted. When failures reach a threshold, the breaker moves to open, and calls are rejected immediately without contacting the provider. After a cooling period, the breaker moves to half open and allows a limited number of trial calls. If they succeed, it closes again, and if they fail, it opens once more.
Next you will write a CircuitBreaker class with explicit state, a failure counter, a threshold, a recovery time and the injected clock you have used before. You will write methods that report whether a call is allowed and record the result of a call, with the state transitions in one clear place.
You will integrate the breaker with the fallback chain, so that an open breaker causes the chain to skip that target at once. You will also keep one breaker per provider so that a problem with one does not affect others.
You will test every transition using a fake clock, including the half open trial cases.
By the end of this lecture you will be able to implement a circuit breaker, explain each state and use it to protect your gateway and your providers.
Many requests to an AI gateway are repeated exactly, such as a common question or a prompt from a test suite. Paying for the same answer again and again is wasteful. In this lecture you will build an exact-match response cache that returns stored answers for identical requests.
You will begin by deciding what makes two requests identical. The model, the messages and the options that affect the output, such as temperature, must all match, while fields like a request identifier should not. You will build a cache key by selecting these fields, serialising them in a stable order with sorted keys and hashing the result.
Next you will write a cache class that wraps a dictionary. It will offer get and set methods, and the gateway will check it before contacting a provider and store the result afterwards. You will return a header, such as a cache hit marker, so that clients and logs can see when an answer came from the cache.
You will also consider when caching is appropriate. Requests with a high temperature are meant to vary, and streaming responses need special handling, so you will add rules that decide which requests can be cached. You will think about privacy too, making sure that one key's cached data is not served to another if the policy requires separation.
You will test with synthetic requests, confirming hits, misses and the effect of changing a single field.
By the end of this lecture you will be able to build stable cache keys, serve cached responses and decide which requests should be cached.
A cache that never forgets will eventually grow without limit and may serve stale answers. In this lecture you will add expiry and eviction to your cache so that it stays fresh and bounded in size.
You will begin with time-to-live, usually called TTL. Each entry is stored with an expiry time calculated from the injected clock. When an entry is read after that time, it is treated as a miss and removed. You will make the default TTL configurable and let individual entries override it, because some answers stay valid longer than others.
Next you will deal with size. You will set a maximum number of entries and choose an eviction strategy for when that limit is reached. You will implement least recently used eviction with an ordered dictionary, moving an entry to the end each time it is read, and removing the oldest when space is needed. You will compare it with simpler options such as removing the oldest inserted item.
You will also write a cleanup method that removes expired entries in bulk, and discuss when it should run, for example on a schedule or occasionally during writes.
You will track simple statistics, including hits, misses, evictions and expirations, which will later feed into your metrics.
You will test everything with a fake clock and small capacities, checking that expired entries disappear and that the correct entry is evicted.
By the end of this lecture you will be able to implement TTL expiry, apply least recently used eviction and monitor cache behaviour.
Exact-match caching only helps when the wording is identical. Users often ask the same thing in slightly different words, and a semantic cache can recognise that. In this lecture you will build a semantic cache that returns an answer when a new prompt is similar enough to an earlier one.
You will begin with the core idea. Each prompt is turned into a vector of numbers called an embedding, where similar meanings produce similar vectors. To keep the exercise self-contained and free of paid services, you will use a simple deterministic embedding function, such as hashed word counts, which is enough to demonstrate the technique.
Next you will learn cosine similarity, which measures the angle between two vectors and produces a score between minus one and one. You will implement it in plain Python and test it with vectors whose similarity you can work out by hand.
You will write the cache so that a lookup compares the new embedding with the stored ones, finds the best match and returns its answer only if the score meets a threshold. You will explore how the threshold changes behaviour. A high value is safe but rarely hits, and a low value hits often but risks returning a wrong answer.
You will test with synthetic prompt pairs that are similar, related and unrelated, and tune the threshold for sensible results.
By the end of this lecture you will be able to create simple embeddings, compute cosine similarity and use a threshold to serve semantically similar cached answers.
AI systems need safety checks on both what goes in and what comes out. A gateway is the perfect place to apply them consistently, because every request passes through it. In this lecture you will build input and output guardrails.
You will begin by deciding what to protect against. On the input side, you will check for requests that are too long, contain empty content or include patterns that your policy does not allow. You will also detect and redact sensitive-looking values, such as email addresses and long digit sequences, using regular expressions and synthetic examples.
Next you will write a guardrail interface, a function that receives text and returns a decision: allow, modify or block, together with a reason. You will write several small guardrails and chain them so that each one runs in turn. Keeping them small and independent makes them easy to test and reorder.
On the output side, you will apply similar checks to the model's answer. You will redact sensitive values that should not be returned and block responses that break a configured rule, replacing them with a safe message.
You will discuss the limits of simple pattern checks. They are a useful first layer, but they do not catch everything, so they should be combined with other controls and reviewed regularly.
You will test with synthetic strings, confirming that safe text passes, sensitive values are redacted and blocked content produces a clear response.
By the end of this lecture you will be able to build a guardrail pipeline, redact sensitive data and return clear decisions for blocked content.
A gateway that you cannot observe is a gateway you cannot trust. When something goes wrong, you need to know what happened, to whom and how often. In this lecture you will add structured logs and metrics to your gateway.
You will begin with structured logging. Instead of free text, each log entry is a JSON object with fields such as the timestamp, request identifier, key identifier, route, model, status, latency and cache result. You will use Python's logging module with a custom formatter, and you will see why structured data is easier to search and analyse.
You will add a correlation identifier to every request, generated when it arrives and carried through all later steps and into the response headers. This lets you follow one request across authentication, routing, retries and caching.
You will be careful about what you log. You will never record API keys or full prompts by default, and you will use the redaction helpers from the previous lecture where content must appear.
Next you will write a small metrics collector with counters and a histogram-like structure for latency. You will count requests by status, cache hits and misses, retries and fallbacks, and calculate averages and percentiles from recorded durations. You will expose the values through a simple metrics endpoint.
You will test using synthetic requests and check the logged fields and counter values.
By the end of this lecture you will be able to emit structured logs, trace requests with correlation identifiers and collect useful metrics.
Tests are only valuable if they are quick and reliable. For an ASGI gateway, the best approach is to call the application directly in the same process, without starting a server or using the network. In this lecture you will test the gateway with an in-process ASGI client.
You will begin by writing a small test client. It will build an ASGI scope for a given method, path and headers, supply a receive function that delivers the request body and a send function that collects the response messages. When the application finishes, the client assembles the status, headers and body into a simple result object.
Next you will use the client to test real behaviours. You will check the health endpoint, a successful chat request through the mock upstream, a request without a key that must receive a 401 and a body that is not valid JSON that must receive a 400. You will use plain assert statements, or the unittest module, so that no extra packages are needed.
You will also test streaming responses by collecting each chunk in order, which confirms that the frames are formatted properly and that the done marker arrives.
You will organise the tests into small functions with clear names and shared helpers for building synthetic requests, and you will run them together to see a summary.
By the end of this lecture you will be able to build an in-process ASGI test client, test normal and error paths and verify streaming output without any network.
A gateway has many moving parts, such as the clock, the transport, the key store and the random source. If tests rely on the real versions, results become slow and unpredictable. In this lecture you will use dependency overrides to make gateway tests deterministic.
You will begin by reviewing how the application receives its dependencies. Instead of creating them deep inside handlers, it should obtain them from a single configuration object or factory function. You will refactor the gateway so that the transport, clock, sleep function, random source and stores are passed in when the application is built.
Next you will write a test helper that builds the application with replacements. You will provide a fake clock that you advance by hand, a mock transport that returns scripted responses or failures and a key store pre-filled with synthetic keys. You will see how each replacement removes a source of randomness or delay.
With this in place, you will write tests that were hard before. You will check that a rate limit resets exactly after sixty seconds, that a retry waits the expected amounts, that a circuit breaker opens after the threshold and that a cached entry expires on time, all without waiting even a moment.
You will also discuss good test hygiene, such as creating fresh dependencies for each test so that state does not leak between them.
By the end of this lecture you will be able to structure code for injection, override dependencies in tests and write fast, repeatable tests of time-based behaviour.
Once your gateway works and is tested, you need a way to package it so that it runs the same way anywhere. Containers are the standard answer, and a Dockerfile describes how to build one. In this lecture you will write a Dockerfile for your gateway and validate it offline.
You will begin with the structure of a Dockerfile. You will choose a slim Python base image, set a working directory, copy the pinned requirements file first so that the dependency layer is cached, install the packages and then copy the application code. You will learn why this ordering makes rebuilds faster.
Next you will apply good practice. You will run the application as a non-root user, set environment variables to make Python output unbuffered, avoid copying unnecessary files with a dockerignore file and define the command that starts the server. You will also add a health check that calls your health endpoint.
Because the exercise should work without Docker installed or network access, you will validate the Dockerfile with a Python script. The script will read the file and check for a pinned base image, a non-root user, a start command and the absence of obvious mistakes such as copying secrets. This gives quick feedback in any environment.
By the end of this lecture you will be able to write a clear, secure Dockerfile for a Python service, organise layers for fast builds and validate it with a simple offline check.
It is time to bring everything together. In this capstone lecture you will assemble the complete gateway from the pieces you built in the course and test it with a simulated load test. This will show you how the features work together under pressure.
You will begin by composing the request pipeline in a sensible order. Each request is given a correlation identifier, authenticated, checked against permissions, rate limited and tested against its quota. Then guardrails inspect the input, the cache is consulted and routing selects a target. The fallback chain, with retries, timeouts and circuit breakers, forwards the request, the response is normalised and checked by output guardrails, and usage, logs and metrics are recorded.
You will build the application from a single configuration, using the mock providers and synthetic keys, so everything runs locally with no paid services. You will review the order of the steps and discuss why each belongs where it does.
Next you will write a simulated load test with asyncio. It will start many concurrent synthetic clients with different keys, send a mix of repeated and unique prompts and occasionally make a mock provider fail. You will collect the status codes and latencies.
You will then read the results: how many requests succeeded, how many were limited, how often the cache was used, which fallbacks were triggered and what the latency percentiles look like.
By the end of this lecture you will be able to assemble a complete AI gateway, run a concurrent load test and interpret the results to find improvements.
This course contains the use of artificial intelligence.
Master the art of building secure, scalable, and reliable AI Gateways from scratch using Python, Generative AI, and modern Large Language Model (LLM) infrastructure.
As artificial intelligence transforms businesses worldwide, organizations need more than simple connections to AI models. They require centralized infrastructure to manage LLM routing, API security, model integration, cost optimization, rate limiting, and AI governance. This comprehensive, hands-on course teaches you how to build that infrastructure yourself.
Through 9 comprehensive modules and 40 practical lessons, you will progressively develop an AI Gateway, starting with Python foundations and advancing toward enterprise-oriented Generative AI architecture.
What Will You Build?
You will begin by establishing a reproducible Python development environment and exploring asynchronous programming, asyncio, ASGI, HTTP services, and REST API development.
Next, you will implement an LLM Gateway that proxies requests, translates provider-specific payloads, normalizes responses, and provides a unified API for multiple AI model providers. Explore OpenAI-style and Anthropic-style API formats using simulated providers without requiring paid API subscriptions.
Learn how to implement real-time AI response streaming using Server-Sent Events (SSE), asynchronous generators, and efficient stream processing.
Security is a critical component of modern AI infrastructure. You will implement API key authentication, bearer tokens, authorization, access control, API key hashing, and model-specific permissions to protect your AI services.
Build Reliable and Cost-Efficient AI Infrastructure
Discover how enterprise AI platforms manage resource consumption through rate limiting, token bucket algorithms, usage tracking, LLM token accounting, cost management, and spending quotas.
Build intelligent and resilient AI infrastructure using rule-based LLM routing, model selection, provider fallbacks, exponential backoff, automatic retries, request timeouts, and circuit breakers.
You will also explore AI performance optimization through exact-match caching, semantic caching, cosine similarity, cache eviction, and time-to-live mechanisms.
Implement essential AI security guardrails, including input validation, sensitive data redaction, and response filtering. Develop LLM observability capabilities through structured logging, correlation IDs, operational metrics, and performance monitoring.
Practical AI Engineering and Capstone Project
Throughout the course, you will strengthen your knowledge of:
AI Gateway Architecture and Development
Generative AI Infrastructure
Python API Development
LLM Routing and Model Management
Multi-Provider AI Integration
AI Security and Governance
LLMOps and AI Platform Engineering
Distributed Systems and Fault Tolerance
Semantic Caching and Cost Optimization
Docker and Containerization Fundamentals
Automated Testing and Dependency Injection
Load Testing and Performance Engineering
Finally, you will bring everything together in a comprehensive AI Gateway Capstone Project, integrating authentication, routing, caching, rate limiting, logging, and simulated concurrent load testing into a unified application.
Who Should Take This Course?
This course is ideal for Python developers, AI engineers, Generative AI developers, backend developers, software architects, solution architects, DevOps engineers, MLOps engineers, LLMOps professionals, AI consultants, and technology enthusiasts seeking practical AI engineering experience.
Whether you are building AI-powered applications, developing enterprise AI platforms, creating AI SaaS products, or advancing your career in artificial intelligence engineering, this course provides practical skills for designing modern AI infrastructure.
Move beyond simply consuming AI APIs. Learn to build the technology that connects, protects, manages, and optimizes them.
Enroll today and take your Python programming, Generative AI development, and AI engineering skills to the next level!