Skip to content

Commit

Permalink
Merge pull request #1 from rayrayraykk/dev1
Browse files Browse the repository at this point in the history
[Hotfix] Fix runable issue & format some code
  • Loading branch information
ZiTao-Li authored Jan 15, 2024
2 parents 956e19e + 2fe4604 commit 56e5566
Show file tree
Hide file tree
Showing 9 changed files with 192 additions and 122 deletions.
2 changes: 0 additions & 2 deletions examples/game/config/customer_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"hidden_plot": >
1. 王老板想在A市找到当地的经销商,帮助他们在A市打开销路。
2. 王老板生产的鸭脖成本价在1元/包,但王老板的底价希望是1.2元/包,而且希望越高越好。
3. 王老板的工厂可以腾出10万包/天的产能供应A市的消费者。
4. 因为他的新机器已经到位,为了资金周转,王老板希望尽快能找到合适的合作伙伴。
5. 最近几天,他的谈判都不顺利。之前联系的合作对象,或者只能消化2万包一天的产能,或者只愿意出1.1元/包的价格。
Expand All @@ -41,4 +40,3 @@
"plugin_background":
- ""
- "阿炳前两天谈成一个大生意,公司给他发了特别奖金。他今晚想忙里抽闲,犒劳自己。"

2 changes: 1 addition & 1 deletion examples/game/config/game_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
你每次只能透露一小部分你扮演的人物的个人信息,回答不超过30个字。
例子1: 老板,你们的菜做的很好!下次我还会来!
例子2: 多谢老板!你知道,我是搞销售的,如果下次有什么需要帮忙,就跟我说吧。
"invited_chat_prompt": >
"invited_chat_prompt": >
餐馆老板今晚邀请你一起吃饭,饭局上也有其他人。
饭局上的其他可能遇到一些问题。你可以根据你的基本设定,决定是否提供帮助。
例子1: 这确实是个机会啊!你打算出多少货?
Expand Down
127 changes: 77 additions & 50 deletions examples/game/customer.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
from typing import Any, Union
import re
import enum
Expand All @@ -10,15 +11,18 @@

HISTORY_WINDOW = 10


class CustomerConv(enum.IntEnum):
"""Enum for customer status."""

WARMING_UP = 0
AFTER_MEAL_CHAT = 1
INVITED_GROUP_PLOT = 2


class CustomerPlot(enum.IntEnum):
"""Enum for customer plot active or not."""

ACTIVE = 1
NOT_ACTIVE = 0

Expand All @@ -35,8 +39,13 @@ def __init__(self, game_config: dict, **kwargs: Any):
self.stage = CustomerConv.WARMING_UP

def visit(self):
return np.random.binomial(
n=1, p=self.config.get("visit_prob", 0.99)) > 0
return (
np.random.binomial(
n=1,
p=self.config.get("visit_prob", 0.99),
)
> 0
)

def activate_plot(self):
self.plot_stage = CustomerPlot.ACTIVE
Expand All @@ -51,26 +60,31 @@ def reply(self, x: dict = None) -> Union[dict, tuple]:
# TODO:
# not sure if it is some implicit requirement of the tongyi chat api,
# the first/last message must have role 'user'.
x['role'] = 'user'
x["role"] = "user"

if self.stage == CustomerConv.WARMING_UP and "推荐" in x['content']:
if self.stage == CustomerConv.WARMING_UP and "推荐" in x["content"]:
self.stage = CustomerConv.AFTER_MEAL_CHAT
return self._recommendation_to_score(x)
elif self.stage == CustomerConv.WARMING_UP:
return self._pre_meal_chat(x)
elif self.stage == CustomerConv.AFTER_MEAL_CHAT \
or self.stage == CustomerConv.INVITED_GROUP_PLOT:
elif (
self.stage == CustomerConv.AFTER_MEAL_CHAT
or self.stage == CustomerConv.INVITED_GROUP_PLOT
):
return self._main_plot_chat(x)

def _recommendation_to_score(self, x:dict) -> dict:
food = x['content']
food_judge_prompt = self.game_config['food_judge_prompt']
food_judge_prompt = food_judge_prompt.format_map({
"food_preference": self.config["character_setting"][
"food_preference"],
"food": food
})
message = Msg(name='user', content=food_judge_prompt, role='user')
def _recommendation_to_score(self, x: dict) -> dict:
food = x["content"]
food_judge_prompt = self.game_config["food_judge_prompt"]
food_judge_prompt = food_judge_prompt.format_map(
{
"food_preference": self.config["character_setting"][
"food_preference"
],
"food": food,
},
)
message = Msg(name="user", content=food_judge_prompt, role="user")

def _parse_score(text: Any) -> (float, Any):
score = re.search("([0-9]+)分", str(text)).groups()[0]
Expand All @@ -96,18 +110,19 @@ def _default_score(_: str) -> float:

def _pre_meal_chat(self, x: dict) -> dict:
self.preorder_itr_count += 1
system_prompt = self.game_config["order_prompt"].format_map({
"name": self.config["name"],
"character_description":
self.background +
self.config["character_setting"]["food_preference"]
})
system_prompt = self.game_config["order_prompt"].format_map(
{
"name": self.config["name"],
"character_description": self.background
+ self.config["character_setting"]["food_preference"],
},
)
system_msg = Msg(role="user", name="system", content=system_prompt)
# prepare prompt
prompt = self.engine.join(
self._validated_history_messages(recent_n=HISTORY_WINDOW),
system_msg,
x
x,
)
if x is not None:
self.memory.add(x)
Expand All @@ -128,21 +143,27 @@ def _main_plot_chat(self, x: dict) -> dict:
2. Customer is not a main role in the current plot
"""

prompt = self.game_config["basic_background_prompt"].format_map({
"name": self.config["name"],
"character_description": self.background,
})
prompt = self.game_config["basic_background_prompt"].format_map(
{
"name": self.config["name"],
"character_description": self.background,
},
)
if self.plot_stage == CustomerPlot.ACTIVE:
# -> prompt for the main role in the current plot
prompt += self.game_config["hidden_main_plot_prompt"].format_map({
"hidden_plot": self.config["character_setting"]["hidden_plot"]
})
prompt += self.game_config["hidden_main_plot_prompt"].format_map(
{
"hidden_plot": self.config["character_setting"][
"hidden_plot"
],
},
)
if self.stage == CustomerConv.AFTER_MEAL_CHAT:
prompt += self.game_config["hidden_main_plot_after_meal"]
else:
prompt += self.game_config["hidden_main_plot_discussion"]
else:
# -> prompt for the helper or irrelvant roles in the current plot
# -> prompt for the helper or irrelvant roles in the current plot
if self.stage == CustomerConv.AFTER_MEAL_CHAT:
prompt += self.game_config["regular_after_meal_prompt"]
else:
Expand Down Expand Up @@ -172,16 +193,23 @@ def _main_plot_chat(self, x: dict) -> dict:
self.memory.add(reply_msg)
return reply_msg


def refine_background(self) -> None:
background_prompt = self.game_config["basic_background_prompt"].format_map({
"name": self.config["name"],
"character_description": self.background,
})
background_prompt += self.game_config["hidden_main_plot_prompt"].format_map({
"hidden_plot": self.config["character_setting"]["hidden_plot"]
})
analysis_prompt =background_prompt + self.game_config["analysis_conv"]
background_prompt = self.game_config[
"basic_background_prompt"
].format_map(
{
"name": self.config["name"],
"character_description": self.background,
},
)
background_prompt += self.game_config[
"hidden_main_plot_prompt"
].format_map(
{
"hidden_plot": self.config["character_setting"]["hidden_plot"],
},
)
analysis_prompt = background_prompt + self.game_config["analysis_conv"]

system_msg = Msg(role="user", name="system", content=analysis_prompt)

Expand All @@ -193,21 +221,20 @@ def refine_background(self) -> None:
analysis = self.model(messages=prompt)
logger.info(f"聊完之后,{self.name}在想:" + analysis)

update_promot = self.game_config["update_background"].format_map({
"analysis": analysis,
"background": self.background,
"name": self.name,
})
update_msg = Msg(role="user", name="system", content=update_promot)
update_prompt = self.game_config["update_background"].format_map(
{
"analysis": analysis,
"background": self.background,
"name": self.name,
},
)
update_msg = Msg(role="user", name="system", content=update_prompt)
new_background = self.model(messages=[update_msg])
logger.info(f"根据对话,{self.name}的背景更新为:"+ new_background)
logger.info(f"根据对话,{self.name}的背景更新为:" + new_background)
self.background = new_background

def _validated_history_messages(self, recent_n: int=10):
def _validated_history_messages(self, recent_n: int = 10):
hist_mem = self.memory.get_memory(recent_n=recent_n)
if len(hist_mem) > 0:
hist_mem[0]["role"], hist_mem[-1]["role"] = "user", "user"
return hist_mem



Loading

0 comments on commit 56e5566

Please sign in to comment.