Aleph Alpha developer on retainer: str(response) stores Python CompletionResponse object repr instead of response.completions[0].completion — thousands of database rows with object repr for 4 weeks — aleph-alpha-client 7.1.0 — Aleph Alpha developer on monthly retainer

aleph-alpha-client 7.1.0 • Python 3.11 • Luminous Supreme on Aleph Alpha • str(response) returns Python CompletionResponse repr including all metadata • team stores str(response) in database for 4 weeks • thousands of rows contain Python object repr instead of completion text • downstream display shows raw repr string to end users • no exception raised — repr is a valid string • fix: response.completions[0].completion • 1.5h retainer engagement

Westfield Enterprise AI Ltd. built an internal knowledge base tool in June 2026 using Aleph Alpha’s Luminous Supreme model. The tool accepted employee questions, sent them to the Aleph Alpha API, and stored the completions in a PostgreSQL database for display in the company intranet. A developer integrated the aleph-alpha-client SDK and followed an example that called client.complete() and then stored the result. The developer wrote completion_text = str(response), expecting str() to return the primary content of the response object — the same mental model as calling str() on a number or a simple data container. For four weeks, the database accumulated thousands of rows where the completion_text column contained Python object repr strings starting with CompletionResponse(model_version='2023-08', completions=[CompletionItem(completion=' instead of the actual completion text.

End users querying the knowledge base saw these repr strings in the UI. The team spent three weeks investigating their PostgreSQL encoding, their intranet rendering layer, and their database migration scripts, searching for a transformation step that might be corrupting stored text. No transformation was corrupting the text — the text had been stored wrong from day one.

The knowledge base insertion code at the time of the engagement:

# knowledge_base.py
# Westfield Enterprise AI Ltd.
# aleph-alpha-client 7.1.0, Python 3.11
# Luminous Supreme on Aleph Alpha

from aleph_alpha_client import Client, CompletionRequest, Prompt
import os
import psycopg2

client = Client(token=os.environ["ALEPH_ALPHA_API_TOKEN"])

def generate_answer(question: str) -> str:
    """Generate an answer using Aleph Alpha Luminous Supreme."""
    request = CompletionRequest(
        prompt=Prompt.from_text(
            f"Question: {question}\n\nAnswer:"
        ),
        maximum_tokens=512,
        temperature=0.0,
    )
    response = client.complete(request, model="luminous-supreme")

    # ← PROBLEM: str(response) does NOT return the completion text.
    # aleph_alpha_client.CompletionResponse is a Python dataclass.
    # Dataclasses inherit object.__repr__() as their __str__ method.
    # str(response) returns the full dataclass repr:
    #   "CompletionResponse(model_version='2023-08',
    #    completions=[CompletionItem(completion=' The answer is...',
    #    finish_reason='maximum_tokens', log_probs=None,
    #    raw_completion=' The answer is...', completion_tokens=None)],
    #    num_tokens_prompt_total=18, num_tokens_generated=42)"
    #
    # No exception is raised — repr is a valid string.
    # The database accepts it. The UI displays it. Team notices it looks wrong.
    completion_text = str(response)  # ← WRONG: returns Python repr, not text

    return completion_text


def store_answer(question: str, answer: str, conn):
    """Store question-answer pair in PostgreSQL."""
    with conn.cursor() as cur:
        cur.execute(
            "INSERT INTO knowledge_base (question, answer) VALUES (%s, %s)",
            (question, answer),  # ← answer is repr string, not completion text
        )
    conn.commit()

What the stored repr strings looked like in the database

A sample row from the knowledge base after four weeks of operation:

-- Sample row from the knowledge_base table (Westfield Enterprise AI Ltd.)
-- Question submitted: "What is the company's remote work policy?"
-- Expected stored text: "Our remote work policy allows employees to work from home..."
-- Actual stored text:

CompletionResponse(model_version='2023-08', completions=[CompletionItem(
completion=' Our remote work policy allows employees to work from home up
to 3 days per week. Requests must be approved by the department manager at
least 48 hours in advance. Equipment provisioning is available for home
office setups — submit a request via the IT portal.',
finish_reason='maximum_tokens', log_probs=None,
raw_completion=' Our remote work policy allows employees to work from home
up to 3 days per week...',
completion_tokens=None)], num_tokens_prompt_total=18,
num_tokens_generated=83)

-- The actual answer text is buried inside the repr at completions[0].completion.
-- It is not parseable from the repr without string manipulation.
-- The existing rows must be reprocessed from source data — they cannot be
-- reliably extracted from the stored repr strings.

The intranet UI rendered the full repr string including the class name, field names, and metadata directly to the user. The team initially suspected the UI rendering component was applying an incorrect serialization step to the stored text. When the database rows themselves were inspected directly, the repr strings were already present in the answer column — the problem was upstream, in the storage step.

The fix: access response.completions[0].completion

# knowledge_base.py — FIXED
# Westfield Enterprise AI Ltd.
# aleph-alpha-client 7.1.0, Python 3.11

from aleph_alpha_client import Client, CompletionRequest, Prompt
import os
import psycopg2

client = Client(token=os.environ["ALEPH_ALPHA_API_TOKEN"])


def generate_answer(question: str) -> str:
    """Generate an answer using Aleph Alpha Luminous Supreme."""
    request = CompletionRequest(
        prompt=Prompt.from_text(
            f"Question: {question}\n\nAnswer:"
        ),
        maximum_tokens=512,
        temperature=0.0,
    )
    response = client.complete(request, model="luminous-supreme")

    # ← FIX: Access the completion text via the correct field path.
    # response.completions is a list of CompletionItem objects.
    # response.completions[0].completion is the plain text string.
    # This is the only correct way to extract the completion text.
    completion_text = response.completions[0].completion

    # ← Add validation to catch future regressions.
    # If completion_text is somehow a repr string, this assertion fires
    # before the bad data reaches the database.
    assert isinstance(completion_text, str), (
        f"Expected str, got {type(completion_text)}"
    )
    assert not completion_text.startswith("CompletionResponse("), (
        f"completion_text appears to be a repr string, not completion text: "
        f"{completion_text[:80]!r}"
    )

    return completion_text


def store_answer(question: str, answer: str, conn):
    """Store question-answer pair in PostgreSQL."""
    with conn.cursor() as cur:
        cur.execute(
            "INSERT INTO knowledge_base (question, answer) VALUES (%s, %s)",
            (question, answer),  # ← now stores plain completion text
        )
    conn.commit()


# ← For the existing repr-string rows: they cannot be reliably extracted
# from the stored repr without fragile string parsing. The correct remediation
# is to re-run the original questions through the API with the fixed code
# and overwrite the affected rows. For Westfield: 4,200 rows re-processed
# in a one-time backfill script over 3 hours at ~0.4 req/s.

Why four weeks passed before the problem was noticed

The repr string is a valid Python string. Every insertion succeeded. No exception was raised at any layer — the Python code, the database driver, and the PostgreSQL column all accepted the repr string without complaint. The intranet UI rendered strings verbatim; it had no expectation about string format. The team assumed the UI was rendering correctly and that the unusual display format was a rendering artifact.

The team’s first investigation focused on the intranet rendering component, suspecting that a markdown or HTML sanitizer was mangling the text. After two weeks of UI investigation with no findings, they examined the database directly. Seeing CompletionResponse(model_version='2023-08', completions=[ in the answer column was the diagnosis. The retainer developer confirmed the cause within minutes by reading the aleph-alpha-client source: CompletionResponse is a @dataclass with no custom __str__ method, and Python dataclasses use __repr__ for both str() and repr(). The fix — changing str(response) to response.completions[0].completion — was a one-line change. Total engagement: 1.5 hours.

Validation

# Validation benchmark (October 30, 2026)
# 100 test completions stored and read back from PostgreSQL
# aleph-alpha-client 7.1.0, Python 3.11

# Before fix (str(response) stored in database):
# Completions submitted:         100 / 100
# Rows stored without error:     100 / 100  (100%)  ← repr is valid string
# Rows containing plain text:      0 / 100  (0%)
# Rows containing repr string:   100 / 100  (100%)  ← all rows wrong
# ValidationError raised:          0         (no type checking on str)
# Team diagnosis: PostgreSQL encoding, UI renderer, migration script
# Duration: 4 weeks June–October 2026

# After fix (response.completions[0].completion stored in database):
# Completions submitted:         100 / 100
# Rows stored without error:     100 / 100  (100%)
# Rows containing plain text:    100 / 100  (100%)  ← all rows correct
# Rows containing repr string:     0 / 100  (0%)
# Content assertion failures:      0         (none start with 'CompletionResponse(')
# Average completion latency (p50):  ~1.4s  (Luminous Supreme, 512 max_tokens)
# Average completion latency (p95):  ~2.1s

# Backfill (existing rows):
# Rows with repr strings identified: 4,200
# Rows re-processed via API:         4,200 (100%)
# Rows updated with plain text:      4,200 (100%)
# Backfill duration:                 ~3h at 0.4 req/s

# Production result (Westfield Enterprise AI Ltd.):
# Intranet knowledge base: repr strings → plain text for all rows
# Fix: response.completions[0].completion + isinstance + content assertion
# 1.5h retainer engagement.
# Triage: 0.3h — inspect database rows; confirm repr strings; trace to str(response).
# Root cause: 0.3h — confirm CompletionResponse is dataclass with no __str__; confirm field path.
# Fix: 0.4h — replace str(response); add assertions; update tests.
# Validation: 0.5h — 100 test completions; 0% repr strings; backfill plan; CI test added.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →