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

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-podklyuchit-ii-k-1s-integratsiya-chatgpt-i-lokalnoy_en.html

## TL;DR

- Time to complete: 90 minutes
- Difficulty: Intermediate
- 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.

## What you will get

- A running AI gateway on `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.
- A dedicated 1C user `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.
- A JSONL audit log (`audit.jsonl`) where every AI request produces one line with backend, latency, and question text.

## Quick start

```bash
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](https://ai-release.org/guides/img/kak-podklyuchit-ii-k-1s-integratsiya-chatgpt-i-lokalnoy-en-1.jpg?v=1795596644)


- 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 local path. Setup walkthrough: [How to connect n8n to a local LLM: step-by-step private automation setup with Ollama](https://ai-release.org/guides/kak-podklyuchit-n8n-k-lokalnoy-yazykovoy-modeli-poshago.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).
- An OpenAI API key if you use the cloud backend. Model IDs change over time — take the current one from the provider documentation, not from this guide.
- Write permissions on a log directory for `audit.jsonl`.

## 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:**

- [ ] Role contains only read rights on the whitelisted objects
- [ ] `AI_Service` has no administrative or configuration rights
- [ ] Interactive access is disabled
- [ ] Provider API keys are stored outside the infobase (Step 2)
- [ ] `audit.jsonl` is written outside the web root

**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.

```bash
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](https://ai-release.org/guides/img/kak-podklyuchit-ii-k-1s-integratsiya-chatgpt-i-lokalnoy-en-2.jpg?v=1795596668)


**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.

```python
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](https://ai-release.org/guides/kak-podklyuchit-modeli-openai-cherez-google-cloud-posha.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

**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:**

```bash
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](https://ai-release.org/guides/img/kak-podklyuchit-ii-k-1s-integratsiya-chatgpt-i-lokalnoy-en-3.jpg?v=1795596694)


**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.

```bsl
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:**

```bash
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**

- Error: `{"detail":"invalid bearer token"}`
- Cause: the `Authorization` header is malformed — a trailing space after the token, or the token in the infobase differs from `AI_GATEWAY_TOKEN` after a rotation.
- Solution: compare both values, then retest the exact header: `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: `{"error":"model \"<tag>\" not found, try pulling it first"}`
- Cause: `OLLAMA_MODEL` names a tag that was never pulled on this host, or the tag includes a suffix the local registry does not have.
- Solution: run `ollama list`, copy an exact tag into `OLLAMA_MODEL`, restart `uvicorn`, and repeat the Step 2 check.

**Problem. Connection refused from the 1C server**

- Error: `curl: (7) Failed to connect to 127.0.0.1 port 8080`
- Cause: the gateway is bound to `127.0.0.1` but 1C runs on another machine, so the loopback address points at the 1C host itself.
- Solution: start with `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.

## 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](https://ai-release.org/guides/sravnenie-ii-assistentov.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

## 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.
