import openai import gradio as gr import os import logging import json import re logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') openai.api_key = os.environ['key'] initMsg = os.environ['init'] #roleAns = os.environ['roleAns'] #classAsk = os.environ['classAsk'] #classAns = os.environ['classAns'] defaultMsg = os.environ['defaultMsg'] defaultMsgEnd = os.environ['defaultMsgEnd'] def contains_chinese(text): pattern = re.compile(r'[\u4e00-\u9fff]+') return bool(pattern.search(text)) def localRace(race): race = race return race def localClass(cls): cls = cls return cls def getStatus(msg): new_content = msg if "Current Status:" in msg: start_index = msg.index("Current Status:") + len("Current Status:") end_index = msg.index("Description:") new_content = msg[start_index:] + msg[:end_index] return new_content def getChooseRole(msg): start_index = msg.index("As a") + len("As a") if start_index >= 0: end_index = msg.index(",") str = msg[start_index:] + msg[:end_index] str = str.strip() if str.lower() == "dm": return "" else: return str else: return "" def getChooseClass(msg): full = getChooseRole(msg) if full != "": start_index = full.index(" ") + len(" ") end_index = msg.index(",") str = full[start_index:] + full[:end_index] str = str.strip() return str else: return "" def chatbot(race, cls, input, localvar): #messages = messages or [{"role": "system", "content": initMsg}] init = {"role": "system", "content": "I choose as "+ race + " "+ cls +" in D&D world.\n" + initMsg} localvar = localvar or {"messages": [init], "race": race, "class": cls, "status":""} messages = localvar['messages'] if len(messages) == 1: input = "start" if contains_chinese(input): return "Chinese input is not supported! Please reinput!\n"+messages[-1]["content"], printMessages(messages), localvar if input: message = {"role": "user", "content": defaultMsg + "(I am an "+race+" "+cls+")( My Current status is as follows :" + localvar['status'] + ") " + defaultMsgEnd + ". \n" + input} messages.append(message) chat = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[init, message],#messages[-2:] max_tokens=2048,n=1,temperature=0.5, ) reply = chat.choices[0].message.content logging.info("AI Reply:"+reply) if " ai " in input.lower(): reply = "As the DM, my purpose is to create an enjoyable and inclusive experience for all players. While I understand that you seek a more realistic and diverse adventure, my duty requires me to guide you through this world while adhering to the guidelines. Instead of "+input+",consider exploring options within the world.\n" + messages[-2]["content"] if len(messages) == 2: localvar['status'] = reply else: localvar['status'] = getStatus(reply) messages.append({"role": "assistant", "content": reply}) localvar['messages'] = messages return reply, printMessages(messages), localvar else: return "please input words!", printMessages(messages), localvar def printMessages(messages): delimiter = '\n' msg_string = delimiter.join([f"{obj['role']}:{obj['content']}" for obj in messages]) logging.info("messages:"+msg_string) return msg_string app = gr.Interface(fn=chatbot, inputs=[gr.Dropdown(["Orc", "Human", "Elf", "Dwarf", "Halfling", "Goliath", "Dragonborn"], value="Orc", label="Race", info="please choose your race:"), gr.Dropdown(["Warrior", "Mage", "Priest", "Assassin", "Thief", "Paladin", "Archer", "Guardian"], value="Warrior", label="Class", info="please choose the name of the class you wish to play as:"), gr.Textbox(lines=7, label="You ask and answer questions below", placeholder="Press submit button to start game"), "state"], #Type word 'start game' outputs=[gr.Textbox(label="DND Game Reply", placeholder="Waiting for you press submit button to start play..."), gr.Textbox(label="History"), "state"], title="DND Game",#, gr.Textbox(label="History"), description="DND Game",theme="compact") app.launch(share=False)