My First Project with an AI Coding Tool: Building a Custom Translator
This article walks through building a custom text translation tool as the first project with an AI coding assistant. It covers how to turn a vague pain point into structured requirements, why a four-layer architecture (capture, pre-processing, model invocation, and rendering) keeps the tool easy to modify, and how to solve key engineering challenges such as protecting code blocks and placeholders, chunking long text, enforcing glossary consistency, caching results, and handling failures. It also details non-negotiable rules for API key storage and data boundaries, desktop packaging considerations, and a property-based testing strategy for validating non-deterministic LLM output. Readers will gain a reusable methodology for delivering small, extensible tools that preserve data privacy and architectural flexibility.
1. Background: Why the First Project Is Often a Translator
When developers get their hands on a powerful AI coding tool, their first instinct is usually not to refactor a business system, but to solve a high-frequency, low-complexity, yet extremely time-consuming personal pain point: reading foreign-language material. Technical documentation, open-source project READMEs, academic papers, and community discussions from overseas make up the bulk of a developer’s information input. Copying paragraph by paragraph into a web-based translator, switching windows back and forth, and losing context and formatting constantly interrupts focus.
This kind of need has three typical characteristics: frequent invocation, short individual tasks, and sensitivity to context and formatting. It is not enough to justify building a full product, but it does consume tens of minutes of focused attention every day. That makes it the ideal testing ground for validating “whether an AI coding tool can genuinely improve delivery efficiency”: the scope is controllable, feedback is immediate, and the cost of failure is low.
It is worth emphasizing that this article does not revolve around any specific third-party product. Instead, it abstracts the topic into a general engineering problem: how to build a localized, extensible text translation tool that respects data boundaries, based on general-purpose large model capabilities.
2. Breaking Down Requirements into Engineering Items
Before starting, convert the vague request into explicit items. This is the prerequisite for an AI coding tool to generate usable code in one pass.
- Input formats: plain text, Markdown, code comments, or subtitle files — and whether structure must be preserved.
- Output requirements: target language, tone (technically rigorous vs. conversational), and glossary constraints.
- Interaction patterns: always-on window, hotkey invocation, clipboard monitoring, or batch file processing.
- Non-functional requirements: startup speed, memory footprint, offline availability, key storage method, and retry on failure.
Write the items above into a structured requirement description and hand it to the AI coding tool to generate a skeleton. The hit rate will be significantly higher than a vague instruction like “help me build a translator.” A reusable prompt structure looks like this:
Role: Senior desktop client developerGoal: Implement the core translation service layer of a cross-platform desktop translation toolInput: Text to translate + source language + target language + optional glossaryOutput: Translation result + confidence hint + list of unrecognized termsConstraints: On network errors, retry with exponential backoff; if a single request's text exceeds a threshold, split it automatically;do not log user text to local filesPlease first provide the interface definitions and directory structure, then the implementation code and unit tests
3. Architecture: Layering and Extensibility First
For a translation tool to evolve over the long term, its core lies not in the interface but in the layered design of the “translation pipeline.” Four layers are recommended:
- Capture layer: handles clipboard monitoring, file reading, and text selection from windows, abstracting away differences between input sources.
- Pre-processing layer: language detection, structure protection (extracting code blocks and placeholders), length-based chunking, and duplicate cache lookup.
- Model invocation layer: uniformly encapsulates request construction, authentication, timeouts, retries, rate limiting, and usage statistics.
- Rendering layer: result insertion, diff highlighting, glossary validation hints, and history search.
The direct benefit of layering is an extremely low replacement cost: today you use a large model service from a cloud provider; tomorrow you switch to local inference or another general-purpose model service — you only replace the third layer’s implementation, and the rest of the code stays untouched. A schematic interface looks like this:
class Translator(Protocol):def translate(self, text: str, src: str, dst: str,glossary: dict[str, str] | None = None) -> TranslationResult: ...class CloudTranslator:"""Implementation based on a general-purpose LLM API, with retries and rate limiting"""def __init__(self, endpoint: str, key_ref: str,max_retries: int = 3, timeout: float = 20.0): ...
4. Key Challenges and Engineering Solutions
4.1 Structure Protection and the Placeholder Mechanism
What translation models most easily break are code blocks, variable names, Markdown links, and formatting placeholders. The common approach is to first replace these fragments with non-translatable sentinel markers, restore them after translation, and verify that the counts match:
import reTOKEN = "\u2063{}\u2063" # Use invisible characters to reduce the chance of the model rewriting themdef protect(text: str) -> tuple[str, dict[str, str]]:store, idx = {}, 0def repl(m):nonlocal idxkey = f"PH{idx}"store[key] = m.group(0)idx += 1return TOKEN.format(key)pattern = r"```[\s\S]*?```|`[^`]+`|\$\{[^}]+\}|\[[^\]]+\]\([^)]+\)"return re.sub(pattern, repl, text), storedef restore(text: str, store: dict[str, str]) -> str:for k, v in store.items():text = text.replace(TOKEN.format(k), v)return text
After restoration, a consistency assertion must be performed. If the placeholder counts do not match, treat it as a failure and retry, rather than showing the broken result directly to the user.
4.2 Chunking Long Text and Maintaining Context Consistency
Chunk at paragraph or sentence boundaries to avoid truncating mid-word. Carrying a “summary of the preceding context” as a hint between adjacent chunks can significantly improve the coherence of pronouns and terminology. Chunk size should be determined jointly by the model’s context window and the cost budget, and is best exposed as a configuration item rather than hard-coded.
4.3 Terminology Consistency
Maintain a domain glossary, explicitly instruct in the prompt that “the following translations must be used strictly,” and validate on the output side: if an unauthorized translation of a glossary entry appears in the output, trigger an automatic re-translation. This is the watershed for technical documentation translation quality.
4.4 Cost, Latency, and Caching
Use “normalized text hash + language pair + glossary version” as the cache key for a local cache; the hit rate in personal scenarios is usually quite substantial. Combined with batch request merging and concurrency limit control, you can balance perceived speed against invocation cost. Usage statistics should be aggregated and displayed locally, rather than relying on server-side billing.
4.5 Failures and Degradation
On network errors, retry with exponential backoff plus jitter. On persistent failure, degrade to “translate only the selected paragraph” or prompt the user to retry later — never clear the user’s original text. All exception paths must guarantee that the original text is not lost.
5. Keys and Data Boundaries: A Non-Negotiable Baseline
Personal tools most easily neglect security. Three hard recommendations:
- No plaintext keys: manage them via the operating system’s credential store or a permission-restricted configuration file in the user’s home directory; the interface should only show masked values.
- Log desensitization: by default, do not log the text to be translated; if diagnostics are needed, log only length, elapsed time, and status codes.
- Clear data flow: in the settings page, clearly inform the user that text will be sent to the configured model service endpoint, and provide a “local-only mode” switch.
If you use cloud-based general capabilities, you can combine object storage for history archiving, log services for auditing, and monitoring alerts for availability observation — all implemented through general product categories, without binding to any vendor’s proprietary interfaces.
6. Distribution and Installation Experience
The usability of a desktop tool depends half on the installation experience. Key practices include: providing an installer that does not require administrator privileges, bundling the runtime so users do not need to configure the environment separately, guiding first-time startup to fill in the endpoint and key, and offering a portable mode plus an auto-update channel. Version numbers, changelogs, and rollback strategies should also be part of the release process.
7. Validation: Covering Generative Uncertainty with Tests
Large model output is non-deterministic, so the testing strategy should shift toward “property-based testing” rather than “exact assertions”:
- Placeholder conservation test: construct samples containing code blocks and links, and assert they are fully identical after restoration.
- Glossary compliance test: assert that the translation of glossary entries is unique.
- Idempotency and length test: assert that results are concatenated in the correct order after automatic chunking of over-long input.
- Fault injection test: simulate timeouts and rate limiting, and assert that retry and degradation paths work.
8. Conclusion
The value of the first project built with an AI coding tool lies not in the product itself, but in completing a closed loop: structuring a pain point into requirements, mapping requirements into a layered architecture, covering uncertainty with tests and degradation, and writing security boundaries into the design. Once you master this methodology, whether it is a translator, a log analyzer, or a data cleaning tool, you can deliver quickly at the same pace. If you need stronger model services along with supporting data, logging, and monitoring capabilities, you can compose them on demand by general product category on Baidu AI Cloud — keeping the architecture replaceable is the true source of long-term efficiency.
