Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Install dependencies
|
2 |
+
# pip install gradio langgraph
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
import random
|
6 |
+
from typing import Literal
|
7 |
+
from typing_extensions import TypedDict
|
8 |
+
from langgraph.graph import StateGraph, START, END
|
9 |
+
|
10 |
+
# Define the game state
|
11 |
+
global_score = {"total": 0} # Track winnings globally
|
12 |
+
|
13 |
+
class State(TypedDict):
|
14 |
+
bet: int
|
15 |
+
result: str
|
16 |
+
score: int
|
17 |
+
|
18 |
+
# Nodes for LangGraph
|
19 |
+
def input_node(state):
|
20 |
+
return state
|
21 |
+
|
22 |
+
def success_node(state):
|
23 |
+
global_score["total"] += 10
|
24 |
+
state["result"] = f"You win! +$10"
|
25 |
+
state["score"] = global_score["total"]
|
26 |
+
return state
|
27 |
+
|
28 |
+
def failure_node(state):
|
29 |
+
global_score["total"] -= 5
|
30 |
+
state["result"] = f"You lose! -$5"
|
31 |
+
state["score"] = global_score["total"]
|
32 |
+
return state
|
33 |
+
|
34 |
+
def determine_outcome(state) -> Literal["node_2", "node_3"]:
|
35 |
+
roll = random.randint(1, 6) + random.randint(1, 6)
|
36 |
+
print(f"[Roll]: {roll} vs Bet: {state['bet']}")
|
37 |
+
return "node_2" if roll <= state["bet"] else "node_3"
|
38 |
+
|
39 |
+
# Build LangGraph
|
40 |
+
builder = StateGraph(State)
|
41 |
+
builder.add_node("node_1", input_node)
|
42 |
+
builder.add_node("node_2", success_node)
|
43 |
+
builder.add_node("node_3", failure_node)
|
44 |
+
|
45 |
+
builder.add_edge(START, "node_1")
|
46 |
+
builder.add_conditional_edges("node_1", determine_outcome)
|
47 |
+
builder.add_edge("node_2", END)
|
48 |
+
builder.add_edge("node_3", END)
|
49 |
+
|
50 |
+
graph = builder.compile()
|
51 |
+
|
52 |
+
# Gradio UI function
|
53 |
+
def play_game(bet: int):
|
54 |
+
if bet < 1 or bet > 12:
|
55 |
+
return "Please enter a value between 1 and 12.", global_score["total"]
|
56 |
+
result = graph.invoke({"bet": bet, "result": "", "score": global_score["total"]})
|
57 |
+
return result["result"], result["score"]
|
58 |
+
|
59 |
+
# Gradio Interface
|
60 |
+
with gr.Blocks() as demo:
|
61 |
+
gr.Markdown("## 🎲 Dice Bet Game with LangGraph")
|
62 |
+
with gr.Row():
|
63 |
+
bet_input = gr.Number(label="Your Bet (1-12)", value=7, precision=0)
|
64 |
+
result_output = gr.Textbox(label="Result")
|
65 |
+
score_output = gr.Number(label="Total Winnings", value=0, precision=0, interactive=False)
|
66 |
+
play_button = gr.Button("Roll Dice")
|
67 |
+
play_button.click(play_game, inputs=[bet_input], outputs=[result_output, score_output])
|
68 |
+
|
69 |
+
if __name__ == "__main__":
|
70 |
+
demo.launch()
|