File size: 2,689 Bytes
79899c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from asgi_correlation_id import correlation_id
from fastapi import APIRouter
from fastapi.responses import StreamingResponse, JSONResponse

from utils.bio_logger import bio_logger as logger
from utils.i18n_util import (
    get_language,
    create_error_response,
)
from utils.i18n_context import with_language

from bio_requests.chat_request import ChatRequest

from service.chat import ChatService

router = APIRouter(prefix="/mcp", tags=["MCP"])


@router.post("/bio_qa", response_model=None, operation_id="bio_qa_stream_chat")
async def bio_qa(query: str, lang: str = "en"):
    """
    生物医学问答接口,提供RAG问答服务。
    query: 问答内容
    lang: 语言设置,zh代表中文,en代表英文
    """

    logger.info(f"{correlation_id.get()} Bio QA for {query}")
    chat_request = ChatRequest(query=query, language=lang)
    # 解析语言设置
    language = get_language(chat_request.language)

    # 使用上下文管理器设置语言
    with with_language(language):
        try:
            chat_service = ChatService()
            return StreamingResponse(
                chat_service.generate_stream(chat_request),
                media_type="text/event-stream",
                headers={
                    "Connection": "keep-alive",
                    "Cache-Control": "no-cache",
                },
            )
        except Exception as e:
            logger.error(f"{correlation_id.get()} Stream chat error: {e}")
            error_response = create_error_response(
                error_key="service_unavailable",
                details=str(e),
                error_code=500,
            )
            return JSONResponse(content=error_response, status_code=500)


# 添加MCP协议所需的端点
@router.get("/tools")
async def list_tools():
    """列出可用的MCP工具"""
    return {
        "tools": [
            {
                "name": "bio_qa_stream_chat",
                "description": "生物医学问答服务,提供RAG问答功能",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "问题内容"
                        },
                        "lang": {
                            "type": "string",
                            "description": "语言设置,zh代表中文,en代表英文",
                            "enum": ["zh", "en"],
                            "default": "en"
                        }
                    },
                    "required": ["query"]
                }
            }
        ]
    }