Skip to main content

Python SDK for Nexus AI Platform - The keystone of your AI applications

Project description

Nexus AI Python SDK

Python Version PyPI version License

Official Python SDK for Nexus AI - A unified AI capabilities platform.

🎉 Stable Release v0.2.1

Production Ready - 95.2% test pass rate with 100% P0 core features passing.

Installation:

pip install keystone-ai

Quick Start:

from nexusai import NexusAIClient

client = NexusAIClient(api_key="your_api_key")
response = client.text.generate("Hello, AI!")
print(response.text)

Features

  • 🚀 Simple & Intuitive - Clean API design with sensible defaults
  • 🔄 Multi-Model Support - 6 text models + 2 image models
  • 📡 Streaming - Real-time streaming for text generation
  • 💬 Session Management - Stateful conversations with automatic context handling
  • 🧠 Knowledge Bases - RAG capabilities with semantic search
  • 🎨 Multi-Modal - Text, images, audio (ASR), and document processing
  • 🔐 Type-Safe - Full type hints with Pydantic models
  • 🌐 Production Ready - Defaults to production API at https://nexus-ai.juncai-ai.com/api/v1

Installation

pip install keystone-ai

国内镜像加速:

# 清华镜像
pip install keystone-ai -i https://pypi.tuna.tsinghua.edu.cn/simple

# 阿里云镜像
pip install keystone-ai -i https://mirrors.aliyun.com/pypi/simple/

从源码安装:

git clone https://github.com/aidrshao/nexus-ai-sdk.git
cd nexus-ai-sdk
poetry install

Quick Start

1. Set up your API key

Create a .env file in your project root:

NEXUS_API_KEY=nxs_your_api_key_here
# SDK automatically uses production: https://nexus-ai.juncai-ai.com/api/v1
# For local development, set: NEXUS_BASE_URL=http://localhost:8000/api/v1

2. Initialize the client

from nexusai import NexusAIClient

# Simple - uses production API automatically
client = NexusAIClient(api_key="nxs_your_api_key")

# Or read from environment variables
client = NexusAIClient()

# For local development
client = NexusAIClient(
    api_key="nxs_your_api_key",
    base_url="http://localhost:8000/api/v1"
)

3. Generate text

# Simple mode (省心模式) - uses default model
response = client.text.generate("写一首关于春天的诗")
print(response.text)

# With model selection
response = client.text.generate(
    prompt="Explain quantum computing",
    model="gpt-5-mini",       # Recommended: fast and cost-effective
    temperature=0.7,
    max_tokens=500
)
print(response.text)
print(f"Tokens used: {response.usage.total_tokens}")

# Available models (三档体系):
# 🥇 高端: "gpt-5" (fastest premium), "gemini-2.5-pro" (strongest reasoning)
# 🥈 中端: "gpt-5-mini" (recommended), "gpt-4o-mini" (alternative)
# 🥉 经济: "deepseek-v3.2-exp" (cheapest)

4. Stream text generation

for chunk in client.text.stream("Tell me a story"):
    if "delta" in chunk:
        print(chunk["delta"].get("content", ""), end="", flush=True)
print()

5. Work with sessions (conversations)

# Create a session
session = client.sessions.create(
    name="My Chat",
    agent_config={
        "model": "gpt-5-mini",   # Recommended model for conversations
        "temperature": 0.7
    }
)

# Have a conversation
response = session.invoke("My name is Alice")
print(response.response.content)

response = session.invoke("What's my name?")
print(response.response.content)  # Remembers "Alice"

# Get conversation history
history = session.history()
for message in history:
    print(f"{message.role}: {message.content}")

6. Generate images

# Simple mode
image = client.images.generate("A futuristic city")
print(image.image_url)

# With options
image = client.images.generate(
    prompt="A sunset over mountains, digital art",
    model="doubao-seedream-4-0-250828",  # Default recommended model (ByteDance Doubao)
    aspect_ratio="16:9",                  # Use ratio instead of pixel size
    num_images=1
)
print(f"Image: {image.image_url}")

# Supported aspect ratios: "1:1", "16:9", "9:16", "4:3", "3:4", "21:9"
# Image models: "doubao-seedream-4-0-250828" (default), "gemini-2.5-flash-image" (alternative)

7. Speech-to-Text (ASR)

# Upload audio file
file_meta = client.files.upload("meeting.mp3")

# Transcribe
transcription = client.audio.transcribe(
    file_id=file_meta.file_id,
    language="zh"
)
print(transcription.text)

8. Knowledge Base & RAG

# Create knowledge base
kb = client.knowledge_bases.create(
    name="Company Docs",
    description="Internal documentation"
)

# Upload documents (uses unified file architecture internally)
task = client.knowledge_bases.upload_document(
    kb_id=kb.kb_id,
    file="policy.pdf"
)

# ⚠️ Important: Document processing is asynchronous!
# The task object contains task_id but NOT doc_id
# doc_id is available after processing completes (10-60 seconds)

# Method 1: Poll for completion
import time
while True:
    status = client._internal_client.request("GET", f"/tasks/{task.task_id}")
    if status["status"] == "completed":
        doc_id = status["output"]["doc_id"]
        print(f"Document processed: {doc_id}")
        break
    time.sleep(2)

# Method 2: Use two-step process for file reuse
file_meta = client.files.upload("policy.pdf")
task = client.knowledge_bases.add_document(kb.kb_id, file_meta.file_id)
# Same file can be added to multiple knowledge bases!

# Search (after documents are processed)
results = client.knowledge_bases.search(
    query="What is the vacation policy?",
    knowledge_base_ids=[kb.kb_id],
    top_k=3
)

# Use results for RAG
context = "\n\n".join([r.content for r in results.results])
answer = client.text.generate(
    prompt=f"Based on this context:\n{context}\n\nQuestion: What is the vacation policy?"
)
print(answer.text)

📖 Important: Knowledge base document processing is asynchronous. See Knowledge Base Async Guide for complete details on handling async operations.

Configuration

The SDK can be configured via environment variables or constructor parameters:

Environment Variable Default Description
NEXUS_API_KEY (required) Your API key
NEXUS_BASE_URL https://nexus-ai.juncai-ai.com/api/v1 API base URL
NEXUS_TIMEOUT 30 Request timeout (seconds)
NEXUS_MAX_RETRIES 3 Maximum retry attempts
NEXUS_POLL_INTERVAL 2 Task polling interval (seconds)
NEXUS_POLL_TIMEOUT 300 Task polling timeout (seconds)

Production vs Development Mode

Production Mode (Default):

# Uses production API by default - zero configuration needed!
client = NexusAIClient(api_key="nxs_your_api_key")
# → Connects to https://nexus-ai.juncai-ai.com/api/v1

Local Development Mode:

# Set environment variable
export NEXUS_BASE_URL=http://localhost:8000/api/v1

Or in code:

client = NexusAIClient(
    api_key="nxs_dev_key",
    base_url="http://localhost:8000/api/v1"
)

Error Handling

The SDK provides specific exception types for different error scenarios:

from nexusai import NexusAIClient
from nexusai.error import (
    AuthenticationError,
    RateLimitError,
    NotFoundError,
    APITimeoutError,
)

client = NexusAIClient()

try:
    response = client.text.generate("Hello")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except NotFoundError:
    print("Resource not found")
except APITimeoutError:
    print("Request timed out")
except Exception as e:
    print(f"Unexpected error: {e}")

Context Manager

The client supports context manager for automatic cleanup:

with NexusAIClient() as client:
    response = client.text.generate("Hello")
    print(response.text)
# Client automatically closed

📚 Complete Documentation

📖 Complete Documentation Index - All documentation in one place

Quick Links

Code Examples

Check out the examples/ directory:

Model Documentation

Text Models (6 available):

  • 🥇 Premium: gpt-5, gemini-2.5-pro
  • 🥈 Standard: gpt-5-mini
  • 🥉 Budget: deepseek-v3.2-exp (default), gpt-4o-mini

Image Models (2 available):

  • doubao-seedream-4-0-250828 (default)
  • gemini-2.5-flash-image

Requirements

  • Python 3.8+
  • httpx >= 0.25.0
  • pydantic >= 2.5.0
  • python-dotenv >= 1.0.0

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support & Community

Star History

If you find this project helpful, please consider giving it a ⭐ on GitHub!

Changelog

v0.1.0 (2025-10-04)

  • Initial release
  • Text generation (sync, async, streaming)
  • Image generation
  • Session management
  • Audio processing (ASR/TTS)
  • Knowledge base management
  • File upload system
  • Full type hints with Pydantic

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

keystone_ai-0.2.2.tar.gz (25.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

keystone_ai-0.2.2-py3-none-any.whl (35.5 kB view details)

Uploaded Python 3

File details

Details for the file keystone_ai-0.2.2.tar.gz.

File metadata

  • Download URL: keystone_ai-0.2.2.tar.gz
  • Upload date:
  • Size: 25.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for keystone_ai-0.2.2.tar.gz
Algorithm Hash digest
SHA256 7c6ed5aa51251b2094e8bbd1dd01ed120acdade232ccd4fd34fa23d651153ee2
MD5 1a8d8f9c8df1a540a17c7d9b95a6efef
BLAKE2b-256 9fa7db98c9ac0aff63be8c52fe7f18dffa6bdc5c6fde4e4333838e026db67c6d

See more details on using hashes here.

File details

Details for the file keystone_ai-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: keystone_ai-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 35.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for keystone_ai-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 34e00e826e2dbd9583f0827eff35bbf114b892792e88f90c0af0b506ae8fb5a9
MD5 b4a93a5c93e1ddf950089e49b8e27a68
BLAKE2b-256 bc80faa27033b97281b20427f212997ab6e3e6b2d958e42422867d78bc78d2cf

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page