-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
183 lines (143 loc) · 4.04 KB
/
app.py
File metadata and controls
183 lines (143 loc) · 4.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import os
from dotenv import load_dotenv
from typing import TypedDict, List, Literal
from langchain_groq import ChatGroq
from langgraph.graph import StateGraph, END
# Load Environment
load_dotenv()
# LLM Configuration
llm = ChatGroq(
model="llama-3.3-70b-versatile",
temperature=0.3,
max_tokens=800,
timeout=60,
)
# State Definition-
class SolverState(TypedDict):
problem: str
history: List[str]
round: int
max_rounds: int
last_speaker: Literal["creative", "critic", "none"]
# System Prompts
CREATIVE_SYS = """You are the Creative Brainstormer.
Generate structured, concrete ideas.
Be concise (<= 120 words).
End with:
QUESTION_FOR_CRITIC: <one sharp question>
"""
CRITIC_SYS = """You are the Harsh Critic.
Identify flaws, risks, assumptions, and suggest improvements.
Be concise (<= 120 words).
End with:
QUESTION_FOR_CREATIVE: <one sharp question>
"""
EDITOR_SYS = """You are the Editor.
You will receive a problem and a short debate log.
Produce the final result in this structure:
1) Final Answer (concise)
2) Step-by-step execution plan
3) Key risks + mitigations
4) Open questions (max 5 bullets)
Be specific and actionable.
"""
# Helper: Safe LLM Call
def safe_llm_call(prompt: str) -> str:
try:
response = llm.invoke(prompt)
return response.content.strip()
except Exception as e:
return f"[LLM ERROR]: {str(e)}"
# Agent Nodes
def creative_node(state: SolverState) -> SolverState:
prompt = (
f"{CREATIVE_SYS}\n\n"
f"PROBLEM:\n{state['problem']}\n\n"
f"HISTORY:\n" + "\n".join(state["history"][-6:])
)
resp = safe_llm_call(prompt)
return {
**state,
"history": state["history"] + [f"CREATIVE:\n{resp}"],
"round": state["round"] + 1,
"last_speaker": "creative",
}
def critic_node(state: SolverState) -> SolverState:
prompt = (
f"{CRITIC_SYS}\n\n"
f"PROBLEM:\n{state['problem']}\n\n"
f"HISTORY:\n" + "\n".join(state["history"][-6:])
)
resp = safe_llm_call(prompt)
return {
**state,
"history": state["history"] + [f"CRITIC:\n{resp}"],
"round": state["round"] + 1,
"last_speaker": "critic",
}
def editor_node(state: SolverState) -> SolverState:
prompt = (
f"{EDITOR_SYS}\n\n"
f"PROBLEM:\n{state['problem']}\n\n"
f"DEBATE LOG:\n" + "\n".join(state["history"])
)
resp = safe_llm_call(prompt)
return {
**state,
"history": state["history"] + [f"EDITOR_FINAL:\n{resp}"],
}
# Routing Logic
def route_next(state: SolverState):
if state["round"] >= state["max_rounds"]:
return "editor"
if state["last_speaker"] in ("none", "critic"):
return "creative"
return "critic"
# Build Graph
graph = StateGraph(SolverState)
graph.add_node("creative", creative_node)
graph.add_node("critic", critic_node)
graph.add_node("editor", editor_node)
graph.set_entry_point("creative")
graph.add_conditional_edges(
"creative",
route_next,
{
"creative": "creative",
"critic": "critic",
"editor": "editor",
},
)
graph.add_conditional_edges(
"critic",
route_next,
{
"creative": "creative",
"critic": "critic",
"editor": "editor",
},
)
graph.add_edge("editor", END)
app = graph.compile()
# Main Runner
if __name__ == "__main__":
problem = input("\nPaste your complex problem:\n> ").strip()
initial_state: SolverState = {
"problem": problem,
"history": [],
"round": 0,
"max_rounds": 6, # 3 full rounds (Creative + Critic)
"last_speaker": "none",
}
result = app.invoke(initial_state)
print("\n\n================= FULL RUN LOG =================\n")
for msg in result["history"]:
print(msg)
print("\n" + "-" * 70 + "\n")
print("\n================= FINAL ANSWER =================\n")
final = next(
(x for x in result["history"] if x.startswith("EDITOR_FINAL")),
"No final output generated."
)
print(final)
print("\n✅ Done.\n")