Skip to main content

chatbot-oai

An out-of-the-box, lightweight Python module for building production-ready chat applications with OpenAI-compatible APIs. Features automatic tool/function calling, multi-round reasoning loops, flexible provider routing, and built-in token tracking.

📦 Installation

pip install chatbot-oai

🚀 Quick Start

A minimal working example using the default OpenRouter endpoint:

from chatbot_oai import BotConfig, ChatBot

bot = ChatBot(BotConfig())
response = bot.chat("Hello! Please introduce yourself briefly.")
print(response)

⚙️ Configuration

All settings are managed through the BotConfig dataclass. When instantiated without arguments, it defaults to the OpenRouter platform and reads OPENROUTER_API_KEY from your environment.

🔑 Environment Variable Setup

The module validates that your API key exists at initialization. Set it in your shell:

export OPENROUTER_API_KEY="sk-xxxxxxxx"

It's NOT recommanded to deliver API Key directly like bot_config = BotConfig(api_key="sk-xxxxxxxx")

🌍 Multi-Provider Support

Switch endpoints effortlessly by overriding base_url, env_key_name, and model. Provider-specific quirks can be passed via extra_body.

Local vLLM / llama.cpp

bot_conf = BotConfig(
    base_url="http://localhost:9998/v1",
    env_key_name="PRIVATE_KEY",  # Many local servers require a dummy key
    model="Qwopus-9B-Q4_K_M.gguf",
)

DeepSeek Official API

bot_conf = BotConfig(
    base_url="https://api.deepseek.com",
    env_key_name="DEEPSEEK_API_KEY",
    model="deepseek-v4-flash",
    extra_body={"thinking": {"type": "disabled"}},
)

🛠️ Custom Tools & Automatic Function Calling

Register Python functions as tools. The LLM will automatically decide when to call them, the module will execute them, feed results back into the context, and continue until no more tools are requested.

1. Define Your Function

def get_weather(city: str) -> str:
    """Returns weather information for a given city."""
    # Replace with real API call or mock data
    return f"The weather in {city} is currently sunny with 22°C."

2. Create the OpenAI-Compatible Schema

weather_schema = {
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Retrieve current weather conditions for a specific city.",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name"}
            },
            "required": ["city"]
        }
    }
}

3. Register & Use

bot = ChatBot(BotConfig())
bot.tool_register(weather_schema, "get_weather", get_weather)

response = bot.chat("What's the weather in Beijing?")
print(response)

🔁 How It Works Internally

  1. User sends a prompt → LLM decides whether to call a tool
  2. If tool calls are returned, _tools_handler() parses JSON arguments, executes the registered Python callable, and captures output
  3. Failed executions are caught, logged, and returned as structured error strings so the LLM can self-correct
  4. Tool results are appended to conversation history as "tool" role messages
  5. Loop continues until completion.choices[0].message.tool_calls is empty or max_tool_call_round is reached

You can use bot.context to show full chat contexts.

📄 License

MIT

Metadata

Release files for chatbot-oai 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for chatbot-oai 0.2.1
File Size Uploaded Provenance Actions
chatbot_oai-0.2.1.tar.gz 10.6 kB Without provenance Details for chatbot_oai-0.2.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for chatbot-oai 0.2.1
File Interpreter ABI Platform Actions
chatbot_oai-0.2.1-py3-none-any.whl Python 3 none any Details for chatbot_oai-0.2.1-py3-none-any.whl

Total release size: 17.2 kB

Release files / chatbot_oai-0.2.1.tar.gz

Download URL chatbot_oai-0.2.1.tar.gz
Size 10.6 kB
Tags Source
SHA-256 checksum
How to use checksums
7d721e446acfa9196c03d5ca27a0f23b33fdc8f8753f7da89a1a2afe62447696
BLAKE2b-256 checksum
How to use checksums
041fe10236cce70e83718ef40e25e8e1cb075233fe8d3e8223c55cfdc7ecfb3a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.12

Release files / chatbot_oai-0.2.1-py3-none-any.whl

Download URL chatbot_oai-0.2.1-py3-none-any.whl
Size 6.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1c612d3f229d9a4d194ba2bbd52aabaead270be95fc859794ec6daf6e0bec1da
BLAKE2b-256 checksum
How to use checksums
0fba74a33ba7a3345101eb2c80c41f379cfaf5a86304bf991fe8073970271fc7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.12

Security for chatbot-oai 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page