-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstategraph_example.py
More file actions
70 lines (55 loc) · 1.73 KB
/
stategraph_example.py
File metadata and controls
70 lines (55 loc) · 1.73 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
"""
StateGraph Agent Example
Custom graph-based workflow with nodes and routing.
Use case: Multi-step analysis pipelines.
"""
from agentensemble.agents import StateGraphAgent, AgentState
def analyze_node(state: AgentState) -> dict:
"""Analyze the query and prepare context."""
return {
"context": {
**state.context,
"analyzed": True,
"query_length": len(state.query),
},
}
def process_node(state: AgentState) -> dict:
"""Process based on analysis."""
q = state.query.lower()
if "python" in q:
result = "Python is a high-level programming language."
elif "ai" in q or "agent" in q:
result = "AI agents are autonomous systems that use LLMs and tools."
else:
result = f"Processed query: {state.query[:50]}..."
return {"result": result}
def main():
nodes = {
"start": lambda s: {"context": {**s.context, "started": True}},
"analyze": analyze_node,
"process": process_node,
}
agent = StateGraphAgent(
name="analysis_agent",
nodes=nodes,
max_iterations=10,
)
# Override routing: start -> analyze -> process -> end
original_route = agent._route
def custom_route(state, current):
if state.result:
return "end"
if current == "start":
return "analyze"
if current == "analyze":
return "process"
return "end"
agent._route = custom_route
result = agent.run("What is Python?")
print("Query: What is Python?")
print(f"Result: {result['result']}")
print(f"Metadata: {result['metadata']}")
if __name__ == "__main__":
print("\n🎭 StateGraph Agent Example\n")
main()
print("\n✅ Done!")