Chat Context Dependency Injection
Chat Context Dependency Injection
In this tutorial, we’ll build upon the concepts introduced in the Tools
with Dependency
Injection
notebook to demonstrate how to use ChatContext
for more advanced
workflows.
By leveraging ChatContext
, we can track the flow of conversations,
ensuring proper function execution order. For example, before retrieving
a user’s account balance, we’ll ensure the user has logged in first.
This approach prevents unauthorized actions and enhances security.
Benefits of Using ChatContext
- Flow Control: It helps enforce the
correct sequence of function calls. - Enhanced Security: Ensures actions
depend on preconditions like authentication. - Simplified Debugging:
Logs conversation history, making it easier to trace issues.
Installation
To install AG2
, simply run the following command:
Imports
Define BaseContext Class
The following BaseContext
class and helper functions are adapted from
the previous tutorial. They define the structure for securely handling
account data and operations like login and balance retrieval.
Helper Functions
These functions validate account credentials and retrieve account balances.
Agent Configuration
Configure the agents for the interaction.
config_list
defines the LLM configurations, including the model and API key.UserProxyAgent
simulates user inputs without requiring actual human interaction (set toNEVER
).AssistantAgent
represents the AI agent, configured with the LLM settings.
Injecting a ChatContext Parameter
Now let’s upgrade the example from the previous tutorial by introducing
the ChatContext
parameter. This enhancement allows us to enforce
proper execution order in the workflow, ensuring that users log in
before accessing sensitive data like account balances.
The following functions will be registered:
login
: Verifies the user’s credentials and ensures they are logged in.get_balance
: Retrieves the account balance but only if the user has successfully logged in first.
Finally, we initiate a chat to retrieve the balance.