SyedHasanCronosPMC commited on
Commit
d1d9178
·
verified ·
1 Parent(s): af45274

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -32
app.py CHANGED
@@ -1,5 +1,7 @@
1
  import gradio as gr
2
  import os
 
 
3
  from langgraph.graph import StateGraph, START, END
4
  from langgraph.graph.message import MessagesState
5
  from langgraph.prebuilt import create_react_agent
@@ -7,13 +9,13 @@ from langgraph.types import Command
7
  from langchain_core.messages import HumanMessage
8
  from langchain_anthropic import ChatAnthropic
9
 
10
- # Set Anthropic API key from Hugging Face secret environment
11
  os.environ["ANTHROPIC_API_KEY"] = os.getenv("ANTHROPIC_API_KEY")
12
 
13
- # Initialize Claude 3.5 Sonnet LLM
14
  llm = ChatAnthropic(model="claude-3-5-sonnet-latest")
15
 
16
- # System prompt template function
17
  def make_system_prompt(suffix: str) -> str:
18
  return (
19
  "You are a helpful AI assistant, collaborating with other assistants."
@@ -25,7 +27,7 @@ def make_system_prompt(suffix: str) -> str:
25
  f"\n{suffix}"
26
  )
27
 
28
- # Research agent logic
29
  def research_node(state: MessagesState) -> Command[str]:
30
  agent = create_react_agent(
31
  llm,
@@ -33,13 +35,12 @@ def research_node(state: MessagesState) -> Command[str]:
33
  state_modifier=make_system_prompt("You can only do research.")
34
  )
35
  result = agent.invoke(state)
36
- goto = END if "FINAL ANSWER" in result["messages"][-1].content else "chart_generator"
37
- result["messages"][-1] = HumanMessage(
38
- content=result["messages"][-1].content, name="researcher"
39
- )
40
  return Command(update={"messages": result["messages"]}, goto=goto)
41
 
42
- # Chart generator logic
43
  def chart_node(state: MessagesState) -> Command[str]:
44
  agent = create_react_agent(
45
  llm,
@@ -47,13 +48,12 @@ def chart_node(state: MessagesState) -> Command[str]:
47
  state_modifier=make_system_prompt("You can only generate charts.")
48
  )
49
  result = agent.invoke(state)
50
- goto = END if "FINAL ANSWER" in result["messages"][-1].content else "researcher"
51
- result["messages"][-1] = HumanMessage(
52
- content=result["messages"][-1].content, name="chart_generator"
53
- )
54
  return Command(update={"messages": result["messages"]}, goto=goto)
55
 
56
- # Build the LangGraph workflow
57
  workflow = StateGraph(MessagesState)
58
  workflow.add_node("researcher", research_node)
59
  workflow.add_node("chart_generator", chart_node)
@@ -62,28 +62,38 @@ workflow.add_edge("researcher", "chart_generator")
62
  workflow.add_edge("chart_generator", END)
63
  graph = workflow.compile()
64
 
65
- # Function to execute LangGraph flow
66
- def run_langgraph(user_input):
67
- events = graph.stream(
68
- {"messages": [("user", user_input)]},
69
- {"recursion_limit": 150}
70
- )
71
- output = []
72
- for event in events:
73
- output.append(event)
74
- return output[-1]["messages"][-1].content if output else "No output generated"
 
75
 
76
- # Gradio interface logic
77
- def process_input(user_input):
78
- return run_langgraph(user_input)
 
 
 
 
 
 
 
 
 
79
 
80
- # Launch Gradio app
81
  interface = gr.Interface(
82
- fn=process_input,
83
- inputs="text",
84
- outputs="text",
85
  title="LangGraph Research Automation",
86
- description="Enter your research task (e.g., 'Get GDP data for the USA over the past 5 years and create a chart.')"
87
  )
88
 
89
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import os
3
+ import matplotlib.pyplot as plt
4
+ from io import BytesIO
5
  from langgraph.graph import StateGraph, START, END
6
  from langgraph.graph.message import MessagesState
7
  from langgraph.prebuilt import create_react_agent
 
9
  from langchain_core.messages import HumanMessage
10
  from langchain_anthropic import ChatAnthropic
11
 
12
+ # Set API Key
13
  os.environ["ANTHROPIC_API_KEY"] = os.getenv("ANTHROPIC_API_KEY")
14
 
15
+ # Claude LLM
16
  llm = ChatAnthropic(model="claude-3-5-sonnet-latest")
17
 
18
+ # System prompt generator
19
  def make_system_prompt(suffix: str) -> str:
20
  return (
21
  "You are a helpful AI assistant, collaborating with other assistants."
 
27
  f"\n{suffix}"
28
  )
29
 
30
+ # Agent 1: Researcher
31
  def research_node(state: MessagesState) -> Command[str]:
32
  agent = create_react_agent(
33
  llm,
 
35
  state_modifier=make_system_prompt("You can only do research.")
36
  )
37
  result = agent.invoke(state)
38
+ content = result["messages"][-1].content
39
+ result["messages"][-1] = HumanMessage(content=content, name="researcher")
40
+ goto = END if "FINAL ANSWER" in content else "chart_generator"
 
41
  return Command(update={"messages": result["messages"]}, goto=goto)
42
 
43
+ # Agent 2: Chart generator
44
  def chart_node(state: MessagesState) -> Command[str]:
45
  agent = create_react_agent(
46
  llm,
 
48
  state_modifier=make_system_prompt("You can only generate charts.")
49
  )
50
  result = agent.invoke(state)
51
+ content = result["messages"][-1].content
52
+ result["messages"][-1] = HumanMessage(content=content, name="chart_generator")
53
+ goto = END if "FINAL ANSWER" in content else "researcher"
 
54
  return Command(update={"messages": result["messages"]}, goto=goto)
55
 
56
+ # LangGraph flow setup
57
  workflow = StateGraph(MessagesState)
58
  workflow.add_node("researcher", research_node)
59
  workflow.add_node("chart_generator", chart_node)
 
62
  workflow.add_edge("chart_generator", END)
63
  graph = workflow.compile()
64
 
65
+ # Helper: simulate chart from output
66
+ def generate_dummy_chart() -> BytesIO:
67
+ fig, ax = plt.subplots()
68
+ ax.plot([2019, 2020, 2021, 2022, 2023], [21.4, 20.9, 22.7, 25.5, 27.6])
69
+ ax.set_title("Simulated GDP Growth")
70
+ ax.set_xlabel("Year")
71
+ ax.set_ylabel("Trillions USD")
72
+ buf = BytesIO()
73
+ plt.savefig(buf, format='png')
74
+ buf.seek(0)
75
+ return buf
76
 
77
+ # Run LangGraph
78
+ def run_langgraph(user_input):
79
+ try:
80
+ events = graph.stream({"messages": [("user", user_input)]}, {"recursion_limit": 150})
81
+ final_output = ""
82
+ for event in events:
83
+ final_output = event["messages"][-1].content
84
+ if "chart" in user_input.lower():
85
+ return generate_dummy_chart()
86
+ return final_output or "No output generated"
87
+ except Exception as e:
88
+ return f"Error: {str(e)}"
89
 
90
+ # Gradio UI
91
  interface = gr.Interface(
92
+ fn=run_langgraph,
93
+ inputs=gr.Textbox(label="user_input", placeholder="e.g. Get GDP data for the USA over the past 5 years and create a chart."),
94
+ outputs=gr.Image(type="pil", label="output"),
95
  title="LangGraph Research Automation",
96
+ description="Enter a research prompt and view chart output when applicable."
97
  )
98
 
99
  if __name__ == "__main__":