Skip to content

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.

Before using this generator, ensure you have:

  1. A React website (generated using the ts#react-website generator)
  2. A Python Strands Agent (generated using the py#strands-agent generator)
  3. Cognito Auth added via the ts#react-website-auth generator
  1. Install the Nx Console VSCode Plugin if you haven't already
  2. Open the Nx Console in VSCode
  3. Click Generate (UI) in the "Common Nx Commands" section
  4. Search for @aws/nx-plugin - connection
  5. Fill in the required parameters
    • Click Generate

    You 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.

    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.

    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>-openapi target 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

    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.

    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

    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>
    );
    }

    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>
    );
    }

    The connection generator automatically configures serve-local integration:

    1. Running nx serve-local <website> will also start the agent’s local FastAPI server
    2. The runtime config is overridden to point to the local HTTP URL (e.g., http://localhost:8081/)
    3. The TypeScript client is automatically regenerated when the agent’s API changes
    Terminal window
    pnpm nx serve-local <WebsiteProject>

    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.

    For more information, please refer to: