Skip to main content
The ThrindexOpenAI wrapper replaces your OpenAI instance. Every chat.completions.create call automatically retrieves relevant memories and injects them into the system prompt before the call, then captures the conversation turn as a new memory after it. Memory retrieval failures are always silent — if Thrindex is unreachable, the underlying OpenAI call proceeds unaffected.

Install

pip install 'thrindex[openai]'

Usage

Synchronous

from openai import OpenAI
from thrindex import Thrindex
from thrindex.integrations.openai import ThrindexOpenAI

thrindex = Thrindex(api_key="th_live_...")
openai = OpenAI()

client = ThrindexOpenAI(
    thrindex_client=thrindex,
    openai_client=openai,
    agent_id="support-agent",
    user_id="user-42",
)

# Use exactly like openai.chat.completions.create — memory is automatic
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What notification style do I prefer?"}],
)

Asynchronous

from openai import AsyncOpenAI
from thrindex import AsyncThrindex
from thrindex.integrations.openai import ThrindexAsyncOpenAI

client = ThrindexAsyncOpenAI(
    thrindex_client=AsyncThrindex(api_key="th_live_..."),
    openai_client=AsyncOpenAI(),
    agent_id="support-agent",
    user_id="user-42",
)

response = await client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What notification style do I prefer?"}],
)

Options

ParameterTypeDefaultDescription
thrindex_clientThrindex | AsyncThrindexrequiredA configured Thrindex client instance
openai_clientOpenAI | AsyncOpenAINone (auto-creates from env)Your OpenAI client instance
agent_idstrrequiredAgent identifier for memory scoping
user_idstrrequiredUser identifier for memory scoping
inject_kint5Number of memories to retrieve and inject per call
injectboolTrueWhether to inject memories before the call
captureboolTrueWhether to store conversation turns after the call
capture_assistantboolTrueWhen True, captures both the user message and the assistant reply as a single turn (richer extraction context). Set to False to capture only the user message.
format_memoriesCallablebullet listCustom formatter taking a list[SearchHit] and returning a str.

Custom memory format

You can fully control how memories are formatted in the system prompt. This is useful when you want XML tags, numbered lists, or any format your model responds to best.
def xml_formatter(hits):
    lines = ["<memory_context>"]
    for hit in hits:
        lines.append(f"  <memory importance='{hit.importance:.2f}'>{hit.content}</memory>")
    lines.append("</memory_context>")
    return "\n".join(lines)

client = ThrindexOpenAI(
    thrindex_client=thrindex,
    openai_client=openai,
    agent_id="support-agent",
    user_id="user-42",
    format_memories=xml_formatter,
)