The post has been translated automatically. Original language: Russian
Let's say we already have our own knowledge base (documents, price lists, brochures, etc.) and we want to use it to conduct a dialogue with the user.
Then the AI agent's economy consists of two items: one-time indexing of the knowledge base and the cost of each client request. They are counted separately — we pay for the first one once when uploading documents, the second one scales with traffic.
One—time indexing is when documents are converted into embeddings (this is a set of numbers), and these embeddings are stored in a special vector database. The AI builds its responses based on this data.
The Anthropic API is charged for tokens. Input (prompt, system prompt, context) and output (model response) are paid separately, per million tokens (MTok).
The agent's system prompt sets the role, rules, and behavior of the model for the entire dialog.
An example of a system prompt:
You are an assistant to an insurance company. Answer politely and accurately.
Rules:
- ALWAYS get the cost of insurance by calling the get_price tool. Never calculate or invent sums yourself.
- Get answers to reference questions only from search_knownge_base. If there is no information, speak honestly.
- If the tool returns an error due to the lack of necessary data, ask a clarifying question.
- For complex legal issues, suggest contacting the manager.
- Never request or disclose the data of another client.The LLM models in the table below have a 5:1 price ratio of output tokens to input tokens, which simplifies planning: you know the cost of entry, multiply by five to exit.
Current prices (for 1M tokens, entry/exit):
| Model | Entrance | Exit | Role in the agent |
| Claude Haiku 4.5 | $1.00 | $5.00 | Adding context to chunks during indexing |
| Claude Sonnet 5 | $2.00 | $10.00 | The main agent is the orchestrator |
| Claude Opus 5 | $5.00 | $25.00 | If you need maximum quality of reasoning |
Anthropic also offers Fable 5.1 ($10 / $50 per MTok) for cases where deeper reasoning is needed than Opus 5 — using it would change the numbers below.
There are two ways to reduce costs, and each of them belongs to a different part of the system.
Prompt caching reduces the price of re-entry tokens by up to 90% and works great for online chat.
Batch API — You send up to 100,000 requests at a time and collect the results according to a maximum load schedule with a 24-hour SLA. Your concession to wait up to 24 hours for a response gives you a 50% discount from Anthropic. Batch API is used exclusively for offline work - one—time indexing of your knowledge base when documents are changed, for example.
A token is the minimum unit (piece) of text that the model uses. Common short words are one token in its entirety: the, and, to. Long or rare words are split up: insurance can become ins + urance. The GPT-4o / o200k_base tokenizer test gives (roughly) 1.12 tokens per word for English, 2.91 for Kazakh, and 1.6 for Russian.
Let's take a typical production project in English with examples and edge case processing - it is noticeably more voluminous than the training example above. Tokens are made up of all the steps of the cycle:
- Agent's system prompt: ~500 tokens
- Descriptions of three tools: ~400 tokens
- User's question: ~50 tokens
- 5 chunks found, submitted to the context: ~2500 tokens
- Internal reasoning steps and tool invocation: ~600 tokens
- Final answer: ~400 tokens
Roughly, there are about 4,000 input and 400 output tokens per request (for an agent cycle with one access to the tool, the input is calculated taking into account the re—presentation of the context at the formulation step).
On Sonnet 5 without optimizations:
- Entry: 4000/1M × $2.00 = $0.008
- Output: 400/1M × $10.00 = $0.004
- Total ≈ $0.012 per request
That is, about 1.2 cents per reference question. A cost calculation request (get_price) is usually cheaper — there is no heavy RAG context (finding the answer based on your vector database), only a compact JSON result of the function.
The system prompt and tool descriptions are identical in each request — this is an ideal candidate for prompt caching. By caching ~900 tokens of the static part, you save up to 90% on this entry share. With noticeable traffic, this significantly reduces the bill.
Monthly cost estimate for different volumes (Sonnet 5, ~$0.012/request, without cache):
| Requests/day | Per month | Approximately |
| 100 | 3 000 | ~$36 |
| 1 000 | 30 000 | ~$360 |
| 10 000 | 300 000 | ~$3 600 |
With prompt caching of the static part and batching of background operations, the real bill is noticeably lower than these figures.
Adding context to chunks via Haiku at the document upload stage.
Let's say the base is 5,000 chunks, with ~600 input and ~50 output tokens for each:
- Entrance: 5000 × 600 / 1M × $1.00 = $3.00
- Output: 5000 × 50 / 1M × $5.00 = $1.25
- Total ≈ $4.25 for full database indexing
Plus embeddings: Anthropic does not provide embedding API, they are taken from a third-party provider (Voyage, OpenAI) and charged separately, costing pennies on such volume. Reindexing occurs only with a new edition of documents, and not for every request, so this article has almost no effect on operating costs.
The cost is an architectural decision, not a surprise in the bill. At approximately $0.012 per request, the bill scales linearly depending on traffic; caching system software and tool descriptions is the biggest savings available, and it needs to be built in from the very beginning, rather than added later.
Prices are checked on the official Anthropic page (September 2026) and are subject to change. All the calculations above are indicative estimates for planning, not an accurate forecast of the bill.
Пусть у нас уже есть своя база знаний (документы, прайсы, проспекты и т.д.) и мы хотим её использовать для ведения диалога с пользователем.
Тогда экономика AI-агента складывается из двух статей: разовая индексация базы знаний и стоимость каждого запроса клиента. Их считают отдельно — за первую платим один раз при загрузке документов, вторая масштабируется с трафиком.
Разовая индексация — это когда документы конвертируются в эмбеддинги (это набор чисел), и эти эмбеддинги сохраняются в специальной векторной базе данных. По этим данным AI строит свои ответы.
API Anthropic тарифицируется за токены. Входные (промпт, системный промпт, контекст) и выходные (ответ модели) оплачиваются раздельно, в расчёте на миллион токенов (MTok).
Системный промпт агента — задаёт роль, правила и поведение модели на весь диалог.
Пример системного промпта:
Вы — помощник страховой компании. Отвечайте вежливо и точно.
Правила:
- ВСЕГДА получай стоимость страховки через вызов инструмента get_price. Никогда не вычисляй и не придумывай суммы сам.
- Получай ответы на справочные вопросы только из search_knowledge_base. Если информации нет — говори честно.
- Если инструмент возвращает ошибку из-за отсутствия нужных данных — задай уточняющий вопрос.
- По сложным юридическим вопросам предложи связаться с менеджером.
- Никогда не запрашивай и не раскрывай данные другого клиента.У LLM-моделей в таблице ниже соотношение цены выходных токенов к входным — 5:1, что упрощает планирование: знаешь стоимость входа, умножаешь на пять для выхода.
Актуальные цены (за 1M токенов, вход / выход):
| Модель | Вход | Выход | Роль в агенте |
| Claude Haiku 4.5 | $1.00 | $5.00 | Добавление контекста к чанкам при индексации |
| Claude Sonnet 5 | $2.00 | $10.00 | Основной агент-оркестратор |
| Claude Opus 5 | $5.00 | $25.00 | Если нужен максимум качества рассуждений |
Anthropic также предлагает Fable 5.1 ($10 / $50 за MTok) для случаев, когда нужны более глубокие рассуждения, чем у Opus 5 — его использование изменило бы приводимые ниже цифры.
Существует два способа снизить затраты, и каждый из них принадлежит к разной части системы.
Prompt caching снижает цену повторных входных токенов до 90% и отлично работает для online-чата.
Batch API — вы отправляете до 100 000 запросов одновременно и собираете результаты по графику максимальной загрузки с 24-часовым SLA. Ваша уступка подождать ответа до 24 часов даёт вам 50% скидку от Anthropic. Batch API применяется исключительно к офлайн-работе — разовой индексации вашей базы знаний при изменении документов, например.
Токен — минимальная единица (кусочек) текста, которой оперирует модель. Частые короткие слова — один токен целиком: the, and, to. Длинные или редкие слова дробятся: insurance может стать ins + urance. Тест на токенизаторе GPT-4o / o200k_base даёт (грубо) для английского языка — 1,12 токена на слово, для казахского — 2,91, для русского — 1,6.
Возьмём типичный продакшен-промпт на английском языке с примерами и обработкой краевых случаев — он заметно объёмнее учебного примера выше. Токены складываются из всех шагов цикла:
- Системный промпт агента: ~500 токенов
- Описания трёх инструментов: ~400 токенов
- Вопрос пользователя: ~50 токенов
- Найденные 5 чанков, поданные в контекст: ~2500 токенов
- Внутренние reasoning-шаги и вызов инструмента: ~600 токенов
- Итоговый ответ: ~400 токенов
Грубо — около 4000 входных и 400 выходных токенов на запрос (для агентного цикла с одним обращением к инструменту вход считается с учётом повторной подачи контекста на шаге формулировки).
На Sonnet 5 без оптимизаций:
- Вход: 4000 / 1M × $2.00 = $0.008
- Выход: 400 / 1M × $10.00 = $0.004
- Итого ≈ $0.012 за запрос
То есть порядка 1,2 цента за справочный вопрос. Запрос на расчёт стоимости (get_price) обычно дешевле — там нет тяжёлого RAG-контекста (нахождение ответа по вашей векторной базе), только компактный JSON-результат функции.
Системный промпт и описания инструментов идентичны в каждом запросе — это идеальный кандидат для prompt caching. Кэшируя ~900 токенов статической части, экономишь до 90% на этой доле входа. При заметном трафике это ощутимо снижает счёт.
Оценка месячной стоимости при разном объёме (Sonnet 5, ~$0.012/запрос, без кэша):
| Запросов/день | В месяц | Ориентировочно |
| 100 | 3 000 | ~$36 |
| 1 000 | 30 000 | ~$360 |
| 10 000 | 300 000 | ~$3 600 |
С prompt caching статической части и батчингом фоновых операций реальный счёт заметно ниже этих цифр.
Добавление контекста к чанкам через Haiku на этапе загрузки документов.
Допустим, база — 5000 чанков, на каждый ~600 входных и ~50 выходных токенов:
- Вход: 5000 × 600 / 1M × $1.00 = $3.00
- Выход: 5000 × 50 / 1M × $5.00 = $1.25
- Итого ≈ $4.25 за полную индексацию базы
Плюс эмбеддинги: Anthropic не предоставляет embedding API, они берутся у стороннего провайдера (Voyage, OpenAI) и тарифицируются отдельно, стоя копейки на таком объёме. Переиндексация происходит только при новой редакции документов, а не на каждый запрос, поэтому эта статья почти не влияет на операционные расходы.
Стоимость — это архитектурное решение, а не сюрприз в счёте. При ориентировочно $0,012 за запрос счёт масштабируется линейно в зависимости от трафика; кэширование системного промпта и описаний инструментов — это самая большая доступная экономия, и её необходимо заложить с самого начала, а не добавлять позже.
Цены проверены по официальной странице Anthropic (сентябрь 2026) и могут меняться. Все расчёты выше — ориентировочные оценки для планирования, а не точный прогноз счёта.