jstoppa commited on
Commit
796674b
·
verified ·
1 Parent(s): 925212b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -82
app.py CHANGED
@@ -1,85 +1,34 @@
1
- import gradio as gr
2
- from typing import Dict, TypedDict
3
  from langgraph.graph import Graph
4
- import transformers
5
- from transformers import pipeline
6
 
7
- class AgentState(TypedDict):
 
8
  messages: list[str]
9
- current_step: int
10
- final_answer: str
11
-
12
- def analyze_sentiment(state: AgentState) -> AgentState:
13
- sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
14
- message = state["messages"][-1]
15
- result = sentiment_analyzer(message)[0]
16
- state["messages"].append(f"Sentiment analysis: {result['label']} ({result['score']:.2f})")
17
- state["current_step"] += 1
18
- return state
19
-
20
- def generate_response(state: AgentState) -> AgentState:
21
- generator = pipeline("text-generation", model="gpt2")
22
- context = " ".join(state["messages"][-2:])
23
- generated_text = generator(context, max_length=50, num_return_sequences=1)[0]["generated_text"]
24
- state["messages"].append(f"Generated response: {generated_text}")
25
- state["current_step"] += 1
26
- return state
27
-
28
- def create_summary(state: AgentState) -> AgentState:
29
- if state["current_step"] >= 4:
30
- summary = "Analysis complete. Final summary: "
31
- summary += " | ".join(state["messages"])
32
- state["final_answer"] = summary
33
- return state
34
-
35
- def build_graph():
36
- workflow = Graph()
37
- workflow.add_node("sentiment", analyze_sentiment)
38
- workflow.add_node("generate", generate_response)
39
- workflow.add_node("summarize", create_summary)
40
- workflow.add_edge("sentiment", "generate")
41
- workflow.add_edge("generate", "summarize")
42
- workflow.add_edge("summarize", "sentiment")
43
- workflow.set_entry_point("sentiment")
44
- return workflow.compile()
45
-
46
- # Initialize the graph globally
47
- GRAPH = build_graph()
48
-
49
- def process_input(message: str, history: list) -> tuple:
50
- # Initialize state
51
- state = AgentState(
52
- messages=[message],
53
- current_step=0,
54
- final_answer=""
55
- )
56
-
57
- # Run the graph for a few steps
58
- for _ in range(3):
59
- state = GRAPH(state)
60
- if state["final_answer"]:
61
- break
62
-
63
- # Format the conversation history
64
- conversation = "\n".join(state["messages"])
65
-
66
- # Add final answer if available
67
- if state["final_answer"]:
68
- conversation += f"\n\nFinal Summary:\n{state['final_answer']}"
69
-
70
- return conversation
71
-
72
- # Create Gradio interface
73
- iface = gr.Interface(
74
- fn=process_input,
75
- inputs=[
76
- gr.Textbox(label="Enter your message"),
77
- gr.State([]) # For maintaining conversation history
78
- ],
79
- outputs=gr.Textbox(label="Analysis Results"),
80
- title="LangGraph Demo with Hugging Face",
81
- description="Enter a message to analyze sentiment and generate responses using LangGraph and Hugging Face models."
82
- )
83
-
84
- if __name__ == "__main__":
85
- iface.launch()
 
 
 
1
  from langgraph.graph import Graph
2
+ from typing import TypedDict
 
3
 
4
+ # Define the state type
5
+ class State(TypedDict):
6
  messages: list[str]
7
+ current_step: str
8
+
9
+ # Create nodes (functions that represent different states)
10
+ def collect_info(state: State) -> State:
11
+ return {
12
+ **state,
13
+ "messages": state["messages"] + ["Information collected"],
14
+ "current_step": "process"
15
+ }
16
+
17
+ def process_info(state: State) -> State:
18
+ return {
19
+ **state,
20
+ "messages": state["messages"] + ["Information processed"],
21
+ "current_step": "end"
22
+ }
23
+
24
+ # Create the graph
25
+ workflow = Graph()
26
+
27
+ # Add nodes and edges
28
+ workflow.add_node("collect", collect_info)
29
+ workflow.add_node("process", process_info)
30
+ workflow.add_edge("collect", "process")
31
+
32
+ # Set the entry point and compile
33
+ workflow.set_entry_point("collect")
34
+ app = workflow.compile()