johndotpub/DiscordianAI
关于
An Opensource AI bot that uses GPT models to provide chat-based interactions with users in Discord channels and via DMs. Supports a hybrid mode with Ollama (OpenAI compatible) and Perplexity API backends!
人工智能与机器学习实测星标增长
- 24小时
- 0
- 7天
- 0
- 15天
- 0
- 1个月
- 正在收集历史
各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。
README.md
原文DiscordianAI
DiscordianAI is a Discord bot that routes each message to an OpenAI-compatible chat provider or Perplexity, keeps conversation history per conversation, and formats replies for Discord. The shipped default chat backend is Ollama Cloud (https://ollama.com/v1/, model deepseek-v4.1-flash:1017); OpenAI remains supported by changing OPENAI_API_URL, GPT_MODEL, and OPENAI_API_KEY. GPT_MODEL is sent as configured, and any non-empty model identifier is accepted. PERPLEXITY_MODEL defaults to perplexity/sonar and the Perplexity path uses the current Agent API. The provider decides which model names are valid. See docs/API-CONTRACT.md for what is sent to each provider.
What Makes It Different
- Deterministic hybrid routing: the default heuristic gate decides each message from explicit overrides and bearing cues (things whose value can change); it uses no scores, weights, or thresholds. The OpenAI-compatible provider (Ollama Cloud by default) handles stable knowledge, reasoning, and creative prompts; Perplexity's Agent API handles live facts and returns citations. See docs/routing/DESIGN.md.
- Conversation history: History is keyed by guild channel (
g:<guild>:c:<channel>) or DM (dm:<user>) and is sent to both providers. A thread keeps its own history, separate from its parent. A short anaphoric or continuation follow-up inherits the previous turn's provider when one is recorded; other messages are decided from their own cues. - Discord-native output: Citation embeds, message splitting at Discord's 2000-character limit, and Perplexity link-preview suppression when a response contains two or more links. The OpenAI-compatible path does not suppress previews.
- Operations: Per-provider HTTP/2 connection pooling with HTTP/1.1 fallback, per-provider circuit breakers, and health checks after login plus HTTP endpoints that report observed provider and breaker state.
- Single-source configuration:
config.inior environment variables drive every mode. Startup validation stops on missing credentials, malformed URLs, and invalid limits; provider model ids are not gated.
Operation Modes
| Mode | What it does | When the chosen provider fails |
|---|---|---|
| 🧠 Smart Hybrid | Requires both clients. Builds one evidence-based routing decision per message, then sends live-data questions to Perplexity and stable/local questions to the OpenAI-compatible provider. | If Perplexity is selected and fails, the bot tries the chat provider and marks the answer degraded. If the chat provider is selected and returns no content, the bot tries Perplexity. A chat answer that says it cannot browse is rerouted only when Perplexity has not already failed in this request. Each provider is attempted at most once. If both fail, the bot sends an error notice. |
| 🤖 OpenAI-compatible Only | Requires only the chat client. Every message goes to the configured OpenAI-compatible model. | The bot sends an error notice. It does not fall back to Perplexity. |
| 🔍 Perplexity Only | Requires only the Perplexity client. Every message goes to the configured Perplexity model and citations are formatted into embeds. | The bot sends an error notice. It does not fall back to OpenAI. |
Quick Start
- Install Python 3.12 or newer.
- Clone & install:
git clone https://github.com/johndotpub/DiscordianAI.git cd DiscordianAI python3.12 -m venv .venv source .venv/bin/activate pip install -e ".[dev]" - Copy config:
cp config.ini.example config.ini - Set tokens in
config.ini(Discord, chat provider, Perplexity as needed). - Run the bot:
python -m src.main --conf config.ini(or the installed console script:discordianai --conf config.ini). In a server channel, mention the bot; guild messages without a mention are ignored. DMs need no mention. - Run tests before shipping:
pytest(coverage gate: 84% via tox/Codecov)
Runtime dependencies are declared in requirements.txt; pip install -r requirements.txt or pip install -e ".[dev]" installs them. The default
python:3.12-slim image needs no compiler.
Logs go to stderr. The bot does not open bot.log; the deprecated LOG_FILE setting is ignored. bot.log exists only when discordian.sh in daemon mode or a process supervisor captures stderr. Redirect stderr, or both streams with >> bot.log 2>&1; redirecting stdout alone produces an empty file.
Need the full Discord bot creation walkthrough and environment prep? See docs/Setup.md.
Running directly
python -m src.main --conf config.ini --folder /path/to/base/folder
--confpoints at the config file.--folder(optional) makes config paths relative to a base directory (useful for Docker or systemd units).- Logs go to stderr. The redirect or supervisor creates the file, for example
python -m src.main --conf config.ini >> bot.log 2>&1. The bot writes only to stderr, andLOG_FILEis deprecated and ignored. Redirecting only stdout leaves the file empty. - The installed console script accepts the same arguments:
discordianai --conf config.ini.
Running with the launcher script
The included discordian.sh script handles Python environment resolution, venv bootstrapping, and process management:
# Foreground (development)
./discordian.sh -c config.ini
# Daemon mode (cron, background)
./discordian.sh -d -c config.ini
# Specify project directory explicitly
./discordian.sh -d -c production.ini -f /opt/discordianai
# Install a systemd service (auto-detects paths)
./discordian.sh --install-systemd bot.ini
The launcher resolves Python in this order: project-local .venv (when its dependencies are present) → shell venv → pyenv → system python3. It also ensures the working directory is correct — no more ModuleNotFoundError: No module named 'src' when running from cron. In daemon mode it redirects both stdout and stderr to bot.log (>> bot.log 2>&1) and records each config's process ID in .bot-<stem>-<hash>.pid, where the hash comes from the resolved absolute config path so two configs with the same basename stay separate.
--install-systemd generates a complete systemd user unit from the config file name (e.g., bot.ini → [email protected]), writes it to ~/.config/systemd/user/, enables and starts it, and prints management commands. See docs/Daemon.md for both cron and systemd setup and for log rotation with the shipped contrib/logrotate/discordianai fragment.
Configuration Essentials
| Key | Purpose |
|---|---|
DISCORD_TOKEN |
Bot authentication token from the Discord Developer Portal. |
GPT_MODEL |
OpenAI-compatible model name sent as configured. Default deepseek-v4.1-flash:1017; any non-empty model identifier is accepted. |
PERPLEXITY_MODEL |
Perplexity model name. Default perplexity/sonar, the current Agent API Sonar model. Legacy Sonar names still answer on Chat Completions but are not used by this bot. |
INPUT_TOKENS / OUTPUT_TOKENS |
Prompt budget and chat completion cap. The output-cap parameter follows the host (see docs/API-CONTRACT.md); the cap includes reasoning tokens. |
PERPLEXITY_OUTPUT_TOKENS |
Perplexity completion cap, sent as max_output_tokens to the Agent API (output only). Defaults to OUTPUT_TOKENS. |
PERPLEXITY_INPUT_TOKENS |
Prompt budget for the Perplexity web path (default 111000). History is trimmed to it after the fixed fetch_url instructions are reserved. |
CONTEXT_WINDOW |
Chat-provider context window (default 1000000). The default chat model's window is 1,000,000 tokens; the value feeds the prompt budget and truncation, not an API usage limit. |
PERPLEXITY_CONTEXT_WINDOW |
Perplexity web-path context window (default 128000); the vendor citation for the figure is in docs/API-CONTRACT.md. |
LOOKBACK_MESSAGES_FOR_CONSISTENCY |
How many recent messages to inspect when a follow-up inherits the previous provider. |
ROUTER_MODE |
Router implementation, heuristic by default (deterministic, no network). clef uses Ollama Cloud's decision model (~0.4 s per message, consuming tokens) and falls back to the heuristic on failure; model is retired and raises. |
CONVERSATION_TTL_SECONDS |
Idle seconds before a conversation and its lock are evicted (default 7200). |
WEB_TOOLS |
Offer native web search and page fetch to Ollama-compatible chat providers (default true); OpenAI endpoints never receive these tools. |
OPENAI_MAX_CONNECTIONS / PERPLEXITY_MAX_CONNECTIONS |
HTTP/2 pool connection limits for each API client. |
CONTEXT_WINDOW is the chat-provider window, not a value shared with Perplexity. Perplexity
uses PERPLEXITY_INPUT_TOKENS and PERPLEXITY_CONTEXT_WINDOW; if an operator explicitly
lowers INPUT_TOKENS or CONTEXT_WINDOW, the smaller chat value also caps the Perplexity
prompt.
Channel Targeting
ALLOWED_CHANNELSmatches channel names case-insensitively (a leading#is ignored).ALLOWED_CHANNEL_IDSmatches channel IDs and takes precedence when set.ALLOWED_GUILDS/ALLOWED_GUILD_IDSnarrow name matching to configured servers; without them, names match in every guild the bot is in.- Threads are authorised by their parent channel's allowlist, but their conversation history uses the thread's own channel ID.
- Bot authors are answered like any other sender, but an answer never mentions the bot that sent the message. After two consecutive bot-authored turns in one conversation, the next is dropped until a human message resets the streak.
- Prefer IDs for stable targeting across servers; names are handy for local testing.
Minimal hybrid config
[Discord]
DISCORD_TOKEN=your_discord_bot_token
[Default]
OPENAI_API_KEY=your-ollama-cloud-api-key
OPENAI_API_URL=https://ollama.com/v1/
GPT_MODEL=deepseek-v4.1-flash:1017
REASONING_EFFORT=high
PERPLEXITY_API_KEY=pplx-your-perplexity-key
PERPLEXITY_MODEL=perplexity/sonar
INPUT_TOKENS=250000
OUTPUT_TOKENS=16384
SYSTEM_MESSAGE=You are a helpful assistant with access to current web information.
[Limits]
RATE_LIMIT=10
RATE_LIMIT_PER=60
Key Components
AI Orchestration
- src/smart_orchestrator.py asks
src/routing/for one evidence-based decision per message, owns provider selection and fallback, and writes the successful turn to history. - src/message_processor.py builds the per-conversation history snapshot and request, calls the orchestrator, and sends the reply.
- src/openai_processing.py sends the model, messages, an output cap, and
reasoning_effortwhen non-empty to the configured OpenAI-compatible provider. src/perplexity_processing.py sends the model,instructions,input,max_output_tokens, and theweb_searchtool to the Agent API; neither sends sampling parameters. Perplexity processing also requests native page fetching and handles citation extraction.
Discord User Experience
- src/discord_embeds.py formats Perplexity citations into embed descriptions and truncates descriptions above the 4096-character hard limit to the 3840-character safe limit.
- src/message_splitter.py splits at 2000 characters, uses 3840 as the safe embed split target and 4096 as the hard embed limit, keeps long code fences balanced across chunks, and provides the link-count check that the Perplexity path uses to suppress previews at two or more links. The OpenAI-compatible path always returns
False. - src/message_router.py handles mentions, DMs, channel and thread allowlists, bot-authored senders, and dispatch to the DM/channel processors.
Reliability & Ops
- src/connection_pool.py creates HTTP/2 clients with 100/20 connections for the chat provider and 40/10 for Perplexity, falling back to HTTP/1.1 when
h2is unavailable. - src/health_checks.py checks each configured provider after login; any non-empty model identifier is accepted. src/health_server.py serves liveness/readiness and reports observed provider and breaker state.
- src/api_validation.py rejects missing credentials, malformed URLs, and invalid limits. src/error_handling.py classifies errors and owns the retry and circuit-breaker policy.
Documentation Map
| Topic | Reference |
|---|---|
| Engineering contract | AGENTS.md |
| Provider request/response contract | docs/API-CONTRACT.md |
| Setup & onboarding | docs/Setup.md |
| Architecture & flow | docs/Architecture.md |
| Smart routing internals | docs/HybridMode.md |
| Configuration deep dive | docs/Configuration.md |
| OpenAI usage | docs/OpenAI.md |
| Perplexity usage & citations | docs/Perplexity.md |
| Message splitting & embeds | docs/MessageSplitting.md, docs/EmbedLimits.md |
| Web access tools | docs/WebScraping.md |
| Image attachments (vision) | docs/Vision.md |
| Connection pooling & HTTP/2 | docs/ConnectionPooling.md |
| Docker & daemonization | docs/Docker.md, docs/Daemon.md |
| Security & rate limiting | docs/Security.md |
| Development workflow | docs/Development.md |
| API parameter validation | docs/API_Validation.md |
Development Workflow
# Install dev extras
pip install -e ".[dev]"
# Lint & format
ruff check --fix .
black .
# Run the targeted suites
pytest -q
pytest tests/test_smart_orchestrator_coverage.py
Run the full local gate with scripts/preflight.sh: bash scripts/preflight.sh. It runs Black, Ruff, pytest, the Sphinx build, and a wheel build.
Use tox -e py312 for the canonical test run; the environment list and CI jobs are in
docs/Python_Versions.md.
Security Checklist
- Keep
config.iniout of version control; copy fromconfig.ini.exampleand setchmod 600 config.inion servers. - Prefer environment variables in production (
export DISCORD_TOKEN=...). - Rotate chat-provider and Perplexity (
pplx-...) keys regularly. - Limit Discord bot permissions to the channels where it operates.
- Prefer
ALLOWED_CHANNEL_IDSfor precise channel targeting in shared or multi-server deployments. - Native web tools return text the model must treat as untrusted reference material; tool instructions cannot make a model obey them. See docs/Security.md.
- Monitor logs for rate-limit bursts or web-tool failures and adjust
RATE_LIMIT/RATE_LIMIT_PERaccordingly.
Support & License
- Questions or feedback: [email protected]
- Issues and feature requests: open a GitHub issue.
- Licensed under the Unlicense.
探索相关项目
加载中…