Abbasid commited on
Commit
4656d22
·
verified ·
1 Parent(s): 1b005cd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -25
app.py CHANGED
@@ -17,11 +17,11 @@ from llama_index.core.workflow import (
17
  )
18
  from llama_index.llms.groq import Groq
19
 
20
- # --- Secret Management ---
21
  GROQ_API_KEY = os.environ.get("Groq_Token")
22
  HF_TOKEN = os.environ.get("HF_TOKEN")
23
 
24
- # --- Event and Workflow Definitions (Copied from our notebook) ---
25
  class StoryContext(Event):
26
  story_part: str
27
  inventory: list[str]
@@ -54,22 +54,19 @@ async def generate_image(prompt: str, hf_token: str) -> str | None:
54
  print(f"Image generation failed: {e}")
55
  return None
56
 
57
- # The full workflow class, now with the required end_story step
58
 
59
  class StorytellerWorkflow(Workflow):
60
  def __init__(self, **kwargs):
61
  super().__init__(timeout=300, **kwargs)
62
 
63
  @step
64
- # app.py
65
-
66
- @step
67
  async def generate_story_part(self, ev: StartEvent | UserChoice, ctx: Context) -> StoryContext | StoryEnd:
68
  inventory = await ctx.store.get("inventory", [])
69
  prompt = ""
70
 
71
  if isinstance(ev, StartEvent):
72
- # The prompt for the first turn remains the same.
73
  prompt = """
74
  You are a creative text adventure game master. Your output is for a console game.
75
  Start a new story about a curious explorer entering a recently discovered, glowing cave.
@@ -78,7 +75,7 @@ class StorytellerWorkflow(Workflow):
78
  """
79
  elif isinstance(ev, UserChoice):
80
  last_story_part = await ctx.store.get("last_story_part")
81
- # --- UPDATED, MORE EXPLICIT PROMPT ---
82
  prompt = f"""
83
  You are a creative text adventure game master.
84
  The story so far: "{last_story_part}"
@@ -100,8 +97,6 @@ class StorytellerWorkflow(Workflow):
100
  response = await llm.acomplete(prompt)
101
  response_text = str(response)
102
 
103
- # --- REMOVED THE [NEW_SCENE] CHECK ---
104
-
105
  items_found = re.findall(r"\[ADD_ITEM: (.*?)\]", response_text)
106
  if items_found:
107
  for item in items_found:
@@ -137,17 +132,6 @@ class StorytellerWorkflow(Workflow):
137
 
138
 
139
  # --- Gradio UI and Application Logic ---
140
- # This is the final, correct version of the main application logic function.
141
-
142
- # This is the final, correct version of the main application logic function.
143
- # This is the final, correct version of the main application logic function.
144
-
145
- # app.py
146
-
147
- # The only change is in the function definition line
148
- # app.py
149
-
150
- # This is the final and correct version of the main application logic function.
151
 
152
  async def run_turn(user_input, game_state):
153
  # This function no longer needs the component objects passed in.
@@ -165,7 +149,6 @@ async def run_turn(user_input, game_state):
165
  result_event = await workflow.generate_story_part(event, ctx)
166
 
167
  if isinstance(result_event, StoryEnd):
168
- # Return a single tuple of 4 values
169
  yield (None, result_event.final_message, "", None)
170
  return
171
 
@@ -176,7 +159,6 @@ async def run_turn(user_input, game_state):
176
  # It finds any choice number (like " 2." or " 3.") that has a space before it
177
  # and replaces that space with a newline character. This forces them to be on separate lines.
178
  choices_text = re.sub(r" (\d\.)", r"\n\1", choices_text)
179
- # --- END OF NEW CODE ---
180
 
181
  story_display_text = f"{textwrap.fill(narrative, width=80)}\n\nChoices:{choices_text}"
182
 
@@ -186,7 +168,6 @@ async def run_turn(user_input, game_state):
186
  }
187
  inventory_text = f"**Inventory:** {', '.join(new_game_state['inventory']) if new_game_state['inventory'] else 'Empty'}"
188
 
189
- # The rest of the function remains the same...
190
  yield (None, story_display_text, inventory_text, new_game_state)
191
 
192
  # 2. Generate the image.
@@ -197,7 +178,6 @@ async def run_turn(user_input, game_state):
197
  # 3. Yield a second, complete tuple with the new image path.
198
  yield (image_path, story_display_text, inventory_text, new_game_state)
199
 
200
- # The create_demo function should look like this.
201
 
202
  def create_demo():
203
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
17
  )
18
  from llama_index.llms.groq import Groq
19
 
20
+ # --- Secrets ---
21
  GROQ_API_KEY = os.environ.get("Groq_Token")
22
  HF_TOKEN = os.environ.get("HF_TOKEN")
23
 
24
+ # --- Event and Workflow Definitions ---
25
  class StoryContext(Event):
26
  story_part: str
27
  inventory: list[str]
 
54
  print(f"Image generation failed: {e}")
55
  return None
56
 
57
+ # The full workflow class
58
 
59
  class StorytellerWorkflow(Workflow):
60
  def __init__(self, **kwargs):
61
  super().__init__(timeout=300, **kwargs)
62
 
63
  @step
 
 
 
64
  async def generate_story_part(self, ev: StartEvent | UserChoice, ctx: Context) -> StoryContext | StoryEnd:
65
  inventory = await ctx.store.get("inventory", [])
66
  prompt = ""
67
 
68
  if isinstance(ev, StartEvent):
69
+ # The prompt for the first turn
70
  prompt = """
71
  You are a creative text adventure game master. Your output is for a console game.
72
  Start a new story about a curious explorer entering a recently discovered, glowing cave.
 
75
  """
76
  elif isinstance(ev, UserChoice):
77
  last_story_part = await ctx.store.get("last_story_part")
78
+ # --- EXPLICIT PROMPT ---
79
  prompt = f"""
80
  You are a creative text adventure game master.
81
  The story so far: "{last_story_part}"
 
97
  response = await llm.acomplete(prompt)
98
  response_text = str(response)
99
 
 
 
100
  items_found = re.findall(r"\[ADD_ITEM: (.*?)\]", response_text)
101
  if items_found:
102
  for item in items_found:
 
132
 
133
 
134
  # --- Gradio UI and Application Logic ---
 
 
 
 
 
 
 
 
 
 
 
135
 
136
  async def run_turn(user_input, game_state):
137
  # This function no longer needs the component objects passed in.
 
149
  result_event = await workflow.generate_story_part(event, ctx)
150
 
151
  if isinstance(result_event, StoryEnd):
 
152
  yield (None, result_event.final_message, "", None)
153
  return
154
 
 
159
  # It finds any choice number (like " 2." or " 3.") that has a space before it
160
  # and replaces that space with a newline character. This forces them to be on separate lines.
161
  choices_text = re.sub(r" (\d\.)", r"\n\1", choices_text)
 
162
 
163
  story_display_text = f"{textwrap.fill(narrative, width=80)}\n\nChoices:{choices_text}"
164
 
 
168
  }
169
  inventory_text = f"**Inventory:** {', '.join(new_game_state['inventory']) if new_game_state['inventory'] else 'Empty'}"
170
 
 
171
  yield (None, story_display_text, inventory_text, new_game_state)
172
 
173
  # 2. Generate the image.
 
178
  # 3. Yield a second, complete tuple with the new image path.
179
  yield (image_path, story_display_text, inventory_text, new_game_state)
180
 
 
181
 
182
  def create_demo():
183
  with gr.Blocks(theme=gr.themes.Soft()) as demo: