chore(align): sync Git with running container as authoritative source
One-time alignment to close drift between the running container (qihu-aiflow / image qihuaiflow:with-deps) and this Git repository. Container hotfixes previously persisted only via `docker commit` are now captured in Git so Git becomes the single source of truth. Backend: - chat_service.py: accumulated fixes incl. EigenFlux README guidance - chat_context.py / chat_media.py: URL/web-repo context injection - api/url_reader.py: NEW SSRF-safe web/README reader (Issue #725) - skills_admin.py & Skills.tsx: 14-scene capability unification - pgvector_search.py, orchestrator.py, platform_knowledge.py, market.py, admin/models.py: drift sync Frontend: - ChatPage.tsx: collapsible AI think/act block (Issue #724) - MarketPage / EvolutionDashboard / TokenDashboard styling sync Migrations: - 018_normalize_marketapp_scene.sql: fixed capability allowlist (prevents capability wipe on restart) Alignment performed 2026-07-23 05:42:47. No deletions; secrets/venv/node_modules/ caches were not touched (tracked-source-only copy).
This commit is contained in:
1 parent
49f7503978
commit
a08ec87b22
19 files changed
+7474
-7196
No files matched your search
@@ -932,7 +932,13 @@ async def test_model_connection(
|
||||
"n": 1,
|
||||
"size": "1024x1024",
|
||||
}
|
||||
resp = await client.post(image_url, json=payload, headers=headers)
|
||||
# 与运行时媒体生成一致:用 _proxy_for_url 解析代理并 trust_env=False;
|
||||
# 图像端点会被 _proxy_for_url 判定为直连(公网 API 直连比代理更稳定)
|
||||
from ..chat_utils import _proxy_for_url
|
||||
async with httpx.AsyncClient(
|
||||
timeout=timeout, proxy=_proxy_for_url(image_url), trust_env=False
|
||||
) as img_client:
|
||||
resp = await img_client.post(image_url, json=payload, headers=headers)
|
||||
latency = int((time.time() - start) * 1000)
|
||||
|
||||
if resp.status_code == 200:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1121,7 +1121,7 @@ def _build_system_prompt(
|
||||
|
||||
all_mcp: list = None,
|
||||
|
||||
|
||||
db: Session = None,
|
||||
|
||||
) -> tuple:
|
||||
|
||||
@@ -1195,7 +1195,7 @@ def _build_system_prompt(
|
||||
|
||||
|
||||
|
||||
pk = get_platform_knowledge()
|
||||
pk = get_platform_knowledge(db=db)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1566,11 +1566,16 @@ async def _generate_media_task(ai_msg_id: str, ai_model_id: str, prompt: str, us
|
||||
|
||||
|
||||
except Exception as e:
|
||||
|
||||
|
||||
|
||||
logger.warning(f"[_generate_media_task] 后台生成异常: {e}")
|
||||
|
||||
logger.warning(f"[_generate_media_task] 后台生成异常: {e}", exc_info=True)
|
||||
# 兜底回写:任何意外异常都不能让消息永久停在「⏳ 生成中…」
|
||||
try:
|
||||
db.rollback()
|
||||
_err = db.query(Message).filter(Message.id == ai_msg_id).first()
|
||||
if _err and str(_err.content or "").startswith("⏳"):
|
||||
_err.content = "⚠️ 媒体生成失败,请稍后重试"
|
||||
db.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
finally:
|
||||
|
||||
+4304
-4273
File diff suppressed because it is too large.
Load diff
@@ -1,387 +1,387 @@
|
||||
# Auto-extracted from chat.py during Phase 1 refactor (Strangler Fig).
|
||||
# Source of truth: scripts/phase1_extract.py. Do not hand-merge back.
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import and_, desc, asc, func
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import re
|
||||
import json
|
||||
import asyncio
|
||||
import math
|
||||
import httpx
|
||||
import os
|
||||
import logging
|
||||
from ..database import get_db, SessionLocal
|
||||
from ..models import (
|
||||
|
||||
|
||||
|
||||
User, Conversation, Message, AIModel, ModelProvider, TokenUsageLog,
|
||||
|
||||
|
||||
|
||||
KnowledgeBase, KnowledgeDocument, KnowledgeDocumentChunk, EvolutionSkill,
|
||||
|
||||
|
||||
|
||||
EvolutionTrajectory, MarketApp, AppPurchase, AppInstallation,
|
||||
|
||||
|
||||
|
||||
MCPServer,
|
||||
|
||||
|
||||
|
||||
gen_uuid
|
||||
|
||||
|
||||
|
||||
)
|
||||
from ..auth import get_current_user
|
||||
from ..platform_knowledge import get_platform_knowledge
|
||||
from ..mcp_client import list_mcp_tools, call_mcp_tool
|
||||
from ..middleware.log_service import LogService
|
||||
from ..capability_registry import resolve_auto_model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CST_TZ = timezone(timedelta(hours=8))
|
||||
|
||||
def cst_now():
|
||||
|
||||
|
||||
|
||||
"""Get current time in CST timezone"""
|
||||
|
||||
|
||||
|
||||
return datetime.now(CST_TZ)
|
||||
|
||||
def _html_escape(s: str) -> str:
|
||||
|
||||
|
||||
|
||||
return (str(s).replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
|
||||
|
||||
|
||||
.replace('"', """).replace("'", "'"))
|
||||
|
||||
def _outbound_proxy() -> str:
|
||||
|
||||
|
||||
|
||||
"""出网代理地址(兜底)。默认经 172.18.0.1:7890 智能路由代理;
|
||||
|
||||
|
||||
|
||||
运行时若未注入代理环境变量则回退到该地址。"""
|
||||
|
||||
|
||||
|
||||
import os
|
||||
|
||||
|
||||
|
||||
return os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or "http://172.18.0.1:7890"
|
||||
|
||||
_HK_PROXY = "http://qyyfw:XHR521yhf@103.242.14.208:11495"
|
||||
|
||||
def _proxy_for_url(url: str) -> str | None:
|
||||
|
||||
|
||||
|
||||
"""按目标域名选择是否走代理。
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
2026-07-15 调整:AGNES(apihub.agnes-ai.com / platform-outputs.agnes-ai.space)
|
||||
|
||||
|
||||
|
||||
经用户实测走香港代理 103.242.14.208:11495 延迟更低、更稳定,故改为走 HK 代理
|
||||
|
||||
|
||||
|
||||
(带鉴权),不再直连,也不经智能路由代理(172.18.0.1:7890 对 AGNES 返 502)。
|
||||
|
||||
|
||||
|
||||
其余国内/平台域名直连,真正的境外域名走 _outbound_proxy()。
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
注意:httpx 默认 trust_env=True 会忽略 proxy 参数而改用环境变量 HTTP_PROXY,
|
||||
|
||||
|
||||
|
||||
故调用方必须同时传 trust_env=False 才能真正走此处指定的代理。
|
||||
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
||||
|
||||
import os
|
||||
|
||||
|
||||
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
|
||||
host = (urlparse(url).hostname or "").lower()
|
||||
|
||||
|
||||
|
||||
# 文生图 / 视频生成走直连:智能路由代理(172.18.0.1:7890)与 HK 代理对这类长耗时、
|
||||
# 大响应体的生成连接会偶发重置(Server disconnected),而各图像/视频供应商均为公网
|
||||
# API,直连更稳定(已实测 gpt-image-2 / agnes 直连均返回 200)。故媒体端点统一直连。
|
||||
_lower = (url or "").lower()
|
||||
if "/images/" in _lower or "/videos/" in _lower or "/v1/images" in _lower or "/v1/videos" in _lower:
|
||||
return None
|
||||
|
||||
|
||||
|
||||
if "agnes-ai.com" in host or "agnes-ai.space" in host:
|
||||
|
||||
|
||||
|
||||
return _HK_PROXY
|
||||
|
||||
|
||||
|
||||
# 平台自有域名(含自建 Dify/n8n 等)必须直连,不经出网代理。
|
||||
|
||||
|
||||
|
||||
if "qihuyun.com" in host:
|
||||
|
||||
|
||||
|
||||
return None
|
||||
|
||||
|
||||
|
||||
# 尊重 NO_PROXY:国内域名(硅基流动/DeepSeek/小米MoE 等)直连更稳定,
|
||||
|
||||
|
||||
|
||||
# 避免经易波动的智能路由代理 172.18.0.1:7890(对国内域名偶发连接重置)。
|
||||
|
||||
|
||||
|
||||
_no_proxy = [h.strip().lower() for h in os.environ.get("NO_PROXY", "").split(",") if h.strip()]
|
||||
|
||||
|
||||
|
||||
for _np in _no_proxy:
|
||||
|
||||
|
||||
|
||||
if host == _np or host.endswith("." + _np) or _np in host:
|
||||
|
||||
|
||||
|
||||
return None
|
||||
|
||||
|
||||
|
||||
return _outbound_proxy()
|
||||
|
||||
def _extract_text_from_json(obj) -> str:
|
||||
|
||||
|
||||
|
||||
"""从 n8n / 通用 webhook 的任意 JSON 响应中尽力抽取文本回答。"""
|
||||
|
||||
|
||||
|
||||
if obj is None:
|
||||
|
||||
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
if isinstance(obj, str):
|
||||
|
||||
|
||||
|
||||
return obj
|
||||
|
||||
|
||||
|
||||
if isinstance(obj, (int, float, bool)):
|
||||
|
||||
|
||||
|
||||
return str(obj)
|
||||
|
||||
|
||||
|
||||
if isinstance(obj, list):
|
||||
|
||||
|
||||
|
||||
# 取第一个可抽取到文本的元素
|
||||
|
||||
|
||||
|
||||
for it in obj:
|
||||
|
||||
|
||||
|
||||
t = _extract_text_from_json(it)
|
||||
|
||||
|
||||
|
||||
if t:
|
||||
|
||||
|
||||
|
||||
return t
|
||||
|
||||
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
if isinstance(obj, dict):
|
||||
|
||||
|
||||
|
||||
# 常见回答字段优先级
|
||||
|
||||
|
||||
|
||||
for k in ("output", "text", "answer", "response", "reply",
|
||||
|
||||
|
||||
|
||||
"message", "content", "result", "data"):
|
||||
|
||||
|
||||
|
||||
if k in obj:
|
||||
|
||||
|
||||
|
||||
t = _extract_text_from_json(obj[k])
|
||||
|
||||
|
||||
|
||||
if t:
|
||||
|
||||
|
||||
|
||||
return t
|
||||
|
||||
|
||||
|
||||
# 兜底:整体序列化
|
||||
|
||||
|
||||
|
||||
try:
|
||||
|
||||
|
||||
|
||||
return json.dumps(obj, ensure_ascii=False)
|
||||
|
||||
|
||||
|
||||
except Exception:
|
||||
|
||||
|
||||
|
||||
return str(obj)
|
||||
|
||||
|
||||
|
||||
return str(obj)
|
||||
|
||||
class CreateConversationRequest(BaseModel):
|
||||
|
||||
|
||||
|
||||
title: str = Field(default="新对话")
|
||||
|
||||
|
||||
|
||||
model_id: Optional[str] = None
|
||||
|
||||
class UpdateConversationRequest(BaseModel):
|
||||
|
||||
|
||||
|
||||
title: Optional[str] = None
|
||||
|
||||
|
||||
|
||||
status: Optional[str] = None # active, archived
|
||||
|
||||
|
||||
|
||||
pinned: Optional[bool] = None
|
||||
|
||||
|
||||
|
||||
agent_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
skill_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
knowledge_base_ids: Optional[list] = None
|
||||
|
||||
class SendMessageRequest(BaseModel):
|
||||
|
||||
|
||||
|
||||
content: str
|
||||
|
||||
|
||||
|
||||
model_id: Optional[str] = None
|
||||
|
||||
|
||||
|
||||
skill_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
agent_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
knowledge_base_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
mcp_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
attachments: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
use_tools: Optional[bool] = False
|
||||
# Auto-extracted from chat.py during Phase 1 refactor (Strangler Fig).
|
||||
# Source of truth: scripts/phase1_extract.py. Do not hand-merge back.
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import and_, desc, asc, func
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import re
|
||||
import json
|
||||
import asyncio
|
||||
import math
|
||||
import httpx
|
||||
import os
|
||||
import logging
|
||||
from ..database import get_db, SessionLocal
|
||||
from ..models import (
|
||||
|
||||
|
||||
|
||||
User, Conversation, Message, AIModel, ModelProvider, TokenUsageLog,
|
||||
|
||||
|
||||
|
||||
KnowledgeBase, KnowledgeDocument, KnowledgeDocumentChunk, EvolutionSkill,
|
||||
|
||||
|
||||
|
||||
EvolutionTrajectory, MarketApp, AppPurchase, AppInstallation,
|
||||
|
||||
|
||||
|
||||
MCPServer,
|
||||
|
||||
|
||||
|
||||
gen_uuid
|
||||
|
||||
|
||||
|
||||
)
|
||||
from ..auth import get_current_user
|
||||
from ..platform_knowledge import get_platform_knowledge
|
||||
from ..mcp_client import list_mcp_tools, call_mcp_tool
|
||||
from ..middleware.log_service import LogService
|
||||
from ..capability_registry import resolve_auto_model
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CST_TZ = timezone(timedelta(hours=8))
|
||||
|
||||
def cst_now():
|
||||
|
||||
|
||||
|
||||
"""Get current time in CST timezone"""
|
||||
|
||||
|
||||
|
||||
return datetime.now(CST_TZ)
|
||||
|
||||
def _html_escape(s: str) -> str:
|
||||
|
||||
|
||||
|
||||
return (str(s).replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
|
||||
|
||||
|
||||
.replace('"', """).replace("'", "'"))
|
||||
|
||||
def _outbound_proxy() -> str:
|
||||
|
||||
|
||||
|
||||
"""出网代理地址(兜底)。默认经 172.18.0.1:7890 智能路由代理;
|
||||
|
||||
|
||||
|
||||
运行时若未注入代理环境变量则回退到该地址。"""
|
||||
|
||||
|
||||
|
||||
import os
|
||||
|
||||
|
||||
|
||||
return os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or "http://172.18.0.1:7890"
|
||||
|
||||
_HK_PROXY = "http://qyyfw:XHR521yhf@103.242.14.208:11495"
|
||||
|
||||
def _proxy_for_url(url: str) -> str | None:
|
||||
|
||||
|
||||
|
||||
"""按目标域名选择是否走代理。
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
2026-07-15 调整:AGNES(apihub.agnes-ai.com / platform-outputs.agnes-ai.space)
|
||||
|
||||
|
||||
|
||||
经用户实测走香港代理 103.242.14.208:11495 延迟更低、更稳定,故改为走 HK 代理
|
||||
|
||||
|
||||
|
||||
(带鉴权),不再直连,也不经智能路由代理(172.18.0.1:7890 对 AGNES 返 502)。
|
||||
|
||||
|
||||
|
||||
其余国内/平台域名直连,真正的境外域名走 _outbound_proxy()。
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
注意:httpx 默认 trust_env=True 会忽略 proxy 参数而改用环境变量 HTTP_PROXY,
|
||||
|
||||
|
||||
|
||||
故调用方必须同时传 trust_env=False 才能真正走此处指定的代理。
|
||||
|
||||
|
||||
|
||||
"""
|
||||
|
||||
|
||||
|
||||
import os
|
||||
|
||||
|
||||
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
|
||||
host = (urlparse(url).hostname or "").lower()
|
||||
|
||||
|
||||
|
||||
# 文生图 / 视频生成走直连:智能路由代理(172.18.0.1:7890)与 HK 代理对这类长耗时、
|
||||
# 大响应体的生成连接会偶发重置(Server disconnected),而各图像/视频供应商均为公网
|
||||
# API,直连更稳定(已实测 gpt-image-2 / agnes 直连均返回 200)。故媒体端点统一直连。
|
||||
_lower = (url or "").lower()
|
||||
if "/images/" in _lower or "/videos/" in _lower or "/v1/images" in _lower or "/v1/videos" in _lower:
|
||||
return None
|
||||
|
||||
|
||||
|
||||
if "agnes-ai.com" in host or "agnes-ai.space" in host:
|
||||
|
||||
|
||||
|
||||
return _HK_PROXY
|
||||
|
||||
|
||||
|
||||
# 平台自有域名(含自建 Dify/n8n 等)必须直连,不经出网代理。
|
||||
|
||||
|
||||
|
||||
if "qihuyun.com" in host:
|
||||
|
||||
|
||||
|
||||
return None
|
||||
|
||||
|
||||
|
||||
# 尊重 NO_PROXY:国内域名(硅基流动/DeepSeek/小米MoE 等)直连更稳定,
|
||||
|
||||
|
||||
|
||||
# 避免经易波动的智能路由代理 172.18.0.1:7890(对国内域名偶发连接重置)。
|
||||
|
||||
|
||||
|
||||
_no_proxy = [h.strip().lower() for h in os.environ.get("NO_PROXY", "").split(",") if h.strip()]
|
||||
|
||||
|
||||
|
||||
for _np in _no_proxy:
|
||||
|
||||
|
||||
|
||||
if host == _np or host.endswith("." + _np) or _np in host:
|
||||
|
||||
|
||||
|
||||
return None
|
||||
|
||||
|
||||
|
||||
return _outbound_proxy()
|
||||
|
||||
def _extract_text_from_json(obj) -> str:
|
||||
|
||||
|
||||
|
||||
"""从 n8n / 通用 webhook 的任意 JSON 响应中尽力抽取文本回答。"""
|
||||
|
||||
|
||||
|
||||
if obj is None:
|
||||
|
||||
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
if isinstance(obj, str):
|
||||
|
||||
|
||||
|
||||
return obj
|
||||
|
||||
|
||||
|
||||
if isinstance(obj, (int, float, bool)):
|
||||
|
||||
|
||||
|
||||
return str(obj)
|
||||
|
||||
|
||||
|
||||
if isinstance(obj, list):
|
||||
|
||||
|
||||
|
||||
# 取第一个可抽取到文本的元素
|
||||
|
||||
|
||||
|
||||
for it in obj:
|
||||
|
||||
|
||||
|
||||
t = _extract_text_from_json(it)
|
||||
|
||||
|
||||
|
||||
if t:
|
||||
|
||||
|
||||
|
||||
return t
|
||||
|
||||
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
|
||||
if isinstance(obj, dict):
|
||||
|
||||
|
||||
|
||||
# 常见回答字段优先级
|
||||
|
||||
|
||||
|
||||
for k in ("output", "text", "answer", "response", "reply",
|
||||
|
||||
|
||||
|
||||
"message", "content", "result", "data"):
|
||||
|
||||
|
||||
|
||||
if k in obj:
|
||||
|
||||
|
||||
|
||||
t = _extract_text_from_json(obj[k])
|
||||
|
||||
|
||||
|
||||
if t:
|
||||
|
||||
|
||||
|
||||
return t
|
||||
|
||||
|
||||
|
||||
# 兜底:整体序列化
|
||||
|
||||
|
||||
|
||||
try:
|
||||
|
||||
|
||||
|
||||
return json.dumps(obj, ensure_ascii=False)
|
||||
|
||||
|
||||
|
||||
except Exception:
|
||||
|
||||
|
||||
|
||||
return str(obj)
|
||||
|
||||
|
||||
|
||||
return str(obj)
|
||||
|
||||
class CreateConversationRequest(BaseModel):
|
||||
|
||||
|
||||
|
||||
title: str = Field(default="新对话")
|
||||
|
||||
|
||||
|
||||
model_id: Optional[str] = None
|
||||
|
||||
class UpdateConversationRequest(BaseModel):
|
||||
|
||||
|
||||
|
||||
title: Optional[str] = None
|
||||
|
||||
|
||||
|
||||
status: Optional[str] = None # active, archived
|
||||
|
||||
|
||||
|
||||
pinned: Optional[bool] = None
|
||||
|
||||
|
||||
|
||||
agent_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
skill_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
knowledge_base_ids: Optional[list] = None
|
||||
|
||||
class SendMessageRequest(BaseModel):
|
||||
|
||||
|
||||
|
||||
content: str
|
||||
|
||||
|
||||
|
||||
model_id: Optional[str] = None
|
||||
|
||||
|
||||
|
||||
skill_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
agent_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
knowledge_base_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
mcp_ids: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
attachments: Optional[list] = None
|
||||
|
||||
|
||||
|
||||
use_tools: Optional[bool] = False
|
||||
@@ -691,7 +691,12 @@ def list_apps(
|
||||
"capability": app.capability or None,
|
||||
"category": app.category or None,
|
||||
"tags": app.tags or None,
|
||||
"installed": (app.id in installed_app_ids or is_user_owned) if user_id else False,
|
||||
# 官方导入并发布的技能默认全局已安装(见 #716:无论前台/后台导入,默认全局安装)
|
||||
"installed": (
|
||||
app.id in installed_app_ids
|
||||
or is_user_owned
|
||||
or (app.source == "official" and app.status == "published")
|
||||
),
|
||||
"version": app.version or "1.0.0",
|
||||
"security_scan": app.security_scan,
|
||||
"verified": bool(app.verified),
|
||||
@@ -756,7 +761,8 @@ def get_app(
|
||||
"tags": app.tags or None,
|
||||
"created_at": str(app.created_at),
|
||||
"purchased": purchased,
|
||||
"installed": installed,
|
||||
# 官方导入并发布的技能默认全局已安装(见 #716)
|
||||
"installed": installed or (app.source == "official" and app.status == "published"),
|
||||
"version": app.version or "1.0.0",
|
||||
"security_scan": app.security_scan,
|
||||
"verified": bool(app.verified),
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
"""服务端 URL 读取器(Issue 2 修复)
|
||||
|
||||
当用户输入包含 URL 且明确要求『读取 / 加入 / 安装 / 分析 / 总结』等意图时,
|
||||
服务端抓取该链接的真实内容并作为参考上下文注入对话,使模型能基于页面真实信息
|
||||
作答(例如按 GitHub 仓库 README 的 Quick Start 引导用户完成安装/加入),
|
||||
而不是凭空编造。
|
||||
|
||||
SSRF 防护:仅允许 http/https;解析域名 IP 后阻断内网/回环/链路本地/云元数据地址;
|
||||
限制跳转、响应体大小与超时。
|
||||
"""
|
||||
import ipaddress
|
||||
import logging
|
||||
import re
|
||||
import socket
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_URL_RE = re.compile(r'https?://[^\s"\)\\\]>]+', re.IGNORECASE)
|
||||
# 触发意图:显式要求读取/加入/安装/分析/总结/打开/访问 等
|
||||
_INTENT_RE = re.compile(
|
||||
r'(read|join|install|fetch|summar|analys|open|visit|access|browse|'
|
||||
r'读取|加入|安装|打开|访问|浏览|总结|分析|抓取|看下这个|查看该|这个网页|这个页面|这个链接|help me join)',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# 常见私有/保留网段(阻断内网扫描与云元数据)
|
||||
_BLOCKED_NETS = [
|
||||
ipaddress.ip_network('10.0.0.0/8'),
|
||||
ipaddress.ip_network('172.16.0.0/12'),
|
||||
ipaddress.ip_network('192.168.0.0/16'),
|
||||
ipaddress.ip_network('127.0.0.0/8'),
|
||||
ipaddress.ip_network('169.254.0.0/16'),
|
||||
ipaddress.ip_network('::1/128'),
|
||||
ipaddress.ip_network('fc00::/7'),
|
||||
ipaddress.ip_network('fe80::/10'),
|
||||
ipaddress.ip_network('0.0.0.0/8'),
|
||||
]
|
||||
|
||||
_MAX_CHARS = 16000
|
||||
_TIMEOUT = 30.0
|
||||
|
||||
|
||||
def _is_blocked_host(host: str) -> bool:
|
||||
host = (host or '').strip().lower()
|
||||
if not host:
|
||||
return True
|
||||
if re.fullmatch(r'(\d{1,3}\.){3}\d{1,3}', host):
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return True
|
||||
return any(ip in net for net in _BLOCKED_NETS)
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, None)
|
||||
for info in infos:
|
||||
ipstr = info[4][0]
|
||||
try:
|
||||
ip = ipaddress.ip_address(ipstr)
|
||||
except ValueError:
|
||||
continue
|
||||
if any(ip in net for net in _BLOCKED_NETS):
|
||||
return True
|
||||
except Exception:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def _make_client():
|
||||
try:
|
||||
return httpx.AsyncClient(trust_env=True, follow_redirects=True, timeout=_TIMEOUT)
|
||||
except Exception:
|
||||
return httpx.AsyncClient(trust_env=False, follow_redirects=True, timeout=_TIMEOUT)
|
||||
|
||||
|
||||
async def _github_text(url: str):
|
||||
p = urlparse(url)
|
||||
if p.netloc.lower() not in ('github.com', 'www.github.com'):
|
||||
return None
|
||||
parts = [x for x in p.path.split('/') if x]
|
||||
if len(parts) < 2:
|
||||
return None
|
||||
owner, repo = parts[0], parts[1]
|
||||
if len(parts) >= 4 and parts[2] == 'blob':
|
||||
ref = parts[3]
|
||||
fpath = '/'.join(parts[4:])
|
||||
raw = f'https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{fpath}'
|
||||
return await _fetch_text(raw)
|
||||
api = f'https://api.github.com/repos/{owner}/{repo}/readme'
|
||||
try:
|
||||
async with await _make_client() as c:
|
||||
r = await c.get(api, headers={
|
||||
'Accept': 'application/vnd.github+json',
|
||||
'User-Agent': 'Mozilla/5.0',
|
||||
})
|
||||
if r.status_code == 200:
|
||||
import base64
|
||||
d = r.json()
|
||||
return base64.b64decode(d.get('content', '')).decode('utf-8', 'replace')
|
||||
except Exception as e:
|
||||
logger.warning('github readme fetch failed: %s', e)
|
||||
return None
|
||||
|
||||
|
||||
async def _fetch_text(url: str) -> str:
|
||||
async with await _make_client() as c:
|
||||
r = await c.get(url, headers={'User-Agent': 'Mozilla/5.0'})
|
||||
r.raise_for_status()
|
||||
data = r.content[:2_000_000]
|
||||
ctype = r.headers.get('content-type', '')
|
||||
text = data.decode('utf-8', 'replace')
|
||||
if 'html' in ctype:
|
||||
return _html_to_text(text)
|
||||
return text
|
||||
|
||||
|
||||
def _html_to_text(html: str) -> str:
|
||||
html = re.sub(r'(?is)<(script|style|head|noscript|svg|template)[^>]*>.*?</\1>', ' ', html)
|
||||
html = re.sub(r'(?is)<!--.*?-->', ' ', html)
|
||||
html = re.sub(r'(?is)<[^>]+>', ' ', html)
|
||||
import html as _html
|
||||
text = _html.unescape(html)
|
||||
text = re.sub(r'[ \t]+', ' ', text)
|
||||
text = re.sub(r'\n{3,}', '\n\n', text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
async def fetch_url_context(text: str):
|
||||
"""若有 URL 且命中读取意图,返回 {'url','text'};否则返回 None。"""
|
||||
if not text:
|
||||
return None
|
||||
m = _URL_RE.search(text)
|
||||
if not m:
|
||||
return None
|
||||
url = m.group(0).rstrip('.,);]')
|
||||
if not _INTENT_RE.search(text):
|
||||
return None
|
||||
try:
|
||||
p = urlparse(url)
|
||||
if p.scheme not in ('http', 'https'):
|
||||
return None
|
||||
if _is_blocked_host(p.hostname):
|
||||
logger.warning('blocked host for url fetch: %s', p.hostname)
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
try:
|
||||
if 'github.com' in (p.hostname or '').lower():
|
||||
body = await _github_text(url)
|
||||
if not body:
|
||||
body = await _fetch_text(url)
|
||||
else:
|
||||
body = await _fetch_text(url)
|
||||
except Exception as e:
|
||||
logger.warning('url fetch failed: %s', e)
|
||||
return None
|
||||
|
||||
if not body or not body.strip():
|
||||
return None
|
||||
return {'url': url, 'text': body[:_MAX_CHARS]}
|
||||
Reference in new issue
Block a user