### LangGraph Studio Development Configuration (Bash) Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt This Bash script outlines the steps for setting up and running the LangGraph Studio development server. It includes installing dependencies, configuring environment variables by copying and editing a `.env.example` file, and starting the development server. It also shows the `langgraph.json` configuration file structure. ```bash # Install dependencies uv sync # Configure environment cp .env.example .env # Edit .env with your API keys # Start LangGraph Studio development server uv run langgraph dev --host=localhost --allow-blocking # langgraph.json configuration: # { # "dependencies": ["."], # "graphs": { # "travel": "./src/agent/graph.py:build_graph_with_langgraph_studio" # } # } # Access Studio UI: # http://localhost:8123 # # Features available in Studio: # - Visual graph execution flow # - Step-by-step state inspection # - Message history visualization # - Interactive testing with custom inputs # - Performance metrics (tokens, latency) # - Real-time debugging of agent decisions ``` -------------------------------- ### End-to-End Travel Planning Workflow Example Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Demonstrates a complete travel planning workflow using LangGraph's RuntimeClient. This example initializes a pre-built graph and processes a user's request for a 3-day Tokyo trip. It showcases how to structure the initial user input, which includes the user's message content. ```python from langgraph.runtime import RuntimeClient import asyncio # Initialize graph graph = build_graph_with_langgraph_studio() # User request user_input = { "messages": [{ "role": "user", "content": "Plan a 3-day trip to Tokyo for first-time visitors. Include attractions, food recommendations, and estimated daily budget." }] } # To run the graph (example): # async def main(): # result = await graph.invoke(user_input) # print(result) # if __name__ == "__main__": # asyncio.run(main()) ``` -------------------------------- ### Configure Environment Variables for API Keys Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Sets up environment variables for API keys and base URLs required by various AI providers. This includes services like DashScope, DeepSeek, Zai, Moonshot, and Tavily. The example demonstrates loading these variables from a `.env` file and then using them to initialize chat models, ensuring secure and flexible API key management. ```python # .env file configuration # DASHSCOPE_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 # DASHSCOPE_API_KEY=sk-xxx # DEEPSEEK_API_KEY=sk-xxx # ZAI_API_KEY=xxx.xxx # MOONSHOT_API_KEY=sk-xxx # TAVILY_API_KEY=tvly-xxx # SILICONFLOW_API_BASE=https://api.siliconflow.cn # SILICONFLOW_API_KEY=sk-xxx # Load in application: from dotenv import load_dotenv load_dotenv(dotenv_path=".env", override=True) # Example: Using environment variables for model initialization import os from langchain_dev_utils import load_chat_model # Automatically uses API keys from environment model = load_chat_model(model="moonshot:kimi-k2-0905-preview") # Internally resolves to: # - base_url: https://api.moonshot.cn/v1 (from registration) # - api_key: os.getenv("MOONSHOT_API_KEY") # - model_name: kimi-k2-0905-preview # Cost-effective model selection strategy: context = Context( plan_model="moonshot:kimi-k2-0905-preview", # Best reasoning for planning sub_model="deepseek:deepseek-chat", # Cost-effective for execution summary_model="dashscope:qwen-flash" # Fast and cheap for summaries ) ``` -------------------------------- ### Register AI Model Providers Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Automatically registers AI model providers upon import. This setup is crucial for enabling the assistant to interact with different chat models like Qwen, SiliconFlow, and OpenAI-compatible services from Zai and Moonshot. It takes a list of provider configurations, specifying the provider name, chat model, and optionally base URLs. ```python from langchain_dev_utils import batch_register_model_provider batch_register_model_provider([ {"provider": "dashscope", "chat_model": ChatQwen}, {"provider": "siliconflow", "chat_model": ChatSiliconFlow}, {"provider": "zai", "chat_model": "openai-compatible", "base_url": "https://open.bigmodel.cn/api/paas/v4"}, {"provider": "moonshot", "chat_model": "openai-compatible", "base_url": "https://api.moonshot.cn/v1"} ]) ``` -------------------------------- ### Define Multi-Agent State with Context Isolation in Python Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Defines the core state structures for the multi-agent system using LangGraph's MessagesState and custom mixins. Implements context isolation between main and sub-agents through separate message tracking fields. Includes an example state instance showing plan, note, and message collections during travel planning execution. ```python from typing import Annotated from langchain_core.messages import AnyMessage from langgraph.graph.message import MessagesState, add_messages from langchain_dev_utils import PlanStateMixin, NoteStateMixin # Main agent state with plan tracking and note storage class State(MessagesState, PlanStateMixin, NoteStateMixin, total=False): task_messages: Annotated[list[AnyMessage], add_messages] # Sub-agent state with isolated temporary context class SubAgentState(State): temp_task_messages: Annotated[list[AnyMessage], add_messages] # Example state structure during execution: state_example = { "messages": [ HumanMessage(content="Plan a 3-day trip to Tokyo"), AIMessage(content="I'll create a plan...", tool_calls=[...]) ], "plan": [ {"content": "Research Tokyo attractions", "status": "done"}, {"content": "Design 3-day itinerary", "status": "in_progress"}, {"content": "Estimate travel budget", "status": "pending"} ], "note": { "Research Tokyo attractions": "Top attractions: Senso-ji Temple...", "Design 3-day itinerary": "Day 1: Asakusa and Ueno..." }, "task_messages": [...], # Historical sub-agent execution logs "temp_task_messages": [...] # Current sub-agent isolated context } ``` -------------------------------- ### LangGraph Studio Production Deployment (Bash) Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt This Bash command demonstrates how to deploy the LangGraph assistant to production using the LangGraph CLI. The `langgraph deploy` command pushes the application to LangGraph Cloud, enabling features like auto-scaling, state persistence, API endpoint generation, and a monitoring dashboard. ```bash # Production deployment: langgraph deploy --name travel-planner-prod # Deploys to LangGraph Cloud with: # - Auto-scaling # - State persistence # - API endpoint generation # - Monitoring dashboard ``` -------------------------------- ### Note Management Tools in Python Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt This system abstracts a file system for inter-agent communication via notes, using LangChain utilities for writing, querying, and listing. Depends on langchain_dev_utils. Inputs are content or filenames; outputs are saved notes or retrieved data. Limitations include reliance on isolated message keys for context. ```python from langchain_dev_utils import ( create_write_note_tool, create_query_note_tool, create_ls_tool ) # Write note tool - saves task results write_note = create_write_note_tool( name="write_note", description="Save task results to note storage", message_key="temp_task_messages" # Uses isolated sub-agent context ) # Query note tool - retrieve previous results query_note = create_query_note_tool( name="query_note", description="Query previously saved note by filename" ) # List available notes ls = create_ls_tool( name="ls", description="List all saved note filenames" ) # Example workflow with dependency: # Task 1: "Research Tokyo attractions" write_note.invoke({"content": "Top 10 Tokyo attractions: 1. Senso-ji Temple..."}) # Saved to: note["Research Tokyo attractions"] = "Top 10 Tokyo attractions..." # Task 2: "Design 3-day itinerary" (depends on Task 1) available_notes = ls.invoke({}) # Returns: ["Research Tokyo attractions"] attractions = query_note.invoke({"file_name": "Research Tokyo attractions"}) # Returns: "Top 10 Tokyo attractions: 1. Senso-ji Temple..." ``` -------------------------------- ### Plan Management Tools in Python Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt These tools provide token-efficient initialization and updates for task plans in a travel planner, using LangChain dev utilities. Dependencies include langchain_dev_utils for creating tools. Inputs are plan lists or update dicts; outputs update plan states. Limitations involve validation requirements for incremental updates to ensure state accuracy. ```python from langchain_dev_utils import create_write_plan_tool, create_update_plan_tool # Initialize plan (used once at start) write_plan = create_write_plan_tool( name="write_plan", description="Initialize task plan with list of todo items" ) # Usage example: response = write_plan.invoke({ "plan": [ "Research Tokyo attractions", "Design 3-day itinerary", "Estimate travel budget", "Recommend accommodations", "Suggest local cuisine" ] }) # Result: Creates plan with first item set to "in_progress" # Update plan status incrementally (key optimization) update_plan = create_update_plan_tool( name="update_plan", description="Update plan status incrementally - only changed items" ) # Token-efficient usage (50% reduction vs sending full plan): update_plan.invoke({ "update_plans": [ {"content": "Research Tokyo attractions", "status": "done"}, {"content": "Design 3-day itinerary", "status": "in_progress"} ] }) # Only sends 2 items instead of all 5 → significant token savings # Validation ensures both "done" and "in_progress" items are present # This prevents ambiguous state transitions ``` -------------------------------- ### Web Search and Weather Tool Integration (Python) Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Provides asynchronous web‑search and synchronous weather‑query tools for the agent. The search tool limits calls to one per task to control costs, while the weather tool is a placeholder returning a formatted string. ```python from langchain_core.tools import tool from langchain_tavily.tavily_search import TavilySearch from typing import Annotated # Web search tool with cost control async def tavily_search(query: Annotated[str, "Search query"]): """Internet search for real-time information. Limited to ONE call per task.""" tavily = TavilySearch(max_results=5) result = await tavily.ainvoke({"query": query}) return result # Example usage in sub-agent: # search_results = await tavily_search("Tokyo top attractions 2024") @tool def get_weather(city: str): """Query weather information for a city""" return f"{city} weather: Sunny, 25°C" # Example usage: # weather = get_weather("Tokyo") ``` -------------------------------- ### Define Flexible Multi‑Provider Model Context (Python) Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Defines a dataclass that holds model identifiers and prompt templates, allowing easy swapping of providers and prompts for planning, sub‑tasks, and summarization. ```python from dataclasses import dataclass from typing import Annotated from src.agent.prompts.prompt import PLAN_MODEL_PROMPT, SUBAGENT_PROMPT, SUMMARY_PROMPT @dataclass class Context: plan_model: Annotated[str, "Main planning agent model"] = "moonshot:kimi-k2-0905-preview" sub_model: Annotated[str, "Task execution model"] = "deepseek:deepseek-chat" summary_model: Annotated[str, "Summary generation model"] = "dashscope:qwen-flash" plan_prompt: Annotated[str, "Main agent prompt"] = PLAN_MODEL_PROMPT sub_prompt: Annotated[str, "Sub-agent prompt"] = SUBAGENT_PROMPT summary_prompt: Annotated[str, "Summary prompt"] = SUMMARY_PROMPT # Example: Switch to different model configuration custom_context = Context( plan_model="deepseek:deepseek-chat", sub_model="dashscope:qwen-plus", summary_model="moonshot:kimi-k1" ) model_providers = { "dashscope": "qwen-flash, qwen-plus, qwen-max, qwen-turbo", "deepseek": "deepseek-chat, deepseek-reasoner", "moonshot": "kimi-k1, kimi-k2-0905-preview", "zai": "glm-4, glm-4-flash, glm-4-plus", "siliconflow": "Various open-source models" } ``` -------------------------------- ### Build Main and Sub‑Agent Graphs with LangGraph (Python) Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Creates a hierarchical LangGraph with a main agent and a sub‑agent subgraph, defining nodes, edges, and compilation steps. The graph enables tool execution, sub‑agent calls, and summary generation. ```python from dotenv import load_dotenv from langgraph.graph.state import StateGraph from src.agent.node import call_model, tool_node from src.agent.state import State, StateInput from src.agent.sub_agent.graph import build_sub_agent from src.agent.utils.context import Context load_dotenv(dotenv_path=".env", override=True) def build_graph_with_langgraph_studio(): graph = StateGraph(State, input_schema=StateInput, context_schema=Context) graph.add_node("call_model", call_model) # Decision maker graph.add_node("tools", tool_node) # Tool executor graph.add_node("subagent", build_sub_agent()) # Sub-agent subgraph graph.add_edge("__start__", "call_model") graph.add_edge("tools", "call_model") graph.add_edge("subagent", "call_model") return graph.compile() # Sub-agent graph structure: def build_sub_agent(): subgraph = StateGraph(SubAgentState) subgraph.add_node("subagent_call_model", subagent_call_model) subgraph.add_node("sub_tools", sub_tools) subgraph.add_node("write_and_summary", build_write_and_summary_node()) subgraph.add_edge("__start__", "subagent_call_model") subgraph.add_edge("sub_tools", "subagent_call_model") subgraph.add_edge("write_and_summary", "subagent_call_model") return subgraph.compile() ``` -------------------------------- ### Execute Travel Planner Graph (Python) Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt This Python script defines and executes an asynchronous graph for the travel planner assistant. It iterates through different stages of plan creation, tool execution, sub-agent delegation, and plan updates, printing each chunk of the execution. The script also highlights token efficiency compared to traditional approaches, showing a 50% cost reduction. ```python async def run_travel_planner(): async for chunk in graph.astream(user_input): # Chunk 1: Main agent creates plan # { ... } # Chunk 2: Execute write_plan tool # {"tools": {"messages": [ToolMessage(content="Plan created")]}} # Chunk 3: Delegate first task to sub-agent # { ... } # Chunk 4: Sub-agent executes web search # { ... } # Chunk 5: Sub-agent saves results # { ... } # Chunk 6: Return summary to main agent # { ... } # Chunk 7: Main agent updates plan # { ... } # ... Process continues for remaining tasks ... # Final chunk: All tasks complete # { ... } print(chunk) asyncio.run(run_travel_planner()) # Token efficiency comparison: # Traditional approach: ~50,000 tokens (full context each step) # This implementation: ~25,000 tokens (context isolation + incremental updates) # Cost savings: 50% reduction in API costs ``` -------------------------------- ### Implement Primary Agent Decision-Making and Task Delegation in Python Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Implements the main agent's decision-making logic that orchestrates travel planning tasks. Loads and configures the LLM model, binds tools for plan management, and routes execution to appropriate nodes based on tool calls. Supports delegation to sub-agents with state updates and handles workflow termination conditions. ```python from typing import Literal from langchain_core.messages import AIMessage, SystemMessage from langchain_dev_utils import load_chat_model from langgraph.types import Command from src.agent.state import State from src.agent.tools import write_plan, update_plan, transfor_task_to_subagent async def call_model(state: State) -> Command[Literal["tools", "subagent", "__end__"]]: # Load model from configuration context model = load_chat_model(model="moonshot:kimi-k2-0905-preview") # Bind tools for plan management and task delegation tools = [write_plan, update_plan, transfor_task_to_subagent, ls, query_note] bind_model = model.bind_tools(tools, parallel_tool_calls=False) # Invoke with system prompt and conversation history response = await bind_model.ainvoke([ SystemMessage(content=PLAN_MODEL_PROMPT), *state["messages"] ]) # Route based on tool calls if response.tool_calls: tool_name = response.tool_calls[0]["name"] if tool_name == "transfor_task_to_subagent": # Delegate to sub-agent with state update return Command( goto="subagent", update={ "messages": [response], "now_task_message_index": len(state.get("task_messages", [])) } ) # Execute other tools return Command(goto="tools", update={"messages": [response]}) # Conversation complete return Command(goto="__end__", update={"messages": [response]}) # Example execution flow: # User: "Plan a 3-day trip to Tokyo" # Agent: Calls write_plan(["Research attractions", "Design itinerary", ...]) # Agent: Calls transfor_task_to_subagent("Research attractions") → routes to subagent # Subagent: Executes task, returns summary # Agent: Calls update_plan([{"content": "Research attractions", "status": "done"}]) # Agent: Repeats for remaining tasks ``` -------------------------------- ### Invoke Sub‑Agent to Write Itinerary Note (Python) Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt Demonstrates how a sub‑agent writes an itinerary note using the write_note tool. The note is stored in the LangGraph state for later access. No external I/O is performed. ```python write_note.invoke({"content": "Day 1: Visit Senso-ji and Asakusa..."}) # Saved to: note["Design 3-day itinerary"] = "Day 1: Visit Senso-ji..." ``` -------------------------------- ### Subagent Task Execution in Python Source: https://context7.com/tbice123123/travel-planner-assistant/llms.txt This function handles specialized task execution for sub-agents in a travel planner, using LangChain models and tools for context-aware responses. It depends on LangChain, LangGraph, and custom utilities for model loading and tool parsing. Inputs include sub-agent state with messages and notes; outputs route to tools or end via Command. Limitations include reliance on specific model bindings and isolated message contexts. ```python from typing import Literal, cast from langchain_core.messages import AIMessage, HumanMessage, SystemMessage from langchain_dev_utils import load_chat_model, parse_tool_calling from langgraph.types import Command from src.agent.sub_agent.state import SubAgentState from src.agent.tools import get_weather, tavily_search, query_note, write_note async def subagent_call_model(state: SubAgentState) -> Command[Literal["sub_tools", "write_and_summary", "__end__"]]: # Extract task name from parent agent's delegation last_ai_message = cast(AIMessage, state["messages"][-1]) _, args = parse_tool_calling(last_ai_message, first_tool_call_only=True) task_name = cast(dict, args).get("content", "") # Load sub-agent model model = load_chat_model(model="deepseek:deepseek-chat").bind_tools([ get_weather, tavily_search, query_note, write_note ]) # Get isolated task context and available notes messages = state.get("temp_task_messages", []) notes = state.get("note", {}) user_requirement = state["messages"][0].content # Execute with task-specific prompt response = await model.ainvoke([ SystemMessage(content=SUBAGENT_PROMPT.format( task_name=task_name, history_files=list(notes.keys()) if notes else "No previous notes", user_requirement=user_requirement )), HumanMessage(content=f"My task is: {task_name}"), *messages ]) # Route based on tool calls if response.tool_calls: tool_name = response.tool_calls[0]["name"] if tool_name == "write_note": # Save results and generate summary return Command(goto="write_and_summary", update={"temp_task_messages": [response]}) else: # Execute search or query tools return Command(goto="sub_tools", update={"temp_task_messages": [response]}) # Task complete, return to main agent return Command(goto="__end__", update={"task_messages": [*messages, response]}) # Example execution: # Task: "Research Tokyo attractions" # Sub-agent: Calls tavily_search("Tokyo top attractions 2024") # Sub-agent: Receives search results # Sub-agent: Calls write_note("Top attractions include Senso-ji Temple...") # System: Saves to note["Research Tokyo attractions"] and generates summary # Sub-agent: Returns summary to main agent ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.