Spaces:
Sleeping
Sleeping
File size: 22,068 Bytes
db1360b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 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 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 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 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 | """
通用问题优化与求解智能体
功能:原始问题 -> Prompt 优化 -> 联网搜索 -> 综合求解 -> 自动生成 PDF 报告
运行:
1. pip install -r requirements.txt
2. 复制 .env.example 为 .env,并填入 OPENAI_API_KEY / OPENAI_BASE_URL / MODEL_NAME
3. python app.py
"""
from __future__ import annotations
import datetime as dt
import json
import os
import re
import traceback
import uuid
from dataclasses import dataclass
from html import escape
from pathlib import Path
from typing import Any, Dict, List, Tuple
import gradio as gr
from dotenv import load_dotenv
from openai import OpenAI
# DuckDuckGo 搜索库:兼容 ddgs 与 duckduckgo_search 两种包名
try:
from ddgs import DDGS # type: ignore
except Exception: # pragma: no cover
try:
from duckduckgo_search import DDGS # type: ignore
except Exception: # pragma: no cover
DDGS = None # type: ignore
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import cm
from reportlab.platypus import (
ListFlowable,
ListItem,
PageBreak,
Paragraph,
Preformatted,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.pdfbase.ttfonts import TTFont
load_dotenv()
APP_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = APP_DIR / "outputs"
OUTPUT_DIR.mkdir(exist_ok=True)
DEFAULT_MODEL = os.getenv("MODEL_NAME", "deepseek-chat")
DEFAULT_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.deepseek.com")
DEFAULT_MAX_RESULTS = int(os.getenv("MAX_SEARCH_RESULTS", "5"))
@dataclass
class SearchItem:
title: str
url: str
snippet: str
def get_client() -> OpenAI:
"""创建 OpenAI-compatible 客户端。"""
api_key = os.getenv("OPENAI_API_KEY", "").strip()
base_url = os.getenv("OPENAI_BASE_URL", DEFAULT_BASE_URL).strip()
if not api_key:
raise RuntimeError(
"未检测到 OPENAI_API_KEY。请先复制 .env.example 为 .env,并填写你的公开大模型 API Key。"
)
return OpenAI(api_key=api_key, base_url=base_url)
def call_llm(messages: List[Dict[str, str]], temperature: float = 0.2) -> str:
"""调用聊天模型。"""
client = get_client()
model_name = os.getenv("MODEL_NAME", DEFAULT_MODEL).strip()
response = client.chat.completions.create(
model=model_name,
messages=messages,
# temperature=temperature,
)
return response.choices[0].message.content or ""
def extract_json(text: str) -> Dict[str, Any]:
"""从 LLM 输出中尽量提取 JSON。"""
text = text.strip()
# 直接解析
try:
return json.loads(text)
except Exception:
pass
# 解析 ```json ... ```
fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.S)
if fenced:
try:
return json.loads(fenced.group(1))
except Exception:
pass
# 解析第一个大括号块
start = text.find("{")
end = text.rfind("}")
if start != -1 and end != -1 and end > start:
candidate = text[start : end + 1]
try:
return json.loads(candidate)
except Exception:
pass
# 兜底
return {
"original_question": "",
"core_goal": "未能解析结构化结果",
"ambiguities": [],
"assumptions": [],
"optimized_prompt": text,
"search_query": text[:120],
"solution_plan": [],
"pdf_outline": [],
}
def optimize_question(user_question: str) -> Dict[str, Any]:
"""第一阶段:问题理解与 Prompt 优化。"""
system_prompt = """
你是一个“通用问题优化智能体”。你的任务是把用户模糊、宽泛、不完整的问题,改写成目标明确、条件清晰、可执行、适合大模型求解的高质量 Prompt。
你必须严格输出 JSON,不要输出 Markdown,不要输出解释性废话。
JSON 字段如下:
{
"original_question": "用户原始问题",
"core_goal": "用户真正想解决的核心目标",
"ambiguities": ["原始问题中的模糊点1", "模糊点2"],
"assumptions": ["在不改变用户原意前提下采用的合理假设1", "合理假设2"],
"optimized_prompt": "优化后的高质量 Prompt。要求包含背景、目标、约束、输出格式、评价标准。",
"search_query": "适合联网搜索的查询语句,尽量简洁明确",
"solution_plan": ["步骤1", "步骤2", "步骤3"],
"pdf_outline": ["PDF报告章节1", "PDF报告章节2", "PDF报告章节3"]
}
要求:
1. 不要改变用户原意。
2. 如果信息缺失,可以给出合理假设,但必须写入 assumptions。
3. search_query 要能直接用于搜索引擎。
4. optimized_prompt 要足够具体,使另一个模型可以据此完成任务。
""".strip()
user_prompt = f"用户原始问题:\n{user_question}"
raw = call_llm(
[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=0.1,
)
data = extract_json(raw)
data["original_question"] = data.get("original_question") or user_question
data["_raw_output"] = raw
return data
def search_web(query: str, max_results: int = DEFAULT_MAX_RESULTS) -> Tuple[List[SearchItem], str]:
"""第二阶段:轻量工具调用,使用 DuckDuckGo 搜索。"""
if DDGS is None:
return [], "未安装 ddgs 或 duckduckgo_search,已跳过联网搜索。"
query = (query or "").strip()
if max_results <= 0:
return [], "已按设置跳过联网搜索。"
if not query:
return [], "搜索关键词为空,已跳过联网搜索。"
try:
items: List[SearchItem] = []
with DDGS() as ddgs:
results = ddgs.text(query, max_results=max_results)
for r in results:
items.append(
SearchItem(
title=str(r.get("title", "无标题")),
url=str(r.get("href") or r.get("url") or ""),
snippet=str(r.get("body") or r.get("snippet") or ""),
)
)
return items, "搜索成功"
except Exception as exc:
return [], f"联网搜索失败,已继续使用模型自身能力求解。错误信息:{exc}"
def format_search_results(items: List[SearchItem], status: str) -> str:
if not items:
return f"搜索状态:{status}\n\n未获得可用搜索结果。"
lines = [f"搜索状态:{status}", ""]
for i, item in enumerate(items, 1):
lines.append(f"[{i}] {item.title}")
lines.append(f"链接:{item.url}")
lines.append(f"摘要:{item.snippet}")
lines.append("")
return "\n".join(lines)
def generate_report(user_question: str, optimized: Dict[str, Any], search_text: str) -> str:
"""第三阶段:综合求解,输出适合 PDF 的 Markdown 报告。"""
optimized_json = json.dumps(optimized, ensure_ascii=False, indent=2)
system_prompt = """
你是一个“通用问题优化与求解智能体”。你不是简单回答问题,而是需要展示完整求解过程:原始问题理解、模糊点分析、Prompt 优化、联网信息整合、最终解答、结果检查,并输出可转换为 PDF 的详细 Markdown 报告。
输出要求:
1. 必须使用 Markdown。
2. 必须适合作为课程作业提交的 PDF 报告。
3. 不要虚构联网搜索结果。如果搜索结果不足,明确说明。
4. 对来源信息只基于提供给你的搜索结果进行概括。
5. 最终解答要具体、可执行。
6. 报告中必须体现“问题优化智能体”的工作流程。
报告结构必须如下:
# 通用问题优化智能体求解报告
## 1. 原始问题
## 2. 问题理解与模糊点分析
## 3. 优化后的高质量 Prompt
## 4. 求解计划
## 5. 联网搜索参考信息
## 6. 综合分析与最终解答
## 7. 结果检查与局限性
## 8. 行动清单
## 9. 本次智能体运行过程总结
""".strip()
user_prompt = f"""
下面是本次智能体运行所需的信息。
【用户原始问题】
{user_question}
【问题优化节点输出】
{optimized_json}
【联网搜索结果】
{search_text}
请基于以上内容生成完整 Markdown 报告。
""".strip()
return call_llm(
[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=0.25,
)
def register_chinese_font() -> str:
"""
注册中文字体,优先使用系统中文字体,避免 PDF 中文乱码。
"""
font_name = "ChineseFont"
candidate_fonts = [
# Windows 本地调试
r"C:\Windows\Fonts\simhei.ttf",
r"C:\Windows\Fonts\msyh.ttc",
r"C:\Windows\Fonts\simsun.ttc",
# Hugging Face Spaces / Linux
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJKsc-Regular.otf",
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
]
for font_path in candidate_fonts:
if os.path.exists(font_path):
try:
pdfmetrics.registerFont(TTFont(font_name, font_path))
print(f"已加载中文字体:{font_path}")
return font_name
except Exception as exc:
print(f"字体加载失败:{font_path},原因:{exc}")
try:
fallback_font = "STSong-Light"
pdfmetrics.registerFont(UnicodeCIDFont(fallback_font))
print("警告:未找到系统中文字体,已回退到 STSong-Light。")
return fallback_font
except Exception:
print("警告:中文字体加载失败,PDF 可能仍然乱码。")
return "Helvetica"
def build_styles(font_name: str) -> Dict[str, ParagraphStyle]:
styles = getSampleStyleSheet()
base = ParagraphStyle(
"BaseCN",
parent=styles["Normal"],
fontName=font_name,
fontSize=10.5,
leading=17,
alignment=TA_LEFT,
spaceAfter=6,
)
return {
"title": ParagraphStyle(
"TitleCN",
parent=base,
fontSize=20,
leading=26,
alignment=TA_CENTER,
spaceAfter=18,
),
"h1": ParagraphStyle(
"H1CN",
parent=base,
fontSize=16,
leading=22,
spaceBefore=14,
spaceAfter=10,
),
"h2": ParagraphStyle(
"H2CN",
parent=base,
fontSize=13,
leading=20,
spaceBefore=10,
spaceAfter=8,
),
"h3": ParagraphStyle(
"H3CN",
parent=base,
fontSize=11.5,
leading=18,
spaceBefore=8,
spaceAfter=6,
),
"body": base,
"bullet": ParagraphStyle(
"BulletCN",
parent=base,
leftIndent=16,
firstLineIndent=-8,
),
"code": ParagraphStyle(
"CodeCN",
parent=base,
fontName=font_name,
fontSize=8.5,
leading=12,
leftIndent=8,
rightIndent=8,
backColor=colors.whitesmoke,
borderColor=colors.lightgrey,
borderWidth=0.5,
borderPadding=6,
),
"footer": ParagraphStyle(
"FooterCN",
parent=base,
fontSize=8,
leading=11,
alignment=TA_CENTER,
textColor=colors.grey,
),
}
def clean_inline_markdown(text: str) -> str:
"""把常见 Markdown 内联语法转换为 ReportLab Paragraph 支持的简单标签。"""
text = escape(text)
text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
# 不再使用 Courier,避免中文行内代码乱码
text = re.sub(r"`(.+?)`", r"<b>\1</b>", text)
# Markdown 链接 [text](url) -> text(url)
text = re.sub(r"\[(.*?)\]\((.*?)\)", r"\1(\2)", text)
return text
def markdown_to_flowables(markdown_text: str, styles: Dict[str, ParagraphStyle]) -> List[Any]:
"""轻量 Markdown 渲染器:支持标题、段落、列表、代码块、简单表格。"""
flowables: List[Any] = []
lines = markdown_text.replace("\r\n", "\n").split("\n")
in_code = False
code_lines: List[str] = []
paragraph_lines: List[str] = []
table_lines: List[str] = []
def flush_paragraph() -> None:
nonlocal paragraph_lines
if paragraph_lines:
text = " ".join(line.strip() for line in paragraph_lines if line.strip())
if text:
flowables.append(Paragraph(clean_inline_markdown(text), styles["body"]))
flowables.append(Spacer(1, 0.08 * cm))
paragraph_lines = []
def flush_code() -> None:
nonlocal code_lines
if code_lines:
code_text = "\n".join(code_lines)
flowables.append(Preformatted(code_text, styles["code"]))
flowables.append(Spacer(1, 0.12 * cm))
code_lines = []
def flush_table() -> None:
nonlocal table_lines
if not table_lines:
return
rows = []
for line in table_lines:
if re.match(r"^\s*\|?\s*:?-{3,}:?\s*", line):
continue
cells = [clean_inline_markdown(c.strip()) for c in line.strip().strip("|").split("|")]
if cells and any(cells):
rows.append([Paragraph(c, styles["body"]) for c in cells])
if rows:
table = Table(rows, hAlign="LEFT")
table.setStyle(
TableStyle(
[
("GRID", (0, 0), (-1, -1), 0.3, colors.lightgrey),
("BACKGROUND", (0, 0), (-1, 0), colors.whitesmoke),
("VALIGN", (0, 0), (-1, -1), "TOP"),
("LEFTPADDING", (0, 0), (-1, -1), 4),
("RIGHTPADDING", (0, 0), (-1, -1), 4),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
]
)
)
flowables.append(table)
flowables.append(Spacer(1, 0.12 * cm))
table_lines = []
for raw_line in lines:
line = raw_line.rstrip()
if line.strip().startswith("```"):
flush_paragraph()
flush_table()
if in_code:
flush_code()
in_code = False
else:
in_code = True
continue
if in_code:
code_lines.append(line)
continue
# 表格行
if "|" in line and line.strip().startswith("|"):
flush_paragraph()
table_lines.append(line)
continue
else:
flush_table()
if not line.strip():
flush_paragraph()
continue
if line.startswith("# "):
flush_paragraph()
title = line[2:].strip()
flowables.append(Paragraph(clean_inline_markdown(title), styles["title"]))
continue
if line.startswith("## "):
flush_paragraph()
title = line[3:].strip()
flowables.append(Paragraph(clean_inline_markdown(title), styles["h1"]))
continue
if line.startswith("### "):
flush_paragraph()
title = line[4:].strip()
flowables.append(Paragraph(clean_inline_markdown(title), styles["h2"]))
continue
if line.startswith("#### "):
flush_paragraph()
title = line[5:].strip()
flowables.append(Paragraph(clean_inline_markdown(title), styles["h3"]))
continue
bullet_match = re.match(r"^\s*[-*+]\s+(.+)$", line)
number_match = re.match(r"^\s*\d+[.)]\s+(.+)$", line)
if bullet_match or number_match:
flush_paragraph()
content = bullet_match.group(1) if bullet_match else number_match.group(1)
bullet = "• " if bullet_match else "- "
flowables.append(Paragraph(bullet + clean_inline_markdown(content), styles["bullet"]))
continue
paragraph_lines.append(line)
flush_paragraph()
flush_table()
if in_code:
flush_code()
return flowables
def add_page_number(canvas, doc) -> None: # type: ignore[no-untyped-def]
canvas.saveState()
canvas.setFont("Helvetica", 8)
page_text = f"Page {doc.page}"
canvas.drawRightString(A4[0] - 2 * cm, 1.2 * cm, page_text)
canvas.restoreState()
def create_pdf(markdown_text: str, filename_prefix: str = "agent_report") -> str:
"""第四阶段:生成 PDF 文件。"""
font_name = register_chinese_font()
styles = build_styles(font_name)
timestamp = dt.datetime.now().strftime("%Y%m%d_%H%M%S")
pdf_path = OUTPUT_DIR / f"{filename_prefix}_{timestamp}_{uuid.uuid4().hex[:6]}.pdf"
doc = SimpleDocTemplate(
str(pdf_path),
pagesize=A4,
rightMargin=2 * cm,
leftMargin=2 * cm,
topMargin=1.8 * cm,
bottomMargin=1.8 * cm,
title="通用问题优化智能体求解报告",
)
flowables = markdown_to_flowables(markdown_text, styles)
if not flowables:
flowables = [Paragraph("未生成有效报告内容。", styles["body"])]
doc.build(flowables, onFirstPage=add_page_number, onLaterPages=add_page_number)
return str(pdf_path)
def run_agent(user_question: str, max_results: int) -> Tuple[Dict[str, Any], str, str, str, str]:
"""Gradio 主流程。"""
if not user_question or not user_question.strip():
return {}, "", "", None, "请输入需要求解的问题。" # type: ignore[return-value]
try:
# 1. 问题优化
optimized = optimize_question(user_question.strip())
# 2. 联网搜索
search_query = optimized.get("search_query") or user_question.strip()
search_items, search_status = search_web(str(search_query), max_results=max_results)
search_text = format_search_results(search_items, search_status)
# 3. 综合求解并生成 Markdown 报告
report_md = generate_report(user_question.strip(), optimized, search_text)
# 4. 生成 PDF
pdf_path = create_pdf(report_md)
status = "运行完成:已完成问题优化、联网搜索、综合求解,并生成 PDF 报告。"
return optimized, search_text, report_md, pdf_path, status
except Exception as exc:
error_detail = traceback.format_exc()
status = f"运行失败:{exc}\n\n调试信息:\n{error_detail}"
return {}, "", "", None, status # type: ignore[return-value]
EXAMPLE_QUESTIONS = [
"我想用大模型智能体完成课程大作业,但现在只有一个简单想法,不知道怎么设计系统、怎么展示效果、怎么写提交材料,请帮我优化这个问题并给出完整方案,最后生成PDF报告。",
"我想准备一次关于大语言模型内部激活探测技术的课程展示,请帮我优化问题、搜索资料并输出报告。",
"我想学习线性规划中的对偶问题,但我基础比较薄弱,请帮我把问题改写清楚并给出适合开卷考试的解题步骤。",
]
def build_demo() -> gr.Blocks:
with gr.Blocks(title="通用问题优化与求解智能体") as demo:
gr.Markdown(
"""
# 通用问题优化与求解智能体
输入一个原始问题,智能体会自动完成:**问题分析 → Prompt 优化 → 联网搜索 → 综合求解 → PDF 报告生成**。
适合用于课程大作业演示:公开视频链接、MP4 录屏、PDF 报告都可以从这里完成。
"""
)
with gr.Row():
with gr.Column(scale=2):
question = gr.Textbox(
label="用户原始问题",
placeholder="请输入一个模糊或复杂的问题,例如:我想完成一个大模型智能体课程作业,但不知道怎么设计系统……",
lines=7,
)
max_results = gr.Slider(
minimum=0,
maximum=10,
value=DEFAULT_MAX_RESULTS,
step=1,
label="联网搜索结果数量。设置为 0 可跳过搜索。",
)
run_btn = gr.Button("开始优化并求解", variant="primary")
gr.Examples(
examples=EXAMPLE_QUESTIONS,
inputs=question,
label="示例问题",
)
with gr.Column(scale=1):
status = gr.Textbox(label="运行状态", lines=10)
pdf_file = gr.File(label="下载 PDF 报告")
with gr.Tab("1. 问题优化结果"):
optimized_json = gr.JSON(label="结构化问题优化结果")
with gr.Tab("2. 联网搜索结果"):
search_output = gr.Textbox(label="搜索结果", lines=18)
with gr.Tab("3. 最终 Markdown 报告"):
report_output = gr.Markdown(label="报告预览")
run_btn.click(
fn=run_agent,
inputs=[question, max_results],
outputs=[optimized_json, search_output, report_output, pdf_file, status],
)
return demo
if __name__ == "__main__":
demo = build_demo()
share = os.getenv("GRADIO_SHARE", "false").lower() in {"1", "true", "yes"}
port = int(os.getenv("PORT", "7860"))
demo.launch(server_name="0.0.0.0", server_port=port, share=share)
|