Skip to main content

smaran-openai-sdk

Memory tools and middleware for the official OpenAI Python SDK with Smaran.

Installation

pip install smaran-openai-sdk

Quick Start

Automatic memory injection

import asyncio
from openai import AsyncOpenAI
from smaran_openai import with_smaran, OpenAIMiddlewareOptions

async def main():
    openai = AsyncOpenAI(api_key="your-openai-api-key")

    openai_with_memory = with_smaran(
        openai,
        OpenAIMiddlewareOptions(
            user_id="user-123",       # Required: memories are scoped to this
            session_id="chat-123",    # Optional: groups saved messages
            add_memory=True,          # Save the conversation after each call
        ),
        api_key="your-smaran-api-key",       # or set SMARAN_API_KEY
        base_url="https://your-smaran-url",  # or set SMARAN_URL
    )

    response = await openai_with_memory.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": "What's my favorite programming language?"}],
    )
    print(response.choices[0].message.content)

asyncio.run(main())

Memory tools (function calling)

import openai
from smaran_openai import SmaranTools, execute_memory_tool_calls

client = openai.AsyncOpenAI(api_key="your-openai-api-key")
tools = SmaranTools("your-smaran-api-key", {"user_id": "user-123"})

response = await client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant with access to user memories."},
        {"role": "user", "content": "Remember that I prefer tea over coffee"},
    ],
    tools=tools.get_tool_definitions(),
)

if response.choices[0].message.tool_calls:
    tool_results = await execute_memory_tool_calls(
        api_key="your-smaran-api-key",
        tool_calls=response.choices[0].message.tool_calls,
        config={"user_id": "user-123"},
    )

Sync client support

from openai import OpenAI
from smaran_openai import with_smaran, OpenAIMiddlewareOptions

openai = OpenAI(api_key="your-openai-api-key")
openai_with_memory = with_smaran(openai, OpenAIMiddlewareOptions(user_id="user-123"))

response = openai_with_memory.chat.completions.create(
    model="gpt-4", messages=[{"role": "user", "content": "Hello!"}]
)

If called from within a running event loop, the sync path falls back to a thread pool for the recall/save calls — the same interface either way.

Background task cleanup

When add_memory=True, saving happens as a background task so it doesn't add latency to the reply. Wait for it explicitly, or use the async context manager:

async with with_smaran(openai, OpenAIMiddlewareOptions(user_id="user-123")) as client:
    response = await client.chat.completions.create(...)
# background save tasks are awaited on exit

# or manually:
client = with_smaran(openai, OpenAIMiddlewareOptions(user_id="user-123"))
response = await client.chat.completions.create(...)
await client.wait_for_background_tasks()

Configuration

@dataclass
class OpenAIMiddlewareOptions:
    user_id: str                    # Required: memory scope
    session_id: Optional[str] = None  # Groups saved messages into one conversation
    verbose: bool = False
    add_memory: bool = True         # Save the conversation after each call
    search_limit: int = 5           # Max memories recalled per turn

SmaranTools

from smaran_openai import SmaranTools

tools = SmaranTools(
    "your-smaran-api-key",
    {"user_id": "user-123", "session_id": "chat-456", "base_url": "https://custom.example"},
)

result = await tools.search_memories(information_to_get="user preferences", limit=5)
result = await tools.add_memory(memory="User prefers tea over coffee")

Or use the individual-tool helpers (create_search_memories_tool, create_add_memory_tool) if you want each as its own object.

Error Handling

from smaran_openai import (
    SmaranConfigurationError,
    SmaranAPIError,
    SmaranNetworkError,
    SmaranMemoryOperationError,
)

try:
    client = with_smaran(openai_client, OpenAIMiddlewareOptions(user_id="user-123"))
except SmaranConfigurationError as e:
    print(f"Configuration issue: {e}")
  • SmaranError — base class for all exceptions here
  • SmaranConfigurationError — missing API key or base URL
  • SmaranAPIError — API request failures (includes status code)
  • SmaranNetworkError — network connectivity issues
  • SmaranMemoryOperationError — recall/save operation failures

Environment Variables

  • SMARAN_API_KEY — your Smaran API key
  • SMARAN_URL — your self-hosted or managed Smaran API base URL

Development

cd packages/openai-sdk-python
uv sync --dev
uv run pytest

License

MIT

Download files

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

Source Distribution

smaran_openai_sdk-0.1.1.tar.gz (9.4 kB view details)

Uploaded Source

Built Distribution

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

smaran_openai_sdk-0.1.1-py3-none-any.whl (11.2 kB view details)

Uploaded Python 3

File details

Details for the file smaran_openai_sdk-0.1.1.tar.gz.

File metadata

  • Download URL: smaran_openai_sdk-0.1.1.tar.gz
  • Upload date:
  • Size: 9.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for smaran_openai_sdk-0.1.1.tar.gz
Algorithm Hash digest
SHA256 a785da7258335c8ce2fbf516167bc1a2b309f4fe21870ba1a972b1e67f99269e
MD5 a72fd094f3d32faded220a500ad6dc9a
BLAKE2b-256 a1539a7c10c3b4b98137955e28783c561066ebae614bf9459ff0599fc867e557

See more details on using hashes here.

Provenance

The following attestation bundles were made for smaran_openai_sdk-0.1.1.tar.gz:

Publisher: publish-openai-sdk-python.yml on Ayushpani/smaran

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file smaran_openai_sdk-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for smaran_openai_sdk-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f04151db7e97fee1f51fbaf39e60598d4550067e2927bb07f95c17701016b56f
MD5 33b33891d7a0d1171a5c0c96665723a4
BLAKE2b-256 68c5a4b59a032b77da8d8c8ae029b446c8d016133251bb671246db4d0f15b3e8

See more details on using hashes here.

Provenance

The following attestation bundles were made for smaran_openai_sdk-0.1.1-py3-none-any.whl:

Publisher: publish-openai-sdk-python.yml on Ayushpani/smaran

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 files

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