Skip to content

Commit 0b67c08

Browse files
danielmillerpclaude
andcommitted
Add LangGraph examples and CLI templates (sync + async)
- Add sync LangGraph example at examples/tutorials/00_sync/030_langgraph - Add async LangGraph example at examples/tutorials/10_async/00_base/100_langgraph - Add sync-langgraph and default-langgraph CLI templates with graph.py, tools.py, and LangGraph deps - Update init.py with new TemplateType entries and sub-menu options for LangGraph Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 66f9ee5 commit 0b67c08

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+2920
-3
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Python
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
*.so
6+
.Python
7+
build/
8+
develop-eggs/
9+
dist/
10+
downloads/
11+
eggs/
12+
.eggs/
13+
lib/
14+
lib64/
15+
parts/
16+
sdist/
17+
var/
18+
wheels/
19+
*.egg-info/
20+
.installed.cfg
21+
*.egg
22+
23+
# Environments
24+
.env**
25+
.venv
26+
env/
27+
venv/
28+
ENV/
29+
env.bak/
30+
venv.bak/
31+
32+
# IDE
33+
.idea/
34+
.vscode/
35+
*.swp
36+
*.swo
37+
38+
# Git
39+
.git
40+
.gitignore
41+
42+
# Misc
43+
.DS_Store
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# syntax=docker/dockerfile:1.3
2+
FROM python:3.12-slim
3+
COPY --from=ghcr.io/astral-sh/uv:0.6.4 /uv /uvx /bin/
4+
5+
# Install system dependencies
6+
RUN apt-get update && apt-get install -y \
7+
htop \
8+
vim \
9+
curl \
10+
tar \
11+
python3-dev \
12+
postgresql-client \
13+
build-essential \
14+
libpq-dev \
15+
gcc \
16+
cmake \
17+
netcat-openbsd \
18+
&& apt-get clean \
19+
&& rm -rf /var/lib/apt/lists/*
20+
21+
RUN uv pip install --system --upgrade pip setuptools wheel
22+
23+
ENV UV_HTTP_TIMEOUT=1000
24+
25+
# Copy pyproject.toml and README.md to install dependencies
26+
COPY 00_sync/030_langgraph/pyproject.toml /app/030_langgraph/pyproject.toml
27+
COPY 00_sync/030_langgraph/README.md /app/030_langgraph/README.md
28+
29+
WORKDIR /app/030_langgraph
30+
31+
# Copy the project code
32+
COPY 00_sync/030_langgraph/project /app/030_langgraph/project
33+
34+
# Copy the test files
35+
COPY 00_sync/030_langgraph/tests /app/030_langgraph/tests
36+
37+
# Copy shared test utilities
38+
COPY test_utils /app/test_utils
39+
40+
# Install the required Python packages with dev dependencies
41+
RUN uv pip install --system .[dev]
42+
43+
# Set environment variables
44+
ENV PYTHONPATH=/app
45+
46+
# Set test environment variables
47+
ENV AGENT_NAME=s030-langgraph
48+
49+
# Run the agent using uvicorn
50+
CMD ["uvicorn", "project.acp:acp", "--host", "0.0.0.0", "--port", "8000"]
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Tutorial 030: Sync LangGraph Agent
2+
3+
This tutorial demonstrates how to build a **synchronous** LangGraph agent on AgentEx with:
4+
- Tool calling (ReAct pattern)
5+
- Streaming token output
6+
- Multi-turn conversation memory via AgentEx checkpointer
7+
- Tracing integration
8+
9+
## Graph Structure
10+
11+
![Graph](graph.png)
12+
13+
## Key Concepts
14+
15+
### Sync ACP
16+
The sync ACP model uses HTTP request/response for communication. The `@acp.on_message_send` handler receives a message and yields streaming events back to the client.
17+
18+
### LangGraph Integration
19+
- **StateGraph**: Defines the agent's state machine with `AgentState` (message history)
20+
- **ToolNode**: Automatically executes tool calls from the LLM
21+
- **tools_condition**: Routes between tool execution and final response
22+
- **Checkpointer**: Uses AgentEx's HTTP checkpointer for cross-request memory
23+
24+
### Streaming
25+
The agent streams tokens as they're generated using `convert_langgraph_to_agentex_events()`, which converts LangGraph's stream events into AgentEx `TaskMessageUpdate` events.
26+
27+
## Files
28+
29+
| File | Description |
30+
|------|-------------|
31+
| `project/acp.py` | ACP server and message handler |
32+
| `project/graph.py` | LangGraph state graph definition |
33+
| `project/tools.py` | Tool definitions (weather example) |
34+
| `tests/test_agent.py` | Integration tests |
35+
| `manifest.yaml` | Agent configuration |
36+
37+
## Running Locally
38+
39+
```bash
40+
# From this directory
41+
agentex agents run
42+
```
43+
44+
## Running Tests
45+
46+
```bash
47+
pytest tests/test_agent.py -v
48+
```
16 KB
Loading
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
build:
2+
context:
3+
root: ../../
4+
include_paths:
5+
- 00_sync/030_langgraph
6+
- test_utils
7+
dockerfile: 00_sync/030_langgraph/Dockerfile
8+
dockerignore: 00_sync/030_langgraph/.dockerignore
9+
10+
local_development:
11+
agent:
12+
port: 8000
13+
host_address: host.docker.internal
14+
paths:
15+
acp: project/acp.py
16+
17+
agent:
18+
acp_type: sync
19+
name: s030-langgraph
20+
description: A sync LangGraph agent with tool calling and streaming
21+
22+
temporal:
23+
enabled: false
24+
25+
credentials:
26+
- env_var_name: OPENAI_API_KEY
27+
secret_name: openai-api-key
28+
secret_key: api-key
29+
- env_var_name: REDIS_URL
30+
secret_name: redis-url-secret
31+
secret_key: url
32+
- env_var_name: SGP_API_KEY
33+
secret_name: sgp-api-key
34+
secret_key: api-key
35+
- env_var_name: SGP_ACCOUNT_ID
36+
secret_name: sgp-account-id
37+
secret_key: account-id
38+
- env_var_name: SGP_CLIENT_BASE_URL
39+
secret_name: sgp-client-base-url
40+
secret_key: url
41+
42+
deployment:
43+
image:
44+
repository: ""
45+
tag: "latest"
46+
47+
global:
48+
agent:
49+
name: "s030-langgraph"
50+
description: "A sync LangGraph agent with tool calling and streaming"
51+
replicaCount: 1
52+
resources:
53+
requests:
54+
cpu: "500m"
55+
memory: "1Gi"
56+
limits:
57+
cpu: "1000m"
58+
memory: "2Gi"

examples/tutorials/00_sync/030_langgraph/project/__init__.py

Whitespace-only changes.
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""
2+
ACP (Agent Communication Protocol) handler for Agentex.
3+
4+
This is the API layer — it manages the graph lifecycle and streams
5+
tokens and tool calls from the LangGraph graph to the Agentex frontend.
6+
"""
7+
8+
from typing import AsyncGenerator
9+
10+
import agentex.lib.adk as adk
11+
from agentex.lib.adk import create_langgraph_tracing_handler, convert_langgraph_to_agentex_events
12+
from agentex.lib.core.tracing.tracing_processor_manager import add_tracing_processor_config
13+
from agentex.lib.sdk.fastacp.fastacp import FastACP
14+
from agentex.lib.types.acp import SendMessageParams
15+
from agentex.lib.types.tracing import SGPTracingProcessorConfig
16+
from agentex.lib.utils.logging import make_logger
17+
from agentex.types.task_message_content import TaskMessageContent
18+
from agentex.types.task_message_delta import TextDelta
19+
from agentex.types.task_message_update import TaskMessageUpdate
20+
from dotenv import load_dotenv
21+
22+
load_dotenv()
23+
import os
24+
25+
from project.graph import create_graph
26+
27+
logger = make_logger(__name__)
28+
29+
# Register the Agentex tracing processor so spans are shipped to the backend
30+
add_tracing_processor_config(
31+
SGPTracingProcessorConfig(
32+
sgp_api_key=os.environ.get("SGP_API_KEY", ""),
33+
sgp_account_id=os.environ.get("SGP_ACCOUNT_ID", ""),
34+
sgp_base_url=os.environ.get("SGP_CLIENT_BASE_URL", ""),
35+
))
36+
# Create ACP server
37+
acp = FastACP.create(acp_type="sync")
38+
39+
# Compiled graph (lazy-initialized on first request)
40+
_graph = None
41+
42+
43+
async def get_graph():
44+
"""Get or create the compiled graph instance."""
45+
global _graph
46+
if _graph is None:
47+
_graph = await create_graph()
48+
return _graph
49+
50+
51+
@acp.on_message_send
52+
async def handle_message_send(
53+
params: SendMessageParams,
54+
) -> TaskMessageContent | list[TaskMessageContent] | AsyncGenerator[TaskMessageUpdate, None]:
55+
"""Handle incoming messages from Agentex, streaming tokens and tool calls."""
56+
graph = await get_graph()
57+
58+
thread_id = params.task.id
59+
user_message = params.content.content
60+
61+
logger.info(f"Processing message for thread {thread_id}")
62+
63+
async with adk.tracing.span(
64+
trace_id=thread_id,
65+
name="message",
66+
input={"message": user_message},
67+
data={"__span_type__": "AGENT_WORKFLOW"},
68+
) as turn_span:
69+
callback = create_langgraph_tracing_handler(
70+
trace_id=thread_id,
71+
parent_span_id=turn_span.id if turn_span else None,
72+
)
73+
74+
stream = graph.astream(
75+
{"messages": [{"role": "user", "content": user_message}]},
76+
config={
77+
"configurable": {"thread_id": thread_id},
78+
"callbacks": [callback],
79+
},
80+
stream_mode=["messages", "updates"],
81+
)
82+
83+
final_text = ""
84+
async for event in convert_langgraph_to_agentex_events(stream):
85+
# Accumulate text deltas for span output
86+
delta = getattr(event, "delta", None)
87+
if isinstance(delta, TextDelta) and delta.text_delta:
88+
final_text += delta.text_delta
89+
yield event
90+
91+
if turn_span:
92+
turn_span.output = {"final_output": final_text}
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""
2+
LangGraph graph definition.
3+
4+
Defines the state, nodes, edges, and compiles the graph.
5+
The compiled graph is the boundary between this module and the API layer.
6+
"""
7+
8+
from datetime import datetime
9+
from typing import Annotated, Any
10+
11+
from agentex.lib.adk import create_checkpointer
12+
from langchain_core.messages import SystemMessage
13+
from langchain_openai import ChatOpenAI
14+
from langgraph.graph import START, StateGraph
15+
from langgraph.graph.message import add_messages
16+
from langgraph.prebuilt import ToolNode, tools_condition
17+
from typing_extensions import TypedDict
18+
19+
from project.tools import TOOLS
20+
21+
MODEL_NAME = "gpt-5"
22+
SYSTEM_PROMPT = """You are a helpful AI assistant with access to tools.
23+
24+
Current date and time: {timestamp}
25+
26+
Guidelines:
27+
- Be concise and helpful
28+
- Use tools when they would help answer the user's question
29+
- If you're unsure, ask clarifying questions
30+
- Always provide accurate information
31+
"""
32+
33+
34+
class AgentState(TypedDict):
35+
"""State schema for the agent graph."""
36+
messages: Annotated[list[Any], add_messages]
37+
38+
39+
async def create_graph():
40+
"""Create and compile the agent graph with checkpointer.
41+
42+
Returns:
43+
A compiled LangGraph StateGraph ready for invocation.
44+
"""
45+
llm = ChatOpenAI(
46+
model=MODEL_NAME,
47+
reasoning={"effort": "high", "summary": "auto"},
48+
)
49+
llm_with_tools = llm.bind_tools(TOOLS)
50+
51+
checkpointer = await create_checkpointer()
52+
53+
def agent_node(state: AgentState) -> dict[str, Any]:
54+
"""Process the current state and generate a response."""
55+
messages = state["messages"]
56+
if not messages or not isinstance(messages[0], SystemMessage):
57+
system_content = SYSTEM_PROMPT.format(
58+
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
59+
)
60+
messages = [SystemMessage(content=system_content)] + messages
61+
response = llm_with_tools.invoke(messages)
62+
return {"messages": [response]}
63+
64+
builder = StateGraph(AgentState)
65+
builder.add_node("agent", agent_node)
66+
builder.add_node("tools", ToolNode(tools=TOOLS))
67+
builder.add_edge(START, "agent")
68+
builder.add_conditional_edges("agent", tools_condition, "tools")
69+
builder.add_edge("tools", "agent")
70+
71+
return builder.compile(checkpointer=checkpointer)

0 commit comments

Comments
 (0)