Upload 93 files
Browse files- .dockerignore +12 -12
- Dockerfile +20 -20
- HUGGINGFACE_SPACE.md +50 -50
- app/__init__.py +2 -1
- app/api/__init__.py +2 -0
- app/api/billing.py +82 -0
- app/api/graph.py +6 -6
- app/api/pipeline.py +230 -214
- app/api/simulation.py +3 -3
- app/config.py +52 -9
- app/services/billing_service.py +85 -0
- app/services/graph_builder.py +60 -28
- app/services/oasis_profile_generator.py +106 -44
- app/services/pipeline_orchestrator.py +4 -2
- app/services/simulation_config_generator.py +48 -18
- app/services/supabase_jobs.py +176 -176
- app/services/zep_entity_reader.py +450 -438
- app/services/zep_graph_memory_updater.py +22 -9
- app/services/zep_tools.py +19 -7
- app/utils/api_key_runtime.py +150 -0
- app/utils/llm_client.py +18 -11
- app/utils/mirofish_jwt.py +59 -59
- app/utils/supabase_auth.py +80 -80
- requirements.txt +1 -0
- supabase/INSTALL_SIMULATION_RUNS.sql +39 -39
- supabase/grants_public_user.sql +8 -8
- supabase/migration_simulation_runs_user_id_text.sql +13 -13
- supabase/schema.sql +55 -55
.dockerignore
CHANGED
|
@@ -1,12 +1,12 @@
|
|
| 1 |
-
__pycache__
|
| 2 |
-
*.py[cod]
|
| 3 |
-
*.egg-info
|
| 4 |
-
.eggs
|
| 5 |
-
.env
|
| 6 |
-
.venv
|
| 7 |
-
venv
|
| 8 |
-
uploads
|
| 9 |
-
*.log
|
| 10 |
-
.git
|
| 11 |
-
.gitignore
|
| 12 |
-
.pytest_cache
|
|
|
|
| 1 |
+
__pycache__
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*.egg-info
|
| 4 |
+
.eggs
|
| 5 |
+
.env
|
| 6 |
+
.venv
|
| 7 |
+
venv
|
| 8 |
+
uploads
|
| 9 |
+
*.log
|
| 10 |
+
.git
|
| 11 |
+
.gitignore
|
| 12 |
+
.pytest_cache
|
Dockerfile
CHANGED
|
@@ -1,20 +1,20 @@
|
|
| 1 |
-
# MiroFish API — Docker (Hugging Face Spaces, Fly, etc.)
|
| 2 |
-
# Build context must be this backend/ directory (contains app/, wsgi.py, requirements.txt).
|
| 3 |
-
|
| 4 |
-
FROM python:3.11-slim-bookworm
|
| 5 |
-
|
| 6 |
-
WORKDIR /app
|
| 7 |
-
|
| 8 |
-
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 9 |
-
build-essential \
|
| 10 |
-
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
-
|
| 12 |
-
COPY requirements.txt .
|
| 13 |
-
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
-
|
| 15 |
-
COPY . .
|
| 16 |
-
|
| 17 |
-
ENV PYTHONUNBUFFERED=1
|
| 18 |
-
EXPOSE 7860
|
| 19 |
-
|
| 20 |
-
CMD gunicorn --bind "0.0.0.0:${PORT:-7860}" --workers 1 --threads 4 --timeout 600 --worker-tmp-dir /dev/shm wsgi:app
|
|
|
|
| 1 |
+
# MiroFish API — Docker (Hugging Face Spaces, Fly, etc.)
|
| 2 |
+
# Build context must be this backend/ directory (contains app/, wsgi.py, requirements.txt).
|
| 3 |
+
|
| 4 |
+
FROM python:3.11-slim-bookworm
|
| 5 |
+
|
| 6 |
+
WORKDIR /app
|
| 7 |
+
|
| 8 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 9 |
+
build-essential \
|
| 10 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
+
|
| 12 |
+
COPY requirements.txt .
|
| 13 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 14 |
+
|
| 15 |
+
COPY . .
|
| 16 |
+
|
| 17 |
+
ENV PYTHONUNBUFFERED=1
|
| 18 |
+
EXPOSE 7860
|
| 19 |
+
|
| 20 |
+
CMD gunicorn --bind "0.0.0.0:${PORT:-7860}" --workers 1 --threads 4 --timeout 600 --worker-tmp-dir /dev/shm wsgi:app
|
HUGGINGFACE_SPACE.md
CHANGED
|
@@ -1,50 +1,50 @@
|
|
| 1 |
-
# Hugging Face Spaces — MiroFish API (Docker)
|
| 2 |
-
|
| 3 |
-
## Create the Space
|
| 4 |
-
|
| 5 |
-
1. [huggingface.co/spaces](https://huggingface.co/spaces) → **Create new Space**
|
| 6 |
-
2. **SDK**: **Docker**
|
| 7 |
-
3. **Hardware**: CPU (free) — long simulations may OOM or time out; upgrade if needed.
|
| 8 |
-
4. Connect this repo and set the Docker **app directory** to **`backend`** (or copy only `backend/` into a dedicated repo).
|
| 9 |
-
|
| 10 |
-
### Visibility must be **Public** (important)
|
| 11 |
-
|
| 12 |
-
If the Space is **Private**, browsers and your static site get **`401` with body `unauthorized`** (plain text) **before** the request reaches Flask.
|
| 13 |
-
Open **Space → Settings → Visibility** and set **Public** so `https://YOUR-SPACE.hf.space/api/...` works without a Hugging Face login cookie.
|
| 14 |
-
|
| 15 |
-
Build context = folder that contains `Dockerfile`, `requirements.txt`, `app/`, `wsgi.py`.
|
| 16 |
-
|
| 17 |
-
## Secrets (Space → Settings → Variables and secrets)
|
| 18 |
-
|
| 19 |
-
| Variable | Notes |
|
| 20 |
-
|----------|--------|
|
| 21 |
-
| `SECRET_KEY` | Long random string (Flask). |
|
| 22 |
-
| `LLM_API_KEY`, `LLM_BASE_URL`, `LLM_MODEL_NAME` | Your LLM. |
|
| 23 |
-
| `ZEP_API_KEY` | Zep. |
|
| 24 |
-
| `SUPABASE_URL` | `https://xxx.supabase.co` |
|
| 25 |
-
| `SUPABASE_SERVICE_ROLE_KEY` | Service role (never expose to browser). |
|
| 26 |
-
| `PIPELINE_CLIENT_SECRET` | **Same** as website `VITE_PIPELINE_CLIENT_SECRET`. |
|
| 27 |
-
| `SUPABASE_REPORTS_BUCKET` | Default `reports`. |
|
| 28 |
-
| `PIPELINE_MAX_ROUNDS` | Optional integer cap. |
|
| 29 |
-
|
| 30 |
-
Optional: `SUPABASE_JWT_SECRET` if you use Supabase Auth JWT on the pipeline.
|
| 31 |
-
|
| 32 |
-
## Website (`website/.env`)
|
| 33 |
-
|
| 34 |
-
```env
|
| 35 |
-
VITE_API_BASE_URLS=https://YOUR-SPACE.hf.space
|
| 36 |
-
VITE_PIPELINE_CLIENT_SECRET=same-as-PIPELINE_CLIENT_SECRET
|
| 37 |
-
VITE_SUPABASE_URL=https://xxx.supabase.co
|
| 38 |
-
VITE_SUPABASE_ANON_KEY=your_anon_key
|
| 39 |
-
```
|
| 40 |
-
|
| 41 |
-
Login/sign-up use **Supabase** on `public."User"` — run `supabase/grants_public_user.sql` in the SQL editor.
|
| 42 |
-
|
| 43 |
-
## Free tier notes
|
| 44 |
-
|
| 45 |
-
- Space **sleeps** when idle; first request is a cold start.
|
| 46 |
-
- Proxies may **time out** on very long HTTP requests; heavy pipelines may need paid hardware or another host.
|
| 47 |
-
|
| 48 |
-
## Health check
|
| 49 |
-
|
| 50 |
-
`GET /health` → `{"status":"ok",...}`
|
|
|
|
| 1 |
+
# Hugging Face Spaces — MiroFish API (Docker)
|
| 2 |
+
|
| 3 |
+
## Create the Space
|
| 4 |
+
|
| 5 |
+
1. [huggingface.co/spaces](https://huggingface.co/spaces) → **Create new Space**
|
| 6 |
+
2. **SDK**: **Docker**
|
| 7 |
+
3. **Hardware**: CPU (free) — long simulations may OOM or time out; upgrade if needed.
|
| 8 |
+
4. Connect this repo and set the Docker **app directory** to **`backend`** (or copy only `backend/` into a dedicated repo).
|
| 9 |
+
|
| 10 |
+
### Visibility must be **Public** (important)
|
| 11 |
+
|
| 12 |
+
If the Space is **Private**, browsers and your static site get **`401` with body `unauthorized`** (plain text) **before** the request reaches Flask.
|
| 13 |
+
Open **Space → Settings → Visibility** and set **Public** so `https://YOUR-SPACE.hf.space/api/...` works without a Hugging Face login cookie.
|
| 14 |
+
|
| 15 |
+
Build context = folder that contains `Dockerfile`, `requirements.txt`, `app/`, `wsgi.py`.
|
| 16 |
+
|
| 17 |
+
## Secrets (Space → Settings → Variables and secrets)
|
| 18 |
+
|
| 19 |
+
| Variable | Notes |
|
| 20 |
+
|----------|--------|
|
| 21 |
+
| `SECRET_KEY` | Long random string (Flask). |
|
| 22 |
+
| `LLM_API_KEY`, `LLM_BASE_URL`, `LLM_MODEL_NAME` | Your LLM. |
|
| 23 |
+
| `ZEP_API_KEY` | Zep. |
|
| 24 |
+
| `SUPABASE_URL` | `https://xxx.supabase.co` |
|
| 25 |
+
| `SUPABASE_SERVICE_ROLE_KEY` | Service role (never expose to browser). |
|
| 26 |
+
| `PIPELINE_CLIENT_SECRET` | **Same** as website `VITE_PIPELINE_CLIENT_SECRET`. |
|
| 27 |
+
| `SUPABASE_REPORTS_BUCKET` | Default `reports`. |
|
| 28 |
+
| `PIPELINE_MAX_ROUNDS` | Optional integer cap. |
|
| 29 |
+
|
| 30 |
+
Optional: `SUPABASE_JWT_SECRET` if you use Supabase Auth JWT on the pipeline.
|
| 31 |
+
|
| 32 |
+
## Website (`website/.env`)
|
| 33 |
+
|
| 34 |
+
```env
|
| 35 |
+
VITE_API_BASE_URLS=https://YOUR-SPACE.hf.space
|
| 36 |
+
VITE_PIPELINE_CLIENT_SECRET=same-as-PIPELINE_CLIENT_SECRET
|
| 37 |
+
VITE_SUPABASE_URL=https://xxx.supabase.co
|
| 38 |
+
VITE_SUPABASE_ANON_KEY=your_anon_key
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Login/sign-up use **Supabase** on `public."User"` — run `supabase/grants_public_user.sql` in the SQL editor.
|
| 42 |
+
|
| 43 |
+
## Free tier notes
|
| 44 |
+
|
| 45 |
+
- Space **sleeps** when idle; first request is a cold start.
|
| 46 |
+
- Proxies may **time out** on very long HTTP requests; heavy pipelines may need paid hardware or another host.
|
| 47 |
+
|
| 48 |
+
## Health check
|
| 49 |
+
|
| 50 |
+
`GET /health` → `{"status":"ok",...}`
|
app/__init__.py
CHANGED
|
@@ -77,11 +77,12 @@ def create_app(config_class=Config):
|
|
| 77 |
return response
|
| 78 |
|
| 79 |
# 注册蓝图
|
| 80 |
-
from .api import graph_bp, simulation_bp, report_bp, pipeline_bp
|
| 81 |
app.register_blueprint(graph_bp, url_prefix='/api/graph')
|
| 82 |
app.register_blueprint(simulation_bp, url_prefix='/api/simulation')
|
| 83 |
app.register_blueprint(report_bp, url_prefix='/api/report')
|
| 84 |
app.register_blueprint(pipeline_bp, url_prefix='/api/pipeline')
|
|
|
|
| 85 |
|
| 86 |
# 健康检查
|
| 87 |
@app.route('/health')
|
|
|
|
| 77 |
return response
|
| 78 |
|
| 79 |
# 注册蓝图
|
| 80 |
+
from .api import graph_bp, simulation_bp, report_bp, pipeline_bp, billing_bp
|
| 81 |
app.register_blueprint(graph_bp, url_prefix='/api/graph')
|
| 82 |
app.register_blueprint(simulation_bp, url_prefix='/api/simulation')
|
| 83 |
app.register_blueprint(report_bp, url_prefix='/api/report')
|
| 84 |
app.register_blueprint(pipeline_bp, url_prefix='/api/pipeline')
|
| 85 |
+
app.register_blueprint(billing_bp, url_prefix='/api/billing')
|
| 86 |
|
| 87 |
# 健康检查
|
| 88 |
@app.route('/health')
|
app/api/__init__.py
CHANGED
|
@@ -8,9 +8,11 @@ graph_bp = Blueprint('graph', __name__)
|
|
| 8 |
simulation_bp = Blueprint('simulation', __name__)
|
| 9 |
report_bp = Blueprint('report', __name__)
|
| 10 |
pipeline_bp = Blueprint('pipeline', __name__)
|
|
|
|
| 11 |
|
| 12 |
from . import graph # noqa: E402, F401
|
| 13 |
from . import simulation # noqa: E402, F401
|
| 14 |
from . import report # noqa: E402, F401
|
| 15 |
from . import pipeline # noqa: E402, F401
|
|
|
|
| 16 |
|
|
|
|
| 8 |
simulation_bp = Blueprint('simulation', __name__)
|
| 9 |
report_bp = Blueprint('report', __name__)
|
| 10 |
pipeline_bp = Blueprint('pipeline', __name__)
|
| 11 |
+
billing_bp = Blueprint('billing', __name__)
|
| 12 |
|
| 13 |
from . import graph # noqa: E402, F401
|
| 14 |
from . import simulation # noqa: E402, F401
|
| 15 |
from . import report # noqa: E402, F401
|
| 16 |
from . import pipeline # noqa: E402, F401
|
| 17 |
+
from . import billing # noqa: E402, F401
|
| 18 |
|
app/api/billing.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Razorpay + coupon unlock for /api/pipeline/start."""
|
| 2 |
+
|
| 3 |
+
from flask import request, jsonify
|
| 4 |
+
|
| 5 |
+
from . import billing_bp
|
| 6 |
+
from ..config import Config
|
| 7 |
+
from ..services import billing_service
|
| 8 |
+
from ..utils.logger import get_logger
|
| 9 |
+
|
| 10 |
+
logger = get_logger("mirofish.api.billing")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@billing_bp.route("/status", methods=["GET"])
|
| 14 |
+
def billing_status():
|
| 15 |
+
if not Config.billing_enabled():
|
| 16 |
+
return jsonify(
|
| 17 |
+
{
|
| 18 |
+
"success": True,
|
| 19 |
+
"data": {
|
| 20 |
+
"enabled": False,
|
| 21 |
+
"key_id": None,
|
| 22 |
+
"amount": None,
|
| 23 |
+
"currency": None,
|
| 24 |
+
},
|
| 25 |
+
}
|
| 26 |
+
)
|
| 27 |
+
data = {
|
| 28 |
+
"enabled": True,
|
| 29 |
+
"key_id": Config.RAZORPAY_KEY_ID or None,
|
| 30 |
+
"amount": Config.RAZORPAY_AMOUNT_PAISE if Config.RAZORPAY_KEY_SECRET else None,
|
| 31 |
+
"currency": Config.RAZORPAY_CURRENCY if Config.RAZORPAY_KEY_SECRET else None,
|
| 32 |
+
"coupons_enabled": bool(Config.payment_coupon_set()),
|
| 33 |
+
}
|
| 34 |
+
return jsonify({"success": True, "data": data})
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@billing_bp.route("/create-order", methods=["POST"])
|
| 38 |
+
def billing_create_order():
|
| 39 |
+
try:
|
| 40 |
+
if not (Config.RAZORPAY_KEY_ID and Config.RAZORPAY_KEY_SECRET):
|
| 41 |
+
return jsonify({"success": False, "error": "Razorpay is not configured"}), 503
|
| 42 |
+
order = billing_service.create_razorpay_order()
|
| 43 |
+
return jsonify({"success": True, "data": order})
|
| 44 |
+
except Exception as e:
|
| 45 |
+
logger.error("create-order: %s", e)
|
| 46 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@billing_bp.route("/verify-payment", methods=["POST"])
|
| 50 |
+
def billing_verify_payment():
|
| 51 |
+
try:
|
| 52 |
+
if not (Config.RAZORPAY_KEY_ID and Config.RAZORPAY_KEY_SECRET):
|
| 53 |
+
return jsonify({"success": False, "error": "Razorpay is not configured"}), 503
|
| 54 |
+
body = request.get_json(silent=True) or {}
|
| 55 |
+
oid = (body.get("razorpay_order_id") or "").strip()
|
| 56 |
+
pid = (body.get("razorpay_payment_id") or "").strip()
|
| 57 |
+
sig = (body.get("razorpay_signature") or "").strip()
|
| 58 |
+
if not oid or not pid or not sig:
|
| 59 |
+
return jsonify({"success": False, "error": "Missing payment fields"}), 400
|
| 60 |
+
if not billing_service.verify_razorpay_payment_signature(oid, pid, sig):
|
| 61 |
+
return jsonify({"success": False, "error": "Invalid payment signature"}), 400
|
| 62 |
+
token = billing_service.issue_simulation_payment_token(via="razorpay")
|
| 63 |
+
return jsonify({"success": True, "data": {"simulation_payment_token": token}})
|
| 64 |
+
except Exception as e:
|
| 65 |
+
logger.error("verify-payment: %s", e)
|
| 66 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@billing_bp.route("/apply-coupon", methods=["POST"])
|
| 70 |
+
def billing_apply_coupon():
|
| 71 |
+
try:
|
| 72 |
+
if not Config.payment_coupon_set():
|
| 73 |
+
return jsonify({"success": False, "error": "Coupons are not configured"}), 503
|
| 74 |
+
body = request.get_json(silent=True) or {}
|
| 75 |
+
code = body.get("code") or body.get("coupon") or ""
|
| 76 |
+
if not billing_service.coupon_valid(str(code)):
|
| 77 |
+
return jsonify({"success": False, "error": "Invalid coupon code"}), 400
|
| 78 |
+
token = billing_service.issue_simulation_payment_token(via="coupon")
|
| 79 |
+
return jsonify({"success": True, "data": {"simulation_payment_token": token}})
|
| 80 |
+
except Exception as e:
|
| 81 |
+
logger.error("apply-coupon: %s", e)
|
| 82 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
app/api/graph.py
CHANGED
|
@@ -284,7 +284,7 @@ def build_graph():
|
|
| 284 |
|
| 285 |
# 检查配置
|
| 286 |
errors = []
|
| 287 |
-
if not Config.
|
| 288 |
errors.append("ZEP_API_KEY未配置")
|
| 289 |
if errors:
|
| 290 |
logger.error(f"配置错误: {errors}")
|
|
@@ -382,7 +382,7 @@ def build_graph():
|
|
| 382 |
)
|
| 383 |
|
| 384 |
# 创建图谱构建服务
|
| 385 |
-
builder = GraphBuilderService(api_key=Config.
|
| 386 |
|
| 387 |
# 分块
|
| 388 |
task_manager.update_task(
|
|
@@ -567,13 +567,13 @@ def get_graph_data(graph_id: str):
|
|
| 567 |
获取图谱数据(节点和边)
|
| 568 |
"""
|
| 569 |
try:
|
| 570 |
-
if not Config.
|
| 571 |
return jsonify({
|
| 572 |
"success": False,
|
| 573 |
"error": "ZEP_API_KEY未配置"
|
| 574 |
}), 500
|
| 575 |
|
| 576 |
-
builder = GraphBuilderService(api_key=Config.
|
| 577 |
graph_data = builder.get_graph_data(graph_id)
|
| 578 |
|
| 579 |
return jsonify({
|
|
@@ -595,13 +595,13 @@ def delete_graph(graph_id: str):
|
|
| 595 |
删除Zep图谱
|
| 596 |
"""
|
| 597 |
try:
|
| 598 |
-
if not Config.
|
| 599 |
return jsonify({
|
| 600 |
"success": False,
|
| 601 |
"error": "ZEP_API_KEY未配置"
|
| 602 |
}), 500
|
| 603 |
|
| 604 |
-
builder = GraphBuilderService(api_key=Config.
|
| 605 |
builder.delete_graph(graph_id)
|
| 606 |
|
| 607 |
return jsonify({
|
|
|
|
| 284 |
|
| 285 |
# 检查配置
|
| 286 |
errors = []
|
| 287 |
+
if not Config.get_zep_api_keys():
|
| 288 |
errors.append("ZEP_API_KEY未配置")
|
| 289 |
if errors:
|
| 290 |
logger.error(f"配置错误: {errors}")
|
|
|
|
| 382 |
)
|
| 383 |
|
| 384 |
# 创建图谱构建服务
|
| 385 |
+
builder = GraphBuilderService(api_key=Config.get_zep_api_keys()[0])
|
| 386 |
|
| 387 |
# 分块
|
| 388 |
task_manager.update_task(
|
|
|
|
| 567 |
获取图谱数据(节点和边)
|
| 568 |
"""
|
| 569 |
try:
|
| 570 |
+
if not Config.get_zep_api_keys():
|
| 571 |
return jsonify({
|
| 572 |
"success": False,
|
| 573 |
"error": "ZEP_API_KEY未配置"
|
| 574 |
}), 500
|
| 575 |
|
| 576 |
+
builder = GraphBuilderService(api_key=Config.get_zep_api_keys()[0])
|
| 577 |
graph_data = builder.get_graph_data(graph_id)
|
| 578 |
|
| 579 |
return jsonify({
|
|
|
|
| 595 |
删除Zep图谱
|
| 596 |
"""
|
| 597 |
try:
|
| 598 |
+
if not Config.get_zep_api_keys():
|
| 599 |
return jsonify({
|
| 600 |
"success": False,
|
| 601 |
"error": "ZEP_API_KEY未配置"
|
| 602 |
}), 500
|
| 603 |
|
| 604 |
+
builder = GraphBuilderService(api_key=Config.get_zep_api_keys()[0])
|
| 605 |
builder.delete_graph(graph_id)
|
| 606 |
|
| 607 |
return jsonify({
|
app/api/pipeline.py
CHANGED
|
@@ -1,214 +1,230 @@
|
|
| 1 |
-
"""
|
| 2 |
-
One-shot pipeline API for the website: upload text + requirement → full automation → report.
|
| 3 |
-
|
| 4 |
-
When Supabase sync is configured (URL + service role), records runs + reports.
|
| 5 |
-
Identify users: Bearer JWT (Mirofish / Supabase Auth) or X-Mirofish-User-Id + X-Pipeline-Client-Secret.
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
-
import threading
|
| 9 |
-
import traceback
|
| 10 |
-
import uuid
|
| 11 |
-
|
| 12 |
-
from flask import request, jsonify
|
| 13 |
-
|
| 14 |
-
from . import pipeline_bp
|
| 15 |
-
from ..models.task import TaskManager, TaskStatus
|
| 16 |
-
from ..services.pipeline_orchestrator import run_full_pipeline
|
| 17 |
-
from ..services.supabase_jobs import (
|
| 18 |
-
get_run_row_for_user,
|
| 19 |
-
insert_pending_run,
|
| 20 |
-
list_simulation_runs_for_user,
|
| 21 |
-
signed_url_for_storage_path,
|
| 22 |
-
sync_enabled,
|
| 23 |
-
)
|
| 24 |
-
from ..
|
| 25 |
-
from ..
|
| 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 |
-
if not
|
| 62 |
-
return jsonify(
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
document_text = raw.decode("utf-8"
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
if
|
| 82 |
-
return jsonify({"success": False, "error": "
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
if
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
@pipeline_bp.route("/runs
|
| 194 |
-
def
|
| 195 |
-
"""
|
| 196 |
-
try:
|
| 197 |
-
if not sync_enabled():
|
| 198 |
-
return jsonify({"success":
|
| 199 |
-
uid, err = resolve_pipeline_user_id()
|
| 200 |
-
if err or not uid:
|
| 201 |
-
return jsonify({"success": False, "error": err or "Unauthorized"}), 401
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
One-shot pipeline API for the website: upload text + requirement → full automation → report.
|
| 3 |
+
|
| 4 |
+
When Supabase sync is configured (URL + service role), records runs + reports.
|
| 5 |
+
Identify users: Bearer JWT (Mirofish / Supabase Auth) or X-Mirofish-User-Id + X-Pipeline-Client-Secret.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import threading
|
| 9 |
+
import traceback
|
| 10 |
+
import uuid
|
| 11 |
+
|
| 12 |
+
from flask import request, jsonify
|
| 13 |
+
|
| 14 |
+
from . import pipeline_bp
|
| 15 |
+
from ..models.task import TaskManager, TaskStatus
|
| 16 |
+
from ..services.pipeline_orchestrator import run_full_pipeline
|
| 17 |
+
from ..services.supabase_jobs import (
|
| 18 |
+
get_run_row_for_user,
|
| 19 |
+
insert_pending_run,
|
| 20 |
+
list_simulation_runs_for_user,
|
| 21 |
+
signed_url_for_storage_path,
|
| 22 |
+
sync_enabled,
|
| 23 |
+
)
|
| 24 |
+
from ..config import Config
|
| 25 |
+
from ..services.billing_service import verify_simulation_payment_token
|
| 26 |
+
from ..utils.logger import get_logger
|
| 27 |
+
from ..utils.supabase_auth import resolve_pipeline_user_id
|
| 28 |
+
|
| 29 |
+
logger = get_logger("mirofish.api.pipeline")
|
| 30 |
+
|
| 31 |
+
ALLOWED = {"txt", "md", "text"}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _allowed(name: str) -> bool:
|
| 35 |
+
if not name or "." not in name:
|
| 36 |
+
return False
|
| 37 |
+
ext = name.rsplit(".", 1)[-1].lower()
|
| 38 |
+
return ext in ALLOWED
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@pipeline_bp.route("/start", methods=["POST"])
|
| 42 |
+
def pipeline_start():
|
| 43 |
+
"""
|
| 44 |
+
multipart/form-data:
|
| 45 |
+
- file: .txt (or .md) reality seed
|
| 46 |
+
- simulation_requirement: string
|
| 47 |
+
|
| 48 |
+
When Supabase sync is enabled: Bearer JWT (optional) or headers
|
| 49 |
+
X-Mirofish-User-Id + X-Pipeline-Client-Secret (same secret as PIPELINE_CLIENT_SECRET).
|
| 50 |
+
|
| 51 |
+
Returns { task_id, simulation_run_id? }.
|
| 52 |
+
"""
|
| 53 |
+
try:
|
| 54 |
+
simulation_requirement = ""
|
| 55 |
+
document_text = ""
|
| 56 |
+
filename = "seed.txt"
|
| 57 |
+
|
| 58 |
+
if request.content_type and "multipart/form-data" in request.content_type:
|
| 59 |
+
simulation_requirement = (request.form.get("simulation_requirement") or "").strip()
|
| 60 |
+
f = request.files.get("file")
|
| 61 |
+
if not f or not f.filename:
|
| 62 |
+
return jsonify({"success": False, "error": "Missing file"}), 400
|
| 63 |
+
if not _allowed(f.filename):
|
| 64 |
+
return jsonify(
|
| 65 |
+
{"success": False, "error": "Only .txt or .md files are allowed for this endpoint"}
|
| 66 |
+
), 400
|
| 67 |
+
filename = f.filename
|
| 68 |
+
raw = f.read()
|
| 69 |
+
try:
|
| 70 |
+
document_text = raw.decode("utf-8")
|
| 71 |
+
except UnicodeDecodeError:
|
| 72 |
+
document_text = raw.decode("utf-8", errors="replace")
|
| 73 |
+
else:
|
| 74 |
+
data = request.get_json(silent=True) or {}
|
| 75 |
+
simulation_requirement = (data.get("simulation_requirement") or "").strip()
|
| 76 |
+
document_text = (data.get("document_text") or "").strip()
|
| 77 |
+
filename = (data.get("filename") or "seed.txt").strip() or "seed.txt"
|
| 78 |
+
if not document_text:
|
| 79 |
+
return jsonify({"success": False, "error": "document_text is required"}), 400
|
| 80 |
+
|
| 81 |
+
if not simulation_requirement:
|
| 82 |
+
return jsonify({"success": False, "error": "simulation_requirement is required"}), 400
|
| 83 |
+
if len(document_text.strip()) < 10:
|
| 84 |
+
return jsonify({"success": False, "error": "Document text is too short"}), 400
|
| 85 |
+
|
| 86 |
+
if Config.billing_enabled():
|
| 87 |
+
if request.content_type and "multipart/form-data" in request.content_type:
|
| 88 |
+
pay_tok = (request.form.get("simulation_payment_token") or "").strip()
|
| 89 |
+
else:
|
| 90 |
+
_jd = request.get_json(silent=True) or {}
|
| 91 |
+
pay_tok = (_jd.get("simulation_payment_token") or "").strip()
|
| 92 |
+
if not verify_simulation_payment_token(pay_tok):
|
| 93 |
+
return jsonify(
|
| 94 |
+
{
|
| 95 |
+
"success": False,
|
| 96 |
+
"error": "Complete payment or apply a valid coupon before starting a simulation.",
|
| 97 |
+
}
|
| 98 |
+
), 402
|
| 99 |
+
|
| 100 |
+
user_id = None
|
| 101 |
+
simulation_run_id = None
|
| 102 |
+
if sync_enabled():
|
| 103 |
+
uid, err = resolve_pipeline_user_id()
|
| 104 |
+
if err or not uid:
|
| 105 |
+
return jsonify({"success": False, "error": err or "Unauthorized"}), 401
|
| 106 |
+
user_id = uid
|
| 107 |
+
simulation_run_id = str(uuid.uuid4())
|
| 108 |
+
|
| 109 |
+
tm = TaskManager()
|
| 110 |
+
task_id = tm.create_task(
|
| 111 |
+
task_type="full_pipeline",
|
| 112 |
+
metadata={
|
| 113 |
+
"filename": filename,
|
| 114 |
+
"simulation_run_id": simulation_run_id,
|
| 115 |
+
"user_id": user_id,
|
| 116 |
+
},
|
| 117 |
+
)
|
| 118 |
+
tm.update_task(
|
| 119 |
+
task_id,
|
| 120 |
+
status=TaskStatus.PROCESSING,
|
| 121 |
+
progress=1,
|
| 122 |
+
message="Pipeline queued…",
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
if sync_enabled() and simulation_run_id and user_id:
|
| 126 |
+
try:
|
| 127 |
+
insert_pending_run(
|
| 128 |
+
simulation_run_id=simulation_run_id,
|
| 129 |
+
user_id=user_id,
|
| 130 |
+
backend_task_id=task_id,
|
| 131 |
+
requirement_preview=simulation_requirement,
|
| 132 |
+
)
|
| 133 |
+
except Exception as e:
|
| 134 |
+
logger.error("Supabase insert_pending_run: %s", e)
|
| 135 |
+
tm.fail_task(task_id, f"Could not record run: {e}")
|
| 136 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
| 137 |
+
|
| 138 |
+
def worker():
|
| 139 |
+
run_full_pipeline(
|
| 140 |
+
simulation_requirement=simulation_requirement,
|
| 141 |
+
document_text=document_text,
|
| 142 |
+
source_filename=filename,
|
| 143 |
+
task_id=task_id,
|
| 144 |
+
task_manager=tm,
|
| 145 |
+
simulation_run_id=simulation_run_id,
|
| 146 |
+
user_id=user_id,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
threading.Thread(target=worker, daemon=True).start()
|
| 150 |
+
|
| 151 |
+
sync = sync_enabled()
|
| 152 |
+
payload = {
|
| 153 |
+
"task_id": task_id,
|
| 154 |
+
"supabase_sync": sync,
|
| 155 |
+
"message": (
|
| 156 |
+
"Simulation started. Runs are saved to Supabase when cloud sync is enabled."
|
| 157 |
+
if sync
|
| 158 |
+
else "Simulation started. Cloud sync is OFF — add SUPABASE_URL + SUPABASE_SERVICE_ROLE_KEY on the server to record runs in Past simulations."
|
| 159 |
+
),
|
| 160 |
+
}
|
| 161 |
+
if simulation_run_id:
|
| 162 |
+
payload["simulation_run_id"] = simulation_run_id
|
| 163 |
+
|
| 164 |
+
if sync:
|
| 165 |
+
logger.info(
|
| 166 |
+
"pipeline/start task=%s simulation_run_id=%s user_id=%s",
|
| 167 |
+
task_id,
|
| 168 |
+
simulation_run_id,
|
| 169 |
+
user_id,
|
| 170 |
+
)
|
| 171 |
+
else:
|
| 172 |
+
logger.warning(
|
| 173 |
+
"pipeline/start task=%s without Supabase sync — no simulation_runs row (set SUPABASE_* env)",
|
| 174 |
+
task_id,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
return jsonify({"success": True, "data": payload})
|
| 178 |
+
except Exception as e:
|
| 179 |
+
logger.error(traceback.format_exc())
|
| 180 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
@pipeline_bp.route("/status/<task_id>", methods=["GET"])
|
| 184 |
+
def pipeline_status(task_id: str):
|
| 185 |
+
tm = TaskManager()
|
| 186 |
+
task = tm.get_task(task_id)
|
| 187 |
+
if not task:
|
| 188 |
+
return jsonify({"success": False, "error": "Unknown task_id"}), 404
|
| 189 |
+
out = task.to_dict()
|
| 190 |
+
return jsonify({"success": True, "data": out})
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@pipeline_bp.route("/runs", methods=["GET"])
|
| 194 |
+
def pipeline_list_runs():
|
| 195 |
+
"""List simulation_runs for the authenticated user (service role query on server)."""
|
| 196 |
+
try:
|
| 197 |
+
if not sync_enabled():
|
| 198 |
+
return jsonify({"success": True, "data": {"runs": [], "supabase_sync": False}})
|
| 199 |
+
uid, err = resolve_pipeline_user_id()
|
| 200 |
+
if err or not uid:
|
| 201 |
+
return jsonify({"success": False, "error": err or "Unauthorized"}), 401
|
| 202 |
+
runs = list_simulation_runs_for_user(user_id=uid)
|
| 203 |
+
return jsonify({"success": True, "data": {"runs": runs, "supabase_sync": True}})
|
| 204 |
+
except Exception as e:
|
| 205 |
+
logger.error(traceback.format_exc())
|
| 206 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@pipeline_bp.route("/runs/<run_id>/signed-download", methods=["GET"])
|
| 210 |
+
def pipeline_signed_report_download(run_id: str):
|
| 211 |
+
"""Return a time-limited signed URL for the report object in Storage."""
|
| 212 |
+
try:
|
| 213 |
+
if not sync_enabled():
|
| 214 |
+
return jsonify({"success": False, "error": "Sync not configured"}), 503
|
| 215 |
+
uid, err = resolve_pipeline_user_id()
|
| 216 |
+
if err or not uid:
|
| 217 |
+
return jsonify({"success": False, "error": err or "Unauthorized"}), 401
|
| 218 |
+
row = get_run_row_for_user(run_id=run_id, user_id=uid)
|
| 219 |
+
if not row:
|
| 220 |
+
return jsonify({"success": False, "error": "Run not found"}), 404
|
| 221 |
+
path = row.get("report_storage_path") or ""
|
| 222 |
+
if not path:
|
| 223 |
+
return jsonify({"success": False, "error": "Report not ready"}), 400
|
| 224 |
+
url = signed_url_for_storage_path(storage_path=path, expires_sec=3600)
|
| 225 |
+
if not url:
|
| 226 |
+
return jsonify({"success": False, "error": "Could not create download link"}), 500
|
| 227 |
+
return jsonify({"success": True, "data": {"signed_url": url}})
|
| 228 |
+
except Exception as e:
|
| 229 |
+
logger.error(traceback.format_exc())
|
| 230 |
+
return jsonify({"success": False, "error": str(e)}), 500
|
app/api/simulation.py
CHANGED
|
@@ -63,7 +63,7 @@ def get_graph_entities(graph_id: str):
|
|
| 63 |
enrich: 是否获取相关边信息(默认true)
|
| 64 |
"""
|
| 65 |
try:
|
| 66 |
-
if not Config.
|
| 67 |
return jsonify({
|
| 68 |
"success": False,
|
| 69 |
"error": "ZEP_API_KEY未配置"
|
|
@@ -100,7 +100,7 @@ def get_graph_entities(graph_id: str):
|
|
| 100 |
def get_entity_detail(graph_id: str, entity_uuid: str):
|
| 101 |
"""获取单个实体的详细信息"""
|
| 102 |
try:
|
| 103 |
-
if not Config.
|
| 104 |
return jsonify({
|
| 105 |
"success": False,
|
| 106 |
"error": "ZEP_API_KEY未配置"
|
|
@@ -133,7 +133,7 @@ def get_entity_detail(graph_id: str, entity_uuid: str):
|
|
| 133 |
def get_entities_by_type(graph_id: str, entity_type: str):
|
| 134 |
"""获取指定类型的所有实体"""
|
| 135 |
try:
|
| 136 |
-
if not Config.
|
| 137 |
return jsonify({
|
| 138 |
"success": False,
|
| 139 |
"error": "ZEP_API_KEY未配置"
|
|
|
|
| 63 |
enrich: 是否获取相关边信息(默认true)
|
| 64 |
"""
|
| 65 |
try:
|
| 66 |
+
if not Config.get_zep_api_keys():
|
| 67 |
return jsonify({
|
| 68 |
"success": False,
|
| 69 |
"error": "ZEP_API_KEY未配置"
|
|
|
|
| 100 |
def get_entity_detail(graph_id: str, entity_uuid: str):
|
| 101 |
"""获取单个实体的详细信息"""
|
| 102 |
try:
|
| 103 |
+
if not Config.get_zep_api_keys():
|
| 104 |
return jsonify({
|
| 105 |
"success": False,
|
| 106 |
"error": "ZEP_API_KEY未配置"
|
|
|
|
| 133 |
def get_entities_by_type(graph_id: str, entity_type: str):
|
| 134 |
"""获取指定类型的所有实体"""
|
| 135 |
try:
|
| 136 |
+
if not Config.get_zep_api_keys():
|
| 137 |
return jsonify({
|
| 138 |
"success": False,
|
| 139 |
"error": "ZEP_API_KEY未配置"
|
app/config.py
CHANGED
|
@@ -27,21 +27,64 @@ class Config:
|
|
| 27 |
# JSON配置 - 禁用ASCII转义,让中文直接显示(而不是 \uXXXX 格式)
|
| 28 |
JSON_AS_ASCII = False
|
| 29 |
|
| 30 |
-
# LLM
|
|
|
|
|
|
|
| 31 |
LLM_API_KEY = os.environ.get('LLM_API_KEY')
|
| 32 |
LLM_BASE_URL = os.environ.get('LLM_BASE_URL', 'https://api.openai.com/v1')
|
| 33 |
LLM_MODEL_NAME = os.environ.get('LLM_MODEL_NAME', 'gpt-4o-mini')
|
| 34 |
-
|
| 35 |
-
# Zep
|
|
|
|
|
|
|
| 36 |
ZEP_API_KEY = os.environ.get('ZEP_API_KEY')
|
| 37 |
|
| 38 |
@classmethod
|
| 39 |
def get_zep_api_keys(cls):
|
| 40 |
-
|
|
|
|
|
|
|
| 41 |
raw = (cls.ZEP_API_KEY or "").strip()
|
| 42 |
if not raw:
|
| 43 |
return []
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# 文件上传配置
|
| 47 |
MAX_CONTENT_LENGTH = 50 * 1024 * 1024 # 50MB
|
|
@@ -90,9 +133,9 @@ class Config:
|
|
| 90 |
def validate(cls):
|
| 91 |
"""验证必要配置"""
|
| 92 |
errors = []
|
| 93 |
-
if not cls.
|
| 94 |
-
errors.append("LLM_API_KEY 未配置")
|
| 95 |
-
if not cls.
|
| 96 |
-
errors.append("ZEP_API_KEY 未配置")
|
| 97 |
return errors
|
| 98 |
|
|
|
|
| 27 |
# JSON配置 - 禁用ASCII转义,让中文直接显示(而不是 \uXXXX 格式)
|
| 28 |
JSON_AS_ASCII = False
|
| 29 |
|
| 30 |
+
# LLM(OpenAI 兼容)。优先使用 LLM_1 / LLM_2,避免逗号拼接误配
|
| 31 |
+
LLM_1 = os.environ.get("LLM_1", "").strip()
|
| 32 |
+
LLM_2 = os.environ.get("LLM_2", "").strip()
|
| 33 |
LLM_API_KEY = os.environ.get('LLM_API_KEY')
|
| 34 |
LLM_BASE_URL = os.environ.get('LLM_BASE_URL', 'https://api.openai.com/v1')
|
| 35 |
LLM_MODEL_NAME = os.environ.get('LLM_MODEL_NAME', 'gpt-4o-mini')
|
| 36 |
+
|
| 37 |
+
# Zep:优先 ZEP_1 / ZEP_2
|
| 38 |
+
ZEP_1 = os.environ.get("ZEP_1", "").strip()
|
| 39 |
+
ZEP_2 = os.environ.get("ZEP_2", "").strip()
|
| 40 |
ZEP_API_KEY = os.environ.get('ZEP_API_KEY')
|
| 41 |
|
| 42 |
@classmethod
|
| 43 |
def get_zep_api_keys(cls):
|
| 44 |
+
keys = [k for k in (cls.ZEP_1, cls.ZEP_2) if k]
|
| 45 |
+
if keys:
|
| 46 |
+
return keys
|
| 47 |
raw = (cls.ZEP_API_KEY or "").strip()
|
| 48 |
if not raw:
|
| 49 |
return []
|
| 50 |
+
if "," in raw:
|
| 51 |
+
return [k.strip() for k in raw.split(",") if k.strip()]
|
| 52 |
+
return [raw]
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def get_llm_api_keys(cls):
|
| 56 |
+
keys = [k for k in (cls.LLM_1, cls.LLM_2) if k]
|
| 57 |
+
if keys:
|
| 58 |
+
return keys
|
| 59 |
+
raw = (cls.LLM_API_KEY or "").strip()
|
| 60 |
+
if not raw:
|
| 61 |
+
return []
|
| 62 |
+
if "," in raw:
|
| 63 |
+
return [k.strip() for k in raw.split(",") if k.strip()]
|
| 64 |
+
return [raw]
|
| 65 |
+
|
| 66 |
+
# Razorpay + simulation unlock (website)
|
| 67 |
+
RAZORPAY_KEY_ID = os.environ.get("RAZORPAY_KEY_ID", "").strip()
|
| 68 |
+
RAZORPAY_KEY_SECRET = os.environ.get("RAZORPAY_KEY_SECRET", "").strip()
|
| 69 |
+
RAZORPAY_AMOUNT_PAISE = int(os.environ.get("RAZORPAY_AMOUNT_PAISE", "49900"))
|
| 70 |
+
RAZORPAY_CURRENCY = os.environ.get("RAZORPAY_CURRENCY", "INR").strip() or "INR"
|
| 71 |
+
PAYMENT_COUPON_CODES = os.environ.get("PAYMENT_COUPON_CODES", "").strip()
|
| 72 |
+
PAYMENT_JWT_SECRET = os.environ.get("PAYMENT_JWT_SECRET", "").strip()
|
| 73 |
+
|
| 74 |
+
@classmethod
|
| 75 |
+
def payment_coupon_set(cls):
|
| 76 |
+
if not cls.PAYMENT_COUPON_CODES:
|
| 77 |
+
return set()
|
| 78 |
+
return {c.strip().lower() for c in cls.PAYMENT_COUPON_CODES.split(",") if c.strip()}
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def billing_enabled(cls) -> bool:
|
| 82 |
+
razorpay_ok = bool(cls.RAZORPAY_KEY_ID and cls.RAZORPAY_KEY_SECRET)
|
| 83 |
+
return razorpay_ok or bool(cls.payment_coupon_set())
|
| 84 |
+
|
| 85 |
+
@classmethod
|
| 86 |
+
def payment_signing_secret(cls) -> str:
|
| 87 |
+
return (cls.PAYMENT_JWT_SECRET or cls.PIPELINE_CLIENT_SECRET or cls.SECRET_KEY or "mirofish-pay").strip()
|
| 88 |
|
| 89 |
# 文件上传配置
|
| 90 |
MAX_CONTENT_LENGTH = 50 * 1024 * 1024 # 50MB
|
|
|
|
| 133 |
def validate(cls):
|
| 134 |
"""验证必要配置"""
|
| 135 |
errors = []
|
| 136 |
+
if not cls.get_llm_api_keys():
|
| 137 |
+
errors.append("LLM_1 / LLM_2 or LLM_API_KEY 未配置")
|
| 138 |
+
if not cls.get_zep_api_keys():
|
| 139 |
+
errors.append("ZEP_1 / ZEP_2 or ZEP_API_KEY 未配置")
|
| 140 |
return errors
|
| 141 |
|
app/services/billing_service.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Razorpay orders, signature verification, coupon checks, and simulation payment JWTs."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import time
|
| 6 |
+
import uuid
|
| 7 |
+
|
| 8 |
+
import jwt
|
| 9 |
+
|
| 10 |
+
from ..config import Config
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def issue_simulation_payment_token(*, via: str) -> str:
|
| 14 |
+
"""via: 'razorpay' | 'coupon'"""
|
| 15 |
+
now = int(time.time())
|
| 16 |
+
payload = {
|
| 17 |
+
"typ": "sim_pay",
|
| 18 |
+
"via": via,
|
| 19 |
+
"iat": now,
|
| 20 |
+
"exp": now + 3600,
|
| 21 |
+
"jti": uuid.uuid4().hex,
|
| 22 |
+
}
|
| 23 |
+
return jwt.encode(payload, Config.payment_signing_secret(), algorithm="HS256")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def verify_simulation_payment_token(token: str | None) -> bool:
|
| 27 |
+
if not token or not str(token).strip():
|
| 28 |
+
return False
|
| 29 |
+
try:
|
| 30 |
+
payload = jwt.decode(
|
| 31 |
+
str(token).strip(),
|
| 32 |
+
Config.payment_signing_secret(),
|
| 33 |
+
algorithms=["HS256"],
|
| 34 |
+
)
|
| 35 |
+
return payload.get("typ") == "sim_pay"
|
| 36 |
+
except jwt.PyJWTError:
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def create_razorpay_order() -> dict:
|
| 41 |
+
import razorpay
|
| 42 |
+
|
| 43 |
+
client = razorpay.Client(auth=(Config.RAZORPAY_KEY_ID, Config.RAZORPAY_KEY_SECRET))
|
| 44 |
+
receipt = f"mf_{uuid.uuid4().hex[:24]}"
|
| 45 |
+
order = client.order.create(
|
| 46 |
+
{
|
| 47 |
+
"amount": Config.RAZORPAY_AMOUNT_PAISE,
|
| 48 |
+
"currency": Config.RAZORPAY_CURRENCY,
|
| 49 |
+
"receipt": receipt,
|
| 50 |
+
}
|
| 51 |
+
)
|
| 52 |
+
return {
|
| 53 |
+
"order_id": order["id"],
|
| 54 |
+
"amount": order["amount"],
|
| 55 |
+
"currency": order["currency"],
|
| 56 |
+
"key_id": Config.RAZORPAY_KEY_ID,
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def verify_razorpay_payment_signature(
|
| 61 |
+
razorpay_order_id: str,
|
| 62 |
+
razorpay_payment_id: str,
|
| 63 |
+
razorpay_signature: str,
|
| 64 |
+
) -> bool:
|
| 65 |
+
import razorpay
|
| 66 |
+
|
| 67 |
+
client = razorpay.Client(auth=(Config.RAZORPAY_KEY_ID, Config.RAZORPAY_KEY_SECRET))
|
| 68 |
+
try:
|
| 69 |
+
client.utility.verify_payment_signature(
|
| 70 |
+
{
|
| 71 |
+
"razorpay_order_id": razorpay_order_id,
|
| 72 |
+
"razorpay_payment_id": razorpay_payment_id,
|
| 73 |
+
"razorpay_signature": razorpay_signature,
|
| 74 |
+
}
|
| 75 |
+
)
|
| 76 |
+
return True
|
| 77 |
+
except Exception:
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def coupon_valid(code: str | None) -> bool:
|
| 82 |
+
if not code:
|
| 83 |
+
return False
|
| 84 |
+
normalized = code.strip().lower()
|
| 85 |
+
return normalized in Config.payment_coupon_set()
|
app/services/graph_builder.py
CHANGED
|
@@ -15,6 +15,7 @@ from zep_cloud import EpisodeData, EntityEdgeSourceTarget
|
|
| 15 |
|
| 16 |
from ..config import Config
|
| 17 |
from ..models.task import TaskManager, TaskStatus
|
|
|
|
| 18 |
from ..utils.zep_paging import fetch_all_nodes, fetch_all_edges
|
| 19 |
from .text_processor import TextProcessor
|
| 20 |
|
|
@@ -43,12 +44,29 @@ class GraphBuilderService:
|
|
| 43 |
"""
|
| 44 |
|
| 45 |
def __init__(self, api_key: Optional[str] = None):
|
| 46 |
-
self.
|
| 47 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
raise ValueError("ZEP_API_KEY 未配置")
|
| 49 |
-
|
| 50 |
-
self.client = Zep(api_key=self.api_key)
|
| 51 |
self.task_manager = TaskManager()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
def build_graph_async(
|
| 54 |
self,
|
|
@@ -187,13 +205,15 @@ class GraphBuilderService:
|
|
| 187 |
def create_graph(self, name: str) -> str:
|
| 188 |
"""创建Zep图谱(公开方法)"""
|
| 189 |
graph_id = f"mirofish_{uuid.uuid4().hex[:16]}"
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
| 197 |
return graph_id
|
| 198 |
|
| 199 |
def set_ontology(self, graph_id: str, ontology: Dict[str, Any]):
|
|
@@ -279,11 +299,14 @@ class GraphBuilderService:
|
|
| 279 |
|
| 280 |
# 调用Zep API设置本体
|
| 281 |
if entity_types or edge_definitions:
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
def add_text_batches(
|
| 289 |
self,
|
|
@@ -316,10 +339,10 @@ class GraphBuilderService:
|
|
| 316 |
|
| 317 |
# 发送到Zep
|
| 318 |
try:
|
| 319 |
-
|
| 320 |
-
graph_id=graph_id,
|
| 321 |
-
|
| 322 |
-
)
|
| 323 |
|
| 324 |
# 收集返回的 episode uuid
|
| 325 |
if batch_result and isinstance(batch_result, list):
|
|
@@ -370,7 +393,10 @@ class GraphBuilderService:
|
|
| 370 |
# 检查每个 episode 的处理状态
|
| 371 |
for ep_uuid in list(pending_episodes):
|
| 372 |
try:
|
| 373 |
-
|
|
|
|
|
|
|
|
|
|
| 374 |
is_processed = getattr(episode, 'processed', False)
|
| 375 |
|
| 376 |
if is_processed:
|
|
@@ -396,11 +422,11 @@ class GraphBuilderService:
|
|
| 396 |
|
| 397 |
def _get_graph_info(self, graph_id: str) -> GraphInfo:
|
| 398 |
"""获取图谱信息"""
|
| 399 |
-
# 获取节点(分页)
|
| 400 |
-
nodes = fetch_all_nodes(self.client, graph_id)
|
| 401 |
|
| 402 |
-
|
| 403 |
-
|
|
|
|
|
|
|
| 404 |
|
| 405 |
# 统计实体类型
|
| 406 |
entity_types = set()
|
|
@@ -427,8 +453,10 @@ class GraphBuilderService:
|
|
| 427 |
Returns:
|
| 428 |
包含nodes和edges的字典,包括时间信息、属性等详细数据
|
| 429 |
"""
|
| 430 |
-
|
| 431 |
-
|
|
|
|
|
|
|
| 432 |
|
| 433 |
# 创建节点映射用于获取节点名称
|
| 434 |
node_map = {}
|
|
@@ -496,5 +524,9 @@ class GraphBuilderService:
|
|
| 496 |
|
| 497 |
def delete_graph(self, graph_id: str):
|
| 498 |
"""删除图谱"""
|
| 499 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
|
|
|
|
| 15 |
|
| 16 |
from ..config import Config
|
| 17 |
from ..models.task import TaskManager, TaskStatus
|
| 18 |
+
from ..utils.api_key_runtime import call_with_limit_rotation, get_zep_key
|
| 19 |
from ..utils.zep_paging import fetch_all_nodes, fetch_all_edges
|
| 20 |
from .text_processor import TextProcessor
|
| 21 |
|
|
|
|
| 44 |
"""
|
| 45 |
|
| 46 |
def __init__(self, api_key: Optional[str] = None):
|
| 47 |
+
self._fixed_api_key = (api_key or "").strip() or None
|
| 48 |
+
if self._fixed_api_key:
|
| 49 |
+
self.api_key = self._fixed_api_key
|
| 50 |
+
else:
|
| 51 |
+
self.api_key = get_zep_key() or (Config.get_zep_api_keys()[0] if Config.get_zep_api_keys() else None)
|
| 52 |
+
if not self.api_key and not Config.get_zep_api_keys():
|
| 53 |
raise ValueError("ZEP_API_KEY 未配置")
|
| 54 |
+
|
| 55 |
+
self.client = Zep(api_key=self.api_key) if self._fixed_api_key else None # noqa: SLF001
|
| 56 |
self.task_manager = TaskManager()
|
| 57 |
+
|
| 58 |
+
def _zep_call(self, fn):
|
| 59 |
+
"""Zep API call with shared LLM/Zep rate-limit rotation (pipeline uses runtime keys)."""
|
| 60 |
+
if self._fixed_api_key:
|
| 61 |
+
return fn(Zep(api_key=self._fixed_api_key))
|
| 62 |
+
|
| 63 |
+
def run():
|
| 64 |
+
k = get_zep_key()
|
| 65 |
+
if not k:
|
| 66 |
+
raise ValueError("ZEP_API_KEY 未配置")
|
| 67 |
+
return fn(Zep(api_key=k))
|
| 68 |
+
|
| 69 |
+
return call_with_limit_rotation(run)
|
| 70 |
|
| 71 |
def build_graph_async(
|
| 72 |
self,
|
|
|
|
| 205 |
def create_graph(self, name: str) -> str:
|
| 206 |
"""创建Zep图谱(公开方法)"""
|
| 207 |
graph_id = f"mirofish_{uuid.uuid4().hex[:16]}"
|
| 208 |
+
|
| 209 |
+
def op(c: Zep):
|
| 210 |
+
c.graph.create(
|
| 211 |
+
graph_id=graph_id,
|
| 212 |
+
name=name,
|
| 213 |
+
description="MiroFish Social Simulation Graph",
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
self._zep_call(op)
|
| 217 |
return graph_id
|
| 218 |
|
| 219 |
def set_ontology(self, graph_id: str, ontology: Dict[str, Any]):
|
|
|
|
| 299 |
|
| 300 |
# 调用Zep API设置本体
|
| 301 |
if entity_types or edge_definitions:
|
| 302 |
+
def op(c: Zep):
|
| 303 |
+
c.graph.set_ontology(
|
| 304 |
+
graph_ids=[graph_id],
|
| 305 |
+
entities=entity_types if entity_types else None,
|
| 306 |
+
edges=edge_definitions if edge_definitions else None,
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
self._zep_call(op)
|
| 310 |
|
| 311 |
def add_text_batches(
|
| 312 |
self,
|
|
|
|
| 339 |
|
| 340 |
# 发送到Zep
|
| 341 |
try:
|
| 342 |
+
def op(c: Zep):
|
| 343 |
+
return c.graph.add_batch(graph_id=graph_id, episodes=episodes)
|
| 344 |
+
|
| 345 |
+
batch_result = self._zep_call(op)
|
| 346 |
|
| 347 |
# 收集返回的 episode uuid
|
| 348 |
if batch_result and isinstance(batch_result, list):
|
|
|
|
| 393 |
# 检查每个 episode 的处理状态
|
| 394 |
for ep_uuid in list(pending_episodes):
|
| 395 |
try:
|
| 396 |
+
def op(c: Zep):
|
| 397 |
+
return c.graph.episode.get(uuid_=ep_uuid)
|
| 398 |
+
|
| 399 |
+
episode = self._zep_call(op)
|
| 400 |
is_processed = getattr(episode, 'processed', False)
|
| 401 |
|
| 402 |
if is_processed:
|
|
|
|
| 422 |
|
| 423 |
def _get_graph_info(self, graph_id: str) -> GraphInfo:
|
| 424 |
"""获取图谱信息"""
|
|
|
|
|
|
|
| 425 |
|
| 426 |
+
def fetch_pair(c: Zep):
|
| 427 |
+
return fetch_all_nodes(c, graph_id), fetch_all_edges(c, graph_id)
|
| 428 |
+
|
| 429 |
+
nodes, edges = self._zep_call(fetch_pair)
|
| 430 |
|
| 431 |
# 统计实体类型
|
| 432 |
entity_types = set()
|
|
|
|
| 453 |
Returns:
|
| 454 |
包含nodes和edges的字典,包括时间信息、属性等详细数据
|
| 455 |
"""
|
| 456 |
+
def fetch_pair(c: Zep):
|
| 457 |
+
return fetch_all_nodes(c, graph_id), fetch_all_edges(c, graph_id)
|
| 458 |
+
|
| 459 |
+
nodes, edges = self._zep_call(fetch_pair)
|
| 460 |
|
| 461 |
# 创建节点映射用于获取节点名称
|
| 462 |
node_map = {}
|
|
|
|
| 524 |
|
| 525 |
def delete_graph(self, graph_id: str):
|
| 526 |
"""删除图谱"""
|
| 527 |
+
|
| 528 |
+
def op(c: Zep):
|
| 529 |
+
c.graph.delete(graph_id=graph_id)
|
| 530 |
+
|
| 531 |
+
self._zep_call(op)
|
| 532 |
|
app/services/oasis_profile_generator.py
CHANGED
|
@@ -19,6 +19,7 @@ from openai import OpenAI
|
|
| 19 |
from zep_cloud.client import Zep
|
| 20 |
|
| 21 |
from ..config import Config
|
|
|
|
| 22 |
from ..utils.logger import get_logger
|
| 23 |
from .zep_entity_reader import EntityNode, ZepEntityReader
|
| 24 |
|
|
@@ -185,26 +186,30 @@ class OasisProfileGenerator:
|
|
| 185 |
zep_api_key: Optional[str] = None,
|
| 186 |
graph_id: Optional[str] = None
|
| 187 |
):
|
| 188 |
-
self.
|
| 189 |
self.base_url = base_url or Config.LLM_BASE_URL
|
| 190 |
self.model_name = model_name or Config.LLM_MODEL_NAME
|
| 191 |
-
|
| 192 |
-
if
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
)
|
| 199 |
-
|
| 200 |
-
# Zep客户端用于检索丰富上下文
|
| 201 |
-
self.zep_api_key = zep_api_key or Config.ZEP_API_KEY
|
| 202 |
self.zep_client = None
|
| 203 |
self.graph_id = graph_id
|
| 204 |
-
|
| 205 |
-
if self.
|
| 206 |
try:
|
| 207 |
-
self.zep_client = Zep(api_key=self.
|
| 208 |
except Exception as e:
|
| 209 |
logger.warning(f"Zep客户端初始化失败: {e}")
|
| 210 |
|
|
@@ -297,7 +302,9 @@ class OasisProfileGenerator:
|
|
| 297 |
"""
|
| 298 |
import concurrent.futures
|
| 299 |
|
| 300 |
-
if not self.
|
|
|
|
|
|
|
| 301 |
return {"facts": [], "node_summaries": [], "context": ""}
|
| 302 |
|
| 303 |
entity_name = entity.name
|
|
@@ -307,12 +314,7 @@ class OasisProfileGenerator:
|
|
| 307 |
"node_summaries": [],
|
| 308 |
"context": ""
|
| 309 |
}
|
| 310 |
-
|
| 311 |
-
# 必须有graph_id才能进行搜索
|
| 312 |
-
if not self.graph_id:
|
| 313 |
-
logger.debug(f"跳过Zep检索:未设置graph_id")
|
| 314 |
-
return results
|
| 315 |
-
|
| 316 |
comprehensive_query = f"关于{entity_name}的所有信息、活动、事件、关系和背景"
|
| 317 |
|
| 318 |
def search_edges():
|
|
@@ -323,13 +325,29 @@ class OasisProfileGenerator:
|
|
| 323 |
|
| 324 |
for attempt in range(max_retries):
|
| 325 |
try:
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
except Exception as e:
|
| 334 |
last_exception = e
|
| 335 |
if attempt < max_retries - 1:
|
|
@@ -348,13 +366,29 @@ class OasisProfileGenerator:
|
|
| 348 |
|
| 349 |
for attempt in range(max_retries):
|
| 350 |
try:
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
except Exception as e:
|
| 359 |
last_exception = e
|
| 360 |
if attempt < max_retries - 1:
|
|
@@ -526,15 +560,43 @@ class OasisProfileGenerator:
|
|
| 526 |
|
| 527 |
for attempt in range(max_attempts):
|
| 528 |
try:
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 538 |
)
|
| 539 |
|
| 540 |
content = response.choices[0].message.content
|
|
|
|
| 19 |
from zep_cloud.client import Zep
|
| 20 |
|
| 21 |
from ..config import Config
|
| 22 |
+
from ..utils.api_key_runtime import call_with_limit_rotation, get_llm_key, get_zep_key
|
| 23 |
from ..utils.logger import get_logger
|
| 24 |
from .zep_entity_reader import EntityNode, ZepEntityReader
|
| 25 |
|
|
|
|
| 186 |
zep_api_key: Optional[str] = None,
|
| 187 |
graph_id: Optional[str] = None
|
| 188 |
):
|
| 189 |
+
self._fixed_llm_key = (api_key or "").strip() or None
|
| 190 |
self.base_url = base_url or Config.LLM_BASE_URL
|
| 191 |
self.model_name = model_name or Config.LLM_MODEL_NAME
|
| 192 |
+
|
| 193 |
+
if self._fixed_llm_key:
|
| 194 |
+
self.api_key = self._fixed_llm_key
|
| 195 |
+
self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
|
| 196 |
+
else:
|
| 197 |
+
if not Config.get_llm_api_keys():
|
| 198 |
+
raise ValueError("LLM_API_KEY 未配置")
|
| 199 |
+
self.api_key = Config.get_llm_api_keys()[0]
|
| 200 |
+
self.client = None
|
| 201 |
+
|
| 202 |
+
# Zep客户端用于检索丰富上下文(运行时与 pipeline 共用 key slot)
|
| 203 |
+
self._fixed_zep_key = (zep_api_key or "").strip() or None
|
| 204 |
+
self.zep_api_key = self._fixed_zep_key or (
|
| 205 |
+
Config.get_zep_api_keys()[0] if Config.get_zep_api_keys() else None
|
| 206 |
)
|
|
|
|
|
|
|
|
|
|
| 207 |
self.zep_client = None
|
| 208 |
self.graph_id = graph_id
|
| 209 |
+
|
| 210 |
+
if self._fixed_zep_key:
|
| 211 |
try:
|
| 212 |
+
self.zep_client = Zep(api_key=self._fixed_zep_key)
|
| 213 |
except Exception as e:
|
| 214 |
logger.warning(f"Zep客户端初始化失败: {e}")
|
| 215 |
|
|
|
|
| 302 |
"""
|
| 303 |
import concurrent.futures
|
| 304 |
|
| 305 |
+
if not self.graph_id:
|
| 306 |
+
return {"facts": [], "node_summaries": [], "context": ""}
|
| 307 |
+
if self._fixed_zep_key and not self.zep_client:
|
| 308 |
return {"facts": [], "node_summaries": [], "context": ""}
|
| 309 |
|
| 310 |
entity_name = entity.name
|
|
|
|
| 314 |
"node_summaries": [],
|
| 315 |
"context": ""
|
| 316 |
}
|
| 317 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
comprehensive_query = f"关于{entity_name}的所有信息、活动、事件、关系和背景"
|
| 319 |
|
| 320 |
def search_edges():
|
|
|
|
| 325 |
|
| 326 |
for attempt in range(max_retries):
|
| 327 |
try:
|
| 328 |
+
def _edges():
|
| 329 |
+
k = self._fixed_zep_key or get_zep_key()
|
| 330 |
+
if not k:
|
| 331 |
+
raise ValueError("ZEP_API_KEY 未配置")
|
| 332 |
+
return Zep(api_key=k).graph.search(
|
| 333 |
+
query=comprehensive_query,
|
| 334 |
+
graph_id=self.graph_id,
|
| 335 |
+
limit=30,
|
| 336 |
+
scope="edges",
|
| 337 |
+
reranker="rrf",
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
if self._fixed_zep_key:
|
| 341 |
+
r = self.zep_client.graph.search(
|
| 342 |
+
query=comprehensive_query,
|
| 343 |
+
graph_id=self.graph_id,
|
| 344 |
+
limit=30,
|
| 345 |
+
scope="edges",
|
| 346 |
+
reranker="rrf",
|
| 347 |
+
)
|
| 348 |
+
else:
|
| 349 |
+
r = call_with_limit_rotation(_edges)
|
| 350 |
+
return r
|
| 351 |
except Exception as e:
|
| 352 |
last_exception = e
|
| 353 |
if attempt < max_retries - 1:
|
|
|
|
| 366 |
|
| 367 |
for attempt in range(max_retries):
|
| 368 |
try:
|
| 369 |
+
def _nodes():
|
| 370 |
+
k = self._fixed_zep_key or get_zep_key()
|
| 371 |
+
if not k:
|
| 372 |
+
raise ValueError("ZEP_API_KEY 未配置")
|
| 373 |
+
return Zep(api_key=k).graph.search(
|
| 374 |
+
query=comprehensive_query,
|
| 375 |
+
graph_id=self.graph_id,
|
| 376 |
+
limit=20,
|
| 377 |
+
scope="nodes",
|
| 378 |
+
reranker="rrf",
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
if self._fixed_zep_key:
|
| 382 |
+
r = self.zep_client.graph.search(
|
| 383 |
+
query=comprehensive_query,
|
| 384 |
+
graph_id=self.graph_id,
|
| 385 |
+
limit=20,
|
| 386 |
+
scope="nodes",
|
| 387 |
+
reranker="rrf",
|
| 388 |
+
)
|
| 389 |
+
else:
|
| 390 |
+
r = call_with_limit_rotation(_nodes)
|
| 391 |
+
return r
|
| 392 |
except Exception as e:
|
| 393 |
last_exception = e
|
| 394 |
if attempt < max_retries - 1:
|
|
|
|
| 560 |
|
| 561 |
for attempt in range(max_attempts):
|
| 562 |
try:
|
| 563 |
+
def _create():
|
| 564 |
+
if self._fixed_llm_key:
|
| 565 |
+
return self.client.chat.completions.create(
|
| 566 |
+
model=self.model_name,
|
| 567 |
+
messages=[
|
| 568 |
+
{"role": "system", "content": self._get_system_prompt(is_individual)},
|
| 569 |
+
{"role": "user", "content": prompt},
|
| 570 |
+
],
|
| 571 |
+
response_format={"type": "json_object"},
|
| 572 |
+
temperature=0.7 - (attempt * 0.1),
|
| 573 |
+
)
|
| 574 |
+
key = get_llm_key()
|
| 575 |
+
if not key:
|
| 576 |
+
raise ValueError("LLM_API_KEY 未配置")
|
| 577 |
+
cl = OpenAI(api_key=key, base_url=self.base_url)
|
| 578 |
+
return cl.chat.completions.create(
|
| 579 |
+
model=self.model_name,
|
| 580 |
+
messages=[
|
| 581 |
+
{"role": "system", "content": self._get_system_prompt(is_individual)},
|
| 582 |
+
{"role": "user", "content": prompt},
|
| 583 |
+
],
|
| 584 |
+
response_format={"type": "json_object"},
|
| 585 |
+
temperature=0.7 - (attempt * 0.1),
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
response = (
|
| 589 |
+
self.client.chat.completions.create(
|
| 590 |
+
model=self.model_name,
|
| 591 |
+
messages=[
|
| 592 |
+
{"role": "system", "content": self._get_system_prompt(is_individual)},
|
| 593 |
+
{"role": "user", "content": prompt},
|
| 594 |
+
],
|
| 595 |
+
response_format={"type": "json_object"},
|
| 596 |
+
temperature=0.7 - (attempt * 0.1),
|
| 597 |
+
)
|
| 598 |
+
if self._fixed_llm_key
|
| 599 |
+
else call_with_limit_rotation(_create)
|
| 600 |
)
|
| 601 |
|
| 602 |
content = response.choices[0].message.content
|
app/services/pipeline_orchestrator.py
CHANGED
|
@@ -19,6 +19,7 @@ from ..services.report_agent import ReportAgent, ReportManager, ReportStatus
|
|
| 19 |
from ..services.simulation_manager import SimulationManager, SimulationStatus
|
| 20 |
from ..services.simulation_runner import SimulationRunner, RunnerStatus
|
| 21 |
from ..services.text_processor import TextProcessor
|
|
|
|
| 22 |
from ..utils.logger import get_logger
|
| 23 |
|
| 24 |
logger = get_logger("mirofish.pipeline")
|
|
@@ -58,7 +59,7 @@ def _run_graph_build_sync(
|
|
| 58 |
if not text:
|
| 59 |
raise RuntimeError("No extracted text for project")
|
| 60 |
|
| 61 |
-
if not Config.
|
| 62 |
raise RuntimeError("ZEP_API_KEY is not configured")
|
| 63 |
|
| 64 |
graph_name = project.name or "MiroFish Graph"
|
|
@@ -68,7 +69,7 @@ def _run_graph_build_sync(
|
|
| 68 |
project.status = ProjectStatus.GRAPH_BUILDING
|
| 69 |
ProjectManager.save_project(project)
|
| 70 |
|
| 71 |
-
builder = GraphBuilderService(
|
| 72 |
|
| 73 |
_update(tm, pipeline_task_id, 16, "Chunking document…", stage="graph")
|
| 74 |
chunks = TextProcessor.split_text(text, chunk_size=chunk_size, overlap=chunk_overlap)
|
|
@@ -140,6 +141,7 @@ def run_full_pipeline(
|
|
| 140 |
parallel_profiles = Config.PIPELINE_PARALLEL_PROFILES
|
| 141 |
|
| 142 |
try:
|
|
|
|
| 143 |
_update(tm, task_id, 2, "Creating project…", stage="ontology")
|
| 144 |
|
| 145 |
project = ProjectManager.create_project(name=f"Pipeline {source_filename[:40]}")
|
|
|
|
| 19 |
from ..services.simulation_manager import SimulationManager, SimulationStatus
|
| 20 |
from ..services.simulation_runner import SimulationRunner, RunnerStatus
|
| 21 |
from ..services.text_processor import TextProcessor
|
| 22 |
+
from ..utils.api_key_runtime import reset_pipeline_api_keys
|
| 23 |
from ..utils.logger import get_logger
|
| 24 |
|
| 25 |
logger = get_logger("mirofish.pipeline")
|
|
|
|
| 59 |
if not text:
|
| 60 |
raise RuntimeError("No extracted text for project")
|
| 61 |
|
| 62 |
+
if not Config.get_zep_api_keys():
|
| 63 |
raise RuntimeError("ZEP_API_KEY is not configured")
|
| 64 |
|
| 65 |
graph_name = project.name or "MiroFish Graph"
|
|
|
|
| 69 |
project.status = ProjectStatus.GRAPH_BUILDING
|
| 70 |
ProjectManager.save_project(project)
|
| 71 |
|
| 72 |
+
builder = GraphBuilderService()
|
| 73 |
|
| 74 |
_update(tm, pipeline_task_id, 16, "Chunking document…", stage="graph")
|
| 75 |
chunks = TextProcessor.split_text(text, chunk_size=chunk_size, overlap=chunk_overlap)
|
|
|
|
| 141 |
parallel_profiles = Config.PIPELINE_PARALLEL_PROFILES
|
| 142 |
|
| 143 |
try:
|
| 144 |
+
reset_pipeline_api_keys()
|
| 145 |
_update(tm, task_id, 2, "Creating project…", stage="ontology")
|
| 146 |
|
| 147 |
project = ProjectManager.create_project(name=f"Pipeline {source_filename[:40]}")
|
app/services/simulation_config_generator.py
CHANGED
|
@@ -19,6 +19,7 @@ from datetime import datetime
|
|
| 19 |
from openai import OpenAI
|
| 20 |
|
| 21 |
from ..config import Config
|
|
|
|
| 22 |
from ..utils.logger import get_logger
|
| 23 |
from .zep_entity_reader import EntityNode, ZepEntityReader
|
| 24 |
|
|
@@ -227,17 +228,18 @@ class SimulationConfigGenerator:
|
|
| 227 |
base_url: Optional[str] = None,
|
| 228 |
model_name: Optional[str] = None
|
| 229 |
):
|
| 230 |
-
self.
|
| 231 |
self.base_url = base_url or Config.LLM_BASE_URL
|
| 232 |
self.model_name = model_name or Config.LLM_MODEL_NAME
|
| 233 |
-
|
| 234 |
-
if
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
| 241 |
|
| 242 |
def generate_config(
|
| 243 |
self,
|
|
@@ -439,15 +441,43 @@ class SimulationConfigGenerator:
|
|
| 439 |
|
| 440 |
for attempt in range(max_attempts):
|
| 441 |
try:
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
)
|
| 452 |
|
| 453 |
content = response.choices[0].message.content
|
|
|
|
| 19 |
from openai import OpenAI
|
| 20 |
|
| 21 |
from ..config import Config
|
| 22 |
+
from ..utils.api_key_runtime import call_with_limit_rotation, get_llm_key
|
| 23 |
from ..utils.logger import get_logger
|
| 24 |
from .zep_entity_reader import EntityNode, ZepEntityReader
|
| 25 |
|
|
|
|
| 228 |
base_url: Optional[str] = None,
|
| 229 |
model_name: Optional[str] = None
|
| 230 |
):
|
| 231 |
+
self._fixed_api_key = (api_key or "").strip() or None
|
| 232 |
self.base_url = base_url or Config.LLM_BASE_URL
|
| 233 |
self.model_name = model_name or Config.LLM_MODEL_NAME
|
| 234 |
+
|
| 235 |
+
if self._fixed_api_key:
|
| 236 |
+
self.api_key = self._fixed_api_key
|
| 237 |
+
self.client = OpenAI(api_key=self.api_key, base_url=self.base_url)
|
| 238 |
+
else:
|
| 239 |
+
if not Config.get_llm_api_keys():
|
| 240 |
+
raise ValueError("LLM_API_KEY 未配置")
|
| 241 |
+
self.api_key = Config.get_llm_api_keys()[0]
|
| 242 |
+
self.client = None
|
| 243 |
|
| 244 |
def generate_config(
|
| 245 |
self,
|
|
|
|
| 441 |
|
| 442 |
for attempt in range(max_attempts):
|
| 443 |
try:
|
| 444 |
+
def _create():
|
| 445 |
+
if self._fixed_api_key:
|
| 446 |
+
return self.client.chat.completions.create(
|
| 447 |
+
model=self.model_name,
|
| 448 |
+
messages=[
|
| 449 |
+
{"role": "system", "content": system_prompt},
|
| 450 |
+
{"role": "user", "content": prompt},
|
| 451 |
+
],
|
| 452 |
+
response_format={"type": "json_object"},
|
| 453 |
+
temperature=0.7 - (attempt * 0.1),
|
| 454 |
+
)
|
| 455 |
+
key = get_llm_key()
|
| 456 |
+
if not key:
|
| 457 |
+
raise ValueError("LLM_API_KEY 未配置")
|
| 458 |
+
cl = OpenAI(api_key=key, base_url=self.base_url)
|
| 459 |
+
return cl.chat.completions.create(
|
| 460 |
+
model=self.model_name,
|
| 461 |
+
messages=[
|
| 462 |
+
{"role": "system", "content": system_prompt},
|
| 463 |
+
{"role": "user", "content": prompt},
|
| 464 |
+
],
|
| 465 |
+
response_format={"type": "json_object"},
|
| 466 |
+
temperature=0.7 - (attempt * 0.1),
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
response = (
|
| 470 |
+
self.client.chat.completions.create(
|
| 471 |
+
model=self.model_name,
|
| 472 |
+
messages=[
|
| 473 |
+
{"role": "system", "content": system_prompt},
|
| 474 |
+
{"role": "user", "content": prompt},
|
| 475 |
+
],
|
| 476 |
+
response_format={"type": "json_object"},
|
| 477 |
+
temperature=0.7 - (attempt * 0.1),
|
| 478 |
+
)
|
| 479 |
+
if self._fixed_api_key
|
| 480 |
+
else call_with_limit_rotation(_create)
|
| 481 |
)
|
| 482 |
|
| 483 |
content = response.choices[0].message.content
|
app/services/supabase_jobs.py
CHANGED
|
@@ -1,176 +1,176 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Persist pipeline runs and finished reports to Supabase (Postgres + Storage).
|
| 3 |
-
Uses the service role on the server only — never expose the key to the browser.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
from __future__ import annotations
|
| 7 |
-
|
| 8 |
-
from datetime import datetime, timezone
|
| 9 |
-
from typing import Any, Dict, Optional
|
| 10 |
-
|
| 11 |
-
from ..config import Config
|
| 12 |
-
from ..utils.logger import get_logger
|
| 13 |
-
|
| 14 |
-
logger = get_logger("mirofish.supabase_jobs")
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def sync_enabled() -> bool:
|
| 18 |
-
"""True when Postgres + Storage sync is available (service role). JWT secret is only required for Bearer auth."""
|
| 19 |
-
return bool(Config.SUPABASE_URL and Config.SUPABASE_SERVICE_ROLE_KEY)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def _client():
|
| 23 |
-
from supabase import create_client
|
| 24 |
-
|
| 25 |
-
return create_client(Config.SUPABASE_URL, Config.SUPABASE_SERVICE_ROLE_KEY)
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
def insert_pending_run(
|
| 29 |
-
*,
|
| 30 |
-
simulation_run_id: str,
|
| 31 |
-
user_id: str,
|
| 32 |
-
backend_task_id: str,
|
| 33 |
-
requirement_preview: str,
|
| 34 |
-
) -> None:
|
| 35 |
-
if not sync_enabled():
|
| 36 |
-
return
|
| 37 |
-
try:
|
| 38 |
-
sb = _client()
|
| 39 |
-
sb.table("simulation_runs").insert(
|
| 40 |
-
{
|
| 41 |
-
"id": simulation_run_id,
|
| 42 |
-
"user_id": user_id,
|
| 43 |
-
"backend_task_id": backend_task_id,
|
| 44 |
-
"status": "pending",
|
| 45 |
-
"requirement_preview": (requirement_preview or "")[:2000],
|
| 46 |
-
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 47 |
-
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 48 |
-
}
|
| 49 |
-
).execute()
|
| 50 |
-
except Exception as e:
|
| 51 |
-
logger.error("insert_pending_run failed: %s", e)
|
| 52 |
-
raise
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
def mark_run_failed(*, simulation_run_id: str, error_message: str) -> None:
|
| 56 |
-
if not sync_enabled() or not simulation_run_id:
|
| 57 |
-
return
|
| 58 |
-
try:
|
| 59 |
-
sb = _client()
|
| 60 |
-
sb.table("simulation_runs").update(
|
| 61 |
-
{
|
| 62 |
-
"status": "failed",
|
| 63 |
-
"error_message": (error_message or "")[:4000],
|
| 64 |
-
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 65 |
-
}
|
| 66 |
-
).eq("id", simulation_run_id).execute()
|
| 67 |
-
except Exception as e:
|
| 68 |
-
logger.error("mark_run_failed failed: %s", e)
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
def mark_run_completed(
|
| 72 |
-
*,
|
| 73 |
-
simulation_run_id: str,
|
| 74 |
-
user_id: str,
|
| 75 |
-
report_id: str,
|
| 76 |
-
markdown_content: str,
|
| 77 |
-
simulation_id: Optional[str] = None,
|
| 78 |
-
project_id: Optional[str] = None,
|
| 79 |
-
) -> Optional[Dict[str, Any]]:
|
| 80 |
-
"""
|
| 81 |
-
Upload markdown to Storage and mark row completed. Returns { report_storage_path, report_public_url? }.
|
| 82 |
-
"""
|
| 83 |
-
if not sync_enabled() or not simulation_run_id:
|
| 84 |
-
return None
|
| 85 |
-
path = f"{user_id}/{simulation_run_id}.md"
|
| 86 |
-
body = markdown_content.encode("utf-8")
|
| 87 |
-
try:
|
| 88 |
-
sb = _client()
|
| 89 |
-
bucket = Config.SUPABASE_REPORTS_BUCKET
|
| 90 |
-
# upsert so retries overwrite
|
| 91 |
-
storage_api = sb.storage.from_(bucket)
|
| 92 |
-
try:
|
| 93 |
-
storage_api.upload(
|
| 94 |
-
path,
|
| 95 |
-
body,
|
| 96 |
-
file_options={
|
| 97 |
-
"content-type": "text/markdown; charset=utf-8",
|
| 98 |
-
"upsert": "true",
|
| 99 |
-
},
|
| 100 |
-
)
|
| 101 |
-
except TypeError:
|
| 102 |
-
storage_api.upload(path, body)
|
| 103 |
-
|
| 104 |
-
pub: Optional[str] = None
|
| 105 |
-
try:
|
| 106 |
-
u = storage_api.get_public_url(path)
|
| 107 |
-
if isinstance(u, dict):
|
| 108 |
-
pub = u.get("publicUrl") or u.get("public_url")
|
| 109 |
-
elif isinstance(u, str):
|
| 110 |
-
pub = u
|
| 111 |
-
except Exception:
|
| 112 |
-
pub = None
|
| 113 |
-
|
| 114 |
-
sb.table("simulation_runs").update(
|
| 115 |
-
{
|
| 116 |
-
"status": "completed",
|
| 117 |
-
"report_id": report_id,
|
| 118 |
-
"report_storage_path": path,
|
| 119 |
-
"report_public_url": pub,
|
| 120 |
-
"simulation_id": simulation_id,
|
| 121 |
-
"project_id": project_id,
|
| 122 |
-
"error_message": None,
|
| 123 |
-
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 124 |
-
}
|
| 125 |
-
).eq("id", simulation_run_id).execute()
|
| 126 |
-
|
| 127 |
-
return {"report_storage_path": path, "report_public_url": pub}
|
| 128 |
-
except Exception as e:
|
| 129 |
-
logger.error("mark_run_completed failed: %s", e)
|
| 130 |
-
mark_run_failed(simulation_run_id=simulation_run_id, error_message=f"Report upload failed: {e}")
|
| 131 |
-
raise
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
def list_simulation_runs_for_user(*, user_id: str) -> list:
|
| 135 |
-
if not sync_enabled():
|
| 136 |
-
return []
|
| 137 |
-
sb = _client()
|
| 138 |
-
r = sb.table("simulation_runs").select("*").eq("user_id", user_id).order("created_at", desc=True).execute()
|
| 139 |
-
return r.data or []
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
def get_run_row_for_user(*, run_id: str, user_id: str) -> Optional[Dict[str, Any]]:
|
| 143 |
-
if not sync_enabled():
|
| 144 |
-
return None
|
| 145 |
-
sb = _client()
|
| 146 |
-
r = sb.table("simulation_runs").select("*").eq("id", run_id).eq("user_id", user_id).limit(1).execute()
|
| 147 |
-
rows = r.data or []
|
| 148 |
-
return rows[0] if rows else None
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
def signed_url_for_storage_path(*, storage_path: str, expires_sec: int = 3600) -> Optional[str]:
|
| 152 |
-
if not sync_enabled() or not storage_path:
|
| 153 |
-
return None
|
| 154 |
-
sb = _client()
|
| 155 |
-
bucket = Config.SUPABASE_REPORTS_BUCKET
|
| 156 |
-
try:
|
| 157 |
-
res = sb.storage.from_(bucket).create_signed_url(storage_path, expires_sec)
|
| 158 |
-
if isinstance(res, dict):
|
| 159 |
-
return (
|
| 160 |
-
res.get("signedURL")
|
| 161 |
-
or res.get("signed_url")
|
| 162 |
-
or (res.get("data") or {}).get("signedUrl")
|
| 163 |
-
)
|
| 164 |
-
signed = getattr(res, "signed_url", None) or getattr(res, "signedURL", None)
|
| 165 |
-
if signed:
|
| 166 |
-
return signed
|
| 167 |
-
except TypeError:
|
| 168 |
-
try:
|
| 169 |
-
res = sb.storage.from_(bucket).create_signed_url(storage_path, {"expires_in": expires_sec})
|
| 170 |
-
if isinstance(res, dict):
|
| 171 |
-
return res.get("signedURL") or res.get("signed_url")
|
| 172 |
-
except Exception as e2:
|
| 173 |
-
logger.error("signed_url_for_storage_path fallback: %s", e2)
|
| 174 |
-
except Exception as e:
|
| 175 |
-
logger.error("signed_url_for_storage_path: %s", e)
|
| 176 |
-
return None
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Persist pipeline runs and finished reports to Supabase (Postgres + Storage).
|
| 3 |
+
Uses the service role on the server only — never expose the key to the browser.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
from typing import Any, Dict, Optional
|
| 10 |
+
|
| 11 |
+
from ..config import Config
|
| 12 |
+
from ..utils.logger import get_logger
|
| 13 |
+
|
| 14 |
+
logger = get_logger("mirofish.supabase_jobs")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def sync_enabled() -> bool:
|
| 18 |
+
"""True when Postgres + Storage sync is available (service role). JWT secret is only required for Bearer auth."""
|
| 19 |
+
return bool(Config.SUPABASE_URL and Config.SUPABASE_SERVICE_ROLE_KEY)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _client():
|
| 23 |
+
from supabase import create_client
|
| 24 |
+
|
| 25 |
+
return create_client(Config.SUPABASE_URL, Config.SUPABASE_SERVICE_ROLE_KEY)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def insert_pending_run(
|
| 29 |
+
*,
|
| 30 |
+
simulation_run_id: str,
|
| 31 |
+
user_id: str,
|
| 32 |
+
backend_task_id: str,
|
| 33 |
+
requirement_preview: str,
|
| 34 |
+
) -> None:
|
| 35 |
+
if not sync_enabled():
|
| 36 |
+
return
|
| 37 |
+
try:
|
| 38 |
+
sb = _client()
|
| 39 |
+
sb.table("simulation_runs").insert(
|
| 40 |
+
{
|
| 41 |
+
"id": simulation_run_id,
|
| 42 |
+
"user_id": user_id,
|
| 43 |
+
"backend_task_id": backend_task_id,
|
| 44 |
+
"status": "pending",
|
| 45 |
+
"requirement_preview": (requirement_preview or "")[:2000],
|
| 46 |
+
"created_at": datetime.now(timezone.utc).isoformat(),
|
| 47 |
+
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 48 |
+
}
|
| 49 |
+
).execute()
|
| 50 |
+
except Exception as e:
|
| 51 |
+
logger.error("insert_pending_run failed: %s", e)
|
| 52 |
+
raise
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def mark_run_failed(*, simulation_run_id: str, error_message: str) -> None:
|
| 56 |
+
if not sync_enabled() or not simulation_run_id:
|
| 57 |
+
return
|
| 58 |
+
try:
|
| 59 |
+
sb = _client()
|
| 60 |
+
sb.table("simulation_runs").update(
|
| 61 |
+
{
|
| 62 |
+
"status": "failed",
|
| 63 |
+
"error_message": (error_message or "")[:4000],
|
| 64 |
+
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 65 |
+
}
|
| 66 |
+
).eq("id", simulation_run_id).execute()
|
| 67 |
+
except Exception as e:
|
| 68 |
+
logger.error("mark_run_failed failed: %s", e)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def mark_run_completed(
|
| 72 |
+
*,
|
| 73 |
+
simulation_run_id: str,
|
| 74 |
+
user_id: str,
|
| 75 |
+
report_id: str,
|
| 76 |
+
markdown_content: str,
|
| 77 |
+
simulation_id: Optional[str] = None,
|
| 78 |
+
project_id: Optional[str] = None,
|
| 79 |
+
) -> Optional[Dict[str, Any]]:
|
| 80 |
+
"""
|
| 81 |
+
Upload markdown to Storage and mark row completed. Returns { report_storage_path, report_public_url? }.
|
| 82 |
+
"""
|
| 83 |
+
if not sync_enabled() or not simulation_run_id:
|
| 84 |
+
return None
|
| 85 |
+
path = f"{user_id}/{simulation_run_id}.md"
|
| 86 |
+
body = markdown_content.encode("utf-8")
|
| 87 |
+
try:
|
| 88 |
+
sb = _client()
|
| 89 |
+
bucket = Config.SUPABASE_REPORTS_BUCKET
|
| 90 |
+
# upsert so retries overwrite
|
| 91 |
+
storage_api = sb.storage.from_(bucket)
|
| 92 |
+
try:
|
| 93 |
+
storage_api.upload(
|
| 94 |
+
path,
|
| 95 |
+
body,
|
| 96 |
+
file_options={
|
| 97 |
+
"content-type": "text/markdown; charset=utf-8",
|
| 98 |
+
"upsert": "true",
|
| 99 |
+
},
|
| 100 |
+
)
|
| 101 |
+
except TypeError:
|
| 102 |
+
storage_api.upload(path, body)
|
| 103 |
+
|
| 104 |
+
pub: Optional[str] = None
|
| 105 |
+
try:
|
| 106 |
+
u = storage_api.get_public_url(path)
|
| 107 |
+
if isinstance(u, dict):
|
| 108 |
+
pub = u.get("publicUrl") or u.get("public_url")
|
| 109 |
+
elif isinstance(u, str):
|
| 110 |
+
pub = u
|
| 111 |
+
except Exception:
|
| 112 |
+
pub = None
|
| 113 |
+
|
| 114 |
+
sb.table("simulation_runs").update(
|
| 115 |
+
{
|
| 116 |
+
"status": "completed",
|
| 117 |
+
"report_id": report_id,
|
| 118 |
+
"report_storage_path": path,
|
| 119 |
+
"report_public_url": pub,
|
| 120 |
+
"simulation_id": simulation_id,
|
| 121 |
+
"project_id": project_id,
|
| 122 |
+
"error_message": None,
|
| 123 |
+
"updated_at": datetime.now(timezone.utc).isoformat(),
|
| 124 |
+
}
|
| 125 |
+
).eq("id", simulation_run_id).execute()
|
| 126 |
+
|
| 127 |
+
return {"report_storage_path": path, "report_public_url": pub}
|
| 128 |
+
except Exception as e:
|
| 129 |
+
logger.error("mark_run_completed failed: %s", e)
|
| 130 |
+
mark_run_failed(simulation_run_id=simulation_run_id, error_message=f"Report upload failed: {e}")
|
| 131 |
+
raise
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def list_simulation_runs_for_user(*, user_id: str) -> list:
|
| 135 |
+
if not sync_enabled():
|
| 136 |
+
return []
|
| 137 |
+
sb = _client()
|
| 138 |
+
r = sb.table("simulation_runs").select("*").eq("user_id", user_id).order("created_at", desc=True).execute()
|
| 139 |
+
return r.data or []
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def get_run_row_for_user(*, run_id: str, user_id: str) -> Optional[Dict[str, Any]]:
|
| 143 |
+
if not sync_enabled():
|
| 144 |
+
return None
|
| 145 |
+
sb = _client()
|
| 146 |
+
r = sb.table("simulation_runs").select("*").eq("id", run_id).eq("user_id", user_id).limit(1).execute()
|
| 147 |
+
rows = r.data or []
|
| 148 |
+
return rows[0] if rows else None
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def signed_url_for_storage_path(*, storage_path: str, expires_sec: int = 3600) -> Optional[str]:
|
| 152 |
+
if not sync_enabled() or not storage_path:
|
| 153 |
+
return None
|
| 154 |
+
sb = _client()
|
| 155 |
+
bucket = Config.SUPABASE_REPORTS_BUCKET
|
| 156 |
+
try:
|
| 157 |
+
res = sb.storage.from_(bucket).create_signed_url(storage_path, expires_sec)
|
| 158 |
+
if isinstance(res, dict):
|
| 159 |
+
return (
|
| 160 |
+
res.get("signedURL")
|
| 161 |
+
or res.get("signed_url")
|
| 162 |
+
or (res.get("data") or {}).get("signedUrl")
|
| 163 |
+
)
|
| 164 |
+
signed = getattr(res, "signed_url", None) or getattr(res, "signedURL", None)
|
| 165 |
+
if signed:
|
| 166 |
+
return signed
|
| 167 |
+
except TypeError:
|
| 168 |
+
try:
|
| 169 |
+
res = sb.storage.from_(bucket).create_signed_url(storage_path, {"expires_in": expires_sec})
|
| 170 |
+
if isinstance(res, dict):
|
| 171 |
+
return res.get("signedURL") or res.get("signed_url")
|
| 172 |
+
except Exception as e2:
|
| 173 |
+
logger.error("signed_url_for_storage_path fallback: %s", e2)
|
| 174 |
+
except Exception as e:
|
| 175 |
+
logger.error("signed_url_for_storage_path: %s", e)
|
| 176 |
+
return None
|
app/services/zep_entity_reader.py
CHANGED
|
@@ -1,438 +1,450 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Zep实体读取与过滤服务
|
| 3 |
-
从Zep图谱中读取节点,筛选出符合预定义实体类型的节点
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import time
|
| 7 |
-
from typing import Dict, Any, List, Optional, Set, Callable, TypeVar
|
| 8 |
-
from dataclasses import dataclass, field
|
| 9 |
-
|
| 10 |
-
from zep_cloud.client import Zep
|
| 11 |
-
|
| 12 |
-
from ..config import Config
|
| 13 |
-
from ..utils.
|
| 14 |
-
from ..utils.
|
| 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 |
-
|
| 83 |
-
self.
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
""
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
""
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
})
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
"
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
# 获取
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
"
|
| 395 |
-
"
|
| 396 |
-
"
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
return
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Zep实体读取与过滤服务
|
| 3 |
+
从Zep图谱中读取节点,筛选出符合预定义实体类型的节点
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import time
|
| 7 |
+
from typing import Dict, Any, List, Optional, Set, Callable, TypeVar
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
|
| 10 |
+
from zep_cloud.client import Zep
|
| 11 |
+
|
| 12 |
+
from ..config import Config
|
| 13 |
+
from ..utils.api_key_runtime import call_with_limit_rotation, get_zep_key
|
| 14 |
+
from ..utils.logger import get_logger
|
| 15 |
+
from ..utils.zep_paging import fetch_all_nodes, fetch_all_edges
|
| 16 |
+
|
| 17 |
+
logger = get_logger('mirofish.zep_entity_reader')
|
| 18 |
+
|
| 19 |
+
# 用于泛型返回类型
|
| 20 |
+
T = TypeVar('T')
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class EntityNode:
|
| 25 |
+
"""实体节点数据结构"""
|
| 26 |
+
uuid: str
|
| 27 |
+
name: str
|
| 28 |
+
labels: List[str]
|
| 29 |
+
summary: str
|
| 30 |
+
attributes: Dict[str, Any]
|
| 31 |
+
# 相关的边信息
|
| 32 |
+
related_edges: List[Dict[str, Any]] = field(default_factory=list)
|
| 33 |
+
# 相关的其他节点信息
|
| 34 |
+
related_nodes: List[Dict[str, Any]] = field(default_factory=list)
|
| 35 |
+
|
| 36 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 37 |
+
return {
|
| 38 |
+
"uuid": self.uuid,
|
| 39 |
+
"name": self.name,
|
| 40 |
+
"labels": self.labels,
|
| 41 |
+
"summary": self.summary,
|
| 42 |
+
"attributes": self.attributes,
|
| 43 |
+
"related_edges": self.related_edges,
|
| 44 |
+
"related_nodes": self.related_nodes,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
def get_entity_type(self) -> Optional[str]:
|
| 48 |
+
"""获取实体类型(排除默认的Entity标签)"""
|
| 49 |
+
for label in self.labels:
|
| 50 |
+
if label not in ["Entity", "Node"]:
|
| 51 |
+
return label
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@dataclass
|
| 56 |
+
class FilteredEntities:
|
| 57 |
+
"""过滤后的实体集合"""
|
| 58 |
+
entities: List[EntityNode]
|
| 59 |
+
entity_types: Set[str]
|
| 60 |
+
total_count: int
|
| 61 |
+
filtered_count: int
|
| 62 |
+
|
| 63 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 64 |
+
return {
|
| 65 |
+
"entities": [e.to_dict() for e in self.entities],
|
| 66 |
+
"entity_types": list(self.entity_types),
|
| 67 |
+
"total_count": self.total_count,
|
| 68 |
+
"filtered_count": self.filtered_count,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ZepEntityReader:
|
| 73 |
+
"""
|
| 74 |
+
Zep实体读取与过滤服务
|
| 75 |
+
|
| 76 |
+
主要功能:
|
| 77 |
+
1. 从Zep图谱读取所有节点
|
| 78 |
+
2. 筛选出符合预定义实体类型的节点(Labels不只是Entity的节点)
|
| 79 |
+
3. 获取每个实体的相关边和关联节点信息
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, api_key: Optional[str] = None):
|
| 83 |
+
self._fixed_api_key = (api_key or "").strip() or None
|
| 84 |
+
zk = Config.get_zep_api_keys()
|
| 85 |
+
if self._fixed_api_key:
|
| 86 |
+
self.api_key = self._fixed_api_key
|
| 87 |
+
else:
|
| 88 |
+
self.api_key = zk[0] if zk else None
|
| 89 |
+
if not self.api_key and not zk:
|
| 90 |
+
raise ValueError("ZEP_API_KEY 未配置")
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def client(self) -> Zep:
|
| 94 |
+
if self._fixed_api_key:
|
| 95 |
+
return Zep(api_key=self._fixed_api_key)
|
| 96 |
+
k = get_zep_key()
|
| 97 |
+
if not k:
|
| 98 |
+
raise ValueError("ZEP_API_KEY 未配置")
|
| 99 |
+
return Zep(api_key=k)
|
| 100 |
+
|
| 101 |
+
def _call_with_retry(
|
| 102 |
+
self,
|
| 103 |
+
func: Callable[[], T],
|
| 104 |
+
operation_name: str,
|
| 105 |
+
max_retries: int = 3,
|
| 106 |
+
initial_delay: float = 2.0
|
| 107 |
+
) -> T:
|
| 108 |
+
"""
|
| 109 |
+
带重试机制的Zep API调用
|
| 110 |
+
|
| 111 |
+
Args:
|
| 112 |
+
func: 要执行的函数(无参数的lambda或callable)
|
| 113 |
+
operation_name: 操作名称,用于日志
|
| 114 |
+
max_retries: 最大重试次数(默认3次,即最多尝试3次)
|
| 115 |
+
initial_delay: 初始延迟秒数
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
API调用结果
|
| 119 |
+
"""
|
| 120 |
+
last_exception = None
|
| 121 |
+
delay = initial_delay
|
| 122 |
+
|
| 123 |
+
for attempt in range(max_retries):
|
| 124 |
+
try:
|
| 125 |
+
return call_with_limit_rotation(func)
|
| 126 |
+
except Exception as e:
|
| 127 |
+
last_exception = e
|
| 128 |
+
if attempt < max_retries - 1:
|
| 129 |
+
logger.warning(
|
| 130 |
+
f"Zep {operation_name} 第 {attempt + 1} 次尝试失败: {str(e)[:100]}, "
|
| 131 |
+
f"{delay:.1f}秒后重试..."
|
| 132 |
+
)
|
| 133 |
+
time.sleep(delay)
|
| 134 |
+
delay *= 2 # 指数退避
|
| 135 |
+
else:
|
| 136 |
+
logger.error(f"Zep {operation_name} 在 {max_retries} 次尝试后仍失败: {str(e)}")
|
| 137 |
+
|
| 138 |
+
raise last_exception
|
| 139 |
+
|
| 140 |
+
def get_all_nodes(self, graph_id: str) -> List[Dict[str, Any]]:
|
| 141 |
+
"""
|
| 142 |
+
获取图谱的所有节点(分页获取)
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
graph_id: 图谱ID
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
节点列表
|
| 149 |
+
"""
|
| 150 |
+
logger.info(f"获取图谱 {graph_id} 的所有节点...")
|
| 151 |
+
|
| 152 |
+
nodes = call_with_limit_rotation(lambda: fetch_all_nodes(self.client, graph_id))
|
| 153 |
+
|
| 154 |
+
nodes_data = []
|
| 155 |
+
for node in nodes:
|
| 156 |
+
nodes_data.append({
|
| 157 |
+
"uuid": getattr(node, 'uuid_', None) or getattr(node, 'uuid', ''),
|
| 158 |
+
"name": node.name or "",
|
| 159 |
+
"labels": node.labels or [],
|
| 160 |
+
"summary": node.summary or "",
|
| 161 |
+
"attributes": node.attributes or {},
|
| 162 |
+
})
|
| 163 |
+
|
| 164 |
+
logger.info(f"共获取 {len(nodes_data)} 个节点")
|
| 165 |
+
return nodes_data
|
| 166 |
+
|
| 167 |
+
def get_all_edges(self, graph_id: str) -> List[Dict[str, Any]]:
|
| 168 |
+
"""
|
| 169 |
+
获取图谱的所有边(分页获取)
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
graph_id: 图谱ID
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
边列表
|
| 176 |
+
"""
|
| 177 |
+
logger.info(f"获取图谱 {graph_id} 的所有边...")
|
| 178 |
+
|
| 179 |
+
edges = call_with_limit_rotation(lambda: fetch_all_edges(self.client, graph_id))
|
| 180 |
+
|
| 181 |
+
edges_data = []
|
| 182 |
+
for edge in edges:
|
| 183 |
+
edges_data.append({
|
| 184 |
+
"uuid": getattr(edge, 'uuid_', None) or getattr(edge, 'uuid', ''),
|
| 185 |
+
"name": edge.name or "",
|
| 186 |
+
"fact": edge.fact or "",
|
| 187 |
+
"source_node_uuid": edge.source_node_uuid,
|
| 188 |
+
"target_node_uuid": edge.target_node_uuid,
|
| 189 |
+
"attributes": edge.attributes or {},
|
| 190 |
+
})
|
| 191 |
+
|
| 192 |
+
logger.info(f"共获取 {len(edges_data)} 条边")
|
| 193 |
+
return edges_data
|
| 194 |
+
|
| 195 |
+
def get_node_edges(self, node_uuid: str) -> List[Dict[str, Any]]:
|
| 196 |
+
"""
|
| 197 |
+
获取指定节点的所有相关边(带重试机制)
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
node_uuid: 节点UUID
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
边列表
|
| 204 |
+
"""
|
| 205 |
+
try:
|
| 206 |
+
# 使用重试机制调用Zep API
|
| 207 |
+
edges = self._call_with_retry(
|
| 208 |
+
func=lambda: self.client.graph.node.get_entity_edges(node_uuid=node_uuid),
|
| 209 |
+
operation_name=f"获取节点边(node={node_uuid[:8]}...)"
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
edges_data = []
|
| 213 |
+
for edge in edges:
|
| 214 |
+
edges_data.append({
|
| 215 |
+
"uuid": getattr(edge, 'uuid_', None) or getattr(edge, 'uuid', ''),
|
| 216 |
+
"name": edge.name or "",
|
| 217 |
+
"fact": edge.fact or "",
|
| 218 |
+
"source_node_uuid": edge.source_node_uuid,
|
| 219 |
+
"target_node_uuid": edge.target_node_uuid,
|
| 220 |
+
"attributes": edge.attributes or {},
|
| 221 |
+
})
|
| 222 |
+
|
| 223 |
+
return edges_data
|
| 224 |
+
except Exception as e:
|
| 225 |
+
logger.warning(f"获取节点 {node_uuid} 的边失败: {str(e)}")
|
| 226 |
+
return []
|
| 227 |
+
|
| 228 |
+
def filter_defined_entities(
|
| 229 |
+
self,
|
| 230 |
+
graph_id: str,
|
| 231 |
+
defined_entity_types: Optional[List[str]] = None,
|
| 232 |
+
enrich_with_edges: bool = True
|
| 233 |
+
) -> FilteredEntities:
|
| 234 |
+
"""
|
| 235 |
+
筛选出符合预定义实体类型的节点
|
| 236 |
+
|
| 237 |
+
筛选逻辑:
|
| 238 |
+
- 如果节点的Labels只有一个"Entity",说明这个实体不符合我们预定义的类型,跳过
|
| 239 |
+
- 如果节点的Labels包含除"Entity"和"Node"之外的标签,说明符合预定义类型,保留
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
graph_id: 图谱ID
|
| 243 |
+
defined_entity_types: 预定义的实体类型列表(可选,如果提供则只保留这些类型)
|
| 244 |
+
enrich_with_edges: 是否获取每个实体的相关边信息
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
FilteredEntities: 过滤后的实体集合
|
| 248 |
+
"""
|
| 249 |
+
logger.info(f"开始筛选图谱 {graph_id} 的实体...")
|
| 250 |
+
|
| 251 |
+
# 获取所有节点
|
| 252 |
+
all_nodes = self.get_all_nodes(graph_id)
|
| 253 |
+
total_count = len(all_nodes)
|
| 254 |
+
|
| 255 |
+
# 获取所有边(用于后续关联查找)
|
| 256 |
+
all_edges = self.get_all_edges(graph_id) if enrich_with_edges else []
|
| 257 |
+
|
| 258 |
+
# 构建节点UUID到节点数据的映射
|
| 259 |
+
node_map = {n["uuid"]: n for n in all_nodes}
|
| 260 |
+
|
| 261 |
+
# 筛选符合条件的实体
|
| 262 |
+
filtered_entities = []
|
| 263 |
+
entity_types_found = set()
|
| 264 |
+
|
| 265 |
+
for node in all_nodes:
|
| 266 |
+
labels = node.get("labels", [])
|
| 267 |
+
|
| 268 |
+
# 筛选逻辑:Labels必须包含除"Entity"和"Node"之外的标签
|
| 269 |
+
custom_labels = [l for l in labels if l not in ["Entity", "Node"]]
|
| 270 |
+
|
| 271 |
+
if not custom_labels:
|
| 272 |
+
# 只有默认标签,跳过
|
| 273 |
+
continue
|
| 274 |
+
|
| 275 |
+
# 如果指定了预定义类型��检查是否匹配
|
| 276 |
+
if defined_entity_types:
|
| 277 |
+
matching_labels = [l for l in custom_labels if l in defined_entity_types]
|
| 278 |
+
if not matching_labels:
|
| 279 |
+
continue
|
| 280 |
+
entity_type = matching_labels[0]
|
| 281 |
+
else:
|
| 282 |
+
entity_type = custom_labels[0]
|
| 283 |
+
|
| 284 |
+
entity_types_found.add(entity_type)
|
| 285 |
+
|
| 286 |
+
# 创建实体节点对象
|
| 287 |
+
entity = EntityNode(
|
| 288 |
+
uuid=node["uuid"],
|
| 289 |
+
name=node["name"],
|
| 290 |
+
labels=labels,
|
| 291 |
+
summary=node["summary"],
|
| 292 |
+
attributes=node["attributes"],
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
# 获取相关边和节点
|
| 296 |
+
if enrich_with_edges:
|
| 297 |
+
related_edges = []
|
| 298 |
+
related_node_uuids = set()
|
| 299 |
+
|
| 300 |
+
for edge in all_edges:
|
| 301 |
+
if edge["source_node_uuid"] == node["uuid"]:
|
| 302 |
+
related_edges.append({
|
| 303 |
+
"direction": "outgoing",
|
| 304 |
+
"edge_name": edge["name"],
|
| 305 |
+
"fact": edge["fact"],
|
| 306 |
+
"target_node_uuid": edge["target_node_uuid"],
|
| 307 |
+
})
|
| 308 |
+
related_node_uuids.add(edge["target_node_uuid"])
|
| 309 |
+
elif edge["target_node_uuid"] == node["uuid"]:
|
| 310 |
+
related_edges.append({
|
| 311 |
+
"direction": "incoming",
|
| 312 |
+
"edge_name": edge["name"],
|
| 313 |
+
"fact": edge["fact"],
|
| 314 |
+
"source_node_uuid": edge["source_node_uuid"],
|
| 315 |
+
})
|
| 316 |
+
related_node_uuids.add(edge["source_node_uuid"])
|
| 317 |
+
|
| 318 |
+
entity.related_edges = related_edges
|
| 319 |
+
|
| 320 |
+
# 获取关联节点的基本信息
|
| 321 |
+
related_nodes = []
|
| 322 |
+
for related_uuid in related_node_uuids:
|
| 323 |
+
if related_uuid in node_map:
|
| 324 |
+
related_node = node_map[related_uuid]
|
| 325 |
+
related_nodes.append({
|
| 326 |
+
"uuid": related_node["uuid"],
|
| 327 |
+
"name": related_node["name"],
|
| 328 |
+
"labels": related_node["labels"],
|
| 329 |
+
"summary": related_node.get("summary", ""),
|
| 330 |
+
})
|
| 331 |
+
|
| 332 |
+
entity.related_nodes = related_nodes
|
| 333 |
+
|
| 334 |
+
filtered_entities.append(entity)
|
| 335 |
+
|
| 336 |
+
logger.info(f"筛选完成: 总节点 {total_count}, 符合条件 {len(filtered_entities)}, "
|
| 337 |
+
f"实体类型: {entity_types_found}")
|
| 338 |
+
|
| 339 |
+
return FilteredEntities(
|
| 340 |
+
entities=filtered_entities,
|
| 341 |
+
entity_types=entity_types_found,
|
| 342 |
+
total_count=total_count,
|
| 343 |
+
filtered_count=len(filtered_entities),
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
def get_entity_with_context(
|
| 347 |
+
self,
|
| 348 |
+
graph_id: str,
|
| 349 |
+
entity_uuid: str
|
| 350 |
+
) -> Optional[EntityNode]:
|
| 351 |
+
"""
|
| 352 |
+
获取单个实体及其完整上下文(边和关联节点,带重试机制)
|
| 353 |
+
|
| 354 |
+
Args:
|
| 355 |
+
graph_id: 图谱ID
|
| 356 |
+
entity_uuid: 实体UUID
|
| 357 |
+
|
| 358 |
+
Returns:
|
| 359 |
+
EntityNode或None
|
| 360 |
+
"""
|
| 361 |
+
try:
|
| 362 |
+
# 使用重试机制获取节点
|
| 363 |
+
node = self._call_with_retry(
|
| 364 |
+
func=lambda: self.client.graph.node.get(uuid_=entity_uuid),
|
| 365 |
+
operation_name=f"获取节点详情(uuid={entity_uuid[:8]}...)"
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
if not node:
|
| 369 |
+
return None
|
| 370 |
+
|
| 371 |
+
# 获取节点的边
|
| 372 |
+
edges = self.get_node_edges(entity_uuid)
|
| 373 |
+
|
| 374 |
+
# 获取所有节点用于关联查找
|
| 375 |
+
all_nodes = self.get_all_nodes(graph_id)
|
| 376 |
+
node_map = {n["uuid"]: n for n in all_nodes}
|
| 377 |
+
|
| 378 |
+
# 处理相关边和节点
|
| 379 |
+
related_edges = []
|
| 380 |
+
related_node_uuids = set()
|
| 381 |
+
|
| 382 |
+
for edge in edges:
|
| 383 |
+
if edge["source_node_uuid"] == entity_uuid:
|
| 384 |
+
related_edges.append({
|
| 385 |
+
"direction": "outgoing",
|
| 386 |
+
"edge_name": edge["name"],
|
| 387 |
+
"fact": edge["fact"],
|
| 388 |
+
"target_node_uuid": edge["target_node_uuid"],
|
| 389 |
+
})
|
| 390 |
+
related_node_uuids.add(edge["target_node_uuid"])
|
| 391 |
+
else:
|
| 392 |
+
related_edges.append({
|
| 393 |
+
"direction": "incoming",
|
| 394 |
+
"edge_name": edge["name"],
|
| 395 |
+
"fact": edge["fact"],
|
| 396 |
+
"source_node_uuid": edge["source_node_uuid"],
|
| 397 |
+
})
|
| 398 |
+
related_node_uuids.add(edge["source_node_uuid"])
|
| 399 |
+
|
| 400 |
+
# 获取关联节点信息
|
| 401 |
+
related_nodes = []
|
| 402 |
+
for related_uuid in related_node_uuids:
|
| 403 |
+
if related_uuid in node_map:
|
| 404 |
+
related_node = node_map[related_uuid]
|
| 405 |
+
related_nodes.append({
|
| 406 |
+
"uuid": related_node["uuid"],
|
| 407 |
+
"name": related_node["name"],
|
| 408 |
+
"labels": related_node["labels"],
|
| 409 |
+
"summary": related_node.get("summary", ""),
|
| 410 |
+
})
|
| 411 |
+
|
| 412 |
+
return EntityNode(
|
| 413 |
+
uuid=getattr(node, 'uuid_', None) or getattr(node, 'uuid', ''),
|
| 414 |
+
name=node.name or "",
|
| 415 |
+
labels=node.labels or [],
|
| 416 |
+
summary=node.summary or "",
|
| 417 |
+
attributes=node.attributes or {},
|
| 418 |
+
related_edges=related_edges,
|
| 419 |
+
related_nodes=related_nodes,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
except Exception as e:
|
| 423 |
+
logger.error(f"获取实体 {entity_uuid} 失败: {str(e)}")
|
| 424 |
+
return None
|
| 425 |
+
|
| 426 |
+
def get_entities_by_type(
|
| 427 |
+
self,
|
| 428 |
+
graph_id: str,
|
| 429 |
+
entity_type: str,
|
| 430 |
+
enrich_with_edges: bool = True
|
| 431 |
+
) -> List[EntityNode]:
|
| 432 |
+
"""
|
| 433 |
+
获取指定类型的所有实体
|
| 434 |
+
|
| 435 |
+
Args:
|
| 436 |
+
graph_id: 图谱ID
|
| 437 |
+
entity_type: 实体类型(如 "Student", "PublicFigure" 等)
|
| 438 |
+
enrich_with_edges: 是否获取相关边信息
|
| 439 |
+
|
| 440 |
+
Returns:
|
| 441 |
+
实体列表
|
| 442 |
+
"""
|
| 443 |
+
result = self.filter_defined_entities(
|
| 444 |
+
graph_id=graph_id,
|
| 445 |
+
defined_entity_types=[entity_type],
|
| 446 |
+
enrich_with_edges=enrich_with_edges
|
| 447 |
+
)
|
| 448 |
+
return result.entities
|
| 449 |
+
|
| 450 |
+
|
app/services/zep_graph_memory_updater.py
CHANGED
|
@@ -15,6 +15,7 @@ from queue import Queue, Empty
|
|
| 15 |
from zep_cloud.client import Zep
|
| 16 |
|
| 17 |
from ..config import Config
|
|
|
|
| 18 |
from ..utils.logger import get_logger
|
| 19 |
|
| 20 |
logger = get_logger('mirofish.zep_graph_memory_updater')
|
|
@@ -237,13 +238,12 @@ class ZepGraphMemoryUpdater:
|
|
| 237 |
api_key: Zep API Key(可选,默认从配置读取)
|
| 238 |
"""
|
| 239 |
self.graph_id = graph_id
|
| 240 |
-
self.
|
| 241 |
-
|
|
|
|
| 242 |
if not self.api_key:
|
| 243 |
raise ValueError("ZEP_API_KEY未配置")
|
| 244 |
|
| 245 |
-
self.client = Zep(api_key=self.api_key)
|
| 246 |
-
|
| 247 |
# 活动队列
|
| 248 |
self._activity_queue: Queue = Queue()
|
| 249 |
|
|
@@ -405,11 +405,24 @@ class ZepGraphMemoryUpdater:
|
|
| 405 |
# 带重试的发送
|
| 406 |
for attempt in range(self.MAX_RETRIES):
|
| 407 |
try:
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
|
| 414 |
self._total_sent += 1
|
| 415 |
self._total_items_sent += len(activities)
|
|
|
|
| 15 |
from zep_cloud.client import Zep
|
| 16 |
|
| 17 |
from ..config import Config
|
| 18 |
+
from ..utils.api_key_runtime import call_with_limit_rotation, get_zep_key
|
| 19 |
from ..utils.logger import get_logger
|
| 20 |
|
| 21 |
logger = get_logger('mirofish.zep_graph_memory_updater')
|
|
|
|
| 238 |
api_key: Zep API Key(可选,默认从配置读取)
|
| 239 |
"""
|
| 240 |
self.graph_id = graph_id
|
| 241 |
+
self._fixed_api_key = (api_key or "").strip() or None
|
| 242 |
+
self.api_key = self._fixed_api_key or (Config.get_zep_api_keys()[0] if Config.get_zep_api_keys() else None)
|
| 243 |
+
|
| 244 |
if not self.api_key:
|
| 245 |
raise ValueError("ZEP_API_KEY未配置")
|
| 246 |
|
|
|
|
|
|
|
| 247 |
# 活动队列
|
| 248 |
self._activity_queue: Queue = Queue()
|
| 249 |
|
|
|
|
| 405 |
# 带重试的发送
|
| 406 |
for attempt in range(self.MAX_RETRIES):
|
| 407 |
try:
|
| 408 |
+
def _add():
|
| 409 |
+
k = self._fixed_api_key or get_zep_key()
|
| 410 |
+
if not k:
|
| 411 |
+
raise ValueError("ZEP_API_KEY未配置")
|
| 412 |
+
return Zep(api_key=k).graph.add(
|
| 413 |
+
graph_id=self.graph_id,
|
| 414 |
+
type="text",
|
| 415 |
+
data=combined_text,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
if self._fixed_api_key:
|
| 419 |
+
Zep(api_key=self._fixed_api_key).graph.add(
|
| 420 |
+
graph_id=self.graph_id,
|
| 421 |
+
type="text",
|
| 422 |
+
data=combined_text,
|
| 423 |
+
)
|
| 424 |
+
else:
|
| 425 |
+
call_with_limit_rotation(_add)
|
| 426 |
|
| 427 |
self._total_sent += 1
|
| 428 |
self._total_items_sent += len(activities)
|
app/services/zep_tools.py
CHANGED
|
@@ -16,6 +16,7 @@ from dataclasses import dataclass, field
|
|
| 16 |
from zep_cloud.client import Zep
|
| 17 |
|
| 18 |
from ..config import Config
|
|
|
|
| 19 |
from ..utils.logger import get_logger
|
| 20 |
from ..utils.llm_client import LLMClient
|
| 21 |
from ..utils.zep_paging import fetch_all_nodes, fetch_all_edges
|
|
@@ -422,14 +423,25 @@ class ZepToolsService:
|
|
| 422 |
RETRY_DELAY = 2.0
|
| 423 |
|
| 424 |
def __init__(self, api_key: Optional[str] = None, llm_client: Optional[LLMClient] = None):
|
| 425 |
-
self.
|
| 426 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
raise ValueError("ZEP_API_KEY 未配置")
|
| 428 |
-
|
| 429 |
-
self.client = Zep(api_key=self.api_key)
|
| 430 |
# LLM客户端用于InsightForge生成子问题
|
| 431 |
self._llm_client = llm_client
|
| 432 |
logger.info("ZepToolsService 初始化完成")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
@property
|
| 435 |
def llm(self) -> LLMClient:
|
|
@@ -446,7 +458,7 @@ class ZepToolsService:
|
|
| 446 |
|
| 447 |
for attempt in range(max_retries):
|
| 448 |
try:
|
| 449 |
-
return
|
| 450 |
except Exception as e:
|
| 451 |
last_exception = e
|
| 452 |
if attempt < max_retries - 1:
|
|
@@ -659,7 +671,7 @@ class ZepToolsService:
|
|
| 659 |
"""
|
| 660 |
logger.info(f"获取图谱 {graph_id} 的所有节点...")
|
| 661 |
|
| 662 |
-
nodes = fetch_all_nodes(self.client, graph_id)
|
| 663 |
|
| 664 |
result = []
|
| 665 |
for node in nodes:
|
|
@@ -688,7 +700,7 @@ class ZepToolsService:
|
|
| 688 |
"""
|
| 689 |
logger.info(f"获取图谱 {graph_id} 的所有边...")
|
| 690 |
|
| 691 |
-
edges = fetch_all_edges(self.client, graph_id)
|
| 692 |
|
| 693 |
result = []
|
| 694 |
for edge in edges:
|
|
|
|
| 16 |
from zep_cloud.client import Zep
|
| 17 |
|
| 18 |
from ..config import Config
|
| 19 |
+
from ..utils.api_key_runtime import call_with_limit_rotation, get_zep_key
|
| 20 |
from ..utils.logger import get_logger
|
| 21 |
from ..utils.llm_client import LLMClient
|
| 22 |
from ..utils.zep_paging import fetch_all_nodes, fetch_all_edges
|
|
|
|
| 423 |
RETRY_DELAY = 2.0
|
| 424 |
|
| 425 |
def __init__(self, api_key: Optional[str] = None, llm_client: Optional[LLMClient] = None):
|
| 426 |
+
self._fixed_api_key = (api_key or "").strip() or None
|
| 427 |
+
if self._fixed_api_key:
|
| 428 |
+
self.api_key = self._fixed_api_key
|
| 429 |
+
elif Config.get_zep_api_keys():
|
| 430 |
+
self.api_key = Config.get_zep_api_keys()[0]
|
| 431 |
+
else:
|
| 432 |
raise ValueError("ZEP_API_KEY 未配置")
|
|
|
|
|
|
|
| 433 |
# LLM客户端用于InsightForge生成子问题
|
| 434 |
self._llm_client = llm_client
|
| 435 |
logger.info("ZepToolsService 初始化完成")
|
| 436 |
+
|
| 437 |
+
@property
|
| 438 |
+
def client(self) -> Zep:
|
| 439 |
+
if self._fixed_api_key:
|
| 440 |
+
return Zep(api_key=self._fixed_api_key)
|
| 441 |
+
k = get_zep_key()
|
| 442 |
+
if not k:
|
| 443 |
+
raise ValueError("ZEP_API_KEY 未配置")
|
| 444 |
+
return Zep(api_key=k)
|
| 445 |
|
| 446 |
@property
|
| 447 |
def llm(self) -> LLMClient:
|
|
|
|
| 458 |
|
| 459 |
for attempt in range(max_retries):
|
| 460 |
try:
|
| 461 |
+
return call_with_limit_rotation(func)
|
| 462 |
except Exception as e:
|
| 463 |
last_exception = e
|
| 464 |
if attempt < max_retries - 1:
|
|
|
|
| 671 |
"""
|
| 672 |
logger.info(f"获取图谱 {graph_id} 的所有节点...")
|
| 673 |
|
| 674 |
+
nodes = call_with_limit_rotation(lambda: fetch_all_nodes(self.client, graph_id))
|
| 675 |
|
| 676 |
result = []
|
| 677 |
for node in nodes:
|
|
|
|
| 700 |
"""
|
| 701 |
logger.info(f"获取图谱 {graph_id} 的所有边...")
|
| 702 |
|
| 703 |
+
edges = call_with_limit_rotation(lambda: fetch_all_edges(self.client, graph_id))
|
| 704 |
|
| 705 |
result = []
|
| 706 |
for edge in edges:
|
app/utils/api_key_runtime.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Shared LLM + Zep API key slot (same index for both) with rate-limit handling:
|
| 3 |
+
try primary → on limit try secondary → on limit sleep 60s → retry from primary once more.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import contextvars
|
| 9 |
+
import time
|
| 10 |
+
from typing import Any, Callable, TypeVar
|
| 11 |
+
|
| 12 |
+
from ..config import Config
|
| 13 |
+
from ..utils.logger import get_logger
|
| 14 |
+
|
| 15 |
+
logger = get_logger("mirofish.api_key_runtime")
|
| 16 |
+
|
| 17 |
+
T = TypeVar("T")
|
| 18 |
+
|
| 19 |
+
_key_slot: contextvars.ContextVar[int] = contextvars.ContextVar("miro_api_key_slot", default=0)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def reset_pipeline_api_keys() -> None:
|
| 23 |
+
"""Call at the start of each full pipeline run (worker thread)."""
|
| 24 |
+
_key_slot.set(0)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def current_key_slot() -> int:
|
| 28 |
+
return _key_slot.get()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _max_key_slots() -> int:
|
| 32 |
+
lk = Config.get_llm_api_keys()
|
| 33 |
+
zk = Config.get_zep_api_keys()
|
| 34 |
+
n = max(len(lk or []), len(zk or []), 1)
|
| 35 |
+
return n
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def set_key_slot(i: int) -> None:
|
| 39 |
+
n = _max_key_slots()
|
| 40 |
+
_key_slot.set(max(0, min(i, n - 1)))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def get_llm_key() -> str | None:
|
| 44 |
+
keys = Config.get_llm_api_keys()
|
| 45 |
+
if not keys:
|
| 46 |
+
return None
|
| 47 |
+
i = min(_key_slot.get(), len(keys) - 1)
|
| 48 |
+
return keys[i]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_zep_key() -> str | None:
|
| 52 |
+
keys = Config.get_zep_api_keys()
|
| 53 |
+
if not keys:
|
| 54 |
+
return None
|
| 55 |
+
i = min(_key_slot.get(), len(keys) - 1)
|
| 56 |
+
return keys[i]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def is_rate_limit_error(exc: BaseException) -> bool:
|
| 60 |
+
try:
|
| 61 |
+
import openai
|
| 62 |
+
|
| 63 |
+
if isinstance(exc, getattr(openai, "RateLimitError", ())):
|
| 64 |
+
return True
|
| 65 |
+
if isinstance(exc, getattr(openai, "APIStatusError", ())):
|
| 66 |
+
if getattr(exc, "status_code", None) == 429:
|
| 67 |
+
return True
|
| 68 |
+
except Exception:
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
st = getattr(exc, "status_code", None)
|
| 72 |
+
if st == 429:
|
| 73 |
+
return True
|
| 74 |
+
|
| 75 |
+
msg = str(exc).lower()
|
| 76 |
+
for phrase in (
|
| 77 |
+
"rate limit",
|
| 78 |
+
"429",
|
| 79 |
+
"too many requests",
|
| 80 |
+
"quota",
|
| 81 |
+
"resource_exhausted",
|
| 82 |
+
"resource exhausted",
|
| 83 |
+
"throttl",
|
| 84 |
+
"over capacity",
|
| 85 |
+
"capacity",
|
| 86 |
+
):
|
| 87 |
+
if phrase in msg:
|
| 88 |
+
return True
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def is_auth_or_invalid_key_error(exc: BaseException) -> bool:
|
| 93 |
+
"""401 / invalid API key — rotate to next paired slot when LLM_2/ZEP_2 exist."""
|
| 94 |
+
try:
|
| 95 |
+
import openai
|
| 96 |
+
|
| 97 |
+
if isinstance(exc, getattr(openai, "AuthenticationError", ())):
|
| 98 |
+
return True
|
| 99 |
+
if isinstance(exc, getattr(openai, "APIStatusError", ())):
|
| 100 |
+
if getattr(exc, "status_code", None) == 401:
|
| 101 |
+
return True
|
| 102 |
+
except Exception:
|
| 103 |
+
pass
|
| 104 |
+
|
| 105 |
+
if getattr(exc, "status_code", None) == 401:
|
| 106 |
+
return True
|
| 107 |
+
|
| 108 |
+
msg = str(exc).lower()
|
| 109 |
+
if "invalid api key" in msg or "invalid_api_key" in msg:
|
| 110 |
+
return True
|
| 111 |
+
if "401" in msg and ("unauthorized" in msg or "authentication" in msg):
|
| 112 |
+
return True
|
| 113 |
+
return False
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def should_rotate_api_key(exc: BaseException) -> bool:
|
| 117 |
+
return is_rate_limit_error(exc) or is_auth_or_invalid_key_error(exc)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def call_with_limit_rotation(op: Callable[[], T]) -> T:
|
| 121 |
+
"""
|
| 122 |
+
Run op() using keys at the current slot. On rate-limit:
|
| 123 |
+
advance to next key slot if available; else sleep 60s, reset to slot 0, try again;
|
| 124 |
+
if still rate-limited after that full cycle, re-raise.
|
| 125 |
+
"""
|
| 126 |
+
cooldown_used = False
|
| 127 |
+
last_exc: BaseException | None = None
|
| 128 |
+
|
| 129 |
+
while True:
|
| 130 |
+
try:
|
| 131 |
+
return op()
|
| 132 |
+
except BaseException as e:
|
| 133 |
+
if not should_rotate_api_key(e):
|
| 134 |
+
raise
|
| 135 |
+
last_exc = e
|
| 136 |
+
idx = current_key_slot()
|
| 137 |
+
n = _max_key_slots()
|
| 138 |
+
if idx + 1 < n:
|
| 139 |
+
set_key_slot(idx + 1)
|
| 140 |
+
logger.warning(
|
| 141 |
+
"Rate limit hit; switching API key slot to %s (LLM+Zep)", current_key_slot()
|
| 142 |
+
)
|
| 143 |
+
continue
|
| 144 |
+
if not cooldown_used:
|
| 145 |
+
logger.warning("Rate limit on all API key slots; sleeping 60s then retrying from slot 0")
|
| 146 |
+
time.sleep(60)
|
| 147 |
+
cooldown_used = True
|
| 148 |
+
set_key_slot(0)
|
| 149 |
+
continue
|
| 150 |
+
raise last_exc from None
|
app/utils/llm_client.py
CHANGED
|
@@ -9,6 +9,7 @@ from typing import Optional, Dict, Any, List
|
|
| 9 |
from openai import OpenAI
|
| 10 |
|
| 11 |
from ..config import Config
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
class LLMClient:
|
|
@@ -20,17 +21,12 @@ class LLMClient:
|
|
| 20 |
base_url: Optional[str] = None,
|
| 21 |
model: Optional[str] = None
|
| 22 |
):
|
| 23 |
-
self.
|
| 24 |
self.base_url = base_url or Config.LLM_BASE_URL
|
| 25 |
self.model = model or Config.LLM_MODEL_NAME
|
| 26 |
-
|
| 27 |
-
if not self.
|
| 28 |
-
raise ValueError("
|
| 29 |
-
|
| 30 |
-
self.client = OpenAI(
|
| 31 |
-
api_key=self.api_key,
|
| 32 |
-
base_url=self.base_url
|
| 33 |
-
)
|
| 34 |
|
| 35 |
def chat(
|
| 36 |
self,
|
|
@@ -60,8 +56,19 @@ class LLMClient:
|
|
| 60 |
|
| 61 |
if response_format:
|
| 62 |
kwargs["response_format"] = response_format
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
content = response.choices[0].message.content
|
| 66 |
# 部分模型(如MiniMax M2.5)会在content中包含<think>思考内容,需要移除
|
| 67 |
content = re.sub(r'<think>[\s\S]*?</think>', '', content).strip()
|
|
|
|
| 9 |
from openai import OpenAI
|
| 10 |
|
| 11 |
from ..config import Config
|
| 12 |
+
from .api_key_runtime import call_with_limit_rotation, get_llm_key
|
| 13 |
|
| 14 |
|
| 15 |
class LLMClient:
|
|
|
|
| 21 |
base_url: Optional[str] = None,
|
| 22 |
model: Optional[str] = None
|
| 23 |
):
|
| 24 |
+
self._fixed_api_key = (api_key or "").strip() or None
|
| 25 |
self.base_url = base_url or Config.LLM_BASE_URL
|
| 26 |
self.model = model or Config.LLM_MODEL_NAME
|
| 27 |
+
|
| 28 |
+
if not self._fixed_api_key and not Config.get_llm_api_keys():
|
| 29 |
+
raise ValueError("LLM API key not configured (set LLM_1 or LLM_API_KEY)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
def chat(
|
| 32 |
self,
|
|
|
|
| 56 |
|
| 57 |
if response_format:
|
| 58 |
kwargs["response_format"] = response_format
|
| 59 |
+
|
| 60 |
+
def _create():
|
| 61 |
+
key = (self._fixed_api_key or get_llm_key() or "").strip()
|
| 62 |
+
if not key:
|
| 63 |
+
raise ValueError("LLM API key not configured (set LLM_1 / LLM_2 or LLM_API_KEY)")
|
| 64 |
+
client = OpenAI(api_key=key, base_url=self.base_url)
|
| 65 |
+
return client.chat.completions.create(**kwargs)
|
| 66 |
+
|
| 67 |
+
response = (
|
| 68 |
+
_create()
|
| 69 |
+
if self._fixed_api_key
|
| 70 |
+
else call_with_limit_rotation(_create)
|
| 71 |
+
)
|
| 72 |
content = response.choices[0].message.content
|
| 73 |
# 部分模型(如MiniMax M2.5)会在content中包含<think>思考内容,需要移除
|
| 74 |
content = re.sub(r'<think>[\s\S]*?</think>', '', content).strip()
|
app/utils/mirofish_jwt.py
CHANGED
|
@@ -1,59 +1,59 @@
|
|
| 1 |
-
"""Short-lived session JWTs for public.User logins (signed by the backend only)."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
import time
|
| 6 |
-
from typing import Optional, Tuple
|
| 7 |
-
|
| 8 |
-
import jwt
|
| 9 |
-
|
| 10 |
-
from ..config import Config
|
| 11 |
-
|
| 12 |
-
MIROFISH_ISS = "mirofish"
|
| 13 |
-
MIROFISH_AUD = "mirofish-web"
|
| 14 |
-
# Default 14 days
|
| 15 |
-
DEFAULT_TTL_SEC = 14 * 24 * 60 * 60
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def _signing_secret() -> str:
|
| 19 |
-
if (Config.MIROFISH_SESSION_JWT_SECRET or "").strip():
|
| 20 |
-
return Config.MIROFISH_SESSION_JWT_SECRET.strip()
|
| 21 |
-
return (Config.SECRET_KEY or "").strip() or "change-me"
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
def issue_session_token(user_id: str, ttl_sec: int = DEFAULT_TTL_SEC) -> str:
|
| 25 |
-
now = int(time.time())
|
| 26 |
-
payload = {
|
| 27 |
-
"sub": str(user_id),
|
| 28 |
-
"iat": now,
|
| 29 |
-
"exp": now + ttl_sec,
|
| 30 |
-
"iss": MIROFISH_ISS,
|
| 31 |
-
"aud": MIROFISH_AUD,
|
| 32 |
-
}
|
| 33 |
-
return jwt.encode(payload, _signing_secret(), algorithm="HS256")
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def verify_mirofish_session_jwt(token: str) -> Tuple[Optional[str], Optional[str]]:
|
| 37 |
-
"""
|
| 38 |
-
Returns (user_id, None) on success, (None, error_hint) on failure.
|
| 39 |
-
error_hint is None if the token is simply not a MiroFish session JWT (try Supabase next).
|
| 40 |
-
"""
|
| 41 |
-
if not token:
|
| 42 |
-
return None, "missing"
|
| 43 |
-
try:
|
| 44 |
-
payload = jwt.decode(
|
| 45 |
-
token,
|
| 46 |
-
_signing_secret(),
|
| 47 |
-
algorithms=["HS256"],
|
| 48 |
-
audience=MIROFISH_AUD,
|
| 49 |
-
issuer=MIROFISH_ISS,
|
| 50 |
-
options={"verify_exp": True},
|
| 51 |
-
)
|
| 52 |
-
sub = payload.get("sub")
|
| 53 |
-
if not sub:
|
| 54 |
-
return None, "invalid"
|
| 55 |
-
return str(sub), None
|
| 56 |
-
except jwt.ExpiredSignatureError:
|
| 57 |
-
return None, "expired"
|
| 58 |
-
except jwt.InvalidTokenError:
|
| 59 |
-
return None, None
|
|
|
|
| 1 |
+
"""Short-lived session JWTs for public.User logins (signed by the backend only)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import time
|
| 6 |
+
from typing import Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import jwt
|
| 9 |
+
|
| 10 |
+
from ..config import Config
|
| 11 |
+
|
| 12 |
+
MIROFISH_ISS = "mirofish"
|
| 13 |
+
MIROFISH_AUD = "mirofish-web"
|
| 14 |
+
# Default 14 days
|
| 15 |
+
DEFAULT_TTL_SEC = 14 * 24 * 60 * 60
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _signing_secret() -> str:
|
| 19 |
+
if (Config.MIROFISH_SESSION_JWT_SECRET or "").strip():
|
| 20 |
+
return Config.MIROFISH_SESSION_JWT_SECRET.strip()
|
| 21 |
+
return (Config.SECRET_KEY or "").strip() or "change-me"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def issue_session_token(user_id: str, ttl_sec: int = DEFAULT_TTL_SEC) -> str:
|
| 25 |
+
now = int(time.time())
|
| 26 |
+
payload = {
|
| 27 |
+
"sub": str(user_id),
|
| 28 |
+
"iat": now,
|
| 29 |
+
"exp": now + ttl_sec,
|
| 30 |
+
"iss": MIROFISH_ISS,
|
| 31 |
+
"aud": MIROFISH_AUD,
|
| 32 |
+
}
|
| 33 |
+
return jwt.encode(payload, _signing_secret(), algorithm="HS256")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def verify_mirofish_session_jwt(token: str) -> Tuple[Optional[str], Optional[str]]:
|
| 37 |
+
"""
|
| 38 |
+
Returns (user_id, None) on success, (None, error_hint) on failure.
|
| 39 |
+
error_hint is None if the token is simply not a MiroFish session JWT (try Supabase next).
|
| 40 |
+
"""
|
| 41 |
+
if not token:
|
| 42 |
+
return None, "missing"
|
| 43 |
+
try:
|
| 44 |
+
payload = jwt.decode(
|
| 45 |
+
token,
|
| 46 |
+
_signing_secret(),
|
| 47 |
+
algorithms=["HS256"],
|
| 48 |
+
audience=MIROFISH_AUD,
|
| 49 |
+
issuer=MIROFISH_ISS,
|
| 50 |
+
options={"verify_exp": True},
|
| 51 |
+
)
|
| 52 |
+
sub = payload.get("sub")
|
| 53 |
+
if not sub:
|
| 54 |
+
return None, "invalid"
|
| 55 |
+
return str(sub), None
|
| 56 |
+
except jwt.ExpiredSignatureError:
|
| 57 |
+
return None, "expired"
|
| 58 |
+
except jwt.InvalidTokenError:
|
| 59 |
+
return None, None
|
app/utils/supabase_auth.py
CHANGED
|
@@ -1,80 +1,80 @@
|
|
| 1 |
-
"""Verify caller identity for /api/pipeline/* — Bearer JWTs and/or pipeline client headers."""
|
| 2 |
-
|
| 3 |
-
from __future__ import annotations
|
| 4 |
-
|
| 5 |
-
from typing import Optional, Tuple
|
| 6 |
-
|
| 7 |
-
import jwt
|
| 8 |
-
|
| 9 |
-
from flask import request
|
| 10 |
-
|
| 11 |
-
from ..config import Config
|
| 12 |
-
from .mirofish_jwt import verify_mirofish_session_jwt
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
def verify_supabase_user_jwt(token: str) -> Tuple[Optional[str], Optional[str]]:
|
| 16 |
-
"""
|
| 17 |
-
Returns (user_id, error_message). user_id is None on failure.
|
| 18 |
-
"""
|
| 19 |
-
if not token or not Config.SUPABASE_JWT_SECRET:
|
| 20 |
-
return None, "JWT verification not configured"
|
| 21 |
-
try:
|
| 22 |
-
payload = jwt.decode(
|
| 23 |
-
token,
|
| 24 |
-
Config.SUPABASE_JWT_SECRET,
|
| 25 |
-
algorithms=["HS256"],
|
| 26 |
-
audience="authenticated",
|
| 27 |
-
options={"verify_exp": True},
|
| 28 |
-
)
|
| 29 |
-
sub = payload.get("sub")
|
| 30 |
-
if not sub:
|
| 31 |
-
return None, "Invalid token: missing sub"
|
| 32 |
-
return str(sub), None
|
| 33 |
-
except jwt.ExpiredSignatureError:
|
| 34 |
-
return None, "Token expired"
|
| 35 |
-
except jwt.InvalidTokenError as e:
|
| 36 |
-
return None, f"Invalid token: {e}"
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def extract_bearer_token() -> Optional[str]:
|
| 40 |
-
h = request.headers.get("Authorization", "")
|
| 41 |
-
if h.lower().startswith("bearer "):
|
| 42 |
-
return h[7:].strip()
|
| 43 |
-
return None
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def resolve_pipeline_user_id() -> Tuple[Optional[str], Optional[str]]:
|
| 47 |
-
"""
|
| 48 |
-
When Supabase sync is on:
|
| 49 |
-
|
| 50 |
-
1) Authorization: Bearer <MiroFish session JWT> (optional / legacy).
|
| 51 |
-
2) Authorization: Bearer <Supabase Auth JWT> if SUPABASE_JWT_SECRET is set.
|
| 52 |
-
3) X-Mirofish-User-Id + X-Pipeline-Client-Secret matching PIPELINE_CLIENT_SECRET
|
| 53 |
-
(Supabase public.User in browser + VITE_PIPELINE_CLIENT_SECRET).
|
| 54 |
-
|
| 55 |
-
Returns (user_id_str, error_message).
|
| 56 |
-
"""
|
| 57 |
-
token = extract_bearer_token()
|
| 58 |
-
if token:
|
| 59 |
-
m_uid, m_hint = verify_mirofish_session_jwt(token)
|
| 60 |
-
if m_uid:
|
| 61 |
-
return m_uid, None
|
| 62 |
-
if m_hint == "expired":
|
| 63 |
-
return None, "Token expired"
|
| 64 |
-
if Config.SUPABASE_JWT_SECRET:
|
| 65 |
-
s_uid, s_err = verify_supabase_user_jwt(token)
|
| 66 |
-
if s_uid:
|
| 67 |
-
return s_uid, None
|
| 68 |
-
return None, s_err or "Invalid token"
|
| 69 |
-
return None, "Invalid token"
|
| 70 |
-
|
| 71 |
-
uid = (request.headers.get("X-Mirofish-User-Id") or "").strip()
|
| 72 |
-
key = (request.headers.get("X-Pipeline-Client-Secret") or "").strip()
|
| 73 |
-
secret = (Config.PIPELINE_CLIENT_SECRET or "").strip()
|
| 74 |
-
if uid and secret and key == secret:
|
| 75 |
-
return uid, None
|
| 76 |
-
if uid or key:
|
| 77 |
-
return None, "Invalid pipeline client credentials"
|
| 78 |
-
if not secret:
|
| 79 |
-
return None, "Server PIPELINE_CLIENT_SECRET is not configured"
|
| 80 |
-
return None, "Missing credentials"
|
|
|
|
| 1 |
+
"""Verify caller identity for /api/pipeline/* — Bearer JWTs and/or pipeline client headers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from typing import Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import jwt
|
| 8 |
+
|
| 9 |
+
from flask import request
|
| 10 |
+
|
| 11 |
+
from ..config import Config
|
| 12 |
+
from .mirofish_jwt import verify_mirofish_session_jwt
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def verify_supabase_user_jwt(token: str) -> Tuple[Optional[str], Optional[str]]:
|
| 16 |
+
"""
|
| 17 |
+
Returns (user_id, error_message). user_id is None on failure.
|
| 18 |
+
"""
|
| 19 |
+
if not token or not Config.SUPABASE_JWT_SECRET:
|
| 20 |
+
return None, "JWT verification not configured"
|
| 21 |
+
try:
|
| 22 |
+
payload = jwt.decode(
|
| 23 |
+
token,
|
| 24 |
+
Config.SUPABASE_JWT_SECRET,
|
| 25 |
+
algorithms=["HS256"],
|
| 26 |
+
audience="authenticated",
|
| 27 |
+
options={"verify_exp": True},
|
| 28 |
+
)
|
| 29 |
+
sub = payload.get("sub")
|
| 30 |
+
if not sub:
|
| 31 |
+
return None, "Invalid token: missing sub"
|
| 32 |
+
return str(sub), None
|
| 33 |
+
except jwt.ExpiredSignatureError:
|
| 34 |
+
return None, "Token expired"
|
| 35 |
+
except jwt.InvalidTokenError as e:
|
| 36 |
+
return None, f"Invalid token: {e}"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def extract_bearer_token() -> Optional[str]:
|
| 40 |
+
h = request.headers.get("Authorization", "")
|
| 41 |
+
if h.lower().startswith("bearer "):
|
| 42 |
+
return h[7:].strip()
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def resolve_pipeline_user_id() -> Tuple[Optional[str], Optional[str]]:
|
| 47 |
+
"""
|
| 48 |
+
When Supabase sync is on:
|
| 49 |
+
|
| 50 |
+
1) Authorization: Bearer <MiroFish session JWT> (optional / legacy).
|
| 51 |
+
2) Authorization: Bearer <Supabase Auth JWT> if SUPABASE_JWT_SECRET is set.
|
| 52 |
+
3) X-Mirofish-User-Id + X-Pipeline-Client-Secret matching PIPELINE_CLIENT_SECRET
|
| 53 |
+
(Supabase public.User in browser + VITE_PIPELINE_CLIENT_SECRET).
|
| 54 |
+
|
| 55 |
+
Returns (user_id_str, error_message).
|
| 56 |
+
"""
|
| 57 |
+
token = extract_bearer_token()
|
| 58 |
+
if token:
|
| 59 |
+
m_uid, m_hint = verify_mirofish_session_jwt(token)
|
| 60 |
+
if m_uid:
|
| 61 |
+
return m_uid, None
|
| 62 |
+
if m_hint == "expired":
|
| 63 |
+
return None, "Token expired"
|
| 64 |
+
if Config.SUPABASE_JWT_SECRET:
|
| 65 |
+
s_uid, s_err = verify_supabase_user_jwt(token)
|
| 66 |
+
if s_uid:
|
| 67 |
+
return s_uid, None
|
| 68 |
+
return None, s_err or "Invalid token"
|
| 69 |
+
return None, "Invalid token"
|
| 70 |
+
|
| 71 |
+
uid = (request.headers.get("X-Mirofish-User-Id") or "").strip()
|
| 72 |
+
key = (request.headers.get("X-Pipeline-Client-Secret") or "").strip()
|
| 73 |
+
secret = (Config.PIPELINE_CLIENT_SECRET or "").strip()
|
| 74 |
+
if uid and secret and key == secret:
|
| 75 |
+
return uid, None
|
| 76 |
+
if uid or key:
|
| 77 |
+
return None, "Invalid pipeline client credentials"
|
| 78 |
+
if not secret:
|
| 79 |
+
return None, "Server PIPELINE_CLIENT_SECRET is not configured"
|
| 80 |
+
return None, "Missing credentials"
|
requirements.txt
CHANGED
|
@@ -13,3 +13,4 @@ python-dotenv>=1.0.0
|
|
| 13 |
pydantic>=2.0.0
|
| 14 |
supabase>=2.10.0
|
| 15 |
PyJWT>=2.8.0
|
|
|
|
|
|
| 13 |
pydantic>=2.0.0
|
| 14 |
supabase>=2.10.0
|
| 15 |
PyJWT>=2.8.0
|
| 16 |
+
razorpay>=1.4.0
|
supabase/INSTALL_SIMULATION_RUNS.sql
CHANGED
|
@@ -1,39 +1,39 @@
|
|
| 1 |
-
-- =============================================================================
|
| 2 |
-
-- Fix: PGRST205 "Could not find the table 'public.simulation_runs' in the schema cache"
|
| 3 |
-
-- =============================================================================
|
| 4 |
-
-- 1. Open Supabase Dashboard → your project → SQL Editor → New query.
|
| 5 |
-
-- 2. Paste and run this entire script.
|
| 6 |
-
-- 3. If the API still errors after ~1 minute, run the last line alone to reload PostgREST.
|
| 7 |
-
-- 4. Create Storage bucket "reports" (private) under Storage if you use report files.
|
| 8 |
-
-- =============================================================================
|
| 9 |
-
|
| 10 |
-
create table if not exists public.simulation_runs (
|
| 11 |
-
id uuid primary key,
|
| 12 |
-
user_id text not null,
|
| 13 |
-
backend_task_id text,
|
| 14 |
-
report_id text,
|
| 15 |
-
status text not null default 'pending',
|
| 16 |
-
requirement_preview text,
|
| 17 |
-
report_storage_path text,
|
| 18 |
-
report_public_url text,
|
| 19 |
-
simulation_id text,
|
| 20 |
-
project_id text,
|
| 21 |
-
error_message text,
|
| 22 |
-
created_at timestamptz not null default now(),
|
| 23 |
-
updated_at timestamptz not null default now()
|
| 24 |
-
);
|
| 25 |
-
|
| 26 |
-
create index if not exists simulation_runs_user_id_idx on public.simulation_runs (user_id);
|
| 27 |
-
create index if not exists simulation_runs_status_idx on public.simulation_runs (status);
|
| 28 |
-
|
| 29 |
-
alter table public.simulation_runs enable row level security;
|
| 30 |
-
|
| 31 |
-
drop policy if exists "simulation_runs_select_own" on public.simulation_runs;
|
| 32 |
-
create policy "simulation_runs_select_own"
|
| 33 |
-
on public.simulation_runs for select
|
| 34 |
-
to authenticated
|
| 35 |
-
using (auth.uid()::text = user_id);
|
| 36 |
-
|
| 37 |
-
-- If the table exists but REST still returns PGRST205, wait ~1 min or pause/resume the project
|
| 38 |
-
-- in Dashboard → Settings. (Uncomment below only if your project supports it.)
|
| 39 |
-
-- select pg_notify('pgrst', 'reload schema');
|
|
|
|
| 1 |
+
-- =============================================================================
|
| 2 |
+
-- Fix: PGRST205 "Could not find the table 'public.simulation_runs' in the schema cache"
|
| 3 |
+
-- =============================================================================
|
| 4 |
+
-- 1. Open Supabase Dashboard → your project → SQL Editor → New query.
|
| 5 |
+
-- 2. Paste and run this entire script.
|
| 6 |
+
-- 3. If the API still errors after ~1 minute, run the last line alone to reload PostgREST.
|
| 7 |
+
-- 4. Create Storage bucket "reports" (private) under Storage if you use report files.
|
| 8 |
+
-- =============================================================================
|
| 9 |
+
|
| 10 |
+
create table if not exists public.simulation_runs (
|
| 11 |
+
id uuid primary key,
|
| 12 |
+
user_id text not null,
|
| 13 |
+
backend_task_id text,
|
| 14 |
+
report_id text,
|
| 15 |
+
status text not null default 'pending',
|
| 16 |
+
requirement_preview text,
|
| 17 |
+
report_storage_path text,
|
| 18 |
+
report_public_url text,
|
| 19 |
+
simulation_id text,
|
| 20 |
+
project_id text,
|
| 21 |
+
error_message text,
|
| 22 |
+
created_at timestamptz not null default now(),
|
| 23 |
+
updated_at timestamptz not null default now()
|
| 24 |
+
);
|
| 25 |
+
|
| 26 |
+
create index if not exists simulation_runs_user_id_idx on public.simulation_runs (user_id);
|
| 27 |
+
create index if not exists simulation_runs_status_idx on public.simulation_runs (status);
|
| 28 |
+
|
| 29 |
+
alter table public.simulation_runs enable row level security;
|
| 30 |
+
|
| 31 |
+
drop policy if exists "simulation_runs_select_own" on public.simulation_runs;
|
| 32 |
+
create policy "simulation_runs_select_own"
|
| 33 |
+
on public.simulation_runs for select
|
| 34 |
+
to authenticated
|
| 35 |
+
using (auth.uid()::text = user_id);
|
| 36 |
+
|
| 37 |
+
-- If the table exists but REST still returns PGRST205, wait ~1 min or pause/resume the project
|
| 38 |
+
-- in Dashboard → Settings. (Uncomment below only if your project supports it.)
|
| 39 |
+
-- select pg_notify('pgrst', 'reload schema');
|
supabase/grants_public_user.sql
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
-- Required when login/sign-up run in the browser against public."User" (Supabase anon key).
|
| 2 |
-
-- Run in SQL Editor after your "User" table exists.
|
| 3 |
-
|
| 4 |
-
grant usage on schema public to anon, authenticated;
|
| 5 |
-
|
| 6 |
-
grant select, insert on table public."User" to anon;
|
| 7 |
-
|
| 8 |
-
-- Production: prefer hashed passwords + RPC/Edge Function instead of plain Password in the client.
|
|
|
|
| 1 |
+
-- Required when login/sign-up run in the browser against public."User" (Supabase anon key).
|
| 2 |
+
-- Run in SQL Editor after your "User" table exists.
|
| 3 |
+
|
| 4 |
+
grant usage on schema public to anon, authenticated;
|
| 5 |
+
|
| 6 |
+
grant select, insert on table public."User" to anon;
|
| 7 |
+
|
| 8 |
+
-- Production: prefer hashed passwords + RPC/Edge Function instead of plain Password in the client.
|
supabase/migration_simulation_runs_user_id_text.sql
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
-
-- Run once if you already had simulation_runs.user_id as uuid referencing auth.users.
|
| 2 |
-
-- After this, the API can store string user ids from public."User" (e.g. "12").
|
| 3 |
-
|
| 4 |
-
alter table public.simulation_runs drop constraint if exists simulation_runs_user_id_fkey;
|
| 5 |
-
|
| 6 |
-
alter table public.simulation_runs
|
| 7 |
-
alter column user_id type text using user_id::text;
|
| 8 |
-
|
| 9 |
-
drop policy if exists "simulation_runs_select_own" on public.simulation_runs;
|
| 10 |
-
create policy "simulation_runs_select_own"
|
| 11 |
-
on public.simulation_runs for select
|
| 12 |
-
to authenticated
|
| 13 |
-
using (auth.uid()::text = user_id);
|
|
|
|
| 1 |
+
-- Run once if you already had simulation_runs.user_id as uuid referencing auth.users.
|
| 2 |
+
-- After this, the API can store string user ids from public."User" (e.g. "12").
|
| 3 |
+
|
| 4 |
+
alter table public.simulation_runs drop constraint if exists simulation_runs_user_id_fkey;
|
| 5 |
+
|
| 6 |
+
alter table public.simulation_runs
|
| 7 |
+
alter column user_id type text using user_id::text;
|
| 8 |
+
|
| 9 |
+
drop policy if exists "simulation_runs_select_own" on public.simulation_runs;
|
| 10 |
+
create policy "simulation_runs_select_own"
|
| 11 |
+
on public.simulation_runs for select
|
| 12 |
+
to authenticated
|
| 13 |
+
using (auth.uid()::text = user_id);
|
supabase/schema.sql
CHANGED
|
@@ -1,55 +1,55 @@
|
|
| 1 |
-
-- Run in Supabase SQL Editor after creating a project.
|
| 2 |
-
-- If you see PGRST205 (table not in schema cache), create the table first — see INSTALL_SIMULATION_RUNS.sql
|
| 3 |
-
-- 1) Create Storage bucket named "reports" (private).
|
| 4 |
-
-- 2) Apply this script (or run INSTALL_SIMULATION_RUNS.sql for table+RLS only, then storage section below).
|
| 5 |
-
|
| 6 |
-
-- user_id is TEXT so it can hold auth.users UUID strings OR public."User" bigint ids as strings (e.g. "5").
|
| 7 |
-
create table if not exists public.simulation_runs (
|
| 8 |
-
id uuid primary key,
|
| 9 |
-
user_id text not null,
|
| 10 |
-
backend_task_id text,
|
| 11 |
-
report_id text,
|
| 12 |
-
status text not null default 'pending',
|
| 13 |
-
requirement_preview text,
|
| 14 |
-
report_storage_path text,
|
| 15 |
-
report_public_url text,
|
| 16 |
-
simulation_id text,
|
| 17 |
-
project_id text,
|
| 18 |
-
error_message text,
|
| 19 |
-
created_at timestamptz not null default now(),
|
| 20 |
-
updated_at timestamptz not null default now()
|
| 21 |
-
);
|
| 22 |
-
|
| 23 |
-
create index if not exists simulation_runs_user_id_idx on public.simulation_runs (user_id);
|
| 24 |
-
create index if not exists simulation_runs_status_idx on public.simulation_runs (status);
|
| 25 |
-
|
| 26 |
-
alter table public.simulation_runs enable row level security;
|
| 27 |
-
|
| 28 |
-
drop policy if exists "simulation_runs_select_own" on public.simulation_runs;
|
| 29 |
-
-- JWT users (Supabase Auth) can read their own rows when user_id matches auth.uid() as text.
|
| 30 |
-
create policy "simulation_runs_select_own"
|
| 31 |
-
on public.simulation_runs for select
|
| 32 |
-
to authenticated
|
| 33 |
-
using (auth.uid()::text = user_id);
|
| 34 |
-
|
| 35 |
-
-- Custom public."User" accounts use the backend API + service role; RLS still applies to anon.
|
| 36 |
-
|
| 37 |
-
-- Storage: allow signed URL downloads for files under the user's folder (JWT uid as first path segment).
|
| 38 |
-
drop policy if exists "reports_select_own" on storage.objects;
|
| 39 |
-
create policy "reports_select_own"
|
| 40 |
-
on storage.objects for select
|
| 41 |
-
to authenticated
|
| 42 |
-
using (
|
| 43 |
-
bucket_id = 'reports'
|
| 44 |
-
and (storage.foldername(name))[1] = auth.uid()::text
|
| 45 |
-
);
|
| 46 |
-
|
| 47 |
-
-- Optional: custom app table (manage in Table Editor). Example:
|
| 48 |
-
-- create table public."User" (
|
| 49 |
-
-- id bigint generated by default as identity primary key,
|
| 50 |
-
-- created_at timestamptz not null default now(),
|
| 51 |
-
-- "Username" text not null,
|
| 52 |
-
-- "Email" text not null unique,
|
| 53 |
-
-- "Password" text not null
|
| 54 |
-
-- );
|
| 55 |
-
-- Grant anon select/insert on "User" only if you accept client-side checks (prefer Edge Functions + hashing for production).
|
|
|
|
| 1 |
+
-- Run in Supabase SQL Editor after creating a project.
|
| 2 |
+
-- If you see PGRST205 (table not in schema cache), create the table first — see INSTALL_SIMULATION_RUNS.sql
|
| 3 |
+
-- 1) Create Storage bucket named "reports" (private).
|
| 4 |
+
-- 2) Apply this script (or run INSTALL_SIMULATION_RUNS.sql for table+RLS only, then storage section below).
|
| 5 |
+
|
| 6 |
+
-- user_id is TEXT so it can hold auth.users UUID strings OR public."User" bigint ids as strings (e.g. "5").
|
| 7 |
+
create table if not exists public.simulation_runs (
|
| 8 |
+
id uuid primary key,
|
| 9 |
+
user_id text not null,
|
| 10 |
+
backend_task_id text,
|
| 11 |
+
report_id text,
|
| 12 |
+
status text not null default 'pending',
|
| 13 |
+
requirement_preview text,
|
| 14 |
+
report_storage_path text,
|
| 15 |
+
report_public_url text,
|
| 16 |
+
simulation_id text,
|
| 17 |
+
project_id text,
|
| 18 |
+
error_message text,
|
| 19 |
+
created_at timestamptz not null default now(),
|
| 20 |
+
updated_at timestamptz not null default now()
|
| 21 |
+
);
|
| 22 |
+
|
| 23 |
+
create index if not exists simulation_runs_user_id_idx on public.simulation_runs (user_id);
|
| 24 |
+
create index if not exists simulation_runs_status_idx on public.simulation_runs (status);
|
| 25 |
+
|
| 26 |
+
alter table public.simulation_runs enable row level security;
|
| 27 |
+
|
| 28 |
+
drop policy if exists "simulation_runs_select_own" on public.simulation_runs;
|
| 29 |
+
-- JWT users (Supabase Auth) can read their own rows when user_id matches auth.uid() as text.
|
| 30 |
+
create policy "simulation_runs_select_own"
|
| 31 |
+
on public.simulation_runs for select
|
| 32 |
+
to authenticated
|
| 33 |
+
using (auth.uid()::text = user_id);
|
| 34 |
+
|
| 35 |
+
-- Custom public."User" accounts use the backend API + service role; RLS still applies to anon.
|
| 36 |
+
|
| 37 |
+
-- Storage: allow signed URL downloads for files under the user's folder (JWT uid as first path segment).
|
| 38 |
+
drop policy if exists "reports_select_own" on storage.objects;
|
| 39 |
+
create policy "reports_select_own"
|
| 40 |
+
on storage.objects for select
|
| 41 |
+
to authenticated
|
| 42 |
+
using (
|
| 43 |
+
bucket_id = 'reports'
|
| 44 |
+
and (storage.foldername(name))[1] = auth.uid()::text
|
| 45 |
+
);
|
| 46 |
+
|
| 47 |
+
-- Optional: custom app table (manage in Table Editor). Example:
|
| 48 |
+
-- create table public."User" (
|
| 49 |
+
-- id bigint generated by default as identity primary key,
|
| 50 |
+
-- created_at timestamptz not null default now(),
|
| 51 |
+
-- "Username" text not null,
|
| 52 |
+
-- "Email" text not null unique,
|
| 53 |
+
-- "Password" text not null
|
| 54 |
+
-- );
|
| 55 |
+
-- Grant anon select/insert on "User" only if you accept client-side checks (prefer Edge Functions + hashing for production).
|