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

Metadata

Release files for smaran-openai-sdk 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for smaran-openai-sdk 0.1.1
File Size Uploaded Provenance Actions
smaran_openai_sdk-0.1.1.tar.gz 9.4 kB With provenance Details for smaran_openai_sdk-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for smaran-openai-sdk 0.1.1
File Interpreter ABI Platform Actions
smaran_openai_sdk-0.1.1-py3-none-any.whl Python 3 none any Details for smaran_openai_sdk-0.1.1-py3-none-any.whl

Total release size: 20.6 kB

Release files / smaran_openai_sdk-0.1.1.tar.gz

Download URL smaran_openai_sdk-0.1.1.tar.gz
Size 9.4 kB
Tags Source
SHA-256 checksum
How to use checksums
a785da7258335c8ce2fbf516167bc1a2b309f4fe21870ba1a972b1e67f99269e
BLAKE2b-256 checksum
How to use checksums
a1539a7c10c3b4b98137955e28783c561066ebae614bf9459ff0599fc867e557
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 5, 2026.

Transparency log

Release files / smaran_openai_sdk-0.1.1-py3-none-any.whl

Download URL smaran_openai_sdk-0.1.1-py3-none-any.whl
Size 11.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f04151db7e97fee1f51fbaf39e60598d4550067e2927bb07f95c17701016b56f
BLAKE2b-256 checksum
How to use checksums
68c5a4b59a032b77da8d8c8ae029b446c8d016133251bb671246db4d0f15b3e8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 5, 2026.

Transparency log

Security for smaran-openai-sdk 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 2 files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for smaran_openai_sdk-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

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