Compare commits
3 commits
227132d15e
...
ecd2f1105a
| Author | SHA1 | Date | |
|---|---|---|---|
| ecd2f1105a | |||
| bf7cde0bfc | |||
| bbb41a366b |
5 changed files with 302 additions and 1 deletions
|
|
@ -690,8 +690,8 @@ def generate_articles_with_quality_retries(
|
|||
"ИИ-редактор",
|
||||
f"Повторная редактура {attempt}/{QUALITY_REWRITE_ATTEMPTS}: {feedback}",
|
||||
)
|
||||
payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback)
|
||||
try:
|
||||
payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback)
|
||||
articles = articles_from_payload(video, payload, frames)
|
||||
except (RuntimeError, json.JSONDecodeError) as exc:
|
||||
message = str(exc)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,215 @@
|
|||
# LLM JSON Retry Fix Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Make malformed LLM JSON enter the existing three-attempt quality retry loop instead of failing after the first response.
|
||||
|
||||
**Architecture:** Keep the current article-generation pipeline and exception types. Expand the existing `try` boundary by one statement so both payload generation/parsing and article validation share the same quality-retry handler; verify the control flow with an isolated stdlib `unittest` using mocks.
|
||||
|
||||
**Tech Stack:** Python 3.11+, stdlib `unittest` and `unittest.mock`, Celery worker, SQLAlchemy, Docker Compose, Forgejo Actions.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Create `tests/__init__.py` so the focused test module can be addressed directly by `unittest`.
|
||||
- Create `tests/test_worker_llm_retry.py` for deterministic retry-control-flow coverage without a real LLM or database.
|
||||
- Modify `app/worker.py:693-695` only to move payload generation inside the existing exception boundary.
|
||||
|
||||
### Task 1: Add a failing regression test
|
||||
|
||||
**Files:**
|
||||
- Create: `tests/__init__.py`
|
||||
- Create: `tests/test_worker_llm_retry.py`
|
||||
- Test: `tests/test_worker_llm_retry.py`
|
||||
|
||||
- [ ] **Step 1: Create the test package marker**
|
||||
|
||||
Create an empty `tests/__init__.py`.
|
||||
|
||||
- [ ] **Step 2: Write the retry regression test**
|
||||
|
||||
Create `tests/test_worker_llm_retry.py` with:
|
||||
|
||||
```python
|
||||
import unittest
|
||||
from unittest.mock import call, patch
|
||||
|
||||
from app.models import Video
|
||||
from app.worker import generate_articles_with_quality_retries
|
||||
|
||||
|
||||
class GenerateArticlesWithQualityRetriesTest(unittest.TestCase):
|
||||
@patch("app.worker.append_progress")
|
||||
@patch("app.worker.articles_from_payload")
|
||||
@patch("app.worker.generate_article_payload")
|
||||
def test_retries_invalid_json_and_passes_feedback(
|
||||
self,
|
||||
generate_article_payload_mock,
|
||||
articles_from_payload_mock,
|
||||
append_progress_mock,
|
||||
):
|
||||
error = "LLM вернул невалидный JSON: Expecting ',' delimiter в строке 11, колонке 17."
|
||||
valid_payload = {"articles": [{"title": "Готовая статья"}]}
|
||||
expected_articles = [object()]
|
||||
generate_article_payload_mock.side_effect = [RuntimeError(error), valid_payload]
|
||||
articles_from_payload_mock.return_value = expected_articles
|
||||
video = Video(id=213, title="Тест", description="", external_id="test", source_url="")
|
||||
|
||||
result = generate_articles_with_quality_retries(video, "Текст", [])
|
||||
|
||||
self.assertEqual(result, expected_articles)
|
||||
self.assertEqual(generate_article_payload_mock.call_count, 2)
|
||||
self.assertEqual(
|
||||
generate_article_payload_mock.call_args_list,
|
||||
[
|
||||
call(video, "Текст", chapter=None, quality_feedback=""),
|
||||
call(video, "Текст", chapter=None, quality_feedback=error),
|
||||
],
|
||||
)
|
||||
append_progress_mock.assert_called_once()
|
||||
articles_from_payload_mock.assert_called_once_with(video, valid_payload, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run the test and verify the current bug**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
python -m unittest tests.test_worker_llm_retry -v
|
||||
```
|
||||
|
||||
Expected: `ERROR`; the first `RuntimeError` escapes from `generate_article_payload()` and `generate_article_payload_mock.call_count` never reaches two.
|
||||
|
||||
### Task 2: Move payload generation into the retry boundary
|
||||
|
||||
**Files:**
|
||||
- Modify: `app/worker.py:693-695`
|
||||
- Test: `tests/test_worker_llm_retry.py`
|
||||
|
||||
- [ ] **Step 1: Apply the minimal control-flow change**
|
||||
|
||||
Change the loop body from:
|
||||
|
||||
```python
|
||||
payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback)
|
||||
try:
|
||||
articles = articles_from_payload(video, payload, frames)
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```python
|
||||
try:
|
||||
payload = generate_article_payload(video, transcript, chapter=chapter, quality_feedback=feedback)
|
||||
articles = articles_from_payload(video, payload, frames)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the focused test**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
python -m unittest tests.test_worker_llm_retry -v
|
||||
```
|
||||
|
||||
Expected: one test passes and output ends with `OK`.
|
||||
|
||||
- [ ] **Step 3: Run syntax and diff checks**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
python -m compileall -q app tests
|
||||
git diff --check -- app/worker.py tests
|
||||
```
|
||||
|
||||
Expected: both commands exit with status 0 and print no errors.
|
||||
|
||||
- [ ] **Step 4: Commit only implementation files**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git add app/worker.py tests/__init__.py tests/test_worker_llm_retry.py
|
||||
git commit -m "fix: retry malformed LLM JSON responses"
|
||||
```
|
||||
|
||||
Expected: the commit contains exactly the worker change and two test files; unrelated passkey/admin work remains unstaged.
|
||||
|
||||
### Task 3: Push and verify the Forgejo deployment
|
||||
|
||||
**Files:**
|
||||
- No additional file changes.
|
||||
|
||||
- [ ] **Step 1: Push `main`**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git push origin main
|
||||
```
|
||||
|
||||
Expected: Forgejo accepts the new implementation commit on `main`.
|
||||
|
||||
- [ ] **Step 2: Wait for the workflow and verify public health**
|
||||
|
||||
Poll the Forgejo workflow until it completes, then run:
|
||||
|
||||
```bash
|
||||
curl --fail --silent --show-error https://dzen.nstarikov.ru/health
|
||||
```
|
||||
|
||||
Expected: HTTP success with the application's healthy response.
|
||||
|
||||
- [ ] **Step 3: Verify the running worker contains the fix**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
ssh -o BatchMode=yes nstarikov "cd /var/www/dzen.nstarikov.ru && docker compose ps && docker compose exec -T worker sed -n '685,705p' /app/app/worker.py"
|
||||
```
|
||||
|
||||
Expected: `api`, `worker`, `beat`, and `redis` are running; the displayed worker code has `payload = generate_article_payload(...)` below `try:`.
|
||||
|
||||
### Task 4: Reprocess production video 213 and verify the user-visible result
|
||||
|
||||
**Files:**
|
||||
- No source changes.
|
||||
|
||||
- [ ] **Step 1: Record the production baseline**
|
||||
|
||||
Run a read-only query in the worker container for video status, frame count, and non-rejected article count:
|
||||
|
||||
```bash
|
||||
ssh -o BatchMode=yes nstarikov 'cd /var/www/dzen.nstarikov.ru && docker compose exec -T worker python -c '\''import sqlite3; c=sqlite3.connect("/app/data/dzen.sqlite3"); print(c.execute("select status, progress_stage, error_message from videos where id=213").fetchone()); print("frames", c.execute("select count(*) from frames where video_id=213").fetchone()[0]); print("articles", c.execute("select count(*) from articles where video_id=213 and status != \\"rejected\\"").fetchone()[0])'\'''
|
||||
```
|
||||
|
||||
Expected: status is currently `error`; save the printed frame/article counts for comparison.
|
||||
|
||||
- [ ] **Step 2: Queue the same description-selected chapters**
|
||||
|
||||
Run inside the production worker container:
|
||||
|
||||
```bash
|
||||
ssh -o BatchMode=yes nstarikov 'cd /var/www/dzen.nstarikov.ru && docker compose exec -T worker python -c '\''from app.chapters import chapter_to_payload, parse_video_chapters; from app.database import SessionLocal; from app.models import Video; from app.worker import process_video; s=SessionLocal(); v=s.get(Video, 213); chapters=[chapter_to_payload(c) for c in parse_video_chapters(v.description, v.duration_seconds)]; selected=[c for c in chapters if c["selected"]]; print("selected chapters", len(selected)); print("task", process_video.delay(213, selected).id); s.close()'\'''
|
||||
```
|
||||
|
||||
Expected: `selected chapters 9` and a Celery task id are printed.
|
||||
|
||||
- [ ] **Step 3: Monitor the real production job**
|
||||
|
||||
Poll the same video row and progress log at intervals no longer than 30 seconds. Continue until status becomes `drafted` or `error`.
|
||||
|
||||
Expected success: status becomes `drafted`, progress reaches 100, and the log says how many articles were created. If malformed JSON recurs, the log must show `Повторная редактура 2/3` before another model attempt; if all attempts fail, it must also show `3/3` before the final error.
|
||||
|
||||
- [ ] **Step 4: Verify articles and frame-count impact**
|
||||
|
||||
Run a final read-only query listing non-rejected article ids/titles/statuses and the frame count for video `213`.
|
||||
|
||||
Expected: at least one non-rejected draft article exists for the selected chapters. Report the before/after frame counts explicitly because reprocessing currently appends frame records and frame lifecycle is outside this fix.
|
||||
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
# LLM JSON Retry Fix Design
|
||||
|
||||
## Context
|
||||
|
||||
Production video `#213` failed while generating the first of nine chapter articles. The LLM response could not be parsed as JSON and produced `Expecting ',' delimiter` at line 11, column 17.
|
||||
|
||||
The worker already has a three-attempt quality rewrite loop and a prompt that explicitly asks for corrected JSON after a parse failure. However, `generate_article_payload()` calls the LLM and parses its response before entering the loop's `try` block. The resulting `RuntimeError` therefore bypasses the existing retry handler and aborts processing after the first malformed response.
|
||||
|
||||
## Scope
|
||||
|
||||
- Move `generate_article_payload()` into the existing `try` block in `generate_articles_with_quality_retries()`.
|
||||
- Preserve the current limit of three quality rewrite attempts.
|
||||
- Preserve the existing JSON repair function and retry feedback prompt.
|
||||
- Add regression coverage proving that a malformed first response is retried and a valid second response succeeds.
|
||||
- Deploy through the existing Forgejo `main` workflow.
|
||||
- Re-run production video `#213` and verify that draft articles are created or, if all three LLM responses remain invalid, that the progress log records retries `2/3` and `3/3` before the final error.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not store raw LLM responses.
|
||||
- Do not add undocumented `response_format` parameters to the Timeweb request.
|
||||
- Do not refactor the article-generation pipeline or JSON repair heuristics.
|
||||
- Do not change the existing frame lifecycle during reprocessing; record the frame count before and after the production retry so this pre-existing behavior remains visible.
|
||||
- Do not modify unrelated passkey/authentication or admin changes already present in the worktree.
|
||||
|
||||
## Control Flow
|
||||
|
||||
For each quality attempt, the worker will call and parse the LLM response inside the existing exception boundary. A JSON parse `RuntimeError` matching the existing quality markers will set `feedback` and continue to the next attempt. The next prompt will include the current instruction to return one valid JSON object. A valid payload continues through the existing article validation path.
|
||||
|
||||
Network retries inside `call_llm()` remain separate from quality retries: transport and server failures follow the existing network retry policy, while syntactically invalid model content follows the three-attempt quality rewrite policy.
|
||||
|
||||
## Testing
|
||||
|
||||
A focused stdlib `unittest` test will replace `generate_article_payload()` with a deterministic fake and patch `append_progress()` to avoid accessing the real database:
|
||||
|
||||
1. First call raises `RuntimeError` containing the existing invalid-JSON marker.
|
||||
2. Second call returns a valid payload.
|
||||
3. `articles_from_payload()` is patched to return a sentinel successful result so the test remains focused on retry control flow.
|
||||
4. The test asserts that two payload-generation calls occurred, the second call received the first error as `quality_feedback`, and article generation returned the successful result.
|
||||
|
||||
Existing syntax/tests will be run without relying on the real LLM service.
|
||||
|
||||
## Production Verification
|
||||
|
||||
After pushing only the task files, wait for the Forgejo deployment, verify `/health`, confirm the running worker contains the deployed fix, record the current frame count for video `#213`, and requeue it. Completion requires checking the video's production status, progress log, resulting article records, and final frame count; deployment health alone is insufficient.
|
||||
0
dzen-assistant/tests/__init__.py
Normal file
0
dzen-assistant/tests/__init__.py
Normal file
41
dzen-assistant/tests/test_worker_llm_retry.py
Normal file
41
dzen-assistant/tests/test_worker_llm_retry.py
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import unittest
|
||||
from unittest.mock import call, patch
|
||||
|
||||
from app.models import Video
|
||||
from app.worker import generate_articles_with_quality_retries
|
||||
|
||||
|
||||
class GenerateArticlesWithQualityRetriesTest(unittest.TestCase):
|
||||
@patch("app.worker.append_progress")
|
||||
@patch("app.worker.articles_from_payload")
|
||||
@patch("app.worker.generate_article_payload")
|
||||
def test_retries_invalid_json_and_passes_feedback(
|
||||
self,
|
||||
generate_article_payload_mock,
|
||||
articles_from_payload_mock,
|
||||
append_progress_mock,
|
||||
):
|
||||
error = "LLM вернул невалидный JSON: Expecting ',' delimiter в строке 11, колонке 17."
|
||||
valid_payload = {"articles": [{"title": "Готовая статья"}]}
|
||||
expected_articles = [object()]
|
||||
generate_article_payload_mock.side_effect = [RuntimeError(error), valid_payload]
|
||||
articles_from_payload_mock.return_value = expected_articles
|
||||
video = Video(id=213, title="Тест", description="", external_id="test", source_url="")
|
||||
|
||||
result = generate_articles_with_quality_retries(video, "Текст", [])
|
||||
|
||||
self.assertEqual(result, expected_articles)
|
||||
self.assertEqual(generate_article_payload_mock.call_count, 2)
|
||||
self.assertEqual(
|
||||
generate_article_payload_mock.call_args_list,
|
||||
[
|
||||
call(video, "Текст", chapter=None, quality_feedback=""),
|
||||
call(video, "Текст", chapter=None, quality_feedback=error),
|
||||
],
|
||||
)
|
||||
append_progress_mock.assert_called_once()
|
||||
articles_from_payload_mock.assert_called_once_with(video, valid_payload, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue