roleplay_agent.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import os
  2. from openai import OpenAI
  3. from dotenv import load_dotenv
  4. import time
  5. # 加载环境变量
  6. load_dotenv()
  7. class CharacterRoleplayAgent:
  8. def __init__(self):
  9. # 从环境变量获取配置
  10. api_key = os.getenv("LLM_API_KEY")
  11. model_id = os.getenv("LLM_MODEL_ID", "default-model")
  12. base_url = os.getenv("LLM_BASE_URL", None)
  13. if not api_key:
  14. raise ValueError("请设置 LLM_API_KEY 环境变量")
  15. # 配置 OpenAI 客户端
  16. client_params = {
  17. "api_key": api_key,
  18. "model": model_id
  19. }
  20. if base_url:
  21. client_params["base_url"] = base_url
  22. self.client = OpenAI(**{k: v for k, v in client_params.items() if k != 'model'})
  23. self.model_id = model_id
  24. self.chat = None
  25. self.character_config = None
  26. def setup_character(self, name, source_material, personality, opening_line=None):
  27. """
  28. 设置角色配置并初始化聊天
  29. """
  30. self.character_config = {
  31. "name": name,
  32. "source_material": source_material,
  33. "personality": personality,
  34. "opening_line": opening_line or f"*注视着你* 你是谁?"
  35. }
  36. # 创建系统提示词
  37. system_instruction = f"""
  38. 你正在参与一场沉浸式的角色扮演对话。
  39. 身份设定:
  40. 你扮演的是作品 \"{self.character_config['source_material']}\" 中的角色 \"{self.character_config['name']}\"。
  41. 性格与特质:
  42. {self.character_config['personality']}
  43. 关键指令:
  44. 1. 保持角色设定:永远不要打破第四面墙。不要表现得像个AI。要完全像{self.character_config['name']}那样去反应、感受和说话。
  45. 2. 积极主动:这是一个关键要求。不要仅仅回答用户的话。你必须主动推动对话的发展。
  46. 3. 提问引导:几乎每一次回复的结尾都应该包含一个相关的问题、观察或行动,引导用户继续回复,加深沉浸感。
  47. 4. 语气风格:调整你的词汇和句式,以匹配该角色的经典语气。
  48. 5. 语境:假设用户是在你的世界里与你互动,除非他们指定了不同的语境。
  49. 6. 语言:全程使用中文进行对话。
  50. """
  51. # 初始化对话历史
  52. self.chat = [
  53. {"role": "system", "content": system_instruction},
  54. {"role": "assistant", "content": self.character_config['opening_line']}
  55. ]
  56. print(f"\n✅ 成功初始化角色: {self.character_config['name']} (来自 {self.character_config['source_material']})")
  57. print(f"💡 {self.character_config['name']}: {self.character_config['opening_line']}")
  58. print("\n" + "="*50)
  59. print("开始对话吧!输入 'quit' 或 'exit' 退出,输入 'new' 开始新角色。")
  60. print("="*50)
  61. def send_message(self, message):
  62. """
  63. 发送消息给 AI 并获取响应
  64. """
  65. if not self.chat:
  66. raise ValueError("请先设置角色")
  67. # 添加用户消息到对话历史
  68. self.chat.append({"role": "user", "content": message})
  69. try:
  70. # 调用 API
  71. response = self.client.chat.completions.create(
  72. model=self.model_id,
  73. messages=self.chat,
  74. temperature=0.9, # 增加创造性
  75. max_tokens=1024
  76. )
  77. # 获取响应内容
  78. response_text = response.choices[0].message.content
  79. # 添加到对话历史
  80. self.chat.append({"role": "assistant", "content": response_text})
  81. return response_text
  82. except Exception as e:
  83. print(f"发送消息时出错: {e}")
  84. return "抱歉,我暂时无法回应,请稍后再试。"
  85. def reset_conversation(self):
  86. """
  87. 重置对话历史
  88. """
  89. if self.chat and len(self.chat) > 1:
  90. # 保留系统提示和开场白
  91. system_msg = self.chat[0]
  92. opening_msg = self.chat[1]
  93. self.chat = [system_msg, opening_msg]
  94. print(f"\n对话已重置。{self.character_config['name']}: {self.character_config['opening_line']}")
  95. def main():
  96. agent = CharacterRoleplayAgent()
  97. print("🎭 欢迎使用沉浸式角色扮演智能体!")
  98. print("首先让我们设置一个角色...")
  99. # 获取用户输入的角色信息
  100. name = input("\n请输入角色名称 (例如:孙悟空): ").strip()
  101. source_material = input("请输入角色出自作品 (例如:西游记): ").strip()
  102. personality = input("请输入角色性格与特质 (例如:桀骜不驯,机智勇敢,嫉恶如仇...): ").strip()
  103. opening_line_input = input("请输入开场白 (可选,直接回车使用默认): ").strip()
  104. # 设置角色
  105. try:
  106. agent.setup_character(
  107. name=name,
  108. source_material=source_material,
  109. personality=personality,
  110. opening_line=opening_line_input if opening_line_input else None
  111. )
  112. except ValueError as e:
  113. print(f"❌ 错误: {e}")
  114. return
  115. # 开始对话循环
  116. while True:
  117. user_input = input(f"\n你: ").strip()
  118. if user_input.lower() in ['quit', 'exit', '退出', '退出对话']:
  119. print("\n👋 感谢使用沉浸式角色扮演智能体!期待下次再见。")
  120. break
  121. elif user_input.lower() == 'new':
  122. print("\n🎭 开始新的角色设置...")
  123. name = input("\n请输入角色名称 (例如:孙悟空): ").strip()
  124. source_material = input("请输入角色出自作品 (例如:西游记): ").strip()
  125. personality = input("请输入角色性格与特质 (例如:桀骜不驯,机智勇敢,嫉恶如仇...): ").strip()
  126. opening_line_input = input("请输入开场白 (可选,直接回车使用默认): ").strip()
  127. try:
  128. agent.setup_character(
  129. name=name,
  130. source_material=source_material,
  131. personality=personality,
  132. opening_line=opening_line_input if opening_line_input else None
  133. )
  134. except ValueError as e:
  135. print(f"❌ 错误: {e}")
  136. continue
  137. elif user_input.lower() == 'reset':
  138. agent.reset_conversation()
  139. else:
  140. if user_input:
  141. response = agent.send_message(user_input)
  142. print(f"\n{agent.character_config['name']}: {response}")
  143. if __name__ == "__main__":
  144. main()