跳转到内容

React 到 Python Agent

Nx Plugin for AWS 提供了一个生成器,可以快速将您的 Python Agent 与 React 网站集成。它设置了通过类型安全的 OpenAPI 生成客户端连接到您的 agent 所需的所有配置,包括 AWS IAM 和 Cognito 身份验证支持。

在使用此生成器之前,请确保您具备:

  1. 一个 React 网站(使用 ts#website 生成器生成)
  2. 一个使用 protocol=http 的 Python Agent(使用 py#agent 生成器生成)
  3. 通过 ts#website#auth 生成器添加的 Cognito Auth
Terminal window
pnpm nx g @aws/nx-plugin:connection
您还可以执行试运行以查看哪些文件会被更改
Terminal window
pnpm nx g @aws/nx-plugin:connection --dry-run

系统将提示您选择 React 网站作为源项目,并选择包含 Python Agent 的项目作为目标项目。如果您的目标项目包含多个组件(例如多个 agent 或其他组件类型),系统将提示您指定 targetComponent 以消除歧义。

参数类型默认值描述
sourceProject 必需string-源项目
targetProject 必需string-要连接到的目标项目
sourceComponent string-要从其连接的源组件(组件名称、相对于源项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为源。
targetComponent string-要连接到的目标组件(组件名称、相对于目标项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为目标。
preferInstallDependencies booleantrue是否在生成器运行后优先安装依赖项。设置为 false 可在批量运行多个生成器时延迟安装(如果后续生成器需要计算 Nx 项目图,仍会运行安装);在最后统一安装一次。

生成器在您的 Python Agent 项目中创建以下内容:

  • 文件夹scripts
    • <agent_name>_openapi.py Script to generate an OpenAPI specification from the agent’s FastAPI app
  • project.json A new <agent-name>-openapi target is added

生成器在您的 React 应用程序中创建以下结构:

  • 文件夹src
    • 文件夹components
      • <AgentName>Provider.tsx Provider for the OpenAPI client
      • QueryClientProvider.tsx TanStack React Query client provider
    • 文件夹hooks
      • useSigV4.tsx Hook for signing requests with SigV4 (IAM only)
      • use<AgentName>.tsx Hook returning the TanStack Query options proxy for your agent’s API
      • use<AgentName>Client.tsx Hook returning the vanilla API client
    • 文件夹generated
      • 文件夹<agent-name>
        • types.gen.ts Generated types from the agent’s Pydantic models
        • client.gen.ts Type-safe client for calling your agent’s API
        • options-proxy.gen.ts TanStack Query hooks options for interacting with your agent
  • project.json Targets added for client generation and watching for changes
  • .gitignore The generated client files are ignored by default

在构建时,会对 Python Agent 的 FastAPI 应用程序进行内省以生成 OpenAPI 规范。然后使用此规范生成带有 TanStack Query hooks 的类型安全 TypeScript 客户端,遵循与 React 到 FastAPI 连接相同的模式。

每个 agent 都有自己的作用域 OpenAPI 脚本(例如 scripts/agent_openapi.py),以便具有多个 agent 的项目可以生成单独的规范。

运行此连接生成器还会修补 agent 生成的 CDK/Terraform 构造,将其 AgentCore 运行时 ARN 发布到网站的 runtime-config.json(在 connection 命名空间下),因此只有您明确连接的 agent 才会暴露给前端。详情请参阅运行时配置

生成的代码根据您的 agent 配置处理身份验证:

  • IAM(默认):使用 AWS SigV4 签署 HTTP 请求。凭证从配置了网站身份验证的 Cognito Identity Pool 获取
  • Cognito:在 Authorization 标头中嵌入 JWT 访问令牌
  • None:无身份验证

如果您的 agent 使用 IAM 身份验证,则必须授予 Cognito Identity Pool 的已认证角色调用该 agent 的权限。

packages/infra/src/stacks/application-stack.ts
const identity = new UserIdentity(this, 'Identity');
const myAgent = new MyAgent(this, 'MyAgent');
// Grant the authenticated Cognito role permission to invoke the agent
myAgent.grantInvokeAccess(identity.identityPool.authenticatedRole);

grantInvokeAccess 会在 agent 的运行时 ARN 上连接所有 AgentCore 调用操作(InvokeAgentRuntimeInvokeAgentRuntimeWithWebSocketStream)。

如果您的 agent 使用 Cognito 身份验证,则无需定义任何额外的基础设施即可将您的网站连接到您的 agent。

use<AgentName> hook 提供用于调用 agent API 端点的 TanStack Query 选项:

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useMyAgent } from '../hooks/useMyAgent';
import type { StreamChunk } from '../generated/my-agent/types.gen';
function ChatComponent() {
const api = useMyAgent();
const [chunks, setChunks] = useState<StreamChunk[]>([]);
const invoke = useMutation(api.invoke.mutationOptions({
onSuccess: async (stream) => {
setChunks([]);
for await (const chunk of stream) {
setChunks((prev) => [...prev, chunk]);
}
},
}));
const handleSend = (prompt: string) => {
invoke.mutate({ prompt });
};
return (
<div>
<button onClick={() => handleSend('Hello!')}>Send</button>
{invoke.isPending && <p>Agent is thinking...</p>}
{chunks.map((chunk, i) => (
<span key={i}>{chunk.content}</span>
))}
</div>
);
}

use<AgentName>Client hook 提供对 API 客户端的直接访问:

import { useState } from 'react';
import { useMyAgentClient } from '../hooks/useMyAgentClient';
import type { StreamChunk } from '../generated/my-agent/types.gen';
function ChatComponent() {
const client = useMyAgentClient();
const [chunks, setChunks] = useState<StreamChunk[]>([]);
const handleSend = async (prompt: string) => {
setChunks([]);
for await (const chunk of client.invoke({ prompt })) {
setChunks((prev) => [...prev, chunk]);
}
};
return (
<div>
<button onClick={() => handleSend('Hello!')}>Send</button>
{chunks.map((chunk, i) => (
<span key={i}>{chunk.content}</span>
))}
</div>
);
}

连接生成器会自动配置 dev 集成:

  1. 运行 nx dev <website> 也会启动 agent 的本地 FastAPI 服务器
  2. 运行时配置被覆盖以指向本地 HTTP URL(例如 http://localhost:8081/
  3. 当 agent 的 API 发生变化时,TypeScript 客户端会自动重新生成
Terminal window
pnpm nx dev <WebsiteProject>

有关更多信息,请参阅: