Skip to content

Commit cb5b98f

Browse files
committed
Agents TS quickstart - simplier, math question
1 parent 6a73c51 commit cb5b98f

File tree

2 files changed

+17
-190
lines changed

2 files changed

+17
-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: 11 additions & 190 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ author: aahill
44
ms.author: aahi
55
ms.service: azure-ai-agent-service
66
ms.topic: include
7-
ms.date: 07/16/2025
7+
ms.date: 09/12/2025
88
ms.custom: devx-track-ts
99
---
1010

@@ -14,8 +14,7 @@ ms.custom: devx-track-ts
1414
## Prerequisites
1515

1616
[!INCLUDE [universal-prerequisites](universal-prerequisites.md)]
17-
18-
17+
* [Node.js LTS](https://nodejs.org/)
1918

2019
## Configure and run an agent
2120

@@ -31,19 +30,19 @@ ms.custom: devx-track-ts
3130
Key objects in this code include:
3231

3332
* [AgentsClient](/javascript/api/@azure/ai-agents/agentsclient)
34-
* [ToolUtility](/javascript/api/@azure/ai-agents/toolutility)
3533

36-
First, initialize a new project by running:
34+
First, initialize a new TypeScript project by running:
3735

3836
```console
3937
npm init -y
38+
npm pkg set type="module"
4039
```
4140

4241
Run the following commands to install the npm packages required.
4342

4443
```console
4544
npm install @azure/ai-agents @azure/identity
46-
npm install dotenv
45+
npm install @types/node typescript --save-dev
4746
```
4847

4948
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.
@@ -52,7 +51,7 @@ Next, to authenticate your API requests and run the program, use the [az login](
5251
az login
5352
```
5453

55-
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:
54+
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:
5655

5756
`https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>`
5857

@@ -68,190 +67,12 @@ Save the name of your model deployment name as an environment variable named `MO
6867
> * 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.
6968
> * _Remember: If you accidentally commit sensitive information, consider those credentials compromised and rotate them immediately._
7069
70+
Create a tsconfig.json file with the following content:
7171

72-
Next, create an `index.js` file and paste in the following code:
73-
74-
```typescript
75-
// Copyright (c) Microsoft Corporation.
76-
// Licensed under the MIT License.
77-
78-
/**
79-
* This sample demonstrates how to use agent operations with code interpreter from the Azure Agents service.
80-
*
81-
* @summary demonstrates how to use agent operations with code interpreter.
82-
*/
83-
// @ts-nocheck
84-
import type {
85-
MessageDeltaChunk,
86-
MessageDeltaTextContent,
87-
MessageImageFileContent,
88-
MessageTextContent,
89-
ThreadRun,
90-
} from "@azure/ai-agents";
91-
import {
92-
RunStreamEvent,
93-
MessageStreamEvent,
94-
DoneEvent,
95-
ErrorEvent,
96-
AgentsClient,
97-
isOutputOfType,
98-
ToolUtility,
99-
} from "@azure/ai-agents";
100-
import { DefaultAzureCredential } from "@azure/identity";
101-
102-
import * as fs from "fs";
103-
import path from "node:path";
104-
import "dotenv/config";
105-
106-
const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project endpoint>";
107-
const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o";
108-
109-
export async function main(): Promise<void> {
110-
// Create an Azure AI Client
111-
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());
112-
113-
// Upload file and wait for it to be processed
114-
const filePath = "./data/nifty500QuarterlyResults.csv";
115-
const localFileStream = fs.createReadStream(filePath);
116-
const localFile = await client.files.upload(localFileStream, "assistants", {
117-
fileName: "myLocalFile",
118-
});
119-
120-
console.log(`Uploaded local file, file ID : ${localFile.id}`);
121-
122-
// Create code interpreter tool
123-
const codeInterpreterTool = ToolUtility.createCodeInterpreterTool([localFile.id]);
124-
125-
// Notice that CodeInterpreter must be enabled in the agent creation, otherwise the agent will not be able to see the file attachment
126-
const agent = await client.createAgent(modelDeploymentName, {
127-
name: "my-agent",
128-
instructions: "You are a helpful agent",
129-
tools: [codeInterpreterTool.definition],
130-
toolResources: codeInterpreterTool.resources,
131-
});
132-
console.log(`Created agent, agent ID: ${agent.id}`);
133-
134-
// Create a thread
135-
const thread = await client.threads.create();
136-
console.log(`Created thread, thread ID: ${thread.id}`);
72+
:::code language="json" source="~/reusable-content/samples/foundry/azure-ai-agents-quickstart-math/tsconfig.json":::
13773

138-
// Create a message
139-
const message = await client.messages.create(
140-
thread.id,
141-
"user",
142-
"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?",
143-
);
144-
145-
console.log(`Created message, message ID: ${message.id}`);
146-
147-
// Create and execute a run
148-
const streamEventMessages = await client.runs.create(thread.id, agent.id).stream();
149-
150-
for await (const eventMessage of streamEventMessages) {
151-
switch (eventMessage.event) {
152-
case RunStreamEvent.ThreadRunCreated:
153-
console.log(`ThreadRun status: ${(eventMessage.data as ThreadRun).status}`);
154-
break;
155-
case MessageStreamEvent.ThreadMessageDelta:
156-
{
157-
const messageDelta = eventMessage.data as MessageDeltaChunk;
158-
messageDelta.delta.content.forEach((contentPart) => {
159-
if (contentPart.type === "text") {
160-
const textContent = contentPart as MessageDeltaTextContent;
161-
const textValue = textContent.text?.value || "No text";
162-
console.log(`Text delta received:: ${textValue}`);
163-
}
164-
});
165-
}
166-
break;
167-
168-
case RunStreamEvent.ThreadRunCompleted:
169-
console.log("Thread Run Completed");
170-
break;
171-
case ErrorEvent.Error:
172-
console.log(`An error occurred. Data ${eventMessage.data}`);
173-
break;
174-
case DoneEvent.Done:
175-
console.log("Stream completed.");
176-
break;
177-
}
178-
}
179-
180-
// Delete the original file from the agent to free up space (note: this does not delete your version of the file)
181-
await client.files.delete(localFile.id);
182-
console.log(`Deleted file, file ID : ${localFile.id}`);
183-
184-
// Print the messages from the agent
185-
const messagesIterator = client.messages.list(thread.id);
186-
const messagesArray = [];
187-
for await (const m of messagesIterator) {
188-
messagesArray.push(m);
189-
}
190-
console.log("Messages:", messagesArray);
191-
192-
// Get most recent message from the assistant
193-
// Get most recent message from the assistant
194-
const assistantMessage = messagesArray.find((msg) => msg.role === "assistant");
195-
if (assistantMessage) {
196-
// Look for an image file in the assistant's message
197-
const imageFileOutput = assistantMessage.content.find(content =>
198-
content.type === "image_file" && content.imageFile?.fileId);
199-
200-
if (imageFileOutput) {
201-
try {
202-
// Save the newly created file
203-
console.log(`Saving new files...`);
204-
const imageFile = imageFileOutput.imageFile.fileId;
205-
const imageFileName = path.resolve(
206-
"./data/" + (await client.files.get(imageFile)).filename + "ImageFile.png",
207-
);
208-
console.log(`Image file name : ${imageFileName}`);
209-
210-
const fileContent = await client.files.getContent(imageFile).asNodeStream();
211-
if (fileContent && fileContent.body) {
212-
const chunks = [];
213-
for await (const chunk of fileContent.body) {
214-
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
215-
}
216-
const buffer = Buffer.concat(chunks);
217-
fs.writeFileSync(imageFileName, buffer);
218-
console.log(`Successfully saved image to ${imageFileName}`);
219-
} else {
220-
console.error("No file content available in the response");
221-
}
222-
} catch (error) {
223-
console.error("Error saving image file:", error);
224-
}
225-
} else {
226-
console.log("No image file found in assistant's message");
227-
}
228-
} else {
229-
console.log("No assistant message found");
230-
}
231-
232-
// Iterate through messages and print details for each annotation
233-
console.log(`Message Details:`);
234-
messagesArray.forEach((m) => {
235-
console.log(`File Paths:`);
236-
console.log(`Type: ${m.content[0].type}`);
237-
if (isOutputOfType<MessageTextContent>(m.content[0], "text")) {
238-
const textContent = m.content[0] as MessageTextContent;
239-
console.log(`Text: ${textContent.text.value}`);
240-
}
241-
console.log(`File ID: ${m.id}`);
242-
// firstId and lastId are properties of the paginator, not the messages array
243-
// Removing these references as they don't exist in this context
244-
});
245-
246-
// Uncomment these lines to delete the agent once done
247-
//await client.deleteAgent(agent.id);
248-
//console.log(`Deleted agent, agent ID: ${agent.id}`);
249-
}
250-
251-
main().catch((err) => {
252-
console.error("The sample encountered an error:", err);
253-
});
254-
```
74+
Next, create an `index.ts` file and paste in the following code:
25575

76+
:::code language="typescript" source="~/reusable-content/samples/foundry/azure-ai-agents-quickstart-math/index.ts":::
25677

257-
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.
78+
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?`. 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)