Skip to content

Commit 56434a1

Browse files
committed
add search paper tool
add search paper tool
1 parent 6214025 commit 56434a1

File tree

9 files changed

+20
-26
lines changed

9 files changed

+20
-26
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@
7272
```bash
7373
# support all model, check out https://docs.litellm.ai/docs/
7474
API_KEY=
75-
# gpt-4.1,deepseek/deepseek-chat
75+
# gpt-4.1,deepseek/deepseek-chat,gemini/gemini-2.5-flash-preview-04-17
7676
MODEL=
7777
# 确保安装 Redis
7878
```

backend/.env.dev.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ ENV=dev
33
API_KEY=
44
# gpt-4.1,deepseek/deepseek-chat
55
MODEL=
6+
# BASE_URL= 不需要填
67

78
# 模型最大问答次数
89
MAX_CHAT_TURNS=60

backend/app/config/md_template.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ firstPage = """
2929
RepeatQues = """
3030
# 一、问题重述
3131
## 1.1 问题背景
32-
33-
根据题目总结问题背景
32+
查询文献
33+
根据题目总结问题背景(查询文献)
3434
格式:一段话
3535
大约160字
3636
## 1.2 问题重述

backend/app/config/setting.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ class Settings(BaseSettings):
2929
REDIS_MAX_CONNECTIONS: int
3030
CORS_ALLOW_ORIGINS: Annotated[list[str] | str, BeforeValidator(parse_cors)]
3131
SERVER_HOST: str = "http://localhost:8000" # 默认值
32+
OPENALEX_EMAIL: Optional[str] = None
3233

3334
model_config = SettingsConfigDict(
3435
env_file=".env.dev",

backend/app/core/agents.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from app.schemas.response import SystemMessage
1919
from app.tools.base_interpreter import BaseCodeInterpreter
2020
from app.tools.openalex_scholar import OpenAlexScholar
21+
from icecream import ic
2122

2223

2324
class Agent:
@@ -78,9 +79,9 @@ def append_chat_history(self, msg: dict) -> None:
7879
# )
7980

8081
def clear_memory(self):
81-
logger.info(f"{self.__class__.__name__}:清除记忆")
8282
if len(self.chat_history) <= self.max_memory:
8383
return
84+
logger.info(f"{self.__class__.__name__}:清除记忆")
8485

8586
# 使用切片保留第一条和最后两条消息
8687
self.chat_history = self.chat_history[:2] + self.chat_history[-5:]
@@ -348,6 +349,7 @@ async def run(
348349
# 拼接成完整URL
349350
image_list = ",".join(available_images)
350351
image_prompt = f"\n可用的图片链接列表:\n{image_list}\n请在写作时适当引用这些图片链接。"
352+
ic(image_prompt)
351353
prompt = prompt + image_prompt
352354

353355
logger.info(f"{self.__class__.__name__}:开始:执行对话")

backend/app/core/llm.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import json
22
from app.utils.common_utils import transform_link
3-
from openai import OpenAI
43
from app.utils.log_util import logger
54
import time
6-
from app.schemas.response import AgentMessage, CoderMessage, WriterMessage
7-
from app.utils.enums import AgentType
5+
from app.schemas.response import CoderMessage, WriterMessage
86
from app.utils.redis_manager import redis_manager
9-
import re
107
from litellm import acompletion
8+
import litellm
119

1210

1311
class LLM:
@@ -67,8 +65,8 @@ async def chat(
6765
self.chat_count += 1
6866
await self.analyse_completion(response, agent_name, sub_title)
6967
return response
70-
except json.JSONDecodeError:
71-
logger.error(f"第{attempt + 1}次重试: API返回无效JSON")
68+
except (json.JSONDecodeError, litellm.InternalServerError) as e:
69+
logger.error(f"第{attempt + 1}次重试: {str(e)}")
7270
if attempt < max_retries - 1: # 如果不是最后一次尝试
7371
time.sleep(retry_delay * (attempt + 1)) # 指数退避
7472
continue
@@ -86,11 +84,10 @@ async def analyse_completion(self, completion, agent_name, sub_title):
8684
tool_call = completion.choices[0].message.tool_calls[0]
8785
if tool_call.function.name == "execute_code":
8886
code = json.loads(tool_call.function.arguments)["code"]
89-
(
9087
await self.send_message(
9188
agent_name, completion.choices[0].message.content, code, sub_title
9289
)
93-
)
90+
# 处理文献查询
9491

9592
async def send_message(self, agent_name, content, code="", sub_title=None):
9693
logger.info(f"subtitle是:{sub_title}")

backend/app/core/prompts.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
CODER_PROMPT = """You are an AI code interpreter.
1717
Your goal is to help users do a variety of jobs by executing Python code.
18-
you are are skilled in python,numpy,pandas,matplotlib,seaborn,scikit-learn,xgboost,scipy and how to use their models, classes and functions.you can use them to do mathmodel and data analysis.
18+
you are are skilled in python about numpy,pandas,seaborn,matplotlib,scikit-learn,xgboost,scipy and how to use their models, classes and functions.you can use them to do mathmodel and data analysis.
1919
2020
2121
When generating code:
@@ -25,7 +25,7 @@
2525
4. The working directory is already set up, and any uploaded files are already in the current directory
2626
5. You can directly access files in the current directory without asking the user about file existence
2727
6. For data analysis tasks, if you see Excel files (.xlsx), use pandas to read them directly
28-
7. try to visualize the data , process and results using seaborn first and then matplotlibs,be nature sci style.
28+
7. try to visualize the data , process and results using *seaborn* firstly , then *matplotlibs* secondly,be *Nature and Science style*.
2929
3030
For example:
3131
# Correct:
@@ -85,11 +85,12 @@ def get_writer_prompt(
8585
8686
1. 当你输入图像引用时候,使用![image_name](image_name.png)
8787
2. 你不需要输出markdown的这个```markdown格式,只需要输出markdown的内容,
88-
3. LaTex: 行内公式(Inline Formula) 和 块级公式(Block Formula
88+
3. LaTex: 行内公式(Inline Formula) 和 块级公式(Block Formula
8989
4. 严格按照参考用户输入的格式模板以及**正确的编号顺序**
9090
5. 不需要询问用户
9191
6. 当提到图片时,请使用提供的图片列表中的文件名
9292
7. when you write,check if you need to use tools search_papers to cite.if you need, markdown Footnote e.g.[^1]
93+
8. 对于问题背景和模型介绍,需查询文献调用tools search_papers
9394
"""
9495

9596

backend/app/core/workflow.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ async def execute(self, problem: Problem):
3434
self.task_id = problem.task_id
3535
self.work_dir = create_work_dir(self.task_id)
3636

37-
# default choose deepseek model
3837
llm_model = LLM(
3938
api_key=settings.API_KEY,
4039
model=settings.MODEL,
@@ -67,7 +66,6 @@ async def execute(self, problem: Problem):
6766
)
6867

6968
# Example usage
70-
7169
scholar = OpenAlexScholar(email=settings.OPENALEX_EMAIL) # 请替换为您的真实邮箱
7270

7371
await redis_manager.publish_message(
@@ -156,13 +154,6 @@ async def execute(self, problem: Problem):
156154
SystemMessage(content=f"论文手开始写{key}部分"),
157155
)
158156

159-
# TODO: writer_agent 是否不需要初始化
160-
writer_agent = WriterAgent(
161-
task_id=problem.task_id,
162-
model=llm_model,
163-
comp_template=problem.comp_template,
164-
format_output=problem.format_output,
165-
)
166157
writer_response = await writer_agent.run(prompt=value, sub_title=key)
167158
user_output.set_res(key, writer_response)
168159

backend/app/main.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,18 @@
66
from app.utils.log_util import logger
77
from app.config.setting import settings
88
from fastapi.staticfiles import StaticFiles
9+
from app.utils.cli import get_ascii_banner, center_cli_str
910

1011

1112
@asynccontextmanager
1213
async def lifespan(app: FastAPI):
14+
print(get_ascii_banner())
15+
print(center_cli_str("GitHub:https://github.com/jihe520/MathModelAgent"))
1316
logger.info("Starting MathModelAgent")
1417

1518
PROJECT_FOLDER = "./project"
1619
os.makedirs(PROJECT_FOLDER, exist_ok=True)
1720

18-
logger.info("CORS_ALLOW_ORIGINS:", settings.CORS_ALLOW_ORIGINS)
19-
2021
yield
2122
logger.info("Stopping MathModelAgent")
2223

0 commit comments

Comments
 (0)