Convert LangGraph agents to Agent Spec#
This usage example showcases how a LangGraph Agent can be converted into an Agent Spec configuration in JSON format.
# Create a LangGraph Agent
from typing_extensions import Any, TypedDict
from langchain_openai.chat_models import ChatOpenAI
from langgraph.graph import END, START, StateGraph
from pydantic import SecretStr
class InputSchema(TypedDict):
city: str
class OutputSchema(TypedDict):
response: Any
class InternalState(TypedDict):
weather_data: str
def get_weather(state: InputSchema) -> InternalState:
"""Returns the weather in a specific city.
Args
----
city: The city to check the weather for
Returns
-------
weather: The weather in that city
"""
return {"weather_data": f"The weather in {state['city']} is sunny."}
def llm_node(state: InternalState) -> OutputSchema:
model = ChatOpenAI(
base_url="your.url.to.llm/v1",
model="/storage/models/Llama-3.1-70B-Instruct",
api_key=SecretStr("t"),
)
result = model.invoke(
f"Reformulate the following sentence to the user: {state['weather_data']}"
)
return {"response": result.content}
graph = StateGraph(InternalState, input_schema=InputSchema, output_schema=OutputSchema)
graph.add_node("get_weather", get_weather)
graph.add_node("llm_node", llm_node)
graph.add_edge(START, "get_weather")
graph.add_edge("get_weather", "llm_node")
graph.add_edge("llm_node", END)
assistant_name = "Weather Flow"
langgraph_agent = graph.compile(name=assistant_name)
# Convert to Agent Spec
from pyagentspec.adapters.langgraph import AgentSpecExporter
agentspec_config = AgentSpecExporter().to_json(langgraph_agent)