Passing Conversation History Between AI Coding Agents

AI coding assistants have become indispensable for developers, yet no single model dominates every use case. Claude Code excels at complex reasoning and code generation, while Gemini offers strong multimodal capabilities and fast inference. When you switch between these tools, you often face a frustrating gap: the context you built in one session does not automatically transfer to the next. This forces you to re-explain the project structure, recent changes, and pending tasks, wasting time and tokens. The free endpoint at FreeAPIGemini is not affiliated with Google, offering an alternative for those seeking open-weight flexibility without vendor lock-in.
A practical solution is to build a lightweight command-line interface (CLI) wrapper that reads your session history and injects it into the new tool. By parsing the JSONL logs generated by your current assistant, you can extract the relevant conversation turns, the current working directory, and modified files. This structured handoff ensures that your new coding agent starts with the same understanding as the previous one, maintaining continuity across different environments. This approach works regardless of whether you are using commercial APIs or open-weight models served via compatible endpoints.
This guide demonstrates how to create such a routing mechanism using Python scripts. You will learn how to parse session logs, structure the context, and pass it to various models via their respective APIs or CLI tools. Whether you are switching from Claude to Gemini or moving between different OpenAI-compatible endpoints, this approach provides a consistent way to manage context across multiple AI agents. We will also explore how to handle rate limits and optimize token usage during these transitions.
Frequently asked questions
What is context routing in AI coding?
Context routing is the process of extracting conversation history, file modifications, and task metadata from one AI coding session and injecting it as the initial prompt for another. This allows a new agent to understand the ongoing work without requiring you to re-explain the entire project context manually, preserving the flow of your development workflow.
How does Claude Code context differ from Gemini CLI context?
Claude Code typically stores sessions in JSONL format within a specific directory structure, while Gemini CLI may use different logging mechanisms or in-memory states. Context routing scripts must parse these distinct formats to extract the relevant message history and file changes before injecting them into the target agent, ensuring compatibility across different ecosystems.
Which is better for context preservation: CLI or API?
The API offers more granular control over context windows and token limits, making it better for complex routing. However, CLI wrappers are easier to set up for quick context handoffs. The best approach often combines both: using CLI for immediate context injection and API for deeper context management in long-running tasks, depending on your specific needs.
How do I handle rate limits when switching models?
Rate limits are per-model, not per-user. When you hit a limit in Claude Code, switching to Gemini or another model allows you to continue work immediately. Context routing ensures that the new model receives the necessary background information, minimizing the need for re-explanation and maximizing productivity despite the limit, as detailed in our guide on rate limits.
What is the role of JSONL in context routing?
JSONL (JSON Lines) is a common format for storing conversation logs. Each line represents a single message or event. Context routing scripts read these files to reconstruct the conversation history, extract key details like file paths and code snippets, and format them for injection into the new agent's context window, ensuring data integrity.
How does context compaction affect routing?
Context compaction reduces the size of the conversation history to fit within token limits. When routing context, you may need to apply compaction rules to ensure the injected history does not exceed the target model's context window. This often involves summarizing older messages or truncating less relevant parts of the conversation to save space.
Can I route context between different versions of the same model?
Yes, but you must account for differences in model capabilities and context window sizes. For example, routing context from an older model to a newer one may require adjusting the prompt format to leverage the newer model's improved reasoning or larger context window. Always test the handoff to ensure compatibility and optimal performance.
What are the security implications of context routing?
Context routing involves reading and writing file logs, which may contain sensitive code or credentials. Ensure that your routing script has appropriate permissions to read the session logs and that it does not inadvertently expose sensitive information to the target model. Use environment variables or secure storage for any API keys used in the routing process to maintain security.
Step by step
- Locate Session Logs — Find the JSONL session files in your Claude Code directory, typically located in ~/.claude/projects/. Identify the most recent session file to extract the conversation history for routing.
- Parse Conversation History — Write a Python script to read the JSONL file and parse each line into a message object. Extract the user prompts and assistant responses to reconstruct the conversation history accurately.
- Structure Context Payload — Combine the parsed messages with the current working directory and modified files. Format this data into a structured payload that can be injected into the target agent seamlessly.
- Inject into Target Agent — Use a CLI command or API call to pass the structured context to your target agent, such as Gemini CLI or Codex. This initializes the new session with the relevant background information, ensuring continuity.
Understanding Session Logs and Context Structures
AI coding assistants generate session logs that capture the entire interaction history. These logs are typically stored in JSONL format, with each line representing a message or event. For Claude Code, these files are located in the `~/.claude/projects/` directory. Each log file corresponds to a specific session and contains a chronological record of user prompts, model responses, and tool executions, providing a rich source of data for context routing.
To route context effectively, you must first understand the structure of these logs. A typical log entry includes the role (user or assistant), the content of the message, and metadata such as timestamps and tool calls. By parsing these entries, you can reconstruct the conversation history and extract relevant information like the current working directory, modified files, and pending tasks, which are crucial for maintaining continuity.
Parsing JSONL Session Files
JSONL files are straightforward to parse using standard libraries like Python's `json` module. You can read each line, parse it as a JSON object, and extract the relevant fields. For example, you might extract the user's last prompt and the assistant's response to understand the current state of the conversation, ensuring that the most recent context is prioritized.
Extracting Metadata and File Changes
Beyond the conversation text, session logs often contain metadata about file changes and tool executions. This information is crucial for context routing, as it provides the new agent with a snapshot of the project's current state. You can extract file paths, diff snippets, and tool output to give the new agent a comprehensive understanding of the work done so far, reducing the need for re-explanation.
import json
import os
def parse_claude_log(log_file):
messages = []
with open(log_file, 'r') as f:
for line in f:
try:
entry = json.loads(line.strip())
if 'message' in entry:
messages.append(entry['message'])
except json.JSONDecodeError:
continue
return messagesBuilding a Context Router Script
A context router script automates the process of extracting context from one session and injecting it into another. The script reads the session logs, structures the context, and formats it for the target agent. This process involves parsing the logs, extracting relevant information, and constructing a prompt that includes the conversation history and project state, ensuring a seamless transition between tools.
The script should be flexible enough to handle different log formats and target agents. For example, it might need to parse Claude Code logs for one target and Gemini CLI logs for another. By abstracting the parsing logic, you can create a reusable router that works across multiple AI coding assistants, reducing the friction of switching between different environments and models.
Structuring the Context Payload
The context payload should include the conversation history, current working directory, modified files, and any pending tasks. This information provides the new agent with a comprehensive understanding of the ongoing work. You can structure this payload as a JSON object or a formatted string, depending on the target agent's requirements, ensuring that all relevant data is passed along.
Injecting Context into the Target Agent
Once the context is structured, it needs to be injected into the target agent. This can be done by appending the context to the initial prompt or by passing it as a system message. The method of injection depends on the target agent's API or CLI interface. For example, you might use the `messages` parameter in the OpenAI API or the `--system` flag in a CLI tool, ensuring compatibility with the target.
def build_context_payload(messages, cwd, modified_files):
payload = {
'messages': messages,
'cwd': cwd,
'modified_files': modified_files,
'pending_tasks': []
}
return json.dumps(payload)
Routing Context to Different Agents
Different AI coding agents have different interfaces for receiving context. For example, Claude Code uses a CLI interface that accepts prompts via standard input or command-line arguments. Gemini CLI might use a different format, requiring a specific structure for the context payload. Understanding these differences is crucial for successful context routing, as it ensures that the target agent can correctly interpret the injected context.
You can use a library like `requests` or the `openai` SDK to interact with the APIs of various agents. For CLI tools, you can use subprocess calls to execute commands and pass the context as arguments. By abstracting the interaction logic, you can create a unified router that works across multiple agents, providing a consistent experience regardless of the underlying model or interface.
Interacting with Claude Code
Claude Code can be invoked via the command line, passing the context as part of the prompt. You can use a subprocess call to run the Claude Code command and provide the structured context as an argument. This allows you to seamlessly continue your work in Claude Code after switching from another agent, maintaining the flow of your development process.
Interacting with Gemini CLI
Gemini CLI might require a different approach to context injection. You may need to format the context as a specific JSON structure or use a system message. By testing different injection methods, you can find the most effective way to pass context to Gemini CLI and ensure that the agent understands the ongoing work, leveraging its unique capabilities.
import subprocess
def run_claude_code(context_payload):
command = ['claude', '--context', context_payload]
result = subprocess.run(command, capture_output=True, text=True)
return result.stdoutHandling Rate Limits and Quotas
Rate limits are a common challenge when using multiple AI coding assistants. Each model has its own rate limits, and hitting a limit in one agent does not necessarily mean you hit a limit in another. Context routing allows you to switch agents seamlessly when you encounter rate limits, ensuring that you can continue your work without interruption, as discussed in our article on rate limits.
To handle rate limits effectively, you should monitor your usage and switch agents when necessary. You can also use a context router to automatically switch agents when a rate limit is detected. This proactive approach minimizes downtime and maximizes productivity, allowing you to leverage the strengths of different models while avoiding the frustration of hitting quotas.
Monitoring Rate Limits
Monitoring rate limits involves tracking your API usage and checking for 429 status codes or similar indicators. You can implement a retry mechanism that automatically switches agents when a rate limit is detected. This ensures that you can continue your work without manual intervention, maintaining a smooth development workflow even under heavy load.
Switching Agents on Rate Limit
When a rate limit is detected, the context router can automatically switch to a different agent. This involves extracting the context from the current session, routing it to the new agent, and resuming the conversation. By automating this process, you can maintain continuity even when one agent becomes unavailable, ensuring that your work progresses without delay.
def check_rate_limit(response):
if response.status_code == 429:
return True
return False
def switch_agent(context_payload, target_agent):
if target_agent == 'gemini':
return run_gemini_cli(context_payload)
elif target_agent == 'claude':
return run_claude_code(context_payload)
return None
Optimizing Context for Token Limits
Context routing often involves passing large amounts of data, which can exceed token limits. To optimize context, you can compress the conversation history, truncate less relevant messages, or summarize older parts of the conversation. This ensures that the context fits within the target model's context window while retaining the most important information, as explored in our guide on context compaction.
Context compaction is a key technique for optimizing context. By summarizing older messages or removing redundant information, you can reduce the token count while preserving the essential context. This allows you to pass more relevant information to the target agent, improving its ability to understand and continue the work without wasting tokens on unnecessary details.
Summarizing Conversation History
Summarizing conversation history involves creating a concise summary of older messages, retaining the key points and decisions. This summary can be included in the context payload, providing the target agent with a high-level understanding of the project's history without consuming too many tokens, ensuring that the most critical information is preserved.
Truncating Irrelevant Messages
Truncating irrelevant messages involves removing messages that are no longer relevant to the current task. This can include old tool outputs, redundant prompts, or messages from earlier in the conversation that do not impact the current work. By focusing on the most recent and relevant information, you can optimize the context for the target agent, improving efficiency.
def summarize_messages(messages, max_tokens):
summary = []
total_tokens = 0
for msg in reversed(messages):
tokens = count_tokens(msg)
if total_tokens + tokens > max_tokens:
break
summary.append(msg)
total_tokens += tokens
return list(reversed(summary))Error Handling and Debugging
Context routing can fail for various reasons, such as parsing errors, API failures, or token limit exceeded errors. Robust error handling is essential to ensure that the routing process is reliable. You should implement try-except blocks to catch errors and provide meaningful feedback to the user, ensuring that the routing process can recover from common issues without crashing.
Debugging context routing issues often involves inspecting the parsed logs and the constructed context payload. By logging the parsing steps and the final payload, you can identify where the routing process is failing and make adjustments accordingly. This iterative debugging process helps you refine the routing script and improve its reliability, ensuring that it works consistently across different sessions and agents.
Handling Parsing Errors
Parsing errors can occur if the session log format changes or if the log file is corrupted. You can handle these errors by implementing fallback parsing logic or by logging the error and skipping the problematic entry. This ensures that the routing process continues even if some parts of the log are unreadable, maintaining the flow of your work.
Debugging API Failures
API failures can occur due to network issues, authentication errors, or rate limits. You can debug these failures by logging the API response and error message. This information helps you identify the root cause of the failure and take appropriate action, such as retrying the request or switching to a different agent, ensuring that your work continues smoothly.
def safe_parse_log(log_file):
try:
return parse_claude_log(log_file)
except Exception as e:
print(f'Error parsing log: {e}')
return []
Advanced Routing Strategies
Advanced routing strategies involve more sophisticated techniques for managing context across multiple agents. For example, you can implement a priority system that routes context to the agent best suited for the current task. You can also use machine learning models to predict the best agent for a given context, optimizing the routing process for efficiency and quality, as discussed in our multi-agent orchestration guide.
Another advanced strategy is to maintain a global context graph that tracks the state of the project across all agents. This graph can be used to resolve conflicts, merge changes, and ensure consistency across different agents. By maintaining a unified view of the project, you can enhance collaboration and reduce the risk of context loss, ensuring that all agents are working from the same source of truth.
Implementing a Priority System
A priority system routes context to the agent best suited for the current task based on predefined criteria. For example, you might prioritize Gemini for multimodal tasks and Claude for complex reasoning. By implementing a priority system, you can optimize the routing process for quality and efficiency, ensuring that the right agent handles the right task.
Maintaining a Global Context Graph
A global context graph tracks the state of the project across all agents, providing a unified view of the work. This graph can be used to resolve conflicts, merge changes, and ensure consistency. By maintaining a global context graph, you can enhance collaboration and reduce the risk of context loss across multiple agents, ensuring a cohesive development experience.
def route_by_priority(context, agents):
priority_scores = {agent: calculate_priority(context, agent) for agent in agents}
best_agent = max(priority_scores, key=priority_scores.get)
return best_agentConclusion and Best Practices
Context routing is a powerful technique for managing AI coding assistants across different environments. By building a CLI wrapper that reads session logs and injects context into new agents, you can maintain continuity and improve productivity. This approach allows you to leverage the strengths of different models while minimizing the friction of switching between them, creating a seamless development workflow.
To maximize the benefits of context routing, follow best practices such as optimizing context for token limits, implementing robust error handling, and monitoring rate limits. By continuously refining your routing script, you can create a seamless experience that enhances your workflow and enables you to work more effectively with multiple AI coding assistants, ensuring that you get the best of both worlds.
Key Takeaways for Context Routing
Key takeaways include understanding session log formats, structuring context payloads effectively, and optimizing for token limits. By mastering these techniques, you can create a robust context routing system that works seamlessly across different AI coding assistants, ensuring that your work flows smoothly between different tools and models.
Future Developments in Context Routing
Future developments in context routing may include more advanced AI models for context summarization and prediction, as well as better integration with IDEs and development workflows. As AI coding assistants evolve, context routing will become an increasingly important tool for managing complex projects and multiple agents, ensuring that you stay ahead of the curve.
def main():
log_file = '~/.claude/projects/session.jsonl'
messages = parse_claude_log(log_file)
context_payload = build_context_payload(messages, os.getcwd(), [])
target_agent = 'gemini'
result = switch_agent(context_payload, target_agent)
print(result)
Test the keyless endpoint with your own code samples right now to see how it handles your specific requests.