# General Translation Overview: Использование ИИ-агентов для написания кода URL: https://generaltranslation.com/ru/docs/overview/for-coding-agents.mdx --- title: Использование ИИ-агентов для написания кода description: Как использовать ИИ-агентов для написания кода и LLMs с General Translation, направляя их на машиночитаемую документацию, MCP-сервер и наше руководство по быстрому подключению агента. --- General Translation создана для работы с ИИ-агентами для написания кода и LLMs. Библиотеки имеют открытый исходный код, конфигурация предсказуема, а документация публикуется в машиночитаемых форматах. Агент, такой как Cursor, Claude Code или Copilot, может добавить и запустить General Translation за вас, используя точный и актуальный контекст. *Для полностью автоматизированной локализации, которая сама открывает pull request, используйте наш специализированный агент [Locadex](/docs/platform/locadex/quickstart), а не собственного агента.* ## Руководство по быстрому подключению агента [#agent-guide] Дайте своему агенту всё необходимое одной вставкой. Скопируйте приведённое ниже руководство в `AGENTS.md` (или `CLAUDE.md`, правило Cursor либо файл инструкций вашего инструмента) в корне проекта, и ваш агент сможет корректно добавить и запустить General Translation. Используйте кнопку копирования в правом верхнем углу блока. ````markdown title="AGENTS.md" # General Translation — agent guide Instructions for AI coding agents adding [General Translation](https://generaltranslation.com) to a project. General Translation is a full-stack localization product: open-source i18n libraries plus a CLI that translate an app and its content into any language. Follow these rules when internationalizing code or wiring up translations. ## What to use Pick the package that matches the stack: - **Next.js (App Router or Pages Router)** → `gt-next` - **React (SPA, e.g. Vite)** → `gt-react` - **Node.js server** → `gt-node` - **Any JavaScript runtime, or lower-level control** → `generaltranslation` (the Core library) - **Translating content files (JSON, MDX, YAML, and more) or running translation in CI** → the `gt` CLI All of these are free and open-source. The libraries work with or without a General Translation account; an API key unlocks on-demand translation in development and the hosted translation API. ## Setup Prefer the wizard. From the project root, run: ```bash npx gt init ``` It installs the right library and the `gt` CLI, wires up the framework (for Next.js, adds `withGTConfig` and `GTProvider`), creates `gt.config.json`, and generates API credentials. For manual setup, install the packages yourself: ```bash npm install gt-next # or gt-react / gt-node / generaltranslation npm install -D gt ``` Then create `gt.config.json` in the project root — this is the single source of truth for locales: ```json { "defaultLocale": "en", "locales": ["es", "fr", "ja"], "files": { "gt": { "output": "public/_gt/[locale].json" } } } ``` - `defaultLocale` — the language the source is written in. - `locales` — the languages to translate into. - `files.gt.output` — where the CLI writes translation files (`[locale]` is replaced per language). Add this directory to `.gitignore`; the files are generated. Set API credentials as environment variables (in `.env.local` for Next.js, `.env` otherwise): ```bash GT_API_KEY="gtx-dev-..." # gtx-dev- in development, gtx-api- in production/CI GT_PROJECT_ID="..." ``` Never commit `GT_API_KEY`, expose it to the browser, or prefix it with `NEXT_PUBLIC_`. ## Core usage Wrap user-facing JSX in ``. Write source copy directly — no translation keys needed: ```tsx import { T } from 'gt-next'; // or 'gt-react' // Everything inside is translated as a unit

Welcome to my app

; ``` Use `useGT()` for standalone strings (placeholders, `aria-label`, `alt`, button labels). `useGT()` returns the translation function directly: ```tsx import { useGT } from 'gt-next'; const gt = useGT(); // ✅ correct // const { gt } = useGT(); // ❌ wrong — useGT returns the function, not an object ; ``` In async App Router components, use `getGT` instead. `gt-next/server` does not work with the Pages Router: ```tsx import { getGT } from 'gt-next/server'; const gt = await getGT(); ``` Wrap dynamic or private values (names, emails, IDs) in `` so they are not translated and never sent to the API. Use ``, ``, and `` for values that should be reformatted but not translated: ```tsx import { T, Var } from 'gt-next'; // Generates one translation, keeps the name unchanged Hello, {name}! ; ``` For Node.js servers, initialize once and resolve translations per request: ```js import { initializeGT, withGT, getGT } from 'gt-node'; initializeGT({ defaultLocale: 'en', locales: ['en', 'es', 'fr'] }); // wrap handlers in withGT(locale, ...); then `const gt = await getGT()` inside them ``` Keep all locale configuration in `gt.config.json` — do not scatter locale lists across the codebase. ## Commands | Command | When to run | | --- | --- | | `npx gt init` | Once, to set up a project (installs deps, configures the framework, creates `gt.config.json`, generates credentials). | | `npx gt configure` | To create or update `gt.config.json` (locales and files) without the full wizard. | | `npx gt auth` | To generate or refresh API credentials. | | `npx gt translate` | To translate the project via the General Translation API. Run in CI **before** building for production. | | `npx gt generate` | To create translation file templates to translate manually (no API key needed). | Add translation to the production build so translations stay current, for example: `"build": "npx gt translate && next build"`. ## Rules — do and don't Do: - Wrap every new piece of user-facing copy in `` (or `useGT()`/`getGT()` for standalone strings) as you write it. - Run `npx gt translate` before committing or building for production so new copy is translated. - Keep the locale list in `gt.config.json` only. - Wrap dynamic and private values in ``, and add `context` when a string is ambiguous. Don't: - Hardcode already-translated strings in the source, or add per-language `if`/`switch` branches — translate the source copy instead. - Hand-edit generated translation files (the CLI overwrites them). - Commit `GT_API_KEY` or expose it to the client. - Duplicate the locale configuration outside `gt.config.json`. ## Links - [`llms.txt`](/llms.txt) — краткий машиночитаемый индекс документации. - [`llms-full.txt`](/llms-full.txt) — полное содержимое документации для инструментов, способных загружать больший контекст. - [`sitemap.xml`](/sitemap.xml) — карта всех опубликованных страниц. - Quickstart'ы: [React](/docs/react/react-quickstart), [Node](/docs/node/quickstart), [Core library](/docs/platform/core/quickstart) и [CLI](/docs/cli/quickstart). - [Ключевые концепции](/docs/overview/key-concepts) — локали, context и статический vs. динамический контент. ```` ## Дайте агентам доступ к документации [#point-agents] Предоставьте агенту прямой доступ к документации, чтобы его ответы оставались точными. General Translation публикует несколько машиночитаемых точек входа в корневом каталоге сайта и в `/docs` на хосте документации: * [`llms.txt`](/llms.txt) — краткий указатель документации в стиле [llmstxt.org](https://llmstxt.org/). * [`llms-full.txt`](/llms-full.txt) — полное содержимое документации в одном файле, за исключением сгенерированного справочника OpenAPI. * [`sitemap.xml`](/sitemap.xml) — машиночитаемая карта всех опубликованных страниц. Хост документации также отдает эти файлы по адресам `/docs/llms.txt` и `/docs/llms-full.txt`. Каждая страница документации также доступна в формате **raw Markdown**: добавьте `.md` или `.mdx` к URL любой страницы (например, `/docs/cli/quickstart.mdx`), чтобы получить чистый исходник вместо того, чтобы разбирать отрендеренный HTML. Чтобы добавить документацию в контекст, вставьте URL страницы документации или ссылку на `llms.txt` в контекст агента либо добавьте документацию как источник в инструментах, которые поддерживают индексацию документации. ## MCP-сервер [#mcp] General Translation предоставляет сервер [Model Context Protocol](https://modelcontextprotocol.io) (MCP), который позволяет агентам напрямую обращаться к документации. Он доступен в двух вариантах: * **Локальный (stdio)** — опубликованный npm-пакет [`@generaltranslation/mcp`](https://www.npmjs.com/package/@generaltranslation/mcp), который запускается на вашем компьютере через `npx`. Лучше всего подходит для инструментов, которые поддерживают постоянное подключение, таких как Cursor и Claude Code. * **Удалённый (HTTP/SSE)** — размещённый эндпоинт по адресу `https://mcp.gtx.dev`. Используйте SSE-эндпоинт только в том случае, если ваш инструмент не поддерживает streamable HTTP. Настройте подключение, используя транспорт, который поддерживает ваш инструмент. Формат конфигурации одинаков для всех инструментов — добавьте его в конфигурационный файл MCP вашего инструмента (например, `.mcp.json`): ```json title=".mcp.json" { "mcpServers": { "generaltranslation": { "command": "npx", "args": ["-y", "@generaltranslation/mcp@latest"] } } } ``` ```json title=".mcp.json" { "mcpServers": { "generaltranslation": { "type": "streamable-http", "url": "https://mcp.gtx.dev" } } } ``` ```json title=".mcp.json" { "mcpServers": { "generaltranslation": { "type": "sse", "url": "https://mcp.gtx.dev/sse" } } } ``` После подключения попросите своего агента использовать MCP-сервер `generaltranslation`. *Пример: "Используй MCP-сервер generaltranslation, чтобы объяснить, как использовать компонент [``](/docs/react/reference/components/t)."* ## Советы для отдельных редакторов [#editor-tips] Большая часть настройки одинакова для всех агентов; вот лишь несколько моментов, где рекомендации отличаются. * **Cursor** — зарегистрируйте MCP-сервер, затем попросите его «использовать инструмент `generaltranslation`». Добавьте документацию как источник или укажите в запросе `/llms.txt`. * **Claude Code** — автоматически читает корневой `AGENTS.md`, поэтому достаточно добавить [руководство по быстрому подключению агента](#agent-guide) в `AGENTS.md` вашего проекта, чтобы задать нужный контекст. Зарегистрируйте MCP-сервер и попросите его «использовать MCP-сервер `generaltranslation`». * **Copilot** — поместите общие инструкции для всего репозитория в файл инструкций (например, `.github/copilot-instructions.md`) и укажите там `/llms.txt` из документации. ## Рекомендации [#best-practices] Агенты хорошо справляются с механической i18n-работой, но качество перевода и конфигурацию всё равно должен проверять человек. Используйте такое разделение: * **Поручите агенту:** оборачивать пользовательский текст в [``](/docs/react/reference/components/t), добавлять [`useGT()`](/docs/react/reference/hooks/use-gt) для отдельных строк, подготавливать `gt.config.json` и запускать [`npx gt init`](/docs/cli/reference/commands/init). * **Проверяйте вручную:** [контекст перевода](/docs/overview/key-concepts#context) (Glossary и директивы), который создаёт агент, конфигурацию локалей (`defaultLocale` и `locales`), а также то, что динамические или приватные значения обернуты в [``](/docs/react/reference/components/var). * **Никогда не позволяйте агенту:** вручную редактировать сгенерированные файлы перевода или хардкодить уже переведённые строки вместо перевода исходного текста через CLI.