GodSaveMoney / core /make_reply.py
Jeong-hun Kim
debug
151bab0
raw
history blame
2.41 kB
import re
# μƒμ„±λœ λͺ¨λ“  봇 응닡 기둝
def generate_reply(ctx, makePipeLine, user_msg):
# 졜초 응닡
response = generate_valid_response(ctx, makePipeLine, user_msg)
ctx.addHistory("bot", response)
# λΆˆμ•ˆμ •ν•œ 응닡이 μœ λ„λ˜λ―€λ‘œ μ‚¬μš©ν•˜μ§€ μ•ŠμŒ
'''
# 응닡이 λŠκ²Όλ‹€λ©΄ μΆ”κ°€ 생성
if is_truncated_response(response):
continuation = generate_valid_response(ctx, makePipeLine, response)
ctx.addHistory("bot", continuation)
'''
# 봇 응닡 1회 생성
def generate_valid_response(ctx, makePipeline, user_msg) -> str:
user_name = ctx.getUserName()
bot_name = ctx.getBotName()
while True:
prompt = build_prompt(ctx.getHistory(), user_msg, user_name, bot_name)
full_text = makePipeline.character_chat(prompt)
response = extract_response(full_text)
print(f"debug: {response}")
if is_valid_response(response, user_name, bot_name):
break
return clean_response(response, bot_name)
# μž…λ ₯ ν”„λ‘¬ν”„νŠΈ 정리
def build_prompt(history, user_msg, user_name, bot_name):
with open("assets/prompt/init.txt", "r", encoding="utf-8") as f:
system_prompt = f.read().strip()
# 졜근 λŒ€ν™” νžˆμŠ€ν† λ¦¬λ₯Ό 일반 ν…μŠ€νŠΈλ‘œ μž¬κ΅¬μ„±
dialogue = ""
for turn in history[-16:]:
role = user_name if turn["role"] == "user" else bot_name
dialogue += f"{role}: {turn['text']}\n"
dialogue += f"{user_name}: {user_msg}\n"
# λͺ¨λΈμ— λ§žλŠ” 포맷 ꡬ성
prompt = f"""### Instruction:
{system_prompt}
{dialogue}
### Response:
{bot_name}:"""
return prompt
# 좜λ ₯μ—μ„œ 응닡 μΆ”μΆœ (HyperCLOVAX 포맷에 맞게)
def extract_response(full_text):
# '### Response:' 이후 ν…μŠ€νŠΈ μΆ”μΆœ
if "### Response:" in full_text:
reply = full_text.split("### Response:")[-1].strip()
else:
reply = full_text.strip()
return reply
# 응닡 μœ νš¨μ„± 검사
def is_valid_response(text: str, user_name, bot_name) -> bool:
if user_name + ":" in text:
return False
return True
# 응닡 ν˜•μ‹ 정리
def clean_response(text: str, bot_name):
return re.sub(rf"{bot_name}:\\s*", "", text).strip()
# μ€‘λ‹¨λœ 응닡 μ—¬λΆ€ 검사
def is_truncated_response(text: str) -> bool:
return re.search(r"[.?!…\u2026\u2639\u263A\u2764\uD83D\uDE0A\uD83D\uDE22]$", text.strip()) is None