Lesson 28: Complete Backend Flow
"Putting it all together."
End-to-End Example: Chat Request
1. Client Request
javascript
fetch('http://localhost:8001/agents/1/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message: 'What is AI?'})
})2. FastAPI Receives
python
@router.post("/{agent_id}/chat")
def chat_with_agent(
agent_id: int,
chat_data: ChatRequest, # ← Pydantic validates
db: Session = Depends(get_db) # ← DI creates session
):3. Database Query
python
agent = db.query(Agent).filter(Agent.id == agent_id).first()
# SQL: SELECT * FROM agents WHERE id = 1 LIMIT 14. Service Call
python
response = generate_agent_response(
system_prompt=agent.system_prompt,
user_message=chat_data.message
)
# Calls OpenAI API5. OpenAI Processing
Request → api.openai.com
Model: gpt-4o-mini
Temperature: 0.3
Response: "AI is artificial intelligence..."6. Save Messages
python
db.add(Message(agent_id=1, role="user", content="What is AI?"))
db.add(Message(agent_id=1, role="assistant", content=response))
db.commit()7. Create Run Record
python
run = AgentRun(
agent_id=1,
input_text="What is AI?",
output_text=response,
latency_ms=1850,
status="success"
)
db.add(run)
db.commit()8. Return Response
python
return ChatResponse(
agent_id=1,
user_message="What is AI?",
assistant_response=response,
run_id=42,
latency_ms=1850
)9. Pydantic Serialization
python
# Automatically converts to JSON:
{
"agent_id": 1,
"user_message": "What is AI?",
"assistant_response": "AI is...",
"run_id": 42,
"latency_ms": 1850
}10. HTTP Response
HTTP/1.1 200 OK
Content-Type: application/json
{...}11. Cleanup
python
finally:
db.close() # Session closed automaticallyComplete Timing Breakdown
| Step | Duration | % |
|---|---|---|
| HTTP Parsing | 1ms | 0.05% |
| Validation | 1ms | 0.05% |
| DB Query | 5ms | 0.3% |
| OpenAI Call | 1800ms | 97.3% |
| DB Save | 10ms | 0.5% |
| Serialization | 2ms | 0.1% |
| Response | 1ms | 0.05% |
| Total | 1850ms | 100% |
Key insight: 97% of time is waiting for OpenAI
All Layers Involved
- HTTP Layer - FastAPI framework
- Routing - agents.py router
- Validation - Pydantic schemas
- Dependency Injection - get_db()
- Database - SQLAlchemy ORM
- Business Logic - openai_service.py
- External API - OpenAI
- Persistence - SQLite
- Serialization - Pydantic
- Response - HTTP
Debugging Guide
Issue: Slow response
Check:
- Add timing logs at each step
- Check OpenAI dashboard for rate limits
- Verify database indexes exist
- Check network latency
Issue: 500 error
Check:
- Read error logs
- Verify environment variables
- Test database connection
- Check OpenAI API key
Issue: Wrong response
Check:
- Print system prompt
- Check agent configuration
- Review ToolCall logs
- Test prompt in OpenAI playground
Key Takeaways
🎯 Complete flow spans 11 steps across 10 layers 🎯 97% of latency is external API calls 🎯 Every component has specific responsibility 🎯 Debugging requires understanding each layer 🎯 Observability built-in via ToolCall tracking
Next Steps
👉 Exercises → · Interview Questions → · Glossary →
Module 7 · Integration & Flow