Structured Multi-Persona Content Generation with Azure OpenAI and SSE Streaming

Published by Rhein-Ruhr-Informatik on

In this tutorial, we will build a Content-Generation-Studiothat turns a single marketing brief into three structured content variations using distinct AI personas. The frontend is built with Next.js and TypeScript the backend uses Python with FastAPI and Azure OpenAI powers the structured generation and native Server-Sent Events (SSE) streaming with Azure Content Safety providing automated moderation guardrails.

Instead of producing unpredictable raw text, our application enforces guaranteed data schemas (title, body, and SEO keywords), real-time progress feedback via SSE streaming, and three distinct perspectives tailored to specific audiences: Friendly SaaS Marketer, Technical Blogger and Skeptical CFO.

Next.js (TypeScript) → FastAPI → Azure Content Safety (Guardrails)
                                      ↓
                               Azure OpenAI (GPT-4.1 / Structured Outputs)
                                      ↓
                               Server-Sent Events (SSE-Stream)
                                      ↓
                               3 Persona-Variationen (Title, Body, SEO Keywords)

Prerequisites

  • Python and Node.js installed on your computer.
  • An Azure OpenAI resource with a deployed model (e.g. GPT-4.1-mini or GPT-4o).
  • An Azure Content Safety resource.
  • Basic knowledge of FastAPI, Next.js, and TypeScript.
  • Basic understanding of Server-Sent Events (SSE) and Pydantic schemas.

Step 1: Define the Pydantic Schema

The first step is defining the structure our application expects from the model. We create Pydantic models for individual variations and the overall response container:

class Variation(BaseModel):
    id: int
    title: str
    body: str
    seoKeywords: list[str] = Field(default_factory=list)

class ResultSchema(BaseModel):
    variations: list[Variation]

This schema acts as a dual contract: it guarantees the shape of our backend API responses for the Next.js frontend, and it is passed directly to Azure OpenAI's Structured Outputsengine to strictly constrain the model's output JSON Schema.

Step 2: Implement Persona System Prompts

Marketing copy requires different tones depending on the channel and audience. In our app, we define three system prompts:

PERSONAS = {
    „friendly“: {
        „name“: „Friendly SaaS Marketer“,
        „system“: (
            „You are a friendly SaaS marketer. „
            „Write in a warm, benefit-led, conversational tone. „
            „Prefer short sentences and a clear call to action.“
        ),
    },
    „technical“: {
        „name“: „Technical Blogger“,
        „system“: (
            „You are a technical blogger. „
            „Write in a precise, credible, educational tone. „
            „Include concrete details, trade-offs, and one practical tip.“
        ),
    },
    „cfo“: {
        „name“: „Skeptical CFO“,
        „system“: (
            „You are a skeptical CFO. „
            „Write in a direct, evidence-driven, ROI-focused tone. „
            „Quantify impact where possible and flag risks explicitly.“
        ),
    },
}

When a request arrives, the backend dynamically combines the selected persona system prompt with user instructions containing the brief, target audience, format (LinkedIn post, marketing email, or landing page copy), and output language.

Step 3: Guardrail Content with Azure Content Safety

Before invoking the language model, the backend validates the brief against Azure Content Safety. This detects harmful inputs across categories such as violence, hate speech, self-harm, and sexual content:

response = content_safety_client.analyze_text(
    AnalyzeTextOptions(text=req.brief)
)
is_safe = all(item.severity < 2 for item in response.categories_analysis)

If harmful content is detected, the API returns a structured 400 Bad Request with specific category details. This prevents prompt injection and misuse while avoiding unnecessary token costs on blocked prompts. A local heuristic is also available as a fallback when offline.

Step 4: Real-Time SSE Streaming and Incremental Parsing

Generating three comprehensive marketing variations takes several seconds. Rather than making the user wait for the full response, we use Server-Sent Events (SSE) via FastAPI's StreamingResponse von FastAPI:

@app.post(„/generate/stream“)
def generate_stream(req: GenerateRequest):
    def events():
        yield _sse_event(„safety“, {„safe“: True})
        yield _sse_event(„start“, {„request_id“: request_id})
        with client.responses.stream(
            model=DEPLOYMENT,
            instructions=system,
            input=user_prompt,
            text_format=ResultSchema,
        ) as stream:
            for event in stream:
                if event.type == „response.output_text.delta“:
                    yield _sse_event(„delta“, {„text“: event.delta})
                    # Inkrementell abgeschlossene JSON-Variation-Objekte extrahieren
                    for v in _complete_variations_from_json(accumulated_text):
                        yield _sse_event(„variation“, {„variation“: v.dict()})
    return StreamingResponse(events(), media_type=“text/event-stream“)

The streaming generator parses JSON chunks on the fly. As soon as each variation's closing bracket is reached, an SSE variationevent is emitted. This allows the Next.js frontend to render each content card immediately as it finishes, providing a fast and reactive user experience.

Step 5: Connect FastAPI and Next.js with Observability

The Next.js frontend connects directly to the FastAPI stream using standardfetch and reads chunks with a ReadableStreamDefaultReader. It renders live progress, displays persona badges, and supports instant copy, JSON view, and file export. In addition, every request captures observability data:

  • Latency in milliseconds.
  • Prompt, completion, and total token usage.
  • Estimated execution cost based on Azure OpenAI token pricing.
  • Per-client generation logs stored in SQLite and process memory.

Why Personas and Structured Outputs Matter

Without persona steering and structured outputs, LLM outputs tend to be generic, unpredictable, and difficult to parse reliably in production applications. Combining explicit persona instructions with Pydantic schemas yields predictable, high-quality results tailored to real marketing workflows.

  • The frontend receives a guaranteed, type-safe data schema.
  • No regex or Markdown code block stripping is required in application code.
  • Personas provide consistent brand voice and clear positioning.
  • Streaming eliminates perceived latency and improves engagement.

Conclusion

With Next.js, FastAPI, Azure OpenAI, and Azure Content Safety, we built an end-to-end content generation application with enterprise-grade guardrails and real-time streaming.

FastAPI Backend → Controls safety checks, persona mapping, streaming, and token logs
Azure OpenAI → Delivers structured, persona-driven generation via GPT-4.1
Azure Content Safety → Blocks harmful prompts before execution
Next.js Frontend → Delivers a responsive, multi-language UI with live SSE card rendering

This combination transforms generative AI from an unpredictable chat experiment into a dependable, production-ready content engineering pipeline.

I hope this short tutorial was helpful.

Now let’s code!

Categories: Blog

en_USEnglish