> For the complete documentation index, see [llms.txt](https://dnotifier.gitbook.io/product-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/example-multi-agent/python.md).

# Python

Self-contained **blog article writer** workflow with three sequential agents.

## Complete runnable example

```python
import asyncio
import json
from dnotifier import DNotifier, Workflow, define_agent, WorkflowError

def extract_ai_content(ai_response) -> str:
    if isinstance(ai_response, dict) and isinstance(ai_response.get("data"), dict):
        return str(ai_response["data"].get("content", ""))
    return str(ai_response)

# ── Agent 1: Content creator ────────────────────────────────────────

async def content_creator_run(ctx):
    brief = ctx.input if isinstance(ctx.input, dict) else {}
    keywords = brief.get("keywords") or []

    if not brief.get("topic"):
        raise WorkflowError("content-creator: topic is required", agent_name="content-creator")

    ai_response = await ctx.send_ai(
        message={
            "useKnowledgeBase": False,
            "messages": [
                {
                    "role": "system",
                    "content": f"""You are an expert blog writer. Write a complete first-draft article in markdown.
Requirements:
- Target audience: {brief.get('audience', 'general')}
- Tone: {brief.get('tone', 'neutral')}
- Approximate length: {brief.get('wordCount', 800)} words
- Include an engaging introduction, clear H2/H3 headings, and a conclusion.
Return only the article body in markdown.""",
                },
                {
                    "role": "user",
                    "content": f"Topic: {brief['topic']}"
                    + (f"\nSuggested keywords: {', '.join(keywords)}" if keywords else ""),
                },
            ],
        },
        save_history=False,
        label="Blog content creation",
    )

    content = extract_ai_content(ai_response)
    ctx.state["draft"] = content
    return {"content": content, "stage": "content_creation"}

# ── Agent 2: Clarity editor ─────────────────────────────────────────

async def clarity_editor_run(ctx):
    input_data = ctx.input if isinstance(ctx.input, dict) else {}
    draft = input_data.get("content") or ctx.state.get("draft")

    if not draft or not str(draft).strip():
        raise WorkflowError("clarity-editor: no draft to refine", agent_name="clarity-editor")

    ai_response = await ctx.send_ai(
        message={
            "useKnowledgeBase": False,
            "messages": [
                {
                    "role": "system",
                    "content": (
                        "You are an editorial clarity specialist. Improve the draft for readability "
                        "and flow. Preserve facts and markdown formatting. Return only the revised article."
                    ),
                },
                {"role": "user", "content": str(draft)},
            ],
        },
        save_history=False,
        label="Blog clarity editing",
    )

    content = extract_ai_content(ai_response)
    ctx.state["refined"] = content
    return {"content": content, "stage": "clarity"}

# ── Agent 3: SEO optimizer ──────────────────────────────────────────

async def seo_optimizer_run(ctx):
    input_data = ctx.input if isinstance(ctx.input, dict) else {}
    article = input_data.get("content") or ctx.state.get("refined") or ""
    brief = ctx.state.get("blog_brief") or {}
    topic = input_data.get("topic") or brief.get("topic") or ""
    keywords = input_data.get("keywords") or brief.get("keywords") or []

    if not str(article).strip():
        raise WorkflowError("seo-optimizer: no article to optimize", agent_name="seo-optimizer")

    ai_response = await ctx.send_ai(
        message={
            "useKnowledgeBase": False,
            "messages": [
                {
                    "role": "system",
                    "content": """You are an SEO content optimizer. Return JSON only:
{
  "content": "optimized markdown article",
  "metaTitle": "string",
  "metaDescription": "string",
  "slug": "string",
  "keywords": ["string"]
}""",
                },
                {
                    "role": "user",
                    "content": f"Topic: {topic}\nTarget keywords: {', '.join(keywords) if keywords else 'derive from topic'}\nArticle: {article}",
                },
            ],
        },
        save_history=False,
        label="Blog SEO optimization",
    )

    raw = extract_ai_content(ai_response)
    try:
        parsed = json.loads(raw)
    except json.JSONDecodeError:
        parsed = {
            "content": raw,
            "metaTitle": topic,
            "metaDescription": "",
            "slug": topic.lower().replace(" ", "-"),
            "keywords": keywords,
        }

    content = parsed.get("content") or raw
    ctx.state["final"] = content
    return {
        "content": content,
        "metaTitle": parsed.get("metaTitle", topic),
        "metaDescription": parsed.get("metaDescription", ""),
        "slug": parsed.get("slug", ""),
        "keywords": parsed.get("keywords", keywords),
        "stage": "seo",
    }

content_creator_agent = define_agent(name="content-creator", run=content_creator_run)
clarity_editor_agent = define_agent(name="clarity-editor", run=clarity_editor_run)
seo_optimizer_agent = define_agent(name="seo-optimizer", run=seo_optimizer_run)

# ── Workflow ────────────────────────────────────────────────────────

async def blog_article_entry(ctx):
    brief = ctx.input if isinstance(ctx.input, dict) else {}
    ctx.state["blog_brief"] = brief

    creation = await ctx.run_agent("content-creator")
    ctx.state["stage"] = "content_creation"

    clarity = await ctx.run_agent(
        "clarity-editor",
        input_data={"content": creation.get("content") if isinstance(creation, dict) else None},
    )
    ctx.state["stage"] = "clarity"

    seo = await ctx.run_agent(
        "seo-optimizer",
        input_data={
            "content": clarity.get("content") if isinstance(clarity, dict) else None,
            "topic": brief.get("topic"),
            "keywords": brief.get("keywords"),
        },
    )
    ctx.state["stage"] = "seo"

    return {
        "article": seo.get("content") if isinstance(seo, dict) else None,
        "seo": {
            "metaTitle": seo.get("metaTitle") if isinstance(seo, dict) else None,
            "metaDescription": seo.get("metaDescription") if isinstance(seo, dict) else None,
            "slug": seo.get("slug") if isinstance(seo, dict) else None,
            "keywords": seo.get("keywords") if isinstance(seo, dict) else None,
        },
        "stages": {
            "contentCreation": creation.get("content") if isinstance(creation, dict) else None,
            "clarity": clarity.get("content") if isinstance(clarity, dict) else None,
            "seo": seo.get("content") if isinstance(seo, dict) else None,
        },
    }

blog_article_workflow = Workflow(
    name="blog-article-writer",
    description="Three-step blog pipeline: create, clarify, SEO",
    observability=True,
    entry=blog_article_entry,
).register_agents({
    "content-creator": content_creator_agent,
    "clarity-editor": clarity_editor_agent,
    "seo-optimizer": seo_optimizer_agent,
})

# ── Runner ──────────────────────────────────────────────────────────

USER_ID = "blog-pipeline"

async def main():
    notifier = DNotifier(
        app_id="your-app-id",
        secret="your-app-secret",
        transport="http",
        user_id=USER_ID,
        on_connected=lambda: print("Connected"),
    )

    await notifier.connect()

    run = await notifier.run_workflow(
        workflow=blog_article_workflow,
        input_data={
            "topic": "How to build deterministic AI workflows with DNotifier",
            "keywords": ["workflow", "sdk", "observability"],
            "audience": "software developers",
            "tone": "professional",
            "wordCount": 900,
        },
    )

    print(f"Execution: {run.get('executionId')}")
    result = run.get("result")
    if isinstance(result, dict):
        print(f"Meta title: {result.get('seo', {}).get('metaTitle')}")
        article = result.get("article") or ""
        print(f"Article preview: {article[:300]}")

asyncio.run(main())
```

## Learn more

* [**Workflow observability**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/observability.md)
* [**Build a workflow**](https://dnotifier.gitbook.io/product-docs/workflows-and-agents/build-workflow/python.md)
