Skip to content

Python SDK for AI agent monitoring, LLM cost tracking, benchmarking, and more. Integrates with most LLMs and agent frameworks including CrewAI, Agno, OpenAI Agents SDK, Langchain, Autogen, AG2, and CamelAI

Add groq multi agent example (#305)

Manu Suryavansh4193a9ec9eb0
diff --git a/agentops/llm_tracker.py b/agentops/llm_tracker.py
index 90fbf0cd..475c5236 100644
--- a/agentops/llm_tracker.py
+++ b/agentops/llm_tracker.py
@@ -32,6 +32,9 @@ class LlmTracker:
"5.4.0": ("chat", "chat_stream"),
},
"ollama": {"0.0.1": ("chat", "Client.chat", "AsyncClient.chat")},
+ "groq": {
+ "0.9.0": ("Client.chat", "AsyncClient.chat"),
+ },
}
def __init__(self, client):
@@ -487,6 +490,128 @@ class LlmTracker:
self._safe_record(session, self.llm_event)
return response
+ def _handle_response_groq(
+ self, response, kwargs, init_timestamp, session: Optional[Session] = None
+ ):
+ """Handle responses for OpenAI versions >v1.0.0"""
+ from groq import AsyncStream, Stream
+ from groq.resources.chat import AsyncCompletions
+ from groq.types.chat import ChatCompletionChunk
+
+ self.llm_event = LLMEvent(init_timestamp=init_timestamp, params=kwargs)
+ if session is not None:
+ self.llm_event.session_id = session.session_id
+
+ def handle_stream_chunk(chunk: ChatCompletionChunk):
+ # NOTE: prompt/completion usage not returned in response when streaming
+ # We take the first ChatCompletionChunk and accumulate the deltas from all subsequent chunks to build one full chat completion
+ if self.llm_event.returns == None:
+ self.llm_event.returns = chunk
+
+ try:
+ accumulated_delta = self.llm_event.returns.choices[0].delta
+ self.llm_event.agent_id = check_call_stack_for_agent_id()
+ self.llm_event.model = chunk.model
+ self.llm_event.prompt = kwargs["messages"]
+
+ # NOTE: We assume for completion only choices[0] is relevant
+ choice = chunk.choices[0]
+
+ if choice.delta.content:
+ accumulated_delta.content += choice.delta.content
+
+ if choice.delta.role:
+ accumulated_delta.role = choice.delta.role
+
+ if choice.delta.tool_calls:
+ accumulated_delta.tool_calls = choice.delta.tool_calls
+
+ if choice.delta.function_call:
+ accumulated_delta.function_call = choice.delta.function_call
+
+ if choice.finish_reason:
+ # Streaming is done. Record LLMEvent
+ self.llm_event.returns.choices[0].finish_reason = (
+ choice.finish_reason
+ )
+ self.llm_event.completion = {
+ "role": accumulated_delta.role,
+ "content": accumulated_delta.content,
+ "function_call": accumulated_delta.function_call,
+ "tool_calls": accumulated_delta.tool_calls,
+ }
+ self.llm_event.end_timestamp = get_ISO_time()
+
+ self._safe_record(session, self.llm_event)
+ except Exception as e:
+ self._safe_record(
+ session, ErrorEvent(trigger_event=self.llm_event, exception=e)
+ )
+
+ kwargs_str = pprint.pformat(kwargs)
+ chunk = pprint.pformat(chunk)
+ logger.warning(
+ f"Unable to parse a chunk for LLM call. Skipping upload to AgentOps\n"
+ f"chunk:\n {chunk}\n"
+ f"kwargs:\n {kwargs_str}\n"
+ )
+
+ # if the response is a generator, decorate the generator
+ if isinstance(response, Stream):
+
+ def generator():
+ for chunk in response:
+ handle_stream_chunk(chunk)
+ yield chunk
+
+ return generator()
+
+ # For asynchronous AsyncStream
+ elif isinstance(response, AsyncStream):
+
+ async def async_generator():
+ async for chunk in response:
+ handle_stream_chunk(chunk)
+ yield chunk
+
+ return async_generator()
+
+ # For async AsyncCompletion
+ elif isinstance(response, AsyncCompletions):
+
+ async def async_generator():
+ async for chunk in response:
+ handle_stream_chunk(chunk)
+ yield chunk
+
+ return async_generator()
+
+ # v1.0.0+ responses are objects
+ try:
+ self.llm_event.returns = response.model_dump()
+ self.llm_event.agent_id = check_call_stack_for_agent_id()
+ self.llm_event.prompt = kwargs["messages"]
+ self.llm_event.prompt_tokens = response.usage.prompt_tokens
+ self.llm_event.completion = response.choices[0].message.model_dump()
+ self.llm_event.completion_tokens = response.usage.completion_tokens
+ self.llm_event.model = response.model
+
+ self._safe_record(session, self.llm_event)
+ except Exception as e:
+ self._safe_record(
+ session, ErrorEvent(trigger_event=self.llm_event, exception=e)
+ )
+
+ kwargs_str = pprint.pformat(kwargs)
+ response = pprint.pformat(response)
+ logger.warning(
+ f"Unable to parse response for LLM call. Skipping upload to AgentOps\n"
+ f"response:\n {response}\n"
+ f"kwargs:\n {kwargs_str}\n"
+ )
+
+ return response
+
def override_openai_v1_completion(self):
from openai.resources.chat import completions
@@ -645,6 +770,39 @@ class LlmTracker:
# Override the original method with the patched one
AsyncClient.chat = patched_function
+ def override_groq_chat(self):
+ from groq.resources.chat import completions
+
+ original_create = completions.Completions.create
+
+ def patched_function(*args, **kwargs):
+ # Call the original function with its original arguments
+ init_timestamp = get_ISO_time()
+ session = kwargs.get("session", None)
+ if "session" in kwargs.keys():
+ del kwargs["session"]
+ result = original_create(*args, **kwargs)
+ return self._handle_response_groq(
+ result, kwargs, init_timestamp, session=session
+ )
+
+ # Override the original method with the patched one
+ completions.Completions.create = patched_function
+
+ def override_groq_chat_stream(self):
+ from groq.resources.chat import completions
+
+ original_create = completions.AsyncCompletions.create
+
+ def patched_function(*args, **kwargs):
+ # Call the original function with its original arguments
+ init_timestamp = get_ISO_time()
+ result = original_create(*args, **kwargs)
+ return self._handle_response_groq(result, kwargs, init_timestamp)
+
+ # Override the original method with the patched one
+ completions.AsyncCompletions.create = patched_function
+
def _override_method(self, api, method_path, module):
def handle_response(result, kwargs, init_timestamp):
if api == "openai":
@@ -746,6 +904,17 @@ class LlmTracker:
f"Only Ollama>=0.0.1 supported. v{module_version} found."
)
+ if api == "groq":
+ module_version = version(api)
+
+ if Version(module_version) >= parse("0.9.0"):
+ self.override_groq_chat()
+ self.override_groq_chat_stream()
+ else:
+ logger.warning(
+ f"Only Groq>=0.9.0 supported. v{module_version} found."
+ )
+
def stop_instrumenting(self):
self.undo_override_openai_v1_async_completion()
self.undo_override_openai_v1_completion()
diff --git a/examples/multi_agent_example.ipynb b/examples/multi_agent_example.ipynb
index 7749cafb..f95367c9 100644
--- a/examples/multi_agent_example.ipynb
+++ b/examples/multi_agent_example.ipynb
@@ -4,7 +4,10 @@
"cell_type": "markdown",
"id": "a2e266428cefc683",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"source": [
"# Multi-Agent Support\n",
@@ -16,7 +19,10 @@
"execution_count": null,
"id": "7c566fac57d3b6ce",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"outputs": [],
"source": [
@@ -35,7 +41,10 @@
"execution_count": null,
"id": "9f8c52496c04693",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"outputs": [],
"source": [
@@ -49,22 +58,28 @@
},
{
"cell_type": "code",
+ "execution_count": null,
+ "id": "af062552554d60ce",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
"outputs": [],
"source": [
"agentops.init(AGENTOPS_API_KEY, tags=[\"multi-agent-notebook\"])\n",
"openai_client = OpenAI(api_key=OPENAI_API_KEY)"
- ],
- "metadata": {
- "collapsed": false
- },
- "id": "af062552554d60ce",
- "execution_count": null
+ ]
},
{
"cell_type": "markdown",
"id": "95d212546aaf1f82",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"source": [
"Now lets create a few agents!"
@@ -75,7 +90,10 @@
"execution_count": null,
"id": "727e3cc26ce3ec3",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"outputs": [],
"source": [
@@ -118,7 +136,10 @@
"execution_count": null,
"id": "79b75d65de738522",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"outputs": [],
"source": [
@@ -130,7 +151,10 @@
"cell_type": "markdown",
"id": "69dd3af9206308cc",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"source": [
"Now we have our agents and we tagged them with the `@track_agent` decorator. Any LLM calls that go through this class will now be tagged as agent calls in AgentOps.\n",
@@ -138,12 +162,25 @@
"Lets use these agents!"
]
},
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "ae979350-470d-438d-a187-6dbaa0080b8c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "generated_func = engineer.completion(\"python function to test prime number\")"
+ ]
+ },
{
"cell_type": "code",
"execution_count": null,
"id": "830b86dac47dceb3",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"outputs": [],
"source": [
@@ -155,7 +192,10 @@
"execution_count": null,
"id": "63c9d0d457aee91a",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"outputs": [],
"source": [
@@ -169,7 +209,10 @@
"execution_count": null,
"id": "a88ffcbd2015d422",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"outputs": [],
"source": [
@@ -180,7 +223,10 @@
"cell_type": "markdown",
"id": "1bd312ed049a5511",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"source": [
"Perfect! It generated the code as expected, and in the DEBUG logs, you can see that the calls were made by agents named \"engineer\" and \"qa\"!"
@@ -190,7 +236,10 @@
"cell_type": "markdown",
"id": "cbd0817a31756397",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"source": [
"Lets verify one more thing! If we make an LLM call outside of the context of a tracked agent, we want to make sure it gets assigned to the Default Agent."
@@ -201,7 +250,10 @@
"execution_count": null,
"id": "122e923cb07fd5f4",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"outputs": [],
"source": [
@@ -219,7 +271,10 @@
"cell_type": "markdown",
"id": "a30909020c6a1ada",
"metadata": {
- "collapsed": false
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
},
"source": [
"You'll notice that we didn't log an agent name, so the AgentOps backend will assign it to the Default Agent for the session!"
@@ -228,21 +283,21 @@
],
"metadata": {
"kernelspec": {
- "display_name": "Python 3",
+ "display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
- "version": 2
+ "version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
- "pygments_lexer": "ipython2",
- "version": "3.12.2"
+ "pygments_lexer": "ipython3",
+ "version": "3.11.9"
}
},
"nbformat": 4,
diff --git a/examples/multi_agent_groq_example.ipynb b/examples/multi_agent_groq_example.ipynb
new file mode 100644
index 00000000..e446f493
--- /dev/null
+++ b/examples/multi_agent_groq_example.ipynb
@@ -0,0 +1,502 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "a2e266428cefc683",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "source": [
+ "# Multi-Agent Support\n",
+ "This is an example implementation of tracking events from two separate agents"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "7c566fac57d3b6ce",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [],
+ "source": [
+ "import agentops\n",
+ "from agentops.agent import track_agent\n",
+ "from dotenv import load_dotenv\n",
+ "import os\n",
+ "from groq import Groq\n",
+ "import logging\n",
+ "\n",
+ "from IPython.display import display, Markdown"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "9f8c52496c04693",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [],
+ "source": [
+ "load_dotenv()\n",
+ "GROQ_API_KEY = os.getenv(\"GROQ_API_KEY\", \"<your_openai_key>\")\n",
+ "AGENTOPS_API_KEY = os.getenv(\"AGENTOPS_API_KEY\", \"<your_agentops_key>\")\n",
+ "logging.basicConfig(\n",
+ " level=logging.DEBUG\n",
+ ") # this will let us see that calls are assigned to an agent"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "af062552554d60ce",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.agentops.ai:443\n",
+ "DEBUG:urllib3.connectionpool:https://api.agentops.ai:443 \"POST /v2/create_session HTTP/11\" 200 204\n",
+ "🖇 AgentOps: \u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=892edb44-774d-4f52-a9b8-4d4eada5b434\u001b[0m\u001b[0m\n",
+ "INFO:agentops:\u001b[34m\u001b[34mSession Replay: https://app.agentops.ai/drilldown?session_id=892edb44-774d-4f52-a9b8-4d4eada5b434\u001b[0m\u001b[0m\n",
+ "DEBUG:httpx:load_ssl_context verify=True cert=None trust_env=True http2=False\n",
+ "DEBUG:httpx:load_verify_locations cafile='/Users/manu_suryavansh/miniforge3/envs/agentsops_dev/lib/python3.11/site-packages/certifi/cacert.pem'\n",
+ "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.agentops.ai:443\n",
+ "DEBUG:urllib3.connectionpool:https://api.agentops.ai:443 \"POST /v2/create_events HTTP/11\" 200 9\n"
+ ]
+ }
+ ],
+ "source": [
+ "agentops.init(AGENTOPS_API_KEY, tags=[\"multi-agent-groq-notebook\"])\n",
+ "groq_client = Groq(api_key=GROQ_API_KEY)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "95d212546aaf1f82",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "source": [
+ "Now lets create a few agents!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "727e3cc26ce3ec3",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [],
+ "source": [
+ "@track_agent(name=\"qa\")\n",
+ "class QaAgent:\n",
+ " def completion(self, prompt: str):\n",
+ " res = groq_client.chat.completions.create(\n",
+ " model=\"llama3-70b-8192\",\n",
+ " messages=[\n",
+ " {\n",
+ " \"role\": \"system\",\n",
+ " \"content\": \"You are a qa engineer and only output python code, no markdown tags.\",\n",
+ " },\n",
+ " {\"role\": \"user\", \"content\": prompt},\n",
+ " ],\n",
+ " temperature=0.5,\n",
+ " )\n",
+ " return res.choices[0].message.content\n",
+ "\n",
+ "\n",
+ "@track_agent(name=\"engineer\")\n",
+ "class EngineerAgent:\n",
+ " def completion(self, prompt: str):\n",
+ " res = groq_client.chat.completions.create(\n",
+ " model=\"llama3-70b-8192\",\n",
+ " messages=[\n",
+ " {\n",
+ " \"role\": \"system\",\n",
+ " \"content\": \"You are a software engineer and only output python code, no markdown tags.\",\n",
+ " },\n",
+ " {\"role\": \"user\", \"content\": prompt},\n",
+ " ],\n",
+ " temperature=0.5,\n",
+ " )\n",
+ " return res.choices[0].message.content"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "79b75d65de738522",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.agentops.ai:443\n",
+ "DEBUG:urllib3.connectionpool:https://api.agentops.ai:443 \"POST /v2/create_agent HTTP/11\" 200 9\n",
+ "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.agentops.ai:443\n",
+ "DEBUG:urllib3.connectionpool:https://api.agentops.ai:443 \"POST /v2/create_agent HTTP/11\" 200 9\n"
+ ]
+ }
+ ],
+ "source": [
+ "qa = QaAgent()\n",
+ "engineer = EngineerAgent()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "69dd3af9206308cc",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "source": [
+ "Now we have our agents and we tagged them with the `@track_agent` decorator. Any LLM calls that go through this class will now be tagged as agent calls in AgentOps.\n",
+ "\n",
+ "Lets use these agents!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "7272b927-67ef-4b8c-84a5-63ed06f75aa5",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "DEBUG:groq._base_client:Request options: {'method': 'post', 'url': '/openai/v1/chat/completions', 'files': None, 'json_data': {'messages': [{'role': 'system', 'content': 'You are a software engineer and only output python code, no markdown tags.'}, {'role': 'user', 'content': 'python function to test prime number'}], 'model': 'llama3-70b-8192', 'temperature': 0.5}}\n",
+ "DEBUG:groq._base_client:Sending HTTP Request: POST https://api.groq.com/openai/v1/chat/completions\n",
+ "DEBUG:httpcore.connection:connect_tcp.started host='api.groq.com' port=443 local_address=None timeout=5.0 socket_options=None\n",
+ "DEBUG:httpcore.connection:connect_tcp.complete return_value=<httpcore._backends.sync.SyncStream object at 0x108dc1010>\n",
+ "DEBUG:httpcore.connection:start_tls.started ssl_context=<ssl.SSLContext object at 0x10a6e4d40> server_hostname='api.groq.com' timeout=5.0\n",
+ "DEBUG:httpcore.connection:start_tls.complete return_value=<httpcore._backends.sync.SyncStream object at 0x1098df650>\n",
+ "DEBUG:httpcore.http11:send_request_headers.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:send_request_headers.complete\n",
+ "DEBUG:httpcore.http11:send_request_body.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:send_request_body.complete\n",
+ "DEBUG:httpcore.http11:receive_response_headers.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Date', b'Sun, 21 Jul 2024 05:55:22 GMT'), (b'Content-Type', b'application/json'), (b'Transfer-Encoding', b'chunked'), (b'Connection', b'keep-alive'), (b'Cache-Control', b'private, max-age=0, no-store, no-cache, must-revalidate'), (b'vary', b'Origin'), (b'x-ratelimit-limit-requests', b'50000'), (b'x-ratelimit-limit-tokens', b'30000'), (b'x-ratelimit-remaining-requests', b'49999'), (b'x-ratelimit-remaining-tokens', b'29963'), (b'x-ratelimit-reset-requests', b'1.728s'), (b'x-ratelimit-reset-tokens', b'74ms'), (b'x-request-id', b'req_01j39xqscce4dbg5h08vrftym2'), (b'via', b'1.1 google'), (b'alt-svc', b'h3=\":443\"; ma=86400'), (b'CF-Cache-Status', b'DYNAMIC'), (b'Set-Cookie', b'__cf_bm=vDBNcm.4NuP7B9MJyHy7WVBS7CVF.SyvXXsf7ZXdpT8-1721541322-1.0.1.1-QRg7ZBBgC845heu3O2ZfJySw1nqhlOCwpF29NmD1H9xnMUNFOstcyHCHabYKSBZXq6iNGbkYaId01XpPYOfuWQ; path=/; expires=Sun, 21-Jul-24 06:25:22 GMT; domain=.groq.com; HttpOnly; Secure; SameSite=None'), (b'Server', b'cloudflare'), (b'CF-RAY', b'8a68f10f2ba89652-SJC'), (b'Content-Encoding', b'gzip')])\n",
+ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
+ "DEBUG:httpcore.http11:receive_response_body.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:receive_response_body.complete\n",
+ "DEBUG:httpcore.http11:response_closed.started\n",
+ "DEBUG:httpcore.http11:response_closed.complete\n",
+ "DEBUG:groq._base_client:HTTP Response: POST https://api.groq.com/openai/v1/chat/completions \"200 OK\" Headers({'date': 'Sun, 21 Jul 2024 05:55:22 GMT', 'content-type': 'application/json', 'transfer-encoding': 'chunked', 'connection': 'keep-alive', 'cache-control': 'private, max-age=0, no-store, no-cache, must-revalidate', 'vary': 'Origin', 'x-ratelimit-limit-requests': '50000', 'x-ratelimit-limit-tokens': '30000', 'x-ratelimit-remaining-requests': '49999', 'x-ratelimit-remaining-tokens': '29963', 'x-ratelimit-reset-requests': '1.728s', 'x-ratelimit-reset-tokens': '74ms', 'x-request-id': 'req_01j39xqscce4dbg5h08vrftym2', 'via': '1.1 google', 'alt-svc': 'h3=\":443\"; ma=86400', 'cf-cache-status': 'DYNAMIC', 'set-cookie': '__cf_bm=vDBNcm.4NuP7B9MJyHy7WVBS7CVF.SyvXXsf7ZXdpT8-1721541322-1.0.1.1-QRg7ZBBgC845heu3O2ZfJySw1nqhlOCwpF29NmD1H9xnMUNFOstcyHCHabYKSBZXq6iNGbkYaId01XpPYOfuWQ; path=/; expires=Sun, 21-Jul-24 06:25:22 GMT; domain=.groq.com; HttpOnly; Secure; SameSite=None', 'server': 'cloudflare', 'cf-ray': '8a68f10f2ba89652-SJC', 'content-encoding': 'gzip'})\n"
+ ]
+ }
+ ],
+ "source": [
+ "generated_func = engineer.completion(\"python function to test prime number\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "830b86dac47dceb3",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "```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",
+ "```"
+ ],
+ "text/plain": [
+ "<IPython.core.display.Markdown object>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "display(Markdown(\"```python\\n\" + generated_func + \"\\n```\"))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "63c9d0d457aee91a",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "DEBUG:groq._base_client:Request options: {'method': 'post', 'url': '/openai/v1/chat/completions', 'files': None, 'json_data': {'messages': [{'role': 'system', 'content': 'You are a qa engineer and only output python code, no markdown tags.'}, {'role': 'user', 'content': 'Write a python unit test that test the following function: \\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'}], 'model': 'llama3-70b-8192', 'temperature': 0.5}}\n",
+ "DEBUG:groq._base_client:Sending HTTP Request: POST https://api.groq.com/openai/v1/chat/completions\n",
+ "DEBUG:httpcore.http11:send_request_headers.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:send_request_headers.complete\n",
+ "DEBUG:httpcore.http11:send_request_body.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:send_request_body.complete\n",
+ "DEBUG:httpcore.http11:receive_response_headers.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Date', b'Sun, 21 Jul 2024 05:55:23 GMT'), (b'Content-Type', b'application/json'), (b'Transfer-Encoding', b'chunked'), (b'Connection', b'keep-alive'), (b'Cache-Control', b'private, max-age=0, no-store, no-cache, must-revalidate'), (b'vary', b'Origin'), (b'x-ratelimit-limit-requests', b'50000'), (b'x-ratelimit-limit-tokens', b'30000'), (b'x-ratelimit-remaining-requests', b'49998'), (b'x-ratelimit-remaining-tokens', b'29845'), (b'x-ratelimit-reset-requests', b'2.960999999s'), (b'x-ratelimit-reset-tokens', b'310ms'), (b'x-request-id', b'req_01j39xqsy5fxgth4w9q6r24h9w'), (b'via', b'1.1 google'), (b'alt-svc', b'h3=\":443\"; ma=86400'), (b'CF-Cache-Status', b'DYNAMIC'), (b'Server', b'cloudflare'), (b'CF-RAY', b'8a68f112be2c9652-SJC'), (b'Content-Encoding', b'gzip')])\n",
+ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
+ "DEBUG:httpcore.http11:receive_response_body.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:receive_response_body.complete\n",
+ "DEBUG:httpcore.http11:response_closed.started\n",
+ "DEBUG:httpcore.http11:response_closed.complete\n",
+ "DEBUG:groq._base_client:HTTP Response: POST https://api.groq.com/openai/v1/chat/completions \"200 OK\" Headers({'date': 'Sun, 21 Jul 2024 05:55:23 GMT', 'content-type': 'application/json', 'transfer-encoding': 'chunked', 'connection': 'keep-alive', 'cache-control': 'private, max-age=0, no-store, no-cache, must-revalidate', 'vary': 'Origin', 'x-ratelimit-limit-requests': '50000', 'x-ratelimit-limit-tokens': '30000', 'x-ratelimit-remaining-requests': '49998', 'x-ratelimit-remaining-tokens': '29845', 'x-ratelimit-reset-requests': '2.960999999s', 'x-ratelimit-reset-tokens': '310ms', 'x-request-id': 'req_01j39xqsy5fxgth4w9q6r24h9w', 'via': '1.1 google', 'alt-svc': 'h3=\":443\"; ma=86400', 'cf-cache-status': 'DYNAMIC', 'server': 'cloudflare', 'cf-ray': '8a68f112be2c9652-SJC', 'content-encoding': 'gzip'})\n"
+ ]
+ }
+ ],
+ "source": [
+ "generated_test = qa.completion(\n",
+ " \"Write a python unit test that test the following function: \\n \" + generated_func\n",
+ ")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "a88ffcbd2015d422",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [
+ {
+ "data": {
+ "text/markdown": [
+ "```python\n",
+ "import unittest\n",
+ "\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",
+ "class TestIsPrimeFunction(unittest.TestCase):\n",
+ " def test_negative_numbers(self):\n",
+ " self.assertFalse(is_prime(-1))\n",
+ " self.assertFalse(is_prime(-2))\n",
+ " self.assertFalse(is_prime(-3))\n",
+ "\n",
+ " def test_zero_and_one(self):\n",
+ " self.assertFalse(is_prime(0))\n",
+ " self.assertFalse(is_prime(1))\n",
+ "\n",
+ " def test_two(self):\n",
+ " self.assertTrue(is_prime(2))\n",
+ "\n",
+ " def test_even_numbers(self):\n",
+ " self.assertFalse(is_prime(4))\n",
+ " self.assertFalse(is_prime(6))\n",
+ " self.assertFalse(is_prime(8))\n",
+ "\n",
+ " def test_prime_numbers(self):\n",
+ " self.assertTrue(is_prime(3))\n",
+ " self.assertTrue(is_prime(5))\n",
+ " self.assertTrue(is_prime(7))\n",
+ " self.assertTrue(is_prime(11))\n",
+ " self.assertTrue(is_prime(13))\n",
+ "\n",
+ " def test_large_prime_numbers(self):\n",
+ " self.assertTrue(is_prime(104729))\n",
+ " self.assertTrue(is_prime(105013))\n",
+ "\n",
+ "if __name__ == '__main__':\n",
+ " unittest.main()\n",
+ "```"
+ ],
+ "text/plain": [
+ "<IPython.core.display.Markdown object>"
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ }
+ ],
+ "source": [
+ "display(Markdown(\"```python\\n\" + generated_test + \"\\n```\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1bd312ed049a5511",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "source": [
+ "Perfect! It generated the code as expected, and in the DEBUG logs, you can see that the calls were made by agents named \"engineer\" and \"qa\"!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cbd0817a31756397",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "source": [
+ "Lets verify one more thing! If we make an LLM call outside of the context of a tracked agent, we want to make sure it gets assigned to the Default Agent."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "122e923cb07fd5f4",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "DEBUG:groq._base_client:Request options: {'method': 'post', 'url': '/openai/v1/chat/completions', 'files': None, 'json_data': {'messages': [{'role': 'system', 'content': 'You are not a tracked agent'}, {'role': 'user', 'content': 'Say hello'}], 'model': 'llama3-70b-8192'}}\n",
+ "DEBUG:groq._base_client:Sending HTTP Request: POST https://api.groq.com/openai/v1/chat/completions\n",
+ "DEBUG:httpcore.http11:send_request_headers.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:send_request_headers.complete\n",
+ "DEBUG:httpcore.http11:send_request_body.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:send_request_body.complete\n",
+ "DEBUG:httpcore.http11:receive_response_headers.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Date', b'Sun, 21 Jul 2024 05:55:24 GMT'), (b'Content-Type', b'application/json'), (b'Transfer-Encoding', b'chunked'), (b'Connection', b'keep-alive'), (b'Cache-Control', b'private, max-age=0, no-store, no-cache, must-revalidate'), (b'vary', b'Origin'), (b'x-ratelimit-limit-requests', b'50000'), (b'x-ratelimit-limit-tokens', b'30000'), (b'x-ratelimit-remaining-requests', b'49998'), (b'x-ratelimit-remaining-tokens', b'29982'), (b'x-ratelimit-reset-requests', b'3.318s'), (b'x-ratelimit-reset-tokens', b'36ms'), (b'x-request-id', b'req_01j39xqvrgem4bfd3gqybths6c'), (b'via', b'1.1 google'), (b'alt-svc', b'h3=\":443\"; ma=86400'), (b'CF-Cache-Status', b'DYNAMIC'), (b'Server', b'cloudflare'), (b'CF-RAY', b'8a68f11e6dd59652-SJC'), (b'Content-Encoding', b'gzip')])\n",
+ "INFO:httpx:HTTP Request: POST https://api.groq.com/openai/v1/chat/completions \"HTTP/1.1 200 OK\"\n",
+ "DEBUG:httpcore.http11:receive_response_body.started request=<Request [b'POST']>\n",
+ "DEBUG:httpcore.http11:receive_response_body.complete\n",
+ "DEBUG:httpcore.http11:response_closed.started\n",
+ "DEBUG:httpcore.http11:response_closed.complete\n",
+ "DEBUG:groq._base_client:HTTP Response: POST https://api.groq.com/openai/v1/chat/completions \"200 OK\" Headers({'date': 'Sun, 21 Jul 2024 05:55:24 GMT', 'content-type': 'application/json', 'transfer-encoding': 'chunked', 'connection': 'keep-alive', 'cache-control': 'private, max-age=0, no-store, no-cache, must-revalidate', 'vary': 'Origin', 'x-ratelimit-limit-requests': '50000', 'x-ratelimit-limit-tokens': '30000', 'x-ratelimit-remaining-requests': '49998', 'x-ratelimit-remaining-tokens': '29982', 'x-ratelimit-reset-requests': '3.318s', 'x-ratelimit-reset-tokens': '36ms', 'x-request-id': 'req_01j39xqvrgem4bfd3gqybths6c', 'via': '1.1 google', 'alt-svc': 'h3=\":443\"; ma=86400', 'cf-cache-status': 'DYNAMIC', 'server': 'cloudflare', 'cf-ray': '8a68f11e6dd59652-SJC', 'content-encoding': 'gzip'})\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "'Hello!'"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "res = groq_client.chat.completions.create(\n",
+ " model=\"llama3-70b-8192\",\n",
+ " messages=[\n",
+ " {\"role\": \"system\", \"content\": \"You are not a tracked agent\"},\n",
+ " {\"role\": \"user\", \"content\": \"Say hello\"},\n",
+ " ],\n",
+ ")\n",
+ "res.choices[0].message.content"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a30909020c6a1ada",
+ "metadata": {
+ "collapsed": false,
+ "jupyter": {
+ "outputs_hidden": false
+ }
+ },
+ "source": [
+ "You'll notice that we didn't log an agent name, so the AgentOps backend will assign it to the Default Agent for the session!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "d7a167c1-61f3-4499-8790-ec001e361e39",
+ "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.11.9"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}