|
|
|
|
|
|
|
"""
|
|
Dify API 中转服务
|
|
提供REST API端点,转发请求到Dify API
|
|
"""
|
|
|
|
import os
|
|
import json
|
|
import logging
|
|
from typing import Dict, Any, Optional
|
|
from fastapi import FastAPI, Header, Request, HTTPException, Response
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from pydantic import BaseModel
|
|
import uvicorn
|
|
import configparser
|
|
from dify_api_client import DifyAPIClient, setup_logging
|
|
|
|
|
|
is_hf_space = os.environ.get('SPACE_ID') is not None
|
|
|
|
|
|
app = FastAPI(
|
|
title="Dify API 中转服务",
|
|
description="提供REST API端点,转发请求到Dify API",
|
|
version="1.0.0"
|
|
)
|
|
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
setup_logging(debug=False, disable_file_logging=is_hf_space)
|
|
|
|
|
|
class QueryRequest(BaseModel):
|
|
query: str
|
|
conversation_id: Optional[str] = None
|
|
user: Optional[str] = "user"
|
|
response_mode: Optional[str] = "blocking"
|
|
|
|
|
|
@app.get("/")
|
|
@app.get("/health")
|
|
def health_check():
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.post("/dify_api")
|
|
async def dify_api(
|
|
request: Request,
|
|
query_request: QueryRequest,
|
|
dify_url: Optional[str] = Header(None),
|
|
dify_key: Optional[str] = Header(None)
|
|
):
|
|
|
|
if not dify_url:
|
|
raise HTTPException(status_code=400, detail="缺少必要的请求头: dify_url")
|
|
if not dify_key:
|
|
raise HTTPException(status_code=400, detail="缺少必要的请求头: dify_key")
|
|
|
|
logging.info(f"接收到API请求,目标URL: {dify_url}")
|
|
|
|
try:
|
|
|
|
client = DifyAPIClient(api_key=dify_key, base_url=dify_url)
|
|
|
|
|
|
if query_request.response_mode == "streaming":
|
|
|
|
|
|
|
|
response_text = client.send_request_streaming(
|
|
content=query_request.query,
|
|
conversation_id=query_request.conversation_id,
|
|
user=query_request.user
|
|
)
|
|
return {"answer": response_text}
|
|
else:
|
|
|
|
response_data = client.send_request_blocking(
|
|
content=query_request.query,
|
|
conversation_id=query_request.conversation_id,
|
|
user=query_request.user
|
|
)
|
|
return response_data
|
|
|
|
except Exception as e:
|
|
logging.error(f"处理请求时出错: {str(e)}")
|
|
raise HTTPException(status_code=500, detail=f"处理请求时出错: {str(e)}")
|
|
|
|
|
|
def main():
|
|
|
|
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
|
|
|
|
if __name__ == "__main__":
|
|
main() |