← All guides AI Release
RU Subscribe to @ai_releaseorg

How to Integrate AI into 1C: Connecting ChatGPT and Local LLMs with Secure Permissions

Updated: 25.11.2026 · AI Release · @ai_releaseorg
How to Integrate AI into 1C: Connecting ChatGPT and Local LLMs with Secure Permissions

TL;DR

What you will get

Quick start

python3 -m venv .venv && . .venv/bin/activate && pip install fastapi "uvicorn[standard]" httpx
export AI_GATEWAY_TOKEN=<32-char-random-token> OPENAI_API_KEY=<openai-key> OLLAMA_URL=http://127.0.0.1:11434
uvicorn gateway:app --host 127.0.0.1 --port 8080 &
sleep 2 && curl -s http://127.0.0.1:8080/health

Details and checks are in the steps below; gateway.py is created in Step 2.

Requirements and setup

Illustration: Requirements and setup
Illustration: Requirements and setup

Step 1. Create a read-only 1C service user, role, and HTTP service

What to do: In Designer open Configuration → Roles, add a role AI_Integration_ReadOnly. Check only the objects the assistant is allowed to read (for example Catalog.Products, Document.SalesOrder) and leave every other box unchecked. Then open Administration → Users, add AI_Service, assign only that role, uncheck interactive access, and set a password. Finally open Common → HTTP services, add AIAssistant with root URL ai and method ping (GET), then publish the infobase.

Why: The AI gets exactly the data the role allows — no more. Running it as a separate non-interactive user means every AI action is attributable in the 1C logs, and a leaked token cannot be used to log into the interface.

Access checklist:

Example: a request from AI_Service to a non-whitelisted object fails with an access-rights error instead of returning data — that is the expected behaviour.

How to check: call the published service without credentials and with them.

curl -s -o /dev/null -w "%{http_code}\n" -X POST http://<1c-host>/<infobase>/hs/ai/ping
curl -s -o /dev/null -w "%{http_code}\n" -u AI_Service:<password> -X POST http://<1c-host>/<infobase>/hs/ai/ping

First line prints 401, second prints 200. If both print 200, authentication is disabled on the publication — fix that before continuing.

Step 2. Deploy the AI gateway with token auth and an audit log

Illustration: Step 2. Deploy the AI gateway with token auth and an audit log
Illustration: Step 2. Deploy the AI gateway with token auth and an audit log

What to do: Create gateway.py. It accepts one request shape from 1C, checks a bearer token, forwards to OpenAI or Ollama, and appends one line per request to the audit log.

import json, os, time, uuid
import httpx
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel

GATEWAY_TOKEN = os.environ["AI_GATEWAY_TOKEN"]
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
OPENAI_MODEL = os.environ.get("OPENAI_MODEL", "")
OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://127.0.0.1:11434")
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "")
AUDIT_LOG = os.environ.get("AUDIT_LOG", "audit.jsonl")

app = FastAPI()

class AskRequest(BaseModel):
    question: str
    backend: str = "local"

def audit(record: dict) -> None:
    with open(AUDIT_LOG, "a", encoding="utf-8") as f:
        f.write(json.dumps(record, ensure_ascii=False) + "\n")

@app.get("/health")
def health():
    return {"status": "ok"}

@app.post("/v1/ask")
def ask(req: AskRequest, authorization: str = Header(default="")):
    if authorization != f"Bearer {GATEWAY_TOKEN}":
        raise HTTPException(status_code=401, detail="invalid bearer token")
    started = time.time()
    if req.backend == "openai":
        r = httpx.post(
            "https://api.openai.com/v1/chat/completions",
            headers={"Authorization": f"Bearer {OPENAI_API_KEY}"},
            json={"model": OPENAI_MODEL,
                  "messages": [{"role": "user", "content": req.question}]},
            timeout=60,
        )
        r.raise_for_status()
        answer = r.json()["choices"][0]["message"]["content"]
    else:
        r = httpx.post(
            f"{OLLAMA_URL}/api/chat",
            json={"model": OLLAMA_MODEL, "stream": False,
                  "messages": [{"role": "user", "content": req.question}]},
            timeout=120,
        )
        r.raise_for_status()
        answer = r.json()["message"]["content"]
    audit({"id": str(uuid.uuid4()), "ts": time.time(), "backend": req.backend,
           "question": req.question, "ms": int((time.time() - started) * 1000)})
    return {"answer": answer, "backend": req.backend}

Configuration is environment-only:

VariableExamplePurpose
`AI_GATEWAY_TOKEN``a7f3c1...` (32 chars)bearer token 1C must send; rotate on schedule
`OPENAI_API_KEY``sk-...`cloud key, never stored in 1C
`OPENAI_MODEL``<model-id from provider docs>`which cloud model to call
`OLLAMA_URL``http://127.0.0.1:11434`local runtime address
`OLLAMA_MODEL``<tag from ollama list>`which local model to call
`AUDIT_LOG``/var/log/ai/audit.jsonl`one JSON line per request

Why: 1C keeps only a gateway token. If the key leaks or the provider changes, you reissue it in one place. The gateway is also the choke point where you can add rate limits, prompt filtering, and masking before data leaves the network. For organisations that must route cloud calls through their own cloud account, see How to Access OpenAI Models via Google Cloud: Step-by-Step Setup.

Example: AI_GATEWAY_TOKEN=9f2b... and OLLAMA_MODEL=<tag> exported before uvicorn starts; a request with "backend":"openai" produces {"answer":"...","backend":"openai"}.

How to check:

curl -s -X POST http://127.0.0.1:8080/v1/ask -H "Content-Type: application/json" -d '{"question":"Say OK"}'
curl -s -X POST http://127.0.0.1:8080/v1/ask -H "Authorization: Bearer $AI_GATEWAY_TOKEN" \
  -H "Content-Type: application/json" -d '{"question":"Say OK","backend":"local"}'

The first call prints {"detail":"invalid bearer token"} with HTTP 401, the second prints {"answer":"...","backend":"local"} with HTTP 200.

Step 3. Call the gateway from 1C and verify end to end

Illustration: Step 3. Call the gateway from 1C and verify end to end
Illustration: Step 3. Call the gateway from 1C and verify end to end

What to do: Add a POST method ask to the AIAssistant HTTP service. Its handler reads the JSON body, calls the gateway, and returns the answer. Put the call in a common module so any form or scheduled job can reuse it.

Function AskAI(Question) Export

    Headers = New Map();
    Headers.Insert("Authorization", "Bearer <gateway-token>");
    Headers.Insert("Content-Type", "application/json");

    Body = "{""question"": """ + StrReplace(Question, """", "\""") + """, ""backend"": ""local""}";

    Connection = New HTTPConnection("<gateway-host>", 8080);
    Request = New HTTPRequest("/v1/ask", Headers);
    Request.SetBodyFromString(Body);
    Response = Connection.Call("POST", Request);

    If Response.StatusCode <> 200 Then
        Raise "AI gateway returned HTTP " + Response.StatusCode + ": " + Response.GetBodyAsString();
    EndIf;

    Reader = New JSONReader();
    Reader.SetString(Response.GetBodyAsString());
    Result = ReadJSON(Reader);
    Return Result["answer"];

EndFunction

Why: The call runs under the AI_Service rights, so the platform itself blocks access to objects outside the role — the gateway never has to guess. The BSL handler is also the right place to strip fields you do not want to send, for example salary or contact columns, before the string reaches the network. If your Designer UI is localized, use the built-in Syntax Assistant to confirm the exact built-in names for this platform release.

Example: a data processor form button calls AskAI("How many products are in the catalog?") and displays the returned string in a message box.

How to check:

curl -s -X POST http://<1c-host>/<infobase>/hs/ai/ask -u AI_Service:<password> \
  -H "Content-Type: application/json" -d '{"question":"Say OK"}'
tail -n 1 /var/log/ai/audit.jsonl

The first command returns {"answer":"..."}. The second shows a new JSON line with "backend", "question", and "ms" — that line proves the request passed through the gateway rather than going straight to the provider.

Troubleshooting

Problem. 1C call fails with 401 while curl works

Problem. Local backend returns an error about a missing model

Problem. Connection refused from the 1C server

Summary and next steps

You now have a token-protected gateway, a read-only 1C service user, and an HTTP service that routes questions to either a cloud or a local model with a full audit trail. Next, add per-user rate limits in the gateway and a scheduled job that rotates AI_GATEWAY_TOKEN monthly. If you are still choosing a provider, start with the ChatGPT, Claude, Gemini, DeepSeek comparison.

FAQ

Can 1C call OpenAI directly without a gateway?

Technically yes, using the same HTTP connection object, but the API key then lives in the infobase and is readable by anyone with configuration or administrative rights. The gateway keeps the key outside 1C and gives you one place to log and rate-limit.

How do I stop the model from seeing salaries or personal data?

Two layers: the role in Step 1 blocks whole objects, and the BSL handler removes sensitive attributes from the request string before sending. Log the outgoing string in audit.jsonl so you can prove what left the network.

Can this work fully offline?

Yes, with the local backend: Ollama runs on the same host and the gateway only calls OLLAMA_URL. No request leaves your network; the cloud path stays disabled as long as backend is local.

Does the assistant write data back into 1C?

Not in this setup. The role is read-only and the HTTP service only returns text. Any write-back requires a separate role and a separate endpoint — check the documentation for the object-write rights you would need.

🤖 AI summary

AI Release Knowledge Layer
Machine-readable description · Version 1.0

Status: practical guide. Some statements come from vendors; verify in your environment.

1. Summary

Time to complete: 90 minutes Difficulty: Intermediate

Inside: direct answers, key facts, entities, context, reliability, unknowns and sources.

Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.

Full Knowledge Layer: sections 2–8

2. Direct answers

What is required?
1C:Enterprise 8.3 platform and a published infobase reachable over HTTP (publishing via the 1C web server extension).; Designer access to add a role, a user, and a common HTTP service.; Python 3 with pip; the gateway is a single file, no build step.; Ollama installed and at least one model pulled, if you want the… → details (AR-GUIDE-KAKPODKLYU-003)
How to do it?
Step 1. Create a read-only 1C service user, role, and HTTP service → Step 2. Deploy the AI gateway with token auth and an audit log → Step 3. Call the gateway from 1C and verify end to end → details (AR-GUIDE-KAKPODKLYU-004)
Which topics does it cover?
как подключить ИИ к 1С, интеграция 1С с ChatGPT, нейросеть в 1С безопасность → details (AR-GUIDE-KAKPODKLYU-002)
What are the key points?
Time to complete: 90 minutes Difficulty: Intermediate → details (AR-GUIDE-KAKPODKLYU-007)

3. Key facts

  1. Time to complete: 90 minutes — evidence; status: заявление источника.
  2. Difficulty: Intermediate — evidence; status: заявление источника.
  3. You will need: 1C:Enterprise 8.3 with Designer access (exact supported build — check the documentation for your release), an infobase administrator account, Python 3 with pip, FastAPI + Uvicorn + httpx, an OpenAI API key, a local LLM runtime (Ollama) if you want the offline path, and network reachability from the 1C server to the gateway host on port 8080. — evidence; status: заявление источника.
  4. 1C:Enterprise 8.3 platform and a published infobase reachable over HTTP (publishing via the 1C web server extension). — evidence; status: заявление источника.
  5. Designer access to add a role, a user, and a common HTTP service. — evidence; status: заявление источника.
  6. Python 3 with pip; the gateway is a single file, no build step. — evidence; status: заявление источника.

4. Entities

EntityTypeRole
как подключить ИИ к 1Спродукт/модельупоминается в заголовке, TL;DR или разделах гайда
интеграция 1С с ChatGPTпродукт/модельупоминается в заголовке, TL;DR или разделах гайда
нейросеть в 1С безопасностьпродукт/модельупоминается в заголовке, TL;DR или разделах гайда
Pythonплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
OpenAIкомпанияупоминается в заголовке, TL;DR или разделах гайда

5. Context

  • Guide — describes → How to Integrate AI into 1C: Connecting ChatGPT and Local LLMs with Secure Permissions (AR-GUIDE-KAKPODKLYU-001).
  • Guide — includes step → Step 1. Create a read-only 1C service user, role, and HTTP service (AR-GUIDE-KAKPODKLYU-001).

6. Reliability

Confirmed

No independent confirmation is provided; source claims and editorial conclusions are separated below.

Source claims

  • Product features, versions, prices and limits come from vendors and the guide.
  • Commands and steps are recommendations, not guaranteed results.

AI Release analysis

  • Structure, comparison and selection criteria are editorial.
  • The guide does not replace an independent audit or legal advice.

7. Unknowns

  • Current versions, prices and limits.
  • Independent benchmarks and quality checks.
  • Terms of use and data policy.

8. Sources

SourceTypeRole
api.openai.comвнешний источникссылка из тела гайда

Cite as: AI Release. Как подключить ИИ к 1С: интеграция ChatGPT и локальной LLM с безопасными правами доступа. ai-release.org.