Skip to content

Commit de5694e

Browse files
committed
AI Agent example
1 parent 76b27e3 commit de5694e

File tree

2 files changed

+62
-40
lines changed

2 files changed

+62
-40
lines changed

examples/ai_agent/AddObservabilityToAIAgent.md

Lines changed: 62 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,33 @@
1-
# Add OpenTelemetry Observability to an AI Agent
1+
# Add OpenTelemetry Observability to AI Agent
22

3-
This example shows how to add OpenTelemetry observability to an AI Agent. Observability enables monitoring of the requests sent to the agent, which can help with troubleshooting and optimization. In this example, [OpenTelemetry](https://opentelemetry.io/) is used to capture telemetry data including traces and metrics. OpenTelemetry is an open\-source observability framework that provides a standard way to generate, collect, and export telemetry data without vendor lock\-in.
3+
This example shows how to add OpenTelemetry observability to an AI Agent.
44

5-
The original example being instrumented is taken from the[ "Solve Simple Math Problem Using AI Agent"](https://github.com/matlab-deep-learning/llms-with-matlab/blob/main/examples/SolveSimpleMathProblemUsingAIAgent.md) example in the ["Large Language Models (LLMs) with MATLAB"](https://github.com/matlab-deep-learning/llms-with-matlab) package. It shows how to build an AI agent to find the smallest root of a quadratic equation.
5+
*AI agents* are programs that autonomously plan and execute workflows. Typically, agents use large language models (LLMs) to process user queries and identify actions that need to be taken, also known as *tool calls*. The agent then executes the tool calls that the LLM has identified and returns the result to the LLM. Then, the LLM generates an answer or executes more tool calls.
66

7-
AI agents are programs that autonomously plan and execute workflows. Typically, agents use large language models (LLMs) to process user queries and identify actions that need to be taken, also known as *tool calls*. The agent then executes the tool calls that the LLM has identified and returns the result to the LLM. Then, the LLM generates an answer or executes more tool calls.
7+
This agent in this example is based on the [Solve Simple Math Problem Using AI Agent](https://github.com/matlab-deep-learning/llms-with-matlab/blob/main/examples/SolveSimpleMathProblemUsingAIAgent.md) example in the [Large Language Models (LLMs) with MATLAB](https://github.com/matlab-deep-learning/llms-with-matlab) add\-on. The agent finds the smallest root of a quadratic equation.
88

9-
The following is a trace that shows the workflow in this example. For more information about tracing, see this[ introduction](https://opentelemetry.io/docs/concepts/signals/traces/) in the OpenTelemetry website.
9+
*Observability* lets you monitor the requests sent to the agent, which can help with troubleshooting and optimization. This example uses [OpenTelemetry](https://opentelemetry.io/) to capture telemetry data including traces and metrics. OpenTelemetry is an open\-source observability framework that provides a standardized way to generate, collect, and export telemetry data.
1010

11-
![image_0.png](AddObservabilityToAIAgent_media/image_0.png)
11+
This image shows a trace of the workflow in this example. For more information about tracing, see this[ introduction](https://opentelemetry.io/docs/concepts/signals/traces/) in the OpenTelemetry website.
12+
13+
![image_0.png](./AddObservabilityToAIAgent_media/image_0.png)
1214

1315
*Screenshot taken from Jaeger. Used with permission from the Jaeger project. This way to* [*jaegertracing.io*](https://www.jaegertracing.io)*.*
1416

1517
# Prerequisites
1618

17-
This example requires the following add\-on packages to be installed in MATLAB. Use the Add\-on Explorer to download and install them.
19+
This example uses these add\-ons:
1820

19-
- [Large Language Models (LLMs) with MATLAB](https://github.com/matlab-deep-learning/llms-with-matlab)
20-
- [MATLAB Interface to OpenTelemetry](https://github.com/mathworks/OpenTelemetry-MATLAB)
21+
- Large Language Models (LLMs) with MATLAB
22+
- MATLAB Interface to OpenTelemetry
2123

22-
In addition, the following softwares are necessary to collect the generated telemetry data.
24+
Download and install the add\-ons by using the Add\-on Explorer.
2325

24-
- [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/)
25-
- A tracing backend. For example, Jaeger ([https://www.jaegertracing.io/](https://www.jaegertracing.io/))
26-
- A metrics backend. For example, Prometheus [(https://prometheus.io/](http://(https//prometheus.io/))
26+
In addition, the example uses these external code packages:
2727

28-
The OpenTelemetry Collector is a component that uses configurable pipelines to ingest telemetry data in different formats, transform it, and send it to one or more backends. It decouples the instrumented applications from the backends and therefore enables changes to how the telemetry data is processed and where it is sent to without modifying application code. It also handles the complexities of data transmission across networks and retry logic. For details about how to configure the OpenTelemetry Collector, see the documentation at [https://opentelemetry.io/docs/collector/configuration/](https://opentelemetry.io/docs/collector/configuration/).
28+
- [OpenTelemetry Collector](https://opentelemetry.io/docs/collector/). OpenTelemetry Collector is a component that uses configurable pipelines to ingest telemetry data in different formats, transform it, and send it to one or more backends. It decouples the instrumented applications from the backends and therefore enables changes to how the telemetry data is processed and where it is sent to without modifying application code. It also handles the complexities of data transmission across networks and retry logic. For details about how to configure the OpenTelemetry Collector, see the documentation at [https://opentelemetry.io/docs/collector/configuration/](https://opentelemetry.io/docs/collector/configuration/).
29+
- A tracing backend. For example, Jaeger ([https://www.jaegertracing.io/](https://www.jaegertracing.io/)).
30+
- A metrics backend. For example, Prometheus [(https://prometheus.io/](http://(https//prometheus.io/)).
2931

3032
Before proceeding, check both required add\-on packages are installed.
3133

@@ -35,7 +37,9 @@ checkRequiredPackages
3537

3638
# Initialize OpenTelemetry
3739

38-
OpenTelemetry needs to be initialized and configured before it can be used. This needs to be done only once in a MATLAB session. The following initialization code sets the service name as an attribute. Otherwise, it uses default configurations.
40+
First, initialize and configure OpenTelemetry. You only need to do this once during your MATLAB® session.
41+
42+
The following initialization code sets the service name as an attribute. Otherwise, it uses default configurations.
3943

4044
```matlab
4145
function initializeOTel
@@ -56,9 +60,9 @@ runOnce(@initializeOTel);
5660

5761
This example uses the OpenAI® API, which requires an OpenAI API key. For information on how to obtain an OpenAI API key, as well as pricing, terms and conditions of use, and information about available models, see the OpenAI documentation at [https://platform.openai.com/docs/overview](https://platform.openai.com/docs/overview).
5862

59-
To connect to the OpenAI API from MATLAB® using LLMs with MATLAB, specify the OpenAI API key as an environment variable and save it to a file called ".env".
63+
To connect to the OpenAI API from MATLAB using LLMs with MATLAB, specify the OpenAI API key as an environment variable and save it to a file called ".env".
6064

61-
![image_1.png](AddObservabilityToAIAgent_media/image_1.png)
65+
![image_1.png](./AddObservabilityToAIAgent_media/image_1.png)
6266

6367
To connect to OpenAI, the ".env" file must be on the search path. Load the environment file using the [`loadenv`](https://www.mathworks.com/help/matlab/ref/loadenv.html) function.
6468

@@ -68,7 +72,7 @@ loadenv(".env")
6872

6973
# Capture Details of LLM Interactions
7074

71-
To build observability into AI Agent workflow, capture inputs, outputs, properties, and metadata of interactions with the OpenAI LLM. Start an OpenTelemetry span for each interaction, and then record LLM inputs, outputs and other data as attributes of the span. OpenTelemetry metrics can be used to aggregate quantities across multiple calls to the LLM, such as the total number of LLM calls and the total number of tokens.
75+
To build observability into an AI Agent workflow, capture inputs, outputs, properties, and metadata of interactions with the LLM. Start an OpenTelemetry span for each interaction, and then record LLM inputs, outputs and other data as attributes of the span. OpenTelemetry metrics can be used to aggregate quantities across multiple calls to the LLM, such as the total number of LLM calls and the total number of tokens.
7276

7377
## Query Pricing
7478

@@ -98,7 +102,7 @@ end
98102

99103
## Capture Details of Agent Creation
100104

101-
At agent creation, it is useful to record agent name and description, the underlying LLM model and any system prompt sent to the LLM.
105+
When you create the agent, record the agent name and description, the underlying LLM model, as well as any system prompt sent to the LLM.
102106

103107
```matlab
104108
function llm = createAgent(modelName, systemPrompt, tools)
@@ -108,7 +112,7 @@ function llm = createAgent(modelName, systemPrompt, tools)
108112
scopeCreateAgent = makeCurrent(spCreateAgent);
109113
110114
111-
llm = openAIChat(systemPrompt,ModelName=modelName, Tools=tools);
115+
llm = openAIChat(systemPrompt, ModelName=modelName, Tools=tools);
112116
113117
114118
% Capture OpenTelemetry span attributes related to the chat
@@ -128,17 +132,17 @@ end
128132

129133
## Capture Details of Agent Requests
130134

131-
For each LLM request, record the request input and output, the number of tokens, the associated costs, and the tools defined. Other properties including response ID and status, hyperparameters such as temperature, Top P, and stop sequences are also useful. For aggregated quantities such as total requests, tokens and costs, define metric instruments for tracking them.
135+
For each LLM request, record the request input and output, the number of tokens, the associated costs, and the defined tools. You can also record other properties including response ID and status, hyperparameters such as temperature, Top P, and stop sequences. To track aggregated quantities such as total requests, tokens and costs, define metric instruments.
132136

133137
```matlab
134-
function [thought,completeOutput] = invokeAgent(llm, history,toolChoice, tools, inputRate, outputRate)
138+
function [thought, completeOutput] = invokeAgent(llm, history, toolChoice, tools, inputRate, outputRate)
135139
% Start OpenTelemetry span
136140
trInvokeAgent = opentelemetry.trace.getTracer("AddObservabilityToAIAgent");
137141
spInvokeAgent = startSpan(trInvokeAgent, "invokeAgent");
138142
scopeInvokeAgent = makeCurrent(spInvokeAgent);
139143
140144
141-
[thought,completeOutput,response] = generate(llm,history,ToolChoice=toolChoice);
145+
[thought, completeOutput, response] = generate(llm, history, ToolChoice=toolChoice);
142146
143147
144148
% Capture OpenTelemetry span attributes related to the response
@@ -248,38 +252,43 @@ function [observation, argValues] = executeTool(toolCall,toolRegistry)
248252
end
249253
```
250254

251-
# Solve Math Problem
255+
# Run Agent
252256

253-
After the code is instrumented, proceed to start the agent. First, start a top\-level OpenTelemetry span to track the entire workflow.
257+
After you instrumented the code, start the agent. First, start a top\-level OpenTelemetry span to track the entire workflow.
254258

255259
```matlab
256260
tr = opentelemetry.trace.getTracer("AddObservabilityToAIAgent");
257261
sp = startSpan(tr, "AddObservabilityToAIAgent");
258262
scope = makeCurrent(sp);
259263
```
260264

261-
Create a tool registry, which is passed to the agent to define what tools it can use.
265+
Create a tool registry using the `registerToolRegistry` function, which is defined at the bottom of this example. In this example, the tools include a function to solve a quadratic equation, as well as a function to determine the smallest real number of a list of two arbitrary numbers.
262266

263267
```matlab
264268
toolRegistry = registerToolRegistry;
265269
```
266270

267-
Define the query to solve a simple math problem. Answer the query using the agent.
271+
Define the query to solve a simple math problem.
268272

269273
```matlab
270274
userQuery = "What is the smallest root of x^2+2x-3=0?";
275+
```
276+
277+
Answer the query using the agent. Pass the tool registry to the agent to define what tools it can use.
278+
279+
```matlab
271280
agentResponse = runReActAgent(userQuery,toolRegistry);
272281
```
273282

274283
```matlabTextOutput
275284
User: What is the smallest root of x^2+2x-3=0?
276-
[Thought] I will solve the quadratic equation x^2 + 2x - 3 = 0 to find its roots. Then I will determine the smallest root.
285+
[Thought] I will find the roots of the quadratic equation x^2 + 2x - 3 = 0.
277286
[Action] Calling tool 'solveQuadraticEquation' with args: "{\"a\":1,\"b\":2,\"c\":-3}"
278287
[Observation] Result from tool 'solveQuadraticEquation': ["-3","1"]
279-
[Thought] I will determine the smallest real number from the roots -3 and 1.
288+
[Thought] I will determine the smallest root from the roots -3 and 1.
280289
[Action] Calling tool 'smallestRealNumber' with args: "{\"x1\":\"-3\",\"x2\":\"1\"}"
281290
[Observation] Result from tool 'smallestRealNumber': -3
282-
[Thought] I will provide the final answer, which is the smallest root -3.
291+
[Thought] I will return the smallest root, which is -3, as the final answer.
283292
```
284293

285294
End the top\-level OpenTelemetry span and clear its scope. In functions, spans end implicitly at the end of the functions when the span variables run out of scope. In scripts, spans have to be ended explicitly.
@@ -301,17 +310,22 @@ The smallest root of the equation x^2 + 2x - 3 = 0 is -3.
301310

302311
# Visualize Trace
303312

304-
Visualize the generated trace in your tracing backend. For example, the following shows the trace in Jaeger. It shows every request sent to the LLM, every tool call, the order they happen, and the time they take. For every LLM request, it also shows the input and output, the hyperparameters used, the number of input and output tokens, and the costs incurred.
313+
Visualize the generated trace in your tracing backend. For example, the following images show the trace in Jaeger.
305314

306-
![image_2.png](AddObservabilityToAIAgent_media/image_2.png)
315+
The images show every request sent to the LLM, every tool call, the order they happen, and the time they take. For every LLM request, they also show the input and output, the hyperparameters used, the number of input and output tokens, and the costs incurred.
307316

308-
![image_3.png](AddObservabilityToAIAgent_media/image_3.png)
317+
![image_2.png](./AddObservabilityToAIAgent_media/image_2.png)
318+
319+
![image_3.png](./AddObservabilityToAIAgent_media/image_3.png)
309320

310321
*Screenshots taken from Jaeger. Used with permission from the Jaeger project. This way to* [*jaegertracing.io*](https://www.jaegertracing.io)*.*
311322

312-
# Helper Functions
323+
# Supporting Functions
313324

314325
## Check Required Packages
326+
327+
The `checkRequiredPackages` function checks both required add\-on packages are installed.
328+
315329
```matlab
316330
function checkRequiredPackages
317331
installed = matlab.addons.installedAddons;
@@ -411,7 +425,7 @@ end
411425

412426
## Validate Tool Calls
413427

414-
The validateToolCall function validates tool calls identified by the LLM. LLMs can hallucinate tool calls or make errors about the parameters that the tools need. Therefore, validate the tool name and parameters by comparing them to the `toolRegistry` dictionary.
428+
The `validateToolCall` function validates tool calls identified by the LLM. LLMs can hallucinate tool calls or make errors about the parameters that the tools need. Therefore, validate the tool name and parameters by comparing them to the `toolRegistry` dictionary.
415429

416430
```matlab
417431
function argValues = validateToolCall(toolCall,toolRegistry)
@@ -446,7 +460,10 @@ argValues = arrayfun(@(fieldName) args.(fieldName),requiredArgs,UniformOutput=fa
446460
end
447461
```
448462

449-
## Tool for Computing Roots of Second\-Order Polynomial
463+
## Tool 1: Solve Quadratic Equation
464+
465+
The `solveQuadraticEquation` function computes the roots of a second\-order polynomial.
466+
450467
```matlab
451468
function strR = solveQuadraticEquation(a,b,c)
452469
% Start OpenTelemetry span
@@ -460,7 +477,10 @@ strR = string(r);
460477
end
461478
```
462479

463-
## Tool for Finding Smallest Real Number
480+
## Tool 2: Determine Smallest Real Number
481+
482+
The `smallestRealNumber` function computes the smallest real number from a list of two arbitrary numbers.
483+
464484
```matlab
465485
function xMin = smallestRealNumber(strX1,strX2)
466486
% Start OpenTelemetry span
@@ -516,7 +536,7 @@ end
516536

517537
## Run Once
518538

519-
Helper to ensure the input function is only run once.
539+
The `runOnce` function ensures the input function is only run once. This allows you to rerun the script multiple times without re\-initializing OpenTelemetry.
520540

521541
```matlab
522542
function runOnce(fh)
@@ -529,5 +549,7 @@ end
529549
```
530550

531551
# References
532-
<a id="M_4aeb"></a>
533-
\[1\] Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. "ReAct: Synergizing Reasoning and Acting in Language Models". ArXiv, 10 March 2023. [https://doi.org/10.48550/arXiv.2210.03629](https://doi.org/10.48550/arXiv.2210.03629).
552+
553+
\[1\] Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. "ReAct: Synergizing Reasoning and Acting in Language Models". ArXiv, 10 March 2023. [https://doi.org/10.48550/arXiv.2210.03629.](https://doi.org/10.48550/arXiv.2210.03629.)
554+
555+
*Copyright 2026 The MathWorks, Inc.*
99 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)