Skip to content
conversation-state logo

Stateless Conversation State Management

conversation-state

Stateless conversation management with database-backed history, message persistence, and scalable architecture. Use when handling chat state, loading history, or building stateless APIs.

SKILL.md

Full skill instructions

Stateless Conversation State Management

Load Conversation History

async def load_conversation_history(
    session: AsyncSession,
    user_id: str,
    conversation_id: int | None
) -> tuple[Conversation, list[dict]]:
    """Load or create conversation with message history."""
    if conversation_id:
        stmt = select(Conversation).where(
            Conversation.id == conversation_id,
            Conversation.user_id == user_id
        )
        result = await session.execute(stmt)
        conversation = result.scalar_one_or_none()
        if not conversation:
            raise HTTPException(status_code=404, detail="Conversation not found")
    else:
        conversation = Conversation(user_id=user_id)
        session.add(conversation)
        await session.commit()
        await session.refresh(conversation)
    
    # Load messages
    stmt = select(Message).where(
        Message.conversation_id == conversation.id
    ).order_by(Message.created_at)
    result = await session.execute(stmt)
    db_messages = result.scalars().all()
    
    messages = [{"role": msg.role, "content": msg.content} for msg in db_messages]
    return conversation, messages

Complete Stateless Flow

@app.post("/​api/​{user_id}/​chat")
async def chat(
    user_id: str,
    request: ChatRequest,
    session: AsyncSession = Depends(get_db_session),
    current_user: str = Depends(verify_jwt)
):
    # 1. Load history from DB
    conversation, messages = await load_conversation_history(
        session, user_id, request.conversation_id
    )
    
    # 2. Save user message
    user_msg = Message(
        user_id=user_id,
        conversation_id=conversation.id,
        role="user",
        content=request.message
    )
    session.add(user_msg)
    await session.commit()
    
    # 3. Add to history array
    messages.append({"role": "user", "content": request.message})
    
    # 4. Run agent
    response, tool_calls = await run_agent(messages)
    
    # 5. Save assistant response
    assistant_msg = Message(
        user_id=user_id,
        conversation_id=conversation.id,
        role="assistant",
        content=response
    )
    session.add(assistant_msg)
    await session.commit()
    
    # 6. Return (server holds NO state)
    return ChatResponse(
        conversation_id=conversation.id,
        response=response,
        tool_calls=tool_calls
    )

Benefits

  • Horizontal scalability (any server handles any request)
  • Resilience (server restart doesn't lose conversations)
  • Testability (each request independent)
  • No sticky sessions needed

More Other skills

Delegate independent tasks to specialized agents working concurrently with isolated context.

295.4K 206.3K
View

Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.

179.7K 100.1K
View

Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors/fonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.

179.7K 89.5K
View

A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).

179.7K 76.1K
View

Fundamental design principles for writing maintainable, testable Python code.

40.2K 21.9K
View

Modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first strategies.

40.2K 20K
View

Generate Playwright tests from scenarios using interactive browser exploration and validation.

39.7K 18.2K
View

Modern React state management with Redux Toolkit, Zustand, Jotai, and React Query for every state category.

40.2K 14.7K
View

GDPR-compliant data handling with consent management, data subject rights, and privacy controls.

40.2K 14.3K
View

Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.

40.2K 13.5K
View

Detailed multi-file refactor planning with safety checks and rollback guidance.

39.7K 13K
View