Skip to main content

Python SDK for Renbase Context-as-a-Service

Project description

Renbase Python SDK

Python SDK for Renbase Context-as-a-Service API.

Python 3.9+ PyPI version

Developer Preview 🚧

This library is currently in early alpha. The API is subject to change and requires a private invitation to the Renbase platform to function.

Table of Contents


Installation

pip install renbase

With LangChain support:

pip install renbase[langchain]

From source (development):

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

Quick Start

from renbase import RenbaseClient

client = RenbaseClient(api_key="rb_live_xxx")
result = client.context.query("How do I configure authentication?")

for chunk in result.chunks:
    print(f"[{chunk.score:.2f}] {chunk.content[:100]}...")

Authentication

Using API Key

from renbase import RenbaseClient

client = RenbaseClient(api_key="rb_live_xxx")

Using Environment Variable

export RENBASE_API_KEY=rb_live_xxx
from renbase import RenbaseClient

client = RenbaseClient()  # Reads from RENBASE_API_KEY

Tip: Never hardcode API keys in your code. Use environment variables or a secrets manager.


API Reference

Context

Query your knowledge base for relevant context.

client.context.query(text, top_k=5)

Parameter Type Default Description
text str required Search query
top_k int 5 Number of results (max: 100)

Returns: ContextResponse

result = client.context.query("How to setup SSO?", top_k=10)

for chunk in result.chunks:
    print(f"Score: {chunk.score}")
    print(f"Source: {chunk.source}")
    print(f"Title: {chunk.document_title}")
    print(f"Content: {chunk.content}")
    print("---")

Documents

Upload, list, and delete documents.

client.documents.upload(file_path, metadata=None)

Parameter Type Default Description
file_path str required Path to file
metadata dict None Optional metadata

Returns: Document

doc = client.documents.upload(
    "./report.pdf",
    metadata={"department": "engineering", "year": 2024}
)
print(f"Document ID: {doc.id}")

client.documents.list(limit=50, offset=0, source_type=None)

Parameter Type Default Description
limit int 50 Results per page (max: 250)
offset int 0 Pagination offset
source_type str None Filter: upload, confluence, google_drive

Returns: ListDocumentsResponse

response = client.documents.list(limit=10, source_type="upload")

print(f"Total documents: {response.total}")
for doc in response.documents:
    print(f"[{doc.processing_status}] {doc.title} ({doc.mime_type})")

client.documents.delete(document_id)

Parameter Type Default Description
document_id str required Document UUID

Returns: None (202 Accepted)

client.documents.delete("550e8400-e29b-41d4-a716-446655440000")

Feedback

Submit feedback on query results.

client.feedback.create(query_id, score, comment=None)

Parameter Type Default Description
query_id str required Query UUID
score int required 1 (positive) or -1 (negative)
comment str None Optional comment

Returns: Feedback

feedback = client.feedback.create(
    query_id="550e8400-e29b-41d4-a716-446655440000",
    score=1,
    comment="Very helpful result!"
)
print(f"Feedback ID: {feedback.id}")

Async Usage

Use RenbaseAsyncClient for async/await support.

import asyncio
from renbase import RenbaseAsyncClient

async def main():
    async with RenbaseAsyncClient(api_key="rb_live_xxx") as client:
        # Query context
        result = await client.context.query("authentication setup")
        print(f"Found {len(result.chunks)} chunks")

        # Upload document
        doc = await client.documents.upload("./guide.pdf")
        print(f"Uploaded: {doc.id}")

        # List documents
        docs = await client.documents.list(limit=5)
        for d in docs.documents:
            print(f"- {d.title}")

asyncio.run(main())

Framework Integration

FastAPI

from fastapi import FastAPI, HTTPException
from renbase import RenbaseAsyncClient
from contextlib import asynccontextmanager

client: RenbaseAsyncClient = None

@asynccontextmanager
async def lifespan(app: FastAPI):
    global client
    client = RenbaseAsyncClient()
    yield
    await client.close()

app = FastAPI(lifespan=lifespan)

@app.get("/search")
async def search(q: str, top_k: int = 5):
    result = await client.context.query(q, top_k=top_k)
    return {
        "chunks": [
            {"content": c.content, "score": c.score}
            for c in result.chunks
        ]
    }

@app.post("/documents")
async def upload_document(file_path: str):
    doc = await client.documents.upload(file_path)
    return {"id": str(doc.id)}

Django

# views.py
from django.http import JsonResponse
from renbase import RenbaseClient

client = RenbaseClient()

def search(request):
    query = request.GET.get("q", "")
    top_k = int(request.GET.get("top_k", 5))

    result = client.context.query(query, top_k=top_k)

    return JsonResponse({
        "chunks": [
            {"content": c.content, "score": c.score}
            for c in result.chunks
        ]
    })

def list_documents(request):
    limit = int(request.GET.get("limit", 50))
    response = client.documents.list(limit=limit)

    return JsonResponse({
        "total": response.total,
        "documents": [
            {"id": str(d.id), "title": d.title, "status": d.processing_status}
            for d in response.documents
        ]
    })

LangChain Integration

Install with LangChain support:

pip install renbase[langchain]

Basic Usage

from renbase import RenbaseClient
from renbase.integrations.langchain import RenbaseRetriever

client = RenbaseClient(api_key="rb_live_xxx")
retriever = RenbaseRetriever(client=client, top_k=5)

# Use as any LangChain retriever
docs = retriever.invoke("How to configure SSO?")
for doc in docs:
    print(doc.page_content)

RAG Chain Example

from renbase import RenbaseClient
from renbase.integrations.langchain import RenbaseRetriever
from langchain_openai import ChatOpenAI
from langchain.chains import RetrievalQA

client = RenbaseClient(api_key="rb_live_xxx")
retriever = RenbaseRetriever(client=client, top_k=5)
llm = ChatOpenAI(model="gpt-4")

chain = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=retriever
)

answer = chain.invoke("How do I set up SSO?")
print(answer["result"])

Error Handling

All exceptions inherit from RenbaseError.

Exception HTTP Status Description
BadRequestError 400 Invalid request parameters
AuthenticationError 401 Invalid or missing API key
PaymentRequiredError 402 Insufficient credits
NotFoundError 404 Resource not found
RateLimitError 429 Too many requests
APIError 5xx Server error
from renbase import RenbaseClient
from renbase.exceptions import (
    RenbaseError,
    AuthenticationError,
    RateLimitError,
    NotFoundError,
)

client = RenbaseClient(api_key="rb_live_xxx")

try:
    result = client.context.query("test")
except AuthenticationError as e:
    print(f"Auth failed: {e.message}")
except RateLimitError as e:
    print(f"Rate limited: {e.message}")
except NotFoundError as e:
    print(f"Not found: {e.message}")
except RenbaseError as e:
    print(f"API error ({e.status_code}): {e.message}")

Configuration

Parameter Type Default Description
api_key str RENBASE_API_KEY env API key
base_url str https://api.renbase.ai API base URL
timeout float 30.0 Request timeout (seconds)
from renbase import RenbaseClient

client = RenbaseClient(
    api_key="rb_live_xxx",
    base_url="https://api.renbase.ai",
    timeout=60.0
)

Response Models

ContextResponse

class ContextResponse:
    query_id: UUID | None  # Not yet available
    chunks: list[ChunkResult]

ChunkResult

class ChunkResult:
    document_id: UUID
    content: str
    score: float           # 0.0 to 1.0
    source: str            # "upload", "confluence", "google_drive"
    document_title: str | None
    source_url: str | None
    project_name: str | None

Document

class Document:
    id: UUID

DocumentSummary

class DocumentSummary:
    id: UUID
    title: str
    mime_type: str
    source_type: str | None
    processing_status: str  # "pending", "processing", "completed", "failed"
    created_at: datetime

ListDocumentsResponse

class ListDocumentsResponse:
    documents: list[DocumentSummary]
    total: int
    limit: int
    offset: int

Feedback

class Feedback:
    id: UUID
    query_id: UUID
    score: int
    created_at: datetime

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

renbase-0.1.0a1.tar.gz (13.4 kB view details)

Uploaded Source

Built Distribution

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

renbase-0.1.0a1-py3-none-any.whl (13.1 kB view details)

Uploaded Python 3

File details

Details for the file renbase-0.1.0a1.tar.gz.

File metadata

  • Download URL: renbase-0.1.0a1.tar.gz
  • Upload date:
  • Size: 13.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for renbase-0.1.0a1.tar.gz
Algorithm Hash digest
SHA256 859d1b633000fc9582e89f1d8882ae867ae601782767f9703036eaf00d4df05e
MD5 fc5012b4ce0e4b73be549ae215a8c261
BLAKE2b-256 bd72c086cad2bbd84e6c14bbc393529d7ac4b5b875b13f3058a1ff648e1b0e32

See more details on using hashes here.

File details

Details for the file renbase-0.1.0a1-py3-none-any.whl.

File metadata

  • Download URL: renbase-0.1.0a1-py3-none-any.whl
  • Upload date:
  • Size: 13.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for renbase-0.1.0a1-py3-none-any.whl
Algorithm Hash digest
SHA256 e006e81f2cf4768f95b6ba8f150843181319c2ce992169c0018f6c9822ce3c34
MD5 161c23a127bff522a4444ef4d429ab2a
BLAKE2b-256 489517b25ff61595be17fd29f8da4b995bc9b3b722fcb9a584ceb878e15adee7

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