pratikshahp commited on
Commit
befab30
·
verified ·
1 Parent(s): caef204

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -78
app.py CHANGED
@@ -15,40 +15,32 @@ def randomly_select_from_json(world_data):
15
  world_name = world_data["name"]
16
  world_description = world_data["description"]
17
 
18
- # Filter valid kingdoms (those with towns containing NPCs)
19
  valid_kingdoms = {
20
  k_name: k_data
21
  for k_name, k_data in world_data["kingdoms"].items()
22
  if any("npcs" in town_data and town_data["npcs"] for town_data in k_data["towns"].values())
23
  }
24
-
25
  if not valid_kingdoms:
26
  raise ValueError("No kingdoms with valid towns and NPCs found.")
27
 
28
- # Randomly select a kingdom
29
  kingdom_name, kingdom_data = random.choice(list(valid_kingdoms.items()))
30
  kingdom_description = kingdom_data["description"]
31
 
32
- # Filter towns with NPCs in the selected kingdom
33
  valid_towns = {
34
  t_name: t_data
35
  for t_name, t_data in kingdom_data["towns"].items()
36
  if "npcs" in t_data and t_data["npcs"]
37
  }
38
-
39
  if not valid_towns:
40
  raise ValueError(f"No towns with NPCs found in kingdom: {kingdom_name}")
41
 
42
- # Randomly select a town
43
  town_name, town_data = random.choice(list(valid_towns.items()))
44
  town_description = town_data["description"]
45
 
46
- # Randomly select an NPC
47
  npcs = town_data["npcs"]
48
  character_name, character_data = random.choice(list(npcs.items()))
49
  character_description = character_data["description"]
50
 
51
- # Return the selected elements
52
  return {
53
  "world": {"name": world_name, "description": world_description},
54
  "kingdom": {"name": kingdom_name, "description": kingdom_description},
@@ -56,24 +48,14 @@ def randomly_select_from_json(world_data):
56
  "character": {"name": character_name, "description": character_description},
57
  }
58
 
59
- # Game state to store the world, kingdom, town, and character
60
- game_state = None
61
-
62
- # Function to start the game with a new character
63
- def start_new_game():
64
- global game_state
65
- # Reload JSON data and randomly select new elements
66
  random_state = randomly_select_from_json(world_data)
 
 
 
 
67
 
68
- # Format the data for the game
69
- game_state = {
70
- "world": random_state["world"]["description"],
71
- "kingdom": random_state["kingdom"]["description"],
72
- "town": random_state["town"]["description"],
73
- "character": random_state["character"]["description"],
74
- }
75
-
76
- # Create the system prompt for the new game
77
  system_prompt = """You are an AI Game master. Your job is to create a
78
  start to an adventure based on the world, kingdom, town, and character
79
  a player is playing as.
@@ -85,15 +67,13 @@ def start_new_game():
85
  - First describe the character and their backstory.
86
  - Then describe where they start and what they see around them."""
87
 
88
- # Format the world info for the model
89
  world_info = f"""
90
- World: {random_state['world']['description']}
91
- Kingdom: {random_state['kingdom']['description']}
92
- Town: {random_state['town']['description']}
93
- Your Character: {random_state['character']['description']}
94
  """
95
 
96
- # Generate the starting point using Together AI
97
  model_output = client.chat.completions.create(
98
  model="meta-llama/Llama-3-70b-chat-hf",
99
  temperature=1.0,
@@ -103,21 +83,23 @@ def start_new_game():
103
  ],
104
  )
105
 
106
- # Extract the start response
107
- start_text = model_output.choices[0].message.content
108
 
109
- # Save the starting point to the game state
110
- game_state["start"] = start_text
111
- return start_text
 
 
 
 
112
 
113
- # Main action loop for the game
114
- def run_action(message, history):
115
- global game_state
116
 
 
117
  if message.lower() == "start game":
118
  return game_state["start"]
119
 
120
- # Continue the story
121
  system_prompt = """You are an AI Game master. Your job is to write what \
122
  happens next in a player's adventure game.\
123
  Instructions: \
@@ -126,25 +108,24 @@ def run_action(message, history):
126
  - Always write in second person, e.g., "You look north and see..." \
127
  - Write in present tense."""
128
 
129
- # Build the context for the conversation
 
 
 
 
 
130
  messages = [
131
  {"role": "system", "content": system_prompt},
132
- {"role": "user", "content": f"""
133
- World: {game_state['world']}
134
- Kingdom: {game_state['kingdom']}
135
- Town: {game_state['town']}
136
- Your Character: {game_state['character']}
137
- """},
138
  ]
139
 
140
  for action in history:
141
- messages.append({"role": "assistant", "content": action[0]})
142
- messages.append({"role": "user", "content": action[1]})
 
143
 
144
- # Add the user's current action
145
  messages.append({"role": "user", "content": message})
146
 
147
- # Get the model's response
148
  model_output = client.chat.completions.create(
149
  model="meta-llama/Llama-3-70b-chat-hf",
150
  messages=messages,
@@ -152,31 +133,27 @@ def run_action(message, history):
152
 
153
  return model_output.choices[0].message.content
154
 
155
- # Gradio interface
156
- def main_loop(message, history):
157
- return run_action(message, history)
158
-
159
- # Initialize Gradio interface
160
- demo = gr.ChatInterface(
161
- main_loop,
162
- chatbot=gr.Chatbot(
163
- height=250,
164
- placeholder="Type 'start game' to begin",
165
- type="messages",
166
- ),
167
- textbox=gr.Textbox(
168
- placeholder="What do you do next?",
169
- container=False,
170
- scale=7,
171
- ),
172
- title="AI RPG",
173
- theme="soft",
174
- examples=["Look around", "Continue the story"],
175
- cache_examples=False,
176
- )
177
-
178
- # Add a "Start Again" button
179
- demo.add_button("Start Again", start_new_game)
180
-
181
- # Launch the Gradio app
182
- demo.launch(share=True)
 
15
  world_name = world_data["name"]
16
  world_description = world_data["description"]
17
 
 
18
  valid_kingdoms = {
19
  k_name: k_data
20
  for k_name, k_data in world_data["kingdoms"].items()
21
  if any("npcs" in town_data and town_data["npcs"] for town_data in k_data["towns"].values())
22
  }
 
23
  if not valid_kingdoms:
24
  raise ValueError("No kingdoms with valid towns and NPCs found.")
25
 
 
26
  kingdom_name, kingdom_data = random.choice(list(valid_kingdoms.items()))
27
  kingdom_description = kingdom_data["description"]
28
 
 
29
  valid_towns = {
30
  t_name: t_data
31
  for t_name, t_data in kingdom_data["towns"].items()
32
  if "npcs" in t_data and t_data["npcs"]
33
  }
 
34
  if not valid_towns:
35
  raise ValueError(f"No towns with NPCs found in kingdom: {kingdom_name}")
36
 
 
37
  town_name, town_data = random.choice(list(valid_towns.items()))
38
  town_description = town_data["description"]
39
 
 
40
  npcs = town_data["npcs"]
41
  character_name, character_data = random.choice(list(npcs.items()))
42
  character_description = character_data["description"]
43
 
 
44
  return {
45
  "world": {"name": world_name, "description": world_description},
46
  "kingdom": {"name": kingdom_name, "description": kingdom_description},
 
48
  "character": {"name": character_name, "description": character_description},
49
  }
50
 
51
+ # Initialize random state
52
+ def initialize_game_state():
 
 
 
 
 
53
  random_state = randomly_select_from_json(world_data)
54
+ world = random_state["world"]
55
+ kingdom = random_state["kingdom"]
56
+ town = random_state["town"]
57
+ character = random_state["character"]
58
 
 
 
 
 
 
 
 
 
 
59
  system_prompt = """You are an AI Game master. Your job is to create a
60
  start to an adventure based on the world, kingdom, town, and character
61
  a player is playing as.
 
67
  - First describe the character and their backstory.
68
  - Then describe where they start and what they see around them."""
69
 
 
70
  world_info = f"""
71
+ World: {world['description']}
72
+ Kingdom: {kingdom['description']}
73
+ Town: {town['description']}
74
+ Your Character: {character['description']}
75
  """
76
 
 
77
  model_output = client.chat.completions.create(
78
  model="meta-llama/Llama-3-70b-chat-hf",
79
  temperature=1.0,
 
83
  ],
84
  )
85
 
86
+ start = model_output.choices[0].message.content
 
87
 
88
+ return {
89
+ "world": world["description"],
90
+ "kingdom": kingdom["description"],
91
+ "town": town["description"],
92
+ "character": character["description"],
93
+ "start": start,
94
+ }
95
 
96
+ # Game state
97
+ game_state = initialize_game_state()
 
98
 
99
+ def run_action(message, history, game_state):
100
  if message.lower() == "start game":
101
  return game_state["start"]
102
 
 
103
  system_prompt = """You are an AI Game master. Your job is to write what \
104
  happens next in a player's adventure game.\
105
  Instructions: \
 
108
  - Always write in second person, e.g., "You look north and see..." \
109
  - Write in present tense."""
110
 
111
+ world_info = f"""
112
+ World: {game_state['world']}
113
+ Kingdom: {game_state['kingdom']}
114
+ Town: {game_state['town']}
115
+ Your Character: {game_state['character']}"""
116
+
117
  messages = [
118
  {"role": "system", "content": system_prompt},
119
+ {"role": "user", "content": world_info},
 
 
 
 
 
120
  ]
121
 
122
  for action in history:
123
+ if isinstance(action, tuple) and len(action) == 2:
124
+ messages.append({"role": "assistant", "content": action[0]})
125
+ messages.append({"role": "user", "content": action[1]})
126
 
 
127
  messages.append({"role": "user", "content": message})
128
 
 
129
  model_output = client.chat.completions.create(
130
  model="meta-llama/Llama-3-70b-chat-hf",
131
  messages=messages,
 
133
 
134
  return model_output.choices[0].message.content
135
 
136
+ # Main Gradio app
137
+ with gr.Blocks() as demo:
138
+ gr.Markdown("## AI RPG Adventure Game")
139
+ chatbot = gr.Chatbot(type="messages")
140
+ msg_input = gr.Textbox(
141
+ placeholder="Type 'start game' to begin or enter actions...",
142
+ label="Your Action",
143
+ )
144
+ start_again = gr.Button("Start Again")
145
+
146
+ def handle_message(message, history):
147
+ response = run_action(message, history, game_state)
148
+ return history + [(message, response)]
149
+
150
+ def restart_game():
151
+ global game_state
152
+ game_state = initialize_game_state()
153
+ return [("Game restarted!", game_state["start"])]
154
+
155
+ msg_input.submit(handle_message, [msg_input, chatbot], chatbot)
156
+ start_again.click(restart_game, inputs=[], outputs=chatbot)
157
+
158
+ # Launch the game
159
+ demo.launch(share=True, server_name="0.0.0.0")