Team Ai
Apppublic

JavaFXpert/NimGPT-3.5

sourceHugging Faceapache-2.0updated 4y agoView on Hugging Face
11likes
app.py130 linesDownload Raw Back to root
1import gradio as gr2import datetime3from nim_game_env import NimGameEnv4from nim_gpt_functions import plan_move, execute_move5 6TEMPERATURE_DEFAULT = 0.57PILES_DEFAULT = [3, 5, 7]8HUMAN_STR = "Human"9AI_STR = "AI"10 11 12def reset_game(chat_history, nim_game_env):13    chat_history = []14    nim_game_env = NimGameEnv(PILES_DEFAULT)15    game_state_text, game_state_piles = nim_game_env.reset()16    ascii_art = generate_game_state_ascii_art(game_state_piles, False, 0, "")17    message_str = ""18    return chat_history, chat_history, message_str, ascii_art, nim_game_env19 20 21def generate_game_state_ascii_art(piles, done, reward, player):22    ascii_art = "Game Over, " + player + " wins!"23    if not done:24        pile_a = piles[0]25        pile_b = piles[1]26        pile_c = piles[2]27        ascii_art = f"Pile A: {'|' * pile_a} \nPile B: {'|' * pile_b} \nPile C: {'|' * pile_c}"28    return "<pre>" + ascii_art + "</pre>"29 30 31def send_chat_msg(inp, chat_history, nim_game_env, temperature, openai_api_key):32    if not openai_api_key or openai_api_key == "":33        warning_msg = "<pre>Please paste your OpenAI API key (see https://beta.openai.com)</pre>"34        return chat_history, chat_history, warning_msg35 36    if not inp or inp == "":37        warning_msg = "<pre>Please enter a move</pre>"38        return chat_history, chat_history, warning_msg39 40    inp = inp.strip()41    output = None42    chat_history = chat_history or []43 44    text_obs, observation, reward, done, info = execute_move(inp, nim_game_env, openai_api_key)45    ascii_art = generate_game_state_ascii_art(observation, done, reward, HUMAN_STR)46 47    if done:48        if reward == 1:49            output = "Good game!"50            ascii_art = generate_game_state_ascii_art(observation, done, reward, HUMAN_STR)51        else:52            output = text_obs53            ascii_art = generate_game_state_ascii_art(observation, done, reward, AI_STR)54    else:55        output = plan_move(text_obs, temperature, openai_api_key)56        text_obs, observation, reward, done, info = execute_move(output, nim_game_env, openai_api_key)57        ascii_art = generate_game_state_ascii_art(observation, done, reward, AI_STR)58 59    print("\n==== date/time: " + str(datetime.datetime.now() - datetime.timedelta(hours=5)) + " ====")60    print("inp: " + inp, ", output: ", output, ", observation: ", observation)61 62    chat_history.append((HUMAN_STR + ": " + inp, AI_STR + ": " + output))63    return chat_history, chat_history, ascii_art64 65 66def update_foo(widget, state):67    if widget:68        state = widget69        return state70 71 72block = gr.Blocks(css=".gradio-container {background-color: lightgray}")73with block as nim_game:74    temperature_state = gr.State(TEMPERATURE_DEFAULT)75    openai_api_key_state = gr.State()76    history_state = gr.State()77    nim_game_env_state = gr.State(NimGameEnv(PILES_DEFAULT))78 79    with gr.Row():80        game_state_html = gr.Markdown()81        title = gr.Markdown("""<h3><center>NimGPT-3.5</center></h3>""")82        openai_api_key_textbox = gr.Textbox(placeholder="Paste your OpenAI API key",83                                            show_label=False, lines=1, type='password')84 85    chatbot = gr.Chatbot()86 87    with gr.Row():88        message_tb = gr.Textbox(label="What's your move?",89                                placeholder="I'll take 2 sticks from pile A")90        send_btn = gr.Button(value="Send", variant="secondary").style(full_width=False)91 92    with gr.Row():93        gr.Examples(94            examples=["Three sticks from the second pile",95                      "From pile C remove 2 sticks"],96            inputs=message_tb97        )98        reset_btn = gr.Button(value="Reset Game", variant="secondary").style(full_width=False)99        temperature_slider = gr.Slider(label="GPT Temperature", value=TEMPERATURE_DEFAULT, minimum=0.0, maximum=1.0,100                                       step=0.1)101 102    send_btn.click(send_chat_msg, inputs=[message_tb, history_state, nim_game_env_state, temperature_state,103                                          openai_api_key_state],104                   outputs=[chatbot, history_state, game_state_html])105    message_tb.submit(send_chat_msg, inputs=[message_tb, history_state, nim_game_env_state, temperature_state,106                                             openai_api_key_state],107                      outputs=[chatbot, history_state, game_state_html])108    reset_btn.click(reset_game, inputs=[history_state, nim_game_env_state],109                    outputs=[chatbot, history_state, message_tb, game_state_html, nim_game_env_state])110    nim_game.load(reset_game, inputs=[history_state, nim_game_env_state],111                  outputs=[chatbot, history_state, message_tb, game_state_html, nim_game_env_state])112 113    gr.Markdown("""<center>Each player may remove sticks from a pile on their turn. 114    Player to remove the last stick wins.115    <a href="https://en.wikipedia.org/wiki/Nim" target="new">116    Nim is one of the first-ever electronic computerized games</a>117    </center>""")118 119    gr.HTML("<center>Powered by <a href='https://github.com/hwchase17/langchain'>LangChain 🦜️🔗</a></center>")120 121    openai_api_key_textbox.change(update_foo,122                                  inputs=[openai_api_key_textbox, openai_api_key_state],123                                  outputs=[openai_api_key_state])124 125    temperature_slider.change(update_foo,126                              inputs=[temperature_slider, temperature_state],127                              outputs=[temperature_state])128 129block.launch(debug=False)130