itsalissonsilva commited on
Commit
514ad06
·
verified ·
1 Parent(s): 6940dc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -37
app.py CHANGED
@@ -2,66 +2,96 @@ import gradio as gr
2
  import os
3
  from openai import OpenAI
4
 
5
- # Initialize OpenAI client using API key from environment
6
  api_key = os.getenv("OPENAI_API_KEY")
7
  client = OpenAI(api_key=api_key)
8
 
9
- # Initial game scenario and choices
10
- initial_scenario = "You wake up in a strange forest. Paths lead in all directions.\n"
11
- choices = [
12
  "Walk north into the dense forest.",
13
  "Go south back towards a distant town.",
14
  "Explore east towards the sound of water.",
15
  "Move west where the land rises."
16
  ]
17
 
18
- # Conversation history starts with a system prompt and the opening scene
19
- history = [
20
- {
21
- "role": "system",
22
- "content": (
23
- "You are a text-based RPG engine. Continue the story based on the player's choices. "
24
- "Respond in immersive but concise prose. End each turn ready for the next input."
25
- )
26
- },
27
- {"role": "user", "content": initial_scenario}
28
- ]
 
 
 
 
 
 
 
 
29
 
30
- # Function to generate story continuation from the OpenAI API
31
- def generate_continuation(choice):
32
- history.append({"role": "user", "content": f"> {choice}"})
 
 
33
 
34
  response = client.chat.completions.create(
35
- model="gpt-3.5-turbo", # You can switch to "gpt-4" if needed
36
  messages=history,
37
- temperature=0.8,
38
- max_tokens=150,
39
  )
40
 
41
  continuation = response.choices[0].message.content.strip()
42
  history.append({"role": "assistant", "content": continuation})
43
 
44
- # Build full story text
45
- story_text = initial_scenario + "\n"
46
- for msg in history[2:]: # skip system and initial
47
- prefix = "You: " if msg["role"] == "user" else ""
48
- story_text += f"{prefix}{msg['content']}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
- return story_text.strip()
51
 
52
- # Gradio interface
53
  with gr.Blocks() as app:
 
 
 
54
  with gr.Row():
55
- story_display = gr.Textbox(value=initial_scenario, lines=15, interactive=False, label="Story")
56
- with gr.Row():
57
- choice_buttons = [gr.Button(choice) for choice in choices]
 
 
 
 
 
58
 
59
- def handle_choice(choice_index):
60
- chosen_action = choices[choice_index]
61
- updated_story = generate_continuation(chosen_action)
62
- return updated_story
63
 
64
- for i, button in enumerate(choice_buttons):
65
- button.click(fn=lambda x=i: handle_choice(x), inputs=None, outputs=story_display)
66
 
67
  app.launch()
 
2
  import os
3
  from openai import OpenAI
4
 
5
+ # Load API key from Hugging Face secret
6
  api_key = os.getenv("OPENAI_API_KEY")
7
  client = OpenAI(api_key=api_key)
8
 
9
+ # Initial state
10
+ initial_scenario = "You wake up in a strange forest. Paths lead in all directions."
11
+ default_choices = [
12
  "Walk north into the dense forest.",
13
  "Go south back towards a distant town.",
14
  "Explore east towards the sound of water.",
15
  "Move west where the land rises."
16
  ]
17
 
18
+ # System prompt for role instruction
19
+ system_prompt = {
20
+ "role": "system",
21
+ "content": (
22
+ "You are a text-based RPG engine. Continue the story based on the player's input. "
23
+ "Include vivid descriptions and always end your response with a few suggested choices. "
24
+ "Format them as a numbered list (1., 2., etc). Do not break character or give explanations."
25
+ )
26
+ }
27
+
28
+ # Initialize history
29
+ history = [system_prompt, {"role": "user", "content": initial_scenario}]
30
+ story_log = initial_scenario
31
+
32
+
33
+ def parse_choices_from_response(text):
34
+ lines = text.strip().split("\n")
35
+ options = [line.strip() for line in lines if line.strip().startswith(("1.", "2.", "3.", "4."))]
36
+ return options[:4] if options else default_choices
37
 
38
+
39
+ def update_story(player_input):
40
+ global story_log
41
+
42
+ history.append({"role": "user", "content": f"> {player_input}"})
43
 
44
  response = client.chat.completions.create(
45
+ model="gpt-3.5-turbo",
46
  messages=history,
47
+ temperature=0.9,
48
+ max_tokens=300
49
  )
50
 
51
  continuation = response.choices[0].message.content.strip()
52
  history.append({"role": "assistant", "content": continuation})
53
 
54
+ story_log += f"\n\nYou: {player_input}\n{continuation}"
55
+ new_choices = parse_choices_from_response(continuation)
56
+
57
+ return story_log, new_choices
58
+
59
+
60
+ def handle_button(choice_text):
61
+ return update_story(choice_text)
62
+
63
+
64
+ def handle_custom_input(text_input):
65
+ if not text_input.strip():
66
+ return story_log, default_choices
67
+ return update_story(text_input.strip())
68
+
69
+
70
+ def restart_game():
71
+ global history, story_log
72
+ history = [system_prompt, {"role": "user", "content": initial_scenario}]
73
+ story_log = initial_scenario
74
+ return story_log, default_choices
75
 
 
76
 
 
77
  with gr.Blocks() as app:
78
+ gr.Markdown("## 🌲 Text-Based RPG Adventure")
79
+ story_display = gr.Textbox(value=initial_scenario, lines=20, interactive=False, label="Your Story")
80
+
81
  with gr.Row():
82
+ choice_btns = [gr.Button(choice) for choice in default_choices]
83
+
84
+ custom_input = gr.Textbox(lines=1, placeholder="Or type your action here...", label="Your Action")
85
+ restart_btn = gr.Button("🔄 Restart Game")
86
+
87
+ # Link button events
88
+ for btn in choice_btns:
89
+ btn.click(fn=handle_button, inputs=btn, outputs=[story_display, *choice_btns])
90
 
91
+ # Link custom text input
92
+ custom_input.submit(fn=handle_custom_input, inputs=custom_input, outputs=[story_display, *choice_btns])
 
 
93
 
94
+ # Restart
95
+ restart_btn.click(fn=restart_game, inputs=None, outputs=[story_display, *choice_btns])
96
 
97
  app.launch()