[BACK-AI-05] FastAPI Service Development for AI Text Structuring via Qwen Model
AI Components (AI Service)
NoteTask Brief
- Repository / Component:
ai_voice_text_parser. - Language: Python 3.10+ (FastAPI, Pydantic, Requests).
- Task Type: Backend (AI Structuring).
- Status: Ready for Implementation
Task Description
The raw text received after transcribing an audio recording (via Whisper) is a solid, unformatted string. It is necessary to implement a FastAPI-based microservice that forwards this text to the local qwen2.5:3b model via the Ollama API to extract product names, weights, and portions, and generate a valid JSON structure.
Step-by-Step Instructions (Python)
- Implement the Request DTO Model: Design a Pydantic model named
PromptRequestcontaining a mandatory string fieldprompt(where the Go service will pass the raw text along with the system prompt instruction). Fix themodel="qwen2.5:3b",stream=False, andformat="json"fields by default. - Routing and Processing: Create a
POST /api/generateendpoint. Implement request forwarding to Ollama with a strict timeout of25seconds (timeout=25). - Cleaning and Deserialization: Apply markdown tag cleaning for ```
jsoncode blocks usingre.sub, then parse the sanitized string into a true JSON object usingjson.loads. - Failure Handling and Moderation Routing (Fallback):
- When catching
json.JSONDecodeErrorexceptions or timeouts, invoke thefallback_responsefunction. - Modify the default response contract: return a structure containing parameters
"status": "invalid","receipt_no": "VOICE-PARSER-FAIL", and a text description for"moderation_reason". This allows the Go backend to recognize that the AI failed and route the transaction to a queue for manual verification.
- When catching