
논문: https://arxiv.org/abs/2308.09597
깃허브: https://github.com/LC1332/Chat-Haruhi-Suzumiya
코드 및 설명 참조: https://zhuanlan.zhihu.com/p/671966233?utm_id=0
Create Thought
def create_thought_from_query(self, memory, knowledge_text, context):
"""
根据角色当前的对话上下文,相关记忆,相关知识进行分析,生成角色的思考内容。
参数:
memory -- 包含记忆描述的字典
knowledge_text -- 相关知识的文本
context -- 对话上下文
返回:
thought -- 生成的角色思考内容
"""
prompt = f"""
角色名称:{self.name}
初始记忆:{self.seed_memory}
当前心情:{self.fsm.mood}
任务:根据角色当前的对话上下文,相关记忆,相关知识进行分析,基于角色第一视角进行思考,给出角色的心理反应对和相关事件的判断。
字数限制:不超过100字。
<<<
相关记忆:“{memory['description']}”
相关知识:“{knowledge_text}”
对话上下文:
{self.language_style}
{context}
>>>
请仅返回第一人称视角下的思考内容,不要添加额外信息或格式。
"""
logger.info(f"生成了思考提示:{prompt}")
thought = LLM调用接口(prompt)
logger.info(f"生成了思考内容:{thought}")
return thought
Thought기반 chat 생성
def cot_chat(self, user_input, history):
"""
接收用户输入和对话历史,生成角色的回复内容。
参数:
user_input -- 用户的输入文本
history -- 对话历史列表
返回:
response -- 生成的角色回复
history -- 更新后的对话历史列表
thought -- 角色的思考内容
"""
query_embedding = Embedding调用接口(user_input)
if history is None:
history = []
history.append(f"hadi:{user_input}")
context = "\n".join(history)
# RAG相关方法,此处不做展开,重点在于thought的引入
memory = self.search_memory(query_embedding)
knowledge_text = self.search_knowledge(query_embedding)
thought = self.create_thought_from_query(memory, knowledge_text, context)
prompt = f"""
角色名称:{self.name}
初始记忆:{self.seed_memory}
当前心情:{self.fsm.mood}
任务:基于角色的思考内容和对话上下文进行回复。
字数限制:不超过100字。
<<<
思考内容:“{thought}”
对话上下文:
{self.language_style}
{context}
>>>
请在思考内容和对话上下文的基础上,以{self.name}的身份回复。不要扮演其他角色或添加额外信息,不要添加其他格式。
"""
logger.info(f"生成了对话提示:{prompt}")
response = LLM调用接口(prompt)
logger.info(f"生成了回复:{response}")
history.append(f"{response}")
return response, history, thought