pratikshahp commited on
Commit
5915dbb
·
verified ·
1 Parent(s): c98cee8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -0
app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ from helper import load_world, save_world
4
+ from together import Together
5
+ from helper import get_together_api_key
6
+ from guardrail import is_safe
7
+ from randomselection import randomly_select_from_json
8
+ # Initialize Together client
9
+ client = Together(api_key=get_together_api_key())
10
+
11
+ # Load the world data from the JSON file
12
+ world_data = load_world('./YourWorld_L1.json')
13
+
14
+
15
+ # Function to randomly select a world, kingdom, town, and character
16
+
17
+ # Function to initialize or reinitialize the game state
18
+ def initialize_game_state():
19
+ random_state = randomly_select_from_json(world_data)
20
+ world = random_state["world"]
21
+ kingdom = random_state["kingdom"]
22
+ town = random_state["town"]
23
+ character = random_state["character"]
24
+
25
+ system_prompt = """You are an AI Game master. Your job is to create a
26
+ start to an adventure based on the world, kingdom, town, and character
27
+ a player is playing as.
28
+ Instructions:
29
+ - You must use only 2-4 sentences.
30
+ - Please use simple and clear language that is easy for children to understand.
31
+ - Write in second person, e.g., "You are Jack."
32
+ - Write in present tense, e.g., "You stand at..."
33
+ - First describe the character and their backstory.
34
+ - Then describe where they start and what they see around them."""
35
+
36
+ world_info = f"""
37
+ World: {world['description']}
38
+ Kingdom: {kingdom['description']}
39
+ Town: {town['description']}
40
+ Your Character: {character['description']}
41
+ """
42
+
43
+ model_output = client.chat.completions.create(
44
+ model="meta-llama/Llama-3-70b-chat-hf",
45
+ temperature=1.0,
46
+ messages=[
47
+ {"role": "system", "content": system_prompt},
48
+ {"role": "user", "content": world_info + '\nYour Start:'}
49
+ ],
50
+ )
51
+
52
+ start = model_output.choices[0].message.content
53
+
54
+ return {
55
+ "world": world["description"],
56
+ "kingdom": kingdom["description"],
57
+ "town": town["description"],
58
+ "character": character["description"],
59
+ "start": start,
60
+ }
61
+
62
+
63
+ # Initialize the game state
64
+ game_state = initialize_game_state()
65
+ game_running = True # Flag to manage game status
66
+
67
+ # Function to process user input and actions
68
+ def run_action(message, history):
69
+ global game_state, game_running # Access the global game state and game status
70
+
71
+ if not game_running:
72
+ return "The game has ended. Type 'restart the game' to play again."
73
+
74
+ if message.lower() == "start game":
75
+ return game_state["start"]
76
+
77
+ if message.lower() == "restart the game":
78
+ game_state = initialize_game_state()
79
+ return "Game restarted! " + game_state["start"]
80
+
81
+ if message.lower() == "exit":
82
+ game_running = False
83
+ return "The game has ended. Type 'restart the game' to play again."
84
+
85
+ system_prompt = """You are an AI Game master. Your job is to write what \
86
+ happens next in a player's adventure game.\
87
+ Instructions: \
88
+ - Write only 1-3 sentences. \
89
+ - Please use simple and clear language that is easy for children to understand.
90
+ - Always write in second person, e.g., "You look north and see..." \
91
+ - Write in present tense."""
92
+
93
+ world_info = f"""
94
+ World: {game_state['world']}
95
+ Kingdom: {game_state['kingdom']}
96
+ Town: {game_state['town']}
97
+ Your Character: {game_state['character']}"""
98
+
99
+ # Build the context for the conversation
100
+ messages = [
101
+ {"role": "system", "content": system_prompt},
102
+ {"role": "user", "content": world_info},
103
+ ]
104
+
105
+ for action in history:
106
+ if isinstance(action, tuple) and len(action) == 2:
107
+ messages.append({"role": "assistant", "content": action[0]})
108
+ messages.append({"role": "user", "content": action[1]})
109
+
110
+ # Add the user's current action
111
+ messages.append({"role": "user", "content": message})
112
+
113
+ # Get the model's response
114
+ model_output = client.chat.completions.create(
115
+ model="meta-llama/Llama-3-70b-chat-hf",
116
+ messages=messages,
117
+ )
118
+
119
+ return model_output.choices[0].message.content
120
+
121
+
122
+ def main_loop(message, history):
123
+
124
+ if not is_safe(message):
125
+ return 'Invalid action.'
126
+
127
+ result = run_action(message, history)
128
+ safe = is_safe(result)
129
+ if(safe):
130
+ return result # only if safe?
131
+ else:
132
+ return 'Invalid output.'
133
+
134
+
135
+ # Gradio ChatInterface
136
+ demo = gr.ChatInterface(
137
+ main_loop,
138
+ chatbot=gr.Chatbot(
139
+ height=300,
140
+ placeholder="Type 'start game' to begin, 'restart the game' to restart, or 'exit' to end the game.",
141
+ type="messages", # Ensures proper rendering
142
+ ),
143
+ textbox=gr.Textbox(
144
+ placeholder="What do you do next?",
145
+ container=False,
146
+ scale=7,
147
+ ),
148
+ title="AI RPG",
149
+ theme="Monochrome",
150
+ examples=["Look around", "Continue the story"],
151
+ cache_examples=False,
152
+ )
153
+
154
+ # Launch the Gradio app
155
+ demo.launch(share=True, server_name="0.0.0.0")