Skip to content

Commit fbc6b66

Browse files
committed
fix bug
fix bug
1 parent 8fbc371 commit fbc6b66

File tree

8 files changed

+75
-24
lines changed

8 files changed

+75
-24
lines changed

backend/app/core/agents.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def __init__(
3434
self.current_chat_turns = 0 # 当前对话轮次计数器
3535
self.user_output = user_output
3636

37-
async def run(self, prompt: str, system_prompt: str) -> str:
37+
async def run(self, prompt: str, system_prompt: str, sub_title: str) -> str:
3838
"""
3939
执行agent的对话并返回结果和总结
4040
@@ -54,7 +54,9 @@ async def run(self, prompt: str, system_prompt: str) -> str:
5454

5555
# 获取历史消息用于本次对话
5656
response = await self.model.chat(
57-
history=self.chat_history, agent_name=self.__class__.__name__
57+
history=self.chat_history,
58+
agent_name=self.__class__.__name__,
59+
sub_title=sub_title,
5860
)
5961
response_content = response.choices[0].message.content
6062
self.chat_history.append({"role": "assistant", "content": response_content})
@@ -140,7 +142,7 @@ async def run(self, prompt: str, subtask_title: str) -> CoderToWriter:
140142
f"Failed to complete task after {self.max_retries} attempts. Last error: {last_error_message}"
141143
)
142144

143-
# try:
145+
# try:
144146
while (
145147
not task_completed
146148
and retry_count < self.max_retries
@@ -189,6 +191,7 @@ async def run(self, prompt: str, subtask_title: str) -> CoderToWriter:
189191
)
190192

191193
# 执行工具调用
194+
logger.warning("执行工具调用")
192195
(
193196
text_to_gpt,
194197
error_occurred,
@@ -207,6 +210,8 @@ async def run(self, prompt: str, subtask_title: str) -> CoderToWriter:
207210
)
208211

209212
if error_occurred:
213+
logger.warning("代码执行错误")
214+
210215
retry_count += 1
211216
last_error_message = error_message
212217
reflection_prompt = get_reflection_prompt(error_message, code)
@@ -224,6 +229,8 @@ async def run(self, prompt: str, subtask_title: str) -> CoderToWriter:
224229
# 检查任务完成情况时也计入对话轮次
225230
self.current_chat_turns += 1
226231
# 使用所有执行结果生成检查提示
232+
logger.warning("判断是否完成")
233+
227234
completion_check_prompt = get_completion_check_prompt(
228235
prompt, text_to_gpt
229236
)
@@ -245,6 +252,7 @@ async def run(self, prompt: str, subtask_title: str) -> CoderToWriter:
245252
hasattr(completion_response.choices[0].message, "tool_calls")
246253
and completion_response.choices[0].message.tool_calls
247254
):
255+
logger.warning("没有调用工具,代表已经完成了")
248256
task_completed = True
249257
return completion_response.choices[0].message.content
250258

@@ -282,21 +290,25 @@ async def run(
282290
self,
283291
prompt: str,
284292
available_images: list[str] = None,
293+
sub_title: str = None,
285294
) -> str:
286295
"""
287296
执行写作任务
288297
Args:
289298
prompt: 写作提示
290299
available_images: 可用的图片相对路径列表(如 20250420-173744-9f87792c/编号_分布.png)
300+
sub_title: 子任务标题
291301
"""
302+
logger.info(f"subtitle是:{sub_title}")
303+
292304
if available_images:
293305
self.available_images = available_images
294306
# 拼接成完整URL
295307
image_list = ",".join(available_images)
296308
image_prompt = f"\n可用的图片链接列表:\n{image_list}\n请在写作时适当引用这些图片链接。"
297309
prompt = prompt + image_prompt
298310

299-
return await super().run(prompt, self.system_prompt)
311+
return await super().run(prompt, self.system_prompt, sub_title)
300312

301313
async def summarize(self) -> str:
302314
"""

backend/app/core/llm.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
from app.utils.common_utils import transform_link
23
from openai import OpenAI
34
from app.utils.log_util import logger
45
import time
@@ -33,7 +34,10 @@ async def chat(
3334
retry_delay: float = 1.0, # 添加重试延迟
3435
top_p: float | None = None, # 添加top_p参数,
3536
agent_name: str = "NO_NAME", # CoderAgent or WriterAgent
37+
sub_title: str | None = None,
3638
) -> str:
39+
logger.info(f"subtitle是:{sub_title}")
40+
3741
kwargs = {
3842
"model": self.model,
3943
"messages": history,
@@ -52,10 +56,11 @@ async def chat(
5256
for attempt in range(max_retries):
5357
try:
5458
completion = self.client.chat.completions.create(**kwargs)
59+
logger.info(f"API返回: {completion}")
5560
if not completion or not hasattr(completion, "choices"):
5661
raise ValueError("无效的API响应")
5762
self.chat_count += 1
58-
await self.analyse_completion(completion, agent_name)
63+
await self.analyse_completion(completion, agent_name, sub_title)
5964
return completion
6065
except json.JSONDecodeError:
6166
logger.error(f"第{attempt + 1}次重试: API返回无效JSON")
@@ -65,7 +70,9 @@ async def chat(
6570
logger.debug(f"请求参数: {kwargs}")
6671
raise # 如果所有重试都失败,则抛出异常
6772

68-
async def analyse_completion(self, completion, agent_name):
73+
async def analyse_completion(self, completion, agent_name, sub_title):
74+
logger.info(f"subtitle是:{sub_title}")
75+
6976
code = ""
7077
if (
7178
hasattr(completion.choices[0].message, "tool_calls")
@@ -74,20 +81,22 @@ async def analyse_completion(self, completion, agent_name):
7481
tool_call = completion.choices[0].message.tool_calls[0]
7582
if tool_call.function.name == "execute_code":
7683
code = json.loads(tool_call.function.arguments)["code"]
77-
await self.send_message(agent_name, completion.choices[0].message.content, code)
84+
(
85+
await self.send_message(
86+
agent_name, completion.choices[0].message.content, code, sub_title
87+
)
88+
)
7889

79-
async def send_message(self, agent_name, content, code=""):
90+
async def send_message(self, agent_name, content, code="", sub_title=None):
91+
logger.info(f"subtitle是:{sub_title}")
8092
if agent_name == "CoderAgent":
8193
agent_msg: CoderMessage = CoderMessage(content=content, code=code)
8294
elif agent_name == "WriterAgent":
83-
# 判断content是否包含图片 xx.png,对其处理为 http://localhost:8000/static/20250428-200915-ebc154d4/512.jpg
84-
if re.search(r"\.(png|jpg|jpeg|gif|bmp|webp)$", content):
85-
content = re.sub(
86-
r"\.(png|jpg|jpeg|gif|bmp|webp)$",
87-
lambda match: f"http://localhost:8000/static/{self.task_id}/{match.group(0)}",
88-
content,
89-
)
90-
agent_msg: WriterMessage = WriterMessage(content=content)
95+
# 处理 Markdown 格式的图片语法
96+
content = transform_link(self.task_id, content)
97+
agent_msg: WriterMessage = WriterMessage(
98+
content=content, sub_title=sub_title
99+
)
91100
else:
92101
raise ValueError(f"无效的agent_name: {agent_name}")
93102

backend/app/core/workflow.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ async def execute(self, problem: Problem):
126126
writer_response = await writer_agent.run(
127127
writer_prompt,
128128
available_images=await e2b_code_interpreter.get_created_images(key),
129+
sub_title=key,
129130
)
130131

131132
await redis_manager.publish_message(
@@ -156,7 +157,7 @@ async def execute(self, problem: Problem):
156157
comp_template=problem.comp_template,
157158
format_output=problem.format_output,
158159
)
159-
writer_response = await writer_agent.run(value)
160+
writer_response = await writer_agent.run(prompt=value, sub_title=key)
160161
user_output.set_res(key, writer_response)
161162

162163
logger.info(user_output.get_res())

backend/app/routers/modeling.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from app.utils.redis_manager import redis_manager
77
from app.schemas.request import Problem
88
from app.schemas.response import AgentMessage, AgentType, Message, SystemMessage
9-
from app.utils.common_utils import create_task_id, create_work_dir
9+
from app.utils.common_utils import create_task_id, create_work_dir, get_config_template
1010
import os
1111
import asyncio
1212
from fastapi import HTTPException
@@ -83,6 +83,13 @@ async def modeling(
8383
return {"task_id": task_id, "status": "processing"}
8484

8585

86+
@router.get("/writer_seque")
87+
async def get_writer_seque():
88+
# 返回论文顺序
89+
config_template: dict = get_config_template(CompTemplate.CHINA)
90+
return list(config_template.keys())
91+
92+
8693
async def run_modeling_task_async(
8794
task_id: str,
8895
ques_all: str,

backend/app/schemas/response.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ class CoderMessage(AgentMessage):
7777

7878
class WriterMessage(AgentMessage):
7979
agent_type: AgentType = AgentType.WRITER
80+
sub_title: str | None = None
8081

8182

8283
# 所有可能的消息类型

backend/app/tools/code_interpreter.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ async def _pre_execute_code(self):
115115
)
116116
await self.execute_code(init_code)
117117

118-
def _truncate_text(self, text: str, max_length: int = 5000) -> str:
118+
def _truncate_text(self, text: str, max_length: int = 2000) -> str:
119119
"""截断文本,保留开头和结尾的重要信息"""
120120
if len(text) <= max_length:
121121
return text
@@ -264,6 +264,7 @@ async def execute_code(self, code: str) -> tuple[str, bool, str]:
264264
msg=result._repr_javascript_(),
265265
)
266266
)
267+
267268
# 处理主要结果
268269
# if result.is_main_result and result.text:
269270
# result_text = self._truncate_text(result.text)
@@ -278,15 +279,23 @@ async def execute_code(self, code: str) -> tuple[str, bool, str]:
278279
for item in content_to_display:
279280
if isinstance(item, dict):
280281
if item.get("type") in ["stdout", "stderr", "error"]:
281-
text_to_gpt.append(item.get("content") or item.get("value") or "")
282+
text_to_gpt.append(
283+
self._truncate_text(
284+
item.get("content") or item.get("value") or ""
285+
)
286+
)
282287
elif isinstance(item, ResultModel):
283288
if item.format in ["text", "html", "markdown", "json"]:
284-
text_to_gpt.append(f"[{item.format}]\n{item.msg}")
289+
text_to_gpt.append(
290+
self._truncate_text(f"[{item.format}]\n{item.msg}")
291+
)
285292
elif item.format in ["png", "jpeg", "svg", "pdf"]:
286293
text_to_gpt.append(
287294
f"[{item.format} 图片已生成,内容为 base64,未展示]"
288295
)
289296

297+
logger.info(f"text_to_gpt: {text_to_gpt}")
298+
290299
combined_text = "\n".join(text_to_gpt)
291300

292301
# 在代码执行完成后,立即同步文件

backend/app/utils/common_utils.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
import datetime
33
import hashlib
44
import tomllib
5-
from app.core.llm import LLM
65
from app.utils.enums import CompTemplate
76
from app.utils.log_util import logger
7+
import re
88

99

1010
def create_task_id() -> str:
@@ -38,7 +38,8 @@ def get_work_dir(task_id: str) -> str:
3838
raise FileNotFoundError(f"工作目录不存在: {work_dir}")
3939

4040

41-
def get_config_template(comp_template: CompTemplate) -> dict:
41+
# TODO: 是不是应该将 Prompt 写成一个 class
42+
def get_config_template(comp_template: CompTemplate = CompTemplate.CHINA) -> dict:
4243
if comp_template == CompTemplate.CHINA:
4344
return load_toml(os.path.join("app", "config", "md_template.toml"))
4445

@@ -72,7 +73,7 @@ def get_current_files(folder_path: str, type: str = "all") -> list[str]:
7273
]
7374

7475

75-
def simple_chat(model: LLM, history: list) -> str:
76+
def simple_chat(model, history: list) -> str:
7677
"""
7778
Description of the function.
7879
@@ -92,3 +93,13 @@ def simple_chat(model: LLM, history: list) -> str:
9293
completion = model.client.chat.completions.create(**kwargs)
9394

9495
return completion.choices[0].message.content
96+
97+
98+
# 判断content是否包含图片 xx.png,对其处理为 ![filename](http://localhost:8000/static/20250428-200915-ebc154d4/filename.jpg)
99+
def transform_link(task_id: str, content: str):
100+
content = re.sub(
101+
r"!\[(.*?)\]\((.*?\.(?:png|jpg|jpeg|gif|bmp|webp))\)",
102+
lambda match: f"![{match.group(1)}](http://localhost:8000/static/{task_id}/{match.group(2)})",
103+
content,
104+
)
105+
return content

frontend/src/utils/response.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ export interface CoderMessage extends AgentMessage {
7171

7272
export interface WriterMessage extends AgentMessage {
7373
agent_type: 'WriterAgent';
74+
sub_title?: string;
7475
}
7576

7677
export type Message = SystemMessage | UserMessage | CoderMessage | WriterMessage;

0 commit comments

Comments
 (0)