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.
Maintainers
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-bridgeQuick 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
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
MIT License - see LICENSE for details
🔗 Links
- npm package: npmjs.com/package/agent-state-bridge
- PyPI package: pypi.org/project/agent-state-bridge
- GitHub: github.com/SergioCantera/agent-state-bridge
- Issues: github.com/SergioCantera/agent-state-bridge/issues
Made with ❤️ for the AI development community
