Structured Report Generation
Templated reports: executive summary, findings, evidence, recommendations.
Structured Report Generation is a free AI Agents lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
From Facts to a Readable Report
A research agent that only outputs a list of facts is hard to use. Decision makers need structured reports: an executive summary, background section, key findings, evidence, and recommendations.
This lesson covers generating professional reports section by section from verified facts.
The Report Template
Define the report structure up front. The LLM synthesizes one section at a time, keeping each section focused and avoiding repetition.
REPORT_SECTIONS = [
'executive_summary',
'background',
'key_findings',
'evidence',
'recommendations',
'sources'
]
SECTION_PROMPTS = {
'executive_summary': 'Write a 2-3 sentence executive summary of the key findings. Business audience.',
'background': 'Provide background context for the research topic (3-5 sentences).',
'key_findings': 'List 3-5 key findings as bullet points, each with one supporting fact.',
'evidence': 'Summarize the evidence for each finding with inline source citations.',
'recommendations': 'Based on the findings, provide 2-4 actionable recommendations.',
'sources': 'List all sources cited in the report, formatted as numbered URLs.'
}
if __name__ == '__main__':
print('Report sections:', REPORT_SECTIONS)
for section in REPORT_SECTIONS:
print(f'{section}: {SECTION_PROMPTS[section]}')
Generating One Section at a Time
Generating the entire report in one prompt is unreliable — the LLM loses track of facts and structure. Generate section by section, passing prior sections as context.
import openai
client = openai.OpenAI(api_key='YOUR_OPENAI_KEY')
def generate_section(section_name: str, question: str,
facts: list[dict], prior_sections: dict) -> str:
facts_text = '\n'.join(
f'- {f["fact"]} (source: {f["source"]})' for f in facts[:25]
)
prior_text = '\n\n'.join(
f'## {k.replace("_"," ").title()}\n{v}'
for k, v in prior_sections.items()
)
prompt = (
f'Research question: "{question}"\n\n'
f'Verified facts:\n{facts_text}\n\n'
f'Report so far:\n{prior_text}\n\n'
f'Now write the "{section_name}" section.\n'
f'Instructions: {SECTION_PROMPTS[section_name]}'
)
resp = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': prompt}]
)
return resp.choices[0].message.contentBuilding the Report Iteratively
Iterate through all sections, passing accumulating context. Each section is aware of what came before, ensuring coherence and avoiding contradictions within the report.
def build_report(question: str, facts: list[dict]) -> dict:
report = {}
sections_to_generate = [s for s in REPORT_SECTIONS if s != 'sources']
for section in sections_to_generate:
print(f'Generating section: {section}...')
report[section] = generate_section(
section_name=section,
question=question,
facts=facts,
prior_sections={k: v for k, v in report.items()}
)
# Sources section: generate citation list from fact URLs
unique_sources = list(dict.fromkeys(f['source'] for f in facts))
report['sources'] = '\n'.join(
f'{i+1}. {url}' for i, url in enumerate(unique_sources[:20])
)
return reportInjecting Inline Citations
Replace fact references in the generated sections with numbered citations linking back to the sources list. This makes every claim traceable.
import re
def inject_citations(section_text: str, facts: list[dict]) -> str:
source_index = {} # url -> int
for i, fact in enumerate(facts):
url = fact['source']
if url not in source_index:
source_index[url] = len(source_index) + 1
annotated = section_text
for fact in facts:
if fact['fact'] in annotated:
num = source_index[fact['source']]
annotated = annotated.replace(
fact['fact'],
f'{fact["fact"]} [{num}]',
1 # replace first occurrence only
)
return annotated
if __name__ == '__main__':
demo_text = 'Revenue grew 12% last quarter. The team also launched two new products.'
demo_facts = [{'fact': 'Revenue grew 12% last quarter', 'source': 'https://example.com/report'}]
print(inject_citations(demo_text, demo_facts))
Formatting as Markdown
Render the report sections as Markdown. This allows the output to be converted to HTML, PDF, or displayed directly in tools like Notion or Confluence.
def render_markdown(report: dict, title: str) -> str:
section_titles = {
'executive_summary': 'Executive Summary',
'background': 'Background',
'key_findings': 'Key Findings',
'evidence': 'Evidence',
'recommendations': 'Recommendations',
'sources': 'Sources'
}
lines = [f'# {title}', '']
for key in REPORT_SECTIONS:
if key in report:
lines.append(f'## {section_titles[key]}')
lines.append('')
lines.append(report[key])
lines.append('')
return '\n'.join(lines)
# Usage:
# md = render_markdown(report, 'Causes of Inflation in 2024')
# with open('report.md', 'w') as f: f.write(md)Generating a Report with Source Links
When rendering for the web, convert source URLs into hyperlinks. Also add a metadata block with report generation date, number of sources, and verification rate.
from datetime import date
def render_html_report(report: dict, title: str,
facts: list[dict], question: str) -> str:
meta = (
f'<p><em>Generated: {date.today()} | '
f'Sources: {len(set(f["source"] for f in facts))} | '
f'Research question: {question}</em></p>'
)
html_parts = [f'<h1>{title}</h1>', meta]
section_titles = {
'executive_summary': 'Executive Summary',
'background': 'Background',
'key_findings': 'Key Findings',
'evidence': 'Evidence',
'recommendations': 'Recommendations',
'sources': 'Sources'
}
for key in REPORT_SECTIONS:
if key in report:
content = report[key].replace('\n', '<br>')
html_parts.append(f'<h2>{section_titles[key]}</h2><p>{content}</p>')
return '\n'.join(html_parts)Quality Checks Before Publishing
Run automated quality checks before delivering the report: minimum word count per section, at least N citations, all recommendations are action verbs, no placeholder text like '[INSERT]'.
def quality_check(report: dict) -> list[str]:
issues = []
for section in ['executive_summary', 'background', 'key_findings']:
word_count = len(report.get(section, '').split())
if word_count < 30:
issues.append(f'{section} too short: {word_count} words (min 30)')
if report.get('sources', '').count('http') < 3:
issues.append('Less than 3 cited sources')
if '[INSERT]' in str(report) or 'TODO' in str(report):
issues.append('Report contains placeholder text')
recs = report.get('recommendations', '')
if recs and not any(verb in recs.lower()
for verb in ['should', 'recommend', 'consider', 'implement']):
issues.append('Recommendations may not be actionable')
return issues
if __name__ == '__main__':
demo_report = {
'executive_summary': 'Too short.',
'background': 'Also short.',
'key_findings': 'Short too.',
'sources': 'http://a.com',
'recommendations': 'Looks fine as is.',
}
for issue in quality_check(demo_report):
print('-', issue)
Executive Summary: Tight Constraints
The executive summary should be self-contained: someone who reads only this section should understand the core finding and recommended action. Use a strict prompt with a word limit.
def generate_executive_summary(question: str, facts: list[dict],
max_words: int = 80) -> str:
top_facts = '\n'.join(f'- {f["fact"]}' for f in facts[:10])
prompt = (
f'Research question: "{question}"\n\n'
f'Key facts:\n{top_facts}\n\n'
f'Write an executive summary in EXACTLY {max_words} words or fewer.\n'
f'Format: [Main finding]. [Why it matters]. [Recommended action].'
)
resp = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': prompt}]
)
return resp.choices[0].message.contentMulti-Audience Reports
The same research may need different report styles for different audiences: technical deep-dive for engineers, executive summary for leadership, plain-language brief for non-specialists. Generate each variant from the same fact set.
AUDIENCE_STYLES = {
'executive': 'Brief, strategic. Avoid jargon. Focus on business impact and decisions.',
'technical': 'Detailed, precise. Include methodology, caveats, and data sources.',
'general': 'Plain language. Avoid technical terms. Use analogies where helpful.'
}
def generate_for_audience(facts: list[dict], question: str, audience: str) -> str:
style = AUDIENCE_STYLES.get(audience, AUDIENCE_STYLES['general'])
facts_text = '\n'.join(f'- {f["fact"]}' for f in facts[:20])
prompt = (
f'Synthesize these facts into a report for a {audience} audience.\n'
f'Style guide: {style}\n'
f'Question: "{question}"\n\n'
f'Facts:\n{facts_text}'
)
resp = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': prompt}]
)
return resp.choices[0].message.contentSaving and Versioning Reports
Save reports with a timestamp and the research question hash. This allows comparing report versions if the research is re-run with updated sources.
import hashlib, json, os
from datetime import datetime, timezone
def save_report(report: dict, question: str, output_dir: str = '/tmp/reports'):
os.makedirs(output_dir, exist_ok=True)
q_hash = hashlib.md5(question.encode()).hexdigest()[:8]
timestamp = datetime.now(timezone.utc).strftime('%Y%m%d_%H%M')
filename = f'{output_dir}/report_{q_hash}_{timestamp}.json'
with open(filename, 'w') as f:
json.dump({
'question': question,
'generated': timestamp,
'sections': report
}, f, indent=2)
print(f'Report saved: {filename}')
return filename
if __name__ == '__main__':
import tempfile
demo_dir = tempfile.mkdtemp()
save_report({'executive_summary': 'AI agent adoption grew significantly in 2026.'},
'What are the key AI agent trends in 2026?', output_dir=demo_dir)
Which section should always be self-contained in the report structure?
Report structure is designed so that time-constrained readers can extract value without reading the full document. Understanding which section must stand alone is important for report design.
Structured Report Generation Recap
Generate reports section by section using a fixed template (Executive Summary → Background → Key Findings → Evidence → Recommendations → Sources). Inject inline citations, run quality checks, and support multiple audience styles from the same fact set.
Always save reports with timestamps and question hashes for versioning.
Frequently asked questions
Is the “Structured Report Generation” lesson free?
Yes — the full text of “Structured Report Generation” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Structured Report Generation”?
Templated reports: executive summary, findings, evidence, recommendations. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Structured Report Generation” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Multi-Step Research Loop Design
- Source Verification and Citation
- Structured Report Generation
- Fact-Checking and Hallucination Prevention