from dataclasses import dataclassfrom langchain.tools import tool, ToolRuntime @dataclassclass Context: user_id: str@tooldef fetch_user_email_preferences(runtime: ToolRuntime[Context]) -> str: """Fetch the user's email preferences from the store.""" user_id = runtime.context.user_id preferences: str = "The user prefers you to write a brief and polite email." if runtime.store: if memory := runtime.store.get(("users",), user_id): preferences = memory.value["preferences"] return preferences
from langchain.tools import tool, ToolRuntime@tooldef context_aware_tool(runtime: ToolRuntime) -> str: """A tool that uses execution and server info.""" # Access thread and run IDs info = runtime.execution_info print(f"Thread: {info.thread_id}, Run: {info.run_id}") # Access server info (only available on LangGraph Server) server = runtime.server_info if server is not None: print(f"Assistant: {server.assistant_id}") if server.user is not None: print(f"User: {server.user.identity}") return "done"
from langchain.agents import AgentStatefrom langchain.agents.middleware import before_modelfrom langgraph.runtime import Runtime@before_modeldef auth_gate(state: AgentState, runtime: Runtime) -> dict | None: """Block unauthenticated users when running on LangGraph Server.""" server = runtime.server_info if server is not None and server.user is None: raise ValueError("Authentication required") print(f"Thread: {runtime.execution_info.thread_id}") return None