当前位置: 首页 > 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.gsyq.cn/news/9219.html

相关文章:

  • 第二周预习作业
  • AOSP Android12 Source 下载同步
  • 02020404 EF Core基础04-自增主键、Guid主键、混合自增、Hi/Lo算法、Migration深入、数据库其它迁移命令
  • Java中异步任务的执行方式有几种?
  • python爬虫测试
  • [硬件电路-232]:FET(场效应管)的核心机制是通过栅极电压调控半导体“沟道“中的载流子浓度与分布,进而控制源极与漏极之间的电流大小 - 指南
  • 【C++实战⑬】解锁C++文件操作:从基础到实战的进阶之路 - 实践
  • logicFlow________文档2
  • 软件工程第二次作业-第一次个人编程作业
  • 202508_天山固网_to
  • 怎么屏蔽 ahref.com 上你不想看到的网站链接(垃圾外链)
  • 【工具变量】“国家级大数据综合试验区”试点城市DID(2000-2024年) - 教程
  • 《手搓动态顺序表:从数组到自动扩容的华丽转身》 - 详解
  • 《原子习惯》-读书笔记7
  • 201912_EASER
  • 搜索百科(3):Elasticsearch — 搜索界的“流量明星”
  • 打印机漏洞、匿名协议与AWS安全:一周技术热点解析
  • 2025-09-21 网站前几分钟还运行的好好地,几分钟后查看居然显示文件无法加载,访问首页提示无法访问此网站??!==ssl证书过期+域名解析失效
  • [POI 2004] MOS
  • AI 在教育领域的落地困境:个性化教学与资料隐私的平衡之道
  • 2025-06-10.购买联想thinkpad 16p
  • MySQL的Schema是什么? - 公众号
  • 推动安全研究多元化的10万美元捐赠计划
  • 20250919
  • 完整教程:AI+虚拟仿真开启材料工程专业学习与实践新篇章
  • [NOIP2022] 建造军营 解题报告
  • 123213123
  • ​​[硬件电路-240]:为什么高频信号的电路的处理难度要比直流信号、电频信号处理的难度倍增? - 指南
  • 实用指南:EasyCVR在智慧城市中场景中的核心应用与实践方案
  • 03_Angular的突破性优势