From 6bcdaf589a6e1d5b165b24f160c6c6051e0f2d2d Mon Sep 17 00:00:00 2001 From: jinye_huang Date: Tue, 22 Apr 2025 16:31:03 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=BA=86=E6=B5=81=E5=BC=8F?= =?UTF-8?q?=E8=BE=93=E5=87=BA=E7=9A=84=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 84 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 51e584d..243f153 100644 --- a/README.md +++ b/README.md @@ -129,4 +129,87 @@ pip install numpy pandas opencv-python pillow openai 项目提供了一个示例配置文件 `example_config.json`,请务必复制并修改: -``` \ No newline at end of file +## 注意事项 + +- - 确保已安装所有依赖库,特别是 `openai` 库。 +- - **选题生成依赖于 AI 模型严格输出有效的 JSON 格式**。如果 AI 输出格式错误,选题解析会失败。 +- - **内容生成依赖于 AI 在选题 JSON 中提供的 `style` 和 `target_audience` 文件名与 `prompts_dir` 下 `Style/` 和 `Demand/` 目录中的实际文件名(含.txt)完全一致**。请检查这些目录和文件名。 +- - **图片目录结构和命名**需严格符合预期,以便程序能找到对应景点的图片。 +- - AI生成内容的质量很大程度上取决于**提示词的设计**和**输入资源信息的质量**。 +- - 仔细检查 API Key、URL 和文件路径配置。 +- - 如果遇到问题,检查程序输出的日志信息和错误提示。 + + +## API 集成 / 流式输出使用 (Streaming Usage) + +为了方便将 AI 生成的内容以流式传输(例如,用于 API 端点),`AI_Agent` 类提供了一个 `work_stream` 方法。与返回完整文本的 `work` 方法不同,`work_stream` 返回一个 Python 生成器 (generator)。 + +你可以迭代这个生成器来逐块获取 AI 生成的文本。 + +**基本用法示例:** + +```python +import os +import sys +import json + +# 假设已正确设置 Python Path +from core.ai_agent import AI_Agent + +# 1. 加载配置 (与 main.py 类似) +config_path = "poster_gen_config.json" +config = {} +try: + with open(config_path, 'r', encoding='utf-8') as f: + config = json.load(f) +except Exception as e: + print(f"Error loading config: {e}") + sys.exit(1) + +# 2. 初始化 AI Agent (读取超时/重试配置) +ai_agent = None +try: + request_timeout = config.get("request_timeout", 30) + max_retries = config.get("max_retries", 3) + ai_agent = AI_Agent( + config["api_url"], + config["model"], + config["api_key"], + timeout=request_timeout, + max_retries=max_retries + ) + + # 3. 定义提示词和参数 + system_prompt = "You are a travel writer." + user_prompt = "Describe the Great Wall of China in about 50 words." + temperature = config.get("content_temperature", 0.7) + top_p = config.get("content_top_p", 0.9) + presence_penalty = config.get("content_presence_penalty", 1.0) + file_folder = None # 可选的参考文件目录 + + # 4. 调用 work_stream 获取生成器 + stream_generator = ai_agent.work_stream( + system_prompt, + user_prompt, + file_folder, + temperature, + top_p, + presence_penalty + ) + + # 5. 迭代生成器获取文本块 + print("Streaming response:") + for chunk in stream_generator: + print(chunk, end="", flush=True) # 处理文本块,例如发送给客户端 + + print("\\nStream finished.") + +except Exception as e: + print(f"An error occurred: {e}") +finally: + if ai_agent: + ai_agent.close() + +``` + +这个返回的 `stream_generator` 可以很容易地集成到 Web 框架(如 Flask、FastAPI)的流式响应 (StreamingResponse) 中,以实现向客户端的实时流式输出。参考 `examples/test_stream.py` 获取可运行的示例。 \ No newline at end of file