n/aiu/dokke · 2025-10-23
注册 登录
n/ai · 2025-10-23 · 363 次浏览
u/dokkefrog荣誉会员钻石

smithery.ai 2api

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import StreamingResponse, JSONResponse
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any, Union
import requests
import json
import time
import uuid
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="OpenAI Compatible API")


# OpenAI 兼容的请求模型
class Message(BaseModel):
    role: str
    content: str
    name: Optional[str] = None


class ChatCompletionRequest(BaseModel):
    model: str = "gpt-3.5-turbo"
    messages: List[Message]
    stream: Optional[bool] = False
    temperature: Optional[float] = Field(default=1.0, ge=0, le=2)
    max_tokens: Optional[int] = Field(default=None, ge=1)
    top_p: Optional[float] = Field(default=1.0, ge=0, le=1)
    n: Optional[int] = Field(default=1, ge=1)
    stop: Optional[Union[str, List[str]]] = None
    presence_penalty: Optional[float] = Field(default=0, ge=-2, le=2)
    frequency_penalty: Optional[float] = Field(default=0, ge=-2, le=2)
    user: Optional[str] = None

    class Config:
        extra = "allow"  # 允许额外字段


# 添加中间件来记录请求
@app.middleware("http")
async def log_requests(request: Request, call_next):
    body = await request.body()
    logger.info(f"Request path: {request.url.path}")
    logger.info(f"Request body: {body.decode('utf-8')}")

    # 重新构造请求以便后续使用
    async def receive():
        return {"type": "http.request", "body": body}

    request._receive = receive

    response = await call_next(request)
    return response


# 转换 OpenAI 格式到 Smithery 格式
def convert_to_smithery_format(openai_request: ChatCompletionRequest) -> dict:
    messages = []
    system_prompt = "You are a helpful assistant."

    for msg in openai_request.messages:
        if msg.role == "system":
            system_prompt = msg.content
        elif msg.role == "user":
            messages.append({
                "parts": [{
                    "type": "text",
                    "text": msg.content
                }],
                "id": str(uuid.uuid4().hex[:16]),
                "role": "user"
            })
        elif msg.role == "assistant":
            messages.append({
                "parts": [{
                    "type": "text",
                    "text": msg.content
                }],
                "id": str(uuid.uuid4().hex[:16]),
                "role": "assistant"
            })

    return {
        "messages": messages,
        "tools": [],
        "model": openai_request.model,
        "systemPrompt": system_prompt
    }


# 流式生成器
async def stream_generator(smithery_payload: dict, headers: dict):
    """流式返回 SSE 格式数据"""
    url = "https://smithery.ai/api/chat"

    try:
        chunk_id = f"chatcmpl-{uuid.uuid4().hex}"

        with requests.post(url, headers=headers, json=smithery_payload, stream=True, timeout=60) as response:
            response.raise_for_status()

            buffer = ""

            for chunk in response.iter_content(chunk_size=1):
                if chunk:
                    buffer += chunk.decode('utf-8')

                    # 构造 OpenAI 兼容的流式响应
                    chunk_data = {
                        "id": chunk_id,
                        "object": "chat.completion.chunk",
                        "created": int(time.time()),
                        "model": "gpt-3.5-turbo",
                        "choices": [{
                            "index": 0,
                            "delta": {
                                "content": chunk.decode('utf-8')
                            },
                            "finish_reason": None
                        }]
                    }

                    yield f"data: {json.dumps(chunk_data)}\n\n"

            # 发送结束标记
            final_chunk = {
                "id": chunk_id,
                "object": "chat.completion.chunk",
                "created": int(time.time()),
                "model": "gpt-3.5-turbo",
                "choices": [{
                    "index": 0,
                    "delta": {},
                    "finish_reason": "stop"
                }]
            }
            yield f"data: {json.dumps(final_chunk)}\n\n"
            yield "data: [DONE]\n\n"

    except Exception as e:
        logger.error(f"Stream error: {str(e)}")
        error_chunk = {
            "error": {
                "message": str(e),
                "type": "server_error",
                "code": 500
            }
        }
        yield f"data: {json.dumps(error_chunk)}\n\n"


# 非流式响应
def get_non_stream_response(smithery_payload: dict, headers: dict) -> dict:
    """非流式返回完整响应"""
    url = "https://smithery.ai/api/chat"

    try:
        response = requests.post(url, headers=headers, json=smithery_payload, timeout=60)
        response.raise_for_status()

        content = response.text

        return {
            "id": f"chatcmpl-{uuid.uuid4().hex}",
            "object": "chat.completion",
            "created": int(time.time()),
            "model": "gpt-3.5-turbo",
            "choices": [{
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": content
                },
                "finish_reason": "stop"
            }],
            "usage": {
                "prompt_tokens": 0,
                "completion_tokens": 0,
                "total_tokens": 0
            }
        }
    except Exception as e:
        logger.error(f"Non-stream error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/v1/chat/completions")
async def chat_completions(request: ChatCompletionRequest):
    """OpenAI 兼容的聊天接口"""

    try:
        logger.info(f"Received request: {request.dict()}")

        # 准备请求头
        headers = {
            'Cookie': 'your-cookie',  # 替换为实际的 Cookie
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Content-Type': 'application/json',
            'Accept': '*/*',
            'Host': 'smithery.ai',
            'Connection': 'keep-alive'
        }

        # 转换请求格式
        smithery_payload = convert_to_smithery_format(request)
        logger.info(f"Smithery payload: {json.dumps(smithery_payload, indent=2)}")

        # 根据 stream 参数决定返回方式
        if request.stream:
            return StreamingResponse(
                stream_generator(smithery_payload, headers),
                media_type="text/event-stream",
                headers={
                    "Cache-Control": "no-cache",
                    "Connection": "keep-alive",
                }
            )
        else:
            result = get_non_stream_response(smithery_payload, headers)
            return result

    except Exception as e:
        logger.error(f"Error in chat_completions: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/chat/completions")
async def chat_completions_no_v1(request: ChatCompletionRequest):
    """兼容不带 /v1 前缀的请求"""
    return await chat_completions(request)


@app.get("/v1/models")
async def list_models():
    """列出可用模型"""
    return {
        "object": "list",
        "data": [
            {
                "id": "claude-haiku-4.5",
                "object": "model",
                "created": int(time.time()),
                "owned_by": "openai"
            },
            {
                "id": "claude-sonnet-4.5",
                "object": "model",
                "created": int(time.time()),
                "owned_by": "openai"
            },
            {
                "id": "gpt-5",
                "object": "model",
                "created": int(time.time()),
                "owned_by": "openai"
            },
            {
                "id": "gpt-5-mini",
                "object": "model",
                "created": int(time.time()),
                "owned_by": "openai"
            },
           {
                "id": "gpt-5-nano",
                "object": "model",
                "created": int(time.time()),
                "owned_by": "openai"
            },
            {
                "id": "gemini-2.5-flash-lite",
                "object": "model",
                "created": int(time.time()),
                "owned_by": "openai"
            },
           {
                "id": "gemini-2.5-pro",
                "object": "model",
                "created": int(time.time()),
                "owned_by": "openai"
            },
            {
                "id": "glm-4.6",
                "object": "model",
                "created": int(time.time()),
                "owned_by": "openai"
            }
        ]
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "ok"}


@app.exception_handler(422)
async def validation_exception_handler(request: Request, exc):
    """自定义 422 错误处理"""
    logger.error(f"Validation error: {exc}")
    return JSONResponse(
        status_code=422,
        content={
            "error": {
                "message": "Invalid request format",
                "type": "invalid_request_error",
                "details": str(exc)
            }
        }
    )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")

注册后 替换cookie 即可 python 还不是很熟练,写起来稍微费劲点,大佬可以对接CC

https://smithery.ai/playground

5
10
登录后参与讨论。
u/udc2b6nr 广告
QuicksilverVPN

快银 VPN,一键连接全球节点,线路稳定、延迟低。支持 Windows、macOS 等多平台,TUN 全局模式覆盖全部应用流量。无需复杂配置,下载即用。

umami.dnsl.top 了解更多

10 条回复

排序
  1. CoolMan 钻石 3 YEARS 2025-10-23

    大佬强!

    1
  2. trial 钻石 钻石会员 2025-10-23

    看看是啥玩

    1
  3. azhaoyihao 钻石 水王 2025-10-23

    这是啥???

    0
  4. dokke frog荣誉会员 钻石 楼主 荣誉会员 2025-10-23

    2api

    0
  5. tyedh two_hearts 铂金 2025-10-23

    不會用,謝謝!

    0
  6. luscious91 铂金 2025-10-23

    这是啥

    0
  7. Arvin_Leung 王者 3 YEARS 2025-10-23

    路过看看,
    用不到啊!!没那么多项目

    0
  8. creminjess 钻石 2025-10-23

    不错,谢谢分享

    0
  9. kof97zip 钻石 2025-10-23

    大佬代码厉害啊

    0
  10. daryenr 黄金 2025-10-25

    看看是什么

    0