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/nexus-ai/python-sdk.git
cd python-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.image.generate("A futuristic city")
print(image.url)

# With options
image = client.image.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.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"
)

# Or 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
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)

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

API Reference

For detailed API documentation, see docs/api_reference.md.

Examples

Check out the examples/ directory for more usage examples:

  • basic_usage.py - Core features demonstration
  • streaming_example.py - Streaming text generation
  • session_chat.py - Multi-turn conversations
  • knowledge_base_rag.py - RAG with knowledge bases

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

Changelog

v0.1.0 (2025-01-03)

  • 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.1.tar.gz (25.1 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.1-py3-none-any.whl (34.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: keystone_ai-0.2.1.tar.gz
  • Upload date:
  • Size: 25.1 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.1.tar.gz
Algorithm Hash digest
SHA256 04ab61b063cde8ac676638a355f0801e3523a6ad1a70ed208e2bc4726bee89f4
MD5 09ef7a90c82c5221c1d334075e807567
BLAKE2b-256 9663244cf67fd511f44b145d8627e0979d04bcc7af101554e3480109a150d083

See more details on using hashes here.

File details

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

File metadata

  • Download URL: keystone_ai-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 34.7 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 04c97d3bf47e41e566bdfbfde7e0d6fdc4fed359c130e4d384282edca6c9eb54
MD5 e523e2480481fd251d1d082f517176e5
BLAKE2b-256 e47b34b42d8606561c4531e0837289c6590a7a57895bfa3953d7b6d7af34dd21

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