How do I use Commune thread history as context for my LLM when generating email replies? #47
Unanswered
shanjairaj7
asked this question in
Q&A
Replies: 1 comment
Using This with Claude's 200k Context Window for Very Long Email ThreadsClaude's 200k token context window changes the math significantly. For most email threads — even long customer support histories — you can load the entire thread without truncation: import anthropic
from commune import CommuneClient
client = CommuneClient(api_key="YOUR_API_KEY")
anthropic_client = anthropic.Anthropic()
def handle_email_with_claude(payload: dict) -> str:
thread_id = payload["thread_id"]
thread = client.threads.get(thread_id)
# With Claude's 200k context, load the full thread
# Only truncate if thread is genuinely massive (rare)
messages = thread.messages
# Format thread as Claude messages
claude_messages = []
for msg in messages:
role = "user" if msg.direction == "inbound" else "assistant"
body = clean_email_body(msg.body_text)
claude_messages.append({
"role": role,
"content": f"[Email from {msg.from_email} at {msg.created_at}]\n{body}"
})
# The new inbound email is already in thread.messages if fetched fresh
# But if processing from webhook payload, append it explicitly
if not any(m.id == payload.get("message_id") for m in messages):
claude_messages.append({
"role": "user",
"content": f"[Email from {payload['from']} — just received]\n{payload['body']}"
})
# Add instruction as last user message if conversation ends with assistant
if claude_messages and claude_messages[-1]["role"] == "assistant":
claude_messages.append({
"role": "user",
"content": "Based on the full email history above, draft a professional reply to the customer's most recent message."
})
response = anthropic_client.messages.create(
model="claude-opus-4-6",
max_tokens=1024,
system=(
"You are a professional customer support agent. "
"You have access to the full email conversation history. "
"Write replies that reference prior context naturally when relevant. "
"Be concise but thorough. Never repeat information the customer already knows."
),
messages=claude_messages,
)
reply_text = response.content[0].text
# Send via Commune with thread continuity
result = client.messages.send(
inbox_id=payload["inbox_id"],
to=payload["from"],
subject=f"Re: {payload['subject']}",
body=reply_text,
thread_id=thread_id,
)
return result.thread_idThe practical advantage of Claude's large context: for a 6-month support history with a high-value customer (think 80+ emails), you can load everything and Claude can say "I see you've mentioned this issue three times before — let me escalate this directly to our engineering team." That level of contextual awareness is impossible if you are truncating to the last 5 messages. A rough guide:
|
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
The Problem
When your agent receives an inbound email, it rarely has enough context from just that single message to write a great reply. The customer might be referencing something from three emails ago. You need the full thread history — efficiently loaded, well-formatted for the LLM, and within the context window.
This post covers: fetching thread history, formatting it for different LLMs, handling long threads that exceed context limits, and a complete LangChain memory integration.
Step 1: Fetching Thread History
Each message object has:
id,from_email,subject,body_text,body_html,direction(inbound/outbound),created_at.Step 2: Formatting for LLM Context
Raw email bodies contain quoted text, signatures, and HTML artifacts. Clean and structure them:
Step 3: The Structured Format vs. Raw Text Decision
Raw text (above) works for most cases. For better results with complex threads, use a structured chat format that the LLM understands as a conversation:
Step 4: Token Counting and Context Window Management
Long threads can exceed your model's context window. Count tokens before sending:
Step 5: Semantic Search for Very Long Threads
If a customer has 200 emails in a thread and you need the 5 most relevant ones to answer their current question, use search instead of loading everything:
Complete LangChain Integration
Use Commune thread history as LangChain memory:
Performance Considerations
body_textoverbody_htmlfor LLM context — HTML adds tokens with no semantic valueAll reactions