当前位置: 首页 > news >正文

fastapi-langgraph

fastapi-langgraph

https://github.com/fanqingsong/fastapi-langgraph

FastAPI LangGraph Agent Template

A production-ready FastAPI template for building AI agent applications with LangGraph integration. This template provides a robust foundation for building scalable, secure, and maintainable AI agent services.

🌟 Features

  • Production-Ready Architecture

    • FastAPI for high-performance async API endpoints
    • LangGraph integration for AI agent workflows
    • Langfuse for LLM observability and monitoring
    • Structured logging with environment-specific formatting
    • Rate limiting with configurable rules
    • PostgreSQL for data persistence
    • Docker and Docker Compose support
    • Prometheus metrics and Grafana dashboards for monitoring
  • Security

    • JWT-based authentication
    • Session management
    • Input sanitization
    • CORS configuration
    • Rate limiting protection
  • Developer Experience

    • Environment-specific configuration
    • Comprehensive logging system
    • Clear project structure
    • Type hints throughout
    • Easy local development setup
  • Model Evaluation Framework

    • Automated metric-based evaluation of model outputs
    • Integration with Langfuse for trace analysis
    • Detailed JSON reports with success/failure metrics
    • Interactive command-line interface
    • Customizable evaluation metrics

 

 

 

"""Chatbot API endpoints for handling chat interactions.This module provides endpoints for chat interactions, including regular chat,
streaming chat, message history management, and chat history clearing.
"""import json
from typing import Listfrom fastapi import (APIRouter,Depends,HTTPException,Request,
)
from fastapi.responses import StreamingResponsefrom app.api.v1.auth import get_current_session
from app.core.config import settings
from app.core.langgraph.graph import LangGraphAgent
from app.core.limiter import limiter
from app.core.logging import logger
from app.models.session import Session
from app.schemas.chat import (ChatRequest,ChatResponse,Message,StreamResponse,
)router = APIRouter()
agent = LangGraphAgent()@router.post("/chat", response_model=ChatResponse)
@limiter.limit(settings.RATE_LIMIT_ENDPOINTS["chat"][0])
async def chat(request: Request,chat_request: ChatRequest,session: Session = Depends(get_current_session),
):"""Process a chat request using LangGraph.Args:request: The FastAPI request object for rate limiting.chat_request: The chat request containing messages.session: The current session from the auth token.Returns:ChatResponse: The processed chat response.Raises:HTTPException: If there's an error processing the request."""try:logger.info("chat_request_received",session_id=session.id,message_count=len(chat_request.messages),)# Process the request through the LangGraphresult = await agent.get_response(chat_request.messages, session.id, user_id=session.user_id)logger.info("chat_request_processed", session_id=session.id)return ChatResponse(messages=result)except Exception as e:logger.error("chat_request_failed", session_id=session.id, error=str(e), exc_info=True)raise HTTPException(status_code=500, detail=str(e))@router.post("/chat/stream")
@limiter.limit(settings.RATE_LIMIT_ENDPOINTS["chat_stream"][0])
async def chat_stream(request: Request,chat_request: ChatRequest,session: Session = Depends(get_current_session),
):"""Process a chat request using LangGraph with streaming response.Args:request: The FastAPI request object for rate limiting.chat_request: The chat request containing messages.session: The current session from the auth token.Returns:StreamingResponse: A streaming response of the chat completion.Raises:HTTPException: If there's an error processing the request."""try:logger.info("stream_chat_request_received",session_id=session.id,message_count=len(chat_request.messages),)async def event_generator():"""Generate streaming events.Yields:str: Server-sent events in JSON format.Raises:Exception: If there's an error during streaming."""try:full_response = ""async for chunk in agent.get_stream_response(chat_request.messages, session.id, user_id=session.user_id):full_response += chunkresponse = StreamResponse(content=chunk, done=False)yield f"data: {json.dumps(response.model_dump())}\n\n"# Send final message indicating completionfinal_response = StreamResponse(content="", done=True)yield f"data: {json.dumps(final_response.model_dump())}\n\n"except Exception as e:logger.error("stream_chat_request_failed",session_id=session.id,error=str(e),exc_info=True,)error_response = StreamResponse(content=str(e), done=True)yield f"data: {json.dumps(error_response.model_dump())}\n\n"return StreamingResponse(event_generator(), media_type="text/event-stream")except Exception as e:logger.error("stream_chat_request_failed",session_id=session.id,error=str(e),exc_info=True,)raise HTTPException(status_code=500, detail=str(e))@router.get("/messages", response_model=ChatResponse)
@limiter.limit(settings.RATE_LIMIT_ENDPOINTS["messages"][0])
async def get_session_messages(request: Request,session: Session = Depends(get_current_session),
):"""Get all messages for a session.Args:request: The FastAPI request object for rate limiting.session: The current session from the auth token.Returns:ChatResponse: All messages in the session.Raises:HTTPException: If there's an error retrieving the messages."""try:messages = await agent.get_chat_history(session.id)return ChatResponse(messages=messages)except Exception as e:logger.error("get_messages_failed", session_id=session.id, error=str(e), exc_info=True)raise HTTPException(status_code=500, detail=str(e))@router.delete("/messages")
@limiter.limit(settings.RATE_LIMIT_ENDPOINTS["messages"][0])
async def clear_chat_history(request: Request,session: Session = Depends(get_current_session),
):"""Clear all messages for a session.Args:request: The FastAPI request object for rate limiting.session: The current session from the auth token.Returns:dict: A message indicating the chat history was cleared."""try:await agent.clear_chat_history(session.id)return {"message": "Chat history cleared successfully"}except Exception as e:logger.error("clear_chat_history_failed", session_id=session.id, error=str(e), exc_info=True)raise HTTPException(status_code=500, detail=str(e))

 

http://www.jsqmd.com/news/1182/

相关文章:

  • 第二周预习作业
  • 学python的第7天
  • Revit二次开发环境配置
  • CF1016G Appropriate Team
  • CF494C Helping People
  • 深入解析:Extract Chart Data Directly to Excel
  • AOSP Android12 Source 下载同步
  • 02020404 EF Core基础04-自增主键、Guid主键、混合自增、Hi/Lo算法、Migration深入、数据库其它迁移命令
  • 02020403 EF Core基础03-Fluent API、Data Annotation、两种配置的选择
  • 深入解析:Python(1)|| 超基础语法(格式,输入输出,变量,字符串,运算符)
  • 深入解析:STM32-FreeRTOS操作系统-任务管理
  • Java中异步任务的执行方式有几种?
  • mysql数据库自增ID为int类型超过范围
  • 202508_浙江省网络安全测试职业职工技能竞赛_misc-1
  • python爬虫测试
  • 广二联考题解补全计划:
  • 如何在 C# 中将文本转换为 Word 以及将 Word 转换为文本 - 教程
  • Chapter 8 Contour / Shape Detection
  • 【左程云算法笔记016】双端队列-双链表和固定数组实现 - 教程
  • LeetCode 几道 Promises 和 Time 的题目 - 教程
  • [硬件电路-232]:FET(场效应管)的核心机制是通过栅极电压调控半导体“沟道“中的载流子浓度与分布,进而控制源极与漏极之间的电流大小 - 指南
  • java相关问题:面向对象入门2与类的识别
  • EXCEL自动调整列宽的快捷键
  • 【C++实战⑬】解锁C++文件操作:从基础到实战的进阶之路 - 实践
  • 破解塔吊顶升高危难题!让事故率降 50%、审批快 70%
  • logicFlow________文档2
  • CF2086D Even String
  • logicflow___文档3
  • langraph-up-react
  • 2025年运营商API安全建设最佳实践:某头部省级电信案例解析与方案推荐