\n",
"\n",
"`Autogen` is an LLM framework developed by microsoft. It provides a variety of features that may be lacking in other frameworks such as *multi agent tasks*, *nested chats*, *code execution* and so on. It would be interesting to see how agents powered by lightning fast groq perform with such a feature rich framework. Our notebook follows this [guide](https://microsoft.github.io/autogen/0.2/docs/topics/non-openai-models/cloud-groq/)."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "114b3ac6-30fb-4e43-9c50-a7fa18bf5fcb",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"api_key = os.getenv(\"GROQ_API_KEY\")\n",
"if api_key is None:\n",
" raise ValueError(\"Groq API key environment variable not set\")"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "2bee41af-6510-44e2-875f-8c55da14aa4c",
"metadata": {},
"outputs": [],
"source": [
"config_list = [\n",
" {\n",
" \"model\": \"llama3-8b-8192\",\n",
" \"api_key\": api_key,\n",
" # \"api_type\": \"groq\", # Removed as explained here https://stackoverflow.com/a/77560277\n",
" \"base_url\": \"https://api.groq.com/openai/v1\",\n",
" # \"frequency_penalty\": 0.5,\n",
" # \"max_tokens\": 2048,\n",
" # \"presence_penalty\": 0.2,\n",
" # \"seed\": 42,\n",
" # \"temperature\": 0.5,\n",
" # \"top_p\": 0.2,\n",
" }\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "998dfb98-4253-4377-b39d-b1241f047cf0",
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"\n",
"from autogen import AssistantAgent, UserProxyAgent\n",
"from autogen.coding import LocalCommandLineCodeExecutor"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "3880db83-8514-4b2d-919f-b1c42647bb74",
"metadata": {},
"outputs": [],
"source": [
"# Setting up the code executor\n",
"workdir = Path(\"coding\")\n",
"workdir.mkdir(exist_ok=True)\n",
"code_executor = LocalCommandLineCodeExecutor(work_dir=workdir)"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "e261e35e-3c14-4d84-8710-b1726d9fe4b6",
"metadata": {},
"outputs": [],
"source": [
"# Setting up the agents\n",
"\n",
"# The UserProxyAgent will execute the code that the AssistantAgent provides\n",
"user_proxy_agent = UserProxyAgent(\n",
" name=\"User\",\n",
" code_execution_config={\"executor\": code_executor},\n",
" is_termination_msg=lambda msg: \"FINISH\" in msg.get(\"content\"),\n",
")\n",
"\n",
"system_message = \"\"\"You are a helpful AI assistant who writes code and the user executes it.\n",
"Solve tasks using your coding and language skills.\n",
"In the following cases, suggest python code (in a python coding block) for the user to execute.\n",
"Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill.\n",
"When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user.\n",
"Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.\n",
"If the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try.\n",
"When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible.\n",
"IMPORTANT: Wait for the user to execute your code and then you can reply with the word \"FINISH\". DO NOT OUTPUT \"FINISH\" after your code block.\"\"\"\n",
"\n",
"# The AssistantAgent, using Groq's model, will take the coding request and return code\n",
"assistant_agent = AssistantAgent(\n",
" name=\"Groq Assistant\",\n",
" system_message=system_message,\n",
" llm_config={\"config_list\": config_list},\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "f58a8e4c-f026-4dcb-a4f3-cd19cc716ff6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[33mUser\u001b[0m (to Groq Assistant):\n",
"\n",
"Provide code to count the number of prime numbers from 1 to 10000.\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33mGroq Assistant\u001b[0m (to User):\n",
"\n",
"Here is a Python script to count the number of prime numbers from 1 to 10000:\n",
"\n",
"```python\n",
"def is_prime(n):\n",
" if n <= 1:\n",
" return False\n",
" if n == 2:\n",
" return True\n",
" if n % 2 == 0:\n",
" return False\n",
" max_divisor = int(n**0.5) + 1\n",
" for d in range(3, max_divisor, 2):\n",
" if n % d == 0:\n",
" return False\n",
" return True\n",
"\n",
"count = 0\n",
"for num in range(1, 10001):\n",
" if is_prime(num):\n",
" count += 1\n",
"\n",
"print(\"Number of prime numbers from 1 to 10000:\", count)\n",
"```\n",
"\n",
"This script defines a helper function `is_prime` to check if a number is prime, and then iterates over the range from 1 to 10000, incrementing a counter for each prime number found. Finally, it prints the total count of prime numbers.\n",
"\n",
"--------------------------------------------------------------------------------\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Provide feedback to Groq Assistant. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: \n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[31m\n",
">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
"\u001b[31m\n",
">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
"\u001b[31m\n",
">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n",
"\u001b[33mUser\u001b[0m (to Groq Assistant):\n",
"\n",
"exitcode: 0 (execution succeeded)\n",
"Code output: Number of prime numbers from 1 to 10000: 1229\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33mGroq Assistant\u001b[0m (to User):\n",
"\n",
"FINISH\n",
"\n",
"--------------------------------------------------------------------------------\n"
]
},
{
"name": "stdin",
"output_type": "stream",
"text": [
"Provide feedback to Groq Assistant. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: exit\n"
]
}
],
"source": [
"# Start the chat, with the UserProxyAgent asking the AssistantAgent the message\n",
"chat_result = user_proxy_agent.initiate_chat(\n",
" assistant_agent,\n",
" message=\"Provide code to count the number of prime numbers from 1 to 10000.\",\n",
")"
]
},
{
"cell_type": "markdown",
"id": "a9ab2dfb-9752-4ee7-b63e-4cb267ee112b",
"metadata": {},
"source": [
"
GroQ + Autogen + Tool Use
\n",
"\n",
"We push our knowledge further by trying out function calling."
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "e607f555-8f04-4d48-b780-f63215e401a2",
"metadata": {},
"outputs": [],
"source": [
"from autogen import AssistantAgent, UserProxyAgent\n",
"from typing import Literal\n",
"from typing_extensions import Annotated\n",
"import json"
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "864c50ef-e904-40de-9d3e-f7918d70141e",
"metadata": {},
"outputs": [],
"source": [
"config_list = [\n",
" {\n",
" \"model\": \"llama3-groq-8b-8192-tool-use-preview\",\n",
" \"base_url\": \"https://api.groq.com/openai/v1\",\n",
" \"api_key\": api_key,\n",
" }\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "e9ee73b2-7a10-4381-8e9d-9e060226f840",
"metadata": {},
"outputs": [],
"source": [
"# Create the agent for tool calling\n",
"chatbot = AssistantAgent(\n",
" name=\"chatbot\",\n",
" system_message=\"\"\"For currency exchange and weather forecasting tasks,\n",
" only use the functions you have been provided with.\n",
" Output 'HAVE FUN!' when an answer has been provided.\"\"\",\n",
" llm_config={\"config_list\": config_list},\n",
")\n",
"\n",
"# Note that we have changed the termination string to be \"HAVE FUN!\"\n",
"user_proxy = UserProxyAgent(\n",
" name=\"user_proxy\",\n",
" is_termination_msg=lambda x: x.get(\"content\", \"\") and \"HAVE FUN!\" in x.get(\"content\", \"\"),\n",
" human_input_mode=\"NEVER\",\n",
" max_consecutive_auto_reply=1,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 36,
"id": "20887c70-d084-4cb3-b920-d1217fd78a48",
"metadata": {},
"outputs": [],
"source": [
"# Currency Exchange function\n",
"\n",
"CurrencySymbol = Literal[\"USD\", \"EUR\"]\n",
"\n",
"# Define our function that we expect to call\n",
"\n",
"\n",
"def exchange_rate(base_currency: CurrencySymbol, quote_currency: CurrencySymbol) -> float:\n",
" if base_currency == quote_currency:\n",
" return 1.0\n",
" elif base_currency == \"USD\" and quote_currency == \"EUR\":\n",
" return 1 / 1.1\n",
" elif base_currency == \"EUR\" and quote_currency == \"USD\":\n",
" return 1.1\n",
" else:\n",
" raise ValueError(f\"Unknown currencies {base_currency}, {quote_currency}\")\n",
"\n",
"\n",
"# Register the function with the agent\n",
"\n",
"\n",
"@user_proxy.register_for_execution()\n",
"@chatbot.register_for_llm(description=\"Currency exchange calculator.\")\n",
"def currency_calculator(\n",
" base_amount: Annotated[float, \"Amount of currency in base_currency\"],\n",
" base_currency: Annotated[CurrencySymbol, \"Base currency\"] = \"USD\",\n",
" quote_currency: Annotated[CurrencySymbol, \"Quote currency\"] = \"EUR\",\n",
") -> str:\n",
" quote_amount = exchange_rate(base_currency, quote_currency) * base_amount\n",
" return f\"{format(quote_amount, '.2f')} {quote_currency}\"\n",
"\n",
"\n",
"# Weather function\n",
"\n",
"\n",
"# Example function to make available to model\n",
"def get_current_weather(location, unit=\"fahrenheit\"):\n",
" \"\"\"Get the weather for some location\"\"\"\n",
" if \"chicago\" in location.lower():\n",
" return json.dumps({\"location\": \"Chicago\", \"temperature\": \"13\", \"unit\": unit})\n",
" elif \"san francisco\" in location.lower():\n",
" return json.dumps({\"location\": \"San Francisco\", \"temperature\": \"55\", \"unit\": unit})\n",
" elif \"new york\" in location.lower():\n",
" return json.dumps({\"location\": \"New York\", \"temperature\": \"11\", \"unit\": unit})\n",
" else:\n",
" return json.dumps({\"location\": location, \"temperature\": \"unknown\"})\n",
"\n",
"\n",
"# Register the function with the agent\n",
"\n",
"\n",
"@user_proxy.register_for_execution()\n",
"@chatbot.register_for_llm(description=\"Weather forecast for US cities.\")\n",
"def weather_forecast(\n",
" location: Annotated[str, \"City name\"],\n",
") -> str:\n",
" weather_details = get_current_weather(location=location)\n",
" weather = json.loads(weather_details)\n",
" return f\"{weather['location']} will be {weather['temperature']} degrees {weather['unit']}\""
]
},
{
"cell_type": "code",
"execution_count": 37,
"id": "6751d8fe-f0b2-49c8-8fa2-2ba10ccfcd4e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
"\n",
"What's the weather in New York and can you tell me how much is 123.45 EUR in USD so I can spend it on my holiday? Throw a few holiday tips in as well.\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
"\n",
"\u001b[32m***** Suggested tool call (call_fxry): weather_forecast *****\u001b[0m\n",
"Arguments: \n",
"{\"location\": \"New York\"}\n",
"\u001b[32m*************************************************************\u001b[0m\n",
"\u001b[32m***** Suggested tool call (call_6xgr): currency_calculator *****\u001b[0m\n",
"Arguments: \n",
"{\"base_amount\": 123.45, \"base_currency\": \"EUR\", \"quote_currency\": \"USD\"}\n",
"\u001b[32m****************************************************************\u001b[0m\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[35m\n",
">>>>>>>> EXECUTING FUNCTION weather_forecast...\u001b[0m\n",
"\u001b[35m\n",
">>>>>>>> EXECUTING FUNCTION currency_calculator...\u001b[0m\n",
"\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
"\n",
"\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
"\n",
"\u001b[32m***** Response from calling tool (call_fxry) *****\u001b[0m\n",
"New York will be 11 degrees fahrenheit\n",
"\u001b[32m**************************************************\u001b[0m\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
"\n",
"\u001b[32m***** Response from calling tool (call_6xgr) *****\u001b[0m\n",
"135.80 USD\n",
"\u001b[32m**************************************************\u001b[0m\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
"\n",
"\u001b[32m***** Suggested tool call (call_ydzn): weather_forecast *****\u001b[0m\n",
"Arguments: \n",
"{\"location\":\"New York\"}\n",
"\u001b[32m*************************************************************\u001b[0m\n",
"\n",
"--------------------------------------------------------------------------------\n"
]
},
{
"ename": "TypeError",
"evalue": "string indices must be integers",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[37], line 8\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;66;03m# start the conversation\u001b[39;00m\n\u001b[1;32m 2\u001b[0m res \u001b[38;5;241m=\u001b[39m user_proxy\u001b[38;5;241m.\u001b[39minitiate_chat(\n\u001b[1;32m 3\u001b[0m chatbot,\n\u001b[1;32m 4\u001b[0m message\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mWhat\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124ms the weather in New York and can you tell me how much is 123.45 EUR in USD so I can spend it on my holiday? Throw a few holiday tips in as well.\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m 5\u001b[0m summary_method\u001b[38;5;241m=\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mreflection_with_llm\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m 6\u001b[0m )\n\u001b[0;32m----> 8\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mLLM SUMMARY: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[43mres\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msummary\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mcontent\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m]\u001b[49m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
"\u001b[0;31mTypeError\u001b[0m: string indices must be integers"
]
}
],
"source": [
"# start the conversation\n",
"res = user_proxy.initiate_chat(\n",
" chatbot,\n",
" message=\"What's the weather in New York and can you tell me how much is 123.45 EUR in USD so I can spend it on my holiday? Throw a few holiday tips in as well.\",\n",
" summary_method=\"reflection_with_llm\",\n",
")\n",
"\n",
"print(f\"LLM SUMMARY: {res.summary['content']}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "35883ac7-0fb4-44c1-b0a6-8e6f626a8366",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
}
},
"nbformat": 4,
"nbformat_minor": 5
}