Wrapping It in a Service Module
Understand how to unify AI model interactions by creating a shared Python module that handles requests, normalizes responses, and isolates SDK dependencies. This lesson helps you avoid scattered logic and enables seamless switching between AI providers by centralizing the call interface.
Every lesson so far in this chapter has added a piece of logic around a model call: shaping the request as role-tagged messages, checking the stop reason before trusting the text, reading token usage. If we don't put that logic somewhere shared, every file that needs to call a model ends up reimplementing all of it, slightly differently, scattered across the codebase. This lesson is about drawing one boundary: a single module that owns the SDK, so nothing else has to.
Why scattering SDK calls becomes a problem
Imagine three different parts of a backend, ticket classification, reply drafting, and summary generation, each importing a provider's SDK directly and building its own request. The moment we want to switch providers, adjust how we check stop_reason, or add logging around every call, we're now editing three separate places, and it's easy to update two of them and forget the third. Testing gets harder too: mocking a model call means mocking whichever SDK client each file happens to import, rather than mocking one function everyone shares.
The fix is the same one we'd reach for with any other external dependency: put it behind one interface, and make everything else in the codebase depend on that interface instead of the dependency itself. ...