Persisting AI Tasks and Results with PostgreSQL

Persisting AI Tasks and Results with PostgreSQL

Published on

0

views

PostgreSQL AI task persistence, store LLM results in database, SQLAlchemy AI models schema, FastAPI task status tracking, track token usage PostgreSQL

You can call the model, return a summary, and show progress in the UI. The moment a user refreshes the page or asks “what did I summarize last week?”, that in-memory result disappears. Real features need durable records.

This article shows a practical way to persist AI tasks and their results in PostgreSQL without turning the feature into a full workflow engine. We store the request, the model response metadata, the final content, and enough status information to answer basic questions later. Keep the first version simple and inspectable.

The Short Answer

Low-angle shot of a backend engineer reviewing PostgreSQL database schema and SQLAlchemy models on a laptop screen.

Add two tables—one for tasks and one for optional result payloads—write a row before the model call, update it with the outcome, and expose a small query endpoint. Use the same FastAPI service so validation, logging, and cost tracking stay in one place. Do not add queues or background workers until measurement shows the synchronous path is no longer enough.

What Product Problem This Solves

Users and developers both need history. A user wants to revisit an earlier summary. A developer wants to know which calls succeeded, which returned empty content, and how many tokens were spent. Without persistence those questions become guesswork or log diving.

Storing the task and its result turns an ephemeral API call into a feature that can be audited, debugged, and improved over time.

Minimal Working Implementation

We will extend the existing FastAPI service. The example uses SQLAlchemy 2.0 style and asyncpg for a clean async path, but the same ideas work with any PostgreSQL driver you already trust.

Database models

Python

# models.py
from datetime import datetime
from typing import Optional
from sqlalchemy import String, Text, Integer, DateTime, ForeignKey, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship

class Base(DeclarativeBase):
    pass

class AITask(Base):
    __tablename__ = "ai_tasks"

    id: Mapped[int] = mapped_column(primary_key=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
    )
    status: Mapped[str] = mapped_column(String(32), default="pending")  # pending | running | succeeded | failed
    style: Mapped[str] = mapped_column(String(32))
    input_text: Mapped[str] = mapped_column(Text)
    max_tokens: Mapped[int] = mapped_column(Integer, default=180)

    # model outcome
    model: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
    finish_reason: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
    prompt_tokens: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    completion_tokens: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    total_tokens: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
    error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)

    result: Mapped[Optional["AITaskResult"]] = relationship(back_populates="task", uselist=False)

class AITaskResult(Base):
    __tablename__ = "ai_task_results"

    id: Mapped[int] = mapped_column(primary_key=True)
    task_id: Mapped[int] = mapped_column(ForeignKey("ai_tasks.id"), unique=True)
    summary: Mapped[str] = mapped_column(Text)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())

    task: Mapped["AITask"] = relationship(back_populates="result")

Request / response schemas (Pydantic)

Python

from pydantic import BaseModel, Field
from typing import Optional
from datetime import datetime

class SummarizeRequest(BaseModel):
    text: str = Field(..., min_length=20, max_length=6000)
    style: str = Field(default="concise", pattern="^(concise|bullet|technical)$")
    max_tokens: int = Field(default=180, ge=40, le=400)

class TaskResponse(BaseModel):
    id: int
    status: str
    style: str
    summary: Optional[str] = None
    finish_reason: Optional[str] = None
    usage: Optional[dict] = None
    request_id: Optional[str] = None
    error_message: Optional[str] = None
    created_at: datetime

The endpoint that creates and runs the task

Python

# main parts of the route
@app.post("/v1/summarize", response_model=TaskResponse)
async def summarize(
    body: SummarizeRequest,
    db: AsyncSession = Depends(get_db),
    openai_client: OpenAI = Depends(get_client),
):
    # 1. Create the task row first
    task = AITask(
        status="pending",
        style=body.style,
        input_text=body.text,
        max_tokens=body.max_tokens,
    )
    db.add(task)
    await db.commit()
    await db.refresh(task)

    # 2. Mark running
    task.status = "running"
    await db.commit()

    try:
        response = openai_client.chat.completions.create(
            model="gpt-6.1-sol",
            messages=[
                {"role": "system", "content": SYSTEM_PROMPTS[body.style]},
                {"role": "user", "content": body.text},
            ],
            max_tokens=body.max_tokens,
            temperature=0.2,
            timeout=25.0,
        )
    except Exception as e:
        task.status = "failed"
        task.error_message = str(e)[:500]
        await db.commit()
        raise HTTPException(status_code=502, detail="Model call failed")

    choice = response.choices[0]
    content = (choice.message.content or "").strip()
    finish_reason = choice.finish_reason or "unknown"

    task.model = response.model
    task.finish_reason = finish_reason
    task.prompt_tokens = response.usage.prompt_tokens
    task.completion_tokens = response.usage.completion_tokens
    task.total_tokens = response.usage.total_tokens
    task.request_id = response.id

    if not content:
        task.status = "failed"
        task.error_message = f"Empty content (finish_reason={finish_reason})"
        await db.commit()
        raise HTTPException(status_code=502, detail=task.error_message)

    # 3. Persist the successful result
    result = AITaskResult(task_id=task.id, summary=content)
    db.add(result)
    task.status = "succeeded"
    await db.commit()
    await db.refresh(task)

    return TaskResponse(
        id=task.id,
        status=task.status,
        style=task.style,
        summary=content,
        finish_reason=finish_reason,
        usage={
            "prompt_tokens": task.prompt_tokens,
            "completion_tokens": task.completion_tokens,
            "total_tokens": task.total_tokens,
        },
        request_id=task.request_id,
        created_at=task.created_at,
    )

A simple retrieval endpoint completes the minimal loop:

Python

@app.get("/v1/tasks/{task_id}", response_model=TaskResponse)
async def get_task(task_id: int, db: AsyncSession = Depends(get_db)):
    task = await db.get(AITask, task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")

    summary = task.result.summary if task.result else None
    return TaskResponse(
        id=task.id,
        status=task.status,
        style=task.style,
        summary=summary,
        finish_reason=task.finish_reason,
        usage={
            "prompt_tokens": task.prompt_tokens,
            "completion_tokens": task.completion_tokens,
            "total_tokens": task.total_tokens,
        } if task.total_tokens is not None else None,
        request_id=task.request_id,
        error_message=task.error_message,
        created_at=task.created_at,
    )

This is the smallest version that still answers the product question: “Can I look up what happened to a previous AI request?”

Why Two Tables

The task row holds the operational facts—status, tokens, finish reason, error message—that you will query often. The result row holds the potentially longer summary text. Separating them keeps the task table narrow and makes it easy later to add retention policies or move large payloads to object storage without rewriting every query.

I once kept everything in a single JSONB column. It worked until someone asked for “all failed tasks in the last 24 hours with their token counts.” The query became painful. Two ordinary tables would have been simpler from the start.

Status Values That Stay Honest

Wide-angle shot of an engineer testing task lifecycle status values and backend error handling in a dim dev environment.

Four statuses are enough for this feature:

  • pending – row created, model not yet called

  • running – model call in flight

  • succeeded – usable content stored

  • failed – error message recorded

Do not invent intermediate states that the code cannot actually reach. The status should reflect what the application knows, not what we hope the model is doing.

What About the Frontend

The typed TypeScript client can be extended with a getTask(taskId) function that hits the new retrieval endpoint. The progress component from the previous article can store the returned task id and offer a “View previous result” link. That is ordinary React work; the important part is that the backend now has a durable record to show.

Cost and Audit Trail

Every successful or failed call now leaves a permanent token count. You can answer “how much did summarization cost last week?” with a simple SQL query instead of scraping logs. That visibility is one of the main reasons to persist the data in the first place.

What Was Tested and What Remains Uncertain

I created tasks with short and medium inputs, forced model timeouts and empty content, and verified that the status, token fields, and result row were written correctly. Retrieval by id returned the expected shape.

I have not tested concurrent writes under load, nor have I measured the effect of large summary texts on table size over months of traffic. Those checks belong in later articles once the feature has real usage. Connection-pool settings, migration strategy, and exact PostgreSQL version compatibility must still be verified for each environment.

When a Simpler Approach Is Enough

If the feature is a one-off internal script, writing results to a local JSON file may still be fine. The moment a user or another service needs to look up past results, PostgreSQL becomes the smaller useful version: one durable place for status, cost, and content.

Before adding a queue, see whether the current synchronous path meets latency and reliability needs. Before adding an agent, see whether a deterministic workflow is enough. The extra complexity has to earn its place.

Practical Conclusion

Persisting AI tasks and results with PostgreSQL is ordinary application data work applied to model calls. Create the task row first, update it with the outcome, store the content when it is usable, and expose a simple lookup. The model can produce the summary; your application still has to remember what happened.

Start with the smallest version that can answer the product question. In this case the question is “Can I reliably look up a previous AI request and its result?” The schema and endpoints above are that version.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

What to Verify Before Building with GPT-6.1 Sol
Build an AI Feature |

What to Verify Before Building with GPT-6.1 Sol

Before building production-facing applications with GPT-6.1 Sol, running a disciplined verification checklist is essential. This guide outlines critical pre-flight checks—confirming model availability, measuring context windows, testing structured outputs and tool calling, monitoring latency and costs, and evaluating error modes. Verifying these core capabilities beforehand prevents unexpected failures and ensures robust application performance under real-world usage conditions.

0
Build a Small GPT-6.1 Sol Summarization Endpoint
Build an AI Feature |

Build a Small GPT-6.1 Sol Summarization Endpoint

This article demonstrates how to build a production-ready summarization endpoint using FastAPI and the GPT-6.1 Sol model. It covers essential backend practices including input length validation, style constraints, hard timeouts, finish reason verification, and structured operational logging, providing a reliable foundation for adding safe AI features to your application architecture.

0
Add a Typed TypeScript Client for a FastAPI AI Endpoint
Build an AI Feature |

Add a Typed TypeScript Client for a FastAPI AI Endpoint

This article demonstrates how to build a robust, typed TypeScript client for a FastAPI AI summarization endpoint. It covers essential practices including request-response interface mirroring, client-side input validation, custom error classes with HTTP status handling, and runtime response shape checks, providing compile-time safety and clean contract boundaries for your frontend.

0
Show Task Progress in a Next.js AI Application
Build an AI Feature |

Show Task Progress in a Next.js AI Application

This article demonstrates how to build a practical progress tracker for AI features in Next.js without complex queues or WebSockets. Using a lightweight React component, it covers multi-stage loading states, elapsed time counters, abort-controller cancellation, and clear error handling, ensuring users stay informed during slow model inference calls.

0