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.http://<gateway-host>:8080 with a /health endpoint and a /v1/ask endpoint that routes to either OpenAI or a local Ollama model using one request format.AI_Service with a read-only role, plus an HTTP service AIAssistant published at /hs/ai/ask that proxies requests to the gateway — the provider API key never enters the infobase.audit.jsonl) where every AI request produces one line with backend, latency, and question text.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/healthDetails and checks are in the steps below; gateway.py is created in Step 2.

pip; the gateway is a single file, no build step.audit.jsonl.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:
AI_Service has no administrative or configuration rightsaudit.jsonl is written outside the web rootExample: 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/pingFirst line prints 401, second prints 200. If both print 200, authentication is disabled on the publication — fix that before continuing.

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:
| Variable | Example | Purpose |
|---|---|---|
| `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.

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"];
EndFunctionWhy: 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.jsonlThe 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.
Problem. 1C call fails with 401 while curl works
{"detail":"invalid bearer token"}Authorization header is malformed — a trailing space after the token, or the token in the infobase differs from AI_GATEWAY_TOKEN after a rotation.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"}'.Problem. Local backend returns an error about a missing model
{"error":"model \"<tag>\" not found, try pulling it first"}OLLAMA_MODEL names a tag that was never pulled on this host, or the tag includes a suffix the local registry does not have.ollama list, copy an exact tag into OLLAMA_MODEL, restart uvicorn, and repeat the Step 2 check.Problem. Connection refused from the 1C server
curl: (7) Failed to connect to 127.0.0.1 port 8080127.0.0.1 but 1C runs on another machine, so the loopback address points at the 1C host itself.uvicorn gateway:app --host <internal-ip> --port 8080 and allow port 8080 only from the 1C server subnet in the firewall; then rerun the /health check from the 1C host.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.
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.
Status: practical guide. Some statements come from vendors; verify in your environment.
Time to complete: 90 minutes Difficulty: Intermediate
Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.
| Entity | Type | Role |
|---|---|---|
| как подключить ИИ к 1С | продукт/модель | упоминается в заголовке, TL;DR или разделах гайда |
| интеграция 1С с ChatGPT | продукт/модель | упоминается в заголовке, TL;DR или разделах гайда |
| нейросеть в 1С безопасность | продукт/модель | упоминается в заголовке, TL;DR или разделах гайда |
| Python | платформа/технология | упоминается в заголовке, TL;DR или разделах гайда |
| OpenAI | компания | упоминается в заголовке, TL;DR или разделах гайда |
No independent confirmation is provided; source claims and editorial conclusions are separated below.
| Source | Type | Role |
|---|---|---|
| api.openai.com | внешний источник | ссылка из тела гайда |
Cite as: AI Release. Как подключить ИИ к 1С: интеграция ChatGPT и локальной LLM с безопасными правами доступа. ai-release.org.