Skip to content

Commit 01df958

Browse files
authored
Merge pull request #4981 from aahill/agents-js
updating javascript code
2 parents 5593688 + 68394a2 commit 01df958

11 files changed

+769
-442
lines changed

articles/ai-services/agents/how-to/tools/azure-ai-search-samples.md

Lines changed: 71 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -291,53 +291,37 @@ agentClient.Administration.DeleteAgent(agent.Id);
291291
First, create an Azure AI Client using the connection string of your project.
292292

293293
```javascript
294-
const connectionString =
295-
process.env["AZURE_AI_PROJECTS_CONNECTION_STRING"] || "<project connection string>";
294+
const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project connection string>";
296295

297-
if (!connectionString) {
296+
if (!projectString) {
298297
throw new Error("AZURE_AI_PROJECTS_CONNECTION_STRING must be set in the environment variables");
299298
}
300299

301-
const client = AIProjectsClient.fromConnectionString(
302-
connectionString || "",
303-
new DefaultAzureCredential(),
304-
);
305-
```
306-
307-
## Get the connection ID for the Azure AI Search resource
308-
Get the connection ID of the Azure AI Search connection in the project.
309-
310-
```javascript
311-
const cognitiveServicesConnectionName = "<cognitiveServicesConnectionName>";
312-
const cognitiveServicesConnection = await client.connections.getConnection(
313-
cognitiveServicesConnectionName,
314-
);
300+
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());
315301
```
316302

317303
## Configure the Azure AI Search tool
318-
Using the connection ID you got in the previous step, you can now configure the Azure AI Search tool to use your Azure AI Search index.
304+
Using the connection ID of the Azure AI Search resource, configure the Azure AI Search tool to use your Azure AI Search index.
319305

320306
```javascript
321-
const azureAISearchTool = ToolUtility.createAzureAISearchTool(
322-
cognitiveServicesConnection.id,
323-
cognitiveServicesConnection.name,
324-
);
307+
const connectionId = process.env["AZURE_AI_CONNECTION_ID"] || "<connection-name>";
308+
309+
const azureAISearchTool = ToolUtility.createAzureAISearchTool(connectionId, "ai-search-sample", {
310+
queryType: "simple",
311+
topK: 3,
312+
filter: "",
313+
indexConnectionId: "",
314+
indexName: "",
315+
});
325316

326-
// Create agent with the Azure AI search tool
327-
const agent = await client.agents.createAgent("gpt-4o-mini", {
328-
name: "my-agent",
329-
instructions: "You are a helpful agent",
330-
tools: [azureAISearchTool.definition],
331-
toolResources: azureAISearchTool.resources,
332-
});
333-
console.log(`Created agent, agent ID : ${agent.id}`);
334317
```
335318

336319
## Create an agent with the Azure AI Search tool enabled
337320

338321
Change the model to the one deployed in your project. You can find the model name in the Azure AI Foundry under the **Models** tab. You can also change the name and instructions of the agent to suit your needs.
339322

340323
```javascript
324+
341325
const agent = await client.agents.createAgent("gpt-4o-mini", {
342326
name: "my-agent",
343327
instructions: "You are a helpful agent",
@@ -352,60 +336,69 @@ console.log(`Created agent, agent ID : ${agent.id}`);
352336
Now that the agent is created, ask it questions about the data in your Azure AI Search index.
353337

354338
```javascript
355-
// create a thread
356-
const thread = await client.agents.createThread();
357-
358-
// add a message to thread
359-
await client.agents.createMessage(
360-
thread.id, {
361-
role: "user",
362-
content: "what are my health insurance plan coverage types?",
363-
});
339+
// Create thread for communication
340+
const thread = await client.threads.create();
341+
console.log(`Created thread, thread ID: ${thread.id}`);
342+
343+
// Create message to thread
344+
const message = await client.messages.create(
345+
thread.id,
346+
"user",
347+
"What is the temperature rating of the cozynights sleeping bag?",
348+
);
349+
console.log(`Created message, message ID : ${message.id}`);
364350

365-
// Intermission is now correlated with thread
366-
// Intermission messages will retrieve the message just added
367-
368-
// create a run
369-
const streamEventMessages = await client.agents.createRun(thread.id, agent.id).stream();
370-
371-
for await (const eventMessage of streamEventMessages) {
372-
switch (eventMessage.event) {
373-
case RunStreamEvent.ThreadRunCreated:
374-
break;
375-
case MessageStreamEvent.ThreadMessageDelta:
376-
{
377-
const messageDelta = eventMessage.data;
378-
messageDelta.delta.content.forEach((contentPart) => {
379-
if (contentPart.type === "text") {
380-
const textContent = contentPart;
381-
const textValue = textContent.text?.value || "No text";
351+
// Create and process agent run in thread with tools
352+
let run = await client.runs.create(thread.id, agent.id);
353+
while (run.status === "queued" || run.status === "in_progress") {
354+
await delay(1000);
355+
run = await client.runs.get(thread.id, run.id);
356+
}
357+
if (run.status === "failed") {
358+
console.log(`Run failed:`, JSON.stringify(run, null, 2));
359+
}
360+
console.log(`Run finished with status: ${run.status}`);
361+
362+
// Fetch run steps to get the details of agent run
363+
const runSteps = await client.runSteps.list(thread.id, run.id);
364+
365+
for await (const step of runSteps) {
366+
console.log(`Step ID: ${step.id}, Status: ${step.status}`);
367+
const stepDetails = step.stepDetails;
368+
if (isOutputOfType(stepDetails, "tool_calls")) {
369+
const toolCalls = stepDetails.toolCalls;
370+
for (const toolCall of toolCalls) {
371+
console.log(`Tool Call ID: ${toolCall.id}, Tool type: ${toolCall.type}`);
372+
if (isOutputOfType(toolCall, "azure_ai_search")) {
373+
{
374+
const azureAISearch = toolCall.azureAISearch;
375+
if (azureAISearch) {
376+
console.log(`Azure AI Search Tool Call input: ${azureAISearch.input}`);
377+
console.log(`Azure AI Search Tool Call output: ${azureAISearch.output}`);
382378
}
383-
});
379+
}
384380
}
385-
break;
386-
387-
case RunStreamEvent.ThreadRunCompleted:
388-
break;
389-
case ErrorEvent.Error:
390-
console.log(`An error occurred. Data ${eventMessage.data}`);
391-
break;
392-
case DoneEvent.Done:
393-
break;
381+
}
394382
}
395383
}
396-
397-
// Print the messages from the agent
398-
const messages = await client.agents.listMessages(thread.id);
399-
400-
// Messages iterate from oldest to newest
401-
// messages[0] is the most recent
402-
for (let i = messages.data.length - 1; i >= 0; i--) {
403-
const m = messages.data[i];
404-
if (isOutputOfType<MessageTextContentOutput>(m.content[0], "text")) {
405-
const textContent = m.content[0];
406-
console.log(`${textContent.text.value}`);
407-
console.log(`---------------------------------`);
384+
// Delete the assistant when done
385+
await client.deleteAgent(agent.id);
386+
console.log(`Deleted agent, agent ID: ${agent.id}`);
387+
388+
// Fetch and log all messages
389+
const messagesIterator = client.messages.list(thread.id);
390+
console.log(`Messages:`);
391+
392+
// Get the first message
393+
for await (const m of messagesIterator) {
394+
if (m.content.length > 0) {
395+
const agentMessage = m.content[0];
396+
if (isOutputOfType(agentMessage, "text")) {
397+
const textContent = agentMessage;
398+
console.log(`Text Message Content - ${textContent.text.value}`);
399+
}
408400
}
401+
break; // Just process the first message
409402
}
410403
```
411404

articles/ai-services/agents/how-to/tools/azure-functions-samples.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ ms.date: 01/30/2025
1010
author: aahill
1111
ms.author: aahi
1212
ms.custom: azure-ai-agents
13-
zone_pivot_groups: selection-function-calling-samples
13+
zone_pivot_groups: selection-azure-functions-samples
1414
---
1515

1616
# How to use Azure Functions with Azure AI Agents
@@ -275,7 +275,7 @@ curl --request GET \
275275
276276
::: zone-end
277277
278-
278+
<!--
279279
::: zone pivot="typescript"
280280
281281
## Define a function for your agent to call
@@ -309,7 +309,7 @@ For any issues with the TypeScript code, create an issue on the [sample code rep
309309
310310
311311
::: zone-end
312-
312+
-->
313313
::: zone pivot="csharp"
314314
315315
## Prerequisites for .NET Azure Function Sample

articles/ai-services/agents/how-to/tools/bing-code-samples.md

Lines changed: 53 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -285,16 +285,16 @@ agentClient.Administration.DeleteAgent(agentId: agent.Id);
285285
Create a client object, which will contain the connection string for connecting to your AI project and other resources.
286286

287287
```javascript
288-
const connectionString =
289-
process.env["AZURE_AI_PROJECTS_CONNECTION_STRING"] || "<project connection string>";
288+
const { AgentsClient, ToolUtility, isOutputOfType } = require("@azure/ai-agents");
289+
const { delay } = require("@azure/core-util");
290+
const { DefaultAzureCredential } = require("@azure/identity");
290291

291-
if (!connectionString) {
292-
throw new Error("AZURE_AI_PROJECTS_CONNECTION_STRING must be set.");
293-
}
294-
const client = AIProjectsClient.fromConnectionString(
295-
connectionString || "",
296-
new DefaultAzureCredential(),
297-
);
292+
require("dotenv/config");
293+
294+
const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project connection string>";
295+
296+
// Create an Azure AI Client
297+
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());
298298
```
299299

300300

@@ -303,12 +303,13 @@ const client = AIProjectsClient.fromConnectionString(
303303
To make the Grounding with Bing search tool available to your agent, use a connection to initialize the tool and attach it to the agent. You can find your connection in the **connected resources** section of your project in the [Azure AI Foundry portal](https://ai.azure.com/).
304304

305305
```javascript
306-
const bingGroundingConnectionId = "<bingGroundingConnectionId>";
307-
const bingTool = ToolUtility.createConnectionTool(connectionToolType.BingGrounding, [
308-
bingGroundingConnectionId,
309-
]);
310306

311-
const agent = await client.agents.createAgent("gpt-4o", {
307+
const connectionId = process.env["AZURE_BING_CONNECTION_ID"] || "<connection-name>";
308+
// Initialize agent bing tool with the connection id
309+
const bingTool = ToolUtility.createBingGroundingTool([{ connectionId: connectionId }]);
310+
311+
// Create agent with the bing tool and process assistant run
312+
const agent = await client.createAgent("gpt-4o", {
312313
name: "my-agent",
313314
instructions: "You are a helpful agent",
314315
tools: [bingTool.definition],
@@ -319,15 +320,17 @@ console.log(`Created agent, agent ID : ${agent.id}`);
319320
## Create a thread
320321

321322
```javascript
322-
// create a thread
323-
const thread = await client.agents.createThread();
324-
325-
// add a message to thread
326-
await client.agents.createMessage(
327-
thread.id, {
328-
role: "user",
329-
content: "What is the weather in Seattle?",
330-
});
323+
// Create thread for communication
324+
const thread = await client.threads.create();
325+
console.log(`Created thread, thread ID: ${thread.id}`);
326+
327+
// Create message to thread
328+
const message = await client.messages.create(
329+
thread.id,
330+
"user",
331+
"How does wikipedia explain Euler's Identity?",
332+
);
333+
console.log(`Created message, message ID : ${message.id}`);
331334
```
332335

333336
## Create a run and check the output
@@ -337,48 +340,35 @@ Create a run and observe that the model uses the Grounding with Bing Search tool
337340

338341
```javascript
339342

340-
// create a run
341-
const streamEventMessages = await client.agents.createRun(thread.id, agent.id).stream();
342-
343-
for await (const eventMessage of streamEventMessages) {
344-
switch (eventMessage.event) {
345-
case RunStreamEvent.ThreadRunCreated:
346-
break;
347-
case MessageStreamEvent.ThreadMessageDelta:
348-
{
349-
const messageDelta = eventMessage.data;
350-
messageDelta.delta.content.forEach((contentPart) => {
351-
if (contentPart.type === "text") {
352-
const textContent = contentPart;
353-
const textValue = textContent.text?.value || "No text";
354-
}
355-
});
356-
}
357-
break;
358-
359-
case RunStreamEvent.ThreadRunCompleted:
360-
break;
361-
case ErrorEvent.Error:
362-
console.log(`An error occurred. Data ${eventMessage.data}`);
363-
break;
364-
case DoneEvent.Done:
365-
break;
366-
}
343+
// Create and process agent run in thread with tools
344+
let run = await client.runs.create(thread.id, agent.id);
345+
while (run.status === "queued" || run.status === "in_progress") {
346+
await delay(1000);
347+
run = await client.runs.get(thread.id, run.id);
348+
}
349+
if (run.status === "failed") {
350+
console.log(`Run failed: ${run.lastError?.message}`);
351+
}
352+
console.log(`Run finished with status: ${run.status}`);
353+
354+
// Delete the assistant when done
355+
await client.deleteAgent(agent.id);
356+
console.log(`Deleted agent, agent ID: ${agent.id}`);
357+
358+
// Fetch and log all messages
359+
const messagesIterator = client.messages.list(thread.id);
360+
console.log(`Messages:`);
361+
362+
// Get the first message
363+
const firstMessage = await messagesIterator.next();
364+
if (!firstMessage.done && firstMessage.value) {
365+
const agentMessage = firstMessage.value.content[0];
366+
if (isOutputOfType(agentMessage, "text")) {
367+
const textContent = agentMessage;
368+
console.log(`Text Message Content - ${textContent.text.value}`);
367369
}
370+
}
368371
369-
// Print the messages from the agent
370-
const messages = await client.agents.listMessages(thread.id);
371-
372-
// Messages iterate from oldest to newest
373-
// messages[0] is the most recent
374-
for (let i = messages.data.length - 1; i >= 0; i--) {
375-
const m = messages.data[i];
376-
if (isOutputOfType<MessageTextContentOutput>(m.content[0], "text")) {
377-
const textContent = m.content[0];
378-
console.log(`${textContent.text.value}`);
379-
console.log(`---------------------------------`);
380-
}
381-
}
382372
```
383373
384374
::: zone-end

articles/ai-services/agents/how-to/tools/bing-custom-search-samples.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ agentClient.DeleteAgent(agentId: agent.Id);
252252

253253
:::zone-end
254254

255+
<!--
255256
::: zone pivot="javascript"
256257
257258
## Create a project client
@@ -372,7 +373,7 @@ Create a run and observe that the model uses the Grounding with Bing Custom Sear
372373
```
373374
374375
:::zone-end
375-
376+
-->
376377

377378
::: zone pivot="rest"
378379

0 commit comments

Comments
 (0)