|
| 1 | +// Copyright (c) Microsoft Corporation. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +/** |
| 5 | + * This sample demonstrates how to use agent operations with the Browser Automation tool from |
| 6 | + * the Azure Agents service. |
| 7 | + * |
| 8 | + * @summary demonstrates how to use agent operations with the Browser Automation tool. |
| 9 | + */ |
| 10 | + |
| 11 | +import type { |
| 12 | + MessageTextContent, |
| 13 | + ThreadMessage, |
| 14 | + RunStepToolCallDetails, |
| 15 | + RunStepBrowserAutomationToolCall, |
| 16 | + MessageTextUrlCitationAnnotation, |
| 17 | +} from "@azure/ai-agents"; |
| 18 | +import { AgentsClient, isOutputOfType, ToolUtility } from "@azure/ai-agents"; |
| 19 | +import { DefaultAzureCredential } from "@azure/identity"; |
| 20 | +import "dotenv/config"; |
| 21 | + |
| 22 | +const projectEndpoint = process.env["PROJECT_ENDPOINT"] || "<project endpoint>"; |
| 23 | +const modelDeploymentName = process.env["MODEL_DEPLOYMENT_NAME"] || "gpt-4o"; |
| 24 | +const azurePlaywrightConnectionId = |
| 25 | + process.env["AZURE_PLAYWRIGHT_CONNECTION_ID"] || "<connection id>"; |
| 26 | + |
| 27 | +export async function main(): Promise<void> { |
| 28 | + const connectionId = azurePlaywrightConnectionId; |
| 29 | + |
| 30 | + // Initialize Browser Automation tool and add the connection id |
| 31 | + const browserAutomation = ToolUtility.createBrowserAutomationTool(connectionId); |
| 32 | + |
| 33 | + // Create an Azure AI Agents Client |
| 34 | + const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential()); |
| 35 | + |
| 36 | + // Create a new Agent that has the Browser Automation tool attached. |
| 37 | + const agent = await client.createAgent(modelDeploymentName, { |
| 38 | + name: "my-agent", |
| 39 | + instructions: ` |
| 40 | + You are an Agent helping with browser automation tasks. |
| 41 | + You can answer questions, provide information, and assist with various tasks |
| 42 | + related to web browsing using the Browser Automation tool available to you. |
| 43 | + `, |
| 44 | + tools: [browserAutomation.definition], |
| 45 | + }); |
| 46 | + |
| 47 | + console.log(`Created agent, ID: ${agent.id}`); |
| 48 | + |
| 49 | + // Create thread for communication |
| 50 | + const thread = await client.threads.create(); |
| 51 | + console.log(`Created thread, ID: ${thread.id}`); |
| 52 | + |
| 53 | + // Create message to thread |
| 54 | + const message = await client.messages.create( |
| 55 | + thread.id, |
| 56 | + "user", |
| 57 | + ` |
| 58 | + Your goal is to report the percent of Microsoft year-to-date stock price change. |
| 59 | + To do that, go to the website finance.yahoo.com. |
| 60 | + At the top of the page, you will find a search bar. |
| 61 | + Enter the value 'MSFT', to get information about the Microsoft stock price. |
| 62 | + At the top of the resulting page you will see a default chart of Microsoft stock price. |
| 63 | + Click on 'YTD' at the top of that chart, and report the percent value that shows up just below it. |
| 64 | + `, |
| 65 | + ); |
| 66 | + console.log(`Created message, ID: ${message.id}`); |
| 67 | + |
| 68 | + // Create and process agent run in thread with tools |
| 69 | + console.log("Waiting for Agent run to complete. Please wait..."); |
| 70 | + const run = await client.runs.createAndPoll(thread.id, agent.id, { |
| 71 | + pollingOptions: { |
| 72 | + intervalInMs: 2000, |
| 73 | + }, |
| 74 | + }); |
| 75 | + |
| 76 | + console.log(`Run finished with status: ${run.status}`); |
| 77 | + |
| 78 | + if (run.status === "failed") { |
| 79 | + console.log(`Run failed: ${JSON.stringify(run.lastError)}`); |
| 80 | + } |
| 81 | + |
| 82 | + // Fetch run steps to get the details of the agent run |
| 83 | + const runStepsIterator = client.runSteps.list(thread.id, run.id); |
| 84 | + console.log("\nRun Steps:"); |
| 85 | + |
| 86 | + for await (const step of runStepsIterator) { |
| 87 | + console.log(`Step ${step.id} status: ${step.status}`); |
| 88 | + |
| 89 | + if (isOutputOfType<RunStepToolCallDetails>(step.stepDetails, "tool_calls")) { |
| 90 | + console.log(" Tool calls:"); |
| 91 | + const toolCalls = step.stepDetails.toolCalls; |
| 92 | + |
| 93 | + for (const call of toolCalls) { |
| 94 | + console.log(` Tool call ID: ${call.id}`); |
| 95 | + console.log(` Tool call type: ${call.type}`); |
| 96 | + |
| 97 | + if (isOutputOfType<RunStepBrowserAutomationToolCall>(call, "browser_automation")) { |
| 98 | + console.log(` Browser automation input: ${call.browserAutomation.input}`); |
| 99 | + console.log(` Browser automation output: ${call.browserAutomation.output}`); |
| 100 | + |
| 101 | + console.log(" Steps:"); |
| 102 | + for (const toolStep of call.browserAutomation.steps) { |
| 103 | + console.log(` Last step result: ${toolStep.lastStepResult}`); |
| 104 | + console.log(` Current state: ${toolStep.currentState}`); |
| 105 | + console.log(` Next step: ${toolStep.nextStep}`); |
| 106 | + console.log(); // add an extra newline between tool steps |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + console.log(); // add an extra newline between tool calls |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + console.log(); // add an extra newline between run steps |
| 115 | + } |
| 116 | + |
| 117 | + // Optional: Delete the agent once the run is finished. |
| 118 | + // Comment out this line if you plan to reuse the agent later. |
| 119 | + await client.deleteAgent(agent.id); |
| 120 | + console.log("Deleted agent"); |
| 121 | + |
| 122 | + // Print the Agent's response message with optional citation |
| 123 | + const messagesIterator = client.messages.list(thread.id); |
| 124 | + const messages: ThreadMessage[] = []; |
| 125 | + |
| 126 | + for await (const msg of messagesIterator) { |
| 127 | + messages.unshift(msg); // Add to beginning to maintain chronological order |
| 128 | + } |
| 129 | + |
| 130 | + // Find the last assistant message |
| 131 | + const responseMessage = messages.find( |
| 132 | + (msg) => msg.role === "assistant" && msg.content.length > 0, |
| 133 | + ); |
| 134 | + |
| 135 | + if (responseMessage) { |
| 136 | + // Display URL citations if any |
| 137 | + for (const content of responseMessage.content) { |
| 138 | + if (isOutputOfType<MessageTextContent>(content, "text")) { |
| 139 | + console.log(`Agent response: ${content.text.value}`); |
| 140 | + for (const annotation of content.text.annotations || []) { |
| 141 | + if (isOutputOfType<MessageTextUrlCitationAnnotation>(annotation, "url_citation")) { |
| 142 | + console.log( |
| 143 | + `URL Citation: [${annotation.urlCitation.title}](${annotation.urlCitation.url})`, |
| 144 | + ); |
| 145 | + } |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +main().catch((err) => { |
| 153 | + console.error("The sample encountered an error:", err); |
| 154 | + process.exit(1); |
| 155 | +}); |
0 commit comments