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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -48
app.py CHANGED
@@ -1,100 +1,110 @@
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
8
  from langgraph.types import Command
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."
22
  " Use the provided tools to progress towards answering the question."
23
- " If you are unable to fully answer, that's OK, another assistant with different tools "
24
  " will help where you left off. Execute what you can to make progress."
25
  " If you or any of the other assistants have the final answer or deliverable,"
26
  " prefix your response with FINAL ANSWER so the team knows to stop."
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,
34
  tools=[],
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,
47
  tools=[],
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)
60
- workflow.add_edge(START, "researcher")
 
61
  workflow.add_edge("researcher", "chart_generator")
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__":
100
- interface.launch(server_name="0.0.0.0", server_port=7860)
 
1
  import gradio as gr
2
  import os
3
  import matplotlib.pyplot as plt
4
+ import pandas as pd
5
+ from langgraph.graph import StateGraph
 
6
  from langgraph.prebuilt import create_react_agent
7
  from langgraph.types import Command
8
  from langchain_core.messages import HumanMessage
9
  from langchain_anthropic import ChatAnthropic
10
 
11
+ # Set the API key from Hugging Face secrets
12
  os.environ["ANTHROPIC_API_KEY"] = os.getenv("ANTHROPIC_API_KEY")
13
 
14
+ # Claude 3.5 Sonnet
15
  llm = ChatAnthropic(model="claude-3-5-sonnet-latest")
16
 
17
+ # Create the system prompt
18
  def make_system_prompt(suffix: str) -> str:
19
  return (
20
  "You are a helpful AI assistant, collaborating with other assistants."
21
  " Use the provided tools to progress towards answering the question."
22
+ " If you are unable to fully answer, that's OKanother assistant with different tools"
23
  " will help where you left off. Execute what you can to make progress."
24
  " If you or any of the other assistants have the final answer or deliverable,"
25
  " prefix your response with FINAL ANSWER so the team knows to stop."
26
  f"\n{suffix}"
27
  )
28
 
29
+ # Workflow node: research
30
+ def research_node(state):
31
  agent = create_react_agent(
32
  llm,
33
  tools=[],
34
  state_modifier=make_system_prompt("You can only do research.")
35
  )
36
  result = agent.invoke(state)
37
+ goto = "chart_generator" if "FINAL ANSWER" not in result["messages"][-1].content else "__end__"
38
+ result["messages"][-1] = HumanMessage(
39
+ content=result["messages"][-1].content,
40
+ name="researcher"
41
+ )
42
  return Command(update={"messages": result["messages"]}, goto=goto)
43
 
44
+ # Workflow node: chart generation
45
+ def chart_node(state):
46
  agent = create_react_agent(
47
  llm,
48
  tools=[],
49
  state_modifier=make_system_prompt("You can only generate charts.")
50
  )
51
  result = agent.invoke(state)
52
+ result["messages"][-1] = HumanMessage(
53
+ content=result["messages"][-1].content,
54
+ name="chart_generator"
55
+ )
56
+ return Command(update={"messages": result["messages"]}, goto="__end__")
57
 
58
+ # LangGraph setup
59
+ workflow = StateGraph(dict)
60
  workflow.add_node("researcher", research_node)
61
  workflow.add_node("chart_generator", chart_node)
62
+ workflow.set_entry_point("researcher")
63
+ workflow.set_finish_point("__end__")
64
  workflow.add_edge("researcher", "chart_generator")
 
65
  graph = workflow.compile()
66
 
67
+ # LangGraph runner
68
+ def run_langgraph(input_text):
 
 
 
 
 
 
 
 
 
 
 
 
69
  try:
70
+ events = graph.stream({"messages": [("user", input_text)]})
71
+ output = []
72
  for event in events:
73
+ output.append(event)
74
+
75
+ final_response = output[-1]["messages"][-1].content
76
+
77
+ if "FINAL ANSWER" in final_response:
78
+ # Simulated chart creation from dummy data
79
+ years = [2020, 2021, 2022, 2023, 2024]
80
+ gdp = [21.4, 22.0, 23.1, 24.8, 26.2]
81
+
82
+ plt.figure()
83
+ plt.plot(years, gdp, marker="o")
84
+ plt.title("USA GDP Over Last 5 Years")
85
+ plt.xlabel("Year")
86
+ plt.ylabel("GDP in Trillions USD")
87
+ plt.grid(True)
88
+ plt.tight_layout()
89
+ plt.savefig("gdp_chart.png")
90
+
91
+ return "Chart generated based on FINAL ANSWER.", "gdp_chart.png"
92
+ else:
93
+ return final_response, None
94
  except Exception as e:
95
+ return f"Error: {str(e)}", None
96
+
97
+ # Gradio interface
98
+ def process_input(user_input):
99
+ return run_langgraph(user_input)
100
 
 
101
  interface = gr.Interface(
102
+ fn=process_input,
103
+ inputs=gr.Textbox(label="Enter your research task"),
104
+ outputs=[gr.Textbox(label="Output"), gr.Image(type="filepath", label="Chart")],
105
  title="LangGraph Research Automation",
106
  description="Enter a research prompt and view chart output when applicable."
107
  )
108
 
109
  if __name__ == "__main__":
110
+ interface.launch()