npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

agent-state-bridge

v1.0.0

Published

Bridge for sharing app state and chat with Python agent backend. v1: {messages, actions, context} model, breaking changes, RAG-ready architecture.

Readme

agent-state-bridge

Full-stack bridge for sharing app state between frontend and AI agents. Includes React hooks (npm) and Python backend utilities (PyPI) for FastAPI, Flask, and Django.

🚀 Build AI-powered apps with seamless state synchronization. New in v1.0.0: Centralized custom hooks, {messages, actions, context} model is now required, breaking changes, RAG-ready architecture. See CHANGELOG.md.


📦 Packages

This monorepo contains two complementary packages:

| Package | Platform | Description | | ---------------------- | -------- | ------------------------------------------- | | agent-state-bridge | npm | React hooks and UI components for frontend | | agent-state-bridge | PyPI | Python utilities for FastAPI, Flask, Django |


🎯 Frontend (React/TypeScript)

Installation

npm install agent-state-bridge

Quick Start (v1.0.0)

1. Centralized custom hook pattern

See the examples for the recommended pattern. All agent integration logic (chat, actions, context, CRUD) is now centralized in a single custom hook (e.g., useTodoAgent).

// Example: useTodoAgent.jsx
import { useAgentChat, useAgentCRUD } from "agent-state-bridge";
import { useTodos } from "../context/TodoContext.jsx";

export const useTodoAgent = () => {
  const { todos, addTodo, toggleTodo, deleteTodo, getStats } = useTodos();
  const { messages, sendMessage, loading, error } = useAgentChat({
    getContext: () => ({
      todos: todos.map((t) => ({ id: t.id, text: t.text, done: t.done })),
      summary: getStats(),
    }),
    getActions: () => [],
    onActionsReceived: (actions) => {
      actions.forEach((action) => {
        switch (action.type) {
          case "post":
            if (action.payload?.text) addTodo(action.payload.text);
            break;
          case "put":
            if (action.payload?.id) toggleTodo(action.payload.id);
            break;
          case "delete":
            if (action.payload?.id) deleteTodo(action.payload.id);
            break;
        }
      });
    },
    initialMessages: [],
  });
  // ...useAgentCRUD for each action...
  return { messages, sendMessage, isLoading: loading, error };
};

2. Use the hook in your UI

import { useTodoAgent } from "../hooks/useTodoAgent";

export const AgentChatContainer = () => {
  const { messages, sendMessage, isLoading, error } = useTodoAgent();
  // ...
  return (
    <AgentChatSidebar
      messages={messages}
      onSend={sendMessage}
      loading={isLoading}
      error={error}
      // ...
    />
  );
};

New in v1.0.0:

  • All agent logic must be centralized in a custom hook (see examples)
  • {messages, actions, context} model is required
  • No more direct use of removed hooks/components (see CHANGELOG)

Features

State-agnostic: Works with Zustand, Redux, useState, useContext, etc. ✅ Centralized: All agent logic in one hook ✅ UI included: Pre-built chat component with markdown support ✅ Customizable: Use hooks only or customize the UI ✅ TypeScript: Fully typed

📖 Full Frontend Documentation →


🐍 Backend (Python)

Installation

# For FastAPI (recommended)
pip install agent-state-bridge[fastapi]

# For Flask
pip install agent-state-bridge[flask]

# For Django
pip install agent-state-bridge[django]

Quick Start

FastAPI

from fastapi import FastAPI
from agent_state_bridge.fastapi import create_agent_router
from agent_state_bridge.models import AgentResponse, Message, Action

async def my_agent(messages: list[Message], actions: list[Action], context: dict) -> AgentResponse:
    """
    v1.0.0 model: {messages, actions, context}
    - messages: Conversation history
    - actions: Recent CRUD operations (post, put, delete)
    - context: App state + RAG data
    """
    cart_items = context.get("cart", {}).get("items", [])
    last_msg = messages[-1].content if messages else ""

    response_text = f"You have {len(cart_items)} items. You said: {last_msg}"

    # Optionally return actions for the frontend to execute
    return AgentResponse(
        response=response_text,
        actions=[Action(type="post", payload={"product": "suggested_item"})],  # Optional
        context={"updated": "data"}  # Optional
    )

app = FastAPI()
router = create_agent_router(my_agent, tags=["agent"])
app.include_router(router)

Why this model?

  • ✅ Separates state mutations (actions) from context
  • ✅ Ready for RAG: Add vector search results to context
  • ✅ Bidirectional actions: Agent can return actions for frontend to execute
  • ✅ Scalable: Easy to add query agents and semantic search

Flask

from flask import Flask
from agent_state_bridge.flask import create_agent_blueprint

def my_agent(message: str, state: dict) -> str:
    return f"Processed: {message}"

app = Flask(__name__)
bp = create_agent_blueprint(my_agent)
app.register_blueprint(bp)

Django REST Framework

from agent_state_bridge.django import agent_api_view

@agent_api_view
def my_agent(message: str, state: dict) -> str:
    return f"Processed: {message}"

Agent Framework Support

LangChain: Full async support
Microsoft Agent Framework: Azure AI integration
CrewAI: Multi-agent orchestration
Custom agents: Bring your own logic

📖 Full Backend Documentation →
📁 Examples with LangChain, Agent Framework, etc. →


🚀 Complete Example (see examples/)

See the examples/ directory for full working codebases with the new v1.0.0 pattern.


📚 API Reference

See the examples/ and CHANGELOG.md for the latest API usage and migration notes. The previous hooks/components like useAgentChat and AgentChatSidebar have been removed or replaced by centralized custom hooks.


🏗️ Architecture

graph LR
    A[React App] -->|HTTP POST| B[Backend API]
    A -->|state + message| B
    B -->|response| A
    B --> C[Agent Logic]
    C --> D[LangChain/Agent Framework/Custom]

Key principles:

  • Frontend is the source of truth for state
  • Backend is stateless (no session storage)
  • Separation of concerns: Actions (CRUD) vs Context (state + RAG)
  • Messages, actions, and context sent with every request
  • Agent can return actions for frontend to execute
  • Ready for RAG: Add vector search results to context
  • Works with any AI framework

📖 Architecture Documentation →


📚 Examples

Check out complete working examples in the examples/ directory:

  • Shopping Cart - Full-stack e-commerce with AI assistant
    • React + Zustand + LangChain
    • Demonstrates {messages, actions, context} model
    • RAG-ready architecture

View all examples →


🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT License - see LICENSE for details


🔗 Links


Made with ❤️ for the AI development community