Spaces:
Sleeping
Sleeping
File size: 10,514 Bytes
ac583f3 |
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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
import streamlit as st
from typing import TypedDict, Optional
from langgraph.graph import StateGraph, END
from together import Together
import os
import re
from langchain.agents import initialize_agent, AgentType
from tools import get_all_tools
from langchain_together import ChatTogether
# --------------------------------------------
# LangChain Tool Agent Setup (Router + Tools)
# --------------------------------------------
tools = get_all_tools()
llm = ChatTogether(
model="meta-llama/Meta-Llama-3-8B-Instruct",
together_api_key=os.environ["together_api_key"]
)
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
def decide_route_from_output(output: str) -> str:
output = output.lower()
if "explain" in output:
return "explain_code"
elif "generate" in output or "code:" in output:
return "code_generator"
elif "execution result" in output or "run this code" in output:
return "execute_code"
elif "thought" in output or "reason" in output:
return "deep_think"
else:
return "END"
def router_node(state: dict) -> dict:
user_input = state.get("input", "")
result = agent.run(user_input)
route = decide_route_from_output(result)
return {**state, "output": result, "route": route}
# Initialize Together client (for raw completions)
client = Together(api_key="d03eaa038011423d1b8828a3ff2956511b2ca34b6cc88ffcbc4ad6314db31319")
def llm_invoke(prompt: str) -> str:
try:
response = client.completions.create(
model="mistralai/Mixtral-8x7B-Instruct-v0.1",
prompt=prompt,
max_tokens=3000,
temperature=0.2,
stop=["</s>"]
)
return response.choices[0].text.strip()
except Exception as e:
st.error(f"LLM API Error: {str(e)}")
return "Error in LLM response"
# ----------------------
# State Definition
# ----------------------
class AgentState(TypedDict):
domain: str
goal: str
follow_up_questions: Optional[str]
follow_up_answers: Optional[str]
agents_needed: Optional[str]
code_generator: Optional[str]
explanation: Optional[str]
input: Optional[str]
output: Optional[str]
route: Optional[str]
# ----------------------
# Agent Functions
# ----------------------
def collect_domain_goal(state: AgentState) -> AgentState:
return state
def needs_follow_up(goal: str) -> bool:
prompt = f"""
Does this system goal require clarifying questions about input data, file structure, or formats?
Goal: {goal}
Respond only 'yes' or 'no'.
"""
response = llm_invoke(prompt).strip().lower()
return response == "yes"
def ask_follow_up_questions(state: AgentState) -> AgentState:
if needs_follow_up(state["goal"]):
prompt = f"""
Based on the domain: {state['domain']} and goal: {state['goal']},
list 2β3 critical follow-up questions about:
- Data/file formats (CSV, JSON, etc.)
- Column names or structure
- Required reference files (terms, conditions, etc.)
- Any APIs or databases used
Return in bullet-point format.
"""
state["follow_up_questions"] = llm_invoke(prompt)
else:
state["follow_up_questions"] = "No questions needed"
return state
def identify_agents(state: AgentState) -> AgentState:
prompt = f"""
Domain: {state['domain']}
Goal: {state['goal']}
Context: {state.get('follow_up_answers', 'No additional info')}
List the agents needed in an agentic system. For each:
- Name
- Purpose
- What it processes or validates
Return as a clean markdown list.
"""
state["agents_needed"] = llm_invoke(prompt)
return state
def generate_code(state: AgentState) -> AgentState:
prompt = f"""
You are an expert Python engineer. Based on:
- Domain: {state['domain']}
- Goal: {state['goal']}
- Follow-up Answers: {state.get('follow_up_answers', 'None')}
- Agents Needed: {state.get('agents_needed', 'None')}
Generate a full working LangGraph app using this structure:
1. Imports: streamlit, langgraph, together, re, os, csv if needed
2. State: TypedDict
3. One clean agent function per node
4. LangGraph construction with node/edge logic
5. Together LLM call helper
6. Streamlit UI to collect user input and run graph
7. Output final result cleanly
Match code style and flow of our health advisory example. Avoid AgentState subclasses. Ensure the system is executable.
"""
state["code_generator"] = llm_invoke(prompt)
return state
def explain_code(state: AgentState) -> AgentState:
if state.get("code_generator"):
prompt = f"Explain this code simply and clearly:\n\n{state['code_generator']}"
state["explanation"] = llm_invoke(prompt)
else:
state["explanation"] = "No code to explain"
return state
# ----------------------
# Graph Construction
# ----------------------
def create_graph():
graph = StateGraph(AgentState)
graph.add_node("collect_domain_goal", collect_domain_goal)
graph.add_node("ask_follow_up_questions", ask_follow_up_questions)
graph.add_node("identify_agents", identify_agents)
graph.add_node("generate_code", generate_code)
graph.add_node("explain_code", explain_code)
graph.set_entry_point("collect_domain_goal")
graph.add_edge("collect_domain_goal", "ask_follow_up_questions")
graph.add_edge("ask_follow_up_questions", "identify_agents")
graph.add_edge("identify_agents", "generate_code")
graph.add_edge("generate_code", "explain_code")
graph.add_edge("explain_code", END)
return graph.compile()
app = create_graph()
# ----------------------
# Streamlit Interface
# ----------------------
def main():
st.set_page_config(page_title="Agentic Code Generator", layout="centered")
st.title("π€ Auto-Build LangGraph App")
domain = st.text_input("Domain (e.g. finance, warranty claims, medical):")
goal = st.text_area("System Goal (be detailed, include what data is needed):", height=150)
if "state" not in st.session_state:
st.session_state.state = {
"domain": "",
"goal": "",
"follow_up_questions": None,
"follow_up_answers": None,
"agents_needed": None,
"code_generator": None,
"explanation": None,
"input": None,
"output": None,
"route": None
}
if "step" not in st.session_state:
st.session_state.step = "initial"
if st.button("π Generate Agentic App") and domain and goal:
st.session_state.state.update({"domain": domain, "goal": goal})
st.session_state.step = "processing"
with st.spinner("Thinking like an architect..."):
try:
result = app.invoke(st.session_state.state)
st.session_state.state.update(result)
if (st.session_state.state.get("follow_up_questions") and
st.session_state.state["follow_up_questions"] != "No questions needed"):
st.session_state.step = "follow_up"
else:
st.session_state.step = "complete"
except Exception as e:
st.error(f"Error processing request: {str(e)}")
st.session_state.step = "error"
if st.session_state.step == "follow_up":
st.subheader("π Follow-Up Questions")
st.markdown(st.session_state.state["follow_up_questions"])
answers = st.text_area("Your answers to the above:", height=150)
if st.button("Continue with those answers"):
st.session_state.state["follow_up_answers"] = answers
st.session_state.step = "processing_final"
with st.spinner("Building your LangGraph app..."):
try:
final_result = app.invoke(st.session_state.state)
st.session_state.state.update(final_result)
st.session_state.step = "complete"
except Exception as e:
st.error(f"Error in final processing: {str(e)}")
st.session_state.step = "error"
if st.session_state.step == "complete":
st.subheader("π― Identified Agents")
st.markdown(st.session_state.state["agents_needed"])
st.subheader("β
Generated Code")
st.code(st.session_state.state["code_generator"], language="python")
st.subheader("π§ Code Explanation")
st.markdown(st.session_state.state["explanation"])
st.download_button(
label="π₯ Download Generated Code",
data=st.session_state.state["code_generator"],
file_name="generated_langgraph_app.py",
mime="text/python"
)
st.subheader("π§° Use Agentic Tools")
_ = st.text_input("Optional prompt for tools:", key="tool_input")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("Explain Code"):
st.session_state.state["input"] = "Explain this code:\n" + st.session_state.state["code_generator"]
st.session_state.step = "router_tool"
with col2:
if st.button("Run Code"):
st.session_state.state["input"] = "Run this code:\n" + st.session_state.state["code_generator"]
st.session_state.step = "router_tool"
with col3:
if st.button("Deep Think"):
st.session_state.state["input"] = "Think deeply about this:\n" + st.session_state.state["goal"]
st.session_state.step = "router_tool"
if st.session_state.step == "router_tool":
with st.spinner("Running selected tool..."):
try:
result = router_node(st.session_state.state)
st.session_state.state.update(result)
st.session_state.step = "tool_complete"
except Exception as e:
st.error(f"Tool execution failed: {e}")
st.session_state.step = "error"
if st.session_state.step == "tool_complete":
st.subheader("π Tool Output")
st.markdown(st.session_state.state.get("output", "No output available."))
if st.button("π Reset"):
st.session_state.clear()
st.experimental_rerun()
if __name__ == "__main__":
main()
|