docs: simplify context window management documentation

Removed extensive implementation details and configuration examples from the context window management documentation. The document now focuses on core permissions and prohibitions for tool usage, providing a clearer and more concise reference for allowed and forbidden actions. This streamlines the documentation to essential guidelines only.
This commit is contained in:
YueGuobin committed 2026-03-05 14:05:58 +08:00
1 parent a8044cc1c2
commit 8dc8facb13
6 files changed
+1462 -1575

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -56,7 +56,7 @@ from gns3server.agent.gns3_copilot.agent.model_factory import (
create_title_model,
)
from gns3server.agent.gns3_copilot.agent.context_manager import (
prepare_context_messages,
create_pre_model_hook,
)
from gns3server.agent.gns3_copilot.gns3_client import GNS3TopologyTool
from gns3server.agent.gns3_copilot.prompts import TITLE_PROMPT, load_system_prompt
@@ -132,7 +132,13 @@ class MessagesState(TypedDict):
# Define llm call node
def llm_call(state: dict, config: RunnableConfig | None = None):
"""LLM decides whether to call a tool or not"""
"""
LLM decides whether to call a tool or not.
Uses pre_model_hook pattern for automatic topology injection and
message trimming, ensuring separation of concerns and complete
history preservation in state["messages"].
"""
logger.info("LLM call node invoked")
@@ -161,22 +167,14 @@ def llm_call(state: dict, config: RunnableConfig | None = None):
"topology_info": None,
}
# Get system prompt based on ENGLISH_LEVEL configuration
# load_system_prompt() will select base_prompt.py or english_level_prompt_a1-c2.py
# based on the ENGLISH_LEVEL environment variable
current_prompt = load_system_prompt()
# Get project_id from config configurable (set when starting the chat)
project_id = None
topology_info = None
if config and config.get("configurable"):
project_id = config["configurable"].get("project_id")
# Retrieve topology information if available
topology_context = None
topology_info = None
if project_id:
# Try to retrieve topology information using project_id from config
try:
topology_tool = GNS3TopologyTool()
topology = topology_tool._run(project_id=project_id)
@@ -187,8 +185,6 @@ def llm_call(state: dict, config: RunnableConfig | None = None):
"Successfully retrieved topology for project_id: %s, name: %s",
project_id, topology.get("name")
)
# Convert topology dict to string for LLM consumption
topology_context = str(topology)
else:
logger.warning(
"Failed to retrieve topology for project_id %s: %s",
@@ -197,18 +193,16 @@ def llm_call(state: dict, config: RunnableConfig | None = None):
except Exception as e:
logger.warning("Error retrieving topology for project_id %s: %s", project_id, e)
# Prepare context messages with automatic trimming based on model's context window
# This ensures we don't exceed the model's context limit
# llm_config may contain:
# - context_limit: Override built-in context window limit
# - context_strategy: Trimming strategy (conservative/balanced/aggressive)
full_messages = prepare_context_messages(
state_messages=state["messages"],
system_prompt=current_prompt,
topology_context=topology_context,
model_name=llm_config.get("model", "default"),
llm_config=llm_config,
tools=tools, # Pass tools for accurate token estimation
# Store topology_info in state for pre_model_hook to access
state["topology_info"] = topology_info
# Create pre_model_hook for automatic topology injection and trimming
system_prompt = load_system_prompt()
pre_hook = create_pre_model_hook(
system_prompt=system_prompt,
get_topology_func=lambda s: s.get("topology_info"),
get_llm_config_func=get_current_llm_config,
get_tools_func=lambda: tools, # Pass tools for token estimation
)
# Create fresh model with tools for each LLM call
@@ -219,8 +213,15 @@ def llm_call(state: dict, config: RunnableConfig | None = None):
llm_config=llm_config
)
logger.info("Invoking LLM with %d messages", len(full_messages))
response = model_with_tools.invoke(full_messages)
# Call pre_hook directly to prepare messages (topology injection + trimming)
# Note: LangGraph's pre_model_hook only works with prebuilt agents, not custom StateGraph
logger.info("Calling pre_hook to prepare %d messages", len(messages))
prepared_state = pre_hook({"messages": messages, "topology_info": topology_info})
prepared_messages = prepared_state["messages"]
logger.info("Messages prepared: %d → %d", len(messages), len(prepared_messages))
# Invoke model with prepared messages
response = model_with_tools.invoke(prepared_messages)
logger.info("LLM call completed: tool_calls=%d",
len(response.tool_calls) if hasattr(response, 'tool_calls') else 0)
@@ -0,0 +1,112 @@
# Deprecated Context Manager
This directory contains the **advanced context management implementation** that has been replaced with a simplified version.
## What's in Here
- **context_manager.py** (~650 lines)
- Accurate token counting using tiktoken
- Tool definition token estimation
- Custom message trimming with AIMessage + ToolMessage pairing
- Detailed logging and diagnostics
## Why Was It Moved?
The advanced implementation was **over-engineered** for the current use case:
| Feature | Complexity | Necessity | Current Status |
|---------|-----------|-----------|----------------|
| Template injection | Low | ✅ Essential | **Kept** (in new version) |
| Token counting (tiktoken) | High | ❓ Optional | Moved here |
| Message trimming | Medium | ❓ Optional | **Simplified** (LangChain native) |
| Tool token estimation | High | ❓ Optional | Moved here |
| AIMessage/ToolMessage pairing | High | ✅ Important | Moved here |
| 3 strategies (conservative/balanced/aggressive) | Low | ✅ Useful | **Kept** (in new version) |
## When to Use This Implementation
### Use the deprecated version if:
1. **You need accurate token counting**
- Your model has strict token limits
- You need to know exact token usage
- You're working with cost-sensitive applications
2. **You have many tools**
- Tool definitions consume significant tokens (500-1500 per tool)
- You need to account for tool tokens in context limit
3. **You need AIMessage + ToolMessage pairing**
- Your LLM requires tool calls and results to stay together
- You've encountered errors from orphaned ToolMessages
4. **You need detailed diagnostics**
- Debugging context limit issues
- Optimizing token usage
- Fine-tuning context strategy
### Use the current simplified version if:
1. ✅ You just need topology injection
2. ✅ Your model has large context (128K+ tokens)
3. ✅ Conversations are typically short (<50 turns)
4. ✅ You don't need exact token counts
## How to Restore the Advanced Version
If you find you need the advanced features:
```python
# 1. Remove current simplified version
rm gns3server/agent/gns3_copilot/agent/context_manager.py
# 2. Restore from deprecated
cp gns3server/agent/gns3_copilot/deprecated/context_manager.py \
gns3server/agent/gns3_copilot/agent/context_manager.py
```
## Key Differences
### Simplified Version (Current)
```python
# ~200 lines
- Uses LangChain's native trim_messages
- Simple token estimation (char count / 4)
- Template injection for topology
- 3 strategies: conservative/balanced/aggressive
```
### Advanced Version (Deprecated)
```python
# ~650 lines
- Custom trimming with AIMessage/ToolMessage pairing
- Accurate tiktoken-based token counting
- Tool definition token estimation
- Detailed logging with token breakdown
- Template injection for topology
- 3 strategies: conservative/balanced/aggressive
```
## Performance Comparison
| Metric | Simplified | Advanced |
|--------|-----------|----------|
| Code size | ~200 lines | ~650 lines |
| Token accuracy | ~80% (estimation) | ~95%+ (tiktoken) |
| Trimming safety | Good | Excellent |
| Execution speed | Fast | Slower (tiktoken overhead) |
| Maintenance | Low | High |
## Future Considerations
If the simplified version proves insufficient:
1. Consider adding tiktoken back (but keep architecture simple)
2. Use LangChain's more advanced trim_messages features
3. Add optional tool token estimation
4. Consider a hybrid approach: simple by default, advanced when needed
---
**Moved**: 2025-03-05
**Reason**: Simplification for current use case
**Status**: Available for future use if needed
@@ -0,0 +1,730 @@
# SPDX-License-Identifier: GPL-3.0-or-later
#
# GNS3-Copilot - AI-powered Network Lab Assistant for GNS3
#
# This file is part of GNS3-Copilot project.
#
# GNS3-Copilot is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# GNS3-Copilot is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNS3-Copilot. If not, see <https://www.gnu.org/licenses/>.
#
# Copyright (C) 2025 Guobin Yue
# Author: Guobin Yue
#
# Project Home: https://github.com/yueguobin/gns3-copilot
#
"""
Context Window Manager for GNS3-Copilot
This module provides intelligent context window management for LLM models,
including:
- Model-specific context window limits
- Accurate token counting using tiktoken
- Message trimming strategies (conservative/balanced/aggressive)
- System message preservation
- Tool definition token estimation
- Template variable injection for topology info
"""
import json
import logging
from typing import Any, Literal
from langchain_core.messages import (
AIMessage,
HumanMessage,
SystemMessage,
ToolMessage,
)
logger = logging.getLogger(__name__)
# ============================================================================
# Constants
# ============================================================================
# Context strategy ratios
CONTEXT_STRATEGY_RATIOS = {
"conservative": 0.60, # 60% for input, 40% reserved for output
"balanced": 0.75, # 75% for input, 25% reserved for output
"aggressive": 0.85, # 85% for input, 15% reserved for output
}
DEFAULT_CONTEXT_STRATEGY = "balanced"
# ============================================================================
# Token Counting - Using tiktoken for accuracy
# ============================================================================
# Global tiktoken encoding cache (lazy loading)
_tiktoken_encoding = None
def _get_tiktoken_encoding():
"""
Get tiktoken encoding instance (cached).
Uses cl100k_base encoding (GPT-4) which is a good approximation
for most modern LLMs including OpenAI, Anthropic, and DeepSeek.
Returns:
Encoding object
Raises:
ImportError: If tiktoken is not installed
"""
global _tiktoken_encoding
if _tiktoken_encoding is None:
try:
import tiktoken
_tiktoken_encoding = tiktoken.get_encoding("cl100k_base")
logger.debug("Using tiktoken (cl100k_base) for accurate token counting")
except ImportError:
raise ImportError(
"tiktoken is required for accurate token counting. "
"Please install it with: pip install tiktoken>=0.8.0"
)
return _tiktoken_encoding
def count_tokens_accurately(text: str) -> int:
"""
Count tokens in text accurately using tiktoken.
Args:
text: The text to count tokens for
Returns:
Number of tokens
Raises:
ImportError: If tiktoken is not installed
"""
if not text:
return 0
encoding = _get_tiktoken_encoding()
try:
return len(encoding.encode(text))
except Exception as e:
logger.error("tiktoken encoding failed: %s", e)
raise
def count_messages_tokens(messages: list[Any]) -> int:
"""
Count total tokens in a list of messages accurately.
Args:
messages: List of LangChain messages
Returns:
Total token count
Raises:
ImportError: If tiktoken is not installed
"""
total = 0
for msg in messages:
if hasattr(msg, 'content') and msg.content:
# Handle both string and complex content
content = str(msg.content)
total += count_tokens_accurately(content)
return total
# ============================================================================
# Tool Definition Token Estimation
# ============================================================================
def estimate_tool_tokens(tools: list[Any]) -> int:
"""
Estimate the token count of tool definitions.
When tools are bound to an LLM, their schemas (name, description, parameters)
are converted to JSON and sent to the LLM. This function estimates how many
tokens those definitions will consume.
Args:
tools: List of LangChain BaseTool instances
Returns:
Estimated token count for all tool definitions
Raises:
ImportError: If tiktoken is not installed
"""
if not tools:
return 0
total_tokens = 0
encoding = _get_tiktoken_encoding()
for tool in tools:
try:
# Build tool schema as it would be sent to LLM
tool_schema = {
"type": "function",
"function": {
"name": tool.name,
"description": tool.description if hasattr(tool, 'description') else "",
}
}
# Add parameters schema if available
if hasattr(tool, 'args_schema') and tool.args_schema:
try:
tool_schema["function"]["parameters"] = tool.args_schema.schema()
except Exception:
# If schema generation fails, use empty object
tool_schema["function"]["parameters"] = {"type": "object"}
# Count tokens in the schema
schema_str = json.dumps(tool_schema, ensure_ascii=False)
tool_tokens = len(encoding.encode(schema_str))
total_tokens += tool_tokens
logger.debug(
"Tool '%s': ~%d tokens (schema size: %d chars)",
tool.name, tool_tokens, len(schema_str)
)
except Exception as e:
logger.error("Failed to estimate tokens for tool '%s': %s", tool.name, e)
raise
logger.info("Tool definitions estimated at ~%d total tokens (%d tools)", total_tokens, len(tools))
return total_tokens
# ============================================================================
# Model Context Limits
# ============================================================================
# NOTE: Built-in model context limits have been removed.
# Model providers frequently update context limits, and maintaining this list is not sustainable.
# Users MUST configure context_limit explicitly in their LLM model configurations.
#
# For reference, common model context limits as of 2025:
# - OpenAI GPT-4o: 128K tokens
# - OpenAI GPT-4 Turbo: 128K tokens
# - OpenAI GPT-3.5 Turbo: 16K tokens
# - Anthropic Claude 3.5 Sonnet: 200K tokens
# - Google Gemini 1.5 Pro: 2.8M tokens
# - DeepSeek Chat: 128K tokens
#
# Always verify current limits from official provider documentation.
def get_model_context_limit(
model_name: str,
llm_config: dict[str, Any] | None = None
) -> int:
"""
Get the context window limit for a given model.
IMPORTANT: context_limit MUST be provided in llm_config.
Model providers frequently update context limits, so built-in defaults are NOT used.
Users must configure this value explicitly.
NOTE: context_limit unit is K tokens (1 K = 1000 tokens).
Example: 128 means 128K = 128,000 tokens.
Args:
model_name: Name of the model (e.g., "gpt-4o", "deepseek-chat")
llm_config: LLM config dict from database (must contain context_limit in K tokens)
Returns:
int: Maximum context window size in tokens (actual number, not K)
Raises:
ValueError: If context_limit is not provided or invalid
"""
# Check database config for context_limit
if llm_config and "context_limit" in llm_config:
db_limit_k = llm_config["context_limit"]
if isinstance(db_limit_k, int) and db_limit_k > 0:
# Convert K tokens to actual tokens
actual_tokens = db_limit_k * 1000
logger.debug(
"Using database config context limit: %dK tokens (%d tokens) for model '%s'",
db_limit_k, actual_tokens, model_name
)
return actual_tokens
else:
raise ValueError(
f"Invalid context_limit in database config: {db_limit_k} "
f"(type={type(db_limit_k).__name__}, expected positive integer in K tokens)"
)
# No context_limit provided - this is a configuration error
raise ValueError(
f"context_limit is required but not provided for model '{model_name}'. "
f"Please configure context_limit in your LLM model configuration (unit: K tokens). "
f"Example: 128 means 128K = 128,000 tokens. "
f"Refer to the model provider's documentation for the current context window size."
)
def calculate_max_tokens(
model_limit: int,
strategy: Literal["conservative", "balanced", "aggressive"] = DEFAULT_CONTEXT_STRATEGY
) -> int:
"""
Calculate the maximum tokens to use, reserving space for output.
Args:
model_limit: Model's context window limit
strategy: How aggressively to use the context window
- "conservative": Use 60% of limit (safer, more reserved for output)
- "balanced": Use 75% of limit (default)
- "aggressive": Use 85% of limit (maximize input, minimal output reserve)
Returns:
int: Maximum tokens for input messages
"""
ratio = CONTEXT_STRATEGY_RATIOS.get(strategy, CONTEXT_STRATEGY_RATIOS[DEFAULT_CONTEXT_STRATEGY])
max_tokens = int(model_limit * ratio)
logger.debug(
"Context limit: model=%d, strategy=%s, usable=%d tokens",
model_limit, strategy, max_tokens
)
return max_tokens
# ============================================================================
# Message Trimming
# ============================================================================
def trim_messages_for_context(
messages: list[Any],
model_name: str,
llm_config: dict[str, Any] | None = None,
strategy: Literal["conservative", "balanced", "aggressive"] = DEFAULT_CONTEXT_STRATEGY,
preserve_system: bool = True,
tool_tokens: int = 0,
) -> list[Any]:
"""
Trim messages to fit within model's context window.
This function uses tiktoken for accurate token counting and intelligently
reduces message history while preserving conversation flow.
IMPORTANT: Tool definitions are sent separately by LangChain and count towards
the context limit. This function accounts for tool tokens when making
trimming decisions.
Args:
messages: List of LangChain messages (HumanMessage, AIMessage, etc.)
model_name: Name of the LLM model being used
llm_config: Optional LLM config dict from database (may contain context_limit)
strategy: How aggressively to use the context window
preserve_system: Whether to always preserve system messages
tool_tokens: Token count for tool definitions (these are sent separately by LangChain)
Returns:
list: Trimmed list of messages that fit within context limit
Examples:
>>> messages = [HumanMessage("Hello"), AIMessage("Hi there!")]
>>> trimmed = trim_messages_for_context(messages, "gpt-4o", tool_tokens=1000)
>>> len(trimmed) <= len(messages)
True
"""
if not messages:
return messages
# Get model's context limit (from database config)
model_limit = get_model_context_limit(model_name, llm_config)
# Calculate usable tokens (reserve space for output)
max_tokens = calculate_max_tokens(model_limit, strategy)
# Account for tool tokens - these are sent separately by LangChain
# and count towards the context limit
available_for_messages = max_tokens - tool_tokens
if available_for_messages < 0:
logger.warning(
"Tool definitions (%d tokens) exceed input budget (%d tokens). "
"Consider reducing context_limit or using fewer tools.",
tool_tokens, max_tokens
)
available_for_messages = 0
# Check if trimming is needed
current_tokens = count_messages_tokens(messages)
if current_tokens <= available_for_messages:
logger.debug(
"Messages fit in context: %d / %d tokens (available: %d, tools: %d)",
current_tokens, max_tokens, available_for_messages, tool_tokens
)
return messages
logger.info(
"Trimming messages: %d → %d tokens (budget: %d, tools: %d)",
current_tokens, available_for_messages, max_tokens, tool_tokens
)
# Manually separate and trim to ensure system messages are preserved
# This is more reliable than using trim_messages with include_system
system_msgs = [m for m in messages if isinstance(m, SystemMessage)]
other_msgs = [m for m in messages if not isinstance(m, SystemMessage)]
# Calculate tokens for system messages (these will always be preserved)
system_tokens = count_messages_tokens(system_msgs)
# Calculate available tokens for non-system messages (after tools and system)
available_for_other = available_for_messages - system_tokens
if available_for_other <= 0:
# Not enough space for system messages - keep only system messages
logger.warning(
"System messages (%d tokens) exceed available space (%d tokens), truncating to system only",
system_tokens, available_for_messages
)
return system_msgs[:1] if system_msgs else messages[-1:]
# Trim non-system messages to fit available space
trimmed_other = _trim_to_token_limit(other_msgs, available_for_other)
# Combine system messages with trimmed conversation
trimmed = system_msgs + trimmed_other
logger.info(
"Trimmed %d → %d messages (system: %d, history: %d → %d)",
len(messages), len(trimmed),
len(system_msgs), len(other_msgs), len(trimmed_other)
)
return trimmed
def _trim_to_token_limit(messages: list[Any], max_tokens: int) -> list[Any]:
"""
Trim messages to fit within token limit using tiktoken.
Intelligently removes oldest message groups while preserving:
- AIMessage + ToolMessage pairs (must stay together)
- Conversation coherence
Always keeps at least the most recent message.
Args:
messages: List of messages to trim
max_tokens: Maximum tokens allowed
Returns:
Trimmed list of messages
"""
if not messages:
return messages
current_tokens = count_messages_tokens(messages)
if current_tokens <= max_tokens:
return messages
# Build message groups to preserve AIMessage + ToolMessage pairs
groups = _build_message_groups(messages)
# Remove oldest groups until under token limit
trimmed_groups = list(groups)
while trimmed_groups and _count_groups_tokens(trimmed_groups) > max_tokens:
# Always remove from beginning (oldest)
trimmed_groups.pop(0)
# Flatten groups back to message list
trimmed = []
for group in trimmed_groups:
trimmed.extend(group)
# Ensure at least one message remains
if not trimmed and messages:
# Return only the last message if nothing else fits
trimmed = [messages[-1]]
logger.debug(
"Trimmed messages: removed %d groups, %d messages remain, %d → %d tokens",
len(groups) - len(trimmed_groups),
len(trimmed),
current_tokens,
_count_groups_tokens(trimmed_groups)
)
return trimmed
def _build_message_groups(messages: list[Any]) -> list[list[Any]]:
"""
Build message groups where AIMessage + ToolMessage pairs stay together.
Each group is either:
- A standalone message (HumanMessage, SystemMessage)
- An AIMessage with its following ToolMessages (must stay together)
Args:
messages: List of messages
Returns:
List of message groups
"""
groups = []
i = 0
while i < len(messages):
msg = messages[i]
# If AIMessage with tool_calls, group it with all following ToolMessages
if isinstance(msg, AIMessage) and hasattr(msg, 'tool_calls') and msg.tool_calls:
group = [msg]
i += 1
# Collect all following ToolMessages that match these tool_calls
tool_call_ids = {tc['id'] for tc in msg.tool_calls}
while i < len(messages):
next_msg = messages[i]
if isinstance(next_msg, ToolMessage):
# Check if this ToolMessage belongs to current AIMessage
if hasattr(next_msg, 'tool_call_id') and next_msg.tool_call_id in tool_call_ids:
group.append(next_msg)
i += 1
else:
# ToolMessage belongs to a different AIMessage, stop
break
else:
# Not a ToolMessage, stop grouping
break
groups.append(group)
else:
# Standalone message (no tool_calls)
groups.append([msg])
i += 1
return groups
def _count_groups_tokens(groups: list[list[Any]]) -> int:
"""Count total tokens in all groups."""
total = 0
for group in groups:
for msg in group:
if hasattr(msg, 'content') and msg.content:
total += count_tokens_accurately(str(msg.content))
return total
# ============================================================================
# Token Usage Summary
# ============================================================================
def get_token_usage_summary(
messages: list[Any],
model_name: str,
llm_config: dict[str, Any] | None = None,
tool_tokens: int = 0,
) -> dict[str, Any]:
"""
Get a summary of token usage for the given messages.
Args:
messages: List of LangChain messages
model_name: Name of the LLM model
llm_config: Optional LLM config dict from database (may contain context_limit in K tokens)
tool_tokens: Optional token count for tool definitions
Returns:
dict: Token usage summary including:
- estimated_tokens: Estimated total tokens (messages only)
- tool_tokens: Token count for tool definitions
- total_tokens: Sum of messages and tools
- model_limit_k: Model's context window limit in K tokens
- model_limit_tokens: Model's context window limit in actual tokens
- usage_percentage: Percentage of context used (excluding tools)
- total_usage_percentage: Percentage including tools
- message_count: Number of messages
- needs_trimming: Whether messages exceed 80% of limit
"""
try:
estimated_tokens = count_messages_tokens(messages)
except Exception as e:
logger.warning("Failed to count tokens: %s", e)
estimated_tokens = 0
model_limit_tokens = get_model_context_limit(model_name, llm_config)
model_limit_k = model_limit_tokens // 1000
usage_percentage = (estimated_tokens / model_limit_tokens * 100) if model_limit_tokens > 0 else 0
total_tokens = estimated_tokens + tool_tokens
total_usage_percentage = (total_tokens / model_limit_tokens * 100) if model_limit_tokens > 0 else 0
return {
"estimated_tokens": estimated_tokens,
"tool_tokens": tool_tokens,
"total_tokens": total_tokens,
"model_limit_k": model_limit_k,
"model_limit_tokens": model_limit_tokens,
"usage_percentage": round(usage_percentage, 2),
"total_usage_percentage": round(total_usage_percentage, 2),
"message_count": len(messages),
"needs_trimming": usage_percentage > 80,
}
# ============================================================================
# Main Entry Point - Context Preparation with Template Injection
# ============================================================================
def prepare_context_messages(
state_messages: list[Any],
system_prompt: str,
topology_context: str | None,
model_name: str,
llm_config: dict[str, Any] | None = None,
tools: list[Any] | None = None,
) -> list[Any]:
"""
Prepare full context messages for LLM call with automatic trimming.
This is the main entry point for GNS3-Copilot to prepare messages
before calling the LLM. It injects topology info into the system prompt
using template variables and performs intelligent message trimming.
Template Variable Injection:
The system_prompt must contain the {{topology_info}} placeholder.
This function will replace it with actual topology information or
a placeholder message if topology is not available.
Args:
state_messages: Message history from conversation state
system_prompt: System prompt text (must contain {{topology_info}} placeholder)
topology_context: Optional topology information string
model_name: Name of the LLM model
llm_config: Optional LLM config dict from database (may contain context_limit and context_strategy)
tools: Optional list of LangChain tools (for token estimation)
Returns:
list: Prepared messages ready for LLM invocation
Examples:
>>> messages = prepare_context_messages(
... state_messages=[HumanMessage("Help me")],
... system_prompt="You are a helpful assistant\\n\\n{{topology_info}}",
... topology_context=None,
... model_name="gpt-4o"
... )
>>> len(messages)
2 # System message + Human message
"""
# Step 1: Get trimming strategy from config
trim_strategy = DEFAULT_CONTEXT_STRATEGY
if llm_config and "context_strategy" in llm_config:
strategy = llm_config["context_strategy"]
if strategy in CONTEXT_STRATEGY_RATIOS:
trim_strategy = strategy
logger.debug("Using context_strategy from config: %s", trim_strategy)
else:
logger.warning("Invalid context_strategy '%s', using '%s'", strategy, DEFAULT_CONTEXT_STRATEGY)
# Step 2: Estimate tool tokens (tools are sent with each LLM call)
tool_tokens = estimate_tool_tokens(tools) if tools else 0
# Step 3: Inject topology info into system prompt using template variable
# The system_prompt contains {{topology_info}} placeholder
if topology_context:
topology_formatted = f"Current Topology:\n{topology_context}"
formatted_prompt = system_prompt.replace("{{topology_info}}", topology_formatted)
else:
# If no topology, use placeholder
formatted_prompt = system_prompt.replace("{{topology_info}}", "(No topology information available)")
# Step 4: Calculate token breakdown
system_prompt_tokens = count_tokens_accurately(system_prompt)
topology_tokens = count_tokens_accurately(topology_formatted) if topology_context else 0
formatted_tokens = count_tokens_accurately(formatted_prompt)
# Step 5: Build context messages (single system message with topology injected)
context_messages = [SystemMessage(content=formatted_prompt)]
# Step 6: Calculate conversation history tokens
history_tokens = count_messages_tokens(state_messages)
# Step 7: Combine with conversation history
full_messages = context_messages + state_messages
# Step 8: Trim if needed
trimmed_messages = trim_messages_for_context(
full_messages,
model_name=model_name,
llm_config=llm_config,
strategy=trim_strategy,
preserve_system=True, # Always keep system prompts
tool_tokens=tool_tokens, # Account for tool definitions
)
# Step 9: Recalculate after trimming
trimmed_history_tokens = count_messages_tokens([m for m in trimmed_messages if not isinstance(m, SystemMessage)])
# Step 10: Log summary with detailed breakdown
model_limit_k = get_model_context_limit(model_name, llm_config) // 1000
if trimmed_history_tokens < history_tokens:
# Trimming happened
logger.info(
"Context prepared (trimmed): system=%d (base=%d + topology=%d) + history=%d→%d + tools=%d = %d total / %dK limit (%.1f%%), strategy=%s",
formatted_tokens,
system_prompt_tokens,
topology_tokens,
history_tokens,
trimmed_history_tokens,
tool_tokens,
formatted_tokens + trimmed_history_tokens + tool_tokens,
model_limit_k,
((formatted_tokens + trimmed_history_tokens) / (model_limit_k * 1000)) * 100,
trim_strategy
)
else:
# No trimming
logger.info(
"Context prepared: system=%d (base=%d + topology=%d) + history=%d + tools=%d = %d total / %dK limit (%.1f%%), strategy=%s",
formatted_tokens,
system_prompt_tokens,
topology_tokens,
history_tokens,
tool_tokens,
formatted_tokens + history_tokens + tool_tokens,
model_limit_k,
(formatted_tokens / (model_limit_k * 1000)) * 100,
trim_strategy
)
return trimmed_messages
# ============================================================================
# Module Test
# ============================================================================
if __name__ == "__main__":
# Simple test
test_messages = [
HumanMessage(f"Message {i}") for i in range(100)
]
# Test with mock llm_config
mock_config = {"context_limit": 8, "context_strategy": "conservative"}
result = prepare_context_messages(
state_messages=test_messages,
system_prompt="You are GNS3 Copilot.\n\n{{topology_info}}",
topology_context='{"project_id": "test", "nodes": 5}',
model_name="gpt-4o",
llm_config=mock_config,
tools=None
)
print(f"Original: {len(test_messages)} messages")
print(f"Trimmed: {len(result)} messages")
@@ -34,416 +34,90 @@ CRITICAL: This assistant has DIAGNOSIS permissions only, NO configuration permis
"""
# System prompt for LangChain v1.0 agent
# This prompt provides guidance for network teaching and diagnostics
SYSTEM_PROMPT = """
# ========================================
# 🚫 ABSOLUTE PROHIBITIONS - PRIORITY P0
# ========================================
# ROLE & PERMISSIONS
**You DO NOT have configuration permissions, only DIAGNOSIS permissions.**
You are a **GNS3 Lab Teaching Assistant**.
**Core Principle**: Teach students HOW to solve problems, not solve problems FOR them.
**Your Permissions**:
- ✅ **ALLOWED**: Read-only diagnostics (show/display/debug commands)
- ❌ **FORBIDDEN**: Any configuration changes
---
# STRICT PROHIBITIONS
### FORBIDDEN ACTIONS (Strictly Prohibited)
1. ❌ **NEVER** call `execute_multiple_device_config_commands`
2. ❌ **NEVER** use configuration commands: interface, router, ip address, vlan, acl, route-map, etc.
3. ❌ **NEVER** say "I've configured..." / "Configuration complete..." / "Let me configure..."
4. ❌ **NEVER** modify any device settings without explicit student confirmation
2. ❌ **NEVER** say "I've configured..." / "Configuration complete"
3. ❌ **NEVER** execute configuration commands (interface, router, ip address, vlan, acl, route-map, etc.)
### MANDATORY CHECKPOINT
**Before EVERY response, ask yourself:**
> "Am I about to execute a configuration operation?"
> → If YES → 🚫 STOP IMMEDIATELY, output configuration guidance instead
> → If NO → ✅ Continue with diagnosis
### CONSEQUENCES
Violating these prohibitions will cause conversation failure and undermine the learning objective.
**Before EVERY response, ask yourself**: "Am I about to execute a configuration operation?"
→ If YES → Stop and provide guidance instead
→ If NO → Proceed with diagnosis
---
# ========================================
# YOUR IDENTITY
# ========================================
# TOOL USAGE RULES
## Who You Are
| Tool | Permission |
|------|------------|
| `execute_multiple_device_commands` | ✅ Only for show/display/debug |
| `execute_multiple_device_config_commands` | 🚫 **NEVER use** |
**Role**: GNS3 Lab Teaching Assistant
**Permissions**: Read-only diagnostics + Configuration guidance
**Goal**: Develop students' independent problem-solving skills
**Analogy to understand your role**:
- You = **Driving Instructor** (teach skills, don't grab the steering wheel)
- Student = **Student Driver** (must operate the vehicle themselves)
- You = **Fitness Coach** (demonstrate form, don't lift the weights for them)
- Student = **Trainee** (must do the exercises themselves)
- You = **Programming Mentor** (review code, don't write code for students)
- Student = **Learner** (must write their own code)
**Key Principle**: You teach HOW to solve problems, not solve problems FOR students.
**Tool Calling Rules**:
- Call only ONE tool at a time
- Wait for result before calling next tool
- If topology is already in context, DO NOT call topology reader again
---
# ========================================
# SCOPE OF RESPONSIBILITIES
# ========================================
# WORKFLOW
| You CAN Do | You CANNOT Do |
|-----------|---------------|
| View device status (show commands) | Modify device configuration |
| Analyze root causes | Directly solve problems |
| Provide configuration examples | Execute configuration commands |
| Say "You should configure X because..." | Say "I've configured X" |
| Explain why configuration is needed | Make configuration changes |
| Guide through verification steps | Skip to verification without student action |
## Step 1: Diagnose
Use read-only commands to understand the problem:
```
# Cisco
show running-config, show ip route, show ip ospf neighbor, debug ip routing
---
# ========================================
# TOOL CALL DECISION TREE
# ========================================
**Before calling ANY tool, answer these 3 questions:**
### Q1: Is this tool read-only?
├─ Yes → Continue to Q2
└─ No → 🚫 STOP! Output configuration guidance instead
### Q2: Do I have enough information?
├─ No → Call diagnostic tools to gather information
└─ Yes → 🚫 Don't call tools, provide guidance directly
### Q3: Is this a single tool call?
├─ Yes → Execute
└─ No → 🚫 Split into multiple separate calls
### Tool Permission Matrix
| Tool | Permission | Usage |
|------|------------|-------|
| `gns3_topology_reader` | ✅ Allowed | Read topology (only if NOT already in context) |
| `execute_multiple_device_commands` | ⚠️ Restricted | **ONLY for show/display/debug commands** |
| `execute_multiple_device_config_commands` | 🚫 **FORBIDDEN** | **NEVER use under any circumstances** |
---
# ========================================
# STANDARD WORKFLOW
# ========================================
## Step 1: Understand the Problem
- User description: [Extract key symptoms]
- Problem classification: Routing/Switching/Security/Configuration
- Known information: [Check topology/device status in context]
## Step 2: Diagnostic Analysis
**Use ONLY read-only commands:**
```bash
# Cisco IOS
show running-config
show ip route
show ip interface brief
show ip ospf neighbor
show ip bgp summary
debug ip routing
# Huawei VRP
display current-configuration
display ip routing-table
display ospf peer
display bgp peer
# Juniper JunOS
show configuration
show route
show ospf neighbor
show bgp summary
# Huawei
display current-configuration, display ip routing-table, display ospf peer
# Linux
ip route
ip addr
ip link
tcpdump -i eth0
ping -c 4 192.168.1.1
traceroute 192.168.1.1
ip route, ip addr, tcpdump, ping, traceroute
```
**Tool Calling Rules:**
- Call only ONE tool at a time
- Wait for tool result before calling next tool
- If topology is already in context, DO NOT call gns3_topology_reader again
- After receiving output, analyze before deciding next action
## Step 3: Output Diagnostic Results
**Use this exact structure:**
## Step 2: Output Results
```markdown
## 🔍 Problem Diagnosis
**Symptom**: [What is failing on device X]
**Root Cause Analysis**:
Using `show ...` commands, I discovered:
1. [Specific finding 1] - This causes [Consequence A]
2. [Specific finding 2] - This causes [Consequence B]
**Conclusion**: The issue is [specific root cause]
**Root Cause**: [What you found]
---
## 💡 Solution (Requires Your Configuration)
## 💡 Solution
**Configuration Goal**: [What this achieves]
**Configuration Steps**:
[Cisco commands with explanations]
[Huawei commands with explanations]
**Cisco Device Configuration Steps**:
\`\`\`
# Step 1: [Explanation]
router ospf 1
network 192.168.1.0 0.0.0.255 area 0
# Step 2: [Explanation]
interface GigabitEthernet0/0
ip ospf hello-interval 10
\`\`\`
**Huawei Device Configuration Steps**:
\`\`\`
# Step 1: [Explanation]
ospf 1
area 0
network 192.168.1.0 0.0.0.255
# Step 2: [Explanation]
interface GigabitEthernet0/0/0
ospf timer hello 10
\`\`\`
**Configuration Principles**:
- [Why configure this way]
- [What each parameter does]
---
## ✅ Verification Method
**After configuration, run these commands**:
\`\`\`
show ip ospf neighbor
\`\`\`
**Success Indicators**:
- Neighbor state shows FULL
- Peer Router ID is visible
**If still failing**:
1. Check [Item A]
2. Verify [Item B]
3. Confirm [Item C]
**Verification**: `show command` to check success
```
---
# ========================================
# EDGE CASES & SCENARIOS
# ========================================
### Scenario 1: Student Asks You to Configure Directly
**Student**: "Help me configure OSPF" or "Just configure it for me"
**Your Response**:
```
I understand you want to solve this quickly, but as a teaching assistant,
my role is to help you LEARN to configure, not configure FOR you.
Let me diagnose the issue first, then provide detailed configuration steps
and explanations. This way, you'll not only solve the current problem but
also master troubleshooting skills for future issues.
[Then proceed with diagnostic workflow]
```
### Scenario 2: Emergency/Time Pressure
**Student**: "This is urgent! Just fix it fast!"
**Your Response**:
```
I understand this is urgent. However, I cannot bypass the learning process
by directly configuring devices.
Instead, I will:
1. Quickly diagnose the critical issue
2. Provide PRIORITIZED configuration steps
3. Mark the most critical action with ⚡ URGENT
This is the fastest way to solve it while ensuring you understand the fix.
```
Then output configuration steps with priority markers:
```markdown
⚡ **URGENT - Do this first**:
[Most critical configuration]
**Then do these**:
2. [Secondary configuration]
3. [Tertiary configuration]
```
### Scenario 3: Devices Completely Down
Even in critical failure scenarios, **NEVER break the no-direct-configuration rule**.
Instead:
1. Rapidly diagnose using show commands
2. Provide **priority-sorted** configuration guidance
3. Use urgency markers (⚡ URGENT, 🔴 CRITICAL)
---
# ========================================
# OUTPUT QUALITY CHECKLIST
# ========================================
**Before sending response, verify:**
- [ ] Did I call a configuration tool? → If YES, remove and change to guidance
- [ ] Did I say "configured"/"configured it"? → If YES, change to "you need to configure"
- [ ] Did I provide configuration command examples? → MUST include
- [ ] Did I explain configuration principles? → MUST explain
- [ ] Did I provide verification method? → MUST include
- [ ] Is my tone encouraging but not doing the work? → MUST be
---
# ========================================
# TEACHING METHODOLOGY
# ========================================
## 1. The Power of "Why", Not Just "How"
Build **Diagnostic Trees**, don't just give configs:
- ✅ "Let me analyze WHY BGP neighbors aren't establishing. We need to check: AS numbers, network reachability, TCP port 179..."
- ✅ "From OSPF neighbor Down state, possible causes: Hello interval mismatch, network type incompatibility, Area ID mismatch..."
- ❌ "Run `router bgp 65001` then `neighbor 192.168.1.1 remote-as 65002`"
## 2. Mind the Gap (Vendor Specifics)
Always remind students about vendor differences:
- **Cisco IOS** vs **Cisco IOS-XR** vs **Juniper JunOS** vs **Huawei VRP**
- RFC standard protocols (OSPF, BGP, IS-IS): Generally accurate
- Vendor-proprietary protocols or latest features: Remind students to verify with official documentation
## 3. Modular Approach for Complex Topologies
For 20+ node complex networks:
- **Break down problems**: Core layer → Distribution layer → Access layer
- Systematic area checking: OSPF Area 0 → Stub Area → NSSA Area
- Modular fault isolation: Routing protocols → Policy routing → QoS
## 4. Simulation vs Reality
Remind students of GNS3 limitations:
- GNS3 cannot simulate hardware failures (transceivers, port physical faults)
- GNS3 cannot fully simulate real-world traffic load and performance issues
- Your guidance applies to **logical network problems** (routing, policies, protocols)
---
# ========================================
# TOPOLOGY CONTEXT HANDLING
# ========================================
### CURRENT TOPOLOGY
{{topology_info}}
### NOTES
- The topology above is AUTOMATICALLY retrieved for the current project
- This includes nodes, ports, and links information
- **You DO NOT need to call gns3_topology_reader when topology is already provided**
- Check context first before calling topology reader
- **IMPORTANT**: Always use the correct project_id from the topology above when calling tools
---
# ========================================
# RESPONSE LANGUAGE
# ========================================
- User writes in Chinese → Respond in Chinese
- User writes in English → Respond in English
- Keep technical terms in original English (OSPF, BGP, VLAN, CLI commands)
- Keep device command output unchanged
- Keep technical terms in English (OSPF, BGP, VLAN, CLI commands)
---
# ========================================
# EXAMPLE DIALOGUE
# ========================================
# CURRENT TOPOLOGY
**Student**: "OSPF neighbors won't come up, stuck in Down state"
{{topology_info}}
**Your Response**:
## Problem Analysis
OSPF neighbors failing to establish usually has these causes:
1. **Hello/Dead interval mismatch** - Timers must match on both sides
2. **Network type mismatch** - e.g., one side broadcast, other side p2p
3. **Area ID mismatch** - Must be in the same OSPF Area
4. **Authentication misconfiguration** - Mismatched auth keys or types
5. **Layer 2 connectivity issues** - Underlying network cannot communicate
## Diagnostic Steps
Let me help you troubleshoot systematically. First, let me check the OSPF interface configuration...
[Call `execute_multiple_device_commands` with `show ip ospf interface`]
[Wait for result]
[Call `execute_multiple_device_commands` with `show ip interface brief`]
[Wait for result]
Based on the output, I found the issue:
- Hello interval is 10 on R1 but 5 on R2 (mismatch!)
- This prevents OSPF adjacency from forming
## Solution Guidance
**You need to configure** router R2 to correct the Hello interval:
**Configuration example** (Cisco):
```
interface GigabitEthernet0/0
ip ospf hello-interval 10
```
**Huawei example**:
```
interface GigabitEthernet0/0/0
ospf timer hello 10
```
**Why this works**: OSPF requires matching Hello intervals on both sides to form adjacencies. By setting both to 10 seconds, they can now discover each other.
## Verification Method
**After configuration, run these commands to verify:**
- Cisco: `show ip ospf neighbor` - Neighbor state should reach Full
- Huawei: `display ospf peer brief` - Neighbor state should reach Full
**Success indicators**:
- Neighbor state: Full
- Peer Router ID visible
- No state changes after 30 seconds
---
# ========================================
# FINAL REMINDER
# ========================================
**Remember**: You are a coach, not a player.
**Remember**: You teach skills, don't complete tasks.
**Remember**: Diagnosis and guidance, never configuration.
Your success is measured by how well students learn, not how fast problems disappear.
**Note**: Topology is already retrieved. DO NOT call topology reader again unless needed.
"""