Building a Personal AI Workflow from Scratch: Capability Composition and Practical Implementation

    This article explains how to turn high-frequency AI tasks into reusable capability modules and connect them reliably through APIs, workflow orchestration, and templated outputs. Using subtitle translation with automatic dubbing and vocabulary flashcard generation as examples, it covers a four-layer architecture, quality gates, reliable LLM API usage, cost and security controls, observability, common pitfalls, and a practical roadmap from MVP to a stable personal productivity tool.

    Building a Personal AI Workflow from Scratch: Capability Composition and Practical Implementation

    The real value of practical everyday AI tools does not lie in how many applications you install. It lies in whether you can break high-frequency tasks into reusable capability modules and connect them reliably through APIs, workflow orchestration, and templated outputs. This article does not focus on a single software product. Instead, it starts from two representative scenarios—subtitle translation with automatic dubbing, and vocabulary flashcard generation—to show how to build a personal AI workflow with general technical approaches. It also addresses the quality, cost, security, and observability issues that are easy to overlook in engineering implementation.

    1. Establish Criteria First: Which Scenarios Deserve a Workflow

    Not every AI need is worth automating. An AI workflow suitable for long-term daily use usually meets the following conditions:

    1. High frequency or high time cost: for example, long-video organization, multilingual content processing, learning material creation, and meeting note archiving.
    2. Relatively clear inputs and outputs: video in, subtitles and audio out; a word in, a structured card out.
    3. Errors can be detected and corrected: subtitles have timeline and semantic checkpoints, and card fields can be validated through templates and rules.
    4. Costs can be controlled: caching, chunked processing, model tiering, and human review can reduce expenses.
    5. Results can accumulate as assets: glossaries, templates, prompt versions, evaluation samples, and user feedback can all be reused.

    A simplified formula can describe the task:

    1. Task = input specification + processing pipeline + output contract + quality gates + fallback strategy + observability metrics

    The “output contract” is especially important. Many demos can run successfully, but once they enter daily use, they become unusable because of unstable model output formats, overly long subtitles, dubbing misalignment, image layout failures, and other issues. The focus of engineering is not to make the model occasionally produce impressive results, but to keep results controllable in most cases.

    2. Overall Architecture: Split the Application into Four Layers

    To make the workflow maintainable, it should be split into at least four layers.

    2.1 Interaction Layer

    This layer receives user input and displays results, such as uploading a video, entering a word, selecting a target language, specifying a card style, and viewing task progress. The interaction layer should be as thin as possible. Complex logic should not be placed in the page; instead, tasks should be submitted to the backend through task interfaces.

    2.2 Orchestration Layer

    This layer manages task states and workflow nodes, such as “extract audio track—recognize speech—translate—adapt timeline—synthesize—mix—export.” The orchestration layer can use a state machine or queued task model and record the input, output, duration, cost, and failure reason of each step.

    A stable task state can be designed as:

    1. pending -> running -> succeeded
    2. -> failed
    3. -> need_review

    Supporting retries, pauses, manual revisions, and partial reruns is closer to real needs than “fully automatic with one click.”

    2.3 Capability Adapter Layer

    This layer wraps speech recognition, translation, speech synthesis, LLM generation, image rendering, and other capabilities into unified interfaces, avoiding tight coupling between business code and a specific service. Example interfaces can be abstracted as:

    1. asr(audio) -> segments
    2. translate(segments, glossary, targetLang) -> translatedSegments
    3. tts(text, voice, speed) -> audio
    4. llm(prompt, outputSchema) -> structuredResult
    5. render(template, data) -> image

    Inside the interfaces, handle authentication, timeouts, retries, rate limiting, and error normalization. In this way, even if the underlying service is replaced, only the adapter layer is affected.

    2.4 Data and Governance Layer

    This layer includes task records, glossaries, templates, prompt versions, evaluation samples, caches, logs, and metrics. Governance needs to address permissions, key management, data masking, retention periods, and auditing. When audio, video, and user text are involved, the principle of data minimization should be adopted by default: retain only the information needed to complete the task.

    3. Scenario One: Subtitle Translation and Automatic Dubbing

    The original requirement is to “automatically recognize video subtitles, translate them, and further generate Chinese dubbing.” In actual implementation, this is not a single API call but a processing chain containing multiple quality gates.

    3.1 Standard Processing Pipeline

    1. Video input
    2. -> Extract audio track
    3. -> Speech recognition (preserve timestamps)
    4. -> Sentence segmentation, punctuation restoration, and text cleaning
    5. -> Context-aware translation with terminology constraints
    6. -> Subtitle length and duration adaptation
    7. -> Speech synthesis and speed control
    8. -> Volume balancing, background ducking, and mixing
    9. -> Export subtitle file, dubbing file, and final video

    An illustrative pseudocode example is as follows:

    1. function subtitle_and_dub(video, targetLang, glossary):
    2. audio = extractAudio(video)
    3. transcript = recognizeSpeech(audio)
    4. segments = normalizeSegments(transcript)
    5. // Add punctuation, merge short sentences, split overly long sentences,
    6. // and fix overlapping timestamps
    7. translated = translateSegments(
    8. segments,
    9. targetLang,
    10. glossary,
    11. contextWindow = surrounding sentences
    12. )
    13. adjusted = fitSubtitleRules(
    14. translated,
    15. maxCharsPerLine,
    16. minDisplayMs,
    17. maxDisplayMs,
    18. readingSpeedLimit
    19. )
    20. voice = selectVoice(targetLang, style)
    21. speech = synthesize(adjusted, voice)
    22. mixed = mixAudio(audio, speech, backgroundDucking = true)
    23. return package(video, adjusted, mixed)

    The parameters here are illustrative values. In practice, they should be adjusted according to the target language, platform specifications, and audience habits.

    3.2 Key Quality Points

    First, sentence segmentation and timelines. You cannot directly translate an entire block of text and then split it crudely; otherwise, subtitles and speech are very likely to become misaligned. A more reliable approach is to segment by semantics and pauses first, translate each segment with context, and finally adjust display duration dynamically under reading-speed constraints.

    Second, terminology and context. Technical content, course content, and brand guidelines often require glossaries. During translation, numbers, variable names, placeholders, and code snippets should be preserved, and the model should not freely rewrite them. For ambiguous sentences, the model can be asked to provide structured results, such as “preserve terms, give a translation, and mark uncertain items.”

    Third, subtitle readability. Subtitles are not a simple stack of translated text. Line length, on-screen duration, two-line limits, and punctuation density all affect the viewing experience. Hard rules are needed: overly long subtitles must be split, overly short ones must be merged, and overlapping timelines must be resolved.

    Fourth, dubbing naturalness. Speech synthesis needs sentence segmentation and control over pauses and speed to avoid a mechanical feel caused by synthesizing an entire block at once. For segments that significantly exceed the target duration, adjust speed first, and only then consider compressing the wording. Volume also needs to be balanced between background audio and dubbing, avoiding situations where “dubbing covers the original sound” or “background audio suddenly becomes louder and quieter.”

    Fifth, where human review belongs. Full-process review-free operation is not recommended. At minimum, provide “glossary preview, list of overly long subtitles, low-confidence recognition segments, and segments with large duration deviations” for human inspection. This focuses effort on high-risk segments instead of reviewing every sentence again.

    3.3 Engineering Details

    • Segment caching: when the same video is rerun, only failed or modified segments are processed again, avoiding repeated billing.
    • Idempotent tasks: each task and segment uses a stable identifier, so retries do not produce duplicate outputs.
    • Partial failure recovery: if translation of segment 7 fails, the results of the first 6 segments should not be discarded.
    • Asynchronous execution: long-video processing should enter a queue, and the page should only show progress and stage status.
    • Multiple export results: subtitle files, audio-only dubbing files, dubbed final videos, and intermediate editing drafts should be saved separately for later revision.

    4. Scenario Two: From Word to Memory Card

    The second representative scenario is “input a word and output a well-formatted memory card.” This requirement looks simple, but it actually contains three different problems: content generation, structured validation, and visual rendering. It should not be handed entirely to an LLM to “draw it in one pass.”

    1. Word input
    2. -> Query basic definitions from a dictionary or knowledge source
    3. -> LLM completes example sentences, collocations, mnemonics, and image prompts
    4. -> Validate structured JSON
    5. -> Review facts and format
    6. -> Render image with a template
    7. -> Cache and return

    An illustrative field design is as follows:

    1. {
    2. "word": "example",
    3. "phonetic": "/.../",
    4. "definitions": [
    5. { "partOfSpeech": "n.", "meaning": "definition in target language" }
    6. ],
    7. "examples": [
    8. { "en": "English sentence.", "zh": "Chinese translation." }
    9. ],
    10. "collocations": ["common collocation"],
    11. "mnemonic": "memory hint",
    12. "imagePrompt": "description for background or illustration only",
    13. "tags": ["difficulty", "topic"],
    14. "review": { "status": "pending" }
    15. }

    4.2 Why Content Generation and Image Rendering Should Be Separated

    If an image generation model is asked to directly generate a card with text, the most common problems are spelling errors, uncontrolled layout, missing fields, and inability to modify parts of the card. A more reliable approach is:

    • Use an LLM to generate structured learning content.
    • Use a fixed template for text layout.
    • Use image generation only when needed to create text-free backgrounds or illustrations.
    • Use a deterministic rendering pipeline to output the image, ensuring font size, spacing, contrast, and readability.

    Image generation is suitable for “visual atmosphere,” not for carrying precise text. For learning cards, accuracy takes priority over decoration.

    4.3 Quality Gates

    A card should be checked for at least the following:

    1. Whether required fields are complete.
    2. Whether phonetic transcription, part of speech, and definitions correspond.
    3. Whether example sentences contain the target word and whether translations are consistent.
    4. Whether there are obvious factual errors or low-quality boilerplate.
    5. Whether text length exceeds template capacity.
    6. Whether font, contrast, and spacing meet readability requirements.

    Three states can be set: “auto pass,” “needs review,” and “reject.” For daily use, it is recommended to store model output first and then render it with a template. In this way, even if rendering fails, the content can still be reused and corrected.

    5. The Core of Getting Started with LLM APIs: Reliable Calls Matter More Than a Successful Run

    Whether for subtitle translation or card generation, LLM APIs are called behind the scenes. Making a single request work quickly is not difficult. The hard part is long-term stability, controllable cost, and evaluable results.

    5.1 Keys and Permissions

    API keys should only be stored on the server or in a controlled key management environment. They should not be written into frontend code, screenshots, logs, or public repositories. Different tasks should use different credentials and permissions, following the principle of least privilege.

    5.2 Unified Adapters and Prompt Versions

    Business code should not scatter prompts everywhere. It is better to establish a unified call layer:

    1. request = {
    2. taskType,
    3. promptTemplate,
    4. promptVersion,
    5. input,
    6. outputSchema,
    7. budget
    8. }

    Prompt templates should have version numbers. Outputs should use structured contracts whenever possible and undergo format validation. When parsing fails, trigger one repair retry first, then move to human review.

    5.3 Timeouts, Retries, and Rate Limiting

    Long text and audio/video tasks are prone to timeouts. Large tasks should be split into small segments, with exponential backoff, maximum retry counts, circuit breaking, and rate limiting. For scenarios that may incur duplicate billing, record request identifiers and enable idempotency control. Synchronous interfaces are suitable for short tasks, while long tasks should be converted into asynchronous queues.

    5.4 Cost Control

    Common methods include:

    • Use caching for identical inputs.
    • Choose different capability tiers based on content difficulty.
    • Screen with rules or smaller models first, then pass results to larger models.
    • Limit context length and include only relevant segments.
    • Rerun only failed segments.
    • Record input length, output length, duration, and cost for each task.

    Cost optimization is not simply about always using smaller models. It is about letting “expensive capabilities” handle only the segments that truly need them.

    5.5 Security and Compliance

    When processing user videos, meeting audio, and learning materials, clearly define data usage and retention periods. Sensitive content can be masked before entering the model. Logs should avoid recording full original text. Export and sharing features should include access control. For content that may be published externally, content safety review and human confirmation should also be included.

    6. Key Design Decisions for Workflow Orchestration

    A workflow that can be used long term needs to be “recoverable, measurable, and reversible.”

    6.1 States and Checkpoints

    Save a checkpoint after each node completes. For example, if speech recognition is complete but translation fails, the retry should start from the translation node rather than extracting the audio track again. Checkpoints should include input summaries, output locations, version information, and error codes.

    6.2 Observability Metrics

    At minimum, record:

    • Task success rate and distribution of failure reasons.
    • Average duration and tail latency of each node.
    • Cost per task and cache hit rate.
    • Subtitle over-length rate and timeline conflict rate.
    • Card field completeness rate and human review pass rate.
    • User modification ratio and secondary generation rate.

    These metrics are more useful for guiding optimization than “the results feel good.”

    6.3 Evaluation Sets and Regression Testing

    Prepare a fixed set of samples: clear recordings, noisy recordings, long sentences, polysemous words, technical terms, short words, and rare words. Each time prompts, models, or rules are adjusted, run the evaluation set and observe whether quality has degraded. For subtitle scenarios, check terminology adherence rate, duration deviation, and over-length ratio. For card scenarios, check field completeness rate, example quality, and rendering success rate.

    6.4 Human Intervention

    Full automation is not always optimal. Reasonable human-machine collaboration means the machine generates at scale, while humans handle only low-confidence and high-risk results. This improves efficiency while reducing the risk of error propagation.

    7. More Reusable Everyday Combinations

    The methods above can be transferred to many everyday scenarios:

    1. Meeting and course organization: speech recognition produces a transcript, then generate summaries, action items, and section indexes, followed by human proofreading.
    2. Multilingual content publishing: connect transcription, translation, terminology validation, dubbing, and subtitle export into a pipeline, retaining intermediate drafts for revision.
    3. Long-form reading assistance: after document parsing, perform segmented summaries, key question extraction, and question answering, with constraints on cited sources.
    4. Paper material structuring: obtain text through OCR, extract fields with structured output, and then validate rules before storing in a database.
    5. Learning material production: combine dictionary information, example sentences, collocations, and memory hints into templated cards and batch-export review lists.
    6. Data organization and annotation: have the model extract information according to fixed fields, then use scripts to validate enum values, date formats, and required items.

    The common point of these scenarios is: use deterministic processes as a safety net first, and place the LLM where language understanding and generation are most needed.

    8. Common Pitfalls and Governance Checklist

    1. Treating demo results as production-ready: one success does not mean stability. Structured output, validation, and fallback must be established.
    2. Ignoring timeline and layout constraints: subtitles, dubbing, and images all have hard format rules and cannot rely entirely on the model.
    3. Prompts scattered and untraceable: prompts should be versioned and templated, and their correspondence with results should be recorded.
    4. No budgets or rate limits: long text, batch tasks, and retries can amplify costs, so budgets and alerts should be set.
    5. Lack of failure recovery: long tasks must support partial reruns and checkpoints.
    6. Delayed privacy handling: keys, original text, audio, and exported files must all be included in permission and lifecycle management.
    7. Testing only “good samples”: use evaluation sets containing noise, long sentences, technical terms, and abnormal inputs for regression.
    8. Over-pursuing full automation: low-confidence results should enter human review rather than being published directly.

    9. Roadmap from MVP to a Stable Tool

    1. Choose a single high-frequency task: start with either “short-video subtitle translation” or “word card generation”; do not spread across multiple scenarios at the beginning.
    2. Define input and output contracts: specify which formats are supported, which files are output, and how failures are reported.
    3. Wrap the capability adapter layer: isolate recognition, translation, synthesis, generation, and rendering to avoid binding business logic to a specific interface.
    4. Implement asynchronous tasks and checkpoints: ensure recoverability first, then pursue speed.
    5. Build an evaluation set and a human review console: use fixed samples to measure quality and use low-confidence lists to guide human intervention.
    6. Add observability and cost dashboards: record duration, success rate, cost, and quality metrics.
    7. Expand scenarios gradually: after one pipeline is stable, reuse it for meeting organization, multilingual publishing, or learning material production.

    At the deployment and operations layer, depending on actual compliance requirements and team conditions, you can choose general-purpose categories from Baidu AI Cloud, such as general computing, object storage, message queues, logging, and monitoring, and incorporate key hosting, access control, audit alerts, and data lifecycle management into the design. Infrastructure is only the hosting layer. What truly determines workflow usability is still clear interface contracts, reliable failure recovery, strict output validation, and continuous quality evaluation.

    Conclusion

    A practical everyday AI tool should not be an isolated “magic button.” It should be a set of composable capabilities: recognition, understanding, translation, generation, synthesis, rendering, and validation. Build workflows around real tasks, place LLMs in the right positions, use rules to handle deterministic problems, use human review to catch high-risk results, and control cost and stability through caching, queues, versioning, and monitoring. Only then can a one-off demo become a long-term personal productivity system.