mirror of
https://github.com/simplex-chat/simplex-chat.git
synced 2026-11-22 12:18:07 +00:00
support bot: Grok API key in config
This commit is contained in:
1 parent
43e8426732
commit
1eb8041644
6 files changed
+58
-14
No files matched your search
@@ -5,7 +5,7 @@ A business-address bot that triages incoming support chats, optionally runs them
|
||||
## Prerequisites
|
||||
|
||||
- Node.js v18 or newer (v24 tested)
|
||||
- `GROK_API_KEY` env var (xAI) — optional; the bot runs without it
|
||||
- an xAI API key in `GROK_API_KEY` or in `grok_api_key` of the config file — optional; the bot runs without it
|
||||
- For the PostgreSQL backend: Linux x86_64, `libpq5` installed on the host, and a reachable PostgreSQL server
|
||||
|
||||
## Install & build
|
||||
@@ -56,7 +56,7 @@ Run `npm start -- --help` for the auto-generated reference. Summary:
|
||||
| `--timezone` | both | no | `UTC` | IANA zone for weekend detection |
|
||||
| `--complete-hours` | both | no | `3` | auto-complete chats after N hours idle (`0` disables) |
|
||||
| `--card-flush-seconds` | both | no | `300` | debounce card state writes |
|
||||
| `--context-file` | both | required with `GROK_API_KEY` | | text file with Grok system context |
|
||||
| `--context-file` | both | required with a Grok API key | | text file with Grok system context |
|
||||
| `--dry-run` | both | no | | check config, database and state, then exit |
|
||||
| `--allow-migrations` | both | no | | with `--dry-run`: apply pending migrations instead of reporting them |
|
||||
| `--allow-down-migrations` | both | no | | with `--dry-run`: roll back migrations that this build does not have |
|
||||
@@ -64,7 +64,7 @@ Run `npm start -- --help` for the auto-generated reference. Summary:
|
||||
|
||||
## Config file
|
||||
|
||||
`--config config.toml` reads option values and message texts from a TOML file, as [config.toml.example](../../scripts/support-bot/config/config.toml.example) shows. Keys are the command-line options in snake_case (`team_group` for `--team-group`); a list is joined with commas. An option given on the command line takes precedence over the file. `--dry-run`, `--allow-migrations` and `--allow-down-migrations` are command-line only. The file holds the `pg_conn` password, so keep it readable only by the user that runs the bot.
|
||||
`--config config.toml` reads option values and message texts from a TOML file, as [config.toml.example](../../scripts/support-bot/config/config.toml.example) shows. Keys are the command-line options in snake_case (`team_group` for `--team-group`); a list is joined with commas. An option given on the command line takes precedence over the file. `--dry-run`, `--allow-migrations` and `--allow-down-migrations` are command-line only. `grok_api_key` is file-only, so that the key is not visible in the process list; `GROK_API_KEY` takes precedence over it. The file holds the `pg_conn` password and the Grok key, so keep it readable only by the user that runs the bot.
|
||||
|
||||
A message left out of `[messages]` keeps its built-in text. `{hours}` is replaced with 24 on weekdays and 48 at weekends in `timezone`. The welcome message is updated in the bot address on the next start.
|
||||
|
||||
@@ -89,7 +89,7 @@ A message left out of `[messages]` keeps its built-in text. `{hours}` is replace
|
||||
|
||||
| Var | Purpose |
|
||||
|---|---|
|
||||
| `GROK_API_KEY` | xAI API key; enables Grok replies |
|
||||
| `GROK_API_KEY` | xAI API key; enables Grok replies; takes precedence over `grok_api_key` of the config file |
|
||||
| `SIMPLEX_LIBS_DIR` | directory with a local libsimplex build for the `--db` backend, instead of the downloaded one |
|
||||
| `SIMPLEX_ADDON_PATH` | locally built Node.js add-on (`simplex.node`), instead of the downloaded one |
|
||||
| `NODE_OPTIONS` | `--max-old-space-size=8192` on a bot with many chats: single API responses outgrow the default heap |
|
||||
@@ -110,7 +110,7 @@ docker compose up --build
|
||||
LIBS=source docker compose build
|
||||
```
|
||||
|
||||
`scripts/support-bot/config` is mounted at `/etc/support-bot` and holds `config.toml`, with `pg_conn`, and the Grok context file; the bot runs as uid 1000, which must be able to read them. `GROK_API_KEY` is read from the environment. Other arguments are passed after the service name, for example `docker compose run --rm support-bot --config /etc/support-bot/config.toml --dry-run`.
|
||||
`scripts/support-bot/config` is mounted at `/etc/support-bot` and holds `config.toml`, with `pg_conn` and `grok_api_key`, and the Grok context file; the bot runs as uid 1000, which must be able to read them. Other arguments are passed after the service name, for example `docker compose run --rm support-bot --config /etc/support-bot/config.toml --dry-run`.
|
||||
|
||||
## Dry run
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {describe, test, expect, beforeEach, vi} from "vitest"
|
||||
import {describe, test, expect, beforeEach, afterEach, vi} from "vitest"
|
||||
import {mkdtempSync, writeFileSync} from "fs"
|
||||
import {tmpdir} from "os"
|
||||
import {join} from "path"
|
||||
@@ -2559,6 +2559,43 @@ describe("parseConfig Validation", () => {
|
||||
.toThrow(/messages must be a table/)
|
||||
})
|
||||
|
||||
describe("grok_api_key", () => {
|
||||
const savedKey = process.env.GROK_API_KEY
|
||||
beforeEach(() => { delete process.env.GROK_API_KEY })
|
||||
afterEach(() => {
|
||||
if (savedKey === undefined) delete process.env.GROK_API_KEY
|
||||
else process.env.GROK_API_KEY = savedKey
|
||||
})
|
||||
const withKey = (extra = "") => configFile(`team_group = "T"\ncontext_file = "ctx.yaml"\ngrok_api_key = "file-key"${extra}`)
|
||||
|
||||
test("is read from the file", () => {
|
||||
expect(parseConfig(["--config", withKey()]).grokApiKey).toBe("file-key")
|
||||
})
|
||||
|
||||
test("GROK_API_KEY takes precedence; an empty GROK_API_KEY does not", () => {
|
||||
process.env.GROK_API_KEY = "env-key"
|
||||
expect(parseConfig(["--config", withKey()]).grokApiKey).toBe("env-key")
|
||||
process.env.GROK_API_KEY = ""
|
||||
expect(parseConfig(["--config", withKey()]).grokApiKey).toBe("file-key")
|
||||
})
|
||||
|
||||
test("requires a context file", () => {
|
||||
expect(() => parseConfig(["--config", configFile(`team_group = "T"\ngrok_api_key = "file-key"`)]))
|
||||
.toThrow(/A Grok API key is set but --context-file is not provided/)
|
||||
})
|
||||
|
||||
test("must be a non-empty string", () => {
|
||||
expect(() => parseConfig(["--config", configFile(`team_group = "T"\ngrok_api_key = ""`)]))
|
||||
.toThrow(/grok_api_key must be a non-empty string/)
|
||||
expect(() => parseConfig(["--config", configFile(`team_group = "T"\ngrok_api_key = 1`)]))
|
||||
.toThrow(/grok_api_key must be a non-empty string/)
|
||||
})
|
||||
|
||||
test("absent from file and environment → Grok disabled", () => {
|
||||
expect(parseConfig(["--config", configFile(`team_group = "T"`)]).grokApiKey).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
test("malformed TOML → throws", () => {
|
||||
expect(() => parseConfig(["--config", configFile(`team_group = "unclosed`)])).toThrow()
|
||||
})
|
||||
|
||||
@@ -152,7 +152,7 @@ export class SupportBot {
|
||||
}
|
||||
|
||||
private async withGrokProfile<R>(fn: () => Promise<R>): Promise<R> {
|
||||
if (this.grokUserId === null) throw new Error("Grok is disabled (no GROK_API_KEY)")
|
||||
if (this.grokUserId === null) throw new Error("Grok is disabled (no Grok API key)")
|
||||
const grokUserId = this.grokUserId
|
||||
return profileMutex.runExclusive(async () => {
|
||||
await this.chat.apiSetActiveUser(grokUserId)
|
||||
|
||||
@@ -60,11 +60,11 @@ function buildCommand(): Command {
|
||||
.option("--timezone <iana>", "IANA timezone for weekend detection", "UTC")
|
||||
.option("--complete-hours <n>", "auto-complete chats after N hours idle (0 disables)", parseNonNegativeInt("--complete-hours"), 3)
|
||||
.option("--card-flush-seconds <n>", "debounce card state writes", parseNonNegativeInt("--card-flush-seconds"), 300)
|
||||
.option("--context-file <path>", "text file with Grok system context (required if GROK_API_KEY set)")
|
||||
.option("--context-file <path>", "text file with Grok system context (required with a Grok API key)")
|
||||
.option("--dry-run", "check config, database and state, then exit without starting chat")
|
||||
.option("--allow-migrations", "with --dry-run: apply pending migrations instead of reporting them")
|
||||
.option("--allow-down-migrations", "with --dry-run: roll back migrations that this build does not have")
|
||||
.addHelpText("after", "\nEnvironment:\n GROK_API_KEY xAI API key — enables Grok replies\n SIMPLEX_LIBS_DIR local libsimplex build for the --db backend\n SIMPLEX_ADDON_PATH locally built Node.js add-on\n")
|
||||
.addHelpText("after", "\nEnvironment:\n GROK_API_KEY xAI API key — enables Grok replies, takes precedence over grok_api_key in --config\n SIMPLEX_LIBS_DIR local libsimplex build for the --db backend\n SIMPLEX_ADDON_PATH locally built Node.js add-on\n")
|
||||
}
|
||||
|
||||
interface RawOpts {
|
||||
@@ -88,6 +88,7 @@ interface RawOpts {
|
||||
interface ConfigFile {
|
||||
args: string[]
|
||||
messages: Messages
|
||||
grokApiKey: string | null
|
||||
}
|
||||
|
||||
function configFilePath(args: string[]): string | undefined {
|
||||
@@ -97,10 +98,14 @@ function configFilePath(args: string[]): string | undefined {
|
||||
}
|
||||
|
||||
function readConfigFile(path: string): ConfigFile {
|
||||
const {messages = {}, ...options} = parseToml(readFileSync(path, "utf-8"))
|
||||
const {messages = {}, grok_api_key = null, ...options} = parseToml(readFileSync(path, "utf-8"))
|
||||
if (grok_api_key !== null && (typeof grok_api_key !== "string" || grok_api_key === "")) {
|
||||
throw new Error(`${path}: grok_api_key must be a non-empty string`)
|
||||
}
|
||||
return {
|
||||
args: Object.entries(options).map(([key, value]) => configOptionArg(path, key, value)),
|
||||
messages: configMessages(path, messages),
|
||||
grokApiKey: grok_api_key,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +139,7 @@ function configMessages(path: string, table: unknown): Messages {
|
||||
export function parseConfig(args: string[]): Config {
|
||||
const cmd = buildCommand().exitOverride()
|
||||
const configFile = configFilePath(args)
|
||||
const file: ConfigFile = configFile ? readConfigFile(configFile) : {args: [], messages: defaultMessages}
|
||||
const file: ConfigFile = configFile ? readConfigFile(configFile) : {args: [], messages: defaultMessages, grokApiKey: null}
|
||||
try {
|
||||
cmd.parse([...file.args, ...args], {from: "user"})
|
||||
} catch (err) {
|
||||
@@ -145,7 +150,7 @@ export function parseConfig(args: string[]): Config {
|
||||
const opts = cmd.opts<RawOpts>()
|
||||
const given = (option: keyof RawOpts) => cmd.getOptionValueSource(option) === "cli"
|
||||
|
||||
const grokApiKey = process.env.GROK_API_KEY || null
|
||||
const grokApiKey = process.env.GROK_API_KEY || file.grokApiKey
|
||||
|
||||
let db: api.DbConfig
|
||||
if (opts.db === "sqlite") {
|
||||
@@ -179,7 +184,7 @@ export function parseConfig(args: string[]): Config {
|
||||
|
||||
const contextFile = opts.contextFile ?? null
|
||||
if (grokApiKey && !contextFile) {
|
||||
throw new Error("GROK_API_KEY is set but --context-file is not provided. Grok requires a context file.")
|
||||
throw new Error("A Grok API key is set but --context-file is not provided. Grok requires a context file.")
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -35,7 +35,7 @@ async function main(): Promise<void> {
|
||||
completeHours: config.completeHours,
|
||||
})
|
||||
const grokEnabled = config.grokApiKey !== null
|
||||
if (!grokEnabled) log("No GROK_API_KEY provided, disabling Grok support")
|
||||
if (!grokEnabled) log("No Grok API key in GROK_API_KEY or grok_api_key, disabling Grok support")
|
||||
|
||||
const stateFilePath = config.stateFile
|
||||
const state = readState(stateFilePath)
|
||||
|
||||
@@ -6,6 +6,8 @@ context_file = "/etc/support-bot/grok-context.yaml"
|
||||
state_file = "/data/state.json"
|
||||
db = "postgres"
|
||||
pg_conn = "postgres://simplex@127.0.0.1/simplex_support_bot"
|
||||
# Enables Grok replies; GROK_API_KEY takes precedence.
|
||||
# grok_api_key = "xai-..."
|
||||
timezone = "UTC"
|
||||
|
||||
# A message left out keeps its built-in text.
|
||||
|
||||
Reference in new issue
Block a user