React to Python Strands Agent
Nx Plugin for AWS provides a generator to quickly integrate your Python Strands Agent with a React website. It sets up all necessary configuration for connecting to your agent via a type-safe OpenAPI-generated client, including AWS IAM and Cognito authentication support.
Prerequisites
Section titled “Prerequisites”Before using this generator, ensure you have:
- A React website (generated using the
ts#react-websitegenerator) - A Python Strands Agent (generated using the
py#strands-agentgenerator) - Cognito Auth added via the
ts#react-website-authgenerator
Run the Generator
Section titled “Run the Generator”- Install the Nx Console VSCode Plugin if you haven't already
- Open the Nx Console in VSCode
- Click
Generate (UI)in the "Common Nx Commands" section - Search for
@aws/nx-plugin - connection - Fill in the required parameters
- Click
Generate
pnpm nx g @aws/nx-plugin:connectionyarn nx g @aws/nx-plugin:connectionnpx nx g @aws/nx-plugin:connectionbunx nx g @aws/nx-plugin:connectionYou can also perform a dry-run to see what files would be changed
pnpm nx g @aws/nx-plugin:connection --dry-runyarn nx g @aws/nx-plugin:connection --dry-runnpx nx g @aws/nx-plugin:connection --dry-runbunx nx g @aws/nx-plugin:connection --dry-runYou will be prompted to select your React website as the source project and the project containing your Python Strands Agent as the target project. If your target project contains multiple components (such as multiple agents or other component types), you will be prompted to specify a targetComponent to disambiguate.
Options
Section titled “Options”| Parameter | Type | Default | Description |
|---|---|---|---|
| sourceProject Required | string | - | The source project |
| targetProject Required | string | - | The target project to connect to |
| sourceComponent | string | - | The source component to connect from (component name, path relative to source project root, or generator id). Use '.' to explicitly select the project as the source. |
| targetComponent | string | - | The target component to connect to (component name, path relative to target project root, or generator id). Use '.' to explicitly select the project as the target. |
Generator Output
Section titled “Generator Output”The generator creates the following in your Python Strands Agent project:
Directoryscripts
- <agent_name>_openapi.py Script to generate an OpenAPI specification from the agent’s FastAPI app
- project.json A new
<agent-name>-openapitarget is added
The generator creates the following structure in your React application:
Directorysrc
Directorycomponents
- <AgentName>Provider.tsx Provider for the OpenAPI client
- QueryClientProvider.tsx TanStack React Query client provider
Directoryhooks
- 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
Directorygenerated
Directory<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
How It Works
Section titled “How It Works”OpenAPI Client Generation
Section titled “OpenAPI Client Generation”At build time, the Python Strands Agent’s FastAPI app is introspected to generate an OpenAPI specification. This spec is then used to generate a type-safe TypeScript client with TanStack Query hooks, following the same pattern as the React to FastAPI connection.
Each agent gets its own scoped OpenAPI script (e.g., scripts/agent_openapi.py) so that projects with multiple agents can generate individual specs.
Authentication
Section titled “Authentication”The generated code handles authentication depending on your agent’s configuration:
- IAM (default): Uses AWS SigV4 to sign HTTP requests. Credentials are obtained from the Cognito Identity Pool configured with your website’s auth
- Cognito: Embeds the JWT access token in an Authorization header
- None: No authentication
Using the Generated Code
Section titled “Using the Generated Code”Using the API Hook
Section titled “Using the API Hook”The use<AgentName> hook provides TanStack Query options for calling your agent’s API endpoints:
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 = (message: string) => { invoke.mutate({ prompt: message, sessionId: 'my-session', }); };
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> );}Using the Vanilla Client
Section titled “Using the Vanilla Client”The use<AgentName>Client hook provides direct access to the API client:
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 (message: string) => { setChunks([]); for await (const chunk of client.invoke({ prompt: message, sessionId: 'my-session', })) { setChunks((prev) => [...prev, chunk]); } };
return ( <div> <button onClick={() => handleSend('Hello!')}>Send</button> {chunks.map((chunk, i) => ( <span key={i}>{chunk.content}</span> ))} </div> );}Local Development
Section titled “Local Development”The connection generator automatically configures serve-local integration:
- Running
nx serve-local <website>will also start the agent’s local FastAPI server - The runtime config is overridden to point to the local HTTP URL (e.g.,
http://localhost:8081/) - The TypeScript client is automatically regenerated when the agent’s API changes
pnpm nx serve-local <WebsiteProject>yarn nx serve-local <WebsiteProject>npx nx serve-local <WebsiteProject>bunx nx serve-local <WebsiteProject>Infrastructure
Section titled “Infrastructure”If your agent uses IAM auth, the Cognito Identity Pool’s authenticated role must be granted permission to invoke the agent. Refer to your agent’s infrastructure construct for the appropriate grantInvokeAccess method.
More Information
Section titled “More Information”For more information, please refer to: