Commit 52121c88 by 黄南光

修复大模型兼容性问题

修复query中与Ingest中的sources路径对齐问题
1 parent b92fc870
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from src.utils.llm_models import is_default_thinking_enabled, is_multimodal_model
# ================================================================================== # ==================================================================================
# 配置与初始化 # 配置与初始化
...@@ -30,27 +31,24 @@ os.makedirs(METADATA_DIR, exist_ok=True) ...@@ -30,27 +31,24 @@ os.makedirs(METADATA_DIR, exist_ok=True)
API_KEY = os.environ.get("DASHSCOPE_API_KEY") or os.environ.get("OPENAI_API_KEY", "sk-xxx") API_KEY = os.environ.get("DASHSCOPE_API_KEY") or os.environ.get("OPENAI_API_KEY", "sk-xxx")
# 针对不同场景的模型配置 # 针对不同场景的模型配置
INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "deepseek-v4-flash") INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "qwen3.7-plus")
QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "deepseek-v4-flash") QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "deepseek-v4-flash")
LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "deepseek-v4-flash") LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "deepseek-v4-flash")
# INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "qwen3.7-plus")
# INGEST_MODEL_NAME = os.environ.get("INGEST_MODEL_NAME", "qwen3.5-plus") # QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "qwen3.7-plus")
# QUERY_MODEL_NAME = os.environ.get("QUERY_MODEL_NAME", "qwen3.5-flash") # LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "qwen3.7-plus")
# LINT_MODEL_NAME = os.environ.get("LINT_MODEL_NAME", "qwen3.5-flash")
def is_multimodal(model_name: str) -> bool: def is_multimodal(model_name: str) -> bool:
"""是否为带视觉的多模态模型(content 走 list-of-blocks)。 """是否为带视觉的多模态模型(content 走 list-of-blocks)。
判定标准:显式视觉标记 -vl / qvq,或 qwen3.7 系列(qwen3.7-plus 支持图像+文本)。 判定标准:显式视觉标记 -vl / qvq,或 qwen3.7 系列(qwen3.7-plus 支持图像+文本)。
deepseek-v4-flash / qwen-flash / qwen3.6-flash 均为纯文本,返回 False。 deepseek-v4-flash / qwen-flash / qwen3.6-flash 均为纯文本,返回 False。
""" """
name = model_name.lower() return is_multimodal_model(model_name)
return "-vl" in name or name.startswith("qvq") or "qwen3.7" in name
def is_thinking(model_name: str) -> bool: def is_thinking(model_name: str) -> bool:
"""是否开启思考(thinking)模式。deepseek / qwq / qwen3 系列默认开启。""" """是否默认显式传 enable_thinking。当前采用 auto 策略,默认交给模型官方配置。"""
name = model_name.lower() return is_default_thinking_enabled(model_name)
return "deepseek" in name or "qwq" in name or "qwen3" in name
# ================================================================================== # ==================================================================================
......
...@@ -86,7 +86,7 @@ slug 必须按「**作用域实体 + 产品线/主题**」命名,并保证 ** ...@@ -86,7 +86,7 @@ slug 必须按「**作用域实体 + 产品线/主题**」命名,并保证 **
- 实体/政策/流程/话术同理带作用域前缀,**严禁裸名**(不要 `整车延保`,要 `岚图整车延保` 或 `鸿蒙智行官方延保`)。 - 实体/政策/流程/话术同理带作用域前缀,**严禁裸名**(不要 `整车延保`,要 `岚图整车延保` 或 `鸿蒙智行官方延保`)。
- **复用优先**:系统会把现有页面注册表注入你的上下文;若已存在描述同一真实产品/实体的页面,**直接复用其 slug**(系统会自动把本次内容合并入既有页面)。 - **复用优先**:系统会把现有页面注册表注入你的上下文;若已存在描述同一真实产品/实体的页面,**直接复用其 slug**(系统会自动把本次内容合并入既有页面)。
- **slug 全局唯一**:同一 slug 全库只对应一个页面;同一 slug 再次出现(哪怕来自不同来源文件)会**合并**进既有页面,仅当与**不同 type** 的页面撞名才会被打回。 - **slug 全局唯一**:同一 slug 全库只对应一个页面;同一 slug 再次出现(哪怕来自不同来源文件)会**合并**进既有页面,仅当与**不同 type** 的页面撞名才会被打回。
- **目录结构(扁平)**:`file_path` 一律——**只有 sources 用 `ware/wiki/sources/{品牌系列}/{slug}.md`,其余所有 type 一律 `ware/wiki/{type}/{slug}.md`,不加任何品牌/系列子目录**(系统会强制按此归一化路径)。 - **目录结构**:`file_path` 一律由系统归一化;普通页面按 type 扁平落盘为 `ware/wiki/{type}/{slug}.md`,只有 sources 按品牌系列分层为 `ware/wiki/sources/{品牌系列}/{slug}.md`。不要为普通 type 添加品牌/系列子目录。
## Step 3:页面规范写作 (Phase 2: Concurrent Writing) ## Step 3:页面规范写作 (Phase 2: Concurrent Writing)
......
...@@ -65,15 +65,15 @@ description: | ...@@ -65,15 +65,15 @@ description: |
## Step 1:精准定位(务必收敛,尽量少调用工具) ## Step 1:精准定位(务必收敛,尽量少调用工具)
### 1.1 据「知识库地图」直接定位(不要再读 index.md) ### 1.1 据「知识库地图」直接定位(不要再读 index.md)
`ware/wiki/index.md` 的完整内容**已由系统注入到你的提示词**(按 type 分组、`- [[slug]] — 标题`)。 `ware/wiki/index.md` 的完整内容**已由系统注入到提示词**。普通行格式为 `- [[slug]] — 标题`;sources 行会额外带 `| path: ware/wiki/sources/<品牌系列>/<slug>.md`。
**禁止再用 `read_local_file` 读取 index.md**。直接从地图里挑出与意图/品牌最相关的目标 slug。 **禁止再用 `read_local_file` 读取 index.md**。直接从地图里挑出与意图/品牌最相关的目标 slug;如果命中 sources,优先使用该行的 `path:` 完整路径。
### 1.2 直接拼路径读取目标页(优先,≤3 个) ### 1.2 直接拼路径读取目标页(优先,≤3 个)
据 slug 直接拼出物理路径并读取,避免无谓搜索: 据 slug 直接拼出物理路径并读取,避免无谓搜索;但 sources 不能猜扁平路径,必须使用 index 的 `path:` 或先 glob 定位:
```python ```python
# 一般类型:ware/wiki/<type>/<slug>.md # 一般类型:ware/wiki/<type>/<slug>.md
read_local_file(file_path="ware/wiki/scripts/客户嫌贵应对话术.md") read_local_file(file_path="ware/wiki/scripts/客户嫌贵应对话术.md")
# 来源摘要:ware/wiki/sources/<品牌系列>/<slug>.md(系列不确定时用 glob 定位) # 来源摘要:优先使用 index 行里的 path;旧索引没有 path 时,先用 glob 定位)
glob_wiki_files(pattern="ware/wiki/sources/**/某来源.md") glob_wiki_files(pattern="ware/wiki/sources/**/某来源.md")
``` ```
......
...@@ -17,7 +17,7 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Body ...@@ -17,7 +17,7 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Body
from src.database.session import AsyncSessionLocal from src.database.session import AsyncSessionLocal
from src.database.models import WikiFile, WikiFilePage, WikiOperationLog from src.database.models import WikiFile, WikiFilePage, WikiOperationLog
from config import RAW_DIR, SKILLS_DIR, WIKI_DIR, BASE_DIR, INGEST_MODEL_NAME from config import RAW_DIR, SKILLS_DIR, WIKI_DIR, BASE_DIR, INGEST_MODEL_NAME
from src.utils.llm_tracker import current_task_tokens, print_thinking, get_llm_model, load_skill_prompt from src.utils.llm_tracker import current_task_tokens, print_thinking, get_llm_formatter, get_llm_model, load_skill_prompt
from src.tools.document_parser import extract_text_from_file from src.tools.document_parser import extract_text_from_file
from src.tools.wiki_tools import ( from src.tools.wiki_tools import (
...@@ -30,7 +30,6 @@ from src.tools.wiki_tools import ( ...@@ -30,7 +30,6 @@ from src.tools.wiki_tools import (
) )
from agentscope.agent import ReActAgent from agentscope.agent import ReActAgent
from agentscope.message import Msg from agentscope.message import Msg
from agentscope.formatter import DashScopeChatFormatter
from agentscope.tool import Toolkit from agentscope.tool import Toolkit
...@@ -432,7 +431,7 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -432,7 +431,7 @@ async def _run_ingest_agent_impl(file_id: str):
- 切分以**主题**区分,不以原文物理位置区分;务必覆盖原文的每一处内容,**不要遗漏页边/跨页/表格末尾的零散行**。 - 切分以**主题**区分,不以原文物理位置区分;务必覆盖原文的每一处内容,**不要遗漏页边/跨页/表格末尾的零散行**。
- 各页主题应尽量不重叠(同一条事实只在其主题页展开),但当某段内容同时关联多个主题时,**宁可完整归入最相关的那一页,也不要让它落空**。 - 各页主题应尽量不重叠(同一条事实只在其主题页展开),但当某段内容同时关联多个主题时,**宁可完整归入最相关的那一页,也不要让它落空**。
5. 输出的 related_links 必须使用 **slug 简写形式** `[[页面slug]]`(如 `[[岚图整车延保]]`),**禁止全路径、禁止带 .md**;且只能引用你本次规划出的 slug 或注册表中已存在的 slug。 5. 输出的 related_links 必须使用 **slug 简写形式** `[[页面slug]]`(如 `[[岚图整车延保]]`),**禁止全路径、禁止带 .md**;且只能引用你本次规划出的 slug 或注册表中已存在的 slug。
6. 【目录结构】`file_path` 一律扁平:**只有 sources 类用 `ware/wiki/sources/{{品牌系列}}/{{slug}}.md`,其余所有 type 一律 `ware/wiki/{{type}}/{{slug}}.md`(不加任何品牌/系列子目录)**。(注:系统会按此规则强制确定性归一化路径,请勿自行添加子目录。) 6. 【目录结构】`file_path` 由系统确定性归一化:普通页面按 type 扁平落盘为 `ware/wiki/{{type}}/{{slug}}.md`;只有 sources 类按品牌系列分层落盘为 `ware/wiki/sources/{{品牌系列}}/{{slug}}.md`。请勿为普通 type 自行添加品牌/系列子目录。
请务必直接输出一段合法的 JSON,格式如下: 请务必直接输出一段合法的 JSON,格式如下:
{{ {{
...@@ -458,8 +457,8 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -458,8 +457,8 @@ async def _run_ingest_agent_impl(file_id: str):
""" """
planner_agent = ReActAgent( planner_agent = ReActAgent(
name="PlannerAgent", name="PlannerAgent",
model=get_llm_model(INGEST_MODEL_NAME), model=get_llm_model(INGEST_MODEL_NAME, purpose="INGEST"),
formatter=DashScopeChatFormatter(), formatter=get_llm_formatter(INGEST_MODEL_NAME),
sys_prompt=planner_sys_prompt sys_prompt=planner_sys_prompt
) )
# 规划时不开启终端并发打印干扰 # 规划时不开启终端并发打印干扰
...@@ -584,8 +583,8 @@ async def _run_ingest_agent_impl(file_id: str): ...@@ -584,8 +583,8 @@ async def _run_ingest_agent_impl(file_id: str):
writer_agent = ReActAgent( writer_agent = ReActAgent(
name=f"Writer_{page_info.get('slug', 'page')}", name=f"Writer_{page_info.get('slug', 'page')}",
model=get_llm_model(INGEST_MODEL_NAME), model=get_llm_model(INGEST_MODEL_NAME, purpose="INGEST"),
formatter=DashScopeChatFormatter(), formatter=get_llm_formatter(INGEST_MODEL_NAME),
sys_prompt=writer_sys_prompt sys_prompt=writer_sys_prompt
) )
writer_agent.set_console_output_enabled(False) writer_agent.set_console_output_enabled(False)
......
...@@ -14,12 +14,11 @@ from fastapi.responses import StreamingResponse ...@@ -14,12 +14,11 @@ from fastapi.responses import StreamingResponse
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
from config import WIKI_DIR, BASE_DIR, LINT_MODEL_NAME, SKILLS_DIR from config import WIKI_DIR, BASE_DIR, LINT_MODEL_NAME, SKILLS_DIR
from src.utils.llm_tracker import get_llm_model, token_counter_context from src.utils.llm_tracker import get_llm_formatter, get_llm_model, token_counter_context
from src.tools.wiki_tools import read_local_file, write_wiki_file, append_wiki_file, rebuild_index, normalize_br_tags from src.tools.wiki_tools import read_local_file, write_wiki_file, append_wiki_file, rebuild_index, normalize_br_tags
from agentscope.agent import ReActAgent from agentscope.agent import ReActAgent
from agentscope.message import Msg from agentscope.message import Msg
from agentscope.formatter import DashScopeChatFormatter
from agentscope.tool import Toolkit from agentscope.tool import Toolkit
router = APIRouter() router = APIRouter()
...@@ -701,8 +700,8 @@ Phase 1 已自动修复的项(phase1_fixes)单列「自动修复记录」, ...@@ -701,8 +700,8 @@ Phase 1 已自动修复的项(phase1_fixes)单列「自动修复记录」,
agent = ReActAgent( agent = ReActAgent(
name="WikiLinter", name="WikiLinter",
model=get_llm_model(LINT_MODEL_NAME), model=get_llm_model(LINT_MODEL_NAME, purpose="LINT"),
formatter=DashScopeChatFormatter(), formatter=get_llm_formatter(LINT_MODEL_NAME),
sys_prompt=sys_prompt, sys_prompt=sys_prompt,
toolkit=toolkit, toolkit=toolkit,
max_iters=6, max_iters=6,
......
...@@ -12,7 +12,6 @@ from fastapi import APIRouter, Body, HTTPException ...@@ -12,7 +12,6 @@ from fastapi import APIRouter, Body, HTTPException
from fastapi.responses import StreamingResponse from fastapi.responses import StreamingResponse
from agentscope.agent import ReActAgent from agentscope.agent import ReActAgent
from agentscope.formatter import DashScopeChatFormatter
from agentscope.message import Msg from agentscope.message import Msg
from agentscope.tool import Toolkit from agentscope.tool import Toolkit
...@@ -20,7 +19,8 @@ from config import QUERY_MODEL_NAME, WIKI_DIR ...@@ -20,7 +19,8 @@ from config import QUERY_MODEL_NAME, WIKI_DIR
from src.database.models import WikiQueryLog from src.database.models import WikiQueryLog
from src.database.session import AsyncSessionLocal from src.database.session import AsyncSessionLocal
from src.tools.wiki_tools import glob_wiki_files, grep_wiki_files, read_local_file from src.tools.wiki_tools import glob_wiki_files, grep_wiki_files, read_local_file
from src.utils.llm_tracker import get_llm_model, load_skill_prompt, print_thinking, token_counter_context from src.utils.llm_models import extract_text_content, extract_thinking_content
from src.utils.llm_tracker import get_llm_formatter, get_llm_model, load_skill_prompt, print_thinking, token_counter_context
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
router = APIRouter() router = APIRouter()
...@@ -200,16 +200,16 @@ def build_query_agent(history: list) -> ReActAgent: ...@@ -200,16 +200,16 @@ def build_query_agent(history: list) -> ReActAgent:
{history_injection} {history_injection}
【知识库地图(index.md,已为你注入,禁止再用工具读取 index.md)】 【知识库地图(index.md,已为你注入,禁止再用工具读取 index.md)】
下面是全库页面目录,按页面类型分组,每行格式 `- [[slug]] — 标题`。请**直接据此地图定位**目标页面 slug。 下面是全库页面目录,按页面类型分组。普通行格式为 `- [[slug]] — 标题`;sources 行会额外带 `| path: ware/wiki/sources/<品牌系列>/<slug>.md`。请直接据此地图定位目标页面。
{index_map} {index_map}
【页面物理路径规则】(据 slug 直接拼出路径去读,避免无谓搜索) 【页面物理路径规则】(据 slug 直接拼出路径去读,避免无谓搜索)
- 一般类型:`ware/wiki/<type>/<slug>.md`(type 取地图中所属分组,如 products/policies/scripts/procedures/concepts/comparisons/troubleshooting/entities/synthesis)。 - 一般类型:`ware/wiki/<type>/<slug>.md`(type 取地图中所属分组,如 products/policies/scripts/procedures/concepts/comparisons/troubleshooting/entities/synthesis)。
- 来源摘要:`ware/wiki/sources/<品牌系列>/<slug>.md`(系列不确定时用 glob_wiki_files 定位)。 - 来源摘要:优先使用 index.md 中该 sources 条目携带的 `path:` 完整路径读取;如果旧索引没有 path,先调用 `glob_wiki_files(pattern="ware/wiki/sources/**/<slug>.md")` 定位唯一文件,再用 `read_local_file` 读取,禁止直接猜 `ware/wiki/sources/<slug>.md`。
【工作流程(务必收敛,尽量少调用工具)】 【工作流程(务必收敛,尽量少调用工具)】
1. 判断意图并路由(优先级):系统报错/操作受阻→troubleshooting;"能不能说/违规吗"→policies(合规红线);"怎么回/话术"→scripts;产品参数/价格→products;条款/政策→policies;流程/步骤→procedures;对比→comparisons/synthesis;概念→concepts。 1. 判断意图并路由(优先级):系统报错/操作受阻→troubleshooting;"能不能说/违规吗"→policies(合规红线);"怎么回/话术"→scripts;产品参数/价格→products;条款/政策→policies;流程/步骤→procedures;对比→comparisons/synthesis;概念→concepts。
2. 据地图选出最相关的目标 slug,用 read_local_file 直接读 **≤3 个**目标页(路径按上面规则拼)。 2. 据地图选出最相关的目标 slug,用 read_local_file 直接读 **≤3 个**目标页:普通类型按上方规则拼路径;sources 必须优先使用地图中的 `path:`,没有 path 时先 glob 定位。
3. 仅当页面 frontmatter 的 `related` 中有**确有必要**的关联页时,再二跳读取(如产品页→关联 policy 看免责、话术页→关联 concept 看方法论)。 3. 仅当页面 frontmatter 的 `related` 中有**确有必要**的关联页时,再二跳读取(如产品页→关联 policy 看免责、话术页→关联 concept 看方法论)。
4. 基于读到的内容生成最终回答。 4. 基于读到的内容生成最终回答。
- 仅当据图无法定位、或需在正文中查具体数值/罕见词时,才用 grep_wiki_files(兜底)。 - 仅当据图无法定位、或需在正文中查具体数值/罕见词时,才用 grep_wiki_files(兜底)。
...@@ -229,8 +229,8 @@ def build_query_agent(history: list) -> ReActAgent: ...@@ -229,8 +229,8 @@ def build_query_agent(history: list) -> ReActAgent:
""" """
return ReActAgent( return ReActAgent(
name="WikiAssistant", name="WikiAssistant",
model=get_llm_model(QUERY_MODEL_NAME), model=get_llm_model(QUERY_MODEL_NAME, purpose="QUERY"),
formatter=DashScopeChatFormatter(), formatter=get_llm_formatter(QUERY_MODEL_NAME),
sys_prompt=sys_prompt, sys_prompt=sys_prompt,
toolkit=toolkit, toolkit=toolkit,
) )
...@@ -390,7 +390,7 @@ class WikiQueryRunner: ...@@ -390,7 +390,7 @@ class WikiQueryRunner:
return return
# 1) thinking → 思考框(实时) # 1) thinking → 思考框(实时)
thinking_text = "".join(str(b.get("thinking", "")) for b in thinking_blocks).strip() thinking_text = extract_thinking_content(thinking_blocks).strip()
if thinking_text: if thinking_text:
self._emit_reasoning({"id": f"{msg_id}-think", "type": "thought", "content": thinking_text}) self._emit_reasoning({"id": f"{msg_id}-think", "type": "thought", "content": thinking_text})
...@@ -666,7 +666,7 @@ def content_to_reasoning_events(content: Any, msg_id: str) -> list[dict[str, Any ...@@ -666,7 +666,7 @@ def content_to_reasoning_events(content: Any, msg_id: str) -> list[dict[str, Any
) )
elif block_type == "thinking" or "thinking" in content: elif block_type == "thinking" or "thinking" in content:
# 模型内部的 thinking/推理过程 # 模型内部的 thinking/推理过程
thinking = str(content.get("thinking", "")) thinking = extract_thinking_content(content)
if thinking: if thinking:
events.append({"id": msg_id, "type": "thought", "content": thinking}) events.append({"id": msg_id, "type": "thought", "content": thinking})
elif block_type == "text" or "text" in content: elif block_type == "text" or "text" in content:
...@@ -694,26 +694,7 @@ def content_to_reasoning_events(content: Any, msg_id: str) -> list[dict[str, Any ...@@ -694,26 +694,7 @@ def content_to_reasoning_events(content: Any, msg_id: str) -> list[dict[str, Any
def extract_text(content: Any) -> str: def extract_text(content: Any) -> str:
"""提取混合结构数据中的所有纯文本部分并拼接""" """提取混合结构数据中的所有纯文本部分并拼接"""
if content is None: return extract_text_content(content)
return ""
if isinstance(content, str):
return content
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, str):
parts.append(item)
elif isinstance(item, dict):
if item.get("type") == "text" or "text" in item:
parts.append(str(item.get("text", "")))
else:
parts.append(extract_text(item))
return "".join(parts)
if isinstance(content, dict):
if content.get("type") == "text" or "text" in content:
return str(content.get("text", ""))
return ""
return str(content)
def clean_final_answer(text: str) -> str: def clean_final_answer(text: str) -> str:
......
...@@ -17,6 +17,7 @@ from src.rag.config import ( ...@@ -17,6 +17,7 @@ from src.rag.config import (
RAG_QUERY_CACHE_SIZE, RAG_QUERY_CACHE_SIZE,
RAG_QUERY_CACHE_TTL_SECONDS, RAG_QUERY_CACHE_TTL_SECONDS,
) )
from src.utils.llm_models import extract_text_content, extract_thinking_content
from src.utils.llm_tracker import get_llm_model, stream_delta from src.utils.llm_tracker import get_llm_model, stream_delta
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -27,7 +28,7 @@ _embedding_cache: OrderedDict[str, tuple[float, list[float]]] = OrderedDict() ...@@ -27,7 +28,7 @@ _embedding_cache: OrderedDict[str, tuple[float, list[float]]] = OrderedDict()
_cache_lock = threading.RLock() _cache_lock = threading.RLock()
async def chat_once(model_name: str, prompt: str) -> str: async def chat_once(model_name: str, prompt: str, *, purpose: str | None = None) -> str:
""" """
进行单次(非流式)的大语言模型对话请求。 进行单次(非流式)的大语言模型对话请求。
...@@ -35,7 +36,7 @@ async def chat_once(model_name: str, prompt: str) -> str: ...@@ -35,7 +36,7 @@ async def chat_once(model_name: str, prompt: str) -> str:
:param prompt: 构建好的完整提示词 :param prompt: 构建好的完整提示词
:return: 模型生成的纯文本字符串结果 :return: 模型生成的纯文本字符串结果
""" """
model = get_llm_model(model_name) model = get_llm_model(model_name, purpose=purpose)
res = await model([{"role": "user", "content": prompt}]) res = await model([{"role": "user", "content": prompt}])
# 兼容处理某些模型可能返回异步迭代器(流)的情况 # 兼容处理某些模型可能返回异步迭代器(流)的情况
...@@ -45,14 +46,10 @@ async def chat_once(model_name: str, prompt: str) -> str: ...@@ -45,14 +46,10 @@ async def chat_once(model_name: str, prompt: str) -> str:
final_chunk = chunk final_chunk = chunk
res = final_chunk res = final_chunk
content = getattr(res, "content", "") return extract_text_content(getattr(res, "content", ""))
# 针对多模态或者包含其他对象结构的返回内容,提取其中类型为 'text' 的部分
if isinstance(content, list):
return "".join(str(x.get("text", "")) for x in content if isinstance(x, dict) and x.get("type") == "text")
return str(content)
async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool = False): async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool = False, purpose: str | None = None):
""" """
进行流式大语言模型对话请求,按块(Chunk)不断产出生成结果。 进行流式大语言模型对话请求,按块(Chunk)不断产出生成结果。
...@@ -61,7 +58,7 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool = ...@@ -61,7 +58,7 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool =
:param include_thinking: 是否需要返回模型“思考”过程的文本(如某些带有深度思考机制的模型) :param include_thinking: 是否需要返回模型“思考”过程的文本(如某些带有深度思考机制的模型)
:yield: 不断吐出格式如 {"type": "answer_delta", "content": "..."} 的字典 :yield: 不断吐出格式如 {"type": "answer_delta", "content": "..."} 的字典
""" """
model = get_llm_model(model_name) model = get_llm_model(model_name, purpose=purpose)
res = await model([{"role": "user", "content": prompt}]) res = await model([{"role": "user", "content": prompt}])
# 若模型返回的是异步生成器(正常流式表现) # 若模型返回的是异步生成器(正常流式表现)
...@@ -70,12 +67,8 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool = ...@@ -70,12 +67,8 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool =
full_thinking = "" full_thinking = ""
async for chunk in res: async for chunk in res:
content = getattr(chunk, "content", "") content = getattr(chunk, "content", "")
if isinstance(content, list): text = extract_text_content(content)
text = "".join(str(x.get("text", "")) for x in content if isinstance(x, dict) and x.get("type") == "text") thinking = extract_thinking_content(content)
thinking = "".join(str(x.get("thinking", "")) for x in content if isinstance(x, dict) and x.get("type") == "thinking")
else:
text = str(content)
thinking = ""
# 用 stream_delta 兼容「累计式/增量式」两类模型,避免切片错位导致重复或金字塔 # 用 stream_delta 兼容「累计式/增量式」两类模型,避免切片错位导致重复或金字塔
text_delta, full_text = stream_delta(full_text, text) text_delta, full_text = stream_delta(full_text, text)
...@@ -88,12 +81,8 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool = ...@@ -88,12 +81,8 @@ async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool =
else: else:
# 兼容处理未开启流式时,直接一次性返回了结果的情况 # 兼容处理未开启流式时,直接一次性返回了结果的情况
content = getattr(res, "content", "") content = getattr(res, "content", "")
if isinstance(content, list): text = extract_text_content(content)
text = "".join(str(x.get("text", "")) for x in content if isinstance(x, dict) and x.get("type") == "text") thinking = extract_thinking_content(content)
thinking = "".join(str(x.get("thinking", "")) for x in content if isinstance(x, dict) and x.get("type") == "thinking")
else:
text = str(content)
thinking = ""
if include_thinking and thinking: if include_thinking and thinking:
yield {"type": "thinking_delta", "content": thinking} yield {"type": "thinking_delta", "content": thinking}
......
...@@ -76,7 +76,7 @@ need_clarification 必须为 false(信æ¯ä¸è¶³ç”±åŽç»­é—®ç­”链路处ç†ï¼‰ã ...@@ -76,7 +76,7 @@ need_clarification 必须为 false(信æ¯ä¸è¶³ç”±åŽç»­é—®ç­”链路处ç†ï¼‰ã
历史: {json.dumps(history or [], ensure_ascii=False)[:1200]} 历史: {json.dumps(history or [], ensure_ascii=False)[:1200]}
输出字段: intent, intents, confidence, brand, business_category, sub_business, standalone_query, unsupported_reason 输出字段: intent, intents, confidence, brand, business_category, sub_business, standalone_query, unsupported_reason
""" """
content = await chat_once(RAG_INTENT_MODEL, prompt) content = await chat_once(RAG_INTENT_MODEL, prompt, purpose="RAG_INTENT")
# 兼容 markdown 代码块包裹的 JSON # 兼容 markdown 代码块包裹的 JSON
if content.startswith("```json"): if content.startswith("```json"):
...@@ -344,7 +344,11 @@ async def generate_answer(query: str, intent: IntentResult, chunks: list[RagChun ...@@ -344,7 +344,11 @@ async def generate_answer(query: str, intent: IntentResult, chunks: list[RagChun
"""结合召回资料,一次性(非流式)生成完整回答。""" """结合召回资料,一次性(非流式)生成完整回答。"""
if not chunks: if not chunks:
return FALLBACK_ANSWER return FALLBACK_ANSWER
answer = (await chat_once(RAG_ANSWER_MODEL, _build_answer_prompt(query, intent, chunks, history))).strip() answer = (await chat_once(
RAG_ANSWER_MODEL,
_build_answer_prompt(query, intent, chunks, history),
purpose="RAG_ANSWER",
)).strip()
return answer or FALLBACK_ANSWER return answer or FALLBACK_ANSWER
...@@ -353,7 +357,11 @@ async def generate_answer_stream(query: str, intent: IntentResult, chunks: list[ ...@@ -353,7 +357,11 @@ async def generate_answer_stream(query: str, intent: IntentResult, chunks: list[
if not chunks: if not chunks:
yield {"type": "answer_delta", "content": FALLBACK_ANSWER} yield {"type": "answer_delta", "content": FALLBACK_ANSWER}
return return
async for item in chat_stream(RAG_ANSWER_MODEL, _build_answer_prompt(query, intent, chunks, history)): async for item in chat_stream(
RAG_ANSWER_MODEL,
_build_answer_prompt(query, intent, chunks, history),
purpose="RAG_ANSWER",
):
yield item yield item
......
...@@ -207,6 +207,56 @@ def read_local_file(file_path: str, start_line: int = 1, end_line: int = None) - ...@@ -207,6 +207,56 @@ def read_local_file(file_path: str, start_line: int = 1, end_line: int = None) -
content=[TextBlock(type="text", text=f"❌ 读取错误: {str(e)}")] content=[TextBlock(type="text", text=f"❌ 读取错误: {str(e)}")]
) )
_read_local_file_direct = read_local_file
def _tool_response_text(result: ToolResponse) -> str:
"""Extract first text block from AgentScope ToolResponse variants."""
try:
content = getattr(result, "content", None)
if not content:
return ""
first = content[0]
if isinstance(first, dict):
return str(first.get("text", ""))
return str(getattr(first, "text", ""))
except Exception:
return ""
def read_local_file(file_path: str, start_line: int = 1, end_line: int = None) -> ToolResponse:
"""Read a wiki file, with a compatibility fallback for nested sources pages."""
result = _read_local_file_direct(file_path, start_line, end_line)
text = _tool_response_text(result)
normalized_path = file_path.replace("\\", "/")
source_match = re.fullmatch(r"ware/wiki/sources/([^/]+\.md)", normalized_path)
if not source_match or "找不到文件" not in text:
return result
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
source_name = source_match.group(1)
source_glob = os.path.join(root_dir, "ware", "wiki", "sources", "**", source_name)
import glob
matches = [
os.path.abspath(p)
for p in glob.glob(source_glob, recursive=True)
if os.path.isfile(p) and os.path.abspath(p).startswith(root_dir)
]
if len(matches) == 1:
rel_path = os.path.relpath(matches[0], root_dir).replace("\\", "/")
return _read_local_file_direct(rel_path, start_line, end_line)
if len(matches) > 1:
rel_matches = [os.path.relpath(p, root_dir).replace("\\", "/") for p in matches]
return ToolResponse(
content=[TextBlock(
type="text",
text="❌ sources 路径存在多个匹配,请使用完整路径读取:\n" + "\n".join(rel_matches),
)]
)
return result
_BR_RE = re.compile(r"\s*<br\s*/?>\s*", re.IGNORECASE) _BR_RE = re.compile(r"\s*<br\s*/?>\s*", re.IGNORECASE)
...@@ -533,6 +583,7 @@ def rebuild_index(wiki_dir: str) -> int: ...@@ -533,6 +583,7 @@ def rebuild_index(wiki_dir: str) -> int:
skip_dirs = {os.path.join(wiki_dir, "metadata"), os.path.join(wiki_dir, "lint_reports")} skip_dirs = {os.path.join(wiki_dir, "metadata"), os.path.join(wiki_dir, "lint_reports")}
# 收集页面元信息:group_key -> list of (sort_key, slug, title) # 收集页面元信息:group_key -> list of (sort_key, slug, title)
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
grouped: dict[str, list] = {} grouped: dict[str, list] = {}
total = 0 total = 0
for root, dirs, files in os.walk(wiki_dir): for root, dirs, files in os.walk(wiki_dir):
...@@ -541,6 +592,15 @@ def rebuild_index(wiki_dir: str) -> int: ...@@ -541,6 +592,15 @@ def rebuild_index(wiki_dir: str) -> int:
if not fname.endswith(".md") or fname in skip_names: if not fname.endswith(".md") or fname in skip_names:
continue continue
fpath = os.path.join(root, fname) fpath = os.path.join(root, fname)
abs_fpath = os.path.abspath(fpath)
try:
is_project_file = os.path.commonpath([project_root, abs_fpath]) == project_root
except ValueError:
is_project_file = False
if is_project_file:
index_path_ref = os.path.relpath(abs_fpath, project_root).replace("\\", "/")
else:
index_path_ref = os.path.relpath(abs_fpath, wiki_dir).replace("\\", "/")
slug = os.path.splitext(fname)[0] slug = os.path.splitext(fname)[0]
ptype, title, series, brand = "", slug, "", "" ptype, title, series, brand = "", slug, "", ""
try: try:
...@@ -555,7 +615,7 @@ def rebuild_index(wiki_dir: str) -> int: ...@@ -555,7 +615,7 @@ def rebuild_index(wiki_dir: str) -> int:
ptype = "" ptype = ""
group_key = ptype if ptype in dict(_INDEX_TYPE_GROUPS) else "_其他" group_key = ptype if ptype in dict(_INDEX_TYPE_GROUPS) else "_其他"
sort_key = (series, brand, slug) sort_key = (series, brand, slug)
grouped.setdefault(group_key, []).append((sort_key, slug, title)) grouped.setdefault(group_key, []).append((sort_key, slug, title, index_path_ref))
total += 1 total += 1
# 组装 markdown # 组装 markdown
...@@ -572,11 +632,14 @@ def rebuild_index(wiki_dir: str) -> int: ...@@ -572,11 +632,14 @@ def rebuild_index(wiki_dir: str) -> int:
continue continue
entries.sort(key=lambda x: x[0]) entries.sort(key=lambda x: x[0])
lines.append(f"## {heading}") lines.append(f"## {heading}")
for _sort_key, slug, title in entries: for _sort_key, slug, title, path_ref in entries:
if title and title != slug: if title and title != slug:
lines.append(f"- [[{slug}]] — {title}") line = f"- [[{slug}]] — {title}"
else: else:
lines.append(f"- [[{slug}]]") line = f"- [[{slug}]]"
if group_key == "sources":
line += f" | path: {path_ref}"
lines.append(line)
lines.append("") lines.append("")
# 未识别 type 的兜底分组 # 未识别 type 的兜底分组
...@@ -584,7 +647,7 @@ def rebuild_index(wiki_dir: str) -> int: ...@@ -584,7 +647,7 @@ def rebuild_index(wiki_dir: str) -> int:
if others: if others:
others.sort(key=lambda x: x[0]) others.sort(key=lambda x: x[0])
lines.append("## 未分类") lines.append("## 未分类")
for _sort_key, slug, title in others: for _sort_key, slug, title, _path_ref in others:
lines.append(f"- [[{slug}]] — {title}" if title and title != slug else f"- [[{slug}]]") lines.append(f"- [[{slug}]] — {title}" if title and title != slug else f"- [[{slug}]]")
lines.append("") lines.append("")
...@@ -629,3 +692,4 @@ def remove_wiki_link(file_path: str, target: str) -> ToolResponse: ...@@ -629,3 +692,4 @@ def remove_wiki_link(file_path: str, target: str) -> ToolResponse:
return ToolResponse(content=[TextBlock(type="text", text=f"✅ 未发现匹配的断链 {file_path}")]) return ToolResponse(content=[TextBlock(type="text", text=f"✅ 未发现匹配的断链 {file_path}")])
except Exception as e: except Exception as e:
return ToolResponse(content=[TextBlock(type="text", text=f"❌ 转化为纯文本失败: {str(e)}")]) return ToolResponse(content=[TextBlock(type="text", text=f"❌ 转化为纯文本失败: {str(e)}")])
...@@ -3,11 +3,24 @@ import os ...@@ -3,11 +3,24 @@ import os
import functools import functools
import contextlib import contextlib
import contextvars import contextvars
import logging
import agentscope import agentscope
from agentscope.model import DashScopeChatModel from agentscope.formatter import DashScopeChatFormatter, OpenAIChatFormatter
from config import SKILLS_DIR, API_KEY, is_multimodal, is_thinking from agentscope.message import Msg
from agentscope.model import DashScopeChatModel, OpenAIChatModel
from config import SKILLS_DIR, API_KEY
from src.utils.llm_models import (
DASHSCOPE_CLIENT,
OPENAI_COMPATIBLE_CLIENT,
build_model_init_kwargs,
extract_thinking_content,
formatter_name_for_model,
get_chat_model_profile,
)
from src.utils.logger import StreamTranscript from src.utils.logger import StreamTranscript
logger = logging.getLogger(__name__)
# ================================================================================== # ==================================================================================
# 核心组件:Token 消耗跟踪器 (Token Tracker) # 核心组件:Token 消耗跟踪器 (Token Tracker)
# ================================================================================== # ==================================================================================
...@@ -37,7 +50,7 @@ def stream_delta(prev_full: str, chunk_text: str) -> tuple[str, str]: ...@@ -37,7 +50,7 @@ def stream_delta(prev_full: str, chunk_text: str) -> tuple[str, str]:
return chunk_text, prev_full + chunk_text return chunk_text, prev_full + chunk_text
class TrackingDashScopeChatModel(DashScopeChatModel): class TrackingChatModelMixin:
""" """
模型监控包装类 (Wrapper):继承自 AgentScope 的原生 DashScopeChatModel, 模型监控包装类 (Wrapper):继承自 AgentScope 的原生 DashScopeChatModel,
并重写了底层的大模型调用 __call__ 方法。 并重写了底层的大模型调用 __call__ 方法。
...@@ -71,12 +84,8 @@ class TrackingDashScopeChatModel(DashScopeChatModel): ...@@ -71,12 +84,8 @@ class TrackingDashScopeChatModel(DashScopeChatModel):
last_output = getattr(chunk.usage, "output_tokens", last_output) last_output = getattr(chunk.usage, "output_tokens", last_output)
# 实时打印思维链:用 stream_delta 兼容「累计/增量」两类模型,避免阶梯式重复 # 实时打印思维链:用 stream_delta 兼容「累计/增量」两类模型,避免阶梯式重复
if hasattr(chunk, "content") and isinstance(chunk.content, list): if hasattr(chunk, "content"):
chunk_thinking = "".join( chunk_thinking = extract_thinking_content(chunk.content)
str(block.get("thinking", ""))
for block in chunk.content
if isinstance(block, dict) and block.get("type") == "thinking"
)
delta, full_thinking = stream_delta(full_thinking, chunk_thinking) delta, full_thinking = stream_delta(full_thinking, chunk_thinking)
if delta and print_thinking.get(): if delta and print_thinking.get():
transcript.write(delta) transcript.write(delta)
...@@ -108,19 +117,71 @@ class TrackingDashScopeChatModel(DashScopeChatModel): ...@@ -108,19 +117,71 @@ class TrackingDashScopeChatModel(DashScopeChatModel):
return res return res
# Model wrappers and formatter helpers.
class TrackingDashScopeChatModel(TrackingChatModelMixin, DashScopeChatModel):
"""Tracking wrapper for DashScope native chat models."""
class TrackingOpenAIChatModel(TrackingChatModelMixin, OpenAIChatModel):
"""Tracking wrapper for OpenAI-compatible chat models."""
class ThinkingTolerantOpenAIChatFormatter(OpenAIChatFormatter):
"""OpenAI formatter that silently drops historical thinking blocks."""
async def _format(self, msgs: list[Msg]):
return await super()._format([_strip_thinking_blocks(msg) for msg in msgs])
def _strip_thinking_blocks(msg: Msg) -> Msg:
if not isinstance(getattr(msg, "content", None), list):
return msg
content = [
block
for block in msg.content
if not (isinstance(block, dict) and block.get("type") == "thinking")
]
if len(content) == len(msg.content):
return msg
copied = Msg(
name=msg.name,
content=content,
role=msg.role,
metadata=msg.metadata,
timestamp=msg.timestamp,
invocation_id=msg.invocation_id,
)
copied.id = msg.id
return copied
# 初始化 AgentScope 框架 # 初始化 AgentScope 框架
agentscope.init() agentscope.init()
def get_llm_model(model_name: str) -> TrackingDashScopeChatModel: def get_llm_model(model_name: str, purpose: str | None = None):
"""根据传入的模型名称动态实例化 TrackingDashScopeChatModel。""" """根据传入的模型名称动态实例化 TrackingDashScopeChatModel。"""
return TrackingDashScopeChatModel( try:
model_name=model_name, profile = get_chat_model_profile(model_name)
api_key=API_KEY, kwargs = build_model_init_kwargs(model_name, api_key=API_KEY, purpose=purpose)
multimodality=is_multimodal(model_name), except ValueError:
enable_thinking=is_thinking(model_name), logger.exception("[LLM] model configuration error: model=%s purpose=%s", model_name, purpose)
generate_kwargs={"temperature": 0.5} if "deepseek" not in model_name.lower() else {} raise
) if profile.client == OPENAI_COMPATIBLE_CLIENT:
return TrackingOpenAIChatModel(**kwargs)
if profile.client == DASHSCOPE_CLIENT:
return TrackingDashScopeChatModel(**kwargs)
raise ValueError(f"Unsupported LLM client: {profile.client!r}")
def get_llm_formatter(model_name: str):
"""Return the AgentScope formatter that matches the selected model client."""
formatter_name = formatter_name_for_model(model_name)
if formatter_name == "openai":
return ThinkingTolerantOpenAIChatFormatter()
return DashScopeChatFormatter()
@functools.lru_cache(maxsize=None) @functools.lru_cache(maxsize=None)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!