Code Velocity
Nástroje pre vývojárov

Bedrock AgentCore: Vložte živého AI prehliadača do Reactu

·5 min čítania·AWS·Pôvodný zdroj
Zdieľať
Architektonická schéma Amazon Bedrock AgentCore zobrazujúca tok dát pre vloženie živého AI prehliadača do React aplikácie.
  • Ak používate AWS Bedrock pre váš AI model, nainštalujte AWS SDK pre JavaScript:
    npm install @aws-sdk/client-bedrock-runtime
    

Kódová základňa pre implementáciu Live View je zvyčajne rozdelená: kód na strane servera (pre správu relácií a logiku AI agenta) beží v Node.js a kód na strane klienta (pre vykresľovanie Live View) beží v rámci React aplikácie, často balený nástrojmi ako Vite.

Krok za krokom integrácia: Od relácie k streamu

Integrácia živého AI prehliadača s Amazon Bedrock AgentCore zahŕba jasný, trojkrokový proces, ktorý prepojí vašu logiku na strane servera s vašou klientskou React aplikáciou a robustnými schopnosťami AWS Cloud.

1. Spustenie prehliadacej relácie a generovanie URL adresy Live View

Prvý krok prebieha na vašom aplikačnom serveri. Tu vaša backendová logika inicializuje prehliadaciu reláciu v rámci Amazon Bedrock AgentCore a bezpečne získa potrebnú URL adresu na streamovanie živého zobrazenia.

Použijete triedu Browser z SDK bedrock-agentcore. Táto trieda spracováva zložitosť vytvárania a správy izolovaných prehliadacích prostredí v cloude. Kľúčovým výstupom z tohto kroku je SigV4-predpodpísaná URL adresa, ktorá udeľuje bezpečný, dočasný prístup k živému video streamu prehliadacej relácie.

// Príklad kódu na strane servera (Node.js)
import { Browser } from 'bedrock-agentcore';
import { AgentCoreClient } from '@aws-sdk/client-bedrock-agentcore';

// Inicializujte klienta Bedrock AgentCore (zaistite, aby boli správne nakonfigurované poverenia AWS)
const agentCoreClient = new AgentCoreClient({ region: 'us-east-1' }); // Použite požadovanú oblasť

async function startLiveSession() {
    // Vytvorte novú prehliadaciu reláciu
    const browser = new Browser(agentCoreClient);
    await browser.create();

    // Vygenerujte URL adresu Live View
    const liveViewUrl = await browser.getLiveViewURL();
    console.log('Live View URL:', liveViewUrl);

    // Uložte browser.sessionId, aby ste neskôr pripojili svojho AI agenta alebo ukončili reláciu
    const sessionId = browser.sessionId;
    
    return { liveViewUrl, sessionId };
}

// Táto `liveViewUrl` bude odoslaná vášmu React klientovi.

Táto URL adresa je potom odovzdaná vášmu React frontendu, ktorý ju použije na nadviazanie živého streamu.

2. Vykreslenie Live View vo vašej React aplikácii

Akonáhle vaša React aplikácia prijme liveViewUrl z vášho servera, vykreslenie streamu v reálnom čase je pozoruhodne jednoduché, vďaka komponentu BrowserLiveView.

// Príklad kódu na strane klienta (React komponent)
import React, { useEffect, useState } from 'react';
import { BrowserLiveView } from 'bedrock-agentcore';

interface LiveAgentViewerProps {
    liveViewUrl: string;
}

const LiveAgentViewer: React.FC<LiveAgentViewerProps> = ({ liveViewUrl }) => {
    if (!liveViewUrl) {
        return <p>Čakám na URL adresu Live View...</p>;
    }

    return (
        <div style={{ width: '100%', height: '600px', border: '1px solid #ccc' }}>
            <BrowserLiveView url={liveViewUrl} />
        </div>
    );
};

// Vo vašej hlavnej App komponente alebo stránke:
// const MyPage = () => {
//     const [currentLiveViewUrl, setCurrentLiveViewUrl] = useState<string | null>(null);
//
//     useEffect(() => {
//         // Načítajte liveViewUrl z vášho backendu
//         fetch('/api/start-agent-session')
//             .then(res => res.json())
//             .then(data => setCurrentLiveViewUrl(data.liveViewUrl));
//     }, []);
//
//     return (
//         <div>
//             <h1>Živé zobrazenie AI agenta</h1>
//             <LiveAgentViewer liveViewUrl={currentLiveViewUrl} />
//         </div>
//     );
// };

Len s url={liveViewUrl}, komponent BrowserLiveView spracováva zložité detaily nadviazania pripojenia WebSocket, konzumácie streamu DCV a vykresľovania živého video streamu v rámci vašich špecifikovaných rozmerov. Táto minimálna JSX integrácia výrazne zjednodušuje vývoj frontendu, čo vám umožňuje sústrediť sa na používateľskú skúsenosť okolo živého agenta.

3. Prepojenie AI agenta na riadenie prehliadača

Posledným krokom je pripojenie inteligencie vášho AI agenta k skutočným akciám prehliadača v izolovanej relácii. Zatiaľ čo BrowserLiveView poskytuje vizuálnu spätnú väzbu, váš AI agent používa Playwright CDP (Chrome DevTools Protocol) na programatickú interakciu s prehliadačom.

Váš aplikačný server, ktorý tiež hostí vášho AI agenta, použije vlastnosť page objektu Browser (čo je objekt Playwright Page) na vykonávanie akcií prehliadača.

// Príklad kódu na strane servera (pokračovanie z kroku 1)
// Predpokladajme, že máte rozhranie podobné Playwright alebo priame použitie Playwright
import { Browser } from 'bedrock-agentcore';
import { AgentCoreClient } from '@aws-sdk/client-bedrock-agentcore';
import { BedrockRuntimeClient, InvokeModelCommand } from "@aws-sdk/client-bedrock-runtime";

// ... (predchádzajúce nastavenie pre vytvorenie prehliadača) ...

async function driveAgent(sessionId: string) {
    const browser = new Browser(agentCoreClient, { sessionId }); // Znovu sa pripojte k existujúcej relácii
    await browser.connect(); // Pripojte sa k prehliadacej relácii

    const page = browser.page; // Získajte objekt Playwright Page

    // Príklad logiky AI agenta (zjednodušená pre ilustráciu)
    // Tu by ste integrovali s vaším LLM (napr. Anthropic Claude cez Bedrock Converse API)
    // na určenie akcií na základe používateľských výziev a obsahu stránky.
    console.log("Agent navigates to example.com...");
    await page.goto('https://www.example.com');
    console.log("Agent waited for 3 seconds...");
    await page.waitForTimeout(3000); // Simulujte čas spracovania

    console.log("Agent typing into a search box (hypothetical)...");
    // Príklad: await page.type('#search-input', 'Amazon Bedrock AgentCore');
    // Príklad: await page.click('#search-button');

    const content = await page.content();
    // Použite LLM na analýzu 'content' a rozhodnite sa o ďalších krokoch
    const bedrockRuntimeClient = new BedrockRuntimeClient({ region: 'us-east-1' });
    const response = await bedrockRuntimeClient.send(new InvokeModelCommand({
        modelId: "anthropic.claude-3-sonnet-20240229-v1:0", // alebo váš preferovaný model
        contentType: "application/json",
        accept: "application/json",
        body: JSON.stringify({
            messages: [
                {
                    role: "user",
                    content: `Analyze this webpage content and suggest the next action: ${content.substring(0, 500)}`
                }
            ],
            max_tokens: 200,
        }),
    }));
    const decodedBody = new TextDecoder("utf-8").decode(response.body);
    const parsedBody = JSON.parse(decodedBody);
    console.log("AI Model suggested action:", parsedBody.content[0].text);

    // Na základe návrhu LLM vykonajte ďalšie akcie na stránke...

    // Nezabudnite zatvoriť prehliadaciu reláciu po dokončení
    // await browser.close();
}

// Po spustení relácie a získaní URL adresy by ste potom zavolali driveAgent(sessionId)

Táto interakčná slučka – kde váš AI agent analyzuje obsah stránky, určuje ďalšiu akciu a vykoná ju prostredníctvom Playwright CDP – tvorí jadro autonómneho prehliadača. Všetky tieto akcie sú vizuálne vykresľované v reálnom čase prostredníctvom komponentu BrowserLiveView na obrazovke používateľa.

Odomykanie nových možností s vloženými AI agentmi

Integrácia BrowserLiveView z Amazon Bedrock AgentCore je viac než len technická funkcia; je to zmena paradigmy v tom, ako používatelia interagujú s AI agentami a dôverujú im. Vložením vizuálnej spätnej väzby v reálnom čase môžu vývojári vytvárať aplikácie poháňané AI, ktoré sú nielen efektívne, ale aj transparentné, auditovateľné a používateľsky prívetivé.

Táto schopnosť je obzvlášť transformatívna pre aplikácie zahŕňajúce:

  • Komplexné pracovné postupy: Automatizácia viacstupňových online procesov, ako je zadávanie dát, onboarding alebo dodržiavanie regulačných predpisov, kde je viditeľnosť každého kroku prvoradá.
  • Zákaznícka podpora: Umožnenie agentom sledovať AI co-pilotov, ako riešia zákaznícke otázky alebo navigujú v systémoch, čím sa zaisťuje presnosť a poskytujú príležitosti na zásah.
  • Školenie a ladenie: Poskytnutie vývojárom a koncovým používateľom výkonného nástroja na pochopenie správania agenta, ladenie problémov a školenie agentov prostredníctvom priameho pozorovania.
  • Vylepšené auditné stopy: Generovanie vizuálnych záznamov o akciách agenta, ktoré možno kombinovať s nahrávkami relácií do Amazon S3 pre komplexné následné preskúmanie a dodržiavanie súladu.

Schopnosť priamo streamovať prehliadacie relácie z AWS Cloud do klientskych prehliadačov, obchádzajúc aplikačný server pre video stream, ponúka významné výhody z hľadiska výkonu a škálovateľnosti. Táto architektúra minimalizuje latenciu a znižuje zaťaženie vašej backendovej infraštruktúry, čo vám umožňuje nasadiť vysoko reagujúce a škálovateľné riešenia AI agentov.

Prijatím BrowserLiveView nielenže vytvárate AI agentov; budujete dôveru, kontrolu a bohatší používateľský zážitok. Preskúmajte možnosti a posilnite svojich používateľov s dôverou delegovať komplexné webové úlohy inteligentným agentom.

Často kladené otázky

What is the Amazon Bedrock AgentCore BrowserLiveView component and how does it function?
The Amazon Bedrock AgentCore BrowserLiveView component is a crucial part of the Bedrock AgentCore TypeScript SDK, designed to embed a real-time video feed of an AI agent's browsing session directly into a React application. It operates by receiving a SigV4-presigned URL from your application server, which then establishes a persistent WebSocket connection to stream video data via the Amazon DCV protocol from an isolated cloud browser session. This direct streaming mechanism ensures low latency and high fidelity, allowing users to observe every action an AI agent takes on a webpage, from navigation to form submissions, without the video stream passing through your server.
How does embedding Live View enhance user trust and confidence in AI agents?
Embedding Live View significantly boosts user trust and confidence by providing unparalleled transparency into an AI agent's operations. Instead of a 'black box' experience, users gain immediate visual confirmation of the agent's actions, observing its progress and interactions in real-time. This visual feedback loop helps users understand that the agent is on the correct path, interacting with the right elements, and progressing as expected. This is particularly valuable for complex or sensitive workflows, where visual evidence can reassure users that the agent is performing its tasks accurately and responsibly, enhancing overall confidence and allowing for timely intervention if necessary.
What are the primary architectural components involved in integrating a Live View AI agent?
The integration of a Live View AI agent involves three main architectural components. First, the user's web browser, running a React application, hosts the BrowserLiveView component, which renders the real-time stream. Second, the application server acts as the orchestrator, managing the AI agent's logic, initiating browser sessions via the Amazon Bedrock AgentCore API, and generating secure, time-limited SigV4-presigned URLs for the Live View stream. Third, the AWS Cloud hosts Amazon Bedrock AgentCore and Bedrock services, providing the isolated cloud browser sessions, automation capabilities (via Playwright CDP), and the DCV-powered Live View streaming endpoint. A key design point is that the DCV stream flows directly from AWS to the user's browser, bypassing the application server for optimal performance.
Can developers utilize any AI model or agent framework with Amazon Bedrock AgentCore's Live View?
Yes, developers have the flexibility to use any AI model or agent framework of their choice with Amazon Bedrock AgentCore's Live View. While the provided example often demonstrates integration with the Amazon Bedrock Converse API and models like Anthropic Claude, the BrowserLiveView component itself is model-agnostic. This means that the real-time visual streaming functionality is decoupled from the AI agent's underlying reasoning and decision-making logic. As long as your chosen AI agent or framework can interact with the browser automation endpoint provided by AgentCore (typically via Playwright CDP), you can leverage Live View to provide visual feedback to your users, making it a highly adaptable solution for various AI-powered applications.
What are the essential prerequisites for setting up a Live View AI browser agent with Amazon Bedrock AgentCore?
To set up a Live View AI browser agent, several prerequisites are necessary. Developers need Node.js version 20 or later for the server-side logic and React for the client-side application. An AWS account in a supported region is required, along with AWS credentials that have the necessary Amazon Bedrock AgentCore Browser permissions. It's crucial to follow the principle of least privilege for IAM permissions and use temporary credentials (e.g., from AWS IAM Identity Center or STS) rather than long-lived access keys for enhanced security. Additionally, the Amazon Bedrock AgentCore TypeScript SDK (`bedrock-agentcore`) and potentially the AWS SDK for JavaScript (`@aws-sdk/client-bedrock-runtime`) if using Bedrock models, must be installed in your project.
How does the DCV protocol facilitate real-time, low-latency video streaming for Live View?
The Amazon DCV (NICE DCV) protocol is instrumental in providing real-time, low-latency video streaming for the BrowserLiveView component. DCV is a high-performance remote display protocol designed to deliver a rich user experience over varying network conditions. In the context of AgentCore, it efficiently encodes and transmits the visual output of the isolated cloud browser session directly to the user's React application via a WebSocket connection. By optimizing data compression and transmission, DCV ensures that the visual feed of the AI agent's actions appears smooth and responsive, minimizing lag and enabling users to observe the agent's behavior as if it were happening locally on their machine, without the need for complex streaming infrastructure setup by the developer.

Buďte informovaní

Dostávajte najnovšie AI správy do schránky.

Zdieľať