From eb9a727aab2d4d9041cbc20acb45e478fa98a176 Mon Sep 17 00:00:00 2001 From: bridge Date: Tue, 2 Sep 2025 22:29:42 +0800 Subject: [PATCH] update ai prompt --- requirements.txt | 1 + src/front/front.py | 5 +---- src/utils/llm.py | 21 +++++++++++++++++---- static/templates/ai.txt | 3 ++- 4 files changed, 21 insertions(+), 9 deletions(-) diff --git a/requirements.txt b/requirements.txt index 9459fe8..d3634d0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,6 +7,7 @@ PyYAML>=6.0 litellm>=1.0.0 omegaconf>=2.3.0 langchain>=0.1.0 +json5>=0.9.0 # Development and testing (optional) pytest>=7.0.0 diff --git a/src/front/front.py b/src/front/front.py index 06b86e7..4a90fd3 100644 --- a/src/front/front.py +++ b/src/front/front.py @@ -146,10 +146,7 @@ class Front: # 检查step任务是否完成 if current_step_task and current_step_task.done(): - try: - await current_step_task # 获取结果(如果有异常会抛出) - except Exception as e: - print(f"Step执行出错: {e}") + await current_step_task current_step_task = None self._render() diff --git a/src/utils/llm.py b/src/utils/llm.py index a0aeffb..d17a0a7 100644 --- a/src/utils/llm.py +++ b/src/utils/llm.py @@ -1,8 +1,9 @@ from litellm import completion from langchain.prompts import PromptTemplate from pathlib import Path -import json import asyncio +import re +import json5 from src.utils.config import CONFIG from src.utils.io import read_txt @@ -49,6 +50,19 @@ async def call_llm_async(prompt: str) -> str: # 使用asyncio.to_thread包装同步调用 return await asyncio.to_thread(call_llm, prompt) +def parse_llm_response(res: str) -> dict: + """ + 解析LLM返回的结果,支持多种格式 + """ + res = res.strip() + + # 提取markdown代码块中的JSON + json_match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', res, re.DOTALL) + if json_match: + res = json_match.group(1) + + return json5.loads(res) + def get_prompt_and_call_llm(template_path: Path, infos: dict) -> str: """ 根据模板,获取提示词,并调用LLM @@ -56,7 +70,7 @@ def get_prompt_and_call_llm(template_path: Path, infos: dict) -> str: template = read_txt(template_path) prompt = get_prompt(template, infos) res = call_llm(prompt) - json_res = json.loads(res) + json_res = parse_llm_response(res) # print(f"prompt = {prompt}") # print(f"res = {res}") return json_res @@ -68,9 +82,8 @@ async def get_prompt_and_call_llm_async(template_path: Path, infos: dict) -> str template = read_txt(template_path) prompt = get_prompt(template, infos) res = await call_llm_async(prompt) - json_res = json.loads(res) - print(f"prompt = {prompt}") print(f"res = {res}") + json_res = parse_llm_response(res) return json_res def get_ai_prompt_and_call_llm(infos: dict) -> dict: diff --git a/static/templates/ai.txt b/static/templates/ai.txt index d035a1f..affeddd 100644 --- a/static/templates/ai.txt +++ b/static/templates/ai.txt @@ -14,7 +14,8 @@ 注意,只返回json格式的动作 返回格式: {{ - "avatar_id": ..., + "thinking": ..., // 简单思考应该怎么决策 "action_name": ..., "action_params": ..., + "avatar_thinking": ..., // 从角色角度,以第一人称视角,描述心态 }} \ No newline at end of file