event_langchain.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import json
  2. from langchain.chat_models import ChatOpenAI
  3. from langchain.prompts.chat import (
  4. ChatPromptTemplate,
  5. SystemMessagePromptTemplate,
  6. HumanMessagePromptTemplate,
  7. )
  8. from format_langchain import format_langchain
  9. from global_langchain import global_model
  10. from utils.utils import convert_choice
  11. from value_langchain import value_langchain
  12. def event_langchain():
  13. print('--------------------------生成事件中--------------------------')
  14. chat = ChatOpenAI(temperature=0)
  15. model = global_model()
  16. output_type = str(model.event_declare)
  17. intro = model.get_intro_str()
  18. style = model.style
  19. story = model.story
  20. system_template = model.event_system_template
  21. system_message_prompt = SystemMessagePromptTemplate.from_template(
  22. system_template)
  23. human_template = model.event_human_template
  24. human_message_prompt = HumanMessagePromptTemplate.from_template(
  25. human_template)
  26. chat_prompt = ChatPromptTemplate.from_messages(
  27. [system_message_prompt, human_message_prompt])
  28. rsp = chat(
  29. chat_prompt.format_prompt(output_type=output_type,
  30. style=style,
  31. story=story,
  32. intro=intro).to_messages())
  33. print(rsp.content)
  34. try:
  35. game_event = json.loads(rsp.content, object_hook=convert_choice)
  36. except:
  37. print('格式错误,修复中')
  38. game_event = format_langchain(rsp.content, output_type)
  39. print(game_event)
  40. model.add_event({
  41. "事件": game_event["事件"],
  42. "是否需要玩家选择下一步操作": game_event["是否需要玩家选择下一步操作"],
  43. "玩家可以做出的选择": game_event["玩家可以做出的选择"],
  44. "当前场景角色": game_event["当前场景角色"],
  45. "当前场景数值系统": game_event["当前场景数值系统"],
  46. "游戏是否结束": game_event["游戏是否结束"],
  47. })
  48. model.update_if_end(game_event["游戏是否结束"])
  49. value = value_langchain()
  50. return game_event