|
| 1 | +from app.core.llm.llm import LLM |
| 2 | +from app.utils.log_util import logger |
| 3 | + |
| 4 | + |
| 5 | +class Agent: |
| 6 | + def __init__( |
| 7 | + self, |
| 8 | + task_id: str, |
| 9 | + model: LLM, |
| 10 | + max_chat_turns: int = 30, # 单个agent最大对话轮次 |
| 11 | + max_memory: int = 25, # 最大记忆轮次 |
| 12 | + ) -> None: |
| 13 | + self.task_id = task_id |
| 14 | + self.model = model |
| 15 | + self.chat_history: list[dict] = [] # 存储对话历史 |
| 16 | + self.max_chat_turns = max_chat_turns # 最大对话轮次 |
| 17 | + self.current_chat_turns = 0 # 当前对话轮次计数器 |
| 18 | + self.max_memory = max_memory # 最大记忆轮次 |
| 19 | + |
| 20 | + async def run(self, prompt: str, system_prompt: str, sub_title: str) -> str: |
| 21 | + """ |
| 22 | + 执行agent的对话并返回结果和总结 |
| 23 | +
|
| 24 | + Args: |
| 25 | + prompt: 输入的提示 |
| 26 | +
|
| 27 | + Returns: |
| 28 | + str: 模型的响应 |
| 29 | + """ |
| 30 | + try: |
| 31 | + logger.info(f"{self.__class__.__name__}:开始:执行对话") |
| 32 | + self.current_chat_turns = 0 # 重置对话轮次计数器 |
| 33 | + |
| 34 | + # 更新对话历史 |
| 35 | + self.append_chat_history({"role": "system", "content": system_prompt}) |
| 36 | + self.append_chat_history({"role": "user", "content": prompt}) |
| 37 | + |
| 38 | + # 获取历史消息用于本次对话 |
| 39 | + response = await self.model.chat( |
| 40 | + history=self.chat_history, |
| 41 | + agent_name=self.__class__.__name__, |
| 42 | + sub_title=sub_title, |
| 43 | + ) |
| 44 | + response_content = response.choices[0].message.content |
| 45 | + self.chat_history.append({"role": "assistant", "content": response_content}) |
| 46 | + logger.info(f"{self.__class__.__name__}:完成:执行对话") |
| 47 | + return response_content |
| 48 | + except Exception as e: |
| 49 | + error_msg = f"执行过程中遇到错误: {str(e)}" |
| 50 | + logger.error(f"Agent执行失败: {str(e)}") |
| 51 | + return error_msg |
| 52 | + |
| 53 | + def append_chat_history(self, msg: dict) -> None: |
| 54 | + self.clear_memory() |
| 55 | + self.chat_history.append(msg) |
| 56 | + |
| 57 | + def clear_memory(self): |
| 58 | + if len(self.chat_history) <= self.max_memory: |
| 59 | + return |
| 60 | + logger.info(f"{self.__class__.__name__}:清除记忆") |
| 61 | + |
| 62 | + # 使用切片保留第一条和最后两条消息 |
| 63 | + self.chat_history = self.chat_history[:2] + self.chat_history[-5:] |
0 commit comments