Skip to content

Commit 1c02ad4

Browse files
authored
Merge pull request #7064 from diberry/diberry/0912-ai-agents-quickstart
Agents TS quickstart - simplier, math question
2 parents ae651f1 + d9499c9 commit 1c02ad4

File tree

2 files changed

+78
-190
lines changed

2 files changed

+78
-190
lines changed

.openpublishing.publish.config.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,12 @@
5050
"branch": "master",
5151
"branch_mapping": {}
5252
},
53+
{
54+
"path_to_root": "azure-sdk-for-js-docs",
55+
"url": "https://github.com/Azure-samples/azure-sdk-for-js-docs",
56+
"branch": "main",
57+
"branch_mapping": {}
58+
},
5359
{
5460
"path_to_root": "samples-luis",
5561
"url": "https://github.com/Azure-Samples/cognitive-services-language-understanding",

articles/ai-foundry/agents/includes/quickstart-typescript.md

Lines changed: 72 additions & 190 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ ms.author: aahi
55
ms.service: azure-ai-foundry
66
ms.subservice: azure-ai-foundry-agent-service
77
ms.topic: include
8-
ms.date: 07/16/2025
8+
ms.date: 09/12/2025
99
ms.custom: devx-track-ts
1010
---
1111

@@ -15,27 +15,26 @@ ms.custom: devx-track-ts
1515
## Prerequisites
1616

1717
[!INCLUDE [universal-prerequisites](universal-prerequisites.md)]
18-
19-
18+
* [Node.js LTS](https://nodejs.org/)
2019

2120
## Configure and run an agent
2221

2322
Key objects in this code include:
2423

2524
* [AgentsClient](/javascript/api/@azure/ai-agents/agentsclient)
26-
* [ToolUtility](/javascript/api/@azure/ai-agents/toolutility)
2725

28-
First, initialize a new project by running:
26+
First, initialize a new TypeScript project by running:
2927

3028
```console
3129
npm init -y
30+
npm pkg set type="module"
3231
```
3332

3433
Run the following commands to install the npm packages required.
3534

3635
```console
3736
npm install @azure/ai-agents @azure/identity
38-
npm install dotenv
37+
npm install @types/node typescript --save-dev
3938
```
4039

4140
Next, to authenticate your API requests and run the program, use the [az login](/cli/azure/authenticate-azure-cli-interactively) command to sign into your Azure subscription.
@@ -44,7 +43,7 @@ Next, to authenticate your API requests and run the program, use the [az login](
4443
az login
4544
```
4645

47-
Use the following code to create and run an agent which uploads [a CSV file](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/ai/ai-agents/data/syntheticCompanyQuarterlyResults.csv) of data then generates a bar chart from that data. To run this code, you'll need to get the endpoint for your project. This string is in the format:
46+
Use the following code to answer the math question `I need to solve the equation '3x + 11 = 14'. Can you help me?`. To run this code, you'll need to get the endpoint for your project. This string is in the format:
4847

4948
`https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>`
5049

@@ -60,190 +59,73 @@ Save the name of your model deployment name as an environment variable named `MO
6059
> * This quickstart code uses environment variables for sensitive configuration. Never commit your `.env` file to version control by making sure `.env` is listed in your `.gitignore` file.
6160
> * _Remember: If you accidentally commit sensitive information, consider those credentials compromised and rotate them immediately._
6261
62+
Create a tsconfig.json file with the following content:
63+
64+
:::code language="json" source="~/azure-sdk-for-js-docs/samples/foundry/azure-ai-agents-quickstart-math/tsconfig.json":::
65+
66+
Next, create an `index.ts` file and paste in the following code:
67+
68+
:::code language="typescript" source="~/azure-sdk-for-js-docs/samples/foundry/azure-ai-agents-quickstart-math/index.ts":::
69+
70+
Run the code using `npx tsx -r dotenv/config index.ts`. This code answers the question `I need to solve the equation '3x + 11 = 14'. Can you help me?`. Responses aren't deterministic, your output will look similar to the below output:
71+
72+
```console
73+
Created agent, agent ID : asst_X4yDNWrdWKb8LN0SQ6xlzhWk
74+
Created thread, thread ID : thread_TxqZcHL2BqkNWl9dFzBYMIU6
75+
Threads for agent asst_X4yDNWrdWKb8LN0SQ6xlzhWk:
76+
...
77+
Created message, message ID : msg_R0zDsXdc2UbfsNXvS1zeS6hk
78+
Creating run...
79+
Received response with status: queued
80+
Received response with status: in_progress
81+
Received response with status: completed
82+
Run finished with status: completed
83+
84+
85+
========================================================
86+
=================== CONVERSATION RESULTS ===================
87+
========================================================
88+
89+
90+
❓ USER QUESTION: I need to solve the equation `3x + 11 = 14`. Can you help me?
91+
92+
🤖 ASSISTANT'S ANSWER:
93+
--------------------------------------------------
94+
Certainly! Let's solve the equation step by step:
95+
96+
We have:
97+
3x + 11 = 14
98+
99+
### Step 1: Eliminate the constant (+11) on the left-hand side.
100+
Subtract 11 from both sides:
101+
3x + 11 - 11 = 14 - 11
102+
This simplifies to:
103+
3x = 3
104+
105+
We have:
106+
3x + 11 = 14
107+
108+
### Step 1: Eliminate the constant (+11) on the left-hand side.
109+
Subtract 11 from both sides:
110+
3x + 11 - 11 = 14 - 11
111+
This simplifies to:
112+
3x = 3
113+
114+
### Step 2: Solve for x.
115+
Divide both sides by 3:
116+
3x / 3 = 3 / 3
117+
This simplifies to:
118+
x = 1
119+
120+
### Final Answer:
121+
x = 1
122+
--------------------------------------------------
123+
63124

64-
Next, create an `index.js` file and paste in the following code:
65-
66-
```typescript
67-
// Copyright (c) Microsoft Corporation.
68-
// Licensed under the MIT License.
69-
70-
/**
71-
* This sample demonstrates how to use agent operations with code interpreter from the Azure Agents service.
72-
*
73-
* @summary demonstrates how to use agent operations with code interpreter.
74-
*/
75-
// @ts-nocheck
76-
import type {
77-
MessageDeltaChunk,
78-
MessageDeltaTextContent,
79-
MessageImageFileContent,
80-
MessageTextContent,
81-
ThreadRun,
82-
} from "@azure/ai-agents";
83-
import {
84-
RunStreamEvent,
85-
MessageStreamEvent,
86-
DoneEvent,
87-
ErrorEvent,
88-
AgentsClient,
89-
isOutputOfType,
90-
ToolUtility,
91-
} from "@azure/ai-agents";
92-
import { DefaultAzureCredential } from "@azure/identity";
93-
94-
import * as fs from "fs";
95-
import path from "node:path";
96-
import "dotenv/config";
97-
98-
const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project endpoint>";
99-
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";
100-
101-
export async function main(): Promise<void> {
102-
// Create an Azure AI Client
103-
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());
104-
105-
// Upload file and wait for it to be processed
106-
const filePath = "./data/nifty500QuarterlyResults.csv";
107-
const localFileStream = fs.createReadStream(filePath);
108-
const localFile = await client.files.upload(localFileStream, "assistants", {
109-
fileName: "myLocalFile",
110-
});
111-
112-
console.log(`Uploaded local file, file ID : ${localFile.id}`);
113-
114-
// Create code interpreter tool
115-
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool([localFile.id]);
116-
117-
// Notice that CodeInterpreter must be enabled in the agent creation, otherwise the agent will not be able to see the file attachment
118-
const agent = await client.createAgent(modelDeploymentName, {
119-
name: "my-agent",
120-
instructions: "You are a helpful agent",
121-
tools: [codeInterpreterTool.definition],
122-
toolResources: codeInterpreterTool.resources,
123-
});
124-
console.log(`Created agent, agent ID: ${agent.id}`);
125-
126-
// Create a thread
127-
const thread = await client.threads.create();
128-
console.log(`Created thread, thread ID: ${thread.id}`);
129-
130-
// Create a message
131-
const message = await client.messages.create(
132-
thread.id,
133-
"user",
134-
"Could you please create a bar chart in the TRANSPORTATION sector for the operating profit from the uploaded CSV file and provide the file to me?",
135-
);
136-
137-
console.log(`Created message, message ID: ${message.id}`);
138-
139-
// Create and execute a run
140-
const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();
141-
142-
for await (const eventMessage of streamEventMessages) {
143-
switch (eventMessage.event) {
144-
case RunStreamEvent.ThreadRunCreated:
145-
console.log(`ThreadRun status: ${(eventMessage.data as ThreadRun).status}`);
146-
break;
147-
case MessageStreamEvent.ThreadMessageDelta:
148-
{
149-
const messageDelta = eventMessage.data as MessageDeltaChunk;
150-
messageDelta.delta.content.forEach((contentPart) => {
151-
if (contentPart.type === "text") {
152-
const textContent = contentPart as MessageDeltaTextContent;
153-
const textValue = textContent.text?.value || "No text";
154-
console.log(`Text delta received:: ${textValue}`);
155-
}
156-
});
157-
}
158-
break;
159-
160-
case RunStreamEvent.ThreadRunCompleted:
161-
console.log("Thread Run Completed");
162-
break;
163-
case ErrorEvent.Error:
164-
console.log(`An error occurred. Data ${eventMessage.data}`);
165-
break;
166-
case DoneEvent.Done:
167-
console.log("Stream completed.");
168-
break;
169-
}
170-
}
171-
172-
// Delete the original file from the agent to free up space (note: this does not delete your version of the file)
173-
await client.files.delete(localFile.id);
174-
console.log(`Deleted file, file ID : ${localFile.id}`);
175-
176-
// Print the messages from the agent
177-
const messagesIterator = client.messages.list(thread.id);
178-
const messagesArray = [];
179-
for await (const m of messagesIterator) {
180-
messagesArray.push(m);
181-
}
182-
console.log("Messages:", messagesArray);
183-
184-
// Get most recent message from the assistant
185-
// Get most recent message from the assistant
186-
const assistantMessage = messagesArray.find((msg) => msg.role === "assistant");
187-
if (assistantMessage) {
188-
// Look for an image file in the assistant's message
189-
const imageFileOutput = assistantMessage.content.find(content =>
190-
content.type === "image_file" && content.imageFile?.fileId);
191-
192-
if (imageFileOutput) {
193-
try {
194-
// Save the newly created file
195-
console.log(`Saving new files...`);
196-
const imageFile = imageFileOutput.imageFile.fileId;
197-
const imageFileName = path.resolve(
198-
"./data/" + (await client.files.get(imageFile)).filename + "ImageFile.png",
199-
);
200-
console.log(`Image file name : ${imageFileName}`);
201-
202-
const fileContent = await client.files.getContent(imageFile).asNodeStream();
203-
if (fileContent && fileContent.body) {
204-
const chunks = [];
205-
for await (const chunk of fileContent.body) {
206-
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
207-
}
208-
const buffer = Buffer.concat(chunks);
209-
fs.writeFileSync(imageFileName, buffer);
210-
console.log(`Successfully saved image to ${imageFileName}`);
211-
} else {
212-
console.error("No file content available in the response");
213-
}
214-
} catch (error) {
215-
console.error("Error saving image file:", error);
216-
}
217-
} else {
218-
console.log("No image file found in assistant's message");
219-
}
220-
} else {
221-
console.log("No assistant message found");
222-
}
223-
224-
// Iterate through messages and print details for each annotation
225-
console.log(`Message Details:`);
226-
messagesArray.forEach((m) => {
227-
console.log(`File Paths:`);
228-
console.log(`Type: ${m.content[0].type}`);
229-
if (isOutputOfType<MessageTextContent>(m.content[0], "text")) {
230-
const textContent = m.content[0] as MessageTextContent;
231-
console.log(`Text: ${textContent.text.value}`);
232-
}
233-
console.log(`File ID: ${m.id}`);
234-
// firstId and lastId are properties of the paginator, not the messages array
235-
// Removing these references as they don't exist in this context
236-
});
237-
238-
// Uncomment these lines to delete the agent once done
239-
//await client.deleteAgent(agent.id);
240-
//console.log(`Deleted agent, agent ID: ${agent.id}`);
241-
}
242-
243-
main().catch((err) => {
244-
console.error("The sample encountered an error:", err);
245-
});
125+
========================================================
126+
====================== END OF RESULTS ======================
127+
========================================================
246128
```
247129

248130

249-
Run the code using `node index.js`. This code generates a bar chart PNG image file in the TRANSPORTATION sector for the operating profit from the uploaded CSV file and provided the file to you. Full [sample source code](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/ai/ai-agents/samples/v1-beta/typescript/src/codeInterpreterWithStreaming.ts) available.
131+
Full [sample source code](https://github.com/Azure-Samples/azure-sdk-for-js-docs/blob/main/samples/foundry/azure-ai-agents-quickstart-math) available.

0 commit comments

Comments
 (0)