Building LLM Manager
Introduction and Context Setting
Welcome to the lesson on creating the LLM Manager, a central component of the AI Cooking Helper project. In previous lessons, you learned how to render prompt templates and make basic calls to a language model.
Now, we will consolidate these skills into a dedicated manager. To make this tool truly versatile, the manager is designed to accept specific prompt file names as arguments. This flexibility allows you to use the same logic for different tasks — whether you are generating a recipe, summarizing a grocery list, or suggesting substitutions — simply by specifying which files to use for the system and user instructions.
Setting Up the OpenAI Client
To communicate with the language model, we need to initialize a client and configure a logging system to keep track of what happens during the process. We use an API key stored in an environment variable to ensure security.
In this setup:
- We use the
loggingmodule to print helpful status updates to the console. - The
OpenAIclient is initialized with a key retrieved viaos.getenv. This prevents sensitive credentials from being hardcoded into your scripts.
Understanding the generate_response Function
The generate_response function handles the entire lifecycle of an AI interaction: it prepares the text, sends it to the model, and retrieves the result.
The first step is rendering the prompts. Instead of using hardcoded names, we pass the names of the files we want to use.
By passing system_prompt_name and user_prompt_name, the function can locate the correct templates in your project folder. The variables dictionary then fills in the placeholders (like {{dish_name}}} or {{ingredients}}) as we discussed in the previous lesson.
Next, we send these rendered strings to the model:
messages: This list defines the conversation history. Thesystemrole sets the behavior (e.g., "You are a chef"), and theuserrole provides the specific request.temperature: This controls how creative or predictable the response is.
Finally, we extract the text from the response object:
The strip() method ensures that any unnecessary leading or trailing spaces are removed from the chef's response.
