"This notebook illustrates how to use `TransformMessages` give any `ConversableAgent` the ability to handle long contexts, sensitive data, and more.\n",
"Learn more about configuring LLMs for agents [here](/docs/topics/llm_configuration).\n",
":::\n",
"````"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "84d0e5ad-8b35-4b30-847e-4723e9c76f7c",
"metadata": {},
"outputs": [],
"source": [
"# Define your agent; the user proxy and an assistant\n",
"assistant = autogen.AssistantAgent(\n",
" \"assistant\",\n",
" llm_config=llm_config,\n",
")\n",
"user_proxy = autogen.UserProxyAgent(\n",
" \"user_proxy\",\n",
" human_input_mode=\"NEVER\",\n",
" is_termination_msg=lambda x: \"TERMINATE\" in x.get(\"content\", \"\"),\n",
" max_consecutive_auto_reply=10,\n",
")"
]
},
{
"cell_type": "markdown",
"id": "180aa953-45be-469a-a94f-0ed0b4ef5ddf",
"metadata": {},
"source": [
"## Handling Long Contexts\n",
"\n",
"Imagine a scenario where the LLM generates an extensive amount of text, surpassing the token limit imposed by your API provider. To address this issue, you can leverage `TransformMessages` along with its constituent transformations, `MessageHistoryLimiter` and `MessageTokenLimiter`.\n",
"\n",
"- `MessageHistoryLimiter`: You can restrict the total number of messages considered as context history. This transform is particularly useful when you want to limit the conversational context to a specific number of recent messages, ensuring efficient processing and response generation.\n",
"- `MessageTokenLimiter`: Enables you to cap the total number of tokens, either on a per-message basis or across the entire context history (or both). This transformation is invaluable when you need to adhere to strict token limits imposed by your API provider, preventing unnecessary costs or errors caused by exceeding the allowed token count."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "34b943a2-ec58-41bc-a449-d9118c4bbdea",
"metadata": {},
"outputs": [],
"source": [
"# Limit the message history to the 3 most recent messages\n",
"Let's take a look at how these transformations will effect the messages. Below we see that by applying the `MessageHistoryLimiter`, we can see that we limited the context history to the 3 most recent messages."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "61a2ead4-5f8b-4108-b1f0-3b51b41e2231",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[{'content': 'how', 'role': 'user'},\n",
" {'content': [{'text': 'are you doing?', 'type': 'text'}], 'role': 'assistant'},\n",
" {'content': 'very very very very very very long string', 'role': 'user'}]\n"
"Now let's test limiting the number of tokens in messages. We can see that we can limit the number of tokens to 3, which is equivalent to 3 words in this instance."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "739dd260-fa95-4e5d-ae84-9cb7f40de975",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[33mTruncated 6 tokens. Tokens reduced from 15 to 9\u001b[0m\n",
"Let's test these transforms with agents (the upcoming test is replicated from the agentchat_capability_long_context_handling notebook). We will see that the agent without the capability to handle long context will result in an error, while the agent with that capability will have no issues."
"Error code: 429 - {'error': {'message': 'Request too large for gpt-3.5-turbo in organization org-U58JZBsXUVAJPlx2MtPYmdx1 on tokens per min (TPM): Limit 60000, Requested 1252546. The input or output tokens must be reduced in order to run successfully. Visit https://platform.openai.com/account/rate-limits to learn more.', 'type': 'tokens', 'param': None, 'code': 'rate_limit_exceeded'}}\n",
"The graph has been successfully created and saved. You can find the graph as a file named \"x_squared_plot.png\" in the directory where you ran the script. You can open and view this file to see the plotted graph of \\(x^2\\) from -10 to 10.\n",
" user_proxy.initiate_chat(assistant_base, message=\"plot and save a graph of x^2 from -10 to 10\", clear_history=False)\n",
"except Exception as e:\n",
" print(\"Encountered an error with the base assistant\")\n",
" print(e)\n",
" print(\"\\n\\n\")\n",
"\n",
"try:\n",
" user_proxy.initiate_chat(\n",
" assistant_with_context_handling, message=\"plot and save a graph of x^2 from -10 to 10\", clear_history=False\n",
" )\n",
"except Exception as e:\n",
" print(e)"
]
},
{
"cell_type": "markdown",
"id": "5e380678-a923-43cb-91b1-f9c9e8deede2",
"metadata": {},
"source": [
"## Handling Sensitive Data\n",
"\n",
"You can use the `MessageTransform` protocol to create custom message transformations that redact sensitive data from the chat history. This is particularly useful when you want to ensure that sensitive information, such as API keys, passwords, or personal data, is not exposed in the chat history or logs.\n",
"\n",
"Now, we will create a custom message transform to detect any OpenAI API key and redact it."
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "74429344-3c0a-4057-aba3-27358fbf059c",
"metadata": {},
"outputs": [],
"source": [
"# The transform must adhere to transform_messages.MessageTransform protocol.\n",