Skip to main content

Official Python SDK for SVECTOR AI Models - Advanced conversational AI and language models

Project description

SVECTOR Python SDK

PyPI version
Python Version
License: MIT
Downloads

Official Python SDK for accessing SVECTOR APIs.

SVECTOR is a technology-driven organization focused on AI, Mathematics, and Computational research, developing high-performance AI models, mathematical reasoning systems, and next-gen automation. This Python SDK provides convenient access to SVECTOR's powerful foundational AI models including Spec-3, Spec-3-Turbo, Theta-35, and Theta-35-Mini.

The library includes type hints for request parameters and response fields, and offers both synchronous and asynchronous clients powered by httpx and requests.

๐Ÿš€ Quick Start

pip install svector-sdk
from svector import SVECTOR

client = SVECTOR(api_key="your-api-key")  # or set SVECTOR_API_KEY env var

# Sophisticated conversation API - just provide instructions and input!
response = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a helpful AI assistant that explains complex topics clearly.",
    input="What is artificial intelligence?",
)

print(response.output)

๐Ÿ“š Table of Contents

๐Ÿ“ฆ Installation

pip

pip install svector-sdk

Development Install

git clone https://github.com/svector-corporation/svector-python
cd svector-python
pip install -e ".[dev]"

๐Ÿ” Authentication

Get your API key from the SVECTOR Dashboard and set it as an environment variable:

export SVECTOR_API_KEY="your-api-key-here"

Or pass it directly to the client:

from svector import SVECTOR

client = SVECTOR(api_key="your-api-key-here")

โญ Core Features

  • ๐Ÿค– Sophisticated Conversations API - Simple instructions + input interface
  • ๐Ÿ’ฌ Advanced Chat Completions - Full control with role-based messages
  • ๐ŸŒŠ Real-time Streaming - Server-sent events for live responses
  • ๐Ÿ“ File Processing - Upload and process documents (PDF, DOCX, TXT, etc.)
  • ๐Ÿง  Knowledge Collections - Organize files for enhanced RAG
  • ๐Ÿ”ง Type Safety - Full type hints and IntelliSense support
  • โšก Async Support - AsyncSVECTOR client for high-performance applications
  • ๐Ÿ›ก๏ธ Robust Error Handling - Comprehensive error types and retry logic
  • ๐ŸŒ Multi-environment - Works everywhere Python runs

๐ŸŽฏ Conversations API (Recommended)

The Conversations API provides a sophisticated, user-friendly interface. Just provide instructions and input - the SDK handles all the complex role management internally!

Basic Conversation

from svector import SVECTOR

client = SVECTOR()

response = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a helpful assistant that explains things clearly.",
    input="What is machine learning?",
    temperature=0.7,
    max_tokens=200,
)

print(response.output)
print(f"Request ID: {response.request_id}")
print(f"Token Usage: {response.usage}")

Conversation with Context

response = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a programming tutor that helps students learn coding.",
    input="Can you show me an example?",
    context=[
        "How do I create a function in Python?",
        "You can create a function using the def keyword followed by the function name and parameters..."
    ],
    temperature=0.5,
)

Streaming Conversation

stream = client.conversations.create_stream(
    model="spec-3-turbo:latest",
    instructions="You are a creative storyteller.",
    input="Tell me a short story about robots and humans.",
    stream=True,
)

print("Story: ", end="", flush=True)
for event in stream:
    if not event.done:
        print(event.content, end="", flush=True)
    else:
        print("\nโœ“ Story completed!")

Document-based Conversation

# First upload a document
with open("research-paper.pdf", "rb") as f:
    file_response = client.files.create(f, purpose="rag")

# Then ask questions about it
response = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a research assistant that analyzes documents.",
    input="What are the key findings in this paper?",
    files=[{"type": "file", "id": file_response.file_id}],
)

๐Ÿ”ง Chat Completions API (Advanced)

For full control over the conversation structure, use the Chat Completions API with role-based messages:

Basic Chat

response = client.chat.create(
    model="spec-3-turbo:latest",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello, how are you?"}
    ],
    max_tokens=150,
    temperature=0.7,
)

print(response["choices"][0]["message"]["content"])

Multi-turn Conversation

conversation = [
    {"role": "system", "content": "You are a helpful programming assistant."},
    {"role": "user", "content": "How do I reverse a string in Python?"},
    {"role": "assistant", "content": "You can reverse a string using slicing: string[::-1]"},
    {"role": "user", "content": "Can you show me other methods?"}
]

response = client.chat.create(
    model="spec-3-turbo:latest",
    messages=conversation,
    temperature=0.5,
)

Developer Role (System-level Instructions)

response = client.chat.create(
    model="spec-3-turbo:latest",
    messages=[
        {"role": "developer", "content": "You are an expert code reviewer. Provide detailed feedback."},
        {"role": "user", "content": "Please review this Python code: def add(a, b): return a + b"}
    ],
)

๐ŸŒŠ Streaming Responses

Both Conversations and Chat APIs support real-time streaming:

Conversations Streaming

stream = client.conversations.create_stream(
    model="spec-3-turbo:latest",
    instructions="You are a creative writer.",
    input="Write a poem about technology.",
    stream=True,
)

for event in stream:
    if not event.done:
        print(event.content, end="", flush=True)
    else:
        print("\nโœ“ Stream completed")

Chat Streaming

stream = client.chat.create_stream(
    model="spec-3-turbo:latest",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain quantum computing"}
    ],
    stream=True,
)

for event in stream:
    if "choices" in event and len(event["choices"]) > 0:
        delta = event["choices"][0].get("delta", {})
        content = delta.get("content", "")
        if content:
            print(content, end="", flush=True)

๐Ÿ“ File Management & Document Processing

Upload and process various file formats for enhanced AI capabilities:

Upload from File

from pathlib import Path

# PDF document
with open("document.pdf", "rb") as f:
    pdf_file = client.files.create(f, purpose="rag")

# Text file from path
file_response = client.files.create(
    Path("notes.txt"), 
    purpose="rag"
)

print(f"File uploaded: {file_response.file_id}")

Upload from Bytes

with open("document.pdf", "rb") as f:
    data = f.read()

file_response = client.files.create(
    data, 
    purpose="rag", 
    filename="document.pdf"
)

Upload from String Content

content = """
# Research Notes
This document contains important findings...
"""

file_response = client.files.create(
    content.encode(), 
    purpose="rag", 
    filename="notes.md"
)

Document Q&A

# Upload documents
with open("manual.pdf", "rb") as f:
    doc1 = client.files.create(f, purpose="rag")

with open("faq.docx", "rb") as f:
    doc2 = client.files.create(f, purpose="rag")

# Ask questions about the documents
answer = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a helpful assistant that answers questions based on the provided documents.",
    input="What are the key features mentioned in the manual?",
    files=[
        {"type": "file", "id": doc1.file_id},
        {"type": "file", "id": doc2.file_id}
    ],
)

๐Ÿง  Knowledge Collections

Organize multiple files into collections for better performance and context management:

# Add files to a knowledge collection
result1 = client.knowledge.add_file("collection-123", "file-456")
result2 = client.knowledge.add_file("collection-123", "file-789")

# Use the entire collection in conversations
response = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a research assistant with access to our knowledge base.",
    input="Summarize all the information about our products.",
    files=[{"type": "collection", "id": "collection-123"}],
)

๐Ÿค– Models

SVECTOR provides several cutting-edge foundational AI models:

Available Models

# List all available models
models = client.models.list()
print(models["models"])

SVECTOR's Foundational Models:

  • spec-3-turbo:latest - Fast, efficient model for most use cases
  • spec-3:latest - Standard model with balanced performance
  • theta-35-mini:latest - Lightweight model for simple tasks
  • theta-35:latest - Advanced model for complex reasoning

Model Selection Guide

# For quick responses and general tasks
quick_response = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a helpful assistant.",
    input="What time is it?",
)

# For complex reasoning and analysis
complex_analysis = client.conversations.create(
    model="theta-35:latest",
    instructions="You are an expert data analyst.",
    input="Analyze the trends in this quarterly report.",
    files=[{"type": "file", "id": "report-file-id"}],
)

# For lightweight tasks
simple_task = client.conversations.create(
    model="theta-35-mini:latest",
    instructions="You help with simple questions.",
    input="What is 2 + 2?",
)

๐Ÿ›ก๏ธ Error Handling

The SDK provides comprehensive error handling with specific error types:

from svector import (
    SVECTOR, 
    AuthenticationError, 
    RateLimitError, 
    NotFoundError,
    APIError
)

client = SVECTOR()

try:
    response = client.conversations.create(
        model="spec-3-turbo:latest",
        instructions="You are a helpful assistant.",
        input="Hello world",
    )
    
    print(response.output)
except AuthenticationError as e:
    print(f"โŒ Invalid API key: {e}")
    print("๐Ÿ’ก Get your API key from https://www.svector.co.in")
except RateLimitError as e:
    print(f"โฐ Rate limit exceeded: {e}")
    print("๐Ÿ”„ Please wait before making another request")
except NotFoundError as e:
    print(f"๐Ÿ” Resource not found: {e}")
except APIError as e:
    print(f"๐Ÿšจ API error: {e} (Status: {e.status_code})")
    print(f"๐Ÿ“‹ Request ID: {getattr(e, 'request_id', 'N/A')}")
except Exception as e:
    print(f"๐Ÿ’ฅ Unexpected error: {e}")

Available Error Types

  • AuthenticationError - Invalid API key or authentication issues
  • PermissionDeniedError - Insufficient permissions for the resource
  • NotFoundError - Requested resource not found
  • RateLimitError - API rate limit exceeded
  • UnprocessableEntityError - Invalid request data or parameters
  • InternalServerError - Server-side errors
  • APIConnectionError - Network connection issues
  • APIConnectionTimeoutError - Request timeout

โšก Async Support

The SDK provides full async support with AsyncSVECTOR:

Async Basic Usage

import asyncio
from svector import AsyncSVECTOR

async def main():
    async with AsyncSVECTOR() as client:
        response = await client.conversations.create(
            model="spec-3-turbo:latest",
            instructions="You are a helpful assistant.",
            input="Explain quantum computing in simple terms.",
        )
        print(response.output)

asyncio.run(main())

Async Streaming

async def streaming_example():
    async with AsyncSVECTOR() as client:
        stream = await client.conversations.create_stream(
            model="spec-3-turbo:latest",
            instructions="You are a creative storyteller.",
            input="Write a poem about technology.",
            stream=True,
        )
        
        async for event in stream:
            if not event.done:
                print(event.content, end="", flush=True)
        print()

asyncio.run(streaming_example())

Async Concurrent Requests

async def concurrent_example():
    async with AsyncSVECTOR() as client:
        # Multiple async conversations
        tasks = [
            client.conversations.create(
                model="spec-3-turbo:latest",
                instructions="You are a helpful assistant.",
                input=f"What is {topic}?"
            )
            for topic in ["artificial intelligence", "quantum computing", "blockchain"]
        ]
        
        responses = await asyncio.gather(*tasks, return_exceptions=True)
        
        topics = ["artificial intelligence", "quantum computing", "blockchain"]
        for topic, response in zip(topics, responses):
            if isinstance(response, Exception):
                print(f"โŒ {topic}: Error - {response}")
            else:
                print(f"โœ… {topic}: {response.output[:100]}...")

asyncio.run(concurrent_example())

โš™๏ธ Advanced Configuration

Client Configuration

from svector import SVECTOR

client = SVECTOR(
    api_key="your-api-key",
    base_url="https://spec-chat.tech",           # Custom API endpoint
    timeout=30,                                  # Request timeout in seconds
    max_retries=3,                               # Retry failed requests
    verify_ssl=True,                             # SSL verification
    http_client=None,                            # Custom HTTP client
)

Async Configuration

from svector import AsyncSVECTOR

client = AsyncSVECTOR(
    api_key="your-api-key",
    timeout=30,
    max_retries=3,
)

Per-request Options

response = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a helpful assistant.",
    input="Hello",
    timeout=60,           # Override timeout for this request
    headers={             # Additional headers
        "X-Custom-Header": "value",
        "X-Request-Source": "my-app"
    }
)

Raw Response Access

# Get both response data and raw HTTP response
response, raw = client.conversations.create_with_response(
    model="spec-3-turbo:latest",
    instructions="You are a helpful assistant.",
    input="Hello",
)

print(f"Status: {raw.status_code}")
print(f"Headers: {raw.headers}")
print(f"Response: {response.output}")
print(f"Request ID: {response.request_id}")

๐Ÿ’ก Complete Examples

Intelligent Chat Application

from svector import SVECTOR

class IntelligentChat:
    def __init__(self, api_key: str):
        self.client = SVECTOR(api_key=api_key)
        self.conversation_history = []

    def chat(self, user_message: str, system_instructions: str = None) -> str:
        # Add user message to history
        self.conversation_history.append(user_message)

        response = self.client.conversations.create(
            model="spec-3-turbo:latest",
            instructions=system_instructions or "You are a helpful and friendly AI assistant.",
            input=user_message,
            context=self.conversation_history[-10:],  # Keep last 10 messages
            temperature=0.7,
        )

        # Add AI response to history
        self.conversation_history.append(response.output)
        return response.output

    def stream_chat(self, user_message: str):
        print("๐Ÿค– Assistant: ", end="", flush=True)
        
        stream = self.client.conversations.create_stream(
            model="spec-3-turbo:latest",
            instructions="You are a helpful AI assistant. Be conversational and engaging.",
            input=user_message,
            context=self.conversation_history[-6:],
            stream=True,
        )

        full_response = ""
        for event in stream:
            if not event.done:
                print(event.content, end="", flush=True)
                full_response += event.content
        print()

        self.conversation_history.append(user_message)
        self.conversation_history.append(full_response)

    def clear_history(self):
        self.conversation_history = []

# Usage
import os
chat = IntelligentChat(os.environ.get("SVECTOR_API_KEY"))

# Regular chat
print(chat.chat("Hello! How are you today?"))

# Streaming chat
chat.stream_chat("Tell me an interesting fact about space.")

# Specialized chat
print(chat.chat(
    "Explain quantum computing", 
    "You are a physics professor who explains complex topics in simple terms."
))

Document Analysis System

from svector import SVECTOR
from pathlib import Path

class DocumentAnalyzer:
    def __init__(self):
        self.client = SVECTOR()
        self.uploaded_files = []

    def add_document(self, file_path: str) -> str:
        try:
            with open(file_path, "rb") as f:
                file_response = self.client.files.create(
                    f, 
                    purpose="rag",
                    filename=Path(file_path).name
                )
            
            self.uploaded_files.append(file_response.file_id)
            print(f"โœ… Uploaded: {file_path} (ID: {file_response.file_id})")
            return file_response.file_id
        except Exception as error:
            print(f"โŒ Failed to upload {file_path}: {error}")
            raise error

    def add_document_from_text(self, content: str, filename: str) -> str:
        file_response = self.client.files.create(
            content.encode(), 
            purpose="rag", 
            filename=filename
        )
        self.uploaded_files.append(file_response.file_id)
        return file_response.file_id

    def analyze(self, query: str, analysis_type: str = "insights") -> str:
        instructions = {
            "summary": "You are an expert document summarizer. Provide clear, concise summaries.",
            "questions": "You are an expert analyst. Answer questions based on the provided documents with citations.",
            "insights": "You are a research analyst. Extract key insights, patterns, and important findings."
        }

        response = self.client.conversations.create(
            model="spec-3-turbo:latest",
            instructions=instructions[analysis_type],
            input=query,
            files=[{"type": "file", "id": file_id} for file_id in self.uploaded_files],
            temperature=0.3,  # Lower temperature for more factual responses
        )

        return response.output

    def compare_documents(self, query: str) -> str:
        if len(self.uploaded_files) < 2:
            raise ValueError("Need at least 2 documents to compare")

        return self.analyze(
            f"Compare and contrast the documents regarding: {query}",
            "insights"
        )

    def get_uploaded_file_ids(self):
        return self.uploaded_files.copy()

# Usage
analyzer = DocumentAnalyzer()

# Add multiple documents
analyzer.add_document("./reports/quarterly-report.pdf")
analyzer.add_document("./reports/annual-summary.docx")
analyzer.add_document_from_text("""
# Meeting Notes
Key decisions:
1. Increase R&D budget by 15%
2. Launch new product line in Q3
3. Expand team by 5 engineers
""", "meeting-notes.md")

# Analyze documents
summary = analyzer.analyze(
    "Provide a comprehensive summary of all documents",
    "summary"
)
print("๐Ÿ“„ Summary:", summary)

insights = analyzer.analyze(
    "What are the key business decisions and their potential impact?",
    "insights"
)
print("๐Ÿ’ก Insights:", insights)

# Compare documents
comparison = analyzer.compare_documents(
    "financial performance and future projections"
)
print("๐Ÿ” Comparison:", comparison)

Multi-Model Comparison

from svector import SVECTOR
import time

class ModelComparison:
    def __init__(self):
        self.client = SVECTOR()

    def compare_models(self, prompt: str):
        models = ["spec-3-turbo:latest", "spec-3:latest", "theta-35:latest", "theta-35-mini:latest"]
        
        print(f"๐Ÿ”ฌ Comparing models for prompt: \"{prompt}\"\n")

        results = []
        for model in models:
            try:
                start_time = time.time()
                
                response = self.client.conversations.create(
                    model=model,
                    instructions="You are a helpful assistant. Be concise but informative.",
                    input=prompt,
                    max_tokens=150,
                )
                
                duration = time.time() - start_time
                
                results.append({
                    "model": model,
                    "response": response.output,
                    "duration": duration,
                    "usage": response.usage,
                    "success": True
                })
                
            except Exception as e:
                results.append({
                    "model": model,
                    "error": str(e),
                    "success": False
                })

        # Display results
        for result in results:
            if result["success"]:
                print(f"๐Ÿ“Š Model: {result['model']}")
                print(f"โฑ๏ธ  Duration: {result['duration']:.2f}s")
                print(f"๐Ÿ“ˆ Tokens: {result['usage'].get('total_tokens', 'N/A')}")
                print(f"๐Ÿ’ฌ Response: {result['response'][:200]}...")
                print("โ”€" * 80)
            else:
                print(f"โŒ {result['model']} failed: {result['error']}")

# Usage
comparison = ModelComparison()
comparison.compare_models("Explain the concept of artificial general intelligence")

๐ŸŽฏ Best Practices

1. Use Conversations API for Simplicity

# โœ… Recommended: Clean and simple
response = client.conversations.create(
    model="spec-3-turbo:latest",
    instructions="You are a helpful assistant.",
    input=user_message,
)

# โŒ More complex: Manual role management
response = client.chat.create(
    model="spec-3-turbo:latest",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": user_message}
    ],
)

2. Handle Errors Gracefully

import time

def chat_with_retry(client, prompt, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.conversations.create(
                model="spec-3-turbo:latest",
                instructions="You are helpful.",
                input=prompt
            )
        except RateLimitError:
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # Exponential backoff
                time.sleep(wait_time)
            else:
                raise

3. Use Appropriate Models

# For quick responses
model = "spec-3-turbo:latest"

# For complex reasoning
model = "theta-35:latest"

# For simple tasks
model = "theta-35-mini:latest"

4. Optimize File Usage

# โœ… Upload once, use multiple times
with open("document.pdf", "rb") as f:
    file_response = client.files.create(f, purpose="rag")
    file_id = file_response.file_id

# Use in multiple conversations
for question in questions:
    response = client.conversations.create(
        model="spec-3-turbo:latest",
        instructions="You are a document analyst.",
        input=question,
        files=[{"type": "file", "id": file_id}],
    )

5. Environment Variables

import os
from svector import SVECTOR

# โœ… Use environment variables
client = SVECTOR(api_key=os.environ.get("SVECTOR_API_KEY"))

# โŒ Don't hardcode API keys
client = SVECTOR(api_key="sk-hardcoded-key-here")  # Never do this!

6. Use Context Managers for Async

# โœ… Recommended: Use context manager
async with AsyncSVECTOR() as client:
    response = await client.conversations.create(...)

# โŒ Manual cleanup required
client = AsyncSVECTOR()
try:
    response = await client.conversations.create(...)
finally:
    await client.close()

๐Ÿงช Testing

Run tests with pytest:

# Install test dependencies
pip install -e ".[test]"

# Run tests
pytest

# Run with coverage
pytest --cov=svector

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch
  3. Install development dependencies: pip install -e ".[dev]"
  4. Make your changes
  5. Add tests and documentation
  6. Run tests and linting
  7. Submit a pull request

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ”— Links & Support


Built with โค๏ธ by SVECTOR Corporation - Pushing the boundaries of AI, Mathematics, and Computational research

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

svector_sdk-1.1.2.tar.gz (32.9 kB view details)

Uploaded Source

Built Distribution

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

svector_sdk-1.1.2-py3-none-any.whl (31.3 kB view details)

Uploaded Python 3

File details

Details for the file svector_sdk-1.1.2.tar.gz.

File metadata

  • Download URL: svector_sdk-1.1.2.tar.gz
  • Upload date:
  • Size: 32.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.11

File hashes

Hashes for svector_sdk-1.1.2.tar.gz
Algorithm Hash digest
SHA256 81af71447850760e70cdf16555d49f65de0d3c319b7053aa7a9966cefa180608
MD5 a51d33af310a2e2f8dfe81457d26c2e3
BLAKE2b-256 41cdfa42fbb333befa3c762958737518b74cd7bbb87a7797acfb55698208d964

See more details on using hashes here.

File details

Details for the file svector_sdk-1.1.2-py3-none-any.whl.

File metadata

  • Download URL: svector_sdk-1.1.2-py3-none-any.whl
  • Upload date:
  • Size: 31.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.11

File hashes

Hashes for svector_sdk-1.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 f3ecfae5b2e1dcf0255389d244592ea28dbf9a4861a2af7559d5dfd368a59e5f
MD5 17079e4446e6bdf957a3cbf69b82fdcb
BLAKE2b-256 8f8417815e2da1b790732221725f4fc0d71aa105af65b63ea8c6af7c1b5728de

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