AI & LLM integration patterns
Call LLM APIs, structure prompts, parse responses, and ship AI features safely.
How to Summarize Old Conversation Turns in Python
Compress old conversation turns into a brief summary while keeping recent turns intact for LLM context management.
from datetime import datetime, timedelta
def summarize_old_turns(conversation, max_turns=5):
"""Compress turns older than max_turns into a brief summary."""
if len(conversation) <= max_turns:
return conversation, ""
old_turns = conversation[:-max_turns]
recent_turns = conversation[-max_turns…
How to compute ROUGE recall in Python
Compute ROUGE recall by counting token overlap between a reference and candidate summary with pure Python.
def rouge_recall(reference, candidate):
ref_tokens = reference.lower().split()
cand_tokens = candidate.lower().split()
ref_counts = {}
for token in ref_tokens:
ref_counts[token] = ref_counts.get(token, 0) + 1
cand_counts = {}
for token in cand_tokens:
cand_counts[token] = cand…
Browse by section
Each section groups closely related Python snippets.
AI & LLM integration patterns — Python code examples
What you will find here
This page collects ai & llm integration patterns snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.