all articles
December 20, 2024·updated September 23, 2026·11 min

Business AI Integration: Use Cases, RAG, and Cost

How to integrate AI into a business: Telegram bots, document search, data protection, quality checks, and API cost estimation.

AIOpenAI APIAutomationPythonBusiness

By Shcoder, independent developer

“We need ChatGPT” is not a project brief. Usually, a business wants to answer recurring questions faster, process incoming requests, or find information in its documents. Start with one bounded use case whose output can be evaluated and whose uncertain cases can be handed to a person.

Distinguish ChatGPT as a ready-to-use product from the OpenAI API that developers integrate into an application. The examples below use the API. Models, SDKs, and prices change, so check the current model catalog and pricing before implementation.

Business tasks that can benefit from AI

AI is useful when inputs vary, but the result can still be checked:

  • classify incoming requests and route them to the right team;
  • draft a response for an agent instead of sending it automatically;
  • extract fields from an email or form and ask the user to confirm them;
  • search approved documentation and cite the source;
  • summarize a long request before handing it to a specialist.

Do not start with a fully autonomous agent that changes orders, issues refunds, or makes legally significant decisions. Those actions need ordinary server-side checks, limited permissions, and human confirmation.

Before development, define four things: who will use the feature, which data it can access, what counts as a correct result, and where a request goes when the system is uncertain.

Telegram bot architecture

A minimal flow looks like this:

message → access and rate-limit checks → model → output checks → reply or human handoff

Keep API keys on the server. Do not send a customer's entire profile “just in case”; include only what the specific request needs. For personal, financial, or health data, separately review the legal basis, provider terms, and retention requirements.

The small example below uses Aiogram 3 and the official Python SDK. Install aiogram, openai, and python-dotenv; provide TELEGRAM_BOT_TOKEN, OPENAI_API_KEY, and OPENAI_MODEL through a local .env file or environment variables. Never commit .env to Git.

import asyncio
import os

from aiogram import Bot, Dispatcher, F
from aiogram.filters import CommandStart
from aiogram.types import Message
from dotenv import load_dotenv
from openai import AsyncOpenAI, OpenAIError

load_dotenv()

dp = Dispatcher()


@dp.message(CommandStart())
async def start(message: Message) -> None:
    await message.answer("Describe your question. If a specialist is needed, I will pass it to the team.")


@dp.message(F.text)
async def answer(message: Message, openai: AsyncOpenAI) -> None:
    thinking = await message.answer("Preparing an answer…")

    try:
        result = await openai.responses.create(
            model=os.environ["OPENAI_MODEL"],
            instructions=(
                "You are a company assistant. Reply briefly and stay within the provided policy. "
                "Do not invent prices or terms. If information is missing, offer a human handoff."
            ),
            input=message.text or "",
            max_output_tokens=400,
        )
    except OpenAIError:
        await thinking.edit_text("I could not prepare an answer. Please try later or contact a team member.")
        return

    text = result.output_text.strip()
    await thinking.edit_text(text or "I could not find a reliable answer. I will pass this to a specialist.")


async def main() -> None:
    client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])
    dp["openai"] = client

    try:
        async with Bot(token=os.environ["TELEGRAM_BOT_TOKEN"]) as bot:
            await dp.start_polling(bot)
    finally:
        await client.close()


if __name__ == "__main__":
    asyncio.run(main())

This demonstrates only the API call. A production service also needs rate limits, input-length limits, logging that excludes secrets and personal message text, cancellation handling, and a clear human handoff. An HTTP 200 response does not mean the model's answer is correct.

Search internal documents with RAG

If the assistant needs to answer from policies or a knowledge base, it needs retrieval. Retrieval-Augmented Generation (RAG) prepares documents, searches for relevant passages, sends the retrieved context to a model, and checks the result.

For a small corpus, OpenAI File Search can use a Vector Store created in advance. Store creation and file uploads happen separately; a production system must also update and remove obsolete documents.

import os

from openai import AsyncOpenAI


async def answer_from_docs(client: AsyncOpenAI, question: str) -> str:
    result = await client.responses.create(
        model=os.environ["OPENAI_MODEL"],
        instructions=(
            "Answer only using the retrieved documents. "
            "If they do not support an answer, say so and suggest contacting a team member."
        ),
        input=question,
        tools=[
            {
                "type": "file_search",
                "vector_store_ids": [os.environ["OPENAI_VECTOR_STORE_ID"]],
            }
        ],
        max_output_tokens=500,
    )
    return result.output_text

File Search simplifies retrieval, but it does not replace access control: users must not receive documents they are not allowed to read. Separate stores by role or customer, or enforce permissions before search. Evaluate retrieval with representative questions, keep sources visible, and remove outdated files regularly.

If you use your own vector search, Qdrant or another database must be configured first: create a collection, choose its vector dimensions and distance metric, upload embeddings with payloads, and implement access filters. Searching a collection that does not exist is not a working RAG example.

Estimate API costs

There is no honest fixed “cost per thousand messages” without knowing the model, conversation history, instructions, retries, and tools. Measure actual API usage and calculate each kind of operation separately.

For a text model, a basic estimate is:

cost = input tokens / 1,000,000 × current input rate
     + output tokens / 1,000,000 × current output rate
     + tools and additional services

Then include infrastructure, monitoring, and maintenance. In a long conversation, the history may be sent again with every request, so limit or summarize it. Check current rates and tool-specific charges on the OpenAI API pricing page; do not use an old price from an article as a project budget.

Development cost also depends on scope: a basic FAQ bot and an integration with a CRM, role-based access, audit logs, and a document base are different projects. An estimate needs the data sources, workflows, restrictions, integrations, and acceptance criteria.

Checks before launch

  1. Prepare 30–100 typical and difficult questions, including cases where the correct answer is “I don't know.”
  2. Measure answer quality, human handoff, latency, and average cost per request.
  3. Add request limits, maximum input size, and restrictions on available actions.
  4. Test that instructions inside user messages and documents cannot expand the bot's permissions.
  5. Pilot with a small group, compare against the current workflow, and fix the causes of errors.

For document-based scenarios, test permissions, stale versions, and answers without a supported source. For forms and orders, let users verify extracted data before submitting it.

Common mistakes

  • Automating a process before documenting it. Map the current request flow and its exceptions first.
  • Letting the model make decisions without checks. Critical actions belong in server-side business logic, not a text instruction.
  • Treating RAG as a guarantee of accuracy. Retrieval can return irrelevant or stale content; test it and cite sources.
  • Sending unnecessary data. Minimize context and anonymize it where possible.
  • Ignoring the full cost. Include tools, infrastructure, support, and human review in addition to tokens.
  • Promising payback in advance. Compare measured costs and time before and after a pilot; results depend on the process and implementation quality.

Where to start

Choose one recurring use case, prepare test examples, and first build an assistant for employees rather than an autonomous replacement for the workflow. After validating quality, gradually add customers and automated actions.

To scope an AI integration, Telegram bot, or internal assistant, describe the project and we can review its data, risks, and a sensible first release.

Need AI in your product?

I integrate GPT, Claude and RAG into bots, websites and business workflows.