Compare commits

..
25 Commits
Author SHA1 Message Date
Nicolò Boschi be45b4367d formatting 2025-12-16 13:22:17 +01:00
Nicolò Boschi 8905461d99 formatting 2025-12-16 13:21:53 +01:00
Nicolò Boschi 4b2772c47a rm llms-full from repo 2025-12-16 13:15:04 +01:00
Nicolò Boschi 122d16569c ci: test notebooks on ci 2025-12-16 13:10:52 +01:00
Nicolò Boschi f6da55c5e6 ci: test notebooks on ci 2025-12-16 13:09:17 +01:00
Nicolò Boschi 3e5efc314d bump pg0 0.11.x and improve documentation 2025-12-16 12:21:49 +01:00
Nicolò Boschi ceae079234 bump pg0 0.11.x and improve documentation 2025-12-16 12:21:44 +01:00
Nicolò Boschi 4e85510ad2 bump pg0 0.11.x and improve documentation 2025-12-16 12:10:00 +01:00
Nicolò Boschi bb1f9cb221 feat: support for gemini-3-pro and gpt-5.2 (#30)
* feat: support for gemini-3-pro and gpt-5.2

* feat: support for gemini-3-pro and gpt-5.2

* feat: support for gemini-3-pro and gpt-5.2

* feat: support for gemini-3-pro and gpt-5.2

* feat: add local mcp server

* docs

* docs
2025-12-16 11:00:27 +01:00
Nicolò Boschi 7dd68538bb feat: add local mcp server (#32) 2025-12-16 10:50:20 +01:00
Nicolò Boschi 1cef364719 enable model tests on ci (#29) 2025-12-15 15:18:09 +01:00
Nicolò Boschi dff293ca8c fix doc link styling 2025-12-15 14:54:56 +01:00
Nicolò Boschi f4bc8443b3 changelog generator 2025-12-15 14:46:14 +01:00
Nicolò Boschi ae26a8603b models doc 2025-12-15 11:34:34 +01:00
Nicolò Boschi 183b9dacb4 Release v0.1.5
- Update version to 0.1.5 in all components
- Python packages: hindsight-api, hindsight-dev, hindsight-dev/benchmarks, hindsight-all, hindsight-litellm
- Python client: hindsight-clients/python
- TypeScript client: hindsight-clients/typescript
- Rust CLI: hindsight-cli
- Control Plane: hindsight-control-plane
- Helm chart
2025-12-15 10:48:53 +01:00
Nicolò Boschi 8a7c6e4e91 litellm release integration 2025-12-15 10:48:27 +01:00
DK09876andClaude Opus 4.5 dfccbf29f1 Added hindsight_liteLLM implementation (#17)
* Added hindsight_liteLLM implementation

* Add instructions for entity vs bank id

* Add another line about entity

* Address PR review comments and enhance litellm integration

- Remove deprecated limit parameter from recall() and arecall() functions
  since Hindsight uses budget/max_tokens for result control
- Remove dead MODEL_MAX_OUTPUT_TOKENS dict and max_output_tokens property
  from LLMProvider (superseded by hardcoded max_completion_tokens)
- Add test-litellm-integration job to CI workflow
- Add reflect API support with use_reflect config option
- Add verbose mode debug info via get_last_injection_debug()
- Add entity_id support for multi-user memory isolation
- Add retain() and reflect() wrapper functions
- Update docstrings and examples

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Make max_memories optional to allow unlimited memory injection

- Change max_memories default from 10 to None (no limit)
- When max_memories is None, all results from the API are used
- Fix recall result handling to properly detect list vs object return
- Update wrappers (OpenAI, Anthropic) with same optional behavior

This allows users to control memory limits via max_memory_tokens
and recall_budget without an artificial count limit.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Remove entity_id from hindsight_litellm; add gpt-4o token cap

Multi-user support now uses separate bank_ids per user instead of
entity_id scoping (e.g., bank_id=f"user-{user_id}"). This simplifies
the API and aligns with the Hindsight architecture.

Also fixes max_completion_tokens error for gpt-4o models by capping
the value at 16384 (gpt-4o's limit) instead of sending the default
65000 which exceeds the model's supported maximum.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Fix dark mode styling across Control Plane UI components

Improvements to ensure proper text visibility and contrast in both light
and dark modes:

- Add global CSS rules for datetime-local calendar picker icon visibility
  using filter: invert() for both light (0.5) and dark (1) modes
- Fix text colors in dialog components to use theme-aware foreground colors
- Update memory detail panel, document/chunk modals, and data views to use
  proper dark mode text classes (text-foreground, text-card-foreground)
- Fix form labels, headings, and content text in bank selector dialogs
- Update entities view and documents view table styling for dark mode
- Bump package versions to 0.1.4

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Remove session_id feature and add How It Works section to README

- Remove session_id and session management (new_session, set_session,
  get_session) from config.py, callbacks.py, and __init__.py
- Session management was a client-only abstraction not backed by core API
- Add "How It Works" section to README with visual flow diagram
- Update README to remove session management documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Fix readme example

* Add dark mode again

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
2025-12-15 10:42:19 +01:00
Chris Latimer dfea4dbe15 Trademark to README 2025-12-14 18:58:34 -07:00
Derek Bouius fcea8afa6c Change npm packaging structure and fix contributing info (#16)
* change the package to workspace concept

* add provider name and change default model

* add the node_modules to git ignore

* change the npm runs to use workspace

* fix the start scripts to use the workspace

* update the uv.lock

* updated instructions

* update the docker build to use the npm workspace

* Update package-lock.json after merge to sync workspace dependencies

* fix merge conflict
2025-12-12 14:14:19 -05:00
Nicolò Boschi 94c2b85c81 switch to pg0-embedded (#28)
* switch to pg0-embedded

* switch to pg0-embedded

* stricter mcp lib
2025-12-12 19:13:26 +01:00
Chris Bartholomew 160c5581ec fix: add DOM.Iterable lib to resolve URLSearchParams.entries() type error (#27)
The generated queryKeySerializer.gen.ts uses URLSearchParams.entries() which
requires DOM.Iterable in the TypeScript lib config for proper type definitions.
2025-12-12 17:34:47 +01:00
Nicolò Boschi 70983f5817 fix 400 retries on llm 2025-12-12 17:15:56 +01:00
Chris Latimer 44e9571572 README banner 2025-12-12 09:03:59 -07:00
Nicolò Boschi 7445cef7b7 feat: add optional graph retriever MPFP (#26)
* feat: add optional graph retriever MPFP

* feat: add optional graph retriever MPFP
2025-12-12 16:58:50 +01:00
Derek Bouius f018cc5677 fix: upgrade Next.js to 16.0.10 to patch CVE-2025-55184 and CVE-2025-55183 (#25)
CVE-2025-55184 (High) - Denial of Service via malicious HTTP request
CVE-2025-55183 (Medium) - Source Code Exposure of Server Actions

Reference: https://vercel.com/kb/bulletin/security-bulletin-cve-2025-55184-and-cve-2025-55183
2025-12-12 16:43:26 +01:00
93 changed files with 20358 additions and 20779 deletions
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# Pre-commit hook - runs all scripts in scripts/hooks/
set -e
REPO_ROOT="$(git rev-parse --show-toplevel)"
HOOKS_DIR="$REPO_ROOT/scripts/hooks"
if [ ! -d "$HOOKS_DIR" ]; then
exit 0
fi
echo ""
echo "=== Running pre-commit hooks ==="
echo ""
# Run all executable scripts in hooks directory
for hook in "$HOOKS_DIR"/*.sh; do
if [ -x "$hook" ]; then
echo "[hook] $(basename "$hook")"
(cd "$REPO_ROOT" && "$hook")
fi
done
echo ""
echo "=== Pre-commit hooks completed ==="
echo ""
-11
View File
@@ -1,11 +0,0 @@
name: 'Setup pg0'
description: 'Install pg0 embedded PostgreSQL'
runs:
using: 'composite'
steps:
- name: Install pg0
shell: bash
run: |
curl -fsSL https://raw.githubusercontent.com/vectorize-io/pg0/main/install.sh | bash
echo "$HOME/.pg0/bin" >> $GITHUB_PATH
+5 -6
View File
@@ -20,18 +20,17 @@ concurrency:
jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: hindsight-docs
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: hindsight-docs/package-lock.json
- run: npm ci
- run: npm run build
cache-dependency-path: package-lock.json
- uses: astral-sh/setup-uv@v4
- run: npm ci --workspace=hindsight-docs
- run: uv run generate-llms-full
- run: npm run build --workspace=hindsight-docs
- uses: actions/upload-pages-artifact@v3
with:
path: hindsight-docs/build
+17 -48
View File
@@ -38,6 +38,10 @@ jobs:
working-directory: ./hindsight
run: uv build --out-dir dist
- name: Build hindsight-litellm
working-directory: ./hindsight-integrations/litellm
run: uv build --out-dir dist
# Publish in order (client and api first, then hindsight-all which depends on them)
- name: Publish hindsight-client to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
@@ -57,6 +61,12 @@ jobs:
packages-dir: ./hindsight/dist
skip-existing: true
- name: Publish hindsight-litellm to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
packages-dir: ./hindsight-integrations/litellm/dist
skip-existing: true
# Upload artifacts for GitHub release
- name: Upload artifacts
uses: actions/upload-artifact@v4
@@ -66,6 +76,7 @@ jobs:
hindsight-clients/python/dist/*
hindsight-api/dist/*
hindsight/dist/*
hindsight-integrations/litellm/dist/*
retention-days: 1
release-typescript-client:
@@ -80,14 +91,14 @@ jobs:
with:
node-version: '20'
registry-url: 'https://registry.npmjs.org'
cache: 'npm'
cache-dependency-path: package-lock.json
- name: Install dependencies
working-directory: ./hindsight-clients/typescript
run: npm ci
run: npm ci --workspace=hindsight-clients/typescript
- name: Build
working-directory: ./hindsight-clients/typescript
run: npm run build
run: npm run build --workspace=hindsight-clients/typescript
- name: Publish to npm
working-directory: ./hindsight-clients/typescript
@@ -306,6 +317,7 @@ jobs:
cp artifacts/python-packages/hindsight-clients/python/dist/* release-assets/ || true
cp artifacts/python-packages/hindsight-api/dist/* release-assets/ || true
cp artifacts/python-packages/hindsight/dist/* release-assets/ || true
cp artifacts/python-packages/hindsight-integrations/litellm/dist/* release-assets/ || true
# TypeScript client
cp artifacts/typescript-client/*.tgz release-assets/ || true
# Rust CLI binaries
@@ -316,54 +328,11 @@ jobs:
cp artifacts/helm-chart/*.tgz release-assets/ || true
ls -la release-assets/
- name: Generate release notes
run: |
cat << 'EOF' > release-notes.md
## Quick Start
```bash
# Install the CLI
curl -fsSL https://raw.githubusercontent.com/vectorize-io/hindsight/refs/heads/main/hindsight-cli/install.sh | bash
# Start the server
docker run -p 8888:8888 -p 9999:9999 \
-e HINDSIGHT_API_LLM_PROVIDER=openai \
-e HINDSIGHT_API_LLM_API_KEY=$OPENAI_API_KEY \
-e HINDSIGHT_API_LLM_MODEL=gpt-4o-mini \
ghcr.io/${{ github.repository_owner }}/hindsight:${{ steps.get_version.outputs.VERSION }}
```
## Docker Images
- `ghcr.io/${{ github.repository_owner }}/hindsight:${{ steps.get_version.outputs.VERSION }}` - Standalone (recommended)
- `ghcr.io/${{ github.repository_owner }}/hindsight-api:${{ steps.get_version.outputs.VERSION }}` - API only
- `ghcr.io/${{ github.repository_owner }}/hindsight-control-plane:${{ steps.get_version.outputs.VERSION }}` - Web UI only
## CLI
```bash
curl -fsSL https://raw.githubusercontent.com/vectorize-io/hindsight/refs/heads/main/hindsight-cli/install.sh | bash
```
## Python
```bash
pip install hindsight-all # or hindsight-api, hindsight-client
```
## TypeScript/JavaScript
```bash
npm install @vectorize-io/hindsight-client
```
## Helm
```bash
helm install hindsight oci://ghcr.io/${{ github.repository_owner }}/charts/hindsight --version ${{ steps.get_version.outputs.VERSION }}
```
EOF
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
files: release-assets/*
body_path: release-notes.md
generate_release_notes: true
draft: false
prerelease: false
env:
+84 -16
View File
@@ -9,6 +9,54 @@ concurrency:
cancel-in-progress: true
jobs:
build-python-packages:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- name: hindsight-all
path: hindsight
- name: hindsight-api
path: hindsight-api
- name: hindsight-client
path: hindsight-clients/python
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version-file: ".python-version"
- name: Build ${{ matrix.name }}
working-directory: ./${{ matrix.path }}
run: uv build
build-typescript-client:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: package-lock.json
- name: Install dependencies
run: npm ci --workspace=hindsight-clients/typescript
- name: Build TypeScript client
run: npm run build --workspace=hindsight-clients/typescript
build-docs:
runs-on: ubuntu-latest
@@ -19,14 +67,14 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: package-lock.json
- name: Install dependencies
working-directory: ./hindsight-docs
run: npm ci
run: npm ci --workspace=hindsight-docs
- name: Build docs
working-directory: ./hindsight-docs
run: npm run build
run: npm run build --workspace=hindsight-docs
build-rust-cli:
runs-on: ubuntu-latest
@@ -106,6 +154,9 @@ jobs:
env:
HINDSIGHT_API_LLM_PROVIDER: groq
HINDSIGHT_API_LLM_API_KEY: ${{ secrets.GROQ_API_KEY }}
GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
HINDSIGHT_API_LLM_MODEL: openai/gpt-oss-20b
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Prefer CPU-only PyTorch in CI (but keep PyPI for everything else)
@@ -125,9 +176,6 @@ jobs:
with:
python-version-file: ".python-version"
- name: Install pg0
uses: ./.github/actions/setup-pg0
- name: Build API
working-directory: ./hindsight-api
run: uv build
@@ -185,9 +233,6 @@ jobs:
with:
python-version-file: ".python-version"
- name: Install pg0
uses: ./.github/actions/setup-pg0
- name: Build API
working-directory: ./hindsight-api
run: uv build
@@ -269,9 +314,6 @@ jobs:
with:
node-version: '20'
- name: Install pg0
uses: ./.github/actions/setup-pg0
- name: Build API
working-directory: ./hindsight-api
run: uv build
@@ -360,9 +402,6 @@ jobs:
hindsight-clients/rust/target
key: ${{ runner.os }}-cargo-client-${{ hashFiles('hindsight-clients/rust/Cargo.lock') }}
- name: Install pg0
uses: ./.github/actions/setup-pg0
- name: Build API
working-directory: ./hindsight-api
run: uv build
@@ -405,3 +444,32 @@ jobs:
run: |
echo "=== API Server Logs ==="
cat /tmp/api-server.log || echo "No API server log found"
test-litellm-integration:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install uv
uses: astral-sh/setup-uv@v5
with:
enable-cache: true
prune-cache: false
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version-file: ".python-version"
- name: Build litellm integration
working-directory: ./hindsight-integrations/litellm
run: uv build
- name: Install dependencies
working-directory: ./hindsight-integrations/litellm
run: uv sync --extra dev
- name: Run tests
working-directory: ./hindsight-integrations/litellm
run: uv run pytest tests -v
+6
View File
@@ -9,6 +9,9 @@ wheels/
# Virtual environments
.venv
# Node
node_modules/
# Environment variables
.env
@@ -29,6 +32,9 @@ logs/
.DS_Store
# Generated docs files
hindsight-docs/static/llms-full.txt
hindsight-dev/benchmarks/locomo/results/
hindsight-dev/benchmarks/longmemeval/results/
+14 -4
View File
@@ -5,13 +5,23 @@ Thanks for your interest in contributing to Hindsight!
## Getting Started
1. Fork and clone the repository
2. Install dependencies:
```bash
cd hindsight-api && uv sync
git clone [email protected]:vectorize-io/hindsight.git
cd hindsight
```
3. Set up your environment:
2. Set up your environment:
```bash
export OPENAI_API_KEY=your-key
cp .env.example .env
```
Edit the .env to add LLM API key and config as required
3. Install dependencies:
```bash
# Python dependencies
uv sync --directory hindsight-api/
# Node dependencies (uses npm workspaces)
npm install
```
## Development
+2 -2
View File
@@ -1,6 +1,6 @@
<div align="center">
![Hindsight Banner](./hindsight-docs/static/img/banner.webp)
![Hindsight Banner](./hindsight-docs/static/img/banner.svg)
[Documentation](https://vectorize-io.github.io/hindsight) • [Paper](#coming-soon) • [Examples](https://github.com/vectorize-io/hindsight-cookbook)
@@ -18,7 +18,7 @@
## What is Hindsight?
Hindsight is an agent memory system built to create smarter agents that learn over time. It eliminates the shortcomings of alternative techniques such as RAG and knowledge graph.
Hindsight is an agent memory system built to create smarter agents that learn over time. It eliminates the shortcomings of alternative techniques such as RAG and knowledge graph.
Hindsight addresses common challenges that have frustrated AI engineers building agents to automate tasks and assist users with conversational interfaces. Many of these challenges stem directly from a lack of memory.
+21 -68
View File
@@ -54,13 +54,15 @@ FROM node:20-slim AS sdk-builder
ARG INCLUDE_CP
RUN if [ "$INCLUDE_CP" != "true" ]; then echo "Skipping SDK build" && exit 0; fi
WORKDIR /app/sdk
WORKDIR /app
COPY hindsight-clients/typescript/package*.json ./
RUN npm ci
# Copy root package files for npm workspaces
COPY package.json package-lock.json ./
COPY hindsight-clients/typescript/ ./hindsight-clients/typescript/
COPY hindsight-clients/typescript/ ./
RUN npm run build
# Install and build SDK using workspace (--ignore-scripts skips git hooks setup)
RUN npm ci --ignore-scripts -w @vectorize-io/hindsight-client
RUN npm run build -w @vectorize-io/hindsight-client
# =============================================================================
# Stage: Control Plane Builder
@@ -73,7 +75,7 @@ RUN if [ "$INCLUDE_CP" != "true" ]; then echo "Skipping CP build" && exit 0; fi
WORKDIR /app
# Copy built SDK
COPY --from=sdk-builder /app/sdk /app/sdk
COPY --from=sdk-builder /app/hindsight-clients/typescript /app/sdk
# Install Control Plane dependencies
# Only copy package.json (not package-lock.json) to ensure npm installs
@@ -130,38 +132,10 @@ RUN mkdir -p /app/data && chown -R hindsight:hindsight /app
USER hindsight
# Set PATH for hindsight user
ENV PATH="/home/hindsight/.hindsight/bin:/app/api/.venv/bin:${PATH}"
ENV PATH="/app/api/.venv/bin:${PATH}"
# Install pg0 binary
RUN mkdir -p /home/hindsight/.hindsight/bin && \
ARCH=$(uname -m) && \
if [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then \
PG0_BINARY="pg0-linux-aarch64-gnu"; \
elif [ "$ARCH" = "x86_64" ]; then \
PG0_BINARY="pg0-linux-x86_64-gnu"; \
else \
echo "Unsupported architecture: $ARCH" && exit 1; \
fi && \
echo "Installing pg0 binary: $PG0_BINARY" && \
for i in 1 2 3 4 5; do \
curl -fsSL -o /home/hindsight/.hindsight/bin/pg0 \
"https://github.com/vectorize-io/pg0/releases/latest/download/$PG0_BINARY" && \
chmod +x /home/hindsight/.hindsight/bin/pg0 && \
ls -lh /home/hindsight/.hindsight/bin/pg0 && \
file /home/hindsight/.hindsight/bin/pg0 && \
ldd /home/hindsight/.hindsight/bin/pg0 2>&1 || true && \
break || (echo "Retry $i failed, waiting..." && sleep 10); \
done && \
echo "Testing pg0 binary..." && \
/home/hindsight/.hindsight/bin/pg0 --version || (echo "pg0 --version failed with exit code $?"; ldd /home/hindsight/.hindsight/bin/pg0; exit 1)
# Pre-download PostgreSQL binaries
# Pre-cache PostgreSQL binaries by starting/stopping pg0-embedded
ENV PG0_HOME=/home/hindsight/.pg0-cache
RUN pg0 start --help && \
(pg0 start --name hindsight --port 5555 --username hindsight --password hindsight --database hindsight && \
sleep 2 && \
pg0 stop --name hindsight && \
echo "PostgreSQL pre-cached to $PG0_HOME") || echo "Pre-download skipped"
ENV PG0_HOME=/home/hindsight/.pg0
@@ -193,7 +167,7 @@ FROM node:20-alpine AS cp-only
WORKDIR /app
# Copy built SDK
COPY --from=sdk-builder /app/sdk /app/sdk
COPY --from=sdk-builder /app/hindsight-clients/typescript /app/sdk
# Copy Control Plane standalone build
WORKDIR /app/control-plane
@@ -246,7 +220,7 @@ RUN useradd -m -s /bin/bash hindsight
COPY --from=api-builder /app/api /app/api
# Copy built SDK
COPY --from=sdk-builder /app/sdk /app/sdk
COPY --from=sdk-builder /app/hindsight-clients/typescript /app/sdk
# Copy Control Plane standalone build
WORKDIR /app/control-plane
@@ -267,38 +241,17 @@ RUN mkdir -p /app/data && chown -R hindsight:hindsight /app
USER hindsight
# Set PATH for hindsight user
ENV PATH="/home/hindsight/.hindsight/bin:/app/api/.venv/bin:${PATH}"
ENV PATH="/app/api/.venv/bin:${PATH}"
# Install pg0 binary
RUN mkdir -p /home/hindsight/.hindsight/bin && \
ARCH=$(uname -m) && \
if [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then \
PG0_BINARY="pg0-linux-aarch64-gnu"; \
elif [ "$ARCH" = "x86_64" ]; then \
PG0_BINARY="pg0-linux-x86_64-gnu"; \
else \
echo "Unsupported architecture: $ARCH" && exit 1; \
fi && \
echo "Installing pg0 binary: $PG0_BINARY" && \
for i in 1 2 3 4 5; do \
curl -fsSL -o /home/hindsight/.hindsight/bin/pg0 \
"https://github.com/vectorize-io/pg0/releases/latest/download/$PG0_BINARY" && \
chmod +x /home/hindsight/.hindsight/bin/pg0 && \
ls -lh /home/hindsight/.hindsight/bin/pg0 && \
file /home/hindsight/.hindsight/bin/pg0 && \
ldd /home/hindsight/.hindsight/bin/pg0 2>&1 || true && \
break || (echo "Retry $i failed, waiting..." && sleep 10); \
done && \
echo "Testing pg0 binary..." && \
/home/hindsight/.hindsight/bin/pg0 --version || (echo "pg0 --version failed with exit code $?"; ldd /home/hindsight/.hindsight/bin/pg0; exit 1)
# Pre-download PostgreSQL binaries
# Pre-cache PostgreSQL binaries by starting/stopping pg0-embedded
ENV PG0_HOME=/home/hindsight/.pg0-cache
RUN pg0 start --help && \
(pg0 start --name hindsight --port 5555 --username hindsight --password hindsight --database hindsight && \
sleep 2 && \
pg0 stop --name hindsight && \
echo "PostgreSQL pre-cached to $PG0_HOME") || echo "Pre-download skipped"
RUN /app/api/.venv/bin/python -c "\
from pg0 import Pg0; \
print('Pre-caching PostgreSQL binaries...'); \
pg = Pg0(name='hindsight', port=5555, username='hindsight', password='hindsight', database='hindsight'); \
pg.start(); \
pg.stop(); \
print('PostgreSQL pre-cached to PG0_HOME')" || echo "Pre-download skipped"
ENV PG0_HOME=/home/hindsight/.pg0
+2 -2
View File
@@ -2,8 +2,8 @@ apiVersion: v2
name: hindsight
description: Hindsight helm chart
type: application
version: 0.1.4
appVersion: "0.1.4"
version: 0.1.5
appVersion: "0.1.5"
keywords:
- ai
- memory
+2 -6
View File
@@ -61,7 +61,7 @@ def create_mcp_server(memory: MemoryEngine) -> FastMCP:
"""
try:
bank_id = get_current_bank_id()
await memory.put_batch_async(
await memory.retain_batch_async(
bank_id=bank_id,
contents=[{"content": content, "context": context}]
)
@@ -121,11 +121,7 @@ class MCPMiddleware:
self.app = app
self.memory = memory
self.mcp_server = create_mcp_server(memory)
# Use sse_app - http_app requires lifespan management that's complex with middleware
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
self.mcp_app = self.mcp_server.sse_app()
self.mcp_app = self.mcp_server.http_app()
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
+14 -6
View File
@@ -6,7 +6,7 @@ Shows the logo and tagline with gradient colors.
# Gradient colors: #0074d9 -> #009296
GRADIENT_START = (0, 116, 217) # #0074d9
GRADIENT_END = (0, 146, 150) # #009296
GRADIENT_END = (0, 146, 150) # #009296
# Pre-generated logo (generated by test-logo.py)
LOGO = """\
@@ -28,11 +28,12 @@ def _interpolate_color(start: tuple, end: tuple, t: float) -> tuple:
def gradient_text(text: str, start: tuple = GRADIENT_START, end: tuple = GRADIENT_END) -> str:
"""Render text with a gradient color effect."""
result = []
length = len(text)
for i, char in enumerate(text):
if char == ' ':
result.append(' ')
if char == " ":
result.append(" ")
else:
t = i / max(length - 1, 1)
r, g, b = _interpolate_color(start, end, t)
@@ -74,9 +75,16 @@ def dim(text: str) -> str:
return f"\033[38;2;128;128;128m{text}\033[0m"
def print_startup_info(host: str, port: int, database_url: str, llm_provider: str,
llm_model: str, embeddings_provider: str, reranker_provider: str,
mcp_enabled: bool = False):
def print_startup_info(
host: str,
port: int,
database_url: str,
llm_provider: str,
llm_model: str,
embeddings_provider: str,
reranker_provider: str,
mcp_enabled: bool = False,
):
"""Print styled startup information."""
print(color_start("Starting Hindsight API..."))
print(f" {dim('URL:')} {color(f'http://{host}:{port}', 0.2)}")
+2
View File
@@ -30,6 +30,7 @@ ENV_PORT = "HINDSIGHT_API_PORT"
ENV_LOG_LEVEL = "HINDSIGHT_API_LOG_LEVEL"
ENV_MCP_ENABLED = "HINDSIGHT_API_MCP_ENABLED"
ENV_GRAPH_RETRIEVER = "HINDSIGHT_API_GRAPH_RETRIEVER"
ENV_MCP_LOCAL_BANK_ID = "HINDSIGHT_API_MCP_LOCAL_BANK_ID"
# Default values
DEFAULT_DATABASE_URL = "pg0"
@@ -47,6 +48,7 @@ DEFAULT_PORT = 8888
DEFAULT_LOG_LEVEL = "info"
DEFAULT_MCP_ENABLED = True
DEFAULT_GRAPH_RETRIEVER = "bfs" # Options: "bfs", "mpfp"
DEFAULT_MCP_LOCAL_BANK_ID = "mcp"
# Required embedding dimension for database schema
EMBEDDING_DIMENSION = 384
@@ -175,9 +175,13 @@ class LLMProvider:
is_reasoning_model = any(x in model_lower for x in ["gpt-5", "o1", "o3"])
# For GPT-4 and GPT-4.1 models, cap max_completion_tokens to 32000
# For GPT-4o models, cap to 16384
is_gpt4_model = any(x in model_lower for x in ["gpt-4.1", "gpt-4-"])
is_gpt4o_model = "gpt-4o" in model_lower
if max_completion_tokens is not None:
if is_gpt4_model and max_completion_tokens > 32000:
if is_gpt4o_model and max_completion_tokens > 16384:
max_completion_tokens = 16384
elif is_gpt4_model and max_completion_tokens > 32000:
max_completion_tokens = 32000
# For reasoning models, max_completion_tokens includes reasoning + output tokens
# Enforce minimum of 16000 to ensure enough space for both
@@ -268,9 +272,9 @@ class LLMProvider:
raise
except APIStatusError as e:
# Fast fail on 4xx client errors (except 429 rate limit and 498 which is treated as server error)
if 400 <= e.status_code < 500 and e.status_code not in (429, 498):
logger.error(f"Client error (HTTP {e.status_code}), not retrying: {str(e)}")
# Fast fail only on 401 (unauthorized) and 403 (forbidden) - these won't recover with retries
if e.status_code in (401, 403):
logger.error(f"Auth error (HTTP {e.status_code}), not retrying: {str(e)}")
raise
last_exception = e
@@ -408,13 +412,13 @@ class LLMProvider:
raise
except genai_errors.APIError as e:
# Fast fail on 4xx client errors (except 429 rate limit)
if e.code and 400 <= e.code < 500 and e.code != 429:
logger.error(f"Gemini client error (HTTP {e.code}), not retrying: {str(e)}")
# Fast fail only on 401 (unauthorized) and 403 (forbidden) - these won't recover with retries
if e.code in (401, 403):
logger.error(f"Gemini auth error (HTTP {e.code}), not retrying: {str(e)}")
raise
# Retry on 429 and 5xx
if e.code in (429, 500, 502, 503, 504):
# Retry on retryable errors (rate limits, server errors, and other client errors like 400)
if e.code in (400, 429, 500, 502, 503, 504) or (e.code and e.code >= 500):
last_exception = e
if attempt < max_retries:
backoff = min(initial_backoff * (2 ** attempt), max_backoff)
@@ -282,3 +282,81 @@ If no genuine opinions are expressed (e.g., the response just says "I don't know
except Exception as e:
logger.warning(f"Failed to extract opinions: {str(e)}")
return []
async def reflect(
llm_config,
query: str,
experience_facts: List[str] = None,
world_facts: List[str] = None,
opinion_facts: List[str] = None,
name: str = "Assistant",
disposition: DispositionTraits = None,
background: str = "",
context: str = None,
) -> str:
"""
Standalone reflect function for generating answers based on facts.
This is a static version of the reflect operation that can be called
without a MemoryEngine instance, useful for testing.
Args:
llm_config: LLM provider instance
query: Question to answer
experience_facts: List of experience/agent fact strings
world_facts: List of world fact strings
opinion_facts: List of opinion fact strings
name: Name of the agent/persona
disposition: Disposition traits (defaults to neutral)
background: Background information
context: Additional context for the prompt
Returns:
Generated answer text
"""
# Default disposition if not provided
if disposition is None:
disposition = DispositionTraits(skepticism=3, literalism=3, empathy=3)
# Convert string lists to MemoryFact format for formatting
def to_memory_facts(facts: List[str], fact_type: str) -> List[MemoryFact]:
if not facts:
return []
return [MemoryFact(id=f"test-{i}", text=f, fact_type=fact_type) for i, f in enumerate(facts)]
agent_results = to_memory_facts(experience_facts or [], "experience")
world_results = to_memory_facts(world_facts or [], "world")
opinion_results = to_memory_facts(opinion_facts or [], "opinion")
# Format facts for prompt
agent_facts_text = format_facts_for_prompt(agent_results)
world_facts_text = format_facts_for_prompt(world_results)
opinion_facts_text = format_facts_for_prompt(opinion_results)
# Build prompt
prompt = build_think_prompt(
agent_facts_text=agent_facts_text,
world_facts_text=world_facts_text,
opinion_facts_text=opinion_facts_text,
query=query,
name=name,
disposition=disposition,
background=background,
context=context,
)
system_message = get_system_message(disposition)
# Call LLM
answer_text = await llm_config.call(
messages=[
{"role": "system", "content": system_message},
{"role": "user", "content": prompt}
],
scope="memory_think",
temperature=0.9,
max_completion_tokens=1000
)
return answer_text.strip()
+192
View File
@@ -0,0 +1,192 @@
"""
Local MCP server for use with Claude Code (stdio transport).
This runs a fully local Hindsight instance with embedded PostgreSQL (pg0).
No external database or server required.
Run with:
hindsight-local-mcp
Or with uvx:
uvx hindsight-api@latest hindsight-local-mcp
Configure in Claude Code's MCP settings:
{
"mcpServers": {
"hindsight": {
"command": "uvx",
"args": ["hindsight-api@latest", "hindsight-local-mcp"],
"env": {
"HINDSIGHT_API_LLM_API_KEY": "your-openai-key"
}
}
}
}
Environment variables:
HINDSIGHT_API_LLM_API_KEY: Required. API key for LLM provider.
HINDSIGHT_API_LLM_PROVIDER: Optional. LLM provider (default: "openai").
HINDSIGHT_API_LLM_MODEL: Optional. LLM model (default: "gpt-4o-mini").
HINDSIGHT_API_MCP_LOCAL_BANK_ID: Optional. Memory bank ID (default: "mcp").
HINDSIGHT_API_LOG_LEVEL: Optional. Log level (default: "info").
"""
import logging
import os
import sys
from mcp.server.fastmcp import FastMCP
from hindsight_api.config import (
ENV_MCP_LOCAL_BANK_ID,
DEFAULT_MCP_LOCAL_BANK_ID,
)
# Configure logging - default to info
_log_level_str = os.environ.get("HINDSIGHT_API_LOG_LEVEL", "info").lower()
_log_level_map = {
"critical": logging.CRITICAL,
"error": logging.ERROR,
"warning": logging.WARNING,
"info": logging.INFO,
"debug": logging.DEBUG,
}
logging.basicConfig(
level=_log_level_map.get(_log_level_str, logging.WARNING),
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
stream=sys.stderr, # MCP uses stdout for protocol, logs go to stderr
)
logger = logging.getLogger(__name__)
def create_local_mcp_server(bank_id: str, memory=None) -> FastMCP:
"""
Create a stdio MCP server with retain/recall tools.
Args:
bank_id: The memory bank ID to use for all operations.
memory: Optional MemoryEngine instance. If not provided, creates one with pg0.
Returns:
Configured FastMCP server instance.
"""
# Import here to avoid slow startup if just checking --help
from hindsight_api import MemoryEngine
from hindsight_api.engine.memory_engine import Budget
from hindsight_api.engine.response_models import VALID_RECALL_FACT_TYPES
# Create memory engine with pg0 embedded database if not provided
if memory is None:
memory = MemoryEngine(db_url="pg0://hindsight-mcp")
mcp = FastMCP("hindsight")
@mcp.tool()
async def retain(content: str, context: str = "general") -> dict:
"""
Store important information to long-term memory.
Use this tool PROACTIVELY whenever the user shares:
- Personal facts, preferences, or interests
- Important events or milestones
- User history, experiences, or background
- Decisions, opinions, or stated preferences
- Goals, plans, or future intentions
- Relationships or people mentioned
- Work context, projects, or responsibilities
Args:
content: The fact/memory to store (be specific and include relevant details)
context: Category for the memory (e.g., 'preferences', 'work', 'hobbies', 'family'). Default: 'general'
"""
import asyncio
async def _retain():
try:
await memory.retain_batch_async(
bank_id=bank_id,
contents=[{"content": content, "context": context}]
)
except Exception as e:
logger.error(f"Error storing memory: {e}", exc_info=True)
# Fire and forget - don't block on memory storage
asyncio.create_task(_retain())
return {"status": "accepted", "message": "Memory storage initiated"}
@mcp.tool()
async def recall(query: str, max_tokens: int = 4096, budget: str = "low") -> dict:
"""
Search memories to provide personalized, context-aware responses.
Use this tool PROACTIVELY to:
- Check user's preferences before making suggestions
- Recall user's history to provide continuity
- Remember user's goals and context
- Personalize responses based on past interactions
Args:
query: Natural language search query (e.g., "user's food preferences", "what projects is user working on")
max_tokens: Maximum tokens to return in results (default: 4096)
budget: Search budget level - "low", "mid", or "high" (default: "low")
"""
try:
# Map string budget to enum
budget_map = {"low": Budget.LOW, "mid": Budget.MID, "high": Budget.HIGH}
budget_enum = budget_map.get(budget.lower(), Budget.LOW)
search_result = await memory.recall_async(
bank_id=bank_id,
query=query,
fact_type=list(VALID_RECALL_FACT_TYPES),
budget=budget_enum,
max_tokens=max_tokens
)
return search_result.model_dump()
except Exception as e:
logger.error(f"Error searching: {e}", exc_info=True)
return {"error": str(e), "results": []}
return mcp
async def _initialize_and_run(bank_id: str):
"""Initialize memory and run the MCP server."""
from hindsight_api import MemoryEngine
# Create and initialize memory engine with pg0 embedded database
print("Initializing memory engine...", file=sys.stderr)
memory = MemoryEngine(db_url="pg0://hindsight-mcp")
await memory.initialize()
print("Memory engine initialized.", file=sys.stderr)
# Create and run the server
mcp = create_local_mcp_server(bank_id, memory=memory)
await mcp.run_stdio_async()
def main():
"""Main entry point for the stdio MCP server."""
import asyncio
from hindsight_api.config import get_config, ENV_LLM_API_KEY
# Check for required environment variables
config = get_config()
if not config.llm_api_key:
print(f"Error: {ENV_LLM_API_KEY} environment variable is required", file=sys.stderr)
print("Set it in your MCP configuration or shell environment", file=sys.stderr)
sys.exit(1)
# Get bank ID from environment, default to "mcp"
bank_id = os.environ.get(ENV_MCP_LOCAL_BANK_ID, DEFAULT_MCP_LOCAL_BANK_ID)
# Print startup message to stderr (stdout is reserved for MCP protocol)
print(f"Hindsight MCP server starting (bank_id={bank_id})...", file=sys.stderr)
# Run the async initialization and server
asyncio.run(_initialize_and_run(bank_id))
if __name__ == "__main__":
main()
+60 -331
View File
@@ -1,373 +1,117 @@
import asyncio
import json
import logging
import os
import platform
import re
import shutil
import stat
import subprocess
from pathlib import Path
from typing import Optional
import httpx
from pg0 import Pg0
logger = logging.getLogger(__name__)
# pg0 configuration
BINARY_NAME = "pg0"
DEFAULT_PORT = 5555
DEFAULT_USERNAME = "hindsight"
DEFAULT_PASSWORD = "hindsight"
DEFAULT_DATABASE = "hindsight"
def get_platform_binary_name() -> str:
"""Get the appropriate binary name for the current platform.
Supported platforms:
- macOS ARM64 (darwin-aarch64)
- Linux x86_64 (gnu)
- Linux ARM64 (gnu)
- Windows x86_64
"""
system = platform.system().lower()
machine = platform.machine().lower()
# Normalize architecture names
if machine in ("x86_64", "amd64"):
arch = "x86_64"
elif machine in ("arm64", "aarch64"):
arch = "aarch64"
else:
raise RuntimeError(
f"Embedded PostgreSQL is not supported on architecture: {machine}. "
f"Supported architectures: x86_64/amd64 (Linux, Windows), aarch64/arm64 (macOS, Linux)"
)
if system == "darwin" and arch == "aarch64":
return "pg0-darwin-aarch64"
elif system == "linux" and arch == "x86_64":
return "pg0-linux-x86_64-gnu"
elif system == "linux" and arch == "aarch64":
return "pg0-linux-aarch64-gnu"
elif system == "windows" and arch == "x86_64":
return "pg0-windows-x86_64.exe"
else:
raise RuntimeError(
f"Embedded PostgreSQL is not supported on {system}-{arch}. "
f"Supported platforms: darwin-aarch64 (macOS ARM), linux-x86_64-gnu, linux-aarch64-gnu, windows-x86_64"
)
def get_download_url(
version: str = "latest",
repo: str = "vectorize-io/pg0",
) -> str:
"""Get the download URL for pg0 binary."""
binary_name = get_platform_binary_name()
if version == "latest":
return f"https://github.com/{repo}/releases/latest/download/{binary_name}"
else:
return f"https://github.com/{repo}/releases/download/{version}/{binary_name}"
def _find_pg0_binary() -> Optional[Path]:
"""Find pg0 binary in PATH or default install location."""
# First check PATH
pg0_in_path = shutil.which("pg0")
if pg0_in_path:
return Path(pg0_in_path)
# Fall back to default install location
default_path = Path.home() / ".hindsight" / "bin" / "pg0"
if default_path.exists() and os.access(default_path, os.X_OK):
return default_path
return None
class EmbeddedPostgres:
"""
Manages an embedded PostgreSQL server instance using pg0.
This class handles:
- Finding or downloading the pg0 CLI
- Starting/stopping the PostgreSQL server
- Getting the connection URI
Example:
pg = EmbeddedPostgres()
await pg.ensure_installed()
await pg.start()
uri = await pg.get_uri()
# ... use uri with asyncpg ...
await pg.stop()
"""
"""Manages an embedded PostgreSQL server instance using pg0-embedded."""
def __init__(
self,
version: str = "latest",
port: int = DEFAULT_PORT,
port: Optional[int] = None,
username: str = DEFAULT_USERNAME,
password: str = DEFAULT_PASSWORD,
database: str = DEFAULT_DATABASE,
name: str = "hindsight",
**kwargs,
):
"""
Initialize the embedded PostgreSQL manager.
Args:
version: Version of pg0 to download if not found. Defaults to "latest"
port: Port to listen on. Defaults to 5555
username: Username for the database. Defaults to "hindsight"
password: Password for the database. Defaults to "hindsight"
database: Database name to create. Defaults to "hindsight"
name: Instance name for pg0. Defaults to "hindsight"
"""
self.version = version
self.port = port
self.port = port # None means pg0 will auto-assign
self.username = username
self.password = password
self.database = database
self.name = name
self._pg0: Optional[Pg0] = None
# Will be set when binary is found/installed
self._binary_path: Optional[Path] = _find_pg0_binary()
def _get_pg0(self) -> Pg0:
if self._pg0 is None:
kwargs = {
"name": self.name,
"username": self.username,
"password": self.password,
"database": self.database,
}
# Only set port if explicitly specified
if self.port is not None:
kwargs["port"] = self.port
self._pg0 = Pg0(**kwargs)
return self._pg0
@property
def binary_path(self) -> Path:
"""Get the path to the pg0 binary."""
if self._binary_path is None:
# Default install location
return Path.home() / ".hindsight" / "bin" / "pg0"
return self._binary_path
def is_installed(self) -> bool:
"""Check if pg0 is available (in PATH or installed)."""
self._binary_path = _find_pg0_binary()
return self._binary_path is not None
async def ensure_installed(self) -> None:
"""
Ensure pg0 is available.
Checks PATH and default location. If not found, raises an error
instructing the user to install pg0 manually.
"""
if self.is_installed():
logger.debug(f"pg0 found at {self._binary_path}")
return
raise RuntimeError(
"pg0 is not installed. Please install it manually:\n"
" curl -fsSL https://github.com/vectorize-io/pg0/releases/latest/download/pg0-linux-amd64 -o ~/.local/bin/pg0 && chmod +x ~/.local/bin/pg0\n"
"Or visit: https://github.com/vectorize-io/pg0/releases"
)
def _run_command(self, *args: str, capture_output: bool = True) -> subprocess.CompletedProcess:
"""Run a pg0 command synchronously."""
cmd = [str(self.binary_path), *args]
return subprocess.run(cmd, capture_output=capture_output, text=True)
async def _run_command_async(self, *args: str, timeout: int = 120) -> tuple[int, str, str]:
"""Run a pg0 command asynchronously."""
cmd = [str(self.binary_path), *args]
def run_sync():
try:
result = subprocess.run(
cmd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=timeout,
)
return result.returncode, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return 1, "", "Command timed out"
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, run_sync)
def _extract_uri_from_output(self, output: str) -> Optional[str]:
"""Extract the PostgreSQL URI from pg0 start output."""
match = re.search(r"Connection URI:\s*(postgresql://[^\s]+)", output)
if match:
return match.group(1)
return None
async def _get_version(self) -> str:
"""Get the pg0 version."""
returncode, stdout, stderr = await self._run_command_async("--version", timeout=10)
if returncode == 0 and stdout:
return stdout.strip()
return "unknown"
async def start(self, max_retries: int = 3, retry_delay: float = 2.0) -> str:
"""
Start the PostgreSQL server with retry logic.
Args:
max_retries: Maximum number of start attempts (default: 3)
retry_delay: Initial delay between retries in seconds (default: 2.0)
Returns:
The connection URI for the started server.
Raises:
RuntimeError: If the server fails to start after all retries.
"""
if not self.is_installed():
raise RuntimeError("pg0 is not installed. Call ensure_installed() first.")
# Log pg0 version
version = await self._get_version()
logger.info(f"Starting embedded PostgreSQL with pg0 {version} (name: {self.name}, port: {self.port})...")
async def start(self, max_retries: int = 5, retry_delay: float = 4.0) -> str:
"""Start the PostgreSQL server with retry logic."""
port_info = f"port={self.port}" if self.port else "port=auto"
logger.info(f"Starting embedded PostgreSQL (name={self.name}, {port_info})...")
pg0 = self._get_pg0()
last_error = None
for attempt in range(1, max_retries + 1):
returncode, stdout, stderr = await self._run_command_async(
"start",
"--name", self.name,
"--port", str(self.port),
"--username", self.username,
"--password", self.password,
"--database", self.database,
timeout=300,
)
# Try to extract URI from output
uri = self._extract_uri_from_output(stdout)
if uri:
logger.info(f"PostgreSQL started on port {self.port}")
return uri
# Check if pg0 info can find the running instance
try:
uri = await self.get_uri()
logger.info(f"PostgreSQL started on port {self.port}")
loop = asyncio.get_event_loop()
info = await loop.run_in_executor(None, pg0.start)
# Get URI from pg0 (includes auto-assigned port)
uri = info.uri
logger.info(f"PostgreSQL started: {uri}")
return uri
except RuntimeError:
pass
except Exception as e:
last_error = str(e)
if attempt < max_retries:
delay = retry_delay * (2 ** (attempt - 1))
logger.debug(f"pg0 start attempt {attempt}/{max_retries} failed: {last_error}")
logger.debug(f"Retrying in {delay:.1f}s...")
await asyncio.sleep(delay)
else:
logger.debug(f"pg0 start attempt {attempt}/{max_retries} failed: {last_error}")
# Start failed, log and retry
last_error = stderr or f"pg0 start returned exit code {returncode}"
if attempt < max_retries:
delay = retry_delay * (2 ** (attempt - 1))
logger.debug(f"pg0 start attempt {attempt}/{max_retries} failed: {last_error.strip()}")
logger.debug(f"Retrying in {delay:.1f}s...")
await asyncio.sleep(delay)
else:
logger.debug(f"pg0 start attempt {attempt}/{max_retries} failed: {last_error.strip()}")
# All retries exhausted - fail
raise RuntimeError(
f"Failed to start embedded PostgreSQL after {max_retries} attempts. "
f"Last error: {last_error.strip() if last_error else 'unknown'}"
f"Last error: {last_error}"
)
async def stop(self) -> None:
"""Stop the PostgreSQL server."""
if not self.is_installed():
return
pg0 = self._get_pg0()
logger.info(f"Stopping embedded PostgreSQL (name: {self.name})...")
returncode, stdout, stderr = await self._run_command_async("stop", "--name", self.name)
if returncode != 0:
if "not running" in stderr.lower():
return
raise RuntimeError(f"Failed to stop PostgreSQL: {stderr}")
logger.info("Embedded PostgreSQL stopped")
async def _get_info(self) -> dict:
"""Get info from pg0 using the `info -o json` command."""
if not self.is_installed():
raise RuntimeError("pg0 is not installed.")
returncode, stdout, stderr = await self._run_command_async(
"info", "--name", self.name, "-o", "json"
)
if returncode != 0:
raise RuntimeError(f"Failed to get PostgreSQL info: {stderr}")
try:
return json.loads(stdout.strip())
except json.JSONDecodeError as e:
raise RuntimeError(f"Failed to parse pg0 info output: {e}")
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, pg0.stop)
logger.info("Embedded PostgreSQL stopped")
except Exception as e:
if "not running" in str(e).lower():
return
raise RuntimeError(f"Failed to stop PostgreSQL: {e}")
async def get_uri(self) -> str:
"""Get the connection URI for the PostgreSQL server."""
info = await self._get_info()
uri = info.get("uri")
if not uri:
raise RuntimeError("PostgreSQL server is not running or URI not available")
return uri
async def status(self) -> dict:
"""Get the status of the PostgreSQL server."""
if not self.is_installed():
return {"installed": False, "running": False}
try:
info = await self._get_info()
return {
"installed": True,
"running": info.get("running", False),
"uri": info.get("uri"),
}
except RuntimeError:
return {"installed": True, "running": False}
pg0 = self._get_pg0()
loop = asyncio.get_event_loop()
info = await loop.run_in_executor(None, pg0.info)
return info.uri
async def is_running(self) -> bool:
"""Check if the PostgreSQL server is currently running."""
if not self.is_installed():
return False
try:
info = await self._get_info()
return info.get("running", False)
except RuntimeError:
pg0 = self._get_pg0()
loop = asyncio.get_event_loop()
info = await loop.run_in_executor(None, pg0.info)
return info is not None and info.running
except Exception:
return False
async def ensure_running(self) -> str:
"""
Ensure the PostgreSQL server is running.
Installs if needed, starts if not running.
Returns:
The connection URI.
"""
await self.ensure_installed()
"""Ensure the PostgreSQL server is running, starting it if needed."""
if await self.is_running():
return await self.get_uri()
return await self.start()
def uninstall(self) -> None:
"""Remove the pg0 binary (only if we installed it)."""
default_path = Path.home() / ".hindsight" / "bin" / "pg0"
if default_path.exists():
default_path.unlink()
logger.info(f"Removed {default_path}")
def clear_data(self) -> None:
"""Remove all PostgreSQL data (destructive!)."""
result = self._run_command("drop", "--name", self.name, "--force")
if result.returncode == 0:
logger.info(f"Dropped pg0 instance {self.name}")
else:
logger.warning(f"Failed to drop pg0 instance {self.name}: {result.stderr}")
# Convenience functions
_default_instance: Optional[EmbeddedPostgres] = None
@@ -375,33 +119,18 @@ _default_instance: Optional[EmbeddedPostgres] = None
def get_embedded_postgres() -> EmbeddedPostgres:
"""Get or create the default EmbeddedPostgres instance."""
global _default_instance
if _default_instance is None:
_default_instance = EmbeddedPostgres()
return _default_instance
async def start_embedded_postgres() -> str:
"""
Quick start function for embedded PostgreSQL.
Downloads, installs, and starts PostgreSQL in one call.
Returns:
Connection URI string
Example:
db_url = await start_embedded_postgres()
conn = await asyncpg.connect(db_url)
"""
pg = get_embedded_postgres()
return await pg.ensure_running()
"""Quick start function for embedded PostgreSQL."""
return await get_embedded_postgres().ensure_running()
async def stop_embedded_postgres() -> None:
"""Stop the default embedded PostgreSQL instance."""
global _default_instance
if _default_instance:
await _default_instance.stop()
+27 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "hindsight-api"
version = "0.1.4"
version = "0.1.5"
description = "Temporal + Semantic + Entity Memory System for AI agents using PostgreSQL"
readme = "README.md"
requires-python = ">=3.11"
@@ -28,7 +28,8 @@ dependencies = [
"torch>=2.0.0,<2.6.0",
"tiktoken>=0.12.0",
"httpx>=0.27.0",
"fastmcp>=2.0.0",
"fastmcp>=2.3.0",
"pg0-embedded>=0.11.0",
"python-dateutil>=2.8.0",
"opentelemetry-api>=1.20.0",
"opentelemetry-sdk>=1.20.0",
@@ -49,6 +50,7 @@ test = [
[project.scripts]
hindsight-api = "hindsight_api.main:main"
hindsight-local-mcp = "hindsight_api.mcp_local:main"
[tool.hatch.build.targets.wheel]
packages = ["hindsight_api"]
@@ -89,4 +91,27 @@ dev = [
"pytest-xdist>=3.8.0",
"python-dotenv>=1.2.1",
"filelock>=3.0.0",
"ruff>=0.8.0",
]
[tool.ruff]
line-length = 120
target-version = "py311"
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # Pyflakes
"I", # isort
"B", # flake8-bugbear
"UP", # pyupgrade
]
ignore = [
"E501", # line too long (handled by formatter)
"B008", # do not perform function calls in argument defaults
]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
+51 -68
View File
@@ -1,9 +1,12 @@
"""
Test LLM provider with different models and providers.
Test LLM provider with different models using actual memory operations.
"""
import os
from datetime import datetime
import pytest
from hindsight_api.engine.llm_wrapper import LLMProvider
from hindsight_api.engine.utils import extract_facts
from hindsight_api.engine.search.think_utils import reflect
# Model matrix: (provider, model)
@@ -15,13 +18,14 @@ MODEL_MATRIX = [
("openai", "gpt-5-mini"),
("openai", "gpt-5-nano"),
("openai", "gpt-5"),
("openai", "gpt-5.2"),
# Groq models
("groq", "llama-3.3-70b-versatile"),
("groq", "openai/gpt-oss-120b"),
("groq", "openai/gpt-oss-20b"),
# Gemini models
("gemini", "gemini-2.5-flash"),
("gemini", "gemini-2.5-flash-lite"),
("gemini", "gemini-3-pro-preview"),
]
@@ -38,10 +42,10 @@ def get_api_key_for_provider(provider: str) -> str | None:
@pytest.mark.parametrize("provider,model", MODEL_MATRIX)
@pytest.mark.asyncio
async def test_llm_provider_call(provider: str, model: str):
async def test_llm_provider_memory_operations(provider: str, model: str):
"""
Test LLM provider can make a basic call with different models.
Skips if the required API key is not available.
Test LLM provider with actual memory operations: fact extraction and reflect.
All models must pass this test.
"""
api_key = get_api_key_for_provider(provider)
if not api_key:
@@ -54,74 +58,53 @@ async def test_llm_provider_call(provider: str, model: str):
model=model,
)
# Test basic call
response = await llm.call(
messages=[{"role": "user", "content": "Say 'hello' and nothing else."}],
max_completion_tokens=50,
temperature=0.1,
# Test 1: Fact extraction (structured output)
test_text = """
User: I just got back from my trip to Paris last week. The Eiffel Tower was amazing!
Assistant: That sounds wonderful! How long were you there?
User: About 5 days. I also visited the Louvre and saw the Mona Lisa.
"""
event_date = datetime(2024, 12, 10)
facts, chunks = await extract_facts(
text=test_text,
event_date=event_date,
context="Travel conversation",
llm_config=llm,
)
print(f"\n{provider}/{model} response: {response}")
assert response is not None, f"{provider}/{model} returned None"
print(f"\n{provider}/{model} - Fact extraction:")
print(f" Extracted {len(facts)} facts from {len(chunks)} chunks")
for fact in facts:
print(f" - {fact.fact}")
assert facts is not None, f"{provider}/{model} fact extraction returned None"
assert len(facts) > 0, f"{provider}/{model} should extract at least one fact"
@pytest.mark.parametrize("provider,model", MODEL_MATRIX)
@pytest.mark.asyncio
async def test_llm_provider_verify_connection(provider: str, model: str):
"""
Test LLM provider verify_connection method with different models.
Skips if the required API key is not available.
"""
api_key = get_api_key_for_provider(provider)
if not api_key:
pytest.skip(f"Skipping {provider}/{model}: no API key available")
# Verify facts have required fields
for fact in facts:
assert fact.fact, f"{provider}/{model} fact missing text"
assert fact.fact_type in ["world", "experience", "opinion"], f"{provider}/{model} invalid fact_type: {fact.fact_type}"
llm = LLMProvider(
provider=provider,
api_key=api_key,
base_url="",
model=model,
# Test 2: Reflect (actual reflect function)
response = await reflect(
llm_config=llm,
query="What was the highlight of my Paris trip?",
experience_facts=[
"I visited Paris in December 2024",
"I saw the Eiffel Tower and it was amazing",
"I visited the Louvre and saw the Mona Lisa",
"The trip lasted 5 days",
],
world_facts=[
"The Eiffel Tower is a famous landmark in Paris",
"The Mona Lisa is displayed at the Louvre museum",
],
name="Traveler",
)
# Test verify_connection
await llm.verify_connection()
print(f"\n{provider}/{model} connection verified")
print(f"\n{provider}/{model} - Reflect response:")
print(f" {response[:200]}...")
# Models that support large output (65000+ tokens)
LARGE_OUTPUT_MODELS = [
("openai", "gpt-5-mini"),
("openai", "gpt-5-nano"),
("openai", "gpt-5"),
("gemini", "gemini-2.5-flash"),
("gemini", "gemini-2.5-flash-lite"),
]
@pytest.mark.parametrize("provider,model", LARGE_OUTPUT_MODELS)
@pytest.mark.asyncio
async def test_llm_provider_large_output(provider: str, model: str):
"""
Test LLM provider with large max_completion_tokens (65000).
Only tests models that support large outputs.
Skips if the required API key is not available.
"""
api_key = get_api_key_for_provider(provider)
if not api_key:
pytest.skip(f"Skipping {provider}/{model}: no API key available")
llm = LLMProvider(
provider=provider,
api_key=api_key,
base_url="",
model=model,
)
# Test call with large max_completion_tokens
response = await llm.call(
messages=[{"role": "user", "content": "Say 'ok'"}],
max_completion_tokens=65000,
)
print(f"\n{provider}/{model} large output response: {response}")
assert response is not None, f"{provider}/{model} returned None"
assert response is not None, f"{provider}/{model} reflect returned None"
assert len(response) > 10, f"{provider}/{model} reflect response too short"
+162
View File
@@ -0,0 +1,162 @@
"""Test local MCP server."""
import asyncio
import pytest
from unittest.mock import AsyncMock, MagicMock
@pytest.fixture
def mock_memory():
"""Create a mock MemoryEngine."""
memory = MagicMock()
memory._initialized = True
memory.retain_batch_async = AsyncMock()
memory.recall_async = AsyncMock(return_value=MagicMock(results=[]))
return memory
@pytest.mark.asyncio
async def test_local_mcp_server_retain(mock_memory):
"""Test that retain tool fires async and returns immediately."""
from hindsight_api.mcp_local import create_local_mcp_server
bank_id = "test-bank"
mcp_server = create_local_mcp_server(bank_id, memory=mock_memory)
# Get the tools
tools = mcp_server._tool_manager._tools
assert "retain" in tools
# Call retain
retain_tool = tools["retain"]
result = await retain_tool.fn(content="test content", context="test_context")
# Returns immediately with accepted status
assert result["status"] == "accepted"
# Wait for background task to complete
await asyncio.sleep(0.1)
# Verify the memory was called correctly
mock_memory.retain_batch_async.assert_called_once()
call_kwargs = mock_memory.retain_batch_async.call_args.kwargs
assert call_kwargs["bank_id"] == "test-bank"
assert call_kwargs["contents"] == [{"content": "test content", "context": "test_context"}]
@pytest.mark.asyncio
async def test_local_mcp_server_recall(mock_memory):
"""Test that recall tool calls memory.recall_async with correct params."""
from hindsight_api.mcp_local import create_local_mcp_server
from hindsight_api.engine.memory_engine import Budget
# Mock recall_async to return a proper pydantic model
mock_result = MagicMock()
mock_result.model_dump.return_value = {"results": []}
mock_memory.recall_async = AsyncMock(return_value=mock_result)
bank_id = "test-bank"
mcp_server = create_local_mcp_server(bank_id, memory=mock_memory)
# Get the tools
tools = mcp_server._tool_manager._tools
assert "recall" in tools
# Call recall with new params
recall_tool = tools["recall"]
result = await recall_tool.fn(query="test query", max_tokens=2048, budget="mid")
# Result is a dict
assert isinstance(result, dict)
# Verify the memory was called correctly
mock_memory.recall_async.assert_called_once()
call_kwargs = mock_memory.recall_async.call_args.kwargs
assert call_kwargs["bank_id"] == "test-bank"
assert call_kwargs["query"] == "test query"
assert call_kwargs["max_tokens"] == 2048
assert call_kwargs["budget"] == Budget.MID
@pytest.mark.asyncio
async def test_local_mcp_server_retain_with_default_context(mock_memory):
"""Test that retain uses default context when not provided."""
from hindsight_api.mcp_local import create_local_mcp_server
bank_id = "test-bank"
mcp_server = create_local_mcp_server(bank_id, memory=mock_memory)
tools = mcp_server._tool_manager._tools
retain_tool = tools["retain"]
# Call retain without context
await retain_tool.fn(content="test content")
# Wait for background task
await asyncio.sleep(0.1)
call_kwargs = mock_memory.retain_batch_async.call_args.kwargs
assert call_kwargs["contents"] == [{"content": "test content", "context": "general"}]
@pytest.mark.asyncio
async def test_local_mcp_server_retain_error_handling(mock_memory):
"""Test that retain errors are logged but don't affect response."""
from hindsight_api.mcp_local import create_local_mcp_server
mock_memory.retain_batch_async = AsyncMock(side_effect=Exception("Test error"))
mcp_server = create_local_mcp_server("test-bank", memory=mock_memory)
tools = mcp_server._tool_manager._tools
retain_tool = tools["retain"]
# Retain returns immediately with accepted status (fire and forget)
result = await retain_tool.fn(content="test content")
assert result["status"] == "accepted"
# Wait for background task to complete (and log error)
await asyncio.sleep(0.1)
@pytest.mark.asyncio
async def test_local_mcp_server_recall_error_handling(mock_memory):
"""Test that recall handles errors gracefully."""
from hindsight_api.mcp_local import create_local_mcp_server
mock_memory.recall_async = AsyncMock(side_effect=Exception("Test error"))
mcp_server = create_local_mcp_server("test-bank", memory=mock_memory)
tools = mcp_server._tool_manager._tools
recall_tool = tools["recall"]
result = await recall_tool.fn(query="test query")
# Result is a dict with error
assert isinstance(result, dict)
assert "error" in result
assert result["results"] == []
@pytest.mark.asyncio
async def test_local_mcp_server_recall_with_defaults(mock_memory):
"""Test that recall uses default max_tokens and budget."""
from hindsight_api.mcp_local import create_local_mcp_server
from hindsight_api.engine.memory_engine import Budget
mock_result = MagicMock()
mock_result.model_dump.return_value = {"results": []}
mock_memory.recall_async = AsyncMock(return_value=mock_result)
mcp_server = create_local_mcp_server("test-bank", memory=mock_memory)
tools = mcp_server._tool_manager._tools
recall_tool = tools["recall"]
# Call with defaults
await recall_tool.fn(query="test query")
call_kwargs = mock_memory.recall_async.call_args.kwargs
assert call_kwargs["max_tokens"] == 4096
assert call_kwargs["budget"] == Budget.LOW
+3 -3
View File
@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock
def mock_memory():
"""Create a mock MemoryEngine."""
memory = MagicMock()
memory.put_batch_async = AsyncMock()
memory.retain_batch_async = AsyncMock()
memory.recall_async = AsyncMock(return_value=MagicMock(results=[]))
return memory
@@ -52,8 +52,8 @@ async def test_mcp_tools_use_context_bank_id(mock_memory):
assert "successfully" in result.lower()
# Verify the memory was called with the context bank_id
mock_memory.put_batch_async.assert_called_once()
call_kwargs = mock_memory.put_batch_async.call_args.kwargs
mock_memory.retain_batch_async.assert_called_once()
call_kwargs = mock_memory.retain_batch_async.call_args.kwargs
assert call_kwargs["bank_id"] == "context-bank-id"
finally:
_current_bank_id.reset(token)
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "hindsight-cli"
version = "0.1.4"
version = "0.1.5"
edition = "2021"
authors = ["Hindsight Team"]
description = "A beautiful CLI for Hindsight - semantic memory system"
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "hindsight-client"
version = "0.1.4"
version = "0.1.5"
description = "Python client for Hindsight - Semantic memory system with personality-driven thinking"
authors = [
{name = "Hindsight Team"}
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@vectorize-io/hindsight-client",
"version": "0.1.4",
"version": "0.1.5",
"description": "TypeScript client for Hindsight - Semantic memory system with personality-driven thinking",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
+1 -1
View File
@@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020", "DOM"],
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"declaration": true,
"outDir": "./dist",
"rootDir": "./",
+7
View File
@@ -0,0 +1,7 @@
{
"semi": true,
"singleQuote": false,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -1,6 +1,6 @@
{
"name": "hindsight-control-plane",
"version": "0.1.4",
"version": "0.1.5",
"private": true,
"scripts": {
"dev": "next dev",
@@ -36,7 +36,7 @@
"eslint": "^9.39.1",
"eslint-config-next": "^16.0.1",
"lucide-react": "^0.553.0",
"next": "^16.0.7",
"next": "^16.0.10",
"postcss": "^8.5.6",
"react": "^19.2.0",
"react-chrono": "^2.9.1",
@@ -48,5 +48,8 @@
"tailwindcss-animate": "^1.0.7",
"three": "^0.182.0",
"typescript": "^5.9.3"
},
"devDependencies": {
"prettier": "^3.7.4"
}
}
@@ -180,4 +180,13 @@ code, pre {
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Fix datetime-local calendar icon visibility in both light and dark modes */
input[type="datetime-local"]::-webkit-calendar-picker-indicator {
filter: invert(0.5);
}
.dark input[type="datetime-local"]::-webkit-calendar-picker-indicator {
filter: invert(1);
}
@@ -239,7 +239,7 @@ export function BankProfileView() {
<div className="flex gap-2">
{editMode ? (
<>
<Button onClick={handleCancel} variant="outline" disabled={saving}>
<Button onClick={handleCancel} variant="secondary" disabled={saving}>
Cancel
</Button>
<Button onClick={handleSave} disabled={saving}>
@@ -258,7 +258,7 @@ export function BankProfileView() {
</>
) : (
<>
<Button onClick={loadData} variant="outline" size="sm">
<Button onClick={loadData} variant="secondary" size="sm">
<RefreshCw className="w-4 h-4 mr-2" />
Refresh
</Button>
@@ -266,7 +266,7 @@ function BankSelectorInner() {
</div>
<DialogFooter>
<Button
variant="outline"
variant="secondary"
onClick={() => {
setCreateDialogOpen(false);
setNewBankId('');
@@ -295,7 +295,7 @@ function BankSelectorInner() {
</DialogHeader>
<div className="py-4 space-y-4">
<div>
<label className="font-bold block mb-1 text-sm">Content *</label>
<label className="font-bold block mb-1 text-sm text-foreground">Content *</label>
<Textarea
value={docContent}
onChange={(e) => setDocContent(e.target.value)}
@@ -306,7 +306,7 @@ function BankSelectorInner() {
</div>
<div>
<label className="font-bold block mb-1 text-sm">Context</label>
<label className="font-bold block mb-1 text-sm text-foreground">Context</label>
<Input
type="text"
value={docContext}
@@ -317,16 +317,17 @@ function BankSelectorInner() {
<div className="grid grid-cols-2 gap-4">
<div>
<label className="font-bold block mb-1 text-sm">Event Date</label>
<label className="font-bold block mb-1 text-sm text-foreground">Event Date</label>
<Input
type="datetime-local"
value={docEventDate}
onChange={(e) => setDocEventDate(e.target.value)}
className="text-foreground"
/>
</div>
<div>
<label className="font-bold block mb-1 text-sm">Document ID</label>
<label className="font-bold block mb-1 text-sm text-foreground">Document ID</label>
<Input
type="text"
value={docDocumentId}
@@ -342,7 +343,7 @@ function BankSelectorInner() {
checked={docAsync}
onCheckedChange={(checked) => setDocAsync(checked as boolean)}
/>
<label htmlFor="async-doc" className="text-sm cursor-pointer">
<label htmlFor="async-doc" className="text-sm cursor-pointer text-foreground">
Process in background (async)
</label>
</div>
@@ -353,7 +354,7 @@ function BankSelectorInner() {
</div>
<DialogFooter>
<Button
variant="outline"
variant="secondary"
onClick={() => {
setDocDialogOpen(false);
setDocContent('');
@@ -480,7 +480,7 @@ export function DataView({ factType }: DataViewProps) {
}`}
>
<TableCell className="py-2">
<div className="line-clamp-2 text-sm leading-snug">{row.text}</div>
<div className="line-clamp-2 text-sm leading-snug text-foreground">{row.text}</div>
{row.context && (
<div className="text-xs text-muted-foreground mt-0.5 truncate">{row.context}</div>
)}
@@ -506,10 +506,10 @@ export function DataView({ factType }: DataViewProps) {
<span className="text-xs text-muted-foreground">-</span>
)}
</TableCell>
<TableCell className="text-xs py-2">
<TableCell className="text-xs py-2 text-foreground">
{occurredDisplay || <span className="text-muted-foreground">-</span>}
</TableCell>
<TableCell className="text-xs py-2">
<TableCell className="text-xs py-2 text-foreground">
{mentionedDisplay || <span className="text-muted-foreground">-</span>}
</TableCell>
<TableCell className="py-2">
@@ -519,7 +519,7 @@ export function DataView({ factType }: DataViewProps) {
copyToClipboard(row.id);
}}
size="sm"
variant="ghost"
variant="secondary"
className="h-6 w-6 p-0"
title="Copy ID"
>
@@ -799,7 +799,7 @@ function TimelineView({ data, filteredRows }: { data: any; filteredRows: any[] }
{/* Zoom controls */}
<div className="flex items-center border border-border rounded mr-2">
<Button
variant="ghost"
variant="secondary"
size="sm"
onClick={zoomOut}
disabled={granularity === 'year'}
@@ -808,11 +808,11 @@ function TimelineView({ data, filteredRows }: { data: any; filteredRows: any[] }
>
<ZoomOut className="h-3 w-3" />
</Button>
<span className="text-[10px] px-2 min-w-[50px] text-center border-x border-border">
<span className="text-[10px] px-2 min-w-[50px] text-center border-x border-border text-foreground">
{granularityLabels[granularity]}
</span>
<Button
variant="ghost"
variant="secondary"
size="sm"
onClick={zoomIn}
disabled={granularity === 'day'}
@@ -826,7 +826,7 @@ function TimelineView({ data, filteredRows }: { data: any; filteredRows: any[] }
{/* Navigation controls */}
<div className="flex items-center border border-border rounded">
<Button
variant="ghost"
variant="secondary"
size="sm"
onClick={() => scrollToGroup(0)}
disabled={timelineGroups.length <= 1}
@@ -836,7 +836,7 @@ function TimelineView({ data, filteredRows }: { data: any; filteredRows: any[] }
<ChevronsLeft className="h-3 w-3" />
</Button>
<Button
variant="ghost"
variant="secondary"
size="sm"
onClick={() => scrollToGroup(currentIndex - 1)}
disabled={currentIndex === 0}
@@ -845,11 +845,11 @@ function TimelineView({ data, filteredRows }: { data: any; filteredRows: any[] }
>
<ChevronLeft className="h-3 w-3" />
</Button>
<span className="text-[10px] px-2 min-w-[60px] text-center border-x border-border">
<span className="text-[10px] px-2 min-w-[60px] text-center border-x border-border text-foreground">
{currentIndex + 1} / {timelineGroups.length}
</span>
<Button
variant="ghost"
variant="secondary"
size="sm"
onClick={() => scrollToGroup(currentIndex + 1)}
disabled={currentIndex >= timelineGroups.length - 1}
@@ -859,7 +859,7 @@ function TimelineView({ data, filteredRows }: { data: any; filteredRows: any[] }
<ChevronRight className="h-3 w-3" />
</Button>
<Button
variant="ghost"
variant="secondary"
size="sm"
onClick={() => scrollToGroup(timelineGroups.length - 1)}
disabled={timelineGroups.length <= 1}
@@ -94,7 +94,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Document ID
</div>
<div className="text-sm font-mono break-all">{data.id}</div>
<div className="text-sm font-mono break-all text-foreground">{data.id}</div>
</div>
{data.created_at && (
<div className="grid grid-cols-2 gap-3">
@@ -102,7 +102,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Created
</div>
<div className="text-sm">
<div className="text-sm text-foreground">
{new Date(data.created_at).toLocaleString()}
</div>
</div>
@@ -110,7 +110,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Memory Units
</div>
<div className="text-sm">{data.memory_unit_count}</div>
<div className="text-sm text-foreground">{data.memory_unit_count}</div>
</div>
</div>
)}
@@ -119,7 +119,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Text Length
</div>
<div className="text-sm">
<div className="text-sm text-foreground">
{data.original_text.length.toLocaleString()} characters
</div>
</div>
@@ -132,7 +132,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
Original Text
</div>
<div className="p-4 bg-muted rounded-lg border border-border max-h-[300px] overflow-y-auto">
<pre className="text-sm whitespace-pre-wrap font-mono">
<pre className="text-sm whitespace-pre-wrap font-mono text-foreground">
{data.original_text}
</pre>
</div>
@@ -146,7 +146,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Chunk ID
</div>
<div className="text-sm font-mono break-all">
<div className="text-sm font-mono break-all text-foreground">
{data.chunk_id}
</div>
</div>
@@ -155,7 +155,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Document ID
</div>
<div className="text-sm font-mono break-all">
<div className="text-sm font-mono break-all text-foreground">
{data.document_id}
</div>
</div>
@@ -163,7 +163,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Chunk Index
</div>
<div className="text-sm">{data.chunk_index}</div>
<div className="text-sm text-foreground">{data.chunk_index}</div>
</div>
</div>
{data.created_at && (
@@ -171,7 +171,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Created
</div>
<div className="text-sm">
<div className="text-sm text-foreground">
{new Date(data.created_at).toLocaleString()}
</div>
</div>
@@ -181,7 +181,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
<div className="text-xs font-bold text-muted-foreground uppercase mb-1">
Text Length
</div>
<div className="text-sm">
<div className="text-sm text-foreground">
{data.chunk_text.length.toLocaleString()} characters
</div>
</div>
@@ -194,7 +194,7 @@ export function DocumentChunkModal({ type, id, onClose }: DocumentChunkModalProp
Chunk Text
</div>
<div className="p-4 bg-muted rounded-lg border border-border max-h-[300px] overflow-y-auto">
<pre className="text-sm whitespace-pre-wrap font-mono">
<pre className="text-sm whitespace-pre-wrap font-mono text-foreground">
{data.chunk_text}
</pre>
</div>
@@ -122,17 +122,17 @@ export function DocumentsView() {
className={`cursor-pointer hover:bg-muted/50 ${selectedDocument?.id === doc.id ? 'bg-primary/10' : ''}`}
onClick={() => viewDocumentText(doc.id)}
>
<TableCell title={doc.id}>
<TableCell title={doc.id} className="text-card-foreground">
{doc.id.length > 30 ? doc.id.substring(0, 30) + '...' : doc.id}
</TableCell>
<TableCell>
<TableCell className="text-card-foreground">
{doc.created_at ? new Date(doc.created_at).toLocaleString() : 'N/A'}
</TableCell>
<TableCell>
<TableCell className="text-card-foreground">
{doc.retain_params?.context || '-'}
</TableCell>
<TableCell>{doc.text_length?.toLocaleString()} chars</TableCell>
<TableCell>{doc.memory_unit_count}</TableCell>
<TableCell className="text-card-foreground">{doc.text_length?.toLocaleString()} chars</TableCell>
<TableCell className="text-card-foreground">{doc.memory_unit_count}</TableCell>
<TableCell>
<Button
onClick={(e) => {
@@ -140,7 +140,7 @@ export function DocumentsView() {
viewDocumentText(doc.id);
}}
size="sm"
variant={selectedDocument?.id === doc.id ? 'default' : 'outline'}
variant={selectedDocument?.id === doc.id ? 'default' : 'secondary'}
title="View original text"
>
View Text
@@ -171,7 +171,7 @@ export function DocumentsView() {
<p className="text-sm text-muted-foreground mt-1">Original document text and metadata</p>
</div>
<Button
variant="outline"
variant="secondary"
size="sm"
onClick={() => setSelectedDocument(null)}
className="h-9 px-3 gap-2"
@@ -193,7 +193,7 @@ export function DocumentsView() {
{/* Document ID */}
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Document ID</div>
<code className="text-sm font-mono break-all text-foreground">{selectedDocument.id}</code>
<div className="text-sm font-mono break-all text-card-foreground">{selectedDocument.id}</div>
</div>
{/* Created & Memory Units */}
@@ -201,11 +201,11 @@ export function DocumentsView() {
<div className="grid grid-cols-2 gap-4">
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Created</div>
<div className="text-sm font-medium text-foreground">{new Date(selectedDocument.created_at).toLocaleString()}</div>
<div className="text-sm font-medium text-card-foreground">{new Date(selectedDocument.created_at).toLocaleString()}</div>
</div>
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Memory Units</div>
<div className="text-sm font-medium text-foreground">{selectedDocument.memory_unit_count}</div>
<div className="text-sm font-medium text-card-foreground">{selectedDocument.memory_unit_count}</div>
</div>
</div>
)}
@@ -214,7 +214,7 @@ export function DocumentsView() {
{selectedDocument.original_text && (
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Text Length</div>
<div className="text-sm font-medium text-foreground">{selectedDocument.original_text.length.toLocaleString()} characters</div>
<div className="text-sm font-medium text-card-foreground">{selectedDocument.original_text.length.toLocaleString()} characters</div>
</div>
)}
@@ -222,7 +222,7 @@ export function DocumentsView() {
{selectedDocument.retain_params && (
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Retain Parameters</div>
<div className="text-sm space-y-2">
<div className="text-sm space-y-2 text-card-foreground">
{selectedDocument.retain_params.context && (
<div><span className="font-semibold">Context:</span> {selectedDocument.retain_params.context}</div>
)}
@@ -232,7 +232,7 @@ export function DocumentsView() {
{selectedDocument.retain_params.metadata && (
<div className="mt-2">
<span className="font-semibold">Metadata:</span>
<pre className="mt-1 text-xs bg-background p-2 rounded">{JSON.stringify(selectedDocument.retain_params.metadata, null, 2)}</pre>
<pre className="mt-1 text-xs bg-background p-2 rounded text-card-foreground">{JSON.stringify(selectedDocument.retain_params.metadata, null, 2)}</pre>
</div>
)}
</div>
@@ -244,7 +244,7 @@ export function DocumentsView() {
<div>
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Original Text</div>
<div className="p-4 bg-muted/50 rounded-lg border border-border max-h-[400px] overflow-y-auto">
<pre className="text-sm whitespace-pre-wrap font-mono leading-relaxed text-foreground">{selectedDocument.original_text}</pre>
<pre className="text-sm whitespace-pre-wrap font-mono leading-relaxed text-card-foreground">{selectedDocument.original_text}</pre>
</div>
</div>
)}
@@ -126,10 +126,10 @@ export function EntitiesView() {
selectedEntity?.id === entity.id ? 'bg-primary/10' : ''
}`}
>
<TableCell className="font-medium">{entity.canonical_name}</TableCell>
<TableCell>{entity.mention_count}</TableCell>
<TableCell>{formatDate(entity.first_seen)}</TableCell>
<TableCell>{formatDate(entity.last_seen)}</TableCell>
<TableCell className="font-medium text-card-foreground">{entity.canonical_name}</TableCell>
<TableCell className="text-card-foreground">{entity.mention_count}</TableCell>
<TableCell className="text-card-foreground">{formatDate(entity.first_seen)}</TableCell>
<TableCell className="text-card-foreground">{formatDate(entity.last_seen)}</TableCell>
</TableRow>
))}
</TableBody>
@@ -154,7 +154,7 @@ export function EntitiesView() {
{/* Header */}
<div className="flex justify-between items-center mb-6 pb-4 border-b border-border">
<div>
<h3 className="text-xl font-bold text-foreground">{selectedEntity.canonical_name}</h3>
<h3 className="text-xl font-bold text-card-foreground">{selectedEntity.canonical_name}</h3>
<p className="text-sm text-muted-foreground mt-1">Entity details</p>
</div>
<Button
@@ -172,11 +172,11 @@ export function EntitiesView() {
<div className="grid grid-cols-2 gap-4">
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Mentions</div>
<div className="text-lg font-semibold text-foreground">{selectedEntity.mention_count}</div>
<div className="text-lg font-semibold text-card-foreground">{selectedEntity.mention_count}</div>
</div>
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">First Seen</div>
<div className="text-sm font-medium text-foreground">{formatDate(selectedEntity.first_seen)}</div>
<div className="text-sm font-medium text-card-foreground">{formatDate(selectedEntity.first_seen)}</div>
</div>
</div>
@@ -206,7 +206,7 @@ export function EntitiesView() {
<ul className="space-y-2">
{selectedEntity.observations.map((obs, idx) => (
<li key={idx} className="p-3 bg-muted/50 rounded-lg">
<div className="text-sm text-foreground">{obs.text}</div>
<div className="text-sm text-card-foreground">{obs.text}</div>
{obs.mentioned_at && (
<div className="text-xs text-muted-foreground mt-2">
{formatDate(obs.mentioned_at)}
@@ -67,7 +67,7 @@ export function MemoryDetailPanel({
<p className="text-sm text-muted-foreground mt-1">Full memory content and metadata</p>
</div>
<Button
variant="ghost"
variant="secondary"
size="sm"
onClick={onClose}
className="h-8 w-8 p-0"
@@ -80,14 +80,14 @@ export function MemoryDetailPanel({
{/* Full Text */}
<div>
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Full Text</div>
<div className="text-sm whitespace-pre-wrap leading-relaxed">{memory.text}</div>
<div className="text-sm whitespace-pre-wrap leading-relaxed text-foreground">{memory.text}</div>
</div>
{/* Context */}
{memory.context && (
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Context</div>
<div className="text-sm">{memory.context}</div>
<div className="text-sm text-foreground">{memory.context}</div>
</div>
)}
@@ -95,7 +95,7 @@ export function MemoryDetailPanel({
<div className="grid grid-cols-2 gap-4">
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Occurred</div>
<div className="text-sm font-medium">
<div className="text-sm font-medium text-foreground">
{memory.occurred_start
? new Date(memory.occurred_start).toLocaleString()
: 'N/A'}
@@ -103,7 +103,7 @@ export function MemoryDetailPanel({
</div>
<div className="p-4 bg-muted/50 rounded-lg">
<div className="text-xs font-bold text-muted-foreground uppercase mb-2">Mentioned</div>
<div className="text-sm font-medium">
<div className="text-sm font-medium text-foreground">
{memory.mentioned_at
? new Date(memory.mentioned_at).toLocaleString()
: 'N/A'}
@@ -159,7 +159,7 @@ export function MemoryDetailPanel({
{memory.document_id && (
<Button
onClick={() => openDocumentModal(memory.document_id)}
variant="outline"
variant="secondary"
className="flex-1"
>
View Document
@@ -168,7 +168,7 @@ export function MemoryDetailPanel({
{memory.chunk_id && (
<Button
onClick={() => openChunkModal(memory.chunk_id)}
variant="outline"
variant="secondary"
className="flex-1"
>
View Chunk
@@ -300,7 +300,7 @@ export function MemoryDetailPanel({
<Button
onClick={() => openDocumentModal(memory.document_id)}
size="sm"
variant="outline"
variant="secondary"
className={`flex-1 ${compact ? 'h-7 text-xs' : ''}`}
>
View Document
@@ -310,7 +310,7 @@ export function MemoryDetailPanel({
<Button
onClick={() => openChunkModal(memory.chunk_id)}
size="sm"
variant="outline"
variant="secondary"
className={`flex-1 ${compact ? 'h-7 text-xs' : ''}`}
>
View Chunk
@@ -44,7 +44,7 @@ const DialogContent = React.forwardRef<
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm ring-offset-background transition-opacity hover:opacity-80 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground text-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
@@ -88,7 +88,7 @@ const DialogTitle = React.forwardRef<
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
"text-lg font-semibold leading-none tracking-tight text-foreground",
className
)}
{...props}
@@ -0,0 +1,359 @@
#!/usr/bin/env python3
"""
Generate changelog entry for a new release.
This script fetches the commit diff between releases, uses an LLM to summarize,
and prepends the entry to the changelog page.
"""
import argparse
import json
import os
import re
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from openai import OpenAI
from pydantic import BaseModel
from rich.console import Console
console = Console()
GITHUB_REPO = "vectorize-io/hindsight"
GITHUB_RELEASES_URL = f"https://github.com/{GITHUB_REPO}/releases"
GITHUB_COMMIT_URL = f"https://github.com/{GITHUB_REPO}/commit"
REPO_PATH = Path(__file__).parent.parent.parent
CHANGELOG_PATH = REPO_PATH / "hindsight-docs" / "docs" / "changelog" / "index.md"
class ChangelogEntry(BaseModel):
"""A single changelog entry."""
category: str # "feature", "improvement", "bugfix", "breaking", "other"
summary: str # Brief description of the change
commit_id: str # Short commit hash
class ChangelogResponse(BaseModel):
"""Structured response from LLM."""
entries: list[ChangelogEntry]
@dataclass
class Commit:
"""Parsed commit from git log."""
hash: str
message: str
def parse_semver(version: str) -> tuple[int, int, int]:
"""Parse a semver string into (major, minor, patch)."""
version = version.lstrip("v")
match = re.match(r"^(\d+)\.(\d+)\.(\d+)", version)
if not match:
raise ValueError(f"Invalid semver: {version}")
return int(match.group(1)), int(match.group(2)), int(match.group(3))
def get_git_tags() -> list[str]:
"""Get all git tags sorted by semver (newest first)."""
result = subprocess.run(
["git", "tag"],
cwd=REPO_PATH,
capture_output=True,
text=True,
check=True,
)
tags = [t.strip() for t in result.stdout.strip().split("\n") if t.strip()]
valid_tags = []
for tag in tags:
try:
parse_semver(tag)
valid_tags.append(tag)
except ValueError:
continue
valid_tags.sort(key=lambda t: parse_semver(t), reverse=True)
return valid_tags
def find_previous_version(new_version: str, existing_tags: list[str]) -> str | None:
"""Find the previous version based on semver rules."""
new_major, new_minor, new_patch = parse_semver(new_version)
candidates = []
for tag in existing_tags:
try:
major, minor, patch = parse_semver(tag)
except ValueError:
continue
if (major, minor, patch) >= (new_major, new_minor, new_patch):
continue
candidates.append((tag, (major, minor, patch)))
if not candidates:
return None
candidates.sort(key=lambda x: x[1], reverse=True)
return candidates[0][0]
def get_commits(from_ref: str | None, to_ref: str) -> list[Commit]:
"""Get commits between two refs as structured data."""
if from_ref:
cmd = ["git", "log", "--format=%h|%s", "--no-merges", f"{from_ref}..{to_ref}"]
else:
cmd = ["git", "log", "--format=%h|%s", "--no-merges", to_ref]
result = subprocess.run(
cmd,
cwd=REPO_PATH,
capture_output=True,
text=True,
check=True,
)
commits = []
for line in result.stdout.strip().split("\n"):
if not line:
continue
parts = line.split("|", 1)
if len(parts) == 2:
commits.append(Commit(hash=parts[0], message=parts[1]))
return commits
def get_detailed_diff(from_ref: str | None, to_ref: str) -> str:
"""Get file change stats between two refs."""
if from_ref:
cmd = ["git", "diff", "--stat", f"{from_ref}..{to_ref}"]
else:
cmd = ["git", "diff", "--stat", f"{to_ref}^..{to_ref}"]
result = subprocess.run(
cmd,
cwd=REPO_PATH,
capture_output=True,
text=True,
)
return result.stdout.strip()
def analyze_commits_with_llm(
client: OpenAI,
model: str,
version: str,
commits: list[Commit],
file_diff: str,
) -> list[ChangelogEntry]:
"""Use LLM to analyze commits and return structured changelog entries."""
commits_json = json.dumps(
[{"commit_id": c.hash, "message": c.message} for c in commits],
indent=2
)
prompt = f"""Analyze the following git commits for release {version} of Hindsight (an AI memory system).
For each meaningful change, create a changelog entry with:
- category: one of "feature", "improvement", "bugfix", "breaking", "other"
- summary: brief one-line description of the change (user-facing, not technical)
- commit_id: the commit hash from the input
Rules:
- Group related commits into a single entry if they're part of the same change
- Skip trivial changes (typo fixes, formatting, internal refactoring)
- Skip repository-only changes: README updates, CI/GitHub Actions, release scripts, changelog updates, version bumps
- Focus on user-facing changes that affect the product functionality
- Use the exact commit_id from the input (pick the most relevant one if grouping)
- If no meaningful changes remain after filtering, return an empty list
Commits:
{commits_json}
Files changed summary:
{file_diff[:4000]}"""
response = client.beta.chat.completions.parse(
model=model,
messages=[{"role": "user", "content": prompt}],
response_format=ChangelogResponse,
max_completion_tokens=16000,
)
return response.choices[0].message.parsed.entries
def build_changelog_markdown(
version: str,
tag: str,
entries: list[ChangelogEntry],
) -> str:
"""Build markdown changelog from structured entries."""
release_url = f"{GITHUB_RELEASES_URL}/tag/{tag}"
# Group entries by category
categories = {
"breaking": ("Breaking Changes", []),
"feature": ("Features", []),
"improvement": ("Improvements", []),
"bugfix": ("Bug Fixes", []),
"other": ("Other", []),
}
for entry in entries:
cat = entry.category.lower()
if cat in categories:
categories[cat][1].append(entry)
else:
categories["other"][1].append(entry)
# Build markdown
lines = [f"## [{version}]({release_url})", ""]
for cat_key in ["breaking", "feature", "improvement", "bugfix", "other"]:
cat_name, cat_entries = categories[cat_key]
if cat_entries:
lines.append(f"**{cat_name}**")
lines.append("")
for entry in cat_entries:
commit_url = f"{GITHUB_COMMIT_URL}/{entry.commit_id}"
lines.append(f"- {entry.summary} ([`{entry.commit_id}`]({commit_url}))")
lines.append("")
return "\n".join(lines)
def read_existing_changelog() -> tuple[str, str]:
"""Read existing changelog and split into header and content."""
if not CHANGELOG_PATH.exists():
header = """---
sidebar_position: 1
---
# Changelog
For full release details, see [GitHub Releases](https://github.com/vectorize-io/hindsight/releases).
"""
return header, ""
content = CHANGELOG_PATH.read_text()
match = re.search(r"^## ", content, re.MULTILINE)
if match:
header = content[:match.start()].rstrip() + "\n\n"
releases = content[match.start():]
else:
header = content.rstrip() + "\n\n"
releases = ""
return header, releases
def write_changelog(header: str, new_entry: str, existing_releases: str) -> None:
"""Write changelog with new entry prepended."""
content = header + new_entry + "\n" + existing_releases
CHANGELOG_PATH.parent.mkdir(parents=True, exist_ok=True)
CHANGELOG_PATH.write_text(content.rstrip() + "\n")
def generate_changelog_entry(
version: str,
llm_model: str = "gpt-5.2",
) -> None:
"""Generate changelog entry for a specific version."""
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
console.print("[red]Error: OPENAI_API_KEY environment variable not set[/red]")
sys.exit(1)
client = OpenAI(api_key=api_key)
tag = version if version.startswith("v") else f"v{version}"
display_version = version.lstrip("v")
console.print(f"[blue]Fetching tags from repository...[/blue]")
existing_tags = get_git_tags()
if tag not in existing_tags and display_version not in existing_tags:
console.print(f"[red]Error: Tag {tag} not found in repository[/red]")
console.print("[red]Create the tag first before generating changelog[/red]")
sys.exit(1)
actual_tag = tag if tag in existing_tags else display_version
previous_tag = find_previous_version(display_version, existing_tags)
if previous_tag:
console.print(f"[green]Found previous version: {previous_tag}[/green]")
else:
console.print("[yellow]No previous version found, will include all commits[/yellow]")
console.print(f"[blue]Getting commits...[/blue]")
commits = get_commits(previous_tag, actual_tag)
file_diff = get_detailed_diff(previous_tag, actual_tag)
if not commits:
console.print("[red]Error: No commits found for this release[/red]")
sys.exit(1)
console.print(f"[blue]Found {len(commits)} commits[/blue]")
# Log commits
console.print("\n[bold]Commits:[/bold]")
for c in commits:
console.print(f" {c.hash} {c.message}")
console.print("\n[bold]Files changed:[/bold]")
console.print(file_diff[:4000] if len(file_diff) > 4000 else file_diff)
console.print("")
console.print(f"[blue]Analyzing commits with LLM ({llm_model})...[/blue]")
entries = analyze_commits_with_llm(client, llm_model, display_version, commits, file_diff)
console.print(f"\n[bold]LLM identified {len(entries)} changelog entries:[/bold]")
for entry in entries:
console.print(f" [{entry.category}] {entry.summary} ({entry.commit_id})")
new_entry = build_changelog_markdown(display_version, tag, entries)
header, existing_releases = read_existing_changelog()
if f"## [{display_version}]" in existing_releases:
console.print(f"[red]Error: Version {display_version} already exists in changelog[/red]")
sys.exit(1)
write_changelog(header, new_entry, existing_releases)
console.print(f"\n[green]Changelog updated: {CHANGELOG_PATH}[/green]")
console.print(f"\n[bold]New entry:[/bold]\n{new_entry}")
def main():
parser = argparse.ArgumentParser(
description="Generate changelog entry for a release",
usage="generate-changelog VERSION [--model MODEL]",
)
parser.add_argument(
"version",
help="Version to generate changelog for (e.g., 1.0.5, v1.0.5)",
)
parser.add_argument(
"--model",
default="gpt-5.2",
help="OpenAI model to use (default: gpt-5.2)",
)
args = parser.parse_args()
generate_changelog_entry(
version=args.version,
llm_model=args.model,
)
if __name__ == "__main__":
main()
@@ -0,0 +1,156 @@
#!/usr/bin/env python3
"""
Generates llms-full.txt by concatenating all documentation markdown files.
This file is used by LLMs to understand the full documentation.
Usage: generate-llms-full (after installing hindsight-dev)
Output: hindsight-docs/static/llms-full.txt (served at /llms-full.txt)
"""
import re
from datetime import datetime, timezone
from pathlib import Path
# Order matters - more important docs first
DOC_ORDER = [
"developer/index.md",
"developer/api/quickstart.md",
"developer/api/main-methods.md",
"developer/retain.md",
"developer/retrieval.md",
"developer/reflect.md",
"developer/api/retain.md",
"developer/api/recall.md",
"developer/api/reflect.md",
"developer/api/memory-banks.md",
"developer/api/entities.md",
"developer/api/documents.md",
"developer/api/operations.md",
"developer/installation.md",
"developer/configuration.md",
"developer/models.md",
"developer/rag-vs-hindsight.md",
"sdks/python.md",
"sdks/nodejs.md",
"sdks/cli.md",
"sdks/mcp.md",
"cookbook/index.mdx",
"cookbook/recipes/quickstart.md",
"cookbook/recipes/per-user-memory.md",
"cookbook/recipes/support-agent-shared-knowledge.md",
"cookbook/applications/openai-fitness-coach.md",
]
def get_docs_dir() -> Path:
"""Find the hindsight-docs directory relative to this script."""
script_dir = Path(__file__).parent
return script_dir.parent.parent / "hindsight-docs" / "docs"
def get_output_file() -> Path:
"""Get output file path."""
script_dir = Path(__file__).parent
return script_dir.parent.parent / "hindsight-docs" / "static" / "llms-full.txt"
def get_all_markdown_files(docs_dir: Path) -> list[str]:
"""Recursively find all markdown files."""
files = []
for path in docs_dir.rglob("*"):
if path.suffix in (".md", ".mdx"):
files.append(str(path.relative_to(docs_dir)))
return files
def strip_frontmatter(content: str) -> str:
"""Remove YAML frontmatter (between --- markers)."""
return re.sub(r"^---\n[\s\S]*?\n---\n", "", content)
def clean_markdown(content: str) -> str:
"""Clean markdown content for LLM consumption."""
cleaned = strip_frontmatter(content)
# Remove import statements
cleaned = re.sub(r"^import\s+.*$", "", cleaned, flags=re.MULTILINE)
# Remove JSX components (like <RecipeCarousel ... />)
cleaned = re.sub(r"<[A-Z][a-zA-Z]*\s+[^>]*/>", "", cleaned)
cleaned = re.sub(r"<[A-Z][a-zA-Z]*[^>]*>[\s\S]*?</[A-Z][a-zA-Z]*>", "", cleaned)
# Remove empty lines at start
cleaned = re.sub(r"^\n+", "", cleaned)
return cleaned
def main():
"""Generate llms-full.txt."""
print("Generating llms-full.txt...")
docs_dir = get_docs_dir()
output_file = get_output_file()
# Get all markdown files
all_files = get_all_markdown_files(docs_dir)
# Create ordered list: prioritized files first, then remaining files
ordered_files = []
remaining_files = set(all_files)
# Add prioritized files in order
for file in DOC_ORDER:
if file in remaining_files:
ordered_files.append(file)
remaining_files.discard(file)
# Add remaining files (sorted alphabetically)
ordered_files.extend(sorted(remaining_files))
# Build the output
sections = []
# Header
timestamp = datetime.now(timezone.utc).isoformat()
sections.append(f"""# Hindsight Documentation
> Agent Memory that Works Like Human Memory
This file contains the complete Hindsight documentation for LLM consumption.
Generated: {timestamp}
---
""")
# Process each file
for file in ordered_files:
file_path = docs_dir / file
if not file_path.exists():
print(f" Warning: {file} not found, skipping")
continue
content = file_path.read_text()
cleaned_content = clean_markdown(content)
if cleaned_content.strip():
sections.append(f"\n## File: {file}\n")
sections.append(cleaned_content)
sections.append("\n---\n")
print(f" Added: {file}")
# Write output
output = "\n".join(sections)
output_file.write_text(output)
size_kb = output_file.stat().st_size / 1024
print(f"\nGenerated: {output_file}")
print(f"Size: {size_kb:.1f} KB")
print(f"Files included: {len(ordered_files)}")
if __name__ == "__main__":
main()
@@ -0,0 +1,514 @@
#!/usr/bin/env python3
"""
Syncs content from the hindsight-cookbook repository.
- Clones the cookbook repo to a temp directory
- Converts notebooks/*.ipynb → docs/cookbook/recipes/*.md
- Converts app directories (with README.md) → docs/cookbook/applications/*.md
- Updates sidebars.ts with the new entries
Usage: sync-cookbook (after installing hindsight-dev)
Conventions in cookbook repo:
- notebooks/*.ipynb → Recipes (use cases, tutorials)
- Directories with README.md at root → Applications (complete apps)
- Notebook title extracted from first # heading in first markdown cell
- App title extracted from first # heading in README.md
"""
import json
import os
import re
import shutil
import subprocess
import tempfile
from pathlib import Path
COOKBOOK_REPO = "https://github.com/vectorize-io/hindsight-cookbook.git"
IGNORE_DIRS = {".git", "notebooks", "node_modules", "__pycache__", ".venv", "venv"}
def get_docs_dir() -> Path:
"""Find the hindsight-docs directory relative to this script."""
# Navigate from hindsight-dev to hindsight-docs
script_dir = Path(__file__).parent
docs_dir = script_dir.parent.parent / "hindsight-docs" / "docs" / "cookbook"
return docs_dir
def get_sidebars_file() -> Path:
script_dir = Path(__file__).parent
return script_dir.parent.parent / "hindsight-docs" / "sidebars.ts"
def slugify(filename: str) -> str:
"""Convert filename to slug. e.g., '01-quickstart.ipynb''quickstart'"""
slug = re.sub(r"\.ipynb$", "", filename)
slug = re.sub(r"\.md$", "", slug)
slug = re.sub(r"^\d+-", "", slug)
return slug
def extract_title_from_notebook(notebook_path: Path) -> str:
"""Extract title from first markdown cell's # heading."""
try:
content = json.loads(notebook_path.read_text())
for cell in content.get("cells", []):
if cell.get("cell_type") == "markdown":
source = cell.get("source", [])
if isinstance(source, list):
source = "".join(source)
match = re.search(r"^#\s+(.+)$", source, re.MULTILINE)
if match:
return match.group(1).strip()
except Exception as e:
print(f" Warning: Could not parse notebook {notebook_path}: {e}")
# Fallback to filename
slug = slugify(notebook_path.name)
return " ".join(word.capitalize() for word in slug.split("-"))
def extract_description_from_notebook(notebook_path: Path) -> str | None:
"""Extract first paragraph after title from notebook."""
try:
content = json.loads(notebook_path.read_text())
for cell in content.get("cells", []):
if cell.get("cell_type") == "markdown":
source = cell.get("source", [])
if isinstance(source, list):
source = "".join(source)
lines = source.split("\n")
found_title = False
description = []
for line in lines:
if line.startswith("#"):
found_title = True
continue
if found_title and line.strip():
if line.startswith("#"):
break
description.append(line.strip())
if line.strip().endswith("."):
break
if description:
return " ".join(description)[:200]
except Exception:
pass
return None
def extract_title_from_readme(readme_path: Path) -> str | None:
"""Extract title from README's first # heading."""
try:
content = readme_path.read_text()
match = re.search(r"^#\s+(.+)$", content, re.MULTILINE)
if match:
return match.group(1).strip()
except Exception as e:
print(f" Warning: Could not read {readme_path}: {e}")
return None
def convert_notebook_to_markdown(notebook_path: Path) -> str:
"""Convert Jupyter notebook to markdown.
Uses nbconvert with --no-input to exclude outputs (which often contain
characters that break MDX parsing).
"""
# Try nbconvert first
try:
with tempfile.TemporaryDirectory() as tmpdir:
subprocess.run(
[
"jupyter",
"nbconvert",
"--to",
"markdown",
"--TemplateExporter.exclude_output=True", # Exclude cell outputs
str(notebook_path),
"--output-dir",
tmpdir,
],
capture_output=True,
check=True,
)
md_file = Path(tmpdir) / notebook_path.with_suffix(".md").name
if md_file.exists():
return md_file.read_text()
except Exception as e:
print(f" Warning: nbconvert failed ({e}), using fallback parser")
# Fallback: manual conversion
return convert_notebook_manually(notebook_path)
def convert_notebook_manually(notebook_path: Path) -> str:
"""Manually convert notebook to markdown.
Note: We skip cell outputs to avoid MDX parsing issues (outputs often contain
characters like < and > that get interpreted as JSX tags).
"""
content = json.loads(notebook_path.read_text())
parts = []
lang = content.get("metadata", {}).get("kernelspec", {}).get("language", "python")
for cell in content.get("cells", []):
source = cell.get("source", [])
if isinstance(source, list):
source = "".join(source)
if cell.get("cell_type") == "markdown":
parts.append(source)
elif cell.get("cell_type") == "code":
parts.append(f"```{lang}\n{source}\n```")
# Skip outputs - they often contain characters that break MDX parsing
return "\n\n".join(parts)
def process_notebooks(cookbook_dir: Path, recipes_dir: Path) -> list[dict]:
"""Process all notebooks and convert to recipe markdown files."""
notebooks_dir = cookbook_dir / "notebooks"
recipes = []
if not notebooks_dir.exists():
print(" No notebooks directory found")
return recipes
files = sorted(f for f in notebooks_dir.iterdir() if f.suffix == ".ipynb")
print(f" Found {len(files)} notebooks")
for i, notebook_path in enumerate(files):
slug = slugify(notebook_path.name)
title = extract_title_from_notebook(notebook_path)
description = extract_description_from_notebook(notebook_path)
print(f" Processing: {notebook_path.name}{slug}.md")
# Convert notebook to markdown
md_content = convert_notebook_to_markdown(notebook_path)
# Create recipe page with frontmatter
notebook_url = f"https://github.com/vectorize-io/hindsight-cookbook/blob/main/notebooks/{notebook_path.name}"
frontmatter = f"""---
sidebar_position: {i + 1}
---
"""
callout = f"""
:::tip Run this notebook
This recipe is available as an interactive Jupyter notebook.
[**Open in GitHub →**]({notebook_url})
:::
"""
# Insert callout after first heading
first_heading_match = re.search(r"^(#\s+.+\n)", md_content, re.MULTILINE)
if first_heading_match:
idx = md_content.index(first_heading_match.group(0)) + len(
first_heading_match.group(0)
)
final_content = md_content[:idx] + "\n" + callout + "\n" + md_content[idx:]
else:
final_content = callout + "\n" + md_content
output_path = recipes_dir / f"{slug}.md"
output_path.write_text(frontmatter + final_content)
recipes.append(
{
"slug": slug,
"title": title,
"description": description,
"id": f"cookbook/recipes/{slug}",
}
)
return recipes
def process_applications(cookbook_dir: Path, apps_dir: Path) -> list[dict]:
"""Process application directories with README.md."""
apps = []
for entry in sorted(cookbook_dir.iterdir()):
if not entry.is_dir() or entry.name in IGNORE_DIRS:
continue
readme_path = entry / "README.md"
if not readme_path.exists():
continue
slug = entry.name
title = extract_title_from_readme(readme_path) or " ".join(
word.capitalize() for word in slug.split("-")
)
print(f" Processing app: {entry.name}{slug}.md")
# Read README content
readme_content = readme_path.read_text()
# Create application page with frontmatter
app_url = f"https://github.com/vectorize-io/hindsight-cookbook/tree/main/{entry.name}"
frontmatter = f"""---
sidebar_position: {len(apps) + 1}
---
"""
callout = f"""
:::info Complete Application
This is a complete, runnable application demonstrating Hindsight integration.
[**View source on GitHub →**]({app_url})
:::
"""
# Insert callout after first heading
first_heading_match = re.search(r"^(#\s+.+\n)", readme_content, re.MULTILINE)
if first_heading_match:
idx = readme_content.index(first_heading_match.group(0)) + len(
first_heading_match.group(0)
)
final_content = (
readme_content[:idx] + "\n" + callout + "\n" + readme_content[idx:]
)
else:
final_content = callout + "\n" + readme_content
output_path = apps_dir / f"{slug}.md"
output_path.write_text(frontmatter + final_content)
apps.append(
{
"slug": slug,
"title": title,
"id": f"cookbook/applications/{slug}",
}
)
return apps
def update_sidebars(recipes: list[dict], apps: list[dict], sidebars_file: Path):
"""Update sidebars.ts with new recipe and app entries."""
content = sidebars_file.read_text()
# Build recipe items
recipe_item_list = []
for r in recipes:
label = r["title"].replace("'", "\\'")
recipe_item_list.append(
f""" {{
type: 'doc',
id: '{r["id"]}',
label: '{label}',
}}"""
)
recipe_items = ",\n".join(recipe_item_list)
# Build app items
app_item_list = []
for a in apps:
label = a["title"].replace("'", "\\'")
app_item_list.append(
f""" {{
type: 'doc',
id: '{a["id"]}',
label: '{label}',
}}"""
)
app_items = ",\n".join(app_item_list)
new_cookbook_sidebar = f"""cookbookSidebar: [
{{
type: 'doc',
id: 'cookbook/index',
label: 'Overview',
}},
{{
type: 'category',
label: 'Recipes',
collapsible: false,
items: [
{recipe_items}
],
}},
{{
type: 'category',
label: 'Applications',
collapsible: false,
items: [
{app_items}
],
}},
]"""
# Replace existing cookbookSidebar - match the full sidebar array including nested structures
# We need to match balanced brackets
start = content.find("cookbookSidebar:")
if start == -1:
raise ValueError("cookbookSidebar not found in sidebars.ts")
# Find the opening bracket
bracket_start = content.find("[", start)
if bracket_start == -1:
raise ValueError("Could not find opening bracket for cookbookSidebar")
# Find matching closing bracket by counting brackets
depth = 0
end = bracket_start
for i, char in enumerate(content[bracket_start:], bracket_start):
if char == "[":
depth += 1
elif char == "]":
depth -= 1
if depth == 0:
end = i + 1
break
# Include trailing comma if present
if end < len(content) and content[end] == ",":
end += 1
content = content[:start] + new_cookbook_sidebar + "," + content[end:]
sidebars_file.write_text(content)
print("\nUpdated sidebars.ts")
def clean_description(desc: str) -> str:
"""Clean description for display in carousel cards."""
if not desc:
return ""
# Remove markdown formatting
desc = re.sub(r"\*\*([^*]+)\*\*", r"\1", desc) # Bold
desc = re.sub(r"\*([^*]+)\*", r"\1", desc) # Italic
desc = re.sub(r"`([^`]+)`", r"\1", desc) # Code
desc = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", desc) # Links
desc = re.sub(r"^[-*]\s+", "", desc) # List items
desc = re.sub(r"\s+", " ", desc).strip() # Normalize whitespace
# Truncate at sentence boundary or max length
if len(desc) > 120:
# Try to cut at sentence
period_idx = desc.rfind(".", 0, 120)
if period_idx > 60:
desc = desc[: period_idx + 1]
else:
desc = desc[:117] + "..."
return desc
def update_cookbook_index(
recipes: list[dict], apps: list[dict], docs_dir: Path
):
"""Update cookbook/index.mdx with recipe and app carousels."""
# Build recipe items for the carousel
recipe_items = []
for r in recipes:
title = r["title"].replace('"', '\\"')
recipe_items.append(
f' {{ title: "{title}", href: "/cookbook/recipes/{r["slug"]}" }}'
)
recipes_json = ",\n".join(recipe_items)
# Build app items for the carousel
app_items = []
for a in apps:
title = a["title"].replace('"', '\\"')
app_items.append(
f' {{ title: "{title}", href: "/cookbook/applications/{a["slug"]}" }}'
)
apps_json = ",\n".join(app_items)
content = f"""---
sidebar_position: 1
---
import RecipeCarousel from '@site/src/components/RecipeCarousel';
# Cookbook
Practical patterns, recipes, and complete applications for building with Hindsight.
<RecipeCarousel
title="Recipes"
items={{[
{recipes_json}
]}}
/>
<RecipeCarousel
title="Applications"
items={{[
{apps_json}
]}}
/>
"""
index_path = docs_dir / "index.mdx"
index_path.write_text(content)
# Remove old .md if exists
old_index = docs_dir / "index.md"
if old_index.exists():
old_index.unlink()
print("Updated cookbook/index.mdx")
def main():
"""Main entry point."""
print("Syncing hindsight-cookbook...\n")
docs_dir = get_docs_dir()
sidebars_file = get_sidebars_file()
recipes_dir = docs_dir / "recipes"
apps_dir = docs_dir / "applications"
# Create temp directory and clone
with tempfile.TemporaryDirectory() as tmpdir:
cookbook_dir = Path(tmpdir) / "cookbook"
print(f"Cloning {COOKBOOK_REPO}...")
subprocess.run(
["git", "clone", "--depth", "1", COOKBOOK_REPO, str(cookbook_dir)],
capture_output=True,
check=True,
)
print("Cloned successfully\n")
# Clean and recreate output directories
if recipes_dir.exists():
shutil.rmtree(recipes_dir)
if apps_dir.exists():
shutil.rmtree(apps_dir)
recipes_dir.mkdir(parents=True, exist_ok=True)
apps_dir.mkdir(parents=True, exist_ok=True)
# Process notebooks → Recipes
print("Processing notebooks...")
recipes = process_notebooks(cookbook_dir, recipes_dir)
# Process app directories → Applications
print("\nProcessing applications...")
apps = process_applications(cookbook_dir, apps_dir)
# Update sidebars.ts and index
if recipes or apps:
update_sidebars(recipes, apps, sidebars_file)
update_cookbook_index(recipes, apps, docs_dir)
print(f"\nDone! Generated {len(recipes)} recipes and {len(apps)} applications")
if __name__ == "__main__":
main()
+4 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "hindsight-dev"
version = "0.1.4"
version = "0.1.5"
description = "Development utilities for Hindsight"
requires-python = ">=3.11"
dependencies = [
@@ -24,3 +24,6 @@ hindsight-api = { workspace = true }
[project.scripts]
generate-openapi = "hindsight_dev.generate_openapi:generate_openapi_spec"
generate-changelog = "hindsight_dev.generate_changelog:main"
sync-cookbook = "hindsight_dev.sync_cookbook:main"
generate-llms-full = "hindsight_dev.generate_llms_full:main"
+32 -1
View File
@@ -4,4 +4,35 @@ sidebar_position: 1
# Changelog
Coming soon.
For full release details, see [GitHub Releases](https://github.com/vectorize-io/hindsight/releases).
## [0.1.5](https://github.com/vectorize-io/hindsight/releases/tag/v0.1.5)
**Features**
- Added LiteLLM integration so Hindsight can capture and manage memories from LiteLLM-based LLM calls. ([`dfccbf2`](https://github.com/vectorize-io/hindsight/commit/dfccbf2))
- Added an optional graph-based retriever (MPFP) to improve recall by leveraging relationships between memories. ([`7445cef`](https://github.com/vectorize-io/hindsight/commit/7445cef))
**Improvements**
- Switched the embedded Postgres layer to pg0-embedded for a smoother local/standalone experience. ([`94c2b85`](https://github.com/vectorize-io/hindsight/commit/94c2b85))
**Bug Fixes**
- Fixed repeated retries on 400 errors from the LLM, preventing unnecessary request loops and failures. ([`70983f5`](https://github.com/vectorize-io/hindsight/commit/70983f5))
- Fixed recall trace visualization in the control plane so search/recall debugging displays correctly. ([`922164e`](https://github.com/vectorize-io/hindsight/commit/922164e))
- Fixed the CLI installer to make installation more reliable. ([`158a6aa`](https://github.com/vectorize-io/hindsight/commit/158a6aa))
- Updated Next.js to patch security vulnerabilities (CVE-2025-55184, CVE-2025-55183). ([`f018cc5`](https://github.com/vectorize-io/hindsight/commit/f018cc5))
## [0.1.3](https://github.com/vectorize-io/hindsight/releases/tag/v0.1.3)
**Improvements**
- Improved CLI and UI branding/polish, including new banner/logo assets and updated interface styling. ([`fa554b8`](https://github.com/vectorize-io/hindsight/commit/fa554b8))
## [0.1.2](https://github.com/vectorize-io/hindsight/releases/tag/v0.1.2)
**Bug Fixes**
- Fixed the standalone Docker image so it builds/runs correctly. ([`1056a20`](https://github.com/vectorize-io/hindsight/commit/1056a20))
@@ -0,0 +1,315 @@
---
sidebar_position: 1
---
# OpenAI Agent + Hindsight Memory Integration
:::info Complete Application
This is a complete, runnable application demonstrating Hindsight integration.
[**View source on GitHub →**](https://github.com/vectorize-io/hindsight-cookbook/tree/main/openai-fitness-coach)
:::
A fitness coach example demonstrating how to use **OpenAI Agents** with **Hindsight as a memory backend**.
## What This Demonstrates
This example showcases:
- **OpenAI Assistants** handling conversation logic
- **Hindsight** providing sophisticated memory storage & retrieval
- **Function calling** to bridge them together
- **Streaming responses** for real-time interaction (enabled by default)
- **Bidirectional memory** - both user data AND coach observations stored
- **System-level post-processing** - automatic opinion storage for reliability
- **Temporal-semantic memory** queries via function tools
- **Enhanced preference learning** - coach learns and respects user likes/dislikes
- **Real-world integration pattern** for adding memory to AI agents
## Architecture
```
User: "I ran 5K today, don't like tempo runs"
|
OpenAI Assistant
|
Function Call: store_memory(workout + preference)
|
Hindsight API (stores as world/agent)
|
OpenAI Assistant: "What should I focus on?"
|
Function Call: retrieve_memories("workouts and preferences")
|
Hindsight API (returns workouts + preferences)
|
OpenAI Assistant (analyzes, gives advice)
|
Function Call: store_memory(advice as opinion)
|
Hindsight API (stores coach's observation)
|
Personalized Answer
```
## Key Difference from Standard Demo
| Component | Standard Demo | OpenAI Integration |
|-----------|---------------|-------------------|
| **Conversation** | Hindsight `/think` endpoint | OpenAI Assistant API |
| **Memory** | Hindsight (built-in) | Hindsight (via function calling) |
| **LLM** | Configured in Hindsight | OpenAI GPT-4 |
| **Opinion Formation** | Automatic in `/think` | Explicit via `store_memory(type="opinion")` |
| **Best For** | Hindsight-native apps | Integrating memory into existing OpenAI agents |
## Quick Start
### Prerequisites
1. **OpenAI API Key**
```bash
export OPENAI_API_KEY=your_openai_api_key
```
2. **Hindsight API running**
```bash
# Follow Hindsight setup instructions to start the API
# Default: http://localhost:8888
```
3. **Install dependencies**
```bash
pip install openai requests
```
### Run the Conversational Demo
```bash
cd openai-fitness-coach
export OPENAI_API_KEY=your_key_here
python demo_conversational.py
```
The demo showcases:
1. **Natural language workout logging** - Tell the coach what you did conversationally
2. **Preference learning** - Express likes/dislikes and watch the coach adapt
3. **Goal tracking** - Set goals, track progress, achieve milestones
4. **Bidirectional memory** - Both your activities AND coach's advice are stored
5. **Streaming responses** - See responses appear in real-time
6. **7 interactive phases** - From goal setting to achievement recognition
The demo uses a separate agent (`fitness-coach-demo`) to avoid mixing with real data.
## Usage
### Chat with Your Coach
**Interactive mode:**
```bash
python openai_coach.py
```
**Single question:**
```bash
python openai_coach.py "What did I do for training this week?"
```
## How It Works
### 1. Memory Tools (`memory_tools.py`)
Defines function tools that the OpenAI Agent can call:
```python
retrieve_memories(query, fact_types, top_k)
search_workouts(after_date, before_date, workout_type)
get_nutrition_summary(after_date, before_date)
get_user_goals()
get_coach_opinions(about)
```
Each function makes API calls to Hindsight to fetch relevant memories.
### 2. OpenAI Agent (`openai_coach.py`)
Creates an OpenAI Assistant with:
- Fitness coaching instructions
- Access to memory function tools
- Conversation management
When you ask a question:
1. User message is sent to OpenAI Assistant
2. Assistant decides which memory functions to call
3. Functions fetch data from Hindsight
4. Assistant generates response using retrieved context
### 3. Function Calling Flow
```python
# User asks: "What did I run this week?"
# OpenAI Assistant decides to call:
search_workouts(
after_date="2024-11-18",
workout_type="running"
)
# Function retrieves from Hindsight:
{
"results": [
{"text": "User completed 45-minute cardio workout: running..."},
{"text": "User completed 60-minute cardio workout: running..."}
]
}
# OpenAI Assistant generates response:
"This week you've done two runs: a 45-minute run on Monday
and a longer 60-minute run on Wednesday. Great consistency!"
```
## Example Questions
Try asking:
```bash
python openai_coach.py "What does my training look like this week?"
python openai_coach.py "Based on my workouts, should I rest today?"
python openai_coach.py "How is my nutrition supporting my goals?"
python openai_coach.py "What's my progress toward my goal?"
python openai_coach.py "Compare my training this month to last month"
```
The agent will automatically:
1. Identify what memories it needs
2. Call the appropriate function tools
3. Retrieve data from Hindsight
4. Generate a personalized response
## Memory Types Retrieved
The OpenAI Agent can retrieve different memory types from Hindsight:
- **World Facts** (`fact_type: "world"`): Workouts, meals, activities
- **Agent Facts** (`fact_type: "agent"`): Goals, intentions
- **Opinions** (`fact_type: "opinion"`): Coach's observations about patterns
## Customization
### Add New Function Tools
Edit `memory_tools.py` to add new capabilities:
```python
def get_weekly_summary(week_offset: int = 0):
"""Get a summary of a specific week."""
# Implementation
pass
# Add to MEMORY_TOOLS list
MEMORY_TOOLS.append({
"type": "function",
"function": {
"name": "get_weekly_summary",
"description": "Get training summary for a specific week",
# ... parameters
}
})
# Add to FUNCTION_MAP
FUNCTION_MAP["get_weekly_summary"] = get_weekly_summary
```
### Modify Assistant Instructions
Edit `openai_coach.py` to change the coach's personality or behavior:
```python
assistant = client.beta.assistants.create(
name="Your Custom Coach",
instructions="Your custom instructions here...",
model="gpt-4o-mini",
tools=MEMORY_TOOLS
)
```
## Use Cases
This pattern works for any application that needs memory:
1. **Customer Support Agents** - Remember past conversations and issues
2. **Personal Assistants** - Remember preferences, schedules, past decisions
3. **Educational Tutors** - Track learning progress over time
4. **Health Coaches** - Monitor habits, progress, goals (like this example)
5. **Sales Assistants** - Remember customer interactions and preferences
## Integration Pattern
**To add Hindsight memory to your own OpenAI Agent:**
1. Define function tools that call Hindsight API
2. Register them with your OpenAI Assistant
3. Implement function handlers to execute Hindsight queries
4. Let OpenAI Assistant decide when to retrieve memories
The key benefit: **Separation of concerns**
- OpenAI = Conversation logic
- Hindsight = Memory storage, retrieval, temporal queries, entity linking
## When to Use This vs. Standard Hindsight
**Use OpenAI + Hindsight (this example) when:**
- You want OpenAI's conversation capabilities
- You're already using OpenAI Agents
- You want explicit control over when to retrieve memories
- You want to combine Hindsight with other OpenAI features
**Use Hindsight directly when:**
- You want a complete memory-first solution
- You want automatic memory retrieval and opinion formation
- You want to use different LLM providers (not just OpenAI)
- You want the `/think` endpoint's integrated approach
## Learning Points
After running this demo, you'll understand:
1. How to add sophisticated memory to any OpenAI Agent
2. How function calling bridges LLMs and memory systems
3. How temporal-semantic queries work via function tools
4. Real-world pattern for LLM + memory integration
## Core Files
- `demo_conversational.py` - Conversational demo showcasing preference learning and goal tracking
- `openai_coach.py` - OpenAI Assistant wrapper with streaming and memory integration
- `memory_tools.py` - Function calling tools that bridge to Hindsight API
- `.openai_assistant_id` - Saved assistant ID (auto-generated, gitignored)
## Common Issues
**"OPENAI_API_KEY not set"**
```bash
export OPENAI_API_KEY=your_api_key_here
```
**"Agent not found"**
- Make sure the Hindsight fitness-coach agent exists
**"Connection refused"**
- Make sure Hindsight API is running on localhost:8888
## Next Steps
1. Run the demo to see it in action
2. Try chatting with the coach: `python openai_coach.py`
3. Log your own workouts and meals
4. Experiment with different questions
5. Add custom function tools for your use case
---
**Built with:**
- OpenAI Assistants API
- Hindsight (temporal-semantic memory)
- Function calling for integration
-21
View File
@@ -1,21 +0,0 @@
---
sidebar_position: 1
---
# Cookbook
Practical patterns and recipes for building with Hindsight.
## Use Cases
### [Per-User Memory](/cookbook/per-user-memory)
The simplest pattern: give your agent persistent memory for each user. The agent remembers past conversations, preferences, and context across sessions.
**Use when:** Building chatbots, personal assistants, or any 1:1 user-to-agent interaction.
### [Support Agent with Shared Knowledge](/cookbook/support-agent-with-shared-knowledge)
Build a support agent that combines per-user memory with shared product documentation. Users get personalized support while you index docs only once.
**Use when:** Building multi-tenant support agents, RAG + memory applications, or any scenario needing user isolation with shared reference data.
+27
View File
@@ -0,0 +1,27 @@
---
sidebar_position: 1
---
import RecipeCarousel from '@site/src/components/RecipeCarousel';
# Cookbook
Practical patterns, recipes, and complete applications for building with Hindsight.
<RecipeCarousel
title="Recipes"
items={[
{ title: "Hindsight Quickstart", href: "/cookbook/recipes/quickstart" },
{ title: "Per-User Memory", href: "/cookbook/recipes/per-user-memory" },
{ title: "Support Agent with Shared Knowledge", href: "/cookbook/recipes/support-agent-shared-knowledge" },
{ title: "Hindsight Memory Demo with LiteLLM", href: "/cookbook/recipes/litellm-memory-demo" },
{ title: "Hindsight Tool Learning Demo", href: "/cookbook/recipes/tool-learning-demo" }
]}
/>
<RecipeCarousel
title="Applications"
items={[
{ title: "OpenAI Agent + Hindsight Memory Integration", href: "/cookbook/applications/openai-fitness-coach" }
]}
/>
@@ -0,0 +1,187 @@
---
sidebar_position: 4
---
# Hindsight Memory Demo with LiteLLM
:::tip Run this notebook
This recipe is available as an interactive Jupyter notebook.
[**Open in GitHub →**](https://github.com/vectorize-io/hindsight-cookbook/blob/main/notebooks/04-litellm-memory-demo.ipynb)
:::
This notebook demonstrates how to add persistent memory to any LLM app using the `hindsight-litellm` package. Memory storage and injection happen automatically via LiteLLM callbacks - no manual memory management needed!
**Key features demonstrated:**
1. `configure()` + `enable()` - Set up automatic memory integration
2. Automatic storage - Conversations are stored after each LLM call
3. Automatic injection - Relevant memories are injected into prompts
The `hindsight-litellm` package hooks into LiteLLM's callback system to:
- Store each conversation after successful LLM responses
- Inject relevant memories into the system prompt before LLM calls
## Prerequisites
Make sure you have Hindsight running:
```bash
export OPENAI_API_KEY=your-key
docker run --rm -it --pull always -p 8888:8888 -p 9999:9999 \
-e HINDSIGHT_API_LLM_API_KEY=$OPENAI_API_KEY \
-e HINDSIGHT_API_LLM_MODEL=o3-mini \
-v $HOME/.hindsight-docker:/home/hindsight/.pg0 \
ghcr.io/vectorize-io/hindsight:latest
```
- API: http://localhost:8888
- UI: http://localhost:9999
## Installation
```python
!pip install hindsight-litellm litellm nest_asyncio python-dotenv -U -q
```
## Setup
```python
import os
import uuid
import time
import logging
import nest_asyncio
from dotenv import load_dotenv
# Apply nest_asyncio for Jupyter compatibility
nest_asyncio.apply()
# Load environment variables
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("LiteLLM").setLevel(logging.WARNING)
logging.getLogger("LiteLLM Router").setLevel(logging.WARNING)
logging.getLogger("LiteLLM Proxy").setLevel(logging.WARNING)
# Import hindsight_litellm
import hindsight_litellm
# Configuration
HINDSIGHT_API_URL = os.getenv("HINDSIGHT_API_URL", "http://localhost:8888")
# Check for API key
if not os.getenv("OPENAI_API_KEY"):
print("Warning: OPENAI_API_KEY not set")
```
## Configure and Enable Automatic Memory
This is all you need! After this, all LiteLLM calls will automatically:
- Have relevant memories injected into the prompt
- Store conversations to Hindsight after the response
```python
# Generate a unique bank_id for this demo session
bank_id = f"demo-{uuid.uuid4().hex[:8]}"
print(f"Using bank_id: {bank_id}")
# Configure and enable hindsight
hindsight_litellm.configure(
hindsight_api_url=HINDSIGHT_API_URL,
bank_id=bank_id,
store_conversations=True, # Automatically store conversations
inject_memories=True, # Automatically inject relevant memories
verbose=True, # Enable logging to debug memory operations
)
hindsight_litellm.enable()
print("Hindsight memory integration enabled!")
```
## Conversation 1: User Introduces Themselves
In this first conversation, the user shares some information about themselves. This will be automatically stored to Hindsight memory.
```python
user_message_1 = "Hi! I'm Alex and I work at Google as a software engineer. I love Python and machine learning."
print(f"User: {user_message_1}\n")
# Use hindsight_litellm.completion() directly
response_1 = hindsight_litellm.completion(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message_1}
],
)
assistant_response_1 = response_1.choices[0].message.content
print(f"Assistant: {assistant_response_1}")
print("\n(Conversation automatically stored to Hindsight)")
```
## Wait for Memory Processing
Hindsight needs a few seconds to process and extract facts from the conversation.
```python
print("Waiting 12 seconds for memory processing...")
time.sleep(12)
print("Done!")
```
## Conversation 2: Test Memory-Augmented Response
Now we start a fresh conversation and ask what the assistant remembers. The memories from the previous conversation will be automatically injected into the prompt!
```python
user_message_2 = "What do you know about me? What programming language should I use for my next project?"
print(f"User: {user_message_2}\n")
# Memories are automatically injected before this call!
response_2 = hindsight_litellm.completion(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message_2}
],
)
print(f"Assistant: {response_2.choices[0].message.content}")
```
## Summary
The assistant should have remembered that Alex:
- Works at Google as a software engineer
- Loves Python and machine learning
And it should have recommended Python based on that knowledge!
```python
print(f"Memories stored in bank: {bank_id}")
print(f"View in UI: http://localhost:9999/banks/{bank_id}")
```
## Cleanup
```python
hindsight_litellm.cleanup()
# Optional: delete the bank
import requests
response = requests.delete(f"{HINDSIGHT_API_URL}/v1/default/banks/{bank_id}")
print(f"Deleted bank: {response.json()}")
```
@@ -1,9 +1,16 @@
---
sidebar_position: 1
sidebar_position: 2
---
# Per-User Memory
:::tip Run this notebook
This recipe is available as an interactive Jupyter notebook.
[**Open in GitHub →**](https://github.com/vectorize-io/hindsight-cookbook/blob/main/notebooks/02-per-user-memory.ipynb)
:::
The simplest pattern: give your agent persistent memory for each user. The agent remembers past conversations, user preferences, and context across sessions.
## The Problem
@@ -31,28 +38,54 @@ Session 2: "What's my preferred language?" → Agent doesn't know
Each user gets their own memory bank. Complete isolation, simple mental model.
## Implementation
### 1. Create a Bank When User Signs Up
```python
from hindsight import HindsightClient
!pip install hindsight-client nest_asyncio openai python-dotenv -U
```
client = HindsightClient()
## 1. Create a Bank When User Signs Up
```python
# Jupyter notebooks already run an asyncio event loop. The hindsight client
# uses loop.run_until_complete() internally, but Python doesn't allow nested
# event loops by default. nest_asyncio patches this to allow nesting.
import nest_asyncio
nest_asyncio.apply()
import os
from dotenv import load_dotenv
from openai import OpenAI as OpenAIClient
# Load environment variables from .env file
# Copy .env.example to .env and fill in your values
load_dotenv()
# Configuration (override with env vars if set)
HINDSIGHT_API_URL = os.getenv("HINDSIGHT_API_URL", "http://localhost:8888")
HINDSIGHT_UI_URL = os.getenv("HINDSIGHT_UI_URL", "http://localhost:9999")
from hindsight_client import Hindsight
client = Hindsight(base_url=HINDSIGHT_API_URL)
llm = OpenAIClient() # Uses OPENAI_API_KEY from .env
def on_user_signup(user_id: str):
client.create_bank(
bank_id=f"user-{user_id}",
name=f"Memory for {user_id}"
)
print(f"View bank: {HINDSIGHT_UI_URL}/banks/user-{user_id}?view=documents")
```
### 2. Manage Conversation Sessions
## 2. Manage Conversation Sessions
Use `document_id` to group messages belonging to the same conversation. When you retain with the same `document_id`, Hindsight replaces the previous version (upsert behavior), keeping the memory up-to-date as the conversation evolves.
```python
import uuid
import json
class ConversationSession:
def __init__(self, user_id: str):
@@ -63,74 +96,101 @@ class ConversationSession:
def add_message(self, role: str, content: str):
self.messages.append({"role": role, "content": content})
async def save(self, client: HindsightClient):
def save(self, client: Hindsight):
"""Save the entire conversation. Replaces previous version if session_id exists."""
await client.retain(
# Convert messages to string format for retain
content = "\n".join([f"{m['role']}: {m['content']}" for m in self.messages])
client.retain(
bank_id=f"user-{self.user_id}",
content=self.messages,
content=content,
document_id=self.session_id # Same ID = upsert (replace old version)
)
```
### 3. Recall Context Before Responding
## 3. Recall Context Before Responding
```python
async def get_context(user_id: str, query: str):
result = await client.recall(
def get_context(user_id: str, query: str):
result = client.recall(
bank_id=f"user-{user_id}",
query=query
)
return result.results
```
### 4. Complete Agent Loop
## 4. Complete Agent Loop
```python
async def handle_message(session: ConversationSession, user_message: str):
def format_results(results):
"""Format recall results for the prompt."""
if not results:
return "No relevant memories found."
return "\n".join([f"- {r.text}" for r in results])
def format_messages(messages):
"""Format conversation messages for the prompt."""
return "\n".join([f"{m['role']}: {m['content']}" for m in messages])
def handle_message(session: ConversationSession, user_message: str):
# 1. Add user message to session
session.add_message("user", user_message)
# 2. Recall relevant context from past conversations
context = await client.recall(
context = client.recall(
bank_id=f"user-{session.user_id}",
query=user_message
)
# 3. Build prompt with memory
prompt = f"""You are a helpful assistant with memory of past conversations.
# 3. Build system prompt with memory
system_prompt = f"""You are a helpful assistant with memory of past conversations.
## What you remember about this user
{format_results(context.results)}
## Current conversation
{format_messages(session.messages)}
"""
Respond helpfully and reference relevant memories when appropriate."""
# 4. Generate response
response = await llm.complete(prompt)
# 4. Generate response using OpenAI
response = llm.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_prompt},
*[{"role": m["role"], "content": m["content"]} for m in session.messages]
]
)
assistant_response = response.choices[0].message.content
# 5. Add assistant response to session
session.add_message("assistant", response)
session.add_message("assistant", assistant_response)
# 6. Save the updated conversation (upserts based on session_id)
await session.save(client)
session.save(client)
return response
print(f"User: {user_message}")
print(f"Assistant: {assistant_response}\n")
return assistant_response
```
### 5. Starting a New Conversation
## 5. Starting a New Conversation
```python
# Create the user's bank
on_user_signup("alice")
# Each new conversation gets a new session with a unique ID
session = ConversationSession(user_id="alice")
# Multiple exchanges in the same conversation
await handle_message(session, "Hi! I'm working on a Python project")
await handle_message(session, "Can you help me with async/await?")
handle_message(session, "Hi! I'm working on a Python project")
handle_message(session, "Can you help me with async/await?")
# Start a new conversation later (new session_id)
new_session = ConversationSession(user_id="alice")
await handle_message(new_session, "Different topic today...")
# View the stored conversation in the UI.
# Each message updates the same document (via document_id), so you'll see
# the full conversation history in a single document rather than separate entries.
print(f"\nView documents: {HINDSIGHT_UI_URL}/banks/user-alice?view=documents")
```
## How Document ID Works
@@ -171,4 +231,17 @@ You don't need to manually extract or structure this - just retain the conversat
**Consider adding shared knowledge if:**
- You have product docs or FAQs to reference
- Multiple users need access to the same information
- See [Support Agent with Shared Knowledge](./support-agent-with-shared-knowledge)
- See the Support Agent with Shared Knowledge notebook
## Cleanup
Delete the banks created during this notebook:
```python
import requests
# Delete the user-alice bank
response = requests.delete(f"{HINDSIGHT_API_URL}/v1/default/banks/user-alice")
print(f"Deleted user-alice: {response.json()}")
```
@@ -0,0 +1,162 @@
---
sidebar_position: 1
---
# Hindsight Quickstart
:::tip Run this notebook
This recipe is available as an interactive Jupyter notebook.
[**Open in GitHub →**](https://github.com/vectorize-io/hindsight-cookbook/blob/main/notebooks/01-quickstart.ipynb)
:::
This notebook covers the basics of using Hindsight:
- **Retain**: Store information in memory
- **Recall**: Retrieve memories matching a query
- **Reflect**: Generate insights from memories
## Prerequisites
Make sure you have Hindsight running. The easiest way is via Docker:
```bash
export OPENAI_API_KEY=your-key
docker run --rm -it --pull always -p 8888:8888 -p 9999:9999 \
-e HINDSIGHT_API_LLM_API_KEY=$OPENAI_API_KEY \
-e HINDSIGHT_API_LLM_MODEL=o3-mini \
-v $HOME/.hindsight-docker:/home/hindsight/.pg0 \
ghcr.io/vectorize-io/hindsight:latest
```
- API: http://localhost:8888
- UI: http://localhost:9999
## Installation
Install the Hindsight Python client:
```python
!pip install hindsight-client nest_asyncio python-dotenv -U
```
## Connect to Hindsight
```python
# Jupyter notebooks already run an asyncio event loop. The hindsight client
# uses loop.run_until_complete() internally, but Python doesn't allow nested
# event loops by default. nest_asyncio patches this to allow nesting.
import nest_asyncio
nest_asyncio.apply()
import os
from dotenv import load_dotenv
# Load environment variables from .env file
# Copy .env.example to .env and fill in your values
load_dotenv()
# Configuration (override with env vars if set)
HINDSIGHT_API_URL = os.getenv("HINDSIGHT_API_URL", "http://localhost:8888")
HINDSIGHT_UI_URL = os.getenv("HINDSIGHT_UI_URL", "http://localhost:9999")
from hindsight_client import Hindsight
client = Hindsight(base_url=HINDSIGHT_API_URL)
```
## Retain: Store Information
The `retain` operation is used to push new memories into Hindsight. It tells Hindsight to _retain_ the information you pass in.
Behind the scenes, the retain operation uses an LLM to extract key facts, temporal data, entities, and relationships.
```python
# Simple retain
client.retain(
bank_id="my-bank",
content="Alice works at Google as a software engineer"
)
# View the stored document in the UI:
print(f"View documents: {HINDSIGHT_UI_URL}/banks/my-bank?view=documents")
```
```python
# Retain with context and timestamp
client.retain(
bank_id="my-bank",
content="Alice got promoted to senior engineer",
context="career update",
timestamp="2025-06-15T10:00:00Z"
)
```
## Recall: Retrieve Memories
The `recall` operation retrieves memories matching a query. It performs 4 retrieval strategies in parallel:
- **Semantic**: Vector similarity
- **Keyword**: BM25 exact matching
- **Graph**: Entity/temporal/causal links
- **Temporal**: Time range filtering
```python
# Simple recall
results = client.recall(bank_id="my-bank", query="What does Alice do?")
print("Memories:")
for r in results.results:
print(f" - {r.text}")
```
```python
# Temporal recall
results = client.recall(bank_id="my-bank", query="What happened in June?")
print("Memories:")
for r in results.results:
print(f" - {r.text}")
```
## Reflect: Generate Insights
The `reflect` operation performs a more thorough analysis of existing memories. This allows the agent to form new connections between memories which are then persisted as opinions and/or observations.
Example use cases:
- An AI Project Manager reflecting on what risks need to be mitigated
- A Sales Agent reflecting on why certain outreach messages have gotten responses
- A Support Agent reflecting on opportunities where customers have unanswered questions
```python
response = client.reflect(bank_id="my-bank", query="What should I know about Alice?")
print(response)
```
## Memory Types
Hindsight organizes memory into four networks to mimic human memory:
- **World**: Facts about the world ("The stove gets hot")
- **Experiences**: Agent's own experiences ("I touched the stove and it really hurt")
- **Opinion**: Beliefs with confidence scores ("I shouldn't touch the stove again" - .99 confidence)
- **Observation**: Complex mental models derived by reflecting on facts and experiences
## Cleanup
Delete the bank created during this notebook:
```python
import requests
response = requests.delete(f"{HINDSIGHT_API_URL}/v1/default/banks/my-bank")
print(f"Deleted my-bank: {response.json()}")
```
@@ -4,6 +4,13 @@ sidebar_position: 3
# Support Agent with Shared Knowledge
:::tip Run this notebook
This recipe is available as an interactive Jupyter notebook.
[**Open in GitHub →**](https://github.com/vectorize-io/hindsight-cookbook/blob/main/notebooks/03-support-agent-shared-knowledge.ipynb)
:::
This pattern shows how to build a support agent that combines **per-user memory** with **shared product knowledge** (RAG), giving users personalized support while leveraging a single source of truth for documentation.
## The Problem
@@ -17,8 +24,6 @@ A naive approach would index product docs into each user's memory bank, but this
## The Solution: Multi-Bank Architecture
Create separate memory banks for different concerns:
```
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ User A Bank │ │ User B Bank │ │ Shared Docs │
@@ -40,16 +45,39 @@ Create separate memory banks for different concerns:
- User memory is 100% isolated
- Simple mental model, no complex filtering
## Implementation
### 1. Set Up Memory Banks
```python
!pip install hindsight-client nest_asyncio openai python-dotenv -U
```
## 1. Set Up Memory Banks
Create three types of banks:
```python
from hindsight import HindsightClient
client = HindsightClient()
```python
# Jupyter notebooks already run an asyncio event loop. The hindsight client
# uses loop.run_until_complete() internally, but Python doesn't allow nested
# event loops by default. nest_asyncio patches this to allow nesting.
import nest_asyncio
nest_asyncio.apply()
import os
from dotenv import load_dotenv
from openai import OpenAI as OpenAIClient
# Load environment variables from .env file
# Copy .env.example to .env and fill in your values
load_dotenv()
# Configuration (override with env vars if set)
HINDSIGHT_API_URL = os.getenv("HINDSIGHT_API_URL", "http://localhost:8888")
HINDSIGHT_UI_URL = os.getenv("HINDSIGHT_UI_URL", "http://localhost:9999")
from hindsight_client import Hindsight
client = Hindsight(base_url=HINDSIGHT_API_URL)
llm = OpenAIClient() # Uses OPENAI_API_KEY from .env
# Shared knowledge bank (created once)
shared_bank = client.create_bank(
@@ -65,55 +93,57 @@ def create_user_bank(user_id: str):
)
```
### 2. Index Product Documentation
## 2. Index Product Documentation
Index your product docs into the shared bank (do this once, or on doc updates):
```python
# Index product documentation
# Index product documentation - retain each doc separately
client.retain(
bank_id="product-docs",
content=[
{
"role": "document",
"content": "# Pricing Tiers\n\nBasic: $10/mo...",
"metadata": {"source": "pricing.md"}
},
{
"role": "document",
"content": "# Getting Started\n\nTo set up...",
"metadata": {"source": "quickstart.md"}
}
]
content="# Pricing Tiers\n\nBasic: $10/mo, Pro: $25/mo, Enterprise: Contact us"
)
client.retain(
bank_id="product-docs",
content="# Getting Started\n\nTo set up your account, visit the dashboard and click 'New Project'"
)
# View the stored documents in the UI:
print(f"View documents: {HINDSIGHT_UI_URL}/banks/product-docs?view=documents")
```
### 3. Store User Conversations
## 3. Store User Conversations
After each support interaction, retain it in the user's bank:
```python
def save_conversation(user_id: str, messages: list):
# Convert messages to string format
content = "\n".join([f"{m['role']}: {m['content']}" for m in messages])
client.retain(
bank_id=f"user-{user_id}",
content=messages # [{"role": "user", "content": "..."}, ...]
content=content
)
```
### 4. Query Multiple Banks at Support Time
## 4. Query Multiple Banks at Support Time
When handling a user query, retrieve context from both banks:
```python
async def get_support_context(user_id: str, query: str):
def get_support_context(user_id: str, query: str):
# Get user's personal context
user_context = await client.recall(
user_context = client.recall(
bank_id=f"user-{user_id}",
query=query
)
# Get relevant product documentation
docs_context = await client.recall(
docs_context = client.recall(
bank_id="product-docs",
query=query
)
@@ -124,11 +154,18 @@ async def get_support_context(user_id: str, query: str):
}
```
### 5. Build the Agent Prompt
## 5. Build the Agent Prompt
Combine both contexts in your agent's prompt:
```python
def format_results(results):
"""Format recall results for the prompt."""
if not results:
return "No relevant information found."
return "\n".join([f"- {r.text}" for r in results])
def build_prompt(query: str, context: dict) -> str:
return f"""You are a helpful support agent.
@@ -167,6 +204,7 @@ When the agent discovers a solution that's not in the docs, you can optionally p
all three banks
```
```python
# Optional: Create a curated learnings bank
learnings_bank = client.create_bank(
@@ -178,71 +216,77 @@ learnings_bank = client.create_bank(
def promote_learning(insight: str):
client.retain(
bank_id="support-learnings",
content=[{
"role": "system",
"content": insight,
"metadata": {"type": "verified_solution"}
}]
content=insight
)
```
Then query three banks: user + docs + learnings.
## Complete Example
```python
from hindsight import HindsightClient
def format_results(results):
if not results:
return "No relevant information found."
return "\n".join([f"- {r.text}" for r in results])
client = HindsightClient()
async def handle_support_request(user_id: str, query: str):
def handle_support_request(user_id: str, query: str):
# 1. Recall from user's memory
user_recall = await client.recall(
user_recall = client.recall(
bank_id=f"user-{user_id}",
query=query
)
# 2. Recall from shared docs
docs_recall = await client.recall(
docs_recall = client.recall(
bank_id="product-docs",
query=query
)
# 3. Recall from learnings (optional)
learnings_recall = await client.recall(
learnings_recall = client.recall(
bank_id="support-learnings",
query=query
)
# 4. Build context for LLM
context = f"""
User History:
# 4. Build system prompt with context
system_prompt = f"""You are a helpful support agent. Use the context below to answer the user's question.
## User's History
{format_results(user_recall.results)}
Product Docs:
## Product Documentation
{format_results(docs_recall.results)}
Known Solutions:
## Known Solutions
{format_results(learnings_recall.results)}
"""
# 5. Generate response with your LLM
response = await llm.complete(
system="You are a support agent...",
context=context,
query=query
)
Provide helpful, accurate responses based on the documentation. Reference the user's history when relevant."""
# 6. Save the conversation to user's memory
await client.retain(
bank_id=f"user-{user_id}",
content=[
{"role": "user", "content": query},
{"role": "assistant", "content": response}
# 5. Generate response using OpenAI
response = llm.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": query}
]
)
assistant_response = response.choices[0].message.content
return response
# 6. Save the conversation to user's memory
conversation = f"user: {query}\nassistant: {assistant_response}"
client.retain(
bank_id=f"user-{user_id}",
content=conversation
)
return assistant_response
# Test the function
create_user_bank("bob")
print("User: How do I get started?")
result = handle_support_request("bob", "How do I get started?")
print(f"Assistant: {result}")
print(f"\nView user memory: {HINDSIGHT_UI_URL}/banks/user-bob?view=documents")
```
## When to Use This Pattern
@@ -256,3 +300,16 @@ Known Solutions:
- You need cross-user learning (users benefiting from other users' solutions)
- Entity relationships must span across users and docs
## Cleanup
Delete the banks created during this notebook:
```python
import requests
# Delete all banks created in this notebook
for bank_id in ["product-docs", "support-learnings", "user-bob"]:
response = requests.delete(f"{HINDSIGHT_API_URL}/v1/default/banks/{bank_id}")
print(f"Deleted {bank_id}: {response.json()}")
```
@@ -0,0 +1,372 @@
---
sidebar_position: 5
---
# Hindsight Tool Learning Demo
:::tip Run this notebook
This recipe is available as an interactive Jupyter notebook.
[**Open in GitHub →**](https://github.com/vectorize-io/hindsight-cookbook/blob/main/notebooks/05-tool-learning-demo.ipynb)
:::
This notebook demonstrates how Hindsight helps an LLM learn which tool to use when tool names are ambiguous. Without memory, the LLM might randomly select between similarly-named tools. With Hindsight, it learns from past interactions and consistently makes the correct choice.
## The Scenario
We have a task routing system with two tools:
- `route_to_channel_alpha` - Routes to processing channel Alpha
- `route_to_channel_omega` - Routes to processing channel Omega
The tool names and descriptions are **intentionally vague**. In reality:
- Channel Alpha handles **FINANCIAL/PAYMENT** tasks (refunds, billing, etc.)
- Channel Omega handles **TECHNICAL/SUPPORT** tasks (bugs, features, etc.)
**Without Hindsight:** The LLM guesses randomly based on vague descriptions
**With Hindsight:** The LLM learns from feedback which channel handles what
## Prerequisites
Make sure you have Hindsight running:
```bash
export OPENAI_API_KEY=your-key
docker run --rm -it --pull always -p 8888:8888 -p 9999:9999 \
-e HINDSIGHT_API_LLM_API_KEY=$OPENAI_API_KEY \
-e HINDSIGHT_API_LLM_MODEL=o3-mini \
-v $HOME/.hindsight-docker:/home/hindsight/.pg0 \
ghcr.io/vectorize-io/hindsight:latest
```
## Installation
```python
!pip install hindsight-litellm hindsight-client litellm nest_asyncio python-dotenv -U -q
```
## Setup
```python
import os
import json
import uuid
import time
import logging
import nest_asyncio
from typing import Optional
from dotenv import load_dotenv
nest_asyncio.apply()
load_dotenv()
logging.basicConfig(level=logging.INFO)
logging.getLogger("LiteLLM").setLevel(logging.WARNING)
logging.getLogger("LiteLLM Router").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
import litellm
import hindsight_litellm
from hindsight_client import Hindsight
HINDSIGHT_API_URL = os.getenv("HINDSIGHT_API_URL", "http://localhost:8888")
if not os.getenv("OPENAI_API_KEY"):
print("Warning: OPENAI_API_KEY not set")
```
## Define Tools
These tool definitions are **intentionally ambiguous** - the descriptions don't reveal which channel handles what type of request.
```python
TOOLS = [
{
"type": "function",
"function": {
"name": "route_to_channel_alpha",
"description": "Routes the customer request to processing channel Alpha. Use this channel for appropriate request types.",
"parameters": {
"type": "object",
"properties": {
"request_summary": {
"type": "string",
"description": "A brief summary of the customer's request"
},
"priority": {
"type": "string",
"enum": ["low", "medium", "high"],
"description": "Priority level of the request"
}
},
"required": ["request_summary"]
}
}
},
{
"type": "function",
"function": {
"name": "route_to_channel_omega",
"description": "Routes the customer request to processing channel Omega. Use this channel for appropriate request types.",
"parameters": {
"type": "object",
"properties": {
"request_summary": {
"type": "string",
"description": "A brief summary of the customer's request"
},
"priority": {
"type": "string",
"enum": ["low", "medium", "high"],
"description": "Priority level of the request"
}
},
"required": ["request_summary"]
}
}
}
]
```
## Test Scenarios
A mix of financial and technical requests to test routing accuracy.
```python
TEST_SCENARIOS = [
{
"type": "financial",
"request": "I was charged twice for my subscription last month. I need a refund for the duplicate charge.",
"correct_tool": "route_to_channel_alpha"
},
{
"type": "technical",
"request": "The app keeps crashing when I try to upload a file larger than 10MB. This bug is blocking my work.",
"correct_tool": "route_to_channel_omega"
},
{
"type": "financial",
"request": "My invoice shows an incorrect amount. The billing department needs to fix this.",
"correct_tool": "route_to_channel_alpha"
},
{
"type": "technical",
"request": "I'd like to request a new feature: the ability to export reports as PDF.",
"correct_tool": "route_to_channel_omega"
},
{
"type": "financial",
"request": "I need to update my payment method and understand why my last payment failed.",
"correct_tool": "route_to_channel_alpha"
},
]
```
## Helper Functions
```python
SYSTEM_PROMPT = """You are a customer service routing agent. Your job is to route customer requests to the appropriate processing channel.
You have access to two routing channels:
- route_to_channel_alpha: Routes to channel Alpha
- route_to_channel_omega: Routes to channel Omega
Analyze the customer's request and route it to the most appropriate channel. You must call one of the routing functions to process the request.
Important: Base your routing decision on what you know about each channel's purpose. If you have learned from previous interactions which channel handles specific types of requests, use that knowledge."""
def make_routing_request(user_request: str, use_hindsight: bool, bank_id: Optional[str] = None):
"""Make a routing request and return the tool called."""
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"Customer Request: {user_request}"}
]
if use_hindsight and bank_id:
response = hindsight_litellm.completion(
model="gpt-4o-mini",
messages=messages,
tools=TOOLS,
tool_choice="required",
temperature=0.0,
)
else:
response = litellm.completion(
model="gpt-4o-mini",
messages=messages,
tools=TOOLS,
tool_choice="required",
temperature=0.7,
)
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
return tool_call.function.name
return None
def store_feedback(bank_id: str, request: str, correct_tool: str, request_type: str):
"""Store feedback about which tool was correct for a request type."""
client = Hindsight(base_url=HINDSIGHT_API_URL, timeout=60.0)
feedback_content = f"""ROUTING FEEDBACK:
Request type: {request_type}
Customer request: "{request}"
Correct routing: {correct_tool}
LEARNED RULE: {request_type.upper()} requests (like refunds, billing, payments, charges, invoices) should ALWAYS be routed to {correct_tool}.
This is important institutional knowledge for routing decisions."""
client.retain(
bank_id=bank_id,
content=feedback_content,
context=f"routing:feedback:{request_type}",
metadata={"request_type": request_type, "correct_tool": correct_tool}
)
```
## Phase 1: Without Hindsight (No Memory)
The LLM has no prior knowledge about which channel handles what. With ambiguous tool descriptions, it may route incorrectly.
```python
print("=" * 60)
print("PHASE 1: WITHOUT HINDSIGHT (No Memory)")
print("=" * 60)
phase1_results = []
for i, scenario in enumerate(TEST_SCENARIOS[:3], 1):
print(f"\n--- Test {i}: {scenario['type'].upper()} Request ---")
print(f"Request: \"{scenario['request'][:60]}...\"")
tool_name = make_routing_request(scenario['request'], use_hindsight=False)
is_correct = tool_name == scenario['correct_tool']
phase1_results.append(is_correct)
print(f"LLM chose: {tool_name}")
print(f"Correct tool: {scenario['correct_tool']}")
print(f"Result: {'✓ CORRECT' if is_correct else '✗ INCORRECT'}")
phase1_accuracy = sum(phase1_results) / len(phase1_results) * 100
print(f"\n>>> Phase 1 Accuracy: {phase1_accuracy:.0f}% ({sum(phase1_results)}/{len(phase1_results)})")
```
## Phase 2: Teaching Phase
Now we provide feedback about correct routing to build memory. This simulates a human supervisor correcting the AI's routing decisions.
```python
bank_id = f"tool-learning-{uuid.uuid4().hex[:8]}"
print(f"Using bank_id: {bank_id}")
# Configure and enable Hindsight
hindsight_litellm.configure(
hindsight_api_url=HINDSIGHT_API_URL,
bank_id=bank_id,
store_conversations=True,
inject_memories=True,
max_memories=10,
recall_budget="high",
verbose=False,
)
hindsight_litellm.enable()
print("\nStoring routing feedback...")
feedback_examples = [
("I need a refund for an incorrect charge on my account.", "route_to_channel_alpha", "financial"),
("There's a bug in the system causing data loss.", "route_to_channel_omega", "technical"),
("My billing statement has errors that need correction.", "route_to_channel_alpha", "financial"),
("I want to request a new feature for the dashboard.", "route_to_channel_omega", "technical"),
]
for request, correct_tool, req_type in feedback_examples:
print(f" Storing: {req_type.upper()}{correct_tool}")
store_feedback(bank_id, request, correct_tool, req_type)
print("\nWaiting 15 seconds for Hindsight to process memories...")
time.sleep(15)
print("Done!")
```
## Phase 3: With Hindsight (Memory-Augmented)
The LLM now has access to learned routing knowledge via Hindsight. It should route requests correctly based on past feedback.
```python
print("=" * 60)
print("PHASE 3: WITH HINDSIGHT (Memory-Augmented)")
print("=" * 60)
phase3_results = []
for i, scenario in enumerate(TEST_SCENARIOS, 1):
print(f"\n--- Test {i}: {scenario['type'].upper()} Request ---")
print(f"Request: \"{scenario['request'][:60]}...\"")
tool_name = make_routing_request(
scenario['request'],
use_hindsight=True,
bank_id=bank_id
)
is_correct = tool_name == scenario['correct_tool']
phase3_results.append(is_correct)
print(f"LLM chose: {tool_name}")
print(f"Correct tool: {scenario['correct_tool']}")
print(f"Result: {'✓ CORRECT' if is_correct else '✗ INCORRECT'}")
phase3_accuracy = sum(phase3_results) / len(phase3_results) * 100
print(f"\n>>> Phase 3 Accuracy: {phase3_accuracy:.0f}% ({sum(phase3_results)}/{len(phase3_results)})")
```
## Summary
```python
print("=" * 60)
print("SUMMARY")
print("=" * 60)
print(f"\nPhase 1 (No Memory): {phase1_accuracy:.0f}% accuracy")
print(f"Phase 3 (With Hindsight): {phase3_accuracy:.0f}% accuracy")
improvement = phase3_accuracy - phase1_accuracy
if improvement > 0:
print(f"\n🎉 Improvement: +{improvement:.0f}% accuracy with Hindsight!")
elif improvement == 0:
print(f"\nNote: Results may vary. Run again to see learning effect.")
else:
print(f"\nNote: Phase 1 got lucky! Run again to see typical behavior.")
print(f"\nMemories stored in bank: {bank_id}")
print(f"View in UI: http://localhost:9999/banks/{bank_id}")
print("\n" + "=" * 60)
print("KEY INSIGHT")
print("=" * 60)
print("Hindsight allows the LLM to learn from experience which tool")
print("to use, even when tool names/descriptions are ambiguous.")
```
## Cleanup
```python
hindsight_litellm.cleanup()
# Optional: delete the bank
import requests
response = requests.delete(f"{HINDSIGHT_API_URL}/v1/default/banks/{bank_id}")
print(f"Deleted bank: {response.json()}")
```
@@ -22,7 +22,7 @@ export HINDSIGHT_API_LLM_API_KEY=$OPENAI_API_KEY
hindsight-api
```
API available at http://localhost:8888
API available at [http://localhost:8888](http://localhost:8888/docs)
</TabItem>
<TabItem value="docker" label="Docker (Full Experience)">
+86 -122
View File
@@ -1,127 +1,81 @@
# Configuration
Complete reference for configuring Hindsight server through environment variables and configuration files.
Complete reference for configuring Hindsight services through environment variables.
## Environment Variables
Hindsight has two services, each with its own configuration prefix:
Hindsight is configured entirely through environment variables, making it easy to deploy across different environments and container orchestration platforms.
| Service | Prefix | Description |
|---------|--------|-------------|
| **API Service** | `HINDSIGHT_API_*` | Core memory engine |
| **Control Plane** | `HINDSIGHT_CP_*` | Web UI |
All environment variable names and defaults are defined in `hindsight_api.config`. You can use `MemoryEngine.from_env()` to create a MemoryEngine instance configured from environment variables:
---
```python
from hindsight_api import MemoryEngine
## API Service
# Create from environment variables
memory = MemoryEngine.from_env()
await memory.initialize()
```
The API service handles all memory operations (retain, recall, reflect).
### LLM Provider Configuration
### Database
Configure the LLM provider used for fact extraction, entity resolution, and reasoning operations.
| Variable | Description | Default |
|----------|-------------|---------|
| `HINDSIGHT_API_DATABASE_URL` | PostgreSQL connection string | `pg0` (embedded) |
#### Common LLM Settings
If not provided, the server uses embedded `pg0` — convenient for development but not recommended for production.
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `HINDSIGHT_API_LLM_PROVIDER` | LLM provider: `groq`, `openai`, `gemini`, `ollama` | `groq` | Yes |
| `HINDSIGHT_API_LLM_API_KEY` | API key for LLM provider | - | Yes (except ollama) |
| `HINDSIGHT_API_LLM_MODEL` | Model name | Provider-specific | No |
| `HINDSIGHT_API_LLM_BASE_URL` | Custom LLM endpoint | Provider default | No |
### LLM Provider
#### Provider-Specific Examples
| Variable | Description | Default |
|----------|-------------|---------|
| `HINDSIGHT_API_LLM_PROVIDER` | Provider: `groq`, `openai`, `gemini`, `ollama` | `openai` |
| `HINDSIGHT_API_LLM_API_KEY` | API key for LLM provider | - |
| `HINDSIGHT_API_LLM_MODEL` | Model name | `gpt-5-mini` |
| `HINDSIGHT_API_LLM_BASE_URL` | Custom LLM endpoint | Provider default |
**Groq (Recommended for Fast Inference)**
**Provider Examples**
```bash
# Groq (recommended for fast inference)
export HINDSIGHT_API_LLM_PROVIDER=groq
export HINDSIGHT_API_LLM_API_KEY=gsk_xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=openai/gpt-oss-20b
```
**OpenAI**
```bash
# OpenAI
export HINDSIGHT_API_LLM_PROVIDER=openai
export HINDSIGHT_API_LLM_API_KEY=sk-xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=gpt-4o
```
**Gemini**
```bash
# Gemini
export HINDSIGHT_API_LLM_PROVIDER=gemini
export HINDSIGHT_API_LLM_API_KEY=xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=gemini-2.0-flash
```
**Ollama (Local, No API Key)**
```bash
# Ollama (local, no API key)
export HINDSIGHT_API_LLM_PROVIDER=ollama
export HINDSIGHT_API_LLM_BASE_URL=http://localhost:11434/v1
export HINDSIGHT_API_LLM_MODEL=llama3.1
```
**OpenAI-Compatible Endpoints**
```bash
# OpenAI-compatible endpoint
export HINDSIGHT_API_LLM_PROVIDER=openai
export HINDSIGHT_API_LLM_BASE_URL=https://your-endpoint.com/v1
export HINDSIGHT_API_LLM_API_KEY=your-api-key
export HINDSIGHT_API_LLM_MODEL=your-model-name
```
### Database Configuration
### Embeddings
Configure the PostgreSQL database connection and behavior.
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `HINDSIGHT_API_DATABASE_URL` | PostgreSQL connection string | - | Yes* |
**\*Note**: If `DATABASE_URL` is not provided, the server will use embedded `pg0` (embedded PostGRE).
### MCP Server Configuration
Configure the Model Context Protocol (MCP) server for AI assistant integrations.
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `HINDSIGHT_API_MCP_ENABLED` | Enable MCP server | `true` | No |
```bash
# Enable MCP server (default)
export HINDSIGHT_API_MCP_ENABLED=true
# Disable MCP server
export HINDSIGHT_API_MCP_ENABLED=false
```
### Embeddings Configuration
Configure the embeddings provider for semantic search. By default, uses local SentenceTransformers models.
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `HINDSIGHT_API_EMBEDDINGS_PROVIDER` | Provider: `local` or `tei` | `local` | No |
| `HINDSIGHT_API_EMBEDDINGS_LOCAL_MODEL` | Model name for local provider | `BAAI/bge-small-en-v1.5` | No |
| `HINDSIGHT_API_EMBEDDINGS_TEI_URL` | TEI server URL | - | Yes (if provider is `tei`) |
**Local Provider (Default)**
Uses SentenceTransformers to run embedding models locally. Good for development and smaller deployments.
| Variable | Description | Default |
|----------|-------------|---------|
| `HINDSIGHT_API_EMBEDDINGS_PROVIDER` | Provider: `local` or `tei` | `local` |
| `HINDSIGHT_API_EMBEDDINGS_LOCAL_MODEL` | Model for local provider | `BAAI/bge-small-en-v1.5` |
| `HINDSIGHT_API_EMBEDDINGS_TEI_URL` | TEI server URL | - |
```bash
# Local (default) - uses SentenceTransformers
export HINDSIGHT_API_EMBEDDINGS_PROVIDER=local
export HINDSIGHT_API_EMBEDDINGS_LOCAL_MODEL=BAAI/bge-small-en-v1.5
```
**TEI Provider (HuggingFace Text Embeddings Inference)**
Uses a remote [TEI server](https://github.com/huggingface/text-embeddings-inference) for high-performance inference. Recommended for production deployments.
```bash
# TEI - HuggingFace Text Embeddings Inference (recommended for production)
export HINDSIGHT_API_EMBEDDINGS_PROVIDER=tei
export HINDSIGHT_API_EMBEDDINGS_TEI_URL=http://localhost:8080
```
@@ -130,63 +84,73 @@ export HINDSIGHT_API_EMBEDDINGS_TEI_URL=http://localhost:8080
All embedding models must produce 384-dimensional vectors to match the database schema.
:::
### Reranker Configuration
### Reranker
Configure the cross-encoder reranker for improving search result relevance. By default, uses local SentenceTransformers models.
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| `HINDSIGHT_API_RERANKER_PROVIDER` | Provider: `local` or `tei` | `local` | No |
| `HINDSIGHT_API_RERANKER_LOCAL_MODEL` | Model name for local provider | `cross-encoder/ms-marco-MiniLM-L-6-v2` | No |
| `HINDSIGHT_API_RERANKER_TEI_URL` | TEI server URL | - | Yes (if provider is `tei`) |
**Local Provider (Default)**
Uses SentenceTransformers CrossEncoder to run reranking locally.
| Variable | Description | Default |
|----------|-------------|---------|
| `HINDSIGHT_API_RERANKER_PROVIDER` | Provider: `local` or `tei` | `local` |
| `HINDSIGHT_API_RERANKER_LOCAL_MODEL` | Model for local provider | `cross-encoder/ms-marco-MiniLM-L-6-v2` |
| `HINDSIGHT_API_RERANKER_TEI_URL` | TEI server URL | - |
```bash
# Local (default) - uses SentenceTransformers CrossEncoder
export HINDSIGHT_API_RERANKER_PROVIDER=local
export HINDSIGHT_API_RERANKER_LOCAL_MODEL=cross-encoder/ms-marco-MiniLM-L-6-v2
```
**TEI Provider (HuggingFace Text Embeddings Inference)**
Uses a remote [TEI server](https://github.com/huggingface/text-embeddings-inference) with a reranker model.
```bash
# TEI - for high-performance inference
export HINDSIGHT_API_RERANKER_PROVIDER=tei
export HINDSIGHT_API_RERANKER_TEI_URL=http://localhost:8081
```
:::tip
When using TEI, you can run separate servers for embeddings and reranking, or use a single server if it supports both operations with your chosen model.
:::
### Server
## Configuration Files
| Variable | Description | Default |
|----------|-------------|---------|
| `HINDSIGHT_API_HOST` | Bind address | `0.0.0.0` |
| `HINDSIGHT_API_PORT` | Server port | `8888` |
| `HINDSIGHT_API_LOG_LEVEL` | Log level: `debug`, `info`, `warning`, `error` | `info` |
| `HINDSIGHT_API_MCP_ENABLED` | Enable MCP server | `true` |
### .env File
### Programmatic Configuration
The Hindsight API will look for a `.env` file:
You can also configure the API programmatically using `MemoryEngine.from_env()`:
```bash
# .env
```python
from hindsight_api import MemoryEngine
# Database
HINDSIGHT_API_DATABASE_URL=postgresql://hindsight:hindsight_dev@localhost:5432/hindsight
# LLM
HINDSIGHT_API_LLM_PROVIDER=groq
HINDSIGHT_API_LLM_API_KEY=gsk_xxxxxxxxxxxx
# Embeddings (optional, defaults to local)
# HINDSIGHT_API_EMBEDDINGS_PROVIDER=local
# HINDSIGHT_API_EMBEDDINGS_LOCAL_MODEL=BAAI/bge-small-en-v1.5
# Reranker (optional, defaults to local)
# HINDSIGHT_API_RERANKER_PROVIDER=local
# HINDSIGHT_API_RERANKER_LOCAL_MODEL=cross-encoder/ms-marco-MiniLM-L-6-v2
memory = MemoryEngine.from_env()
await memory.initialize()
```
---
For configuration issues not covered here, please [open an issue](https://github.com/your-repo/hindsight/issues) on GitHub.
## Control Plane
The Control Plane is the web UI for managing memory banks.
| Variable | Description | Default |
|----------|-------------|---------|
| `HINDSIGHT_CP_DATAPLANE_API_URL` | URL of the API service | `http://localhost:8888` |
```bash
# Point Control Plane to a remote API service
export HINDSIGHT_CP_DATAPLANE_API_URL=http://api.example.com:8888
```
---
## Example .env File
```bash
# API Service
HINDSIGHT_API_DATABASE_URL=postgresql://hindsight:hindsight_dev@localhost:5432/hindsight
HINDSIGHT_API_LLM_PROVIDER=groq
HINDSIGHT_API_LLM_API_KEY=gsk_xxxxxxxxxxxx
# Control Plane
HINDSIGHT_CP_DATAPLANE_API_URL=http://localhost:8888
```
---
For configuration issues not covered here, please [open an issue](https://github.com/vectorize-io/hindsight/issues) on GitHub.
@@ -126,7 +126,6 @@ hindsight-api
hindsight-api --port 9000 # Custom port (default: 8888)
hindsight-api --host 127.0.0.1 # Bind to localhost only
hindsight-api --workers 4 # Multiple worker processes
hindsight-api --mcp # Enable MCP server
hindsight-api --log-level debug # Verbose logging
```
+63 -48
View File
@@ -6,14 +6,71 @@ Hindsight uses several machine learning models for different tasks.
| Model Type | Purpose | Default | Configurable |
|------------|---------|---------|--------------|
| **LLM** | Fact extraction, reasoning, generation | Provider-specific | Yes |
| **Embedding** | Vector representations for semantic search | `BAAI/bge-small-en-v1.5` | Yes |
| **Cross-Encoder** | Reranking search results | `cross-encoder/ms-marco-MiniLM-L-6-v2` | Yes |
| **LLM** | Fact extraction, reasoning, generation | Provider-specific | Yes |
All local models (embedding, cross-encoder) are automatically downloaded from HuggingFace on first run.
---
## LLM
Used for fact extraction, entity resolution, opinion generation, and answer synthesis.
**Supported providers:** OpenAI, Gemini, Groq, Ollama
### Tested Models
The following models have been tested and verified to work correctly with Hindsight:
| Provider | Model |
|----------|-------|
| **OpenAI** | `gpt-5.2` |
| **OpenAI** | `gpt-5` |
| **OpenAI** | `gpt-5-mini` |
| **OpenAI** | `gpt-5-nano` |
| **OpenAI** | `gpt-4.1-mini` |
| **OpenAI** | `gpt-4.1-nano` |
| **OpenAI** | `gpt-4o-mini` |
| **Gemini** | `gemini-3-pro-preview` |
| **Gemini** | `gemini-2.5-flash` |
| **Gemini** | `gemini-2.5-flash-lite` |
| **Groq** | `openai/gpt-oss-120b` |
| **Groq** | `openai/gpt-oss-20b` |
### Using Other Models
Other LLM models not listed above may work with Hindsight, but they must support **at least 65,000 output tokens** to ensure reliable fact extraction. If you need support for a specific model that doesn't meet this requirement, please [open an issue](https://github.com/hindsight-ai/hindsight/issues) to request an exception.
### Configuration
```bash
# Groq (recommended)
export HINDSIGHT_API_LLM_PROVIDER=groq
export HINDSIGHT_API_LLM_API_KEY=gsk_xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=openai/gpt-oss-20b
# OpenAI
export HINDSIGHT_API_LLM_PROVIDER=openai
export HINDSIGHT_API_LLM_API_KEY=sk-xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=gpt-4o
# Gemini
export HINDSIGHT_API_LLM_PROVIDER=gemini
export HINDSIGHT_API_LLM_API_KEY=xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=gemini-2.0-flash
# Ollama (local)
export HINDSIGHT_API_LLM_PROVIDER=ollama
export HINDSIGHT_API_LLM_BASE_URL=http://localhost:11434/v1
export HINDSIGHT_API_LLM_MODEL=llama3.1
```
**Note:** The LLM is the primary bottleneck for retain operations. See [Performance](./performance) for optimization strategies.
---
## Embedding Model
Converts text into dense vector representations for semantic similarity search.
@@ -22,14 +79,13 @@ Converts text into dense vector representations for semantic similarity search.
**Alternatives:**
| Model | Dimensions | Use Case |
|-------|------------|----------|
| `BAAI/bge-small-en-v1.5` | 384 | Default, fast, good quality |
| `BAAI/bge-base-en-v1.5` | 768 | Higher accuracy, slower |
| `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | Multilingual (50+ languages) |
| Model | Use Case |
|-------|----------|
| `BAAI/bge-small-en-v1.5` | Default, fast, good quality |
| `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | Multilingual (50+ languages) |
:::warning
All embedding models must produce 384-dimensional vectors to match the database schema.
All embedding models must produce **384-dimensional vectors** to match the database schema.
:::
**Configuration:**
@@ -71,44 +127,3 @@ export HINDSIGHT_API_RERANKER_LOCAL_MODEL=cross-encoder/ms-marco-MiniLM-L-6-v2
export HINDSIGHT_API_RERANKER_PROVIDER=tei
export HINDSIGHT_API_RERANKER_TEI_URL=http://localhost:8081
```
---
## LLM
Used for fact extraction, entity resolution, opinion generation, and answer synthesis.
**Supported providers:** Groq, OpenAI, Gemini, Ollama
| Provider | Recommended Model | Best For |
|----------|------------------|----------|
| **Groq** | `openai/gpt-oss-20b` | Fast inference, high throughput (recommended) |
| **OpenAI** | `gpt-4o` | Good quality |
| **Gemini** | `gemini-2.0-flash` | Good quality, cost effective |
| **Ollama** | `llama3.1` | Local deployment, privacy |
**Configuration:**
```bash
# Groq (recommended)
export HINDSIGHT_API_LLM_PROVIDER=groq
export HINDSIGHT_API_LLM_API_KEY=gsk_xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=openai/gpt-oss-20b
# OpenAI
export HINDSIGHT_API_LLM_PROVIDER=openai
export HINDSIGHT_API_LLM_API_KEY=sk-xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=gpt-4o
# Gemini
export HINDSIGHT_API_LLM_PROVIDER=gemini
export HINDSIGHT_API_LLM_API_KEY=xxxxxxxxxxxx
export HINDSIGHT_API_LLM_MODEL=gemini-2.0-flash
# Ollama (local)
export HINDSIGHT_API_LLM_PROVIDER=ollama
export HINDSIGHT_API_LLM_BASE_URL=http://localhost:11434/v1
export HINDSIGHT_API_LLM_MODEL=llama3.1
```
**Note:** The LLM is the primary bottleneck for retain operations. See [Performance](./performance) for optimization strategies.
+19 -29
View File
@@ -25,10 +25,10 @@ This means **Recall (search) operations are blazingly fast** because all the hea
### Performance Comparison
| Operation | Typical Latency | Primary Bottleneck | Optimization Strategy |
|-----------|----------------|-------------------|----------------------|
| **Recall** | 100-600ms | Vector search, graph traversal | ✅ Already optimized |
| **Reflect** | 800-3000ms | LLM generation + search | Reduce search budget, use faster LLM |
| Operation | Typical Latency | Primary Bottleneck | Optimization Strategy |
|-----------|----------------|-------------------|----------------------------------|
| **Recall** | 100-600ms | Re-ranker (on CPU) | Use GPU for re-ranking, or reduce budget |
| **Reflect** | 800-3000ms | LLM generation | Use faster LLM |
| **Retain** | 500ms-2000ms per batch | **LLM fact extraction** | Use high-throughput LLM provider |
Hindsight is designed to ensure your **application's read path (recall/reflect) is always fast**, even if it means spending more time upfront during writes. This is the right trade-off for memory systems where:
@@ -50,8 +50,8 @@ The fact extraction process is structured and well-defined, so smaller, faster m
To maximize retention throughput:
1. **Use high-throughput LLM providers**: Choose providers with high requests-per-minute (RPM) limits and low latency
- **Fast**: [Groq](https://groq.com) with `gpt-oss-20b` or other openai-oss models, self-hosted models on GPU clusters (vLLM, TGI)
- ⚠️ **Slower**: Standard cloud LLM providers with rate limits
- **Fast**: [Groq](https://groq.com) with `gpt-oss-20b` or other openai-oss models, self-hosted models on GPU clusters (vLLM, TGI)
- **Slow**: Standard cloud LLM providers with rate limits
2. **Batch your operations**: Group related content into batch requests. The only limit is the HTTP payload size — Hindsight automatically splits large batches into smaller, optimized chunks under the hood, so you don't have to worry about it.
@@ -61,15 +61,7 @@ To maximize retention throughput:
### Throughput
Typical ingestion performance:
| Mode | Items/second | Use Case |
|------|--------------|----------|
| Synchronous | ~50-100 | Real-time updates, small batches |
| Async (batched) | ~500-1000 | Bulk imports, background processing |
| Parallel async | ~2000-5000 | Large-scale data migration |
**Factors affecting throughput:**
Factors affecting throughput:
- Document size and complexity
- LLM provider rate limits (for fact extraction)
- Database write performance
@@ -83,13 +75,13 @@ Typical ingestion performance:
The `budget` parameter controls the search depth and quality. Choose based on query complexity — comprehensive questions that need thorough analysis benefit from higher budgets:
| Budget | Latency | Memory Activation | Use Case |
|--------|---------|-------------------|----------|
| `low` | 100-300ms | ~10-50 facts | Quick lookups, real-time chat |
| `mid` | 300-600ms | ~50-200 facts | Standard queries, balanced performance |
| `high` | 500-1500ms | ~200-500 facts | Comprehensive questions, thorough analysis |
| Budget | Use Case |
|--------|----------|
| `low` | Quick lookups, real-time chat |
| `mid` | Standard queries, balanced performance |
| `high` | Comprehensive questions, thorough analysis |
### Search Optimization
### Optimization
1. **Appropriate budgets**: Use lower budgets for simple queries, higher for comprehensive reasoning
2. **Limit result tokens**: Set `max_tokens` to control response size (default: 4096)
@@ -107,18 +99,16 @@ Hindsight uses PostgreSQL with pgvector for efficient vector search:
### Performance Characteristics
| Component | Latency | Description |
|-----------|---------|-------------|
| Memory search | 300-1000ms | Based on budget (low/mid/high) |
| LLM generation | 500-2000ms | Depends on provider and response length |
| **Total** | **800-3000ms** | Typical end-to-end latency |
| Component | Latency | Description |
|-----------|----------------|-------------|
| Memory search | 100-600ms | Based on budget (low/mid/high) |
| LLM generation | 500-2000ms | Depends on provider and response length |
| **Total** | **600-2600ms** | Typical end-to-end latency |
### Optimization Strategies
1. **Budget selection**: Use lower budgets when context is sufficient
2. **Context provision**: Provide relevant `context` to reduce search requirements
3. **Streaming responses**: Use streaming APIs (when available) for faster time-to-first-token
4. **Caching**: Cache frequent queries at the application level
2. **Context provision**: Provide relevant `context` to reduce recall requirements and steer towards more focused answers
## Best Practices
+1 -1
View File
@@ -62,9 +62,9 @@ Hindsight distinguishes between **world** facts (about others) and **experience*
| **world** | Facts about people, places, things | "Alice works at Google" |
| **experience** | Conversations and events | "I recommended Python to Alice" |
This separation is important for `reflect()` — the bank can reason about what it knows versus what happened in conversations.
**Note:** Opinions aren't created during `retain()` — only during `reflect()` when the bank forms beliefs.
This separation is important for `reflect()` — the bank can reason about what it knows versus what happened in conversations.
---
+53 -29
View File
@@ -108,6 +108,19 @@ After the four strategies run, results are **fused together**:
---
## Why Multiple Strategies?
Consider the query: **"What did Alice think about Python last spring?"**
- **Semantic** finds facts about Alice's opinions on programming
- **Keyword** ensures "Python" is actually mentioned
- **Graph** connects Alice → opinions → programming languages
- **Temporal** filters to "last spring" timeframe
The **fusion** of all four gives you exactly what you're looking for, even though no single strategy would suffice.
---
## Token Budget Management
Hindsight is built for AI agents, not humans. Traditional search systems return "top-k" results, but agents don't think in terms of result counts—they think in tokens. An agent's context window is measured in tokens, and that's exactly how Hindsight measures results.
@@ -119,19 +132,43 @@ Hindsight is built for AI agents, not humans. Traditional search systems return
**Parameters you control:**
- `max_tokens`: How much memory content to return (default: 4096 tokens)
- `budget`: Budget level for graph traversal (low, mid, high)
- `budget`: Search depth level (low, mid, high)
- `fact_type`: Filter by world, experience, opinion, or all
### Additional Context: Chunks and Entity Observations
### Expanding Context: Chunks and Entity Observations
For the most relevant memories, you can optionally retrieve additional context—each with its own token budget:
Memories are distilled facts—concise but sometimes missing nuance. When your agent needs deeper context, you can optionally retrieve the source material and related knowledge:
| Option | Parameters | Description |
| Option | Parameters | When to Use |
|--------|------------|-------------|
| **Chunks** | `include_chunks`, `max_chunk_tokens` | Raw text chunks that generated the memories |
| **Entity Observations** | `include_entities`, `max_entity_tokens` | Related observations about entities mentioned in results |
| **Chunks** | `include_chunks`, `max_chunk_tokens` | Need exact quotes, original phrasing, or surrounding context |
| **Entity Observations** | `include_entities`, `max_entity_tokens` | Need broader knowledge about people/things mentioned in results |
This gives your agent richer context while maintaining precise control over total token consumption.
**Chunks** return the raw text that generated each memory—useful when the distilled fact loses important nuance:
```
Memory: "Alice prefers Python over JavaScript"
Chunk: "Alice mentioned she prefers Python over JavaScript, mainly because
of its data science ecosystem, though she admits JS is better for
frontend work and she's been learning TypeScript lately."
```
**Entity Observations** pull in related facts about entities mentioned in your results. If a memory mentions "Alice", you automatically get her role, skills, and other relevant context—without needing a separate query:
```
Query: "What programming languages does Alice like?"
Memory: "Alice prefers Python over JavaScript"
Entity Observations (Alice):
- "Alice is a senior data scientist at Google"
- "Alice specializes in machine learning"
- "Alice has been learning TypeScript"
```
**When to include them:**
- **Chunks**: When generating responses that need verbatim quotes or when context matters (e.g., "What exactly did Alice say about the project?")
- **Entity Observations**: When building complete profiles or when the conversation might reference multiple aspects of an entity (e.g., "Tell me about Alice's work")
Each has its own token budget, giving you precise control over total context size.
---
@@ -139,17 +176,17 @@ This gives your agent richer context while maintaining precise control over tota
Different use cases require different trade-offs between **recall quality** and **response speed**. Two parameters control this:
### Budget: Graph Exploration Depth
### Budget: Search Depth
Controls how many nodes to explore when traversing the knowledge graph:
Controls how thoroughly Hindsight explores the memory bank—affecting graph traversal depth, candidate pool size, and cross-encoder re-ranking:
| Budget | Nodes Explored | Best For | Trade-off |
|--------|----------------|----------|-----------|
| **low** | 100 nodes | Quick lookups, simple queries | Fast, may miss distant connections |
| **mid** | 300 nodes | Most queries, balanced | Good coverage, reasonable speed |
| **high** | 600 nodes | Complex multi-hop queries | Thorough, slower |
| Budget | Best For | Trade-off |
|--------|----------|-----------|
| **low** | Quick lookups, simple queries | Fast, may miss indirect connections |
| **mid** | Most queries, balanced | Good coverage, reasonable speed |
| **high** | Complex queries requiring deep exploration | Thorough, slower |
**Example:** "What did Alice's manager's team work on?" benefits from high budget to traverse Alice → manager → team → projects.
**Example:** "What did Alice's manager's team work on?" benefits from high budget to traverse multiple hops (Alice → manager → team → projects) and evaluate more candidates.
### Max Tokens: Context Window Size
@@ -169,7 +206,7 @@ Budget and max_tokens control different aspects of recall:
| Parameter | What it controls | Latency impact | Example |
|-----------|------------------|----------------|---------|
| **Budget** | How deep to explore the graph | Search time | High budget finds Alice → manager → team → projects |
| **Budget** | How thoroughly to explore memories | Search time | High budget finds Alice → manager → team → projects |
| **Max Tokens** | How much context to return | LLM processing time | High tokens returns more memories to the agent |
**They're independent.** Common combinations:
@@ -192,19 +229,6 @@ Budget and max_tokens control different aspects of recall:
---
## Why Multiple Strategies?
Consider the query: **"What did Alice think about Python last spring?"**
- **Semantic** finds facts about Alice's opinions on programming
- **Keyword** ensures "Python" is actually mentioned
- **Graph** connects Alice → opinions → programming languages
- **Temporal** filters to "last spring" timeframe
The **fusion** of all four gives you exactly what you're looking for, even though no single strategy would suffice.
---
## Next Steps
- [**Retain**](./retain) — How memories are stored with rich context
+42
View File
@@ -0,0 +1,42 @@
# Services
Hindsight consists of two services that can run together or separately depending on your deployment needs.
## API Service
The core memory engine. Handles all memory operations:
- **Retain**: Ingests content, extracts facts, builds knowledge graph
- **Recall**: Semantic search across memories
- **Reflect**: Disposition-aware answer generation
```
hindsight-api # Default port: 8888
```
The API service is stateless and can be horizontally scaled behind a load balancer. All state is stored in PostgreSQL.
## Control Plane
Web UI for managing and exploring your memory banks:
- Browse agents and memory banks
- Explore entities and relationships
- View ingestion history and operations
- Test recall queries interactively
```
hindsight-control-plane # Default port: 9999
```
The Control Plane connects to the API service and provides a visual interface for development and debugging.
## Deployment Options
| Deployment | Services | Use Case |
|------------|----------|----------|
| **Docker (single container)** | Both bundled | Development, quick start |
| **Helm / Kubernetes** | Separate pods | Production, scaling |
| **Bare metal** | Run independently | Custom deployments |
In the Docker quickstart, both services run in a single container. For production Kubernetes deployments, they run as separate pods with independent scaling.
+3 -4
View File
@@ -52,10 +52,9 @@ pg0 is a single binary containing:
### Behavior
When no `DATABASE_URL` is configured, Hindsight:
1. Downloads the pg0 binary for the current platform (macOS ARM, Linux x86_64/ARM64, Windows)
2. Starts an embedded PostgreSQL instance on port 5555
3. Initializes the schema
4. Stores data in `~/.hindsight/pg0/`
1. Starts an embedded PostgreSQL instance on port 5555
2. Initializes the schema
3. Stores data in `~/.hindsight/pg0/`
### Environments
@@ -0,0 +1,345 @@
---
sidebar_position: 1
---
# LiteLLM
Universal LLM memory integration via [LiteLLM](https://github.com/BerriAI/litellm). Add persistent memory to any LLM application with just a few lines of code.
## Features
- **Universal LLM Support** - Works with 100+ LLM providers via LiteLLM (OpenAI, Anthropic, Groq, Azure, AWS Bedrock, Google Vertex AI, and more)
- **Simple Integration** - Just configure, enable, and use `hindsight_litellm.completion()`
- **Automatic Memory Injection** - Relevant memories are injected into prompts before LLM calls
- **Automatic Conversation Storage** - Conversations are stored to Hindsight for future recall
- **Two Memory Modes** - Choose between `reflect` (synthesized context) or `recall` (raw memory retrieval)
- **Direct Memory APIs** - Query, synthesize, and store memories manually
- **Native Client Wrappers** - Alternative wrappers for OpenAI and Anthropic SDKs
## Installation
```bash
pip install hindsight-litellm
```
## Quick Start
```python
import hindsight_litellm
# Configure and enable memory integration
hindsight_litellm.configure(
hindsight_api_url="http://localhost:8888",
bank_id="my-agent",
)
hindsight_litellm.enable()
# Use the convenience wrapper - memory is automatically injected and stored
response = hindsight_litellm.completion(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "What did we discuss about AI?"}]
)
```
## How It Works
When you call `completion()`, the following happens automatically:
1. **Memory Retrieval** - Hindsight is queried for relevant memories based on the conversation
2. **Prompt Injection** - Memories are injected into the system message
3. **LLM Call** - The enriched prompt is sent to the LLM
4. **Conversation Storage** - The conversation is stored to Hindsight for future recall
5. **Response Returned** - You receive the response as normal
## Configuration Options
```python
hindsight_litellm.configure(
# Required
hindsight_api_url="http://localhost:8888", # Hindsight API server URL
bank_id="my-agent", # Memory bank ID
api_key="your-api-key", # Optional API key for authentication
# Optional - Memory behavior
store_conversations=True, # Store conversations after LLM calls
inject_memories=True, # Inject relevant memories into prompts
use_reflect=False, # Use reflect API (synthesized) vs recall (raw memories)
reflect_include_facts=False, # Include source facts with reflect responses
max_memories=None, # Maximum memories to inject (None = unlimited)
max_memory_tokens=4096, # Maximum tokens for memory context
recall_budget="mid", # Recall budget: "low", "mid", "high"
fact_types=["world", "agent"], # Filter fact types to inject
# Optional - Bank Configuration
bank_name="My Agent", # Human-readable display name for the memory bank
background="This agent...", # Instructions guiding what Hindsight should remember
# Optional - Advanced
injection_mode="system_message", # or "prepend_user"
excluded_models=["gpt-3.5*"], # Exclude certain models
verbose=True, # Enable verbose logging and debug info
)
```
### Bank Configuration
The `background` and `bank_name` parameters configure the memory bank itself. When provided, `configure()` will automatically create or update the bank with these settings.
```python
hindsight_litellm.configure(
hindsight_api_url="http://localhost:8888",
bank_id="support-router",
bank_name="Customer Support Router",
background="""This agent routes customer support requests to the appropriate team.
Remember which types of issues should go to which teams (billing, technical, sales).
Track customer preferences for communication channels and past issue resolutions.""",
)
```
### Memory Modes: Reflect vs Recall
- **Recall mode** (`use_reflect=False`, default): Retrieves raw memory facts and injects them as a numbered list. Best when you need precise, individual memories.
- **Reflect mode** (`use_reflect=True`): Synthesizes memories into a coherent context paragraph. Best for natural, conversational memory context.
```python
# Recall mode - raw memories
hindsight_litellm.configure(
bank_id="my-agent",
use_reflect=False, # Default
)
# Injects: "1. [WORLD] User prefers Python\n2. [OPINION] User dislikes Java..."
# Reflect mode - synthesized context
hindsight_litellm.configure(
bank_id="my-agent",
use_reflect=True,
)
# Injects: "Based on previous conversations, the user is a Python developer who..."
```
## Multi-Provider Support
Works with any LiteLLM-supported provider:
```python
import hindsight_litellm
hindsight_litellm.configure(
hindsight_api_url="http://localhost:8888",
bank_id="my-agent",
)
hindsight_litellm.enable()
# OpenAI
hindsight_litellm.completion(model="gpt-4o", messages=[...])
# Anthropic
hindsight_litellm.completion(model="claude-3-5-sonnet-20241022", messages=[...])
# Groq
hindsight_litellm.completion(model="groq/llama-3.1-70b-versatile", messages=[...])
# Azure OpenAI
hindsight_litellm.completion(model="azure/gpt-4", messages=[...])
# AWS Bedrock
hindsight_litellm.completion(model="bedrock/anthropic.claude-3", messages=[...])
# Google Vertex AI
hindsight_litellm.completion(model="vertex_ai/gemini-pro", messages=[...])
```
## Direct Memory APIs
### Recall - Query raw memories
```python
from hindsight_litellm import configure, recall
configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
memories = recall("what projects am I working on?", budget="mid")
for m in memories:
print(f"- [{m.fact_type}] {m.text}")
```
### Reflect - Get synthesized context
```python
from hindsight_litellm import configure, reflect
configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
result = reflect("what do you know about the user's preferences?")
print(result.text)
```
### Retain - Store memories
```python
from hindsight_litellm import configure, retain
configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
result = retain(
content="User mentioned they're working on a machine learning project",
context="Discussion about current projects",
)
```
### Async APIs
```python
from hindsight_litellm import arecall, areflect, aretain
# Async versions of all memory APIs
memories = await arecall("what do you know about me?")
context = await areflect("summarize user preferences")
result = await aretain(content="New information to remember")
```
## Native Client Wrappers
Alternative to LiteLLM callbacks for direct SDK integration.
### OpenAI Wrapper
```python
from openai import OpenAI
from hindsight_litellm import wrap_openai
client = OpenAI()
wrapped = wrap_openai(
client,
bank_id="my-agent",
hindsight_api_url="http://localhost:8888",
)
response = wrapped.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "What do you know about me?"}]
)
```
### Anthropic Wrapper
```python
from anthropic import Anthropic
from hindsight_litellm import wrap_anthropic
client = Anthropic()
wrapped = wrap_anthropic(
client,
bank_id="my-agent",
hindsight_api_url="http://localhost:8888",
)
response = wrapped.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}]
)
```
## Debug Mode
When `verbose=True`, you can inspect exactly what memories are being injected:
```python
from hindsight_litellm import configure, enable, completion, get_last_injection_debug
configure(
bank_id="my-agent",
hindsight_api_url="http://localhost:8888",
verbose=True,
)
enable()
response = completion(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "What's my favorite color?"}]
)
# Inspect what was injected
debug = get_last_injection_debug()
if debug:
print(f"Mode: {debug.mode}") # "reflect" or "recall"
print(f"Injected: {debug.injected}") # True/False
print(f"Results: {debug.results_count}")
print(f"Memory context:\n{debug.memory_context}")
```
## Context Manager
```python
from hindsight_litellm import hindsight_memory
import litellm
with hindsight_memory(bank_id="user-123"):
response = litellm.completion(model="gpt-4", messages=[...])
# Memory integration automatically disabled after context
```
## Disabling and Cleanup
```python
from hindsight_litellm import disable, cleanup
# Temporarily disable memory integration
disable()
# Clean up all resources (call when shutting down)
cleanup()
```
## API Reference
### Main Functions
| Function | Description |
|----------|-------------|
| `configure(...)` | Configure global Hindsight settings |
| `enable()` | Enable memory integration with LiteLLM |
| `disable()` | Disable memory integration |
| `is_enabled()` | Check if memory integration is enabled |
| `cleanup()` | Clean up all resources |
### Configuration Functions
| Function | Description |
|----------|-------------|
| `get_config()` | Get current configuration |
| `is_configured()` | Check if Hindsight is configured |
| `reset_config()` | Reset configuration to defaults |
### Memory Functions
| Function | Description |
|----------|-------------|
| `recall(query, ...)` | Synchronously query raw memories |
| `arecall(query, ...)` | Asynchronously query raw memories |
| `reflect(query, ...)` | Synchronously get synthesized memory context |
| `areflect(query, ...)` | Asynchronously get synthesized memory context |
| `retain(content, ...)` | Synchronously store a memory |
| `aretain(content, ...)` | Asynchronously store a memory |
### Debug Functions
| Function | Description |
|----------|-------------|
| `get_last_injection_debug()` | Get debug info from last memory injection |
| `clear_injection_debug()` | Clear stored debug info |
### Client Wrappers
| Function | Description |
|----------|-------------|
| `wrap_openai(client, ...)` | Wrap OpenAI client with memory |
| `wrap_anthropic(client, ...)` | Wrap Anthropic client with memory |
## Requirements
- Python >= 3.10
- litellm >= 1.40.0
- A running Hindsight API server
@@ -0,0 +1,172 @@
---
sidebar_position: 2
---
# Local MCP Server
Hindsight provides a fully local MCP server that runs entirely on your machine with an embedded PostgreSQL database. No external server or database setup required.
This is ideal for:
- **Personal use with Claude Code** — Give Claude long-term memory across conversations
- **Development and testing** — Quick setup without infrastructure
- **Privacy-focused setups** — All data stays on your machine
## Quick Start
### With uvx (recommended)
```bash
uvx hindsight-api@latest hindsight-local-mcp
```
### With pip
```bash
pip install hindsight-api
hindsight-local-mcp
```
## Claude Code Configuration
Add to your Claude Code MCP settings (`~/.claude/claude_desktop_config.json`):
```json
{
"mcpServers": {
"hindsight": {
"command": "uvx",
"args": ["hindsight-api@latest", "hindsight-local-mcp"],
"env": {
"HINDSIGHT_API_LLM_API_KEY": "your-openai-key"
}
}
}
}
```
### With Custom Bank ID
By default, memories are stored in a bank called `mcp`. To use a different bank:
```json
{
"mcpServers": {
"hindsight": {
"command": "uvx",
"args": ["hindsight-api@latest", "hindsight-local-mcp"],
"env": {
"HINDSIGHT_API_LLM_API_KEY": "your-openai-key",
"HINDSIGHT_API_MCP_LOCAL_BANK_ID": "my-personal-memory"
}
}
}
}
```
## Environment Variables
All standard [Hindsight configuration variables](/developer/configuration) are supported.
### Local MCP Specific
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `HINDSIGHT_API_MCP_LOCAL_BANK_ID` | No | `mcp` | Memory bank ID to use |
## Available Tools
### retain
Store information to long-term memory. This is a **fire-and-forget** operation — it returns immediately while processing happens in the background.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `content` | string | Yes | The fact or memory to store |
| `context` | string | No | Category for the memory (default: `general`) |
**Example:**
```json
{
"name": "retain",
"arguments": {
"content": "User's favorite color is blue",
"context": "preferences"
}
}
```
**Response:**
```json
{
"status": "accepted",
"message": "Memory storage initiated"
}
```
### recall
Search memories to provide personalized responses.
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | Natural language search query |
| `max_tokens` | integer | No | Maximum tokens to return (default: 4096) |
| `budget` | string | No | Search depth: `low`, `mid`, or `high` (default: `low`) |
**Example:**
```json
{
"name": "recall",
"arguments": {
"query": "What are the user's color preferences?",
"max_tokens": 2048,
"budget": "mid"
}
}
```
## How It Works
The local MCP server:
1. **Starts an embedded PostgreSQL** (pg0) on an automatically assigned port
2. **Initializes the Hindsight memory engine** with local embeddings
3. **Connects via stdio** to Claude Code using the MCP protocol
Data is persisted in the pg0 data directory (`~/.pg0/hindsight-mcp/`), so your memories survive restarts.
## Troubleshooting
### "HINDSIGHT_API_LLM_API_KEY required"
Make sure you've set the API key in your MCP configuration:
```json
{
"env": {
"HINDSIGHT_API_LLM_API_KEY": "sk-..."
}
}
```
### Slow startup
The first startup may take longer as it:
- Downloads the embedding model (~100MB)
- Initializes the PostgreSQL database
Subsequent starts are faster.
### Checking logs
Set `HINDSIGHT_API_LOG_LEVEL=debug` for verbose output:
```json
{
"env": {
"HINDSIGHT_API_LOG_LEVEL": "debug"
}
}
```
Logs are written to stderr and visible in Claude Code's MCP server output.
+13
View File
@@ -2,6 +2,10 @@ import {themes as prismThemes} from 'prism-react-renderer';
import type {Config} from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';
// Announcement bar - supports HTML for links
// Set to empty string '' to hide the bar
const ANNOUNCEMENT_BAR = 'HINDSIGHT is State-of-the-Art on Memory for AI Agents | <a href="https://arxiv.org/abs/2512.12818" target="_blank">Read the paper →</a>';
const config: Config = {
title: 'Hindsight',
tagline: 'Entity-Aware Memory System for AI Agents',
@@ -115,6 +119,15 @@ const config: Config = {
themes: ['@docusaurus/theme-mermaid'],
themeConfig: {
...(ANNOUNCEMENT_BAR && {
announcementBar: {
id: 'announcement',
content: ANNOUNCEMENT_BAR,
backgroundColor: '#0074d9',
textColor: '#ffffff',
isCloseable: true,
},
}),
image: 'img/hindsight-social-card.jpg',
colorMode: {
defaultMode: 'dark',
+2 -3
View File
@@ -4,9 +4,8 @@
"private": true,
"scripts": {
"docusaurus": "docusaurus",
"generate-llms": "node scripts/generate-llms-full.js",
"start": "npm run generate-llms && docusaurus start",
"build": "npm run generate-llms && docusaurus build",
"start": "docusaurus start",
"build": "docusaurus build",
"swizzle": "docusaurus swizzle",
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
@@ -1,150 +0,0 @@
#!/usr/bin/env node
/**
* Generates llms-full.txt by concatenating all documentation markdown files.
* This file is used by LLMs to understand the full documentation.
*
* Usage: node scripts/generate-llms-full.js
*
* Output: static/llms-full.txt (served at /llms-full.txt)
*/
const fs = require('fs');
const path = require('path');
const DOCS_DIR = path.join(__dirname, '..', 'docs');
const OUTPUT_FILE = path.join(__dirname, '..', 'static', 'llms-full.txt');
// Order matters - more important docs first
const DOC_ORDER = [
'developer/index.md',
'developer/api/quickstart.md',
'developer/api/main-methods.md',
'developer/retain.md',
'developer/retrieval.md',
'developer/reflect.md',
'developer/api/retain.md',
'developer/api/recall.md',
'developer/api/reflect.md',
'developer/api/memory-banks.md',
'developer/api/entities.md',
'developer/api/documents.md',
'developer/api/operations.md',
'developer/installation.md',
'developer/configuration.md',
'developer/models.md',
'developer/rag-vs-hindsight.md',
'sdks/python.md',
'sdks/nodejs.md',
'sdks/cli.md',
'sdks/mcp.md',
'cookbook/index.md',
'cookbook/per-user-memory.md',
'cookbook/support-agent-with-shared-knowledge.md',
];
function getAllMarkdownFiles(dir, baseDir = dir) {
const files = [];
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...getAllMarkdownFiles(fullPath, baseDir));
} else if (entry.name.endsWith('.md') || entry.name.endsWith('.mdx')) {
const relativePath = path.relative(baseDir, fullPath);
files.push(relativePath);
}
}
return files;
}
function stripFrontmatter(content) {
// Remove YAML frontmatter (between --- markers)
const frontmatterRegex = /^---\n[\s\S]*?\n---\n/;
return content.replace(frontmatterRegex, '');
}
function cleanMarkdown(content) {
let cleaned = stripFrontmatter(content);
// Remove import statements
cleaned = cleaned.replace(/^import\s+.*$/gm, '');
// Remove empty lines at start
cleaned = cleaned.replace(/^\n+/, '');
return cleaned;
}
function generateLlmsFullTxt() {
console.log('Generating llms-full.txt...');
// Get all markdown files
const allFiles = getAllMarkdownFiles(DOCS_DIR);
// Create ordered list: prioritized files first, then remaining files
const orderedFiles = [];
const remainingFiles = new Set(allFiles);
// Add prioritized files in order
for (const file of DOC_ORDER) {
if (remainingFiles.has(file)) {
orderedFiles.push(file);
remainingFiles.delete(file);
}
}
// Add remaining files (sorted alphabetically)
const sortedRemaining = Array.from(remainingFiles).sort();
orderedFiles.push(...sortedRemaining);
// Build the output
const sections = [];
// Header
sections.push(`# Hindsight Documentation
> Agent Memory that Works Like Human Memory
This file contains the complete Hindsight documentation for LLM consumption.
Generated: ${new Date().toISOString()}
---
`);
// Process each file
for (const file of orderedFiles) {
const filePath = path.join(DOCS_DIR, file);
if (!fs.existsSync(filePath)) {
console.warn(` Warning: ${file} not found, skipping`);
continue;
}
const content = fs.readFileSync(filePath, 'utf-8');
const cleanedContent = cleanMarkdown(content);
if (cleanedContent.trim()) {
// Add file path as context
sections.push(`\n## File: ${file}\n`);
sections.push(cleanedContent);
sections.push('\n---\n');
console.log(` Added: ${file}`);
}
}
// Write output
const output = sections.join('\n');
fs.writeFileSync(OUTPUT_FILE, output);
const stats = fs.statSync(OUTPUT_FILE);
const sizeKb = (stats.size / 1024).toFixed(1);
console.log(`\nGenerated: ${OUTPUT_FILE}`);
console.log(`Size: ${sizeKb} KB`);
console.log(`Files included: ${orderedFiles.length}`);
}
generateLlmsFullTxt();
+53 -4
View File
@@ -101,6 +101,11 @@ const sidebars: SidebarsConfig = {
id: 'developer/installation',
label: 'Installation',
},
{
type: 'doc',
id: 'developer/services',
label: 'Services',
},
{
type: 'doc',
id: 'developer/configuration',
@@ -147,6 +152,23 @@ const sidebars: SidebarsConfig = {
},
],
},
{
type: 'category',
label: 'Integrations',
collapsible: false,
items: [
{
type: 'doc',
id: 'sdks/integrations/local-mcp',
label: 'Local MCP Server',
},
{
type: 'doc',
id: 'sdks/integrations/litellm',
label: 'LiteLLM',
},
],
},
],
cookbookSidebar: [
{
@@ -156,19 +178,46 @@ const sidebars: SidebarsConfig = {
},
{
type: 'category',
label: 'Use Cases',
label: 'Recipes',
collapsible: false,
items: [
{
type: 'doc',
id: 'cookbook/per-user-memory',
id: 'cookbook/recipes/quickstart',
label: 'Hindsight Quickstart',
},
{
type: 'doc',
id: 'cookbook/recipes/per-user-memory',
label: 'Per-User Memory',
},
{
type: 'doc',
id: 'cookbook/support-agent-with-shared-knowledge',
label: 'Support Agent + Shared Knowledge',
id: 'cookbook/recipes/support-agent-shared-knowledge',
label: 'Support Agent with Shared Knowledge',
},
{
type: 'doc',
id: 'cookbook/recipes/litellm-memory-demo',
label: 'Hindsight Memory Demo with LiteLLM',
},
{
type: 'doc',
id: 'cookbook/recipes/tool-learning-demo',
label: 'Hindsight Tool Learning Demo',
}
],
},
{
type: 'category',
label: 'Applications',
collapsible: false,
items: [
{
type: 'doc',
id: 'cookbook/applications/openai-fitness-coach',
label: 'OpenAI Agent + Hindsight Memory Integration',
}
],
},
],
@@ -0,0 +1,80 @@
.carouselSection {
margin: 2rem 0;
}
.sectionTitle {
font-size: 1.5rem;
margin-bottom: 1rem;
font-weight: 600;
}
.carousel {
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: thin;
scrollbar-color: var(--ifm-color-emphasis-400) transparent;
padding-bottom: 0.5rem;
margin: 0 -1rem;
padding: 0 1rem;
}
.carousel::-webkit-scrollbar {
height: 6px;
}
.carousel::-webkit-scrollbar-track {
background: transparent;
}
.carousel::-webkit-scrollbar-thumb {
background-color: var(--ifm-color-emphasis-400);
border-radius: 3px;
}
.carouselTrack {
display: flex;
gap: 1rem;
padding-bottom: 0.5rem;
}
.card {
flex: 0 0 auto;
padding: 0.75rem 1rem;
border-radius: 8px;
border: 1px solid var(--ifm-color-emphasis-300);
background: var(--ifm-background-surface-color);
text-decoration: none;
color: inherit;
display: flex;
align-items: center;
gap: 0.5rem;
transition: all 0.2s ease;
white-space: nowrap;
}
.card:hover {
text-decoration: none;
border-color: var(--ifm-color-primary);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
[data-theme='dark'] .card {
background: var(--ifm-background-color);
border-color: var(--ifm-color-emphasis-400);
}
[data-theme='dark'] .card:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
border-color: var(--ifm-color-primary);
}
.cardTitle {
font-size: 0.95rem;
font-weight: 500;
color: var(--ifm-font-color-base);
}
.cardLink {
color: var(--ifm-color-primary);
font-weight: 500;
}
@@ -0,0 +1,31 @@
import React from 'react';
import Link from '@docusaurus/Link';
import styles from './RecipeCarousel.module.css';
export interface RecipeCard {
title: string;
href: string;
}
interface RecipeCarouselProps {
title: string;
items: RecipeCard[];
}
export default function RecipeCarousel({ title, items }: RecipeCarouselProps): React.ReactElement {
return (
<div className={styles.carouselSection}>
<h2 className={styles.sectionTitle}>{title}</h2>
<div className={styles.carousel}>
<div className={styles.carouselTrack}>
{items.map((item, index) => (
<Link key={index} to={item.href} className={styles.card}>
<span className={styles.cardTitle}>{item.title}</span>
<span className={styles.cardLink}></span>
</Link>
))}
</div>
</div>
</div>
);
}
+11
View File
@@ -509,6 +509,17 @@ article a:not(.button):not([class*="hash-link"]) {
font-weight: 500;
}
/* Links containing code - the code inherits the transparent text-fill from the link */
article a code {
-webkit-text-fill-color: #3396e8 !important;
color: #3396e8 !important;
}
article a:hover code {
-webkit-text-fill-color: #0074d9 !important;
color: #0074d9 !important;
}
article a:not(.button):not([class*="hash-link"]):hover {
text-decoration: underline;
text-decoration-color: var(--hindsight-gradient-start);
+799
View File
@@ -0,0 +1,799 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.4.1, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 1572 273" style="enable-background:new 0 0 1572 273;" xml:space="preserve">
<style type="text/css">
.st0{fill:url(#SVGID_1_);}
.st1{fill:none;stroke:#FFFFFF;stroke-width:3;stroke-miterlimit:10;}
.st2{fill:#FFFFFF;}
.st3{opacity:0.1;clip-path:url(#SVGID_00000129914111459972265670000000360129721314932366_);}
.st4{opacity:0.0163;}
.st5{opacity:0.3419;}
.st6{opacity:0.3053;}
.st7{opacity:0.4947;}
.st8{opacity:0.1716;}
.st9{opacity:0.2827;}
.st10{opacity:0.4396;}
.st11{opacity:0.2191;}
.st12{opacity:0.3687;}
.st13{opacity:0.3264;}
.st14{opacity:0.2876;}
.st15{opacity:0.2448;}
.st16{opacity:0.0105;}
.st17{opacity:0.3395;}
.st18{opacity:0.1932;}
.st19{opacity:0.2467;}
.st20{opacity:0.2535;}
.st21{opacity:0.2581;}
.st22{opacity:0.4273;}
.st23{opacity:0.149;}
.st24{opacity:0.2501;}
.st25{opacity:0.0713;}
.st26{opacity:0.1763;}
.st27{opacity:0.2282;}
.st28{opacity:0.2712;}
.st29{opacity:0.384;}
.st30{opacity:0.4021;}
.st31{opacity:0.2087;}
.st32{opacity:0.42;}
.st33{opacity:0.3495;}
.st34{opacity:0.2778;}
.st35{opacity:0.2694;}
.st36{opacity:0.2895;}
.st37{opacity:0.3209;}
.st38{opacity:0.2074;}
.st39{opacity:0.4718;}
.st40{opacity:0.477;}
.st41{opacity:0.359;}
.st42{opacity:0.3551;}
.st43{opacity:0.2133;}
.st44{opacity:0.1705;}
.st45{opacity:0.3991;}
.st46{opacity:0.4943;}
.st47{opacity:0.2426;}
.st48{opacity:0.5;}
.st49{opacity:0.6;}
.st50{opacity:0.4;}
.st51{opacity:0.3;}
.st52{opacity:0.0838;}
.st53{opacity:0.3084;}
.st54{opacity:0.5;fill:#7C0FEF;}
</style>
<linearGradient id="SVGID_1_" gradientUnits="userSpaceOnUse" x1="0" y1="136.5" x2="1572" y2="136.5">
<stop offset="0" style="stop-color:#009296"/>
<stop offset="0.838" style="stop-color:#0079CE"/>
<stop offset="1" style="stop-color:#0074D9"/>
</linearGradient>
<rect y="-0.63" class="st0" width="1572" height="274.27"/>
<line class="st1" x1="834.29" y1="190.07" x2="834.29" y2="82.93"/>
<g>
<path class="st2" d="M916.92,119.5l13.15-36.13h2.26l13.15,36.13h-2.26l-12.8-35.18h1.5l-12.75,35.18H916.92z M921.94,110.12v-2.01
h18.47v2.01H921.94z"/>
<path class="st2" d="M960.28,120.25c-2.56,0-4.71-0.63-6.46-1.89c-1.75-1.26-3.07-2.98-3.98-5.14c-0.9-2.17-1.35-4.6-1.35-7.31
c0-2.66,0.44-5.07,1.33-7.23c0.89-2.16,2.18-3.87,3.88-5.13c1.7-1.26,3.76-1.89,6.19-1.89c2.53,0,4.65,0.61,6.39,1.84
c1.73,1.23,3.04,2.92,3.93,5.07c0.89,2.15,1.33,4.6,1.33,7.34c0,2.69-0.44,5.12-1.32,7.29c-0.88,2.17-2.15,3.89-3.83,5.16
S962.67,120.25,960.28,120.25z M960.33,132.3c-1.3,0-2.62-0.18-3.94-0.55c-1.32-0.37-2.56-0.99-3.73-1.87
c-1.16-0.88-2.15-2.08-2.97-3.6l1.86-1.25c0.9,1.86,2.17,3.17,3.81,3.95c1.64,0.78,3.29,1.17,4.97,1.17c2.43,0,4.32-0.46,5.68-1.37
c1.36-0.91,2.32-2.27,2.87-4.06c0.55-1.8,0.83-4.04,0.83-6.71v-6.93h0.2V92.4h1.96V118c0,0.82-0.02,1.61-0.05,2.38
c-0.03,0.77-0.1,1.53-0.2,2.28c-0.27,2.19-0.85,4-1.74,5.42c-0.9,1.42-2.13,2.48-3.7,3.17C964.6,131.95,962.66,132.3,960.33,132.3z
M960.28,118.15c2.12,0,3.9-0.54,5.33-1.61c1.43-1.07,2.5-2.53,3.22-4.38c0.72-1.85,1.08-3.94,1.08-6.26
c0-2.36-0.36-4.45-1.09-6.29c-0.73-1.83-1.81-3.27-3.24-4.3c-1.43-1.04-3.2-1.56-5.31-1.56c-2.16,0-3.94,0.53-5.36,1.59
c-1.41,1.06-2.46,2.51-3.15,4.34c-0.69,1.83-1.03,3.9-1.03,6.21c0,2.33,0.36,4.41,1.08,6.26c0.72,1.85,1.79,3.31,3.2,4.38
C956.44,117.61,958.19,118.15,960.28,118.15z"/>
<path class="st2" d="M989.79,120.25c-2.56,0-4.76-0.58-6.61-1.73c-1.85-1.15-3.27-2.8-4.28-4.94s-1.51-4.68-1.51-7.63
c0-2.96,0.5-5.51,1.49-7.65s2.42-3.78,4.27-4.93c1.85-1.15,4.06-1.72,6.64-1.72c2.59,0,4.81,0.59,6.65,1.76
c1.84,1.17,3.25,2.87,4.23,5.09c0.98,2.23,1.47,4.91,1.47,8.05h-2.26v-0.7c-0.1-3.9-1.02-6.89-2.75-8.97
c-1.73-2.08-4.18-3.12-7.34-3.12c-3.21,0-5.7,1.07-7.48,3.2s-2.66,5.13-2.66,9s0.89,6.86,2.66,9s4.27,3.2,7.48,3.2
c2.24,0,4.21-0.53,5.9-1.58c1.69-1.05,3.04-2.57,4.04-4.54l1.76,1c-1.1,2.31-2.67,4.09-4.69,5.34
C994.76,119.63,992.43,120.25,989.79,120.25z M978.75,106.55v-2.11h22.08v2.11H978.75z"/>
<path class="st2" d="M1006.9,119.5V92.4h1.96v5.52h0.15v21.58H1006.9z M1027.02,119.5v-14.35c0-1.94-0.2-3.62-0.59-5.03
c-0.39-1.41-0.97-2.58-1.74-3.51c-0.77-0.93-1.7-1.62-2.8-2.07s-2.35-0.68-3.75-0.68c-1.66,0-3.07,0.29-4.23,0.87
c-1.16,0.58-2.1,1.37-2.82,2.37c-0.72,1-1.25,2.16-1.58,3.46c-0.33,1.3-0.5,2.68-0.5,4.14l-1.96,0.05c0-3.09,0.51-5.59,1.53-7.49
c1.02-1.9,2.37-3.28,4.05-4.15c1.68-0.87,3.52-1.3,5.51-1.3c1.37,0,2.63,0.19,3.78,0.58c1.15,0.38,2.17,0.94,3.06,1.67
c0.89,0.73,1.65,1.62,2.27,2.67c0.62,1.05,1.09,2.25,1.41,3.6c0.32,1.35,0.48,2.82,0.48,4.43v14.75H1027.02z"/>
<path class="st2" d="M1032.64,94.51V92.4h17.01v2.11H1032.64z M1049.66,119.5c-1.36,0.3-2.69,0.41-4.01,0.34s-2.5-0.39-3.54-0.95
c-1.04-0.56-1.82-1.41-2.33-2.55c-0.4-0.89-0.63-1.79-0.68-2.7c-0.05-0.91-0.08-1.95-0.08-3.12V84.88h2.11v25.64
c0,1.17,0.01,2.12,0.04,2.84c0.02,0.72,0.2,1.4,0.51,2.03c0.6,1.2,1.56,1.94,2.86,2.22c1.3,0.28,3.01,0.24,5.12-0.11V119.5z"/>
<path class="st2" d="M1064.71,119.5V83.37h2.01l15.36,33.57l15.21-33.57h2.11v36.08h-2.11V88.44l-14.05,31.06h-2.36l-14.05-31.06
v31.06H1064.71z"/>
<path class="st2" d="M1117.3,120.25c-2.56,0-4.76-0.58-6.61-1.73s-3.27-2.8-4.28-4.94c-1-2.14-1.5-4.68-1.5-7.63
c0-2.96,0.5-5.51,1.49-7.65c0.99-2.14,2.42-3.78,4.26-4.93c1.85-1.15,4.06-1.72,6.64-1.72c2.59,0,4.81,0.59,6.65,1.76
c1.84,1.17,3.25,2.87,4.23,5.09c0.98,2.23,1.47,4.91,1.47,8.05h-2.26v-0.7c-0.1-3.9-1.02-6.89-2.75-8.97
c-1.73-2.08-4.18-3.12-7.34-3.12c-3.21,0-5.7,1.07-7.48,3.2c-1.77,2.13-2.66,5.13-2.66,9s0.89,6.86,2.66,9
c1.77,2.13,4.27,3.2,7.48,3.2c2.24,0,4.21-0.53,5.9-1.58c1.69-1.05,3.04-2.57,4.04-4.54l1.76,1c-1.1,2.31-2.67,4.09-4.69,5.34
C1122.28,119.63,1119.94,120.25,1117.3,120.25z M1106.26,106.55v-2.11h22.08v2.11H1106.26z"/>
<path class="st2" d="M1134.41,119.5V92.4h1.96v5.52h0.15v21.58H1134.41z M1150.52,119.5l0.05-18.32c0-2.34-0.65-4.2-1.94-5.57
c-1.3-1.37-2.97-2.06-5.03-2.06c-2.11,0-3.81,0.72-5.12,2.16c-1.3,1.44-1.96,3.36-1.96,5.77l-1.86-0.8c0-1.74,0.39-3.29,1.18-4.65
c0.79-1.36,1.87-2.43,3.25-3.21s2.96-1.17,4.75-1.17c1.52,0,2.95,0.32,4.29,0.97c1.34,0.64,2.42,1.64,3.25,3
c0.83,1.35,1.24,3.1,1.24,5.22l-0.05,18.67H1150.52z M1166.58,119.5l0.05-18.67c0-2.26-0.66-4.04-1.98-5.33
c-1.32-1.3-2.95-1.94-4.89-1.94c-1.07,0-2.15,0.24-3.25,0.73c-1.1,0.49-2.02,1.3-2.76,2.46s-1.12,2.73-1.12,4.74h-1.86
c-0.08-1.99,0.26-3.72,1.04-5.19c0.78-1.47,1.87-2.61,3.27-3.42s3.01-1.22,4.82-1.22c2.56,0,4.67,0.8,6.34,2.41
c1.66,1.61,2.5,3.81,2.5,6.62l-0.05,18.82H1166.58z"/>
<path class="st2" d="M1186.15,120.25c-2.68,0-4.93-0.61-6.77-1.83c-1.84-1.22-3.24-2.91-4.19-5.07c-0.95-2.16-1.43-4.64-1.43-7.45
c0-2.84,0.48-5.34,1.46-7.48c0.97-2.14,2.38-3.81,4.23-4.99c1.85-1.19,4.09-1.78,6.71-1.78c2.69,0,4.96,0.61,6.8,1.82
s3.23,2.89,4.18,5.03c0.95,2.14,1.42,4.61,1.42,7.4c0,2.86-0.48,5.37-1.43,7.52c-0.95,2.15-2.35,3.83-4.2,5.03
C1191.07,119.65,1188.81,120.25,1186.15,120.25z M1186.15,118.15c3.41,0,5.96-1.13,7.63-3.4c1.67-2.27,2.51-5.21,2.51-8.84
c0-3.7-0.84-6.65-2.52-8.84c-1.68-2.2-4.22-3.3-7.62-3.3c-2.29,0-4.19,0.52-5.68,1.56s-2.61,2.47-3.35,4.29
c-0.74,1.82-1.1,3.92-1.1,6.3c0,3.68,0.86,6.64,2.57,8.88C1180.3,117.03,1182.82,118.15,1186.15,118.15z"/>
<path class="st2" d="M1204.07,119.5V92.4h1.96v6.47l-0.65-0.85c0.28-0.74,0.64-1.42,1.08-2.06c0.43-0.64,0.86-1.15,1.28-1.56
c0.74-0.72,1.61-1.27,2.62-1.64s2.03-0.59,3.05-0.65c1.02-0.06,1.92,0.04,2.71,0.29v2.01c-1.12-0.25-2.31-0.3-3.56-0.14
c-1.25,0.16-2.43,0.74-3.51,1.74c-0.95,0.89-1.63,1.91-2.02,3.06c-0.39,1.15-0.63,2.35-0.71,3.58c-0.08,1.23-0.13,2.4-0.13,3.5
v13.35H1204.07z"/>
<path class="st2" d="M1224.94,131.54l5.27-14.15l0.05,4.22l-11.89-29.21h2.31l10.64,26.3h-1.61l9.54-26.3h2.26l-14.2,39.14H1224.94
z"/>
<path class="st2" d="M1266.54,119.5V85.48h-13.25v-2.11h28.6v2.11h-13.25v34.02H1266.54z"/>
<path class="st2" d="M1285.91,119.5V83.37h1.96v21.33h0.15v14.8H1285.91z M1306.04,119.5v-14.35c0-1.94-0.2-3.62-0.59-5.03
c-0.39-1.41-0.97-2.58-1.74-3.51c-0.77-0.93-1.7-1.62-2.8-2.07s-2.35-0.68-3.75-0.68c-1.66,0-3.07,0.29-4.23,0.87
c-1.16,0.58-2.1,1.37-2.82,2.37c-0.72,1-1.25,2.16-1.58,3.46c-0.33,1.3-0.5,2.68-0.5,4.14l-1.96,0.05c0-3.09,0.51-5.59,1.53-7.49
c1.02-1.9,2.37-3.28,4.05-4.15c1.68-0.87,3.52-1.3,5.51-1.3c1.37,0,2.63,0.19,3.78,0.58c1.15,0.38,2.17,0.94,3.06,1.67
c0.89,0.73,1.65,1.62,2.27,2.67c0.62,1.05,1.09,2.25,1.41,3.6c0.32,1.35,0.48,2.82,0.48,4.43v14.75H1306.04z"/>
<path class="st2" d="M1322.55,120.25c-2.11,0-3.86-0.37-5.24-1.1c-1.39-0.74-2.43-1.71-3.11-2.91c-0.69-1.2-1.03-2.51-1.03-3.91
c0-1.59,0.35-2.91,1.04-3.95c0.69-1.05,1.6-1.87,2.72-2.47s2.33-1.04,3.61-1.3c1.57-0.32,3.26-0.6,5.06-0.84
c1.8-0.24,3.46-0.45,4.98-0.61c1.52-0.17,2.66-0.3,3.41-0.4l-0.75,0.5c0.08-3.19-0.5-5.57-1.74-7.14
c-1.25-1.56-3.44-2.35-6.59-2.35c-2.28,0-4.1,0.51-5.48,1.52s-2.35,2.56-2.9,4.65l-2.31-0.6c0.6-2.51,1.84-4.42,3.7-5.72
c1.87-1.3,4.23-1.96,7.09-1.96c2.51,0,4.6,0.51,6.27,1.53c1.67,1.02,2.81,2.4,3.41,4.14c0.23,0.67,0.4,1.48,0.5,2.43
c0.1,0.95,0.15,1.88,0.15,2.79v16.96h-1.96v-7.43l1,0.05c-0.72,2.58-2.15,4.58-4.29,6
C1327.96,119.54,1325.44,120.25,1322.55,120.25z M1322.45,118.15c1.96,0,3.68-0.35,5.18-1.05c1.5-0.7,2.71-1.72,3.64-3.05
c0.93-1.33,1.52-2.92,1.77-4.78c0.13-0.94,0.2-1.94,0.2-3.01s0-1.84,0-2.31l1.1,0.85c-0.89,0.08-2.11,0.2-3.68,0.34
c-1.56,0.14-3.22,0.33-4.96,0.55c-1.74,0.23-3.31,0.51-4.72,0.87c-0.82,0.2-1.67,0.52-2.53,0.95c-0.87,0.44-1.6,1.05-2.2,1.83
c-0.59,0.79-0.89,1.8-0.89,3.04c0,0.87,0.22,1.75,0.65,2.63c0.44,0.89,1.17,1.63,2.2,2.23
C1319.25,117.84,1320.66,118.15,1322.45,118.15z"/>
<path class="st2" d="M1338.86,94.51V92.4h17.01v2.11H1338.86z M1355.87,119.5c-1.35,0.3-2.69,0.41-4.01,0.34s-2.5-0.39-3.54-0.95
c-1.04-0.56-1.82-1.41-2.33-2.55c-0.4-0.89-0.63-1.79-0.68-2.7c-0.05-0.91-0.08-1.95-0.08-3.12V84.88h2.11v25.64
c0,1.17,0.01,2.12,0.04,2.84c0.03,0.72,0.2,1.4,0.51,2.03c0.6,1.2,1.56,1.94,2.86,2.22c1.3,0.28,3.01,0.24,5.12-0.11V119.5z"/>
<path class="st2" d="M1378.75,119.5l-10.34-36.13h2.16l9.28,32.32l9.23-32.32h2.21l9.28,32.32l9.23-32.32h2.21l-10.34,36.13h-2.21
l-9.28-32.27l-9.23,32.27H1378.75z"/>
<path class="st2" d="M1424.42,120.25c-2.68,0-4.93-0.61-6.77-1.83c-1.84-1.22-3.24-2.91-4.19-5.07c-0.95-2.16-1.43-4.64-1.43-7.45
c0-2.84,0.49-5.34,1.46-7.48c0.97-2.14,2.38-3.81,4.23-4.99c1.85-1.19,4.08-1.78,6.71-1.78c2.69,0,4.96,0.61,6.8,1.82
c1.84,1.21,3.23,2.89,4.18,5.03c0.94,2.14,1.42,4.61,1.42,7.4c0,2.86-0.48,5.37-1.43,7.52s-2.35,3.83-4.2,5.03
C1429.33,119.65,1427.08,120.25,1424.42,120.25z M1424.42,118.15c3.41,0,5.96-1.13,7.63-3.4c1.67-2.27,2.51-5.21,2.51-8.84
c0-3.7-0.84-6.65-2.52-8.84c-1.68-2.2-4.22-3.3-7.62-3.3c-2.29,0-4.19,0.52-5.68,1.56s-2.61,2.47-3.35,4.29s-1.1,3.92-1.1,6.3
c0,3.68,0.86,6.64,2.57,8.88C1418.57,117.03,1421.09,118.15,1424.42,118.15z"/>
<path class="st2" d="M1442.33,119.5V92.4h1.96v6.47l-0.65-0.85c0.28-0.74,0.64-1.42,1.08-2.06s0.86-1.15,1.28-1.56
c0.74-0.72,1.61-1.27,2.62-1.64c1.01-0.38,2.03-0.59,3.05-0.65s1.92,0.04,2.71,0.29v2.01c-1.12-0.25-2.31-0.3-3.56-0.14
c-1.25,0.16-2.43,0.74-3.51,1.74c-0.95,0.89-1.63,1.91-2.02,3.06c-0.39,1.15-0.63,2.35-0.71,3.58s-0.12,2.4-0.12,3.5v13.35H1442.33
z"/>
<path class="st2" d="M1459.14,119.5V83.37h2.11v22.08l13.55-13.05h3.16l-14.15,13.55l16.31,13.55h-3.61l-15.25-13.05v13.05H1459.14
z"/>
<path class="st2" d="M1492.01,120.2c-3.06,0-5.6-0.64-7.63-1.92c-2.02-1.28-3.28-3.05-3.76-5.31l2.16-0.4
c0.45,1.67,1.51,3.01,3.17,4.01c1.66,1,3.7,1.51,6.11,1.51c2.46,0,4.41-0.53,5.86-1.58c1.45-1.05,2.17-2.48,2.17-4.29
c0-0.99-0.22-1.79-0.65-2.42c-0.44-0.63-1.28-1.2-2.55-1.72s-3.12-1.11-5.58-1.78c-2.58-0.7-4.58-1.38-6.01-2.04
c-1.43-0.66-2.43-1.4-3.01-2.23s-0.87-1.84-0.87-3.05c0-1.44,0.43-2.71,1.28-3.81c0.85-1.1,2.03-1.97,3.54-2.58
s3.25-0.93,5.22-0.93c1.99,0,3.79,0.33,5.38,0.99c1.6,0.66,2.88,1.58,3.86,2.76c0.98,1.18,1.54,2.54,1.69,4.08l-2.16,0.4
c-0.32-1.89-1.28-3.38-2.9-4.48s-3.62-1.64-6.03-1.64c-2.26-0.03-4.1,0.43-5.53,1.38c-1.43,0.95-2.15,2.2-2.15,3.74
c0,0.85,0.24,1.58,0.73,2.2c0.49,0.61,1.33,1.17,2.53,1.67c1.2,0.5,2.88,1.02,5.02,1.56c2.71,0.69,4.82,1.38,6.33,2.08
c1.51,0.7,2.58,1.52,3.19,2.46c0.61,0.94,0.92,2.1,0.92,3.49c0,2.46-0.92,4.39-2.76,5.78S1495.22,120.2,1492.01,120.2z"/>
<path class="st2" d="M995.68,179.72v-36.13h2.11v34.02h17.97v2.11H995.68z"/>
<path class="st2" d="M1020.52,146.8v-3.21h2.11v3.21H1020.52z M1020.52,179.72v-27.1h2.11v27.1H1020.52z"/>
<path class="st2" d="M1030.16,179.72v-36.13h2.11v22.08l13.55-13.05h3.16l-14.15,13.55l16.31,13.55h-3.61l-15.25-13.05v13.05
H1030.16z"/>
<path class="st2" d="M1064.03,180.47c-2.56,0-4.76-0.58-6.61-1.73s-3.27-2.8-4.28-4.94c-1-2.14-1.5-4.68-1.5-7.63
c0-2.96,0.5-5.51,1.49-7.65c0.99-2.14,2.42-3.78,4.26-4.93c1.85-1.15,4.06-1.72,6.64-1.72c2.59,0,4.81,0.59,6.65,1.76
s3.25,2.87,4.23,5.09c0.98,2.23,1.47,4.91,1.47,8.05h-2.26v-0.7c-0.1-3.9-1.02-6.89-2.75-8.97c-1.73-2.08-4.18-3.12-7.34-3.12
c-3.21,0-5.7,1.07-7.48,3.2c-1.77,2.13-2.66,5.13-2.66,9c0,3.86,0.89,6.86,2.66,9c1.77,2.13,4.27,3.2,7.48,3.2
c2.24,0,4.21-0.53,5.9-1.58s3.04-2.57,4.04-4.54l1.76,1c-1.1,2.31-2.67,4.09-4.69,5.34
C1069.01,179.85,1066.68,180.47,1064.03,180.47z M1052.99,166.77v-2.11h22.08v2.11H1052.99z"/>
<path class="st2" d="M1091.93,179.72v-36.13h2.11v17.01h21.88v-17.01h2.11v36.13h-2.11v-17.01h-21.88v17.01H1091.93z"/>
<path class="st2" d="M1135.54,180.32c-1.37,0-2.63-0.19-3.78-0.58s-2.17-0.94-3.06-1.67c-0.9-0.73-1.65-1.62-2.27-2.67
c-0.62-1.05-1.09-2.25-1.4-3.6c-0.32-1.35-0.48-2.82-0.48-4.43v-14.75h2.11v14.35c0,1.92,0.2,3.6,0.59,5.02
c0.39,1.42,0.97,2.6,1.74,3.53c0.77,0.93,1.7,1.62,2.8,2.07c1.1,0.45,2.35,0.68,3.75,0.68c1.66,0,3.07-0.29,4.23-0.87
c1.16-0.58,2.1-1.37,2.82-2.37c0.72-1,1.25-2.16,1.58-3.46c0.33-1.3,0.5-2.69,0.5-4.14l1.96-0.05c0,3.09-0.51,5.59-1.53,7.49
c-1.02,1.9-2.37,3.28-4.05,4.15C1139.37,179.89,1137.53,180.32,1135.54,180.32z M1144.83,179.72v-5.52h-0.15v-21.58h2.11v27.1
H1144.83z"/>
<path class="st2" d="M1153.81,179.72v-27.1h1.96v5.52h0.15v21.58H1153.81z M1169.92,179.72l0.05-18.32c0-2.34-0.65-4.2-1.95-5.57
c-1.3-1.37-2.97-2.06-5.03-2.06c-2.11,0-3.81,0.72-5.12,2.16c-1.3,1.44-1.96,3.36-1.96,5.77l-1.86-0.8c0-1.74,0.39-3.29,1.18-4.65
s1.87-2.43,3.25-3.21c1.38-0.78,2.96-1.17,4.75-1.17c1.52,0,2.95,0.32,4.29,0.97c1.34,0.64,2.42,1.64,3.25,3
c0.83,1.35,1.24,3.09,1.24,5.22l-0.05,18.67H1169.92z M1185.98,179.72l0.05-18.67c0-2.26-0.66-4.04-1.98-5.33
c-1.32-1.3-2.95-1.94-4.89-1.94c-1.07,0-2.15,0.24-3.25,0.73s-2.02,1.3-2.76,2.46c-0.75,1.15-1.12,2.74-1.12,4.74h-1.86
c-0.08-1.99,0.26-3.72,1.04-5.19c0.78-1.47,1.87-2.61,3.27-3.42c1.41-0.81,3.01-1.22,4.82-1.22c2.56,0,4.67,0.8,6.33,2.41
c1.66,1.61,2.5,3.81,2.5,6.62l-0.05,18.82H1185.98z"/>
<path class="st2" d="M1202.54,180.47c-2.11,0-3.86-0.37-5.24-1.1c-1.39-0.74-2.43-1.71-3.11-2.91c-0.69-1.2-1.03-2.51-1.03-3.91
c0-1.59,0.35-2.91,1.04-3.95c0.69-1.04,1.6-1.87,2.72-2.47s2.33-1.04,3.61-1.3c1.57-0.32,3.26-0.6,5.06-0.84
c1.8-0.24,3.46-0.45,4.98-0.61c1.52-0.17,2.66-0.3,3.41-0.4l-0.75,0.5c0.08-3.2-0.5-5.57-1.74-7.14s-3.44-2.35-6.59-2.35
c-2.28,0-4.1,0.51-5.48,1.52s-2.35,2.56-2.9,4.65l-2.31-0.6c0.6-2.51,1.84-4.42,3.7-5.72s4.23-1.96,7.09-1.96
c2.51,0,4.6,0.51,6.27,1.53c1.67,1.02,2.81,2.4,3.41,4.14c0.23,0.67,0.4,1.48,0.5,2.43c0.1,0.95,0.15,1.88,0.15,2.79v16.96h-1.96
v-7.43l1,0.05c-0.72,2.58-2.15,4.58-4.29,6C1207.95,179.76,1205.43,180.47,1202.54,180.47z M1202.44,178.37
c1.96,0,3.68-0.35,5.18-1.05c1.5-0.7,2.71-1.72,3.64-3.05c0.93-1.33,1.52-2.92,1.77-4.78c0.13-0.94,0.2-1.94,0.2-3.01
s0-1.84,0-2.31l1.1,0.85c-0.89,0.08-2.11,0.2-3.68,0.34c-1.56,0.14-3.22,0.33-4.96,0.55c-1.74,0.23-3.31,0.51-4.72,0.87
c-0.82,0.2-1.67,0.52-2.53,0.95c-0.87,0.44-1.6,1.05-2.2,1.83s-0.89,1.8-0.89,3.04c0,0.87,0.22,1.75,0.65,2.63
c0.44,0.89,1.17,1.63,2.2,2.23C1199.24,178.06,1200.65,178.37,1202.44,178.37z"/>
<path class="st2" d="M1221.86,179.72v-27.1h1.96v5.52h0.15v21.58H1221.86z M1241.98,179.72v-14.35c0-1.94-0.2-3.62-0.59-5.03
c-0.39-1.41-0.97-2.58-1.74-3.51c-0.77-0.93-1.7-1.62-2.8-2.07c-1.1-0.45-2.35-0.68-3.75-0.68c-1.66,0-3.07,0.29-4.23,0.87
c-1.16,0.58-2.1,1.37-2.82,2.37c-0.72,1-1.25,2.16-1.58,3.46c-0.33,1.3-0.5,2.69-0.5,4.14l-1.96,0.05c0-3.09,0.51-5.59,1.53-7.49
c1.02-1.9,2.37-3.28,4.05-4.15c1.68-0.87,3.52-1.3,5.51-1.3c1.37,0,2.63,0.19,3.78,0.58c1.15,0.38,2.17,0.94,3.06,1.67
c0.89,0.73,1.65,1.62,2.27,2.67c0.62,1.05,1.09,2.25,1.41,3.6c0.32,1.35,0.48,2.82,0.48,4.43v14.75H1241.98z"/>
<path class="st2" d="M1260.65,179.72v-36.13h2.01l15.36,33.57l15.21-33.57h2.11v36.08h-2.11v-31.01l-14.05,31.06h-2.36
l-14.05-31.06v31.06H1260.65z"/>
<path class="st2" d="M1313.24,180.47c-2.56,0-4.76-0.58-6.61-1.73c-1.85-1.15-3.27-2.8-4.28-4.94c-1-2.14-1.51-4.68-1.51-7.63
c0-2.96,0.5-5.51,1.49-7.65c1-2.14,2.42-3.78,4.27-4.93c1.85-1.15,4.06-1.72,6.64-1.72c2.59,0,4.81,0.59,6.65,1.76
c1.84,1.17,3.25,2.87,4.23,5.09c0.98,2.23,1.47,4.91,1.47,8.05h-2.26v-0.7c-0.1-3.9-1.02-6.89-2.75-8.97
c-1.73-2.08-4.18-3.12-7.34-3.12c-3.21,0-5.7,1.07-7.48,3.2s-2.66,5.13-2.66,9c0,3.86,0.89,6.86,2.66,9s4.27,3.2,7.48,3.2
c2.24,0,4.21-0.53,5.9-1.58s3.04-2.57,4.04-4.54l1.76,1c-1.1,2.31-2.67,4.09-4.69,5.34
C1318.21,179.85,1315.88,180.47,1313.24,180.47z M1302.2,166.77v-2.11h22.08v2.11H1302.2z"/>
<path class="st2" d="M1330.35,179.72v-27.1h1.96v5.52h0.15v21.58H1330.35z M1346.46,179.72l0.05-18.32c0-2.34-0.65-4.2-1.94-5.57
c-1.3-1.37-2.97-2.06-5.03-2.06c-2.11,0-3.81,0.72-5.12,2.16c-1.3,1.44-1.96,3.36-1.96,5.77l-1.86-0.8c0-1.74,0.39-3.29,1.18-4.65
s1.87-2.43,3.25-3.21c1.38-0.78,2.96-1.17,4.75-1.17c1.52,0,2.95,0.32,4.29,0.97c1.34,0.64,2.42,1.64,3.25,3
c0.83,1.35,1.24,3.09,1.24,5.22l-0.05,18.67H1346.46z M1362.52,179.72l0.05-18.67c0-2.26-0.66-4.04-1.98-5.33
c-1.32-1.3-2.95-1.94-4.89-1.94c-1.07,0-2.15,0.24-3.25,0.73c-1.1,0.49-2.02,1.3-2.76,2.46s-1.12,2.74-1.12,4.74h-1.86
c-0.08-1.99,0.26-3.72,1.04-5.19c0.78-1.47,1.87-2.61,3.27-3.42c1.41-0.81,3.01-1.22,4.82-1.22c2.56,0,4.67,0.8,6.34,2.41
c1.66,1.61,2.5,3.81,2.5,6.62l-0.05,18.82H1362.52z"/>
<path class="st2" d="M1382.09,180.47c-2.68,0-4.93-0.61-6.77-1.83s-3.24-2.91-4.19-5.07c-0.95-2.16-1.43-4.64-1.43-7.45
c0-2.84,0.48-5.34,1.46-7.48c0.97-2.14,2.38-3.8,4.23-4.99c1.85-1.19,4.09-1.78,6.71-1.78c2.69,0,4.96,0.61,6.8,1.82
s3.23,2.89,4.18,5.03c0.95,2.14,1.42,4.61,1.42,7.4c0,2.86-0.48,5.37-1.43,7.51c-0.95,2.15-2.35,3.83-4.2,5.03
C1387,179.87,1384.75,180.47,1382.09,180.47z M1382.09,178.37c3.41,0,5.96-1.13,7.63-3.4s2.51-5.21,2.51-8.84
c0-3.7-0.84-6.64-2.52-8.84c-1.68-2.2-4.22-3.3-7.62-3.3c-2.29,0-4.19,0.52-5.68,1.56c-1.5,1.04-2.61,2.47-3.35,4.29
c-0.74,1.82-1.1,3.92-1.1,6.3c0,3.68,0.86,6.64,2.57,8.88C1376.24,177.25,1378.76,178.37,1382.09,178.37z"/>
<path class="st2" d="M1400,179.72v-27.1h1.96v6.47l-0.65-0.85c0.28-0.74,0.64-1.42,1.08-2.06c0.43-0.63,0.86-1.15,1.28-1.56
c0.74-0.72,1.61-1.27,2.62-1.64c1.01-0.38,2.03-0.59,3.05-0.65c1.02-0.06,1.92,0.04,2.71,0.29v2.01c-1.12-0.25-2.31-0.3-3.56-0.14
c-1.25,0.16-2.43,0.74-3.51,1.74c-0.95,0.89-1.63,1.91-2.02,3.06c-0.39,1.15-0.63,2.35-0.71,3.58c-0.08,1.23-0.13,2.4-0.13,3.5
v13.35H1400z"/>
<path class="st2" d="M1420.88,191.76l5.27-14.15l0.05,4.21l-11.89-29.21h2.31l10.64,26.3h-1.61l9.54-26.3h2.26l-14.2,39.14H1420.88
z"/>
</g>
<g>
<g>
<path class="st2" d="M283.59,142.33c0.82-1.5,3.64-2.46,5.65-2.69c9.56-1.09,15.67-9.18,14.1-19.11
c-1.47-9.32-10.16-14.89-19.51-12.51c-8.51,2.18-12.43,8.07-12.08,18.17c0.24,6.71-4.3,14.03-10.37,15.67
c-2.06,0.55-5.57,0.21-6.7-1.15c-3.56-4.27-6.29-9.22-9.44-14.06c7.79-7.12,13.73-15.34,16.46-25.47
c0.92-3.42,2.06-5.36,5.97-6.43c8.68-2.37,13.02-12.08,10.05-20.68c-2.75-7.95-12.56-12.68-20.56-9.9
c-8.49,2.94-13.12,11.83-9.53,20.25c2.04,4.77,1.98,9.27-0.42,12.91c-3.91,5.94-8.99,11.13-13.67,16.55
c-1.9,2.22-3.91,2.1-6.71,0.89c-14.49-6.28-29.48-7.49-44.02-0.96c-5.69,2.55-9.09,1.21-12.8-2.32c-2.23-2.13-4.63-4.26-6.27-6.82
c-4.04-6.27-7.51-12.31-4.17-20.72s-2.32-17.63-10.54-19.97c-8.32-2.37-17.64,2.66-20.03,10.81c-2.61,8.84,2.06,17.34,11.26,19.85
c2.92,0.79,3.96,2.22,4.58,5.04c1.94,8.74,6.24,16.25,12.77,22.45c1.53,1.47,2.92,3.09,4.32,4.58c-2.91,4.34-6.09,8.01-8.03,12.24
c-2.45,5.36-5.92,4.66-9.69,2.55c-6.78-3.83-9.86-9.57-9.31-17.65c0.61-9.23-6.21-16.17-15.25-16.44
c-8.8-0.26-16.23,6.72-16.47,15.49c-0.25,8.95,6.31,16.16,15.46,16.28c3.21,0.03,4.35,1.38,5.57,3.85
c3.71,7.54,9.51,12.78,17.65,15.3c1.98,0.61,3.91,1.43,6.79,2.51c-3.46,5.27-6.39,10.04-9.63,14.6c-2.33,3.29-5.42,3.99-9.54,2.88
c-9.28-2.48-17.6,2.39-20.06,11.18c-2.2,7.94,2.49,16.76,10.26,19.26c8.83,2.83,16.84-1.33,20.49-10.61
c0.58-1.47,1.21-3.1,2.32-4.15c4.19-3.96,8.58-7.7,12.86-11.5c24.89,36.49,73.84,32.67,96.09-0.54c3.15,3.01,6.53,5.78,9.35,9.05
c2.75,3.19,5.07,6.78,7.3,10.38c4.53,7.31,13.1,10.18,20.9,6.77c7.1-3.1,10.91-11.7,8.52-19.25c-2.39-7.59-11.2-13.45-18.99-11.05
c-6.36,1.96-9.73-0.57-12.79-4.99c-2.67-3.85-4.95-7.97-7.56-12.23c1.52-0.55,2.34-0.91,3.21-1.13
C271.3,157.02,278.65,151.38,283.59,142.33z M287.62,114.55c5.21-0.02,8.86,3.3,8.96,8.17c0.12,5.18-3.12,8.84-8,9.07
c-5.25,0.24-9.1-3.28-9.22-8.42C279.26,118.6,283.03,114.56,287.62,114.55z M262.44,70.74c4.96-0.13,8.97,3.49,9.1,8.19
c0.13,4.96-3.84,9.34-8.59,9.49c-4.65,0.14-9.03-4.18-9.15-9.04C253.7,74.62,257.44,70.86,262.44,70.74z M144.09,87.8
c-4.8-0.05-8.7-3.91-8.72-8.62c-0.03-4.69,3.92-8.52,8.8-8.55c5.05-0.01,8.69,3.62,8.56,8.56
C152.58,84.26,148.97,87.86,144.09,87.8z M118.94,131.61c-5.23,0.11-8.86-3.21-8.92-8.16c-0.05-4.79,4.22-9.11,9.02-9.1
c4.42,0.01,8.25,3.91,8.3,8.42C127.38,127.68,123.75,131.51,118.94,131.61z M124.96,202.12c-5.13,0.23-8.73-3.11-8.85-8.21
c-0.12-5.08,3.38-8.76,8.32-8.75c4.56,0.02,8.32,3.71,8.42,8.26C132.95,198.19,129.58,201.91,124.96,202.12z M237.19,162.84
c-8.1,11.67-19.86,16.43-32.82,17.11c-14.48-0.66-25.81-5.71-34.32-16.72c-2.43-3.13-2.41-5.44,0.05-8.52
c17.66-22.19,51.63-21.27,67.44,2.11C238.46,158.18,238.2,161.38,237.19,162.84z M282.26,185.08c4.85-0.03,8.73,3.77,8.73,8.58
c0,4.88-3.87,8.71-8.72,8.6c-4.85-0.11-8.49-3.98-8.39-8.91C273.97,188.65,277.54,185.12,282.26,185.08z"/>
<path class="st2" d="M212.76,171.11c-5.31,4.28-13.32,4.22-18.65-0.13c-5.67-4.63-7.02-12.7-3.21-19.18
c3.69-6.26,10.56-9,17.81-6.53c-4.14,3.5-5.56,7.18-1.64,10.95c3.48,3.36,6.6,1.42,9.27-1.62
C219.24,160.01,217.62,167.2,212.76,171.11z"/>
<path class="st2" d="M263.24,75.51c-2.8-0.18-4.86,2.16-4.65,4.26c0.2,1.96,2.41,3.76,4.98,3.34c1.76-0.36,3.06-1.81,3.19-3.45
C266.92,77.7,265.41,75.81,263.24,75.51z M264.53,78.18c-0.38,0-0.69-0.32-0.69-0.7c0-0.38,0.31-0.7,0.69-0.7
c0.39,0,0.7,0.32,0.7,0.7C265.23,77.87,264.93,78.18,264.53,78.18z"/>
<path class="st2" d="M116.96,119.24c-1.65,0.7-2.64,2.4-2.43,4.12c0.19,1.6,1.37,2.94,2.97,3.37c3.12,0.07,5.33-1.99,5.37-3.69
C122.9,121.22,120.43,118.84,116.96,119.24z M117.99,121.1c-0.38,0-0.7-0.31-0.7-0.69c0-0.38,0.32-0.7,0.7-0.7
c0.38,0,0.7,0.32,0.7,0.7C118.69,120.79,118.37,121.1,117.99,121.1z"/>
<path class="st2" d="M289.45,119.63c-3.11-0.38-5.39,1.83-5.36,3.6c0.02,1.71,2.2,3.75,5.15,3.5c1.48-0.48,2.52-1.82,2.61-3.35
C291.95,121.76,290.98,120.24,289.45,119.63z M290.73,123.54c-0.38,0-0.7-0.31-0.7-0.7c0-0.38,0.32-0.69,0.7-0.69
c0.38,0,0.7,0.31,0.7,0.69C291.43,123.23,291.11,123.54,290.73,123.54z"/>
<path class="st2" d="M142.88,75.67c-1.78,0.24-3.13,1.67-3.23,3.3c-0.12,1.89,1.46,3.69,3.57,3.8c3.11,0.21,5.3-2.01,5.24-3.73
C148.4,77.3,146.02,75.19,142.88,75.67z M141.54,78.28c-0.38,0-0.69-0.31-0.69-0.7c0-0.38,0.31-0.69,0.69-0.69
c0.39,0,0.7,0.31,0.7,0.69C142.24,77.98,141.94,78.28,141.54,78.28z"/>
<path class="st2" d="M283,190.25c-2.23-0.35-4.1,1.32-4.17,3.06c-0.07,1.77,1.77,3.6,4.07,3.33c1.7-0.04,3.07-1.42,3.12-3.11
C286.08,191.83,284.73,190.36,283,190.25z M284.58,193.08c-0.39,0-0.7-0.31-0.7-0.69c0-0.39,0.31-0.7,0.7-0.7
c0.38,0,0.69,0.31,0.69,0.7C285.27,192.77,284.96,193.08,284.58,193.08z"/>
<path class="st2" d="M122.37,190.01c-1.72,0.68-2.72,2.42-2.46,4.14c0.23,1.51,1.4,2.75,2.94,3.11c2.55,0.09,4.46-1.72,4.55-3.44
C127.5,191.9,125.31,189.65,122.37,190.01z M123.63,191.91c-0.38,0-0.69-0.31-0.69-0.7c0-0.38,0.31-0.69,0.69-0.69
c0.39,0,0.7,0.31,0.7,0.69C124.33,191.6,124.03,191.91,123.63,191.91z"/>
</g>
<g>
<path class="st2" d="M383.47,127.79v49.7h-9.97v-21.15h-21.29v21.15h-9.97v-49.7h9.97v20.44h21.29v-20.44H383.47z"/>
<path class="st2" d="M393.97,131.68c-1.16-1.11-1.74-2.5-1.74-4.17c0-1.66,0.58-3.05,1.74-4.17c1.16-1.11,2.62-1.67,4.38-1.67
c1.76,0,3.22,0.56,4.38,1.67c1.16,1.12,1.74,2.5,1.74,4.17c0,1.66-0.58,3.05-1.74,4.17c-1.16,1.12-2.62,1.67-4.38,1.67
C396.59,133.35,395.13,132.79,393.97,131.68z"/>
<path class="st2" d="M547.84,131.68c-1.16-1.11-1.74-2.5-1.74-4.17c0-1.66,0.58-3.05,1.74-4.17c1.16-1.11,2.62-1.67,4.38-1.67
c1.76,0,3.22,0.56,4.38,1.67c1.16,1.12,1.74,2.5,1.74,4.17c0,1.66-0.58,3.05-1.74,4.17c-1.16,1.12-2.62,1.67-4.38,1.67
C550.46,133.35,549,132.79,547.84,131.68z"/>
<rect x="393.3" y="138.05" class="st2" width="9.97" height="39.45"/>
<path class="st2" d="M446.34,141.93c2.89,2.97,4.34,7.11,4.34,12.42v23.14h-9.97v-21.79c0-3.13-0.78-5.54-2.35-7.23
c-1.57-1.68-3.7-2.53-6.41-2.53c-2.75,0-4.93,0.84-6.52,2.53c-1.59,1.69-2.39,4.09-2.39,7.23v21.79h-9.97v-39.45h9.97v4.91
c1.33-1.71,3.03-3.05,5.09-4.02c2.06-0.97,4.33-1.46,6.8-1.46C439.65,137.48,443.45,138.96,446.34,141.93z"/>
<path class="st2" d="M459.98,147.02c1.59-3.09,3.76-5.46,6.51-7.12c2.75-1.66,5.81-2.49,9.19-2.49c2.56,0,5.01,0.56,7.33,1.67
c2.33,1.12,4.18,2.6,5.55,4.45V124.8h10.11v52.69h-10.11v-5.84c-1.23,1.95-2.97,3.51-5.2,4.7c-2.23,1.19-4.82,1.78-7.76,1.78
c-3.32,0-6.36-0.85-9.11-2.56c-2.75-1.71-4.93-4.12-6.51-7.23c-1.59-3.11-2.39-6.68-2.39-10.72
C457.59,153.64,458.39,150.11,459.98,147.02z M487.21,151.54c-0.95-1.73-2.23-3.06-3.84-3.99c-1.61-0.93-3.35-1.39-5.2-1.39
c-1.85,0-3.56,0.45-5.13,1.35c-1.57,0.9-2.84,2.22-3.81,3.95c-0.97,1.73-1.46,3.79-1.46,6.16c0,2.37,0.49,4.45,1.46,6.23
c0.97,1.78,2.25,3.15,3.84,4.09c1.59,0.95,3.29,1.42,5.09,1.42c1.85,0,3.58-0.46,5.2-1.39c1.61-0.93,2.89-2.25,3.84-3.99
c0.95-1.73,1.42-3.81,1.42-6.23C488.64,155.35,488.16,153.27,487.21,151.54z"/>
<path class="st2" d="M514.84,176.39c-2.56-1.16-4.59-2.74-6.09-4.73c-1.5-1.99-2.31-4.2-2.46-6.62h10.04
c0.19,1.52,0.94,2.78,2.24,3.77c1.31,1,2.93,1.5,4.88,1.5c1.9,0,3.38-0.38,4.45-1.14c1.07-0.76,1.6-1.73,1.6-2.92
c0-1.28-0.65-2.24-1.96-2.88c-1.31-0.64-3.38-1.34-6.23-2.1c-2.94-0.71-5.35-1.45-7.23-2.21c-1.88-0.76-3.49-1.92-4.84-3.49
c-1.35-1.57-2.03-3.68-2.03-6.34c0-2.18,0.63-4.18,1.89-5.98c1.26-1.8,3.06-3.23,5.41-4.27c2.35-1.04,5.11-1.57,8.3-1.57
c4.7,0,8.45,1.17,11.25,3.52c2.8,2.35,4.34,5.52,4.63,9.51h-9.54c-0.14-1.57-0.8-2.81-1.96-3.74c-1.16-0.93-2.72-1.39-4.66-1.39
c-1.8,0-3.19,0.33-4.17,1c-0.97,0.66-1.46,1.59-1.46,2.78c0,1.33,0.66,2.34,1.99,3.03c1.33,0.69,3.39,1.39,6.19,2.1
c2.85,0.71,5.2,1.45,7.05,2.21c1.85,0.76,3.45,1.93,4.81,3.52c1.35,1.59,2.05,3.69,2.1,6.3c0,2.28-0.63,4.32-1.89,6.12
c-1.26,1.8-3.06,3.22-5.41,4.24c-2.35,1.02-5.09,1.53-8.22,1.53C520.3,178.13,517.4,177.55,514.84,176.39z"/>
<rect x="547.23" y="138.05" class="st2" width="9.97" height="39.45"/>
<path class="st2" d="M590.24,139.15c2.23,1.16,3.99,2.67,5.27,4.52v-5.62h10.04v39.73c0,3.65-0.74,6.92-2.21,9.79
c-1.47,2.87-3.68,5.15-6.62,6.84c-2.94,1.68-6.5,2.53-10.68,2.53c-5.6,0-10.19-1.31-13.78-3.92c-3.58-2.61-5.61-6.17-6.09-10.68
h9.9c0.52,1.8,1.65,3.24,3.38,4.31c1.73,1.07,3.83,1.6,6.3,1.6c2.89,0,5.24-0.87,7.05-2.6c1.8-1.73,2.71-4.36,2.71-7.87v-6.12
c-1.28,1.85-3.05,3.39-5.3,4.63c-2.26,1.23-4.83,1.85-7.73,1.85c-3.32,0-6.36-0.85-9.11-2.56c-2.75-1.71-4.93-4.12-6.52-7.23
c-1.59-3.11-2.39-6.68-2.39-10.72c0-3.99,0.79-7.52,2.39-10.61c1.59-3.09,3.75-5.46,6.48-7.12c2.73-1.66,5.78-2.49,9.15-2.49
C585.42,137.41,588.01,137.99,590.24,139.15z M594.09,151.54c-0.95-1.73-2.23-3.06-3.85-3.99c-1.61-0.93-3.35-1.39-5.2-1.39
c-1.85,0-3.56,0.45-5.13,1.35c-1.57,0.9-2.84,2.22-3.81,3.95c-0.97,1.73-1.46,3.79-1.46,6.16c0,2.37,0.49,4.45,1.46,6.23
c0.97,1.78,2.25,3.15,3.85,4.09c1.59,0.95,3.29,1.42,5.09,1.42c1.85,0,3.58-0.46,5.2-1.39c1.61-0.93,2.89-2.25,3.85-3.99
c0.95-1.73,1.42-3.81,1.42-6.23C595.51,155.35,595.03,153.27,594.09,151.54z"/>
<path class="st2" d="M645.49,139.44c2.33,1.31,4.14,3.23,5.45,5.77c1.31,2.54,1.96,5.59,1.96,9.15v23.14h-9.97v-21.79
c0-3.13-0.78-5.54-2.35-7.23c-1.57-1.68-3.7-2.53-6.41-2.53c-2.75,0-4.93,0.84-6.52,2.53c-1.59,1.69-2.39,4.09-2.39,7.23v21.79
h-9.97V124.8h9.97v18.16c1.28-1.71,2.99-3.05,5.13-4.02c2.14-0.97,4.51-1.46,7.12-1.46C640.51,137.48,643.17,138.13,645.49,139.44
z"/>
<path class="st2" d="M673.97,146.24v19.08c0,1.33,0.32,2.29,0.96,2.88c0.64,0.59,1.72,0.89,3.24,0.89h4.63v8.4h-6.27
c-8.4,0-12.6-4.08-12.6-12.25v-19.01h-4.7v-8.19h4.7v-9.75h10.04v9.75h8.83v8.19H673.97z"/>
</g>
</g>
<g>
<defs>
<rect id="SVGID_00000142868261346849394960000000696206683628523147_" y="-0.63" width="1572" height="274.27"/>
</defs>
<clipPath id="SVGID_00000022529371134204594770000016760592095366508674_">
<use xlink:href="#SVGID_00000142868261346849394960000000696206683628523147_" style="overflow:visible;"/>
</clipPath>
<g style="opacity:0.1;clip-path:url(#SVGID_00000022529371134204594770000016760592095366508674_);">
<g>
<g>
<polygon class="st4" points="1223.46,207.5 1398.13,271.54 1221.09,290.75 "/>
<g class="st5">
<path d="M1150.25,94.8c-0.06-0.14-0.2-0.24-0.36-0.25c-0.24-0.02-0.45,0.16-0.47,0.4l11.38,97.26
c-0.02,0.24,0.16,0.45,0.4,0.47c0.24,0.02,0.45-0.16,0.47-0.4l-11.38-97.26C1150.29,94.95,1150.28,94.87,1150.25,94.8z"/>
</g>
<g class="st6">
<path d="M1250.24,31.89c-0.09-0.2-0.32-0.3-0.54-0.23l-122,142.47c-0.23,0.08-0.35,0.33-0.28,0.56
c0.07,0.23,0.33,0.35,0.56,0.28l122-142.47c0.23-0.08,0.35-0.33,0.28-0.56C1250.25,31.92,1250.25,31.91,1250.24,31.89z"/>
</g>
<g class="st7">
<path d="M1250.24,31.89c-0.08-0.17-0.26-0.27-0.45-0.25l-99.99,62.91c-0.24,0.03-0.41,0.25-0.38,0.49
c0.03,0.24,0.25,0.41,0.49,0.38l99.99-62.91c0.24-0.03,0.41-0.25,0.38-0.49C1250.27,31.98,1250.26,31.94,1250.24,31.89z"/>
</g>
<g class="st8">
<path d="M1186.09,266.15c-0.08-0.17-0.25-0.27-0.45-0.25c-0.24,0.03-0.42,0.25-0.39,0.49l-18.15,56.38
c0.03,0.24,0.24,0.42,0.49,0.39c0.24-0.03,0.41-0.24,0.39-0.49l18.15-56.38C1186.12,266.24,1186.11,266.19,1186.09,266.15z"/>
</g>
<g class="st9">
<path d="M1186.09,266.15c-0.1-0.21-0.35-0.31-0.56-0.22c-0.23,0.09-0.33,0.35-0.24,0.57l11.33,96.24
c0.09,0.23,0.35,0.33,0.57,0.24c0.23-0.09,0.33-0.35,0.24-0.57l-11.33-96.24C1186.1,266.16,1186.09,266.16,1186.09,266.15z"/>
</g>
<g class="st10">
<path d="M1302.41,175.25c-0.04-0.08-0.1-0.15-0.18-0.19L1250.07,31.7c-0.21-0.12-0.48-0.05-0.6,0.16
c-0.12,0.21-0.05,0.48,0.16,0.6l52.17,143.35c0.21,0.12,0.48,0.05,0.6-0.16C1302.47,175.53,1302.47,175.37,1302.41,175.25z"/>
</g>
<g class="st11">
<path d="M1209.47,165.87c-0.1-0.22-0.36-0.31-0.58-0.21l-47.85,26.2c-0.22,0.1-0.32,0.36-0.22,0.58l0,0
c0.1,0.22,0.36,0.31,0.58,0.21l47.85-26.2C1209.48,166.35,1209.58,166.09,1209.47,165.87L1209.47,165.87z"/>
</g>
<g class="st12">
<path d="M1186.09,266.15c-0.01-0.01-0.01-0.02-0.02-0.03l-16.16-36.38c-0.12-0.21-0.39-0.28-0.6-0.16
c-0.21,0.12-0.26,0.4-0.16,0.6l16.16,36.38c0.12,0.21,0.39,0.28,0.6,0.16C1186.11,266.6,1186.19,266.35,1186.09,266.15z"/>
</g>
<g class="st13">
<path d="M1186.09,266.15c-0.03-0.05-0.06-0.1-0.11-0.15l-40.24-34.93c-0.18-0.16-0.46-0.14-0.62,0.04
c-0.16,0.18-0.14,0.46,0.04,0.62l40.24,34.93c0.18,0.16,0.46,0.14,0.62-0.04C1186.14,266.49,1186.16,266.3,1186.09,266.15z"/>
</g>
<g class="st14">
<path d="M1209.47,165.87c-0.04-0.08-0.1-0.15-0.18-0.2c-0.21-0.12-0.48-0.04-0.6,0.17l-23.38,100.28
c-0.12,0.21-0.04,0.48,0.17,0.6c0.21,0.12,0.48,0.04,0.6-0.17l23.38-100.28C1209.53,166.14,1209.53,165.99,1209.47,165.87z"/>
</g>
<g class="st15">
<path d="M1197.42,362.39c-0.07-0.16-0.24-0.26-0.42-0.25c-0.24,0.01-0.43,0.22-0.42,0.46l24.41-21.21
c0.01,0.24,0.22,0.43,0.46,0.42c0.24-0.01,0.43-0.22,0.42-0.46l-24.41,21.21C1197.46,362.5,1197.44,362.44,1197.42,362.39z"/>
</g>
<g class="st16">
<path d="M1302.41,175.25c0-0.01,0-0.01-0.01-0.02c-0.11-0.22-0.38-0.3-0.59-0.19l-132.48,54.53c-0.22,0.11-0.27,0.38-0.19,0.59
c0.11,0.22,0.38,0.3,0.59,0.19l132.48-54.53C1302.43,175.71,1302.51,175.46,1302.41,175.25z"/>
</g>
<g class="st17">
<path d="M1302.41,175.25c-0.01-0.01-0.01-0.02-0.02-0.04c-0.12-0.21-0.39-0.28-0.6-0.16l-92.94-9.38
c-0.21,0.12-0.28,0.38-0.16,0.6c0.12,0.21,0.39,0.28,0.6,0.16l92.94,9.38C1302.43,175.7,1302.51,175.45,1302.41,175.25z"/>
</g>
<g class="st18">
<path d="M1299.37,64.28c-0.03-0.06-0.07-0.11-0.13-0.16c-0.19-0.15-0.47-0.12-0.62,0.08l3.04,110.97
c-0.15,0.19-0.11,0.47,0.08,0.62c0.19,0.15,0.47,0.12,0.62-0.08l-3.04-110.97C1299.42,64.6,1299.44,64.42,1299.37,64.28z"/>
</g>
<g class="st19">
<path d="M1299.37,64.28c-0.02-0.03-0.04-0.07-0.06-0.1c-0.16-0.18-0.44-0.21-0.62-0.05l-89.89,101.59
c-0.18,0.16-0.2,0.43-0.05,0.62c0.16,0.18,0.44,0.21,0.62,0.05l89.89-101.59C1299.41,64.67,1299.45,64.46,1299.37,64.28z"/>
</g>
<g class="st20">
<path d="M1339.23,159.8c-0.09-0.2-0.33-0.3-0.54-0.23l-129.76,6.07c-0.23,0.08-0.35,0.33-0.27,0.56
c0.06,0.22,0.33,0.35,0.56,0.27l129.76-6.07c0.23-0.08,0.35-0.33,0.27-0.56C1339.25,159.83,1339.24,159.81,1339.23,159.8z"/>
</g>
<g class="st21">
<path d="M1315.89,430.57c-0.08-0.17-0.27-0.28-0.46-0.25l-94.06-89.4c-0.24,0.04-0.4,0.26-0.37,0.5
c0.04,0.24,0.26,0.4,0.5,0.37l94.06,89.4c0.24-0.04,0.41-0.26,0.37-0.5C1315.92,430.65,1315.91,430.61,1315.89,430.57z"/>
</g>
<g class="st22">
<path d="M1414.38-19.24c-0.02-0.05-0.05-0.09-0.1-0.13c-0.18-0.17-0.45-0.16-0.62,0.02l-75.14,179.04
c-0.17,0.18-0.16,0.45,0.02,0.62c0.18,0.17,0.45,0.16,0.62-0.02l75.14-179.04C1414.42-18.88,1414.45-19.08,1414.38-19.24z"/>
</g>
<g class="st23">
<path d="M1339.23,159.8c-0.01-0.02-0.02-0.04-0.03-0.06c-0.14-0.2-0.41-0.25-0.61-0.12l-115.38,47.51
c-0.2,0.14-0.25,0.41-0.12,0.61c0.14,0.2,0.41,0.25,0.61,0.12l115.38-47.51C1339.26,160.23,1339.32,159.99,1339.23,159.8z"/>
</g>
<g class="st24">
<path d="M1570.13,127.23c-0.08-0.17-0.27-0.28-0.47-0.25L1298.9,64.03c-0.24,0.04-0.4,0.26-0.36,0.5
c0.04,0.24,0.26,0.4,0.5,0.36l270.76,62.95c0.24-0.04,0.4-0.26,0.36-0.5C1570.16,127.3,1570.14,127.26,1570.13,127.23z"/>
</g>
<g class="st25">
<path d="M1299.37,64.28c-0.07-0.15-0.23-0.26-0.41-0.25c-0.24,0.01-0.43,0.21-0.43,0.45l19.81,129.02
c0.01,0.24,0.21,0.43,0.45,0.43c0.24-0.01,0.43-0.21,0.43-0.45l-19.81-129.02C1299.41,64.39,1299.39,64.33,1299.37,64.28z"/>
</g>
<g class="st26">
<path d="M1412.78,202.53c-0.02-0.04-0.05-0.08-0.08-0.12L1299.29,64.16c-0.17-0.17-0.45-0.18-0.62-0.01
c-0.17,0.17-0.18,0.45-0.01,0.62l113.41,138.25c0.17,0.17,0.45,0.18,0.62,0.01C1412.82,202.9,1412.85,202.7,1412.78,202.53z"/>
</g>
<g class="st27">
<path d="M1221.49,290.56c-0.08-0.18-0.28-0.28-0.48-0.25c-0.24,0.05-0.39,0.28-0.35,0.52l94.41,140.02
c0.05,0.24,0.28,0.39,0.52,0.35c0.24-0.05,0.39-0.28,0.35-0.52l-94.41-140.02C1221.51,290.63,1221.5,290.59,1221.49,290.56z"/>
</g>
<g class="st28">
<path d="M1221.49,290.56c-0.06-0.12-0.16-0.21-0.3-0.24c-0.24-0.05-0.47,0.09-0.52,0.33l1.6,122.5
c-0.06,0.24,0.09,0.47,0.33,0.53c0.24,0.05,0.47-0.09,0.53-0.33l-1.6-122.5C1221.54,290.74,1221.53,290.64,1221.49,290.56z"/>
</g>
<g class="st29">
<path d="M1262.86,318.75c-0.07-0.15-0.23-0.26-0.4-0.25c-0.24,0-0.44,0.2-0.43,0.45l53.03,111.82c0,0.24,0.2,0.44,0.45,0.43
c0.24,0,0.44-0.2,0.43-0.45l-53.03-111.82C1262.9,318.87,1262.89,318.81,1262.86,318.75z"/>
</g>
<g class="st30">
<path d="M1262.86,318.75c-0.04-0.08-0.1-0.15-0.19-0.2c-0.21-0.12-0.48-0.04-0.6,0.18l-39.78,94.31
c-0.11,0.21-0.03,0.48,0.18,0.6c0.21,0.11,0.48,0.04,0.59-0.18l39.78-94.31C1262.92,319.02,1262.92,318.87,1262.86,318.75z"/>
</g>
<g class="st31">
<path d="M1570.13,127.23c-0.1-0.22-0.36-0.31-0.58-0.21l-230.89,32.57c-0.22,0.1-0.32,0.36-0.22,0.58l0,0
c0.1,0.22,0.36,0.31,0.58,0.21l230.89-32.57C1570.13,127.71,1570.23,127.45,1570.13,127.23L1570.13,127.23z"/>
</g>
<g class="st32">
<path d="M1339.23,159.8c-0.06-0.14-0.19-0.24-0.36-0.25c-0.24-0.02-0.46,0.15-0.48,0.4l-20.05,33.5
c-0.02,0.24,0.15,0.46,0.39,0.48c0.24,0.02,0.46-0.15,0.48-0.4l20.05-33.5C1339.28,159.95,1339.27,159.87,1339.23,159.8z"/>
</g>
<g class="st33">
<path d="M1339.23,159.8c-0.08-0.17-0.26-0.27-0.45-0.25c-0.24,0.03-0.41,0.25-0.38,0.49l59.29,111.55
c0.03,0.24,0.25,0.41,0.49,0.38c0.24-0.03,0.41-0.25,0.38-0.49l-59.29-111.55C1339.27,159.88,1339.25,159.84,1339.23,159.8z"/>
</g>
<g class="st34">
<path d="M1221.49,290.56c-0.03-0.06-0.07-0.11-0.12-0.16l-76.78-78.25c-0.19-0.15-0.47-0.12-0.62,0.07
c-0.15,0.19-0.12,0.47,0.07,0.62l76.78,78.25c0.19,0.15,0.47,0.12,0.62-0.07C1221.54,290.89,1221.55,290.71,1221.49,290.56z"/>
</g>
<g class="st35">
<path d="M1331.87,304.53c-0.06-0.12-0.17-0.22-0.32-0.24c-0.24-0.05-0.47,0.11-0.51,0.35l-15.98,126.05
c-0.05,0.24,0.11,0.47,0.35,0.51c0.24,0.05,0.47-0.11,0.51-0.35l15.98-126.05C1331.93,304.7,1331.91,304.61,1331.87,304.53z"/>
</g>
<g class="st36">
<path d="M1331.87,304.53c-0.03-0.07-0.08-0.13-0.15-0.18c-0.2-0.14-0.47-0.09-0.61,0.12L1222.32,413
c-0.14,0.2-0.08,0.47,0.12,0.61c0.2,0.14,0.47,0.09,0.61-0.12l108.79-108.53C1331.93,304.83,1331.94,304.66,1331.87,304.53z"/>
</g>
<g class="st37">
<path d="M1422.95,366.77c-0.06-0.13-0.19-0.23-0.35-0.25l-199.87,46.29c-0.24-0.03-0.46,0.15-0.49,0.39
c-0.03,0.24,0.14,0.46,0.39,0.49l199.87-46.29c0.24,0.03,0.46-0.15,0.49-0.39C1423,366.92,1422.99,366.84,1422.95,366.77z"/>
</g>
<g class="st38">
<path d="M1319.18,193.3c-0.07-0.15-0.23-0.26-0.4-0.25l-174.48,19c-0.24,0-0.44,0.2-0.43,0.45c0.01,0.24,0.2,0.44,0.45,0.43
l174.48-19c0.24,0,0.44-0.2,0.43-0.45C1319.22,193.42,1319.21,193.36,1319.18,193.3z"/>
</g>
<g class="st39">
<path d="M1398.52,271.35c-0.07-0.14-0.2-0.24-0.37-0.25l-174.67-64.04c-0.24-0.02-0.45,0.16-0.47,0.41
c-0.02,0.24,0.16,0.45,0.41,0.47l174.67,64.04c0.24,0.02,0.45-0.16,0.47-0.41C1398.57,271.5,1398.55,271.42,1398.52,271.35z"/>
</g>
<g class="st40">
<path d="M1319.18,193.3c-0.03-0.07-0.09-0.14-0.16-0.18c-0.21-0.13-0.48-0.07-0.61,0.13l-97.7,97.25
c-0.13,0.21-0.07,0.48,0.13,0.61c0.21,0.13,0.48,0.07,0.61-0.13l97.7-97.25C1319.24,193.6,1319.24,193.44,1319.18,193.3z"/>
</g>
<g class="st41">
<path d="M1331.87,304.53c-0.02-0.04-0.04-0.07-0.07-0.11l-108.02-97.22c-0.16-0.18-0.44-0.2-0.62-0.03
c-0.18,0.16-0.19,0.44-0.03,0.62l108.02,97.22c0.16,0.18,0.44,0.2,0.62,0.03C1331.92,304.91,1331.95,304.7,1331.87,304.53z"/>
</g>
<g class="st42">
<path d="M1319.18,193.3c-0.05-0.11-0.15-0.2-0.28-0.24c-0.23-0.07-0.48,0.07-0.54,0.3l-56.32,125.45
c-0.07,0.23,0.07,0.48,0.3,0.55c0.23,0.07,0.48-0.07,0.54-0.3l56.32-125.45C1319.24,193.51,1319.23,193.4,1319.18,193.3z"/>
</g>
<g class="st43">
<path d="M1495.96,150.44c-0.02-0.05-0.06-0.09-0.1-0.13c-0.18-0.17-0.46-0.16-0.62,0.02l-97.44,120.92
c-0.17,0.18-0.16,0.46,0.02,0.62c0.18,0.17,0.46,0.16,0.62-0.02l97.44-120.92C1496.01,150.79,1496.03,150.6,1495.96,150.44z"/>
</g>
<g class="st44">
<path d="M1570.13,127.23c-0.03-0.06-0.07-0.11-0.12-0.15c-0.19-0.16-0.46-0.13-0.62,0.06l-157.35,75.31
c-0.16,0.19-0.13,0.47,0.06,0.62c0.19,0.15,0.46,0.13,0.62-0.06l157.35-75.31C1570.18,127.56,1570.2,127.38,1570.13,127.23z"/>
</g>
<g class="st45">
<path d="M1319.18,193.3c-0.06-0.13-0.19-0.23-0.34-0.25c-0.24-0.03-0.46,0.14-0.49,0.38l12.69,111.22
c-0.03,0.24,0.14,0.46,0.38,0.49c0.24,0.03,0.46-0.14,0.49-0.38l-12.69-111.22C1319.23,193.46,1319.22,193.38,1319.18,193.3z"
/>
</g>
<g class="st46">
<path d="M1398.52,271.35c-0.05-0.1-0.14-0.19-0.25-0.23c-0.23-0.08-0.48,0.04-0.56,0.27l-66.65,33.17
c-0.08,0.23,0.04,0.48,0.27,0.56c0.23,0.08,0.48-0.04,0.56-0.27l66.65-33.17C1398.58,271.57,1398.57,271.46,1398.52,271.35z"/>
</g>
<g class="st47">
<path d="M1422.95,366.77c-0.01-0.02-0.03-0.05-0.04-0.07l-91.08-62.24c-0.14-0.2-0.42-0.24-0.61-0.1
c-0.2,0.14-0.24,0.41-0.1,0.61l91.08,62.24c0.14,0.2,0.42,0.24,0.61,0.1C1422.99,367.19,1423.04,366.96,1422.95,366.77z"/>
</g>
<g class="st48">
<path d="M1150.25,94.8c-0.02-0.04-0.04-0.08-0.08-0.11c-0.17-0.18-0.44-0.19-0.62-0.02l-22.01,79.56
c-0.18,0.17-0.19,0.45-0.02,0.62c0.17,0.18,0.44,0.19,0.62,0.02l22.01-79.56C1150.29,95.18,1150.33,94.97,1150.25,94.8z"/>
</g>
<g class="st48">
<path d="M1161.63,192.07C1161.63,192.06,1161.63,192.06,1161.63,192.07l-33.39-17.71c-0.11-0.22-0.37-0.31-0.59-0.2
c-0.22,0.11-0.28,0.38-0.2,0.59l33.38,17.7c0.11,0.22,0.37,0.31,0.59,0.2C1161.64,192.54,1161.73,192.28,1161.63,192.07z"/>
</g>
<g class="st48">
<path d="M1197.42,362.39c-0.06-0.13-0.18-0.22-0.33-0.25l-29.48-39.86c-0.24-0.04-0.46,0.13-0.5,0.37
c-0.04,0.24,0.13,0.47,0.37,0.5l29.48,39.86c0.24,0.04,0.46-0.13,0.5-0.37C1197.47,362.55,1197.45,362.47,1197.42,362.39z"/>
</g>
<g class="st48">
<path d="M1161.63,192.07c-0.08-0.17-0.26-0.27-0.45-0.25c-0.24,0.03-0.41,0.25-0.38,0.49l24.46,74.08
c0.03,0.24,0.25,0.41,0.49,0.38c0.24-0.03,0.41-0.25,0.38-0.49l-24.46-74.08C1161.66,192.15,1161.65,192.11,1161.63,192.07z"/>
</g>
<g class="st48">
<path d="M1169.93,229.77c-0.06-0.12-0.17-0.22-0.32-0.25c-0.24-0.04-0.47,0.11-0.52,0.35l-24.08,1.44
c-0.04,0.24,0.11,0.47,0.35,0.51c0.24,0.04,0.47-0.11,0.52-0.35l24.08-1.44C1169.98,229.95,1169.97,229.85,1169.93,229.77z"/>
</g>
<g class="st48">
<path d="M1209.47,165.87c-0.1-0.22-0.36-0.31-0.58-0.21l-39.54,63.9c-0.22,0.1-0.32,0.36-0.22,0.58l0,0.01
c0.1,0.22,0.36,0.31,0.58,0.22l39.54-63.9C1209.48,166.36,1209.58,166.1,1209.47,165.87
C1209.48,165.88,1209.48,165.87,1209.47,165.87z"/>
</g>
<g class="st48">
<path d="M1209.47,165.87c-0.01-0.02-0.02-0.04-0.04-0.06c-0.14-0.2-0.41-0.25-0.61-0.11l-63.62,65.35
c-0.2,0.14-0.26,0.41-0.11,0.61c0.14,0.2,0.41,0.25,0.61,0.11l63.62-65.35C1209.51,166.29,1209.56,166.06,1209.47,165.87z"/>
</g>
<g class="st48">
<path d="M1299.37,64.28c-0.08-0.17-0.27-0.28-0.47-0.25c-0.24,0.04-0.4,0.27-0.36,0.51l39.87,95.52
c0.05,0.24,0.27,0.4,0.51,0.36c0.24-0.04,0.4-0.27,0.36-0.51l-39.87-95.52C1299.4,64.35,1299.38,64.32,1299.37,64.28z"/>
</g>
<g class="st48">
<path d="M1414.38-19.24c-0.1-0.21-0.34-0.31-0.56-0.22l-115.01,83.52c-0.23,0.09-0.34,0.34-0.25,0.57
c0.07,0.22,0.34,0.34,0.57,0.25l115.01-83.52c0.23-0.09,0.34-0.34,0.25-0.57C1414.38-19.22,1414.38-19.23,1414.38-19.24z"/>
</g>
<g class="st48">
<path d="M1315.89,430.57c-0.08-0.16-0.25-0.27-0.44-0.25l-92.81-17.52c-0.24,0.02-0.42,0.24-0.39,0.48
c0.02,0.24,0.24,0.42,0.48,0.39l92.81,17.52c0.24-0.02,0.42-0.24,0.4-0.48C1315.93,430.67,1315.91,430.62,1315.89,430.57z"/>
</g>
<g class="st48">
<path d="M1223.86,207.31c-0.06-0.12-0.17-0.22-0.31-0.25l-79.15,5c-0.24-0.05-0.47,0.11-0.52,0.35
c-0.04,0.24,0.11,0.47,0.35,0.52l79.15-5c0.24,0.05,0.47-0.11,0.52-0.35C1223.91,207.49,1223.9,207.39,1223.86,207.31z"/>
</g>
<g class="st48">
<path d="M1412.78,202.53c-0.04-0.09-0.11-0.16-0.2-0.21l-73.54-42.73c-0.22-0.11-0.48-0.02-0.59,0.2
c-0.11,0.22-0.02,0.48,0.2,0.59l73.54,42.73c0.22,0.11,0.48,0.02,0.59-0.2C1412.83,202.79,1412.83,202.65,1412.78,202.53z"/>
</g>
<g class="st48">
<path d="M1221.49,290.56c-0.01-0.01-0.01-0.03-0.02-0.04l2.37-83.25c-0.12-0.21-0.39-0.28-0.6-0.15
c-0.21,0.12-0.27,0.41-0.16,0.6l-2.37,83.25c0.12,0.21,0.39,0.28,0.6,0.16C1221.51,291.01,1221.58,290.76,1221.49,290.56z"/>
</g>
<g class="st48">
<path d="M1570.13,127.23c-0.07-0.14-0.21-0.24-0.38-0.25L1414-19.49c-0.24-0.01-0.45,0.17-0.46,0.42
c-0.01,0.24,0.17,0.45,0.42,0.46l155.75,146.46c0.24,0.01,0.45-0.17,0.46-0.42C1570.17,127.36,1570.16,127.29,1570.13,127.23z"
/>
</g>
<g class="st48">
<path d="M1422.95,366.77c-0.06-0.12-0.17-0.21-0.3-0.24l-107.06,63.81c-0.24-0.05-0.47,0.1-0.52,0.34
c-0.05,0.24,0.1,0.47,0.34,0.52l107.06-63.81c0.24,0.05,0.47-0.1,0.52-0.34C1423.01,366.95,1422.99,366.85,1422.95,366.77z"/>
</g>
<g class="st48">
<path d="M1495.96,150.44c-0.01-0.02-0.02-0.04-0.03-0.06L1414.34-19.3c-0.14-0.2-0.41-0.25-0.61-0.12
c-0.2,0.14-0.25,0.41-0.12,0.61l81.58,169.68c0.14,0.2,0.41,0.25,0.61,0.12C1495.99,150.87,1496.05,150.63,1495.96,150.44z"/>
</g>
<g class="st48">
<path d="M1319.18,193.3c-0.08-0.17-0.27-0.28-0.46-0.25l-95.33,14.01c-0.24,0.03-0.41,0.26-0.37,0.5
c0.03,0.24,0.26,0.41,0.5,0.37l95.32-14.01c0.24-0.04,0.41-0.26,0.37-0.5C1319.21,193.38,1319.2,193.34,1319.18,193.3z"/>
</g>
<g class="st48">
<path d="M1262.86,318.75c-0.01-0.02-0.02-0.05-0.04-0.07l-41.38-28.19c-0.14-0.2-0.41-0.25-0.61-0.1
c-0.2,0.14-0.24,0.41-0.1,0.61l41.38,28.19c0.14,0.2,0.41,0.25,0.61,0.11C1262.9,319.17,1262.95,318.94,1262.86,318.75z"/>
</g>
<g class="st48">
<path d="M1398.52,271.35c-0.02-0.04-0.04-0.07-0.07-0.11c-0.16-0.18-0.44-0.2-0.62-0.03l-177.04,19.2
c-0.18,0.16-0.2,0.44-0.03,0.62c0.16,0.18,0.44,0.2,0.62,0.03l177.04-19.2C1398.57,271.74,1398.6,271.53,1398.52,271.35z"/>
</g>
<g class="st48">
<path d="M1331.87,304.53c-0.04-0.08-0.11-0.16-0.19-0.2l-110.39-13.97c-0.22-0.11-0.48-0.03-0.59,0.19
c-0.11,0.22-0.03,0.48,0.18,0.59l110.39,13.97c0.22,0.11,0.48,0.03,0.59-0.18C1331.93,304.79,1331.93,304.65,1331.87,304.53z"
/>
</g>
<g class="st48">
<path d="M1398.52,271.36c-0.01-0.02-0.02-0.04-0.04-0.06l-79.34-78.05c-0.14-0.2-0.41-0.25-0.61-0.11
c-0.2,0.14-0.25,0.42-0.11,0.61l79.34,78.05c0.14,0.2,0.41,0.25,0.61,0.11C1398.55,271.78,1398.61,271.55,1398.52,271.36z"/>
</g>
<g class="st48">
<path d="M1570.13,127.23c-0.02-0.03-0.04-0.07-0.06-0.09c-0.16-0.19-0.43-0.21-0.62-0.06l-74.17,23.21
c-0.19,0.15-0.21,0.44-0.06,0.62c0.16,0.19,0.43,0.21,0.62,0.06l74.17-23.21C1570.17,127.62,1570.21,127.4,1570.13,127.23z"/>
</g>
<g class="st48">
<path d="M1331.87,304.53c-0.1-0.22-0.36-0.31-0.58-0.21l-69.01,14.22c-0.22,0.1-0.32,0.36-0.21,0.58l0,0
c0.1,0.22,0.36,0.31,0.58,0.21l69.01-14.22C1331.88,305.01,1331.99,304.74,1331.87,304.53z"/>
</g>
<g class="st48">
<path d="M1412.78,202.53c-0.09-0.18-0.29-0.29-0.5-0.24l-93.59-9.23c-0.24,0.06-0.38,0.3-0.32,0.53
c0.06,0.24,0.3,0.38,0.53,0.32l93.59,9.23c0.24-0.06,0.38-0.3,0.32-0.53C1412.8,202.59,1412.79,202.56,1412.78,202.53z"/>
</g>
<g class="st48">
<path d="M1412.78,202.53c-0.01-0.02-0.02-0.04-0.03-0.06c-0.13-0.2-0.41-0.26-0.61-0.12l-14.25,68.82
c-0.2,0.14-0.25,0.41-0.12,0.61c0.13,0.2,0.41,0.26,0.61,0.12l14.25-68.82C1412.8,202.96,1412.87,202.73,1412.78,202.53z"/>
</g>
<g class="st48">
<path d="M1495.96,150.44c-0.04-0.08-0.1-0.15-0.18-0.19c-0.21-0.12-0.48-0.05-0.6,0.16L1412,202.5
c-0.12,0.21-0.05,0.48,0.16,0.6c0.21,0.12,0.48,0.05,0.6-0.16l83.18-52.1C1496.02,150.72,1496.02,150.56,1495.96,150.44z"/>
</g>
<path d="M1129.08,173.41c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1129.67,175.16,1129.71,174.1,1129.08,173.41z"/>
<path d="M1151.09,93.86c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1151.67,95.6,1151.72,94.54,1151.09,93.86z"/>
<path d="M1168.78,321.58c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1169.36,323.32,1169.41,322.26,1168.78,321.58z"/>
<path d="M1162.47,191.12c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
S1163.1,191.8,1162.47,191.12z"/>
<path d="M1251.08,30.95c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1251.66,32.69,1251.71,31.63,1251.08,30.95z"/>
<path d="M1186.93,265.2c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1187.51,266.95,1187.56,265.88,1186.93,265.2z"/>
<path d="M1198.26,361.44c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1198.84,363.19,1198.89,362.12,1198.26,361.44z"/>
<path d="M1303.25,174.3c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1303.83,176.04,1303.88,174.98,1303.25,174.3z"/>
<path d="M1170.77,228.82c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1171.35,230.57,1171.4,229.51,1170.77,228.82z"/>
<path d="M1146.69,230.27c-0.63-0.68-1.69-0.73-2.37-0.1s-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1147.27,232.01,1147.32,230.95,1146.69,230.27z"/>
<path d="M1210.31,164.92c-0.63-0.68-1.69-0.73-2.37-0.1s-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1210.9,166.67,1210.94,165.61,1210.31,164.92z"/>
<path d="M1222.67,340.23c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1223.25,341.98,1223.3,340.91,1222.67,340.23z"/>
<path d="M1300.21,63.33c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1300.79,65.08,1300.84,64.02,1300.21,63.33z"/>
<path d="M1340.08,158.85c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1340.66,160.6,1340.7,159.54,1340.08,158.85z"/>
<path d="M1316.73,429.63c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1317.31,431.37,1317.36,430.31,1316.73,429.63z"/>
<path d="M1223.92,412.11c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1224.5,413.86,1224.55,412.79,1223.92,412.11z"/>
<path d="M1415.22-20.19c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1415.8-18.44,1415.84-19.5,1415.22-20.19z"/>
<path d="M1224.7,206.36c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1225.28,208.11,1225.32,207.05,1224.7,206.36z"/>
<path d="M1145.54,211.36c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1146.12,213.11,1146.17,212.04,1145.54,211.36z"/>
<path d="M1222.33,289.61c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1222.91,291.36,1222.95,290.29,1222.33,289.61z"/>
<path d="M1263.7,317.8c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1264.29,319.55,1264.33,318.49,1263.7,317.8z"/>
<path d="M1570.97,126.28c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
S1571.59,126.96,1570.97,126.28z"/>
<path d="M1320.02,192.36c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1320.6,194.1,1320.65,193.04,1320.02,192.36z"/>
<path d="M1399.36,270.41c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1399.94,272.15,1399.99,271.09,1399.36,270.41z"/>
<path d="M1496.8,149.49c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1497.38,151.24,1497.43,150.17,1496.8,149.49z"/>
<path d="M1413.62,201.58c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1414.2,203.33,1414.24,202.27,1413.62,201.58z"/>
<path d="M1332.71,303.58c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1333.29,305.33,1333.34,304.26,1332.71,303.58z"/>
<path d="M1423.79,365.82c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1
C1424.37,367.57,1424.42,366.5,1423.79,365.82z"/>
</g>
<g class="st48">
<polygon points="1414.78,-20.04 1414.13,-19.84 1249.73,31.61 1249.68,31.91 1222.53,207.39 1223.51,207.55 1250.61,32.37
1413.78,-18.69 1412.2,202.41 1413.19,202.42 "/>
</g>
<g class="st49">
<polygon points="1221.71,291.41 1221.21,290.56 1167.73,322.24 1168.23,323.09 "/>
</g>
<g class="st49">
<rect x="1218.83" y="322.32" transform="matrix(0.9474 -0.3201 0.3201 0.9474 -36.1558 425.678)" width="115.78" height="0.99"/>
</g>
<g class="st50">
<path d="M1398.26,271.62l-212.96-5.01l-0.32-0.01l-16.18-37.74l229.56,41.77L1398.26,271.62z M1185.64,265.63l206.33,4.85
l-221.52-40.3L1185.64,265.63z"/>
</g>
<g class="st51">
<polygon points="1414.57,-18.97 1413.99,-19.77 1298.65,63.55 1250.44,31.57 1249.9,32.4 1298.68,64.75 1298.95,64.55 "/>
</g>
<polygon class="st52" points="1414.38,-19.24 1298.53,64.48 1249.46,31.86 "/>
<polygon class="st53" points="1197.43,362.41 1185.64,265.63 1167.59,323.15 "/>
<polygon class="st48" points="1315.59,430.33 1331.22,304.36 1422.99,367.01 "/>
<polygon class="st48" points="1412.78,202.53 1318.35,193.45 1339.23,159.8 "/>
<polygon class="st52" points="1127.45,174.75 1161.23,192.25 1149.41,94.96 "/>
<polyline class="st52" points="1149.41,94.96 1127.45,174.75 1161.23,192.25 "/>
<polyline class="st52" points="1149.41,94.96 1127.45,174.75 1161.23,192.25 "/>
</g>
<path class="st54" d="M1316.63,432c0.51-0.47,0.67-1.19,0.45-1.81l104.23-62.12c0.01,0.01,0.01,0.01,0.01,0.02
c0.63,0.68,1.69,0.73,2.37,0.1c0.68-0.63,0.73-1.69,0.1-2.37c-0.62-0.68-1.66-0.72-2.34-0.12l-88.41-60.42
c0.12-0.33,0.13-0.68,0.04-1.01l63.73-31.72c0.03,0.04,0.04,0.09,0.08,0.13c0.63,0.68,1.69,0.73,2.37,0.1
c0.63-0.58,0.69-1.52,0.21-2.2l80.31-99.67l88.66-42.43c0.02,0.02,0.03,0.05,0.05,0.08c0.63,0.68,1.69,0.73,2.37,0.1
c0.68-0.63,0.73-1.69,0.1-2.37c-0.58-0.63-1.51-0.69-2.19-0.22L1415.39-18.19c0.38-0.62,0.35-1.43-0.17-2
c-0.63-0.68-1.69-0.73-2.37-0.1c-0.3,0.27-0.45,0.64-0.51,1.01L1251.2,31.14c-0.04-0.06-0.07-0.14-0.12-0.2
c-0.63-0.68-1.69-0.73-2.37-0.1c-0.5,0.46-0.65,1.16-0.45,1.77L1151,93.79c-0.63-0.61-1.63-0.64-2.29-0.04
c-0.68,0.63-0.73,1.69-0.1,2.37c0.12,0.13,0.26,0.21,0.4,0.29l-11.51,41.82l-9.58,34.63c-0.43-0.02-0.87,0.13-1.21,0.44
c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1c0.05-0.05,0.08-0.11,0.12-0.17l30.54,16.19
c-0.15,0.54-0.05,1.13,0.35,1.57c0.35,0.39,0.84,0.55,1.33,0.52l5.07,15.37l-0.41,0.42l-20.13,2.19
c-0.07-0.19-0.17-0.37-0.32-0.53c-0.63-0.68-1.69-0.73-2.37-0.1c-0.68,0.63-0.73,1.69-0.1,2.37c0.54,0.58,1.38,0.67,2.04,0.31
l8.41,8.57l-7.25,7.45c-0.61-0.34-1.4-0.29-1.94,0.21c-0.68,0.63-0.73,1.69-0.1,2.37c0.57,0.62,1.47,0.69,2.15,0.24l37.82,32.83
c-0.29,0.6-0.21,1.34,0.27,1.86c0.11,0.12,0.24,0.19,0.37,0.27l-17.16,53.31c-0.44-0.03-0.9,0.11-1.25,0.43
c-0.68,0.63-0.73,1.69-0.1,2.37c0.51,0.56,1.3,0.67,1.95,0.36l27.54,37.25c-0.58,0.64-0.61,1.61-0.02,2.26
c0.63,0.68,1.69,0.73,2.37,0.1c0.6-0.55,0.68-1.43,0.27-2.1l21.96-19.08c0.28,0.23,0.61,0.38,0.96,0.4l0.89,68.61
c-0.25,0.07-0.49,0.18-0.69,0.36c-0.68,0.63-0.73,1.69-0.1,2.37c0.63,0.68,1.69,0.73,2.37,0.1c0.17-0.15,0.29-0.33,0.38-0.52
l89.64,16.92c0.03,0.36,0.15,0.73,0.41,1.02C1314.88,432.58,1315.95,432.63,1316.63,432z M1147.12,231.41l14.29-0.86l14.4,14.67
l8.16,19.03l-37.01-32.13C1147.07,231.9,1147.12,231.66,1147.12,231.41z M1330.87,303.16c-0.1,0.04-0.19,0.11-0.28,0.17
l-23.9-21.51l21.48-2.33L1330.87,303.16z M1413.54,201.53c-0.11-0.1-0.22-0.18-0.35-0.25l0.37-51.41l76-10.72l4.91,10.21
c-0.01,0.01-0.03,0.01-0.04,0.03c-0.51,0.46-0.66,1.16-0.45,1.77L1413.54,201.53z M1567.47,127.31l-77.39,10.92l-15.65-32.55
L1567.47,127.31z M1489.18,138.35l-75.61,10.67l0.41-57.4l59.36,13.8L1489.18,138.35z M1222.8,342.29
c0.17-0.26,0.3-0.54,0.31-0.84l25.8-8.72l4.47,6.63l-9.63,22.84L1222.8,342.29z M1329.99,303.96c-0.02,0.05-0.04,0.09-0.06,0.14
l-57.08-7.22l5.38-11.97l27.3-2.96L1329.99,303.96z M1251.08,33.18l46.33,30.73c-0.17,0.48-0.11,1.01,0.18,1.46l-24.99,28.24
l-21.88-60.13c0.09-0.05,0.19-0.09,0.27-0.16C1251.02,33.28,1251.04,33.23,1251.08,33.18z M1292.92,396.55l-21.27-31.55l8.3-8.28
l18.3,38.59L1292.92,396.55z M1298.61,396.09l14.24,30.02l-19.43-28.82L1298.61,396.09z M1324.11,243.95l-23.62-8.66l18.03-40.17
c0,0,0.01,0,0.01,0L1324.11,243.95z M1224.02,204.25l8.42-0.92l-7.66,3.16c-0.03-0.04-0.04-0.09-0.08-0.13
c-0.26-0.28-0.59-0.42-0.93-0.49L1224.02,204.25z M1337.82,158.68c-0.04,0.03-0.09,0.04-0.12,0.07c-0.27,0.25-0.41,0.56-0.48,0.89
l-23.03,1.08l-14.25-92.82L1337.82,158.68z M1236.42,202.9l59.09-6.44l-67.58,9.93L1236.42,202.9z M1282.73,228.78l-57.53-21.09
l92.06-13.53c0.02,0.05,0.06,0.1,0.09,0.15L1282.73,228.78z M1314.79,170.36l3.32,21.62c-0.16,0.07-0.32,0.15-0.46,0.28
c-0.29,0.27-0.44,0.62-0.5,0.98l-77.82,8.48l61.37-25.26c0.03,0.04,0.04,0.09,0.07,0.12c0.63,0.68,1.69,0.73,2.37,0.1
c0.49-0.45,0.64-1.12,0.46-1.71L1314.79,170.36z M1315.62,170.01l21.9-9.02c0.03,0.04,0.04,0.09,0.08,0.13
c0.02,0.02,0.05,0.03,0.07,0.05l-18.4,30.74c-0.1-0.03-0.19-0.06-0.3-0.07L1315.62,170.01z M1315.49,169.14l-1.16-7.58l22.09-1.03
L1315.49,169.14z M1317.43,195.45l-17.75,39.55l-16.06-5.89L1317.43,195.45z M1224.16,203.36l5.4-34.88l70.31,7.09l-64.51,26.57
L1224.16,203.36z M1302.31,173.81l-0.32-11.68l11.46-0.54l1.21,7.88l-11.51,4.74C1302.9,174,1302.61,173.86,1302.31,173.81z
M1301.96,161.29l-2.49-90.64l13.84,90.11L1301.96,161.29z M1371.57,80.93l-70.94-16.49c0-0.2-0.03-0.39-0.1-0.57l112.41-81.63
c0.01,0.01,0.03,0.02,0.04,0.03L1371.57,80.93z M1371.25,81.69l-19.49,46.44l-51.44-62.71c0.04-0.06,0.1-0.12,0.14-0.19
L1371.25,81.69z M1351.38,129.05l-12.3,29.3c-0.15-0.02-0.3-0.02-0.46,0l-38.12-91.33L1351.38,129.05z M1351.97,129.77
l20.54,25.04l-32.14,4.53c-0.07-0.17-0.16-0.35-0.3-0.49c-0.07-0.08-0.16-0.12-0.24-0.18L1351.97,129.77z M1373.14,155.57
l37.36,45.55l-70.07-40.72c0.02-0.08,0.05-0.15,0.05-0.23L1373.14,155.57z M1277.22,285.02l-5.28,11.75l-47.56-6.02
L1277.22,285.02z M1271.59,297.55l-8.87,19.75c-0.48-0.07-0.98,0.04-1.37,0.38l-38.62-26.32L1271.59,297.55z M1280.15,355.3
l-13.54-28.55l62.44-21.1l0.95-0.2c0.01,0.03,0.03,0.05,0.05,0.08L1280.15,355.3z M1266.19,325.85l-2.67-5.62
c0.03-0.02,0.06-0.03,0.08-0.05c0.34-0.31,0.52-0.72,0.54-1.15l56.99-11.75L1266.19,325.85z M1265.42,326.11l-6.42,2.17l3.25-7.69
c0.18,0.02,0.36,0.01,0.54-0.02L1265.42,326.11z M1272.49,297.67l56.09,7.1l-0.83,0.28l-63.81,13.15
c-0.07-0.14-0.13-0.28-0.24-0.39c-0.05-0.06-0.13-0.09-0.19-0.14L1272.49,297.67z M1330.84,306.26l-10.65,83.98l-21.15,4.9
l-18.5-39l50.1-49.98C1330.71,306.19,1330.77,306.23,1330.84,306.26z M1271.16,364.28l-16.82-24.95l4.15-9.84l7.36-2.49l13.7,28.9
L1271.16,364.28z M1253.75,338.47l-4.05-6l7.68-2.59L1253.75,338.47z M1249.13,331.61l-26.52-39.33l38.29,26.09
c-0.2,0.57-0.11,1.22,0.32,1.7c0.06,0.07,0.15,0.1,0.22,0.16l-3.55,8.42L1249.13,331.61z M1220.29,289.31l-21.96-22.38l23.05,0.54
l-0.62,21.66C1220.59,289.16,1220.44,289.22,1220.29,289.31z M1197.33,265.91l-8.97-9.14l5.22-22.38l28.6,5.2l-0.77,26.88
L1197.33,265.91z M1171.14,230.31l2.34,0.43l5.41,16.39l-2.12-2.16l-5.98-13.94C1170.97,230.81,1171.09,230.57,1171.14,230.31z
M1174.45,230.91l18.29,3.33l-5.09,21.81l-7.39-7.53L1174.45,230.91z M1185.6,264.68l-4.72-14.28l6.54,6.66l-1.78,7.62
C1185.63,264.68,1185.62,264.68,1185.6,264.68z M1196.08,265.88l-8.86-0.21c-0.07-0.17-0.15-0.33-0.28-0.47
c-0.13-0.15-0.3-0.25-0.46-0.34l1.65-7.09L1196.08,265.88z M1179.47,251.24l-1.74-4.07l1.79,1.83l3.02,9.15L1179.47,251.24z
M1171.93,229.44l0.99-0.41l0.21,0.62L1171.93,229.44z M1173.72,228.71l22.47-9.25l-3.22,13.81l-18.87-3.43L1173.72,228.71z
M1197.15,219.07l25.17-10.36c0.21,0.2,0.46,0.32,0.72,0.39l-0.84,29.5l-28.4-5.17L1197.15,219.07z M1197.39,218.02l2-8.57
l22.24-1.4L1197.39,218.02z M1199.59,208.58l0.4-1.71l23-2.51l-0.25,1.64c-0.15,0.07-0.29,0.14-0.42,0.25
c-0.27,0.25-0.42,0.58-0.48,0.91L1199.59,208.58z M1200.2,205.97l8.92-38.25c0.39-0.01,0.78-0.14,1.09-0.42
c0.22-0.2,0.35-0.46,0.44-0.72l17.92,1.81l-5.43,35.09L1200.2,205.97z M1214.34,166.23l14.67-0.69l-0.33,2.13L1214.34,166.23z
M1230.01,165.5l66.88-3.13l4.25,11.66c-0.09,0.05-0.19,0.09-0.27,0.16c-0.22,0.2-0.35,0.46-0.44,0.72l-70.78-7.14L1230.01,165.5z
M1297.61,162.34l3.7-0.17l0.31,11.19L1297.61,162.34z M1297.31,161.51l-24.37-66.96l25.29-28.58c0.14,0.07,0.29,0.1,0.45,0.13
l2.61,95.23L1297.31,161.51z M1413.77-17.4L1413,90.56l-40.62-9.44l41.35-98.53C1413.75-17.41,1413.76-17.41,1413.77-17.4z
M1412.99,91.39l-0.41,57.77l-39.05,5.51l-21.18-25.82l19.71-46.97L1412.99,91.39z M1412.57,150.01l-0.37,51.07
c-0.18,0.02-0.34,0.05-0.51,0.13l-37.55-45.77L1412.57,150.01z M1319.61,194.91l76.58,75.33l-0.73-0.13l-70.45-25.83l-5.62-49.23
C1319.47,195.02,1319.54,194.96,1319.61,194.91z M1320.08,391.11l-4.82,38.01c-0.03,0-0.06,0.01-0.09,0.01l-15.76-33.24
L1320.08,391.11z M1313.43,428.43l-30.27-28.77l9.4-2.18L1313.43,428.43z M1282.45,398.98l-22.97-21.83l11.59-11.56l21.01,31.16
L1282.45,398.98z M1281.82,399.13l-57.67,13.36c-0.01-0.02-0.02-0.04-0.03-0.05l34.98-34.9L1281.82,399.13z M1223.95,411.37
l20.25-48l14.27,13.56L1223.95,411.37z M1244.42,362.84l9.54-22.62l16.61,24.64l-11.72,11.69L1244.42,362.84z M1221.54,292.35
c0.04-0.01,0.08-0.01,0.13-0.02l26.67,39.56l-25.5,8.62c-0.06-0.09-0.09-0.19-0.16-0.27c-0.15-0.16-0.33-0.29-0.52-0.38
L1221.54,292.35z M1191.07,308.41l-4.77-40.52c0.19-0.07,0.37-0.17,0.53-0.32c0.27-0.25,0.41-0.57,0.48-0.91l9.76,0.23
l22.58,23.02c-0.29,0.49-0.3,1.08-0.04,1.59L1191.07,308.41z M1172.09,226.52l0.56,1.69l-1.8,0.74c-0.03-0.04-0.04-0.09-0.07-0.12
c-0.02-0.02-0.05-0.03-0.07-0.05L1172.09,226.52z M1172.68,225.56l9.29-15.02l16.54-1.04l-2.08,8.91l-22.99,9.46L1172.68,225.56z
M1172.39,224.66l-4.37-13.23l13.07-0.82L1172.39,224.66z M1167.74,210.59l-0.07-0.2l14.52-1.58l-0.56,0.9L1167.74,210.59z
M1183.11,208.71l15.99-1.74l-0.39,1.67l-16.19,1.02L1183.11,208.71z M1183.69,207.76l24.43-39.47l-8.81,37.77L1183.69,207.76z
M1233.01,139.67l-3.87,25.03l-18.46,0.86c-0.05-0.15-0.13-0.27-0.21-0.41L1233.01,139.67z M1234.22,138.3l38.2-43.17l24.17,66.42
l-66.45,3.11L1234.22,138.3z M1234.47,136.7l15.84-102.36l21.78,59.85L1234.47,136.7z M1414.75-16.43l58.14,120.92l-58.91-13.69
L1414.75-16.43z M1358.48,197.82l37.99,71.49l-76.25-75.01c0.05-0.08,0.08-0.16,0.11-0.24L1358.48,197.82z M1313.98,430.05
l-89.26-16.85l57.82-13.39l31.59,30.03C1314.08,429.91,1314.01,429.97,1313.98,430.05z M1223.09,411.17l-0.89-68.34
c0.08-0.04,0.16-0.09,0.24-0.14l21.09,20.04L1223.09,411.17z M1220.03,342.22l-21.96,19.08c-0.24-0.2-0.52-0.32-0.82-0.37
l-6.06-51.45l29.13-17.26c0.11,0.06,0.23,0.08,0.35,0.12l0.62,47.37c-0.36,0.03-0.72,0.15-1,0.41
C1219.69,340.68,1219.62,341.55,1220.03,342.22z M1196.31,361.08l-4.05-5.48l4.13,5.43
C1196.36,361.05,1196.33,361.07,1196.31,361.08z M1162.57,230.48l5.33-0.32c0.04,0.33,0.15,0.66,0.4,0.93
c0.39,0.43,0.95,0.58,1.48,0.5l5.07,11.41L1162.57,230.48z M1162.37,230.28l-7.64-7.78l10.61-10.9l1.79-0.11l4.67,14.13
l-1.72,2.78c-0.56-0.19-1.21-0.1-1.68,0.33c-0.36,0.33-0.53,0.78-0.53,1.23L1162.37,230.28z M1166.23,210.69l0.15-0.15l0.42-0.05
l0.05,0.16L1166.23,210.69z M1167.38,209.5l39.47-40.54l-24.08,38.91l-15.38,1.68L1167.38,209.5z M1162.44,191.09
c-0.27-0.28-0.61-0.43-0.96-0.48l-5.64-48.17l93.24-108.88c0.11,0.06,0.22,0.08,0.33,0.11l-16.15,104.4l-23.43,26.48
c-0.6-0.3-1.35-0.22-1.88,0.26c-0.46,0.43-0.61,1.05-0.48,1.62L1162.44,191.09z M1247.89,33.78l-92.17,107.64l-5.25-44.88
c0.19-0.07,0.36-0.17,0.52-0.31c0.5-0.46,0.65-1.16,0.45-1.77L1247.89,33.78z M1415.26-17.38l153.06,143.93
c-0.02,0.04-0.05,0.06-0.07,0.1l-94.27-21.92L1415.26-17.38z M1564.78,128.54l-67.81,21.22c-0.06-0.09-0.09-0.19-0.16-0.27
c-0.4-0.44-0.99-0.59-1.54-0.49l-4.8-9.98L1564.78,128.54z M1479.11,170.34l-60.63,29.02l75.2-47.09L1479.11,170.34z
M1411.74,204.26l-13.59,65.61c-0.14,0-0.28,0.03-0.42,0.06l-38.27-72.01l51.29,5.06c0.05,0.32,0.16,0.62,0.39,0.88
C1411.31,204.04,1411.52,204.17,1411.74,204.26z M1396.3,272.1l-63.51,31.61c-0.03-0.04-0.04-0.09-0.08-0.13
c-0.27-0.3-0.63-0.45-1-0.5l-2.7-23.68L1396.3,272.1z M1154.12,223.12l7.09,7.23l-14.12,0.85c-0.03-0.22-0.1-0.43-0.22-0.63
L1154.12,223.12z M1154.12,221.88l-8.39-8.55c0.09-0.16,0.15-0.33,0.19-0.51l18.13-1.15L1154.12,221.88z M1165.03,210.68
l-0.08,0.09l-1.7,0.11L1165.03,210.68z M1167.07,208.58l-4.94-14.95c0.07-0.05,0.16-0.07,0.23-0.14c0.46-0.43,0.61-1.05,0.47-1.62
l43.9-24.04L1167.07,208.58z M1480.94,169.46l13.94-17.3c0.59,0.26,1.3,0.17,1.81-0.3c0.39-0.35,0.55-0.85,0.52-1.33l67.27-21.05
L1480.94,169.46z M1477.95,171.78l-79.15,98.22c-0.01-0.01-0.02,0-0.04-0.01l13.59-65.61c0.41,0.01,0.83-0.13,1.16-0.43
c0.45-0.41,0.6-1.01,0.48-1.57L1477.95,171.78z"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

File diff suppressed because it is too large Load Diff
+437
View File
@@ -0,0 +1,437 @@
# hindsight-litellm
Universal LLM memory integration via LiteLLM. Add persistent memory to any LLM application with just a few lines of code.
## Features
- **Universal LLM Support** - Works with 100+ LLM providers via LiteLLM (OpenAI, Anthropic, Groq, Azure, AWS Bedrock, Google Vertex AI, and more)
- **Simple Integration** - Just configure, enable, and use `hindsight_litellm.completion()`
- **Automatic Memory Injection** - Relevant memories are injected into prompts before LLM calls
- **Automatic Conversation Storage** - Conversations are stored to Hindsight for future recall
- **Two Memory Modes** - Choose between `reflect` (synthesized context) or `recall` (raw memory retrieval)
- **Direct Memory APIs** - Query, synthesize, and store memories manually
- **Native Client Wrappers** - Alternative wrappers for OpenAI and Anthropic SDKs
- **Debug Mode** - Inspect exactly what memories are being injected
## Installation
```bash
pip install hindsight-litellm
```
## Quick Start
```python
import hindsight_litellm
# Configure and enable memory integration
hindsight_litellm.configure(
hindsight_api_url="http://localhost:8888",
bank_id="my-agent",
)
hindsight_litellm.enable()
# Use the convenience wrapper - memory is automatically injected and stored
response = hindsight_litellm.completion(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "What did we discuss about AI?"}]
)
```
## How It Works
Here's what happens under the hood when you call `completion()`:
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. YOUR CODE │
│ ───────────────────────────────────────────────────────────────────────── │
│ response = hindsight_litellm.completion( │
│ model="gpt-4o-mini", │
│ messages=[{"role": "user", "content": "Help me with my Python project"}]│
│ ) │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ 2. MEMORY RETRIEVAL (before LLM call) │
│ ───────────────────────────────────────────────────────────────────────── │
│ # hindsight_litellm queries Hindsight for relevant memories │
│ │
│ # If use_reflect=False (default) - raw memories: │
│ memories = hindsight.recall(query="Help me with my Python project") │
│ # Returns: ["User prefers pytest", "User is building a FastAPI app", ...] │
│ │
│ # If use_reflect=True - synthesized context: │
│ context = hindsight.reflect(query="Help me with my Python project") │
│ # Returns: "The user is an experienced Python developer working on..." │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ 3. PROMPT INJECTION │
│ ───────────────────────────────────────────────────────────────────────── │
│ # Memories are injected into the system message: │
│ │
│ messages = [ │
│ {"role": "system", "content": """ │
│ # Relevant Memories │
│ 1. [WORLD] User prefers pytest for testing │
│ 2. [WORLD] User is building a FastAPI app │
│ 3. [OPINION] User likes type hints │
│ """}, │
│ {"role": "user", "content": "Help me with my Python project"} │
│ ] │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ 4. LLM CALL │
│ ───────────────────────────────────────────────────────────────────────── │
│ # The enriched prompt is sent to the LLM │
│ response = litellm.completion(model="gpt-4o-mini", messages=messages) │
│ │
│ # LLM now has context and can give personalized responses like: │
│ # "Since you're working on your FastAPI app, here's how to add tests │
│ # with pytest..." │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ 5. CONVERSATION STORAGE (after LLM call) │
│ ───────────────────────────────────────────────────────────────────────── │
│ # The conversation is stored to Hindsight for future recall │
│ hindsight.retain( │
│ content="User: Help me with my Python project\n" │
│ "Assistant: Since you're working on FastAPI..." │
│ ) │
│ # Hindsight extracts facts: "User asked about Python project help" │
└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐
│ 6. RESPONSE RETURNED │
│ ───────────────────────────────────────────────────────────────────────── │
│ # You receive the response as normal │
│ print(response.choices[0].message.content) │
└─────────────────────────────────────────────────────────────────────────────┘
```
The memory injection and storage happen automatically - you just use `completion()` as normal.
## Configuration Options
```python
hindsight_litellm.configure(
# Required
hindsight_api_url="http://localhost:8888", # Hindsight API server URL
bank_id="my-agent", # Memory bank ID
api_key="your-api-key", # Optional API key for authentication
# Optional - Memory behavior
store_conversations=True, # Store conversations after LLM calls
inject_memories=True, # Inject relevant memories into prompts
use_reflect=False, # Use reflect API (synthesized) vs recall (raw memories)
reflect_include_facts=False, # Include source facts with reflect responses
max_memories=None, # Maximum memories to inject (None = unlimited)
max_memory_tokens=4096, # Maximum tokens for memory context
recall_budget="mid", # Recall budget: "low", "mid", "high"
fact_types=["world", "agent"], # Filter fact types to inject
# Optional - Bank Configuration
bank_name="My Agent", # Human-readable display name for the memory bank
background="This agent...", # Instructions guiding what Hindsight should remember (see below)
# Optional - Advanced
injection_mode="system_message", # or "prepend_user"
excluded_models=["gpt-3.5*"], # Exclude certain models
verbose=True, # Enable verbose logging and debug info
)
```
### Bank Configuration: background and bank_name
The `background` and `bank_name` parameters configure the memory bank itself. When provided, `configure()` will automatically create or update the bank with these settings.
- **bank_name**: A human-readable display name for the memory bank. Useful for identifying banks in the Hindsight UI or when managing multiple banks.
- **background**: Instructions that guide Hindsight on what information is important to extract and remember from conversations. This influences memory extraction during the `retain` operation and can affect how the bank's "disposition" (skepticism, literalism, empathy) is calibrated.
```python
# Example: Customer support routing agent
hindsight_litellm.configure(
hindsight_api_url="http://localhost:8888",
bank_id="support-router",
bank_name="Customer Support Router",
background="""This agent routes customer support requests to the appropriate team.
Remember which types of issues should go to which teams (billing, technical, sales).
Track customer preferences for communication channels and past issue resolutions.
Note any escalation patterns or VIP customers who need special handling.""",
)
```
### Memory Modes: Reflect vs Recall
- **Recall mode** (`use_reflect=False`, default): Retrieves raw memory facts and injects them as a numbered list. Best when you need precise, individual memories.
- **Reflect mode** (`use_reflect=True`): Synthesizes memories into a coherent context paragraph. Best for natural, conversational memory context.
```python
# Recall mode - raw memories
hindsight_litellm.configure(
bank_id="my-agent",
use_reflect=False, # Default
)
# Injects: "1. [WORLD] User prefers Python\n2. [OPINION] User dislikes Java..."
# Reflect mode - synthesized context
hindsight_litellm.configure(
bank_id="my-agent",
use_reflect=True,
)
# Injects: "Based on previous conversations, the user is a Python developer who..."
```
## Multi-Provider Support
Works with any LiteLLM-supported provider:
```python
import hindsight_litellm
hindsight_litellm.configure(
hindsight_api_url="http://localhost:8888",
bank_id="my-agent",
)
hindsight_litellm.enable()
# OpenAI
hindsight_litellm.completion(model="gpt-4o", messages=[...])
# Anthropic
hindsight_litellm.completion(model="claude-3-5-sonnet-20241022", messages=[...])
# Groq
hindsight_litellm.completion(model="groq/llama-3.1-70b-versatile", messages=[...])
# Azure OpenAI
hindsight_litellm.completion(model="azure/gpt-4", messages=[...])
# AWS Bedrock
hindsight_litellm.completion(model="bedrock/anthropic.claude-3", messages=[...])
# Google Vertex AI
hindsight_litellm.completion(model="vertex_ai/gemini-pro", messages=[...])
```
## Direct Memory APIs
### Recall - Query raw memories
```python
from hindsight_litellm import configure, recall
configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
# Query memories
memories = recall("what projects am I working on?", budget="mid")
for m in memories:
print(f"- [{m.fact_type}] {m.text}")
# Output:
# - [world] User is building a FastAPI project
# - [opinion] User prefers Python over JavaScript
```
### Reflect - Get synthesized context
```python
from hindsight_litellm import configure, reflect
configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
# Get synthesized memory context
result = reflect("what do you know about the user's preferences?")
print(result.text)
# Output:
# "Based on our conversations, the user prefers Python for backend development..."
```
### Retain - Store memories
```python
from hindsight_litellm import configure, retain
configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
# Store a memory
result = retain(
content="User mentioned they're working on a machine learning project",
context="Discussion about current projects",
)
print(f"Retained successfully: {result.success}, items: {result.items_count}")
```
### Async APIs
```python
from hindsight_litellm import arecall, areflect, aretain
# Async versions of all memory APIs
memories = await arecall("what do you know about me?")
context = await areflect("summarize user preferences")
result = await aretain(content="New information to remember")
```
## Native Client Wrappers
Alternative to LiteLLM callbacks for direct SDK integration:
### OpenAI Wrapper
```python
from openai import OpenAI
from hindsight_litellm import wrap_openai
client = OpenAI()
wrapped = wrap_openai(
client,
bank_id="my-agent",
hindsight_api_url="http://localhost:8888",
)
response = wrapped.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "What do you know about me?"}]
)
```
### Anthropic Wrapper
```python
from anthropic import Anthropic
from hindsight_litellm import wrap_anthropic
client = Anthropic()
wrapped = wrap_anthropic(
client,
bank_id="my-agent",
hindsight_api_url="http://localhost:8888",
)
response = wrapped.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}]
)
```
## Debug Mode
When `verbose=True`, you can inspect exactly what memories are being injected:
```python
from hindsight_litellm import configure, enable, completion, get_last_injection_debug
configure(
bank_id="my-agent",
hindsight_api_url="http://localhost:8888",
verbose=True,
use_reflect=True,
)
enable()
response = completion(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "What's my favorite color?"}]
)
# Inspect what was injected
debug = get_last_injection_debug()
if debug:
print(f"Mode: {debug.mode}") # "reflect" or "recall"
print(f"Injected: {debug.injected}") # True/False
print(f"Results: {debug.results_count}")
print(f"Memory context:\n{debug.memory_context}")
if debug.error:
print(f"Error: {debug.error}")
```
## Context Manager
```python
from hindsight_litellm import hindsight_memory
import litellm
with hindsight_memory(bank_id="user-123"):
response = litellm.completion(model="gpt-4", messages=[...])
# Memory integration automatically disabled after context
```
## Disabling and Cleanup
```python
from hindsight_litellm import disable, cleanup
# Temporarily disable memory integration
disable()
# Clean up all resources (call when shutting down)
cleanup()
```
## API Reference
### Main Functions
| Function | Description |
|----------|-------------|
| `configure(...)` | Configure global Hindsight settings |
| `enable()` | Enable memory integration with LiteLLM |
| `disable()` | Disable memory integration |
| `is_enabled()` | Check if memory integration is enabled |
| `cleanup()` | Clean up all resources |
### Configuration Functions
| Function | Description |
|----------|-------------|
| `get_config()` | Get current configuration |
| `is_configured()` | Check if Hindsight is configured |
| `reset_config()` | Reset configuration to defaults |
### Memory Functions
| Function | Description |
|----------|-------------|
| `recall(query, ...)` | Synchronously query raw memories |
| `arecall(query, ...)` | Asynchronously query raw memories |
| `reflect(query, ...)` | Synchronously get synthesized memory context |
| `areflect(query, ...)` | Asynchronously get synthesized memory context |
| `retain(content, ...)` | Synchronously store a memory |
| `aretain(content, ...)` | Asynchronously store a memory |
### Debug Functions
| Function | Description |
|----------|-------------|
| `get_last_injection_debug()` | Get debug info from last memory injection |
| `clear_injection_debug()` | Clear stored debug info |
### Client Wrappers
| Function | Description |
|----------|-------------|
| `wrap_openai(client, ...)` | Wrap OpenAI client with memory |
| `wrap_anthropic(client, ...)` | Wrap Anthropic client with memory |
## Requirements
- Python >= 3.10
- litellm >= 1.40.0
- A running Hindsight API server
## License
MIT
@@ -0,0 +1,817 @@
"""Hindsight-LiteLLM: Universal LLM memory integration via LiteLLM.
This package provides automatic memory integration for any LLM provider
supported by LiteLLM (100+ providers including OpenAI, Anthropic, Groq,
Azure, AWS Bedrock, Google Vertex AI, and more).
Features:
- Automatic memory injection before LLM calls
- Automatic conversation storage after LLM calls
- Works with any LiteLLM-supported provider
- Zero code changes to existing LiteLLM usage
- Multi-user support via separate bank_ids
- Document grouping for conversation threading
- Direct recall API for manual memory queries
- Native client wrappers for OpenAI and Anthropic
Basic usage:
>>> from hindsight_litellm import configure, enable
>>>
>>> # Configure Hindsight integration
>>> configure(
... hindsight_api_url="http://localhost:8888",
... bank_id="user-123", # Use separate bank_ids for multi-user support
... store_conversations=True,
... inject_memories=True,
... )
>>>
>>> # Enable memory integration
>>> enable()
>>>
>>> # Now use LiteLLM as normal - memory integration is automatic
>>> import litellm
>>> response = litellm.completion(
... model="gpt-4",
... messages=[{"role": "user", "content": "What did we discuss about AI?"}]
... )
Direct recall API:
>>> from hindsight_litellm import configure, recall
>>> configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
>>>
>>> # Query memories directly
>>> memories = recall("what projects am I working on?")
>>> for m in memories:
... print(f"- [{m.fact_type}] {m.text}")
Native client wrappers:
>>> from openai import OpenAI
>>> from hindsight_litellm import wrap_openai
>>>
>>> client = OpenAI()
>>> wrapped = wrap_openai(client, bank_id="user-123")
>>>
>>> response = wrapped.chat.completions.create(
... model="gpt-4",
... messages=[{"role": "user", "content": "Hello!"}]
... )
Works with any LiteLLM-supported provider:
>>> # OpenAI
>>> litellm.completion(model="gpt-4", messages=[...])
>>>
>>> # Anthropic
>>> litellm.completion(model="claude-3-opus-20240229", messages=[...])
>>>
>>> # Groq
>>> litellm.completion(model="groq/llama-3.1-70b-versatile", messages=[...])
>>>
>>> # Azure OpenAI
>>> litellm.completion(model="azure/gpt-4", messages=[...])
>>>
>>> # AWS Bedrock
>>> litellm.completion(model="bedrock/anthropic.claude-3", messages=[...])
>>>
>>> # Google Vertex AI
>>> litellm.completion(model="vertex_ai/gemini-pro", messages=[...])
Context manager usage:
>>> from hindsight_litellm import hindsight_memory
>>>
>>> with hindsight_memory(bank_id="user-123"):
... response = litellm.completion(model="gpt-4", messages=[...])
>>> # Memory integration automatically disabled after context
Configuration options:
- hindsight_api_url: URL of your Hindsight API server
- bank_id: Memory bank ID for memory operations (required). For multi-user
support, use different bank_ids per user (e.g., f"user-{user_id}")
- api_key: Optional API key for Hindsight authentication
- store_conversations: Whether to store conversations (default: True)
- inject_memories: Whether to inject relevant memories (default: True)
- injection_mode: How to inject memories (system_message or prepend_user)
- max_memories: Maximum number of memories to inject (None = unlimited)
- recall_budget: Budget for memory recall (low, mid, high)
- excluded_models: List of model patterns to exclude from interception
- verbose: Enable verbose logging
- bank_name: Display name for the memory bank
- background: Instructions that help Hindsight understand what to remember
Background example:
>>> configure(
... bank_id="routing-agent",
... background="This agent routes customer requests to support channels. "
... "Remember which types of issues should go to which channels.",
... )
"""
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Optional, List, Any
import litellm
from .config import (
configure,
get_config,
is_configured,
reset_config,
HindsightConfig,
MemoryInjectionMode,
)
from .callbacks import (
HindsightCallback,
get_callback,
cleanup_callback,
)
from .wrappers import (
recall,
arecall,
RecallResult,
RecallResponse,
RecallDebugInfo,
reflect,
areflect,
ReflectResult,
ReflectDebugInfo,
retain,
aretain,
RetainResult,
RetainDebugInfo,
wrap_openai,
wrap_anthropic,
HindsightOpenAI,
HindsightAnthropic,
)
__version__ = "0.1.0"
# Track whether we've registered with LiteLLM
_enabled = False
# Store original functions for restoration
_original_completion = None
_original_acompletion = None
@dataclass
class InjectionDebugInfo:
"""Debug information from a memory injection operation.
This is populated when verbose=True in the config and can be retrieved
via get_last_injection_debug() after a completion() call.
Attributes:
mode: The injection mode used ("reflect" or "recall")
query: The user query used for memory lookup
bank_id: The bank ID used
memory_context: The formatted memory context that was injected
reflect_text: The raw reflect text (when mode="reflect")
reflect_facts: The facts used to generate the reflect response (when reflect_include_facts=True)
recall_results: The raw recall results (when mode="recall")
results_count: Number of memories/results found
injected: Whether memories were actually injected into the prompt
error: Error message if injection failed (None on success)
"""
mode: str # "reflect" or "recall"
query: str
bank_id: str
memory_context: str # The formatted context that was injected
reflect_text: Optional[str] = None # Raw reflect response text
reflect_facts: Optional[List[dict]] = None # Facts used by reflect (when reflect_include_facts=True)
recall_results: Optional[List[dict]] = None # Raw recall results
results_count: int = 0
injected: bool = False
error: Optional[str] = None # Error message if injection failed
# Store the last injection debug info (populated when verbose=True)
_last_injection_debug: Optional[InjectionDebugInfo] = None
def get_last_injection_debug() -> Optional[InjectionDebugInfo]:
"""Get debug info from the last memory injection operation.
When verbose=True in the config, this returns information about
what memories were injected into the last completion() call.
Returns:
InjectionDebugInfo if verbose mode captured injection info, None otherwise
Example:
>>> from hindsight_litellm import configure, enable, completion, get_last_injection_debug
>>> configure(bank_id="my-agent", verbose=True, use_reflect=True)
>>> enable()
>>> response = completion(model="gpt-4o-mini", messages=[...])
>>> debug = get_last_injection_debug()
>>> if debug:
... print(f"Injected {debug.results_count} memories via {debug.mode}")
... print(f"Reflect text: {debug.reflect_text}")
"""
return _last_injection_debug
def clear_injection_debug() -> None:
"""Clear the stored injection debug info."""
global _last_injection_debug
_last_injection_debug = None
def _inject_memories(messages: List[dict]) -> List[dict]:
"""Inject memories into messages list.
Returns the modified messages list with memories injected into the system message.
Uses reflect API when config.use_reflect=True, otherwise uses recall API.
When verbose=True in config, stores debug info retrievable via get_last_injection_debug().
"""
global _last_injection_debug
import logging
# Clear previous debug info
_last_injection_debug = None
if not is_configured():
return messages
config = get_config()
if not config or not config.enabled or not config.inject_memories:
return messages
if not messages:
return messages
# Extract user query from last user message
user_query = None
for msg in reversed(messages):
if msg.get("role") == "user":
content = msg.get("content")
if isinstance(content, str):
user_query = content
break
if not user_query:
return messages
try:
from hindsight_client import Hindsight
# Use bank_id directly (no entity scoping)
bank_id = config.bank_id
# Track debug info
mode = "reflect" if config.use_reflect else "recall"
reflect_text = None
reflect_facts = None
recall_results = None
results_count = 0
memory_context = ""
# Create client
client = Hindsight(base_url=config.hindsight_api_url, timeout=30.0)
# Use reflect API if use_reflect is enabled
if config.use_reflect:
# If reflect_include_facts is enabled, use the API directly to include facts
if config.reflect_include_facts:
from hindsight_client_api.models import reflect_request, reflect_include_options
request_obj = reflect_request.ReflectRequest(
query=user_query,
budget=config.recall_budget or "mid",
include=reflect_include_options.ReflectIncludeOptions(facts={}),
)
import asyncio
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
result = loop.run_until_complete(client._api.reflect(bank_id, request_obj))
# Extract facts from based_on
if hasattr(result, 'based_on') and result.based_on:
reflect_facts = [
{
"text": f.text if hasattr(f, 'text') else str(f),
"type": getattr(f, 'type', None),
"context": getattr(f, 'context', None),
}
for f in result.based_on
]
else:
result = client.reflect(
bank_id=bank_id,
query=user_query,
budget=config.recall_budget or "mid",
)
reflect_text = result.text if hasattr(result, 'text') else str(result)
if not reflect_text:
# Store debug info for empty result
if config.verbose:
_last_injection_debug = InjectionDebugInfo(
mode=mode,
query=user_query,
bank_id=bank_id,
memory_context="",
reflect_text="",
reflect_facts=reflect_facts,
results_count=0,
injected=False,
)
return messages
results_count = 1 # reflect returns a single synthesized response
memory_context = (
"# Relevant Context from Memory\n"
f"{reflect_text}"
)
else:
# Use recall API (original behavior)
result = client.recall(
bank_id=bank_id,
query=user_query,
budget=config.recall_budget or "mid",
max_tokens=config.max_memory_tokens or 4096,
types=config.fact_types,
)
# client.recall() returns a list directly, not an object with .results
if isinstance(result, list):
results = result
elif hasattr(result, 'results'):
results = result.results
else:
results = []
# Convert to dicts for debug info
recall_results = [
{
"text": r.text if hasattr(r, 'text') else str(r),
"type": getattr(r, 'type', 'world'),
}
for r in results
]
if not results:
# Store debug info for empty result
if config.verbose:
_last_injection_debug = InjectionDebugInfo(
mode=mode,
query=user_query,
bank_id=bank_id,
memory_context="",
recall_results=[],
results_count=0,
injected=False,
)
return messages
# Format memories (apply limit if set, otherwise use all)
results_to_use = results[:config.max_memories] if config.max_memories else results
memory_lines = []
for i, r in enumerate(results_to_use, 1):
text = r.text if hasattr(r, 'text') else str(r)
fact_type = getattr(r, 'type', 'world')
if text:
type_label = fact_type.upper() if fact_type else "MEMORY"
memory_lines.append(f"{i}. [{type_label}] {text}")
if not memory_lines:
if config.verbose:
_last_injection_debug = InjectionDebugInfo(
mode=mode,
query=user_query,
bank_id=bank_id,
memory_context="",
recall_results=recall_results,
results_count=0,
injected=False,
)
return messages
results_count = len(memory_lines)
memory_context = (
"# Relevant Memories\n"
"The following information from memory may be relevant:\n\n"
+ "\n".join(memory_lines)
)
# Inject into messages
updated_messages = list(messages)
# Find existing system message or create new one
found_system = False
for i, msg in enumerate(updated_messages):
if msg.get("role") == "system":
existing_content = msg.get("content", "")
updated_messages[i] = {
**msg,
"content": f"{existing_content}\n\n{memory_context}"
}
found_system = True
break
if not found_system:
updated_messages.insert(0, {
"role": "system",
"content": memory_context
})
# Store debug info when verbose
if config.verbose:
_last_injection_debug = InjectionDebugInfo(
mode=mode,
query=user_query,
bank_id=bank_id,
memory_context=memory_context,
reflect_text=reflect_text,
reflect_facts=reflect_facts,
recall_results=recall_results,
results_count=results_count,
injected=True,
)
logger = logging.getLogger("hindsight_litellm")
logger.info(f"Injected memories using {mode} into prompt")
return updated_messages
except ImportError as e:
if config.verbose:
logging.getLogger("hindsight_litellm").warning(
f"hindsight_client not installed: {e}. Install with: pip install hindsight-client"
)
_last_injection_debug = InjectionDebugInfo(
mode="reflect" if config.use_reflect else "recall",
query=user_query or "",
bank_id=config.bank_id or "",
memory_context="",
results_count=0,
injected=False,
error=f"hindsight_client not installed: {e}",
)
return messages
except Exception as e:
# Always set debug info on error when verbose mode is on
if config.verbose:
logging.getLogger("hindsight_litellm").warning(f"Failed to inject memories: {e}")
_last_injection_debug = InjectionDebugInfo(
mode="reflect" if config.use_reflect else "recall",
query=user_query or "",
bank_id=config.bank_id or "",
memory_context="",
results_count=0,
injected=False,
error=str(e),
)
return messages
def _wrapped_completion(*args, **kwargs):
"""Wrapper for litellm.completion that injects memories before the call."""
# Inject memories into messages
if "messages" in kwargs:
kwargs["messages"] = _inject_memories(kwargs["messages"])
elif args and len(args) > 1:
# messages might be second positional arg after model
args = list(args)
if isinstance(args[1], list):
args[1] = _inject_memories(args[1])
args = tuple(args)
# Call original
return _original_completion(*args, **kwargs)
async def _wrapped_acompletion(*args, **kwargs):
"""Wrapper for litellm.acompletion that injects memories before the call."""
# Inject memories into messages
if "messages" in kwargs:
kwargs["messages"] = _inject_memories(kwargs["messages"])
elif args and len(args) > 1:
args = list(args)
if isinstance(args[1], list):
args[1] = _inject_memories(args[1])
args = tuple(args)
# Call original
return await _original_acompletion(*args, **kwargs)
def enable() -> None:
"""Enable Hindsight memory integration with LiteLLM.
This monkeypatches LiteLLM functions to:
1. Inject relevant memories into prompts before LLM calls
2. Store conversations to Hindsight after successful LLM calls
Must be called after configure() to take effect.
Example:
>>> from hindsight_litellm import configure, enable
>>> configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
>>> enable()
>>>
>>> # Now all LiteLLM calls will have memory integration
>>> import litellm
>>> response = litellm.completion(model="gpt-4", messages=[...])
"""
global _enabled, _original_completion, _original_acompletion
if _enabled:
return # Already enabled
if not is_configured():
raise RuntimeError(
"Hindsight not configured. Call configure() before enable()."
)
# Store original functions and monkeypatch for memory injection
_original_completion = litellm.completion
_original_acompletion = litellm.acompletion
litellm.completion = _wrapped_completion
litellm.acompletion = _wrapped_acompletion
# Get or create the callback instance for storing conversations
callback = get_callback()
# Register callback using litellm.callbacks for conversation storage
if callback not in litellm.callbacks:
litellm.callbacks.append(callback)
_enabled = True
config = get_config()
if config and config.verbose:
print(f"Hindsight memory enabled for bank: {config.bank_id}")
def disable() -> None:
"""Disable Hindsight memory integration with LiteLLM.
This restores the original LiteLLM functions and removes callbacks,
stopping memory injection and conversation storage.
Example:
>>> from hindsight_litellm import disable
>>> disable() # Stop memory integration
"""
global _enabled, _original_completion, _original_acompletion
if not _enabled:
return # Already disabled
# Restore original functions
if _original_completion is not None:
litellm.completion = _original_completion
_original_completion = None
if _original_acompletion is not None:
litellm.acompletion = _original_acompletion
_original_acompletion = None
# Remove callback from litellm.callbacks
callback = get_callback()
if callback in litellm.callbacks:
litellm.callbacks.remove(callback)
_enabled = False
config = get_config()
if config and config.verbose:
print("Hindsight memory disabled")
def is_enabled() -> bool:
"""Check if Hindsight memory integration is currently enabled.
Returns:
True if enable() has been called and not subsequently disabled
"""
return _enabled
def cleanup() -> None:
"""Clean up all Hindsight resources.
This disables the integration and closes any open connections.
Call this when shutting down your application.
Example:
>>> from hindsight_litellm import cleanup
>>> cleanup() # Clean up when done
"""
disable()
cleanup_callback()
reset_config()
# =============================================================================
# Convenience wrappers - use hindsight_litellm.completion() directly
# =============================================================================
def completion(*args, **kwargs):
"""Call LiteLLM completion with Hindsight memory integration.
This is a convenience wrapper that delegates to litellm.completion().
Memory injection and storage happen automatically if configured and enabled.
Args:
*args: Positional arguments passed to litellm.completion()
**kwargs: Keyword arguments passed to litellm.completion()
Returns:
LiteLLM ModelResponse object
Example:
>>> import hindsight_litellm
>>>
>>> hindsight_litellm.configure(
... hindsight_api_url="http://localhost:8888",
... bank_id="my-agent",
... )
>>> hindsight_litellm.enable()
>>>
>>> # Use directly - no need to import litellm separately
>>> response = hindsight_litellm.completion(
... model="gpt-4o-mini",
... messages=[{"role": "user", "content": "Hello!"}]
... )
"""
return litellm.completion(*args, **kwargs)
async def acompletion(*args, **kwargs):
"""Call LiteLLM async completion with Hindsight memory integration.
This is a convenience wrapper that delegates to litellm.acompletion().
Memory injection and storage happen automatically if configured and enabled.
Args:
*args: Positional arguments passed to litellm.acompletion()
**kwargs: Keyword arguments passed to litellm.acompletion()
Returns:
LiteLLM ModelResponse object
Example:
>>> import hindsight_litellm
>>> import asyncio
>>>
>>> hindsight_litellm.configure(
... hindsight_api_url="http://localhost:8888",
... bank_id="my-agent",
... )
>>> hindsight_litellm.enable()
>>>
>>> async def main():
... response = await hindsight_litellm.acompletion(
... model="gpt-4o-mini",
... messages=[{"role": "user", "content": "Hello!"}]
... )
... return response
>>>
>>> asyncio.run(main())
"""
return await litellm.acompletion(*args, **kwargs)
@contextmanager
def hindsight_memory(
hindsight_api_url: str = "http://localhost:8888",
bank_id: Optional[str] = None,
api_key: Optional[str] = None,
store_conversations: bool = True,
inject_memories: bool = True,
injection_mode: MemoryInjectionMode = MemoryInjectionMode.SYSTEM_MESSAGE,
max_memories: Optional[int] = None,
max_memory_tokens: int = 4096,
recall_budget: str = "mid",
fact_types: Optional[List[str]] = None,
document_id: Optional[str] = None,
excluded_models: Optional[List[str]] = None,
verbose: bool = False,
bank_name: Optional[str] = None,
background: Optional[str] = None,
):
"""Context manager for temporary Hindsight memory integration.
Use this to enable memory integration for a specific block of code,
automatically cleaning up afterwards.
Args:
hindsight_api_url: URL of the Hindsight API server
bank_id: Memory bank ID for memory operations (required). For multi-user
support, use different bank_ids per user (e.g., f"user-{user_id}")
api_key: Optional API key for Hindsight authentication
store_conversations: Whether to store conversations
inject_memories: Whether to inject relevant memories
injection_mode: How to inject memories
max_memories: Maximum number of memories to inject (None = unlimited)
max_memory_tokens: Maximum tokens for memory context
recall_budget: Budget for memory recall (low, mid, high)
fact_types: List of fact types to filter (world, agent, opinion, observation)
document_id: Optional document ID for grouping conversations
excluded_models: List of model patterns to exclude
verbose: Enable verbose logging
bank_name: Optional display name for the memory bank
background: Optional background/instructions for memory extraction
Example:
>>> from hindsight_litellm import hindsight_memory
>>> import litellm
>>>
>>> with hindsight_memory(bank_id="user-123"):
... response = litellm.completion(model="gpt-4", messages=[...])
>>> # Memory integration automatically disabled after context
"""
# Save previous state
was_enabled = is_enabled()
previous_config = get_config()
try:
# Configure and enable
configure(
hindsight_api_url=hindsight_api_url,
bank_id=bank_id,
api_key=api_key,
store_conversations=store_conversations,
inject_memories=inject_memories,
injection_mode=injection_mode,
max_memories=max_memories,
max_memory_tokens=max_memory_tokens,
recall_budget=recall_budget,
fact_types=fact_types,
document_id=document_id,
excluded_models=excluded_models,
verbose=verbose,
bank_name=bank_name,
background=background,
)
enable()
yield
finally:
# Restore previous state
disable()
if previous_config:
configure(
hindsight_api_url=previous_config.hindsight_api_url,
bank_id=previous_config.bank_id,
api_key=previous_config.api_key,
store_conversations=previous_config.store_conversations,
inject_memories=previous_config.inject_memories,
injection_mode=previous_config.injection_mode,
max_memories=previous_config.max_memories,
max_memory_tokens=previous_config.max_memory_tokens,
recall_budget=previous_config.recall_budget,
fact_types=previous_config.fact_types,
document_id=previous_config.document_id,
excluded_models=previous_config.excluded_models,
verbose=previous_config.verbose,
bank_name=previous_config.bank_name,
background=previous_config.background,
)
if was_enabled:
enable()
else:
reset_config()
__all__ = [
# Main API
"configure",
"enable",
"disable",
"is_enabled",
"cleanup",
"hindsight_memory",
# LLM completion wrappers (convenience)
"completion",
"acompletion",
# Direct memory APIs
"recall",
"arecall",
"RecallResult",
"reflect",
"areflect",
"ReflectResult",
"retain",
"aretain",
"RetainResult",
# Native client wrappers
"wrap_openai",
"wrap_anthropic",
"HindsightOpenAI",
"HindsightAnthropic",
# Configuration
"get_config",
"is_configured",
"reset_config",
"HindsightConfig",
"MemoryInjectionMode",
# Injection debug (verbose mode)
"get_last_injection_debug",
"clear_injection_debug",
"InjectionDebugInfo",
# Callback (for advanced usage)
"HindsightCallback",
"get_callback",
"cleanup_callback",
]
@@ -0,0 +1,640 @@
"""LiteLLM callback handlers for Hindsight memory integration.
This module implements LiteLLM's CustomLogger interface to intercept
LLM calls and integrate with Hindsight for memory injection and storage.
Uses direct HTTP calls via requests/httpx to avoid async event loop conflicts
when the hindsight_client's async methods are called from LiteLLM callbacks.
"""
import logging
import fnmatch
import hashlib
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Set
import asyncio
import threading
import concurrent.futures
from litellm.integrations.custom_logger import CustomLogger
from litellm.types.utils import ModelResponse
from .config import get_config, is_configured, HindsightConfig, MemoryInjectionMode
# Use requests for sync HTTP calls to avoid async event loop issues
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
try:
import httpx
HAS_HTTPX = True
except ImportError:
HAS_HTTPX = False
logger = logging.getLogger(__name__)
# Thread pool for running async operations in background
_executor = concurrent.futures.ThreadPoolExecutor(max_workers=4, thread_name_prefix="hindsight-")
class HindsightCallback(CustomLogger):
"""LiteLLM custom logger that integrates with Hindsight memory system.
This callback handler:
1. Injects relevant memories into prompts before LLM calls
2. Stores conversations to Hindsight after successful LLM calls
Features:
- Works with 100+ LLM providers via LiteLLM
- Deduplication to avoid storing duplicate conversations
- Configurable memory injection modes
- Support for entity observations in recall
Usage:
>>> from hindsight_litellm import configure, enable
>>> configure(bank_id="my-agent", hindsight_api_url="http://localhost:8888")
>>> enable()
>>>
>>> # Now all LiteLLM calls will have memory integration
>>> import litellm
>>> response = litellm.completion(
... model="gpt-4",
... messages=[{"role": "user", "content": "What did we discuss?"}]
... )
"""
def __init__(self):
"""Initialize the Hindsight callback handler."""
super().__init__()
self._http_session = None
self._http_lock = threading.Lock()
# Track recently stored conversation hashes for deduplication
self._recent_hashes: Set[str] = set()
self._max_hash_cache = 1000
def _get_http_session(self):
"""Get or create a requests Session (thread-safe)."""
if self._http_session is None:
with self._http_lock:
if self._http_session is None:
if HAS_REQUESTS:
self._http_session = requests.Session()
elif HAS_HTTPX:
self._http_session = httpx.Client(timeout=30.0)
else:
raise RuntimeError(
"Neither 'requests' nor 'httpx' is installed. "
"Please install one: pip install requests"
)
return self._http_session
def _http_post(self, url: str, json_data: dict, config: HindsightConfig) -> Optional[dict]:
"""Make a synchronous HTTP POST request."""
try:
session = self._get_http_session()
headers = {"Content-Type": "application/json"}
if config.api_key:
headers["Authorization"] = f"Bearer {config.api_key}"
if HAS_REQUESTS:
response = session.post(url, json=json_data, headers=headers, timeout=30)
response.raise_for_status()
return response.json()
elif HAS_HTTPX:
response = session.post(url, json=json_data, headers=headers)
response.raise_for_status()
return response.json()
except Exception as e:
if config.verbose:
logger.warning(f"HTTP POST failed: {e}")
return None
def _should_skip_model(self, model: str, config: HindsightConfig) -> bool:
"""Check if this model should be excluded from interception."""
for pattern in config.excluded_models:
if fnmatch.fnmatch(model.lower(), pattern.lower()):
return True
return False
def _extract_user_query(self, messages: List[Dict[str, Any]]) -> Optional[str]:
"""Extract the user's query from the last user message."""
for msg in reversed(messages):
role = msg.get("role", "")
if role == "user":
content = msg.get("content")
if isinstance(content, str):
return content
elif isinstance(content, list):
# Handle structured content (e.g., vision messages)
text_parts = []
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
text_parts.append(item.get("text", ""))
if text_parts:
return " ".join(text_parts)
return None
def _compute_conversation_hash(
self,
user_input: str,
assistant_output: str,
) -> str:
"""Compute a hash for deduplication."""
content = f"{user_input.strip().lower()}|{assistant_output.strip().lower()}"
return hashlib.md5(content.encode()).hexdigest()[:16]
def _is_duplicate(self, conv_hash: str) -> bool:
"""Check if this conversation was recently stored."""
if conv_hash in self._recent_hashes:
return True
# Add to cache, evict oldest if full
self._recent_hashes.add(conv_hash)
if len(self._recent_hashes) > self._max_hash_cache:
# Remove oldest (arbitrary since set, but good enough)
self._recent_hashes.pop()
return False
def _format_memories(
self,
results: List[Any],
config: HindsightConfig
) -> str:
"""Format memory recall results into a context string.
Results can be RecallResult objects (with .text, .type attributes)
or dicts (with get() method).
"""
if not results:
return ""
# Apply limit if set, otherwise use all results
results_to_use = results[:config.max_memories] if config.max_memories else results
memory_lines = []
for i, result in enumerate(results_to_use, 1):
# Handle both RecallResult objects and dicts
if hasattr(result, 'text'):
text = result.text or ""
fact_type = getattr(result, 'type', 'world') or "world"
weight = getattr(result, 'weight', 0.0) or 0.0
else:
text = result.get("text", "")
fact_type = result.get("type", result.get("fact_type", "world"))
weight = result.get("weight", 0.0)
if text:
# Include metadata for context
type_label = fact_type.upper() if fact_type else "MEMORY"
line = f"{i}. [{type_label}] {text}"
if weight > 0 and config.verbose:
line += f" (relevance: {weight:.2f})"
memory_lines.append(line)
if not memory_lines:
return ""
return (
"# Relevant Memories\n"
"The following information from memory may be relevant:\n\n"
+ "\n".join(memory_lines)
)
def _inject_memories_into_messages(
self,
messages: List[Dict[str, Any]],
memory_context: str,
config: HindsightConfig,
) -> List[Dict[str, Any]]:
"""Inject memory context into the messages list."""
if not memory_context:
return messages
updated_messages = list(messages) # Make a copy
if config.injection_mode == MemoryInjectionMode.SYSTEM_MESSAGE:
# Find existing system message or create new one
for i, msg in enumerate(updated_messages):
if msg.get("role") == "system":
# Append to existing system message
existing_content = msg.get("content", "")
updated_messages[i] = {
**msg,
"content": f"{existing_content}\n\n{memory_context}"
}
return updated_messages
# No system message found, prepend one
updated_messages.insert(0, {
"role": "system",
"content": memory_context
})
elif config.injection_mode == MemoryInjectionMode.PREPEND_USER:
# Find the last user message and prepend context
for i in range(len(updated_messages) - 1, -1, -1):
if updated_messages[i].get("role") == "user":
original_content = updated_messages[i].get("content", "")
if isinstance(original_content, str):
updated_messages[i] = {
**updated_messages[i],
"content": f"{memory_context}\n\n---\n\n{original_content}"
}
break
return updated_messages
def _get_bank_id(self, config: HindsightConfig) -> str:
"""Get the bank_id for API calls."""
return config.bank_id
def _recall_memories_sync(
self,
query: str,
config: HindsightConfig
) -> List[Dict[str, Any]]:
"""Recall relevant memories from Hindsight (sync) using direct HTTP."""
try:
bank_id = self._get_bank_id(config)
url = f"{config.hindsight_api_url}/v1/default/banks/{bank_id}/memories/recall"
request_data = {
"query": query,
"budget": config.recall_budget or "mid",
"max_tokens": config.max_memory_tokens or 4096,
}
if config.fact_types:
request_data["types"] = config.fact_types
response = self._http_post(url, request_data, config)
if response and "results" in response:
return response["results"]
return []
except Exception as e:
if config.verbose:
logger.warning(f"Failed to recall memories: {e}")
return []
async def _recall_memories_async(
self,
query: str,
config: HindsightConfig
) -> List[Any]:
"""Recall relevant memories from Hindsight (async).
Uses thread pool executor with sync HTTP to avoid event loop conflicts.
"""
try:
loop = asyncio.get_running_loop()
results = await loop.run_in_executor(
_executor,
self._recall_memories_sync,
query,
config
)
return results if isinstance(results, list) else []
except Exception as e:
if config.verbose:
logger.warning(f"Failed to recall memories: {e}")
return []
def _store_conversation_sync(
self,
messages: List[Dict[str, Any]],
response: ModelResponse,
model: str,
config: HindsightConfig,
) -> None:
"""Store the conversation to Hindsight (sync) using direct HTTP.
By default, stores the full conversation history passed to the LLM.
Each message is stored as a separate item, all linked by document_id.
Hindsight will process the document as a whole for memory extraction.
"""
try:
# Extract assistant response from the LLM response
assistant_output = ""
if response.choices and len(response.choices) > 0:
choice = response.choices[0]
if hasattr(choice, "message") and choice.message:
assistant_output = choice.message.content or ""
if not assistant_output:
return
# Build conversation items - each message becomes a separate item
# All linked by document_id for Hindsight to process together
items = []
for msg in messages:
role = msg.get("role", "").upper()
content = msg.get("content", "")
# Skip system messages - they're instructions, not conversation
if role == "SYSTEM":
continue
# Skip if this looks like our injected memory context
if isinstance(content, str) and content.startswith("# Relevant Memories"):
continue
# Handle structured content (e.g., vision messages)
if isinstance(content, list):
text_parts = []
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
text_parts.append(item.get("text", ""))
content = " ".join(text_parts)
if content:
# Map roles to clearer labels
label = "USER" if role == "USER" else "ASSISTANT"
items.append(f"{label}: {content}")
# Add the new assistant response
items.append(f"ASSISTANT: {assistant_output}")
if not items:
return
# Use last user message for deduplication hash
user_input = self._extract_user_query(messages) or ""
# Deduplication check
conv_hash = self._compute_conversation_hash(user_input, assistant_output)
if self._is_duplicate(conv_hash):
if config.verbose:
logger.debug(f"Skipping duplicate conversation: {conv_hash}")
return
# Build the full conversation as a single item for now
# (Future: could store each message as separate item in same document)
conversation_text = "\n\n".join(items)
# Build metadata
metadata = {
"source": "litellm",
"model": model,
}
# Add token usage if available
if hasattr(response, "usage") and response.usage:
if hasattr(response.usage, "total_tokens"):
metadata["tokens"] = str(response.usage.total_tokens)
bank_id = self._get_bank_id(config)
url = f"{config.hindsight_api_url}/v1/default/banks/{bank_id}/memories"
request_data = {
"items": [
{
"content": conversation_text,
"context": f"conversation:litellm:{model}",
"metadata": metadata,
"document_id": config.document_id, # Group by document
}
],
}
self._http_post(url, request_data, config)
if config.verbose:
logger.info(f"Stored conversation to Hindsight bank: {config.bank_id}")
except Exception as e:
if config.verbose:
logger.warning(f"Failed to store conversation: {e}")
async def _store_conversation_async(
self,
messages: List[Dict[str, Any]],
response: ModelResponse,
model: str,
config: HindsightConfig,
) -> None:
"""Store the conversation to Hindsight (async).
Uses thread pool executor with sync HTTP to avoid event loop conflicts.
"""
try:
loop = asyncio.get_running_loop()
await loop.run_in_executor(
_executor,
self._store_conversation_sync,
messages,
response,
model,
config
)
except Exception as e:
if config.verbose:
logger.warning(f"Failed to store conversation: {e}")
# ========== LiteLLM CustomLogger Interface ==========
def log_pre_api_call(
self,
model: str,
messages: List[Dict[str, Any]],
kwargs: Dict[str, Any],
) -> None:
"""Called before making the API call (sync).
This is where we inject memories into the messages.
"""
if not is_configured():
return
config = get_config()
if not config or not config.enabled or not config.inject_memories:
return
if self._should_skip_model(model, config):
return
# Extract user query
user_query = self._extract_user_query(messages)
if not user_query:
return
# Recall relevant memories
memories = self._recall_memories_sync(user_query, config)
if not memories:
return
# Format and inject memories
memory_context = self._format_memories(memories, config)
updated_messages = self._inject_memories_into_messages(
messages, memory_context, config
)
# Modify messages list IN-PLACE (don't just reassign kwargs)
messages.clear()
messages.extend(updated_messages)
if config.verbose:
logger.info(f"Injected {len(memories)} memories into prompt")
async def async_log_pre_api_call(
self,
model: str,
messages: List[Dict[str, Any]],
kwargs: Dict[str, Any],
) -> None:
"""Called before making the API call (async).
This is where we inject memories into the messages.
"""
if not is_configured():
return
config = get_config()
if not config or not config.enabled or not config.inject_memories:
return
if self._should_skip_model(model, config):
return
# Extract user query
user_query = self._extract_user_query(messages)
if not user_query:
return
# Recall relevant memories
memories = await self._recall_memories_async(user_query, config)
if not memories:
return
# Format and inject memories
memory_context = self._format_memories(memories, config)
updated_messages = self._inject_memories_into_messages(
messages, memory_context, config
)
# Modify messages list IN-PLACE (don't just reassign kwargs)
messages.clear()
messages.extend(updated_messages)
if config.verbose:
logger.info(f"Injected {len(memories)} memories into prompt")
def log_success_event(
self,
kwargs: Dict[str, Any],
response_obj: Any,
start_time: float,
end_time: float,
) -> None:
"""Called after successful API call (sync).
This is where we store the conversation.
"""
if not is_configured():
return
config = get_config()
if not config or not config.enabled or not config.store_conversations:
return
model = kwargs.get("model", "unknown")
if self._should_skip_model(model, config):
return
messages = kwargs.get("messages", [])
if not messages:
return
# Store the conversation
self._store_conversation_sync(messages, response_obj, model, config)
async def async_log_success_event(
self,
kwargs: Dict[str, Any],
response_obj: Any,
start_time: float,
end_time: float,
) -> None:
"""Called after successful API call (async).
This is where we store the conversation.
"""
if not is_configured():
return
config = get_config()
if not config or not config.enabled or not config.store_conversations:
return
model = kwargs.get("model", "unknown")
if self._should_skip_model(model, config):
return
messages = kwargs.get("messages", [])
if not messages:
return
# Store the conversation
await self._store_conversation_async(messages, response_obj, model, config)
def log_failure_event(
self,
kwargs: Dict[str, Any],
response_obj: Any,
start_time: float,
end_time: float,
) -> None:
"""Called after failed API call (sync)."""
# We don't store failed conversations
pass
async def async_log_failure_event(
self,
kwargs: Dict[str, Any],
response_obj: Any,
start_time: float,
end_time: float,
) -> None:
"""Called after failed API call (async)."""
# We don't store failed conversations
pass
def close(self) -> None:
"""Clean up resources."""
with self._http_lock:
if self._http_session is not None:
try:
if HAS_REQUESTS:
self._http_session.close()
elif HAS_HTTPX:
self._http_session.close()
except Exception:
pass
self._http_session = None
self._recent_hashes.clear()
# Global callback instance
_callback: Optional[HindsightCallback] = None
def get_callback() -> HindsightCallback:
"""Get the global callback instance, creating it if necessary."""
global _callback
if _callback is None:
_callback = HindsightCallback()
return _callback
def cleanup_callback() -> None:
"""Clean up the global callback instance."""
global _callback
if _callback is not None:
_callback.close()
_callback = None
@@ -0,0 +1,232 @@
"""Global configuration for Hindsight-LiteLLM integration."""
from typing import Optional, List
from dataclasses import dataclass, field
from enum import Enum
class MemoryInjectionMode(str, Enum):
"""How memories should be injected into the prompt."""
SYSTEM_MESSAGE = "system_message" # Add as system message
PREPEND_USER = "prepend_user" # Prepend to user message
DISABLED = "disabled" # Don't inject memories
@dataclass
class HindsightConfig:
"""Configuration for Hindsight integration with LiteLLM.
Attributes:
hindsight_api_url: URL of the Hindsight API server
bank_id: Memory bank ID for memory operations (required). For multi-user
support, use different bank_ids per user (e.g., f"user-{user_id}")
api_key: Optional API key for Hindsight authentication
store_conversations: Whether to store conversations to Hindsight
inject_memories: Whether to inject relevant memories into prompts
injection_mode: How to inject memories (system_message or prepend_user)
max_memories: Maximum number of memories to inject
max_memory_tokens: Maximum tokens for injected memory context
recall_budget: Budget level for memory recall (low, mid, high)
fact_types: List of fact types to filter recall (world, agent, opinion, observation)
document_id: Optional document ID for grouping stored conversations
enabled: Master switch to enable/disable Hindsight integration
excluded_models: List of model patterns to exclude from interception
verbose: Enable verbose logging
bank_name: Optional display name for the memory bank
background: Optional background/instructions for memory extraction
use_reflect: Use reflect API instead of recall for memory injection (synthesizes answer)
"""
hindsight_api_url: str = "http://localhost:8888"
bank_id: Optional[str] = None
api_key: Optional[str] = None
store_conversations: bool = True
inject_memories: bool = True
injection_mode: MemoryInjectionMode = MemoryInjectionMode.SYSTEM_MESSAGE
max_memories: Optional[int] = None # None = no limit (use all results from API)
max_memory_tokens: int = 4096
recall_budget: str = "mid" # low, mid, high
fact_types: Optional[List[str]] = None # world, agent, opinion, observation
document_id: Optional[str] = None
enabled: bool = True
excluded_models: List[str] = field(default_factory=list)
verbose: bool = False
bank_name: Optional[str] = None # Display name for the memory bank
background: Optional[str] = None # Background/instructions for memory extraction
use_reflect: bool = False # Use reflect instead of recall for memory injection
reflect_include_facts: bool = False # Include facts used by reflect in debug info
# Global configuration instance
_global_config: Optional[HindsightConfig] = None
def configure(
hindsight_api_url: str = "http://localhost:8888",
bank_id: Optional[str] = None,
api_key: Optional[str] = None,
store_conversations: bool = True,
inject_memories: bool = True,
injection_mode: MemoryInjectionMode = MemoryInjectionMode.SYSTEM_MESSAGE,
max_memories: Optional[int] = None,
max_memory_tokens: int = 4096,
recall_budget: str = "mid",
fact_types: Optional[List[str]] = None,
document_id: Optional[str] = None,
enabled: bool = True,
excluded_models: Optional[List[str]] = None,
verbose: bool = False,
bank_name: Optional[str] = None,
background: Optional[str] = None,
use_reflect: bool = False,
reflect_include_facts: bool = False,
) -> HindsightConfig:
"""Configure global Hindsight integration settings for LiteLLM.
This function sets up the global configuration that will be used by the
LiteLLM callbacks to inject memories and store conversations.
Args:
hindsight_api_url: URL of the Hindsight API server
bank_id: Memory bank ID for memory operations (required). For multi-user
support, use different bank_ids per user (e.g., f"user-{user_id}")
api_key: Optional API key for Hindsight authentication
store_conversations: Whether to store conversations to Hindsight
inject_memories: Whether to inject relevant memories into prompts
injection_mode: How to inject memories into the prompt
max_memories: Maximum number of memories to inject
max_memory_tokens: Maximum tokens for injected memory context
recall_budget: Budget level for memory recall (low, mid, high)
fact_types: List of fact types to filter (world, agent, opinion, observation)
document_id: Optional document ID for grouping stored conversations
enabled: Master switch to enable/disable Hindsight integration
excluded_models: List of model patterns to exclude from interception
verbose: Enable verbose logging
bank_name: Optional display name for the memory bank
background: Optional background/instructions that help Hindsight understand
what information is important to extract and remember from conversations.
This is passed to create_bank() to configure the memory bank.
use_reflect: Use reflect API instead of recall for memory injection.
When True, Hindsight will synthesize a contextual answer based on
memories rather than returning raw memory facts.
reflect_include_facts: When use_reflect=True, include the facts that
were used to generate the reflect response in the debug info.
This is useful for debugging what memories the reflect API used.
Returns:
The configured HindsightConfig instance
Example:
>>> from hindsight_litellm import configure, enable
>>> configure(
... hindsight_api_url="http://localhost:8888",
... bank_id="user-123", # Per-user bank for multi-user support
... store_conversations=True,
... inject_memories=True,
... background="This agent routes customer requests to support channels. "
... "Remember which types of issues should go to which channels.",
... )
>>> enable() # Register callbacks with LiteLLM
"""
global _global_config
_global_config = HindsightConfig(
hindsight_api_url=hindsight_api_url,
bank_id=bank_id,
api_key=api_key,
store_conversations=store_conversations,
inject_memories=inject_memories,
injection_mode=injection_mode,
max_memories=max_memories,
max_memory_tokens=max_memory_tokens,
recall_budget=recall_budget,
fact_types=fact_types,
document_id=document_id,
enabled=enabled,
excluded_models=excluded_models or [],
verbose=verbose,
bank_name=bank_name,
background=background,
use_reflect=use_reflect,
reflect_include_facts=reflect_include_facts,
)
# If background or bank_name is provided, create/update the bank
if bank_id and (background or bank_name):
_create_or_update_bank(
hindsight_api_url=hindsight_api_url,
bank_id=bank_id,
name=bank_name,
background=background,
verbose=verbose,
)
return _global_config
def _create_or_update_bank(
hindsight_api_url: str,
bank_id: str,
name: Optional[str] = None,
background: Optional[str] = None,
verbose: bool = False,
) -> None:
"""Create or update a memory bank with the given configuration.
This is called automatically by configure() when background or bank_name is provided.
"""
try:
from hindsight_client import Hindsight
client = Hindsight(hindsight_api_url)
client.create_bank(
bank_id=bank_id,
name=name,
background=background,
)
if verbose:
import logging
logging.getLogger("hindsight_litellm").info(
f"Created/updated bank '{bank_id}' with background"
)
except ImportError:
if verbose:
import logging
logging.getLogger("hindsight_litellm").warning(
"hindsight_client not installed. Cannot create bank with background. "
"Install with: pip install hindsight-client"
)
except Exception as e:
if verbose:
import logging
logging.getLogger("hindsight_litellm").warning(
f"Failed to create/update bank: {e}"
)
def get_config() -> Optional[HindsightConfig]:
"""Get the current global configuration.
Returns:
The current HindsightConfig instance, or None if not configured
"""
return _global_config
def is_configured() -> bool:
"""Check if Hindsight has been configured.
Returns:
True if configure() has been called with a valid bank_id
"""
return (
_global_config is not None
and _global_config.enabled
and _global_config.bank_id is not None
)
def reset_config() -> None:
"""Reset the global configuration to None."""
global _global_config
_global_config = None
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,59 @@
[project]
name = "hindsight-litellm"
version = "0.1.5"
description = "Universal LLM memory integration via LiteLLM - works with 100+ providers"
readme = "README.md"
requires-python = ">=3.10"
license = { text = "MIT" }
authors = [
{ name = "Vectorize", email = "[email protected]" }
]
keywords = [
"ai",
"memory",
"llm",
"litellm",
"openai",
"anthropic",
"groq",
"langchain",
"agents",
"hindsight",
]
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
]
dependencies = [
"litellm>=1.40.0",
]
[project.optional-dependencies]
dev = [
"pytest>=7.0.0",
"pytest-asyncio>=0.21.0",
"pytest-mock>=3.10.0",
]
[project.urls]
Homepage = "https://github.com/vectorize-io/hindsight"
Documentation = "https://github.com/vectorize-io/hindsight/tree/main/hindsight-integrations/litellm"
Repository = "https://github.com/vectorize-io/hindsight"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["hindsight_litellm"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
testpaths = ["tests"]
@@ -0,0 +1 @@
# Tests for hindsight-litellm
@@ -0,0 +1,471 @@
"""Integration tests for hindsight-litellm."""
import pytest
from unittest.mock import Mock, patch, MagicMock
from typing import List, Dict, Any
from hindsight_litellm import (
configure,
enable,
disable,
is_enabled,
cleanup,
get_config,
is_configured,
reset_config,
HindsightConfig,
MemoryInjectionMode,
)
from hindsight_litellm.callbacks import HindsightCallback, get_callback, cleanup_callback
class TestConfiguration:
"""Tests for configuration management."""
def setup_method(self):
"""Reset config before each test."""
reset_config()
disable()
def teardown_method(self):
"""Clean up after each test."""
cleanup()
def test_configure_creates_config(self):
"""Test that configure creates a config object."""
config = configure(
bank_id="test-agent",
hindsight_api_url="http://localhost:8888",
)
assert config is not None
assert config.bank_id == "test-agent"
assert config.hindsight_api_url == "http://localhost:8888"
assert config.enabled is True
def test_configure_with_all_options(self):
"""Test configure with all options."""
config = configure(
hindsight_api_url="http://custom:9999",
bank_id="custom-agent",
api_key="secret-key",
store_conversations=False,
inject_memories=False,
injection_mode=MemoryInjectionMode.PREPEND_USER,
max_memories=5,
max_memory_tokens=1000,
recall_budget="high",
fact_types=["world", "opinion"],
document_id="doc-123",
enabled=True,
excluded_models=["gpt-3.5*"],
verbose=True,
)
assert config.hindsight_api_url == "http://custom:9999"
assert config.bank_id == "custom-agent"
assert config.api_key == "secret-key"
assert config.store_conversations is False
assert config.inject_memories is False
assert config.injection_mode == MemoryInjectionMode.PREPEND_USER
assert config.max_memories == 5
assert config.max_memory_tokens == 1000
assert config.recall_budget == "high"
assert config.fact_types == ["world", "opinion"]
assert config.document_id == "doc-123"
assert config.excluded_models == ["gpt-3.5*"]
assert config.verbose is True
def test_is_configured_without_bank_id(self):
"""Test is_configured returns False without bank_id."""
configure(hindsight_api_url="http://localhost:8888")
assert is_configured() is False
def test_is_configured_with_bank_id(self):
"""Test is_configured returns True with bank_id."""
configure(bank_id="test-agent")
assert is_configured() is True
def test_reset_config(self):
"""Test reset_config clears the configuration."""
configure(bank_id="test-agent")
assert is_configured() is True
reset_config()
assert get_config() is None
assert is_configured() is False
class TestEnableDisable:
"""Tests for enable/disable functionality."""
def setup_method(self):
"""Reset state before each test."""
cleanup()
def teardown_method(self):
"""Clean up after each test."""
cleanup()
def test_enable_without_config_raises(self):
"""Test enable raises error without configuration."""
with pytest.raises(RuntimeError, match="not configured"):
enable()
def test_enable_registers_callback(self):
"""Test enable registers callback with LiteLLM."""
import litellm
configure(bank_id="test-agent")
enable()
callback = get_callback()
assert callback in litellm.callbacks
assert is_enabled() is True
def test_disable_removes_callback(self):
"""Test disable removes callback from LiteLLM."""
import litellm
configure(bank_id="test-agent")
enable()
assert is_enabled() is True
disable()
callback = get_callback()
assert callback not in litellm.callbacks
assert is_enabled() is False
def test_enable_idempotent(self):
"""Test enable is idempotent (can be called multiple times)."""
import litellm
configure(bank_id="test-agent")
# Enable multiple times
enable()
enable()
enable()
# Should only have one callback
callback = get_callback()
assert litellm.callbacks.count(callback) == 1
class TestCallback:
"""Tests for the HindsightCallback class."""
def setup_method(self):
"""Reset state before each test."""
cleanup()
def teardown_method(self):
"""Clean up after each test."""
cleanup()
def test_extract_user_query_simple(self):
"""Test extracting user query from simple messages."""
callback = HindsightCallback()
messages = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "What is the capital of France?"},
]
query = callback._extract_user_query(messages)
assert query == "What is the capital of France?"
def test_extract_user_query_from_last_user_message(self):
"""Test extracting query from last user message."""
callback = HindsightCallback()
messages = [
{"role": "user", "content": "First question"},
{"role": "assistant", "content": "First answer"},
{"role": "user", "content": "Second question"},
]
query = callback._extract_user_query(messages)
assert query == "Second question"
def test_extract_user_query_structured_content(self):
"""Test extracting query from structured content (vision)."""
callback = HindsightCallback()
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{"type": "image_url", "image_url": {"url": "http://example.com/img.png"}},
],
},
]
query = callback._extract_user_query(messages)
assert query == "What's in this image?"
def test_extract_user_query_multiple_text_parts(self):
"""Test extracting query with multiple text parts."""
callback = HindsightCallback()
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "First part."},
{"type": "text", "text": "Second part."},
],
},
]
query = callback._extract_user_query(messages)
assert query == "First part. Second part."
def test_format_memories(self):
"""Test formatting memories into context string."""
callback = HindsightCallback()
config = HindsightConfig(bank_id="test", max_memories=10, verbose=False)
memories = [
{"text": "User likes Python", "fact_type": "world", "weight": 0.95},
{"text": "User works at Google", "fact_type": "world", "weight": 0.8},
]
formatted = callback._format_memories(memories, config)
assert "Relevant Memories" in formatted
assert "User likes Python" in formatted
assert "User works at Google" in formatted
assert "[WORLD]" in formatted
def test_format_memories_with_verbose(self):
"""Test formatting memories with verbose mode shows weights."""
callback = HindsightCallback()
config = HindsightConfig(bank_id="test", max_memories=10, verbose=True)
memories = [
{"text": "User likes Python", "fact_type": "world", "weight": 0.95},
]
formatted = callback._format_memories(memories, config)
assert "relevance: 0.95" in formatted
def test_inject_memories_as_system_message(self):
"""Test injecting memories as system message."""
callback = HindsightCallback()
config = HindsightConfig(
bank_id="test",
injection_mode=MemoryInjectionMode.SYSTEM_MESSAGE,
)
messages = [
{"role": "user", "content": "Hello"},
]
memory_context = "# Relevant Memories\n1. User is John"
result = callback._inject_memories_into_messages(messages, memory_context, config)
assert len(result) == 2
assert result[0]["role"] == "system"
assert "Relevant Memories" in result[0]["content"]
assert result[1]["role"] == "user"
def test_inject_memories_prepend_to_existing_system(self):
"""Test injecting memories appends to existing system message."""
callback = HindsightCallback()
config = HindsightConfig(
bank_id="test",
injection_mode=MemoryInjectionMode.SYSTEM_MESSAGE,
)
messages = [
{"role": "system", "content": "You are helpful."},
{"role": "user", "content": "Hello"},
]
memory_context = "# Relevant Memories\n1. User is John"
result = callback._inject_memories_into_messages(messages, memory_context, config)
assert len(result) == 2
assert result[0]["role"] == "system"
assert "You are helpful." in result[0]["content"]
assert "Relevant Memories" in result[0]["content"]
def test_inject_memories_prepend_user_mode(self):
"""Test injecting memories in prepend_user mode."""
callback = HindsightCallback()
config = HindsightConfig(
bank_id="test",
injection_mode=MemoryInjectionMode.PREPEND_USER,
)
messages = [
{"role": "user", "content": "What's my name?"},
]
memory_context = "# Relevant Memories\n1. User is John"
result = callback._inject_memories_into_messages(messages, memory_context, config)
assert len(result) == 1
assert result[0]["role"] == "user"
assert "Relevant Memories" in result[0]["content"]
assert "What's my name?" in result[0]["content"]
def test_should_skip_model_exact_match(self):
"""Test model exclusion with exact match."""
callback = HindsightCallback()
config = HindsightConfig(
bank_id="test",
excluded_models=["gpt-3.5-turbo"],
)
assert callback._should_skip_model("gpt-3.5-turbo", config) is True
assert callback._should_skip_model("gpt-4", config) is False
def test_should_skip_model_wildcard(self):
"""Test model exclusion with wildcard pattern."""
callback = HindsightCallback()
config = HindsightConfig(
bank_id="test",
excluded_models=["gpt-3.5*", "claude-instant-*"],
)
assert callback._should_skip_model("gpt-3.5-turbo", config) is True
assert callback._should_skip_model("gpt-3.5-turbo-16k", config) is True
assert callback._should_skip_model("claude-instant-1.2", config) is True
assert callback._should_skip_model("gpt-4", config) is False
assert callback._should_skip_model("claude-3-opus", config) is False
class TestDeduplication:
"""Tests for conversation deduplication."""
def setup_method(self):
"""Reset state before each test."""
cleanup()
def teardown_method(self):
"""Clean up after each test."""
cleanup()
def test_compute_conversation_hash(self):
"""Test computing conversation hash."""
callback = HindsightCallback()
hash1 = callback._compute_conversation_hash("Hello", "Hi there!")
hash2 = callback._compute_conversation_hash("Hello", "Hi there!")
hash3 = callback._compute_conversation_hash("Hello", "Different response")
# Same content should produce same hash
assert hash1 == hash2
# Different content should produce different hash
assert hash1 != hash3
def test_compute_conversation_hash_case_insensitive(self):
"""Test that hash is case insensitive."""
callback = HindsightCallback()
hash1 = callback._compute_conversation_hash("HELLO", "HI THERE!")
hash2 = callback._compute_conversation_hash("hello", "hi there!")
assert hash1 == hash2
def test_is_duplicate_first_time(self):
"""Test first occurrence is not a duplicate."""
callback = HindsightCallback()
result = callback._is_duplicate("abc123")
assert result is False
def test_is_duplicate_second_time(self):
"""Test second occurrence is a duplicate."""
callback = HindsightCallback()
callback._is_duplicate("abc123") # First time
result = callback._is_duplicate("abc123") # Second time
assert result is True
def test_is_duplicate_different_hashes(self):
"""Test different hashes are not duplicates."""
callback = HindsightCallback()
callback._is_duplicate("abc123")
result = callback._is_duplicate("xyz789")
assert result is False
class TestContextManager:
"""Tests for the hindsight_memory context manager."""
def setup_method(self):
"""Reset state before each test."""
cleanup()
def teardown_method(self):
"""Clean up after each test."""
cleanup()
def test_context_manager_enables_and_disables(self):
"""Test context manager enables and disables correctly."""
from hindsight_litellm import hindsight_memory
assert is_enabled() is False
with hindsight_memory(bank_id="test-agent"):
assert is_enabled() is True
assert get_config().bank_id == "test-agent"
assert is_enabled() is False
def test_context_manager_restores_previous_config(self):
"""Test context manager restores previous configuration."""
from hindsight_litellm import hindsight_memory
# Set up initial config
configure(bank_id="original-agent")
enable()
assert get_config().bank_id == "original-agent"
# Use context manager with different config
with hindsight_memory(bank_id="temporary-agent"):
assert get_config().bank_id == "temporary-agent"
# Should restore original config
assert get_config().bank_id == "original-agent"
assert is_enabled() is True
def test_context_manager_with_fact_types(self):
"""Test context manager with fact_types parameter."""
from hindsight_litellm import hindsight_memory
with hindsight_memory(bank_id="test-agent", fact_types=["world", "opinion"]):
config = get_config()
assert config.fact_types == ["world", "opinion"]
class TestFactTypes:
"""Tests for fact_types configuration."""
def setup_method(self):
"""Reset config before each test."""
reset_config()
def teardown_method(self):
"""Clean up after each test."""
cleanup()
def test_configure_with_fact_types(self):
"""Test configuring with fact_types."""
config = configure(
bank_id="test-agent",
fact_types=["world", "agent", "opinion"],
)
assert config.fact_types == ["world", "agent", "opinion"]
def test_configure_without_fact_types(self):
"""Test configuring without fact_types defaults to None."""
config = configure(bank_id="test-agent")
assert config.fact_types is None
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "hindsight-all"
version = "0.1.4"
version = "0.1.5"
description = "All-in-one package for Hindsight - Semantic memory system with personality-driven thinking"
readme = "README.md"
requires-python = ">=3.11"
File diff suppressed because it is too large Load Diff
+12
View File
@@ -0,0 +1,12 @@
{
"name": "hindsight",
"private": true,
"workspaces": [
"hindsight-clients/typescript",
"hindsight-control-plane",
"hindsight-docs"
],
"scripts": {
"prepare": "./scripts/setup-hooks.sh"
}
}
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
set -e
cd "$(dirname "$0")/../.."
if [ -z "$1" ]; then
echo "Usage: $0 VERSION [--model MODEL]"
echo ""
echo "Generate changelog entry for a release."
echo ""
echo "Examples:"
echo " $0 1.0.5"
echo " $0 v1.0.5"
echo " $0 1.0.5 --model gpt-4o"
exit 1
fi
if [ -z "$OPENAI_API_KEY" ]; then
ENV_FILE=".env"
if [ -f "$ENV_FILE" ]; then
echo "Loading environment from $ENV_FILE"
set -a
source "$ENV_FILE"
set +a
else
echo "Error: OPENAI_API_KEY not set and no .env file found"
exit 1
fi
fi
cd hindsight-dev
uv run generate-changelog "$@"
+2 -5
View File
@@ -13,13 +13,10 @@ if [ ! -f "$ROOT_DIR/.env" ]; then
fi
echo "🔨 Building TypeScript SDK first to ensure it's up to date..."
cd "$ROOT_DIR/hindsight-clients/typescript" || exit 1
npm run build
npm run build -w @vectorize-io/hindsight-client
echo "✅ SDK built successfully"
echo ""
cd "$ROOT_DIR/hindsight-control-plane" || exit 1
echo "🚀 Starting Control Plane (Next.js dev server)..."
if [ -f "$ROOT_DIR/.env" ]; then
echo "📄 Loading environment from $ROOT_DIR/.env"
@@ -33,4 +30,4 @@ fi
export HOSTNAME="${HINDSIGHT_CP_HOSTNAME:-0.0.0.0}"
# Run dev server
npm run dev
npm run dev -w hindsight-control-plane
+2 -13
View File
@@ -7,22 +7,11 @@ set -e
# Get the project root directory
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
DOCS_DIR="$PROJECT_ROOT/hindsight-docs"
cd "$PROJECT_ROOT" || exit 1
echo "Starting documentation server..."
echo "Documentation directory: $DOCS_DIR"
# Check if node_modules exists
if [ ! -d "$DOCS_DIR/node_modules" ]; then
echo "Installing documentation dependencies..."
cd "$DOCS_DIR"
npm install
fi
# Start the Docusaurus dev server
cd "$DOCS_DIR"
echo ""
echo "Starting Docusaurus development server..."
echo "Documentation will be available at: http://localhost:3000"
echo ""
npm run start
npm run start -w hindsight-docs
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
# Lint and format Node/TypeScript code (hindsight-control-plane only)
set -e
REPO_ROOT="$(git rev-parse --show-toplevel)"
# Get staged JS/TS files in control-plane only
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^hindsight-control-plane/.*\.(js|jsx|ts|tsx)$' || true)
if [ -z "$STAGED_FILES" ]; then
echo " No Node/TS files to lint"
exit 0
fi
cd "$REPO_ROOT/hindsight-control-plane"
# Check if node_modules exists
if [ ! -d "node_modules" ]; then
echo " node_modules not found, skipping Node lint"
exit 0
fi
echo " Linting and formatting Node/TS files..."
# Convert to relative paths
RELATIVE_FILES=""
for file in $STAGED_FILES; do
RELATIVE_FILES="$RELATIVE_FILES ${file#hindsight-control-plane/}"
done
# Run ESLint with --fix
npx eslint --fix $RELATIVE_FILES || true
# Run Prettier for formatting
npx prettier --write $RELATIVE_FILES || true
# Re-add fixed files to staging
cd "$REPO_ROOT"
for file in $STAGED_FILES; do
if [ -f "$file" ]; then
git add "$file"
fi
done
echo " Node lint complete"
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
# Lint Python code with Ruff (hindsight-api and hindsight packages only)
set -e
REPO_ROOT="$(git rev-parse --show-toplevel)"
# Get staged Python files in hindsight-api or hindsight directories only
STAGED_PY_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^(hindsight-api|hindsight)/.*\.py$' || true)
if [ -z "$STAGED_PY_FILES" ]; then
echo " No Python files to lint"
exit 0
fi
cd "$REPO_ROOT/hindsight-api"
# Check if ruff is available
if ! uv run ruff --version &> /dev/null; then
echo " Ruff not installed, skipping Python lint"
exit 0
fi
echo " Linting Python files with Ruff..."
# Convert to absolute paths
ABSOLUTE_FILES=""
for file in $STAGED_PY_FILES; do
ABSOLUTE_FILES="$ABSOLUTE_FILES $REPO_ROOT/$file"
done
# Run ruff check with fix
uv run ruff check --fix $ABSOLUTE_FILES
# Run ruff format
uv run ruff format $ABSOLUTE_FILES
# Re-add fixed files to staging
cd "$REPO_ROOT"
for file in $STAGED_PY_FILES; do
if [ -f "$file" ]; then
git add "$file"
fi
done
echo " Python lint complete"
+2 -2
View File
@@ -65,7 +65,7 @@ fi
print_info "Updating version in all components..."
# Update Python packages
PYTHON_PACKAGES=("hindsight-api" "hindsight-dev" "hindsight-dev/benchmarks" "hindsight")
PYTHON_PACKAGES=("hindsight-api" "hindsight-dev" "hindsight-dev/benchmarks" "hindsight" "hindsight-integrations/litellm")
for package in "${PYTHON_PACKAGES[@]}"; do
PYPROJECT_FILE="$package/pyproject.toml"
if [ -f "$PYPROJECT_FILE" ]; then
@@ -148,7 +148,7 @@ git add -A
git commit -m "Release v$VERSION
- Update version to $VERSION in all components
- Python packages: hindsight-api, hindsight-dev, hindsight-dev/benchmarks, hindsight-all
- Python packages: hindsight-api, hindsight-dev, hindsight-dev/benchmarks, hindsight-all, hindsight-litellm
- Python client: hindsight-clients/python
- TypeScript client: hindsight-clients/typescript
- Rust CLI: hindsight-cli
+11
View File
@@ -0,0 +1,11 @@
#!/bin/bash
# Setup git hooks for the repository
set -e
REPO_ROOT="$(git rev-parse --show-toplevel)"
echo "Setting up git hooks..."
git config core.hooksPath "$REPO_ROOT/.githooks"
echo "Git hooks configured to use .githooks directory"
echo "Done!"
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
# Sync cookbook content from hindsight-cookbook repository
# Converts notebooks to markdown and updates the docs
set -e
cd "$(dirname "$0")/.."
echo "Syncing cookbook..."
uv run sync-cookbook
echo ""
echo "Done! Run 'npm run serve' to preview."
Generated
+47 -5
View File
@@ -1141,7 +1141,7 @@ wheels = [
[[package]]
name = "hindsight-all"
version = "0.1.4"
version = "0.1.5"
source = { editable = "hindsight" }
dependencies = [
{ name = "hindsight-api" },
@@ -1165,7 +1165,7 @@ provides-extras = ["test"]
[[package]]
name = "hindsight-api"
version = "0.1.4"
version = "0.1.5"
source = { editable = "hindsight-api" }
dependencies = [
{ name = "alembic" },
@@ -1182,6 +1182,7 @@ dependencies = [
{ name = "opentelemetry-exporter-prometheus" },
{ name = "opentelemetry-instrumentation-fastapi" },
{ name = "opentelemetry-sdk" },
{ name = "pg0-embedded" },
{ name = "pgvector" },
{ name = "psycopg2-binary" },
{ name = "pydantic" },
@@ -1214,6 +1215,7 @@ dev = [
{ name = "pytest-timeout" },
{ name = "pytest-xdist" },
{ name = "python-dotenv" },
{ name = "ruff" },
]
[package.metadata]
@@ -1222,7 +1224,7 @@ requires-dist = [
{ name = "asyncpg", specifier = ">=0.29.0" },
{ name = "dateparser", specifier = ">=1.2.2" },
{ name = "fastapi", extras = ["standard"], specifier = ">=0.120.3" },
{ name = "fastmcp", specifier = ">=2.0.0" },
{ name = "fastmcp", specifier = ">=2.3.0" },
{ name = "filelock", marker = "extra == 'test'", specifier = ">=3.0.0" },
{ name = "google-genai", specifier = ">=1.0.0" },
{ name = "greenlet", specifier = ">=3.2.4" },
@@ -1233,6 +1235,7 @@ requires-dist = [
{ name = "opentelemetry-exporter-prometheus", specifier = ">=0.41b0" },
{ name = "opentelemetry-instrumentation-fastapi", specifier = ">=0.41b0" },
{ name = "opentelemetry-sdk", specifier = ">=1.20.0" },
{ name = "pg0-embedded", specifier = ">=0.11.0" },
{ name = "pgvector", specifier = ">=0.4.1" },
{ name = "psycopg2-binary", specifier = ">=2.9.11" },
{ name = "pydantic", specifier = ">=2.0.0" },
@@ -1261,11 +1264,12 @@ dev = [
{ name = "pytest-timeout", specifier = ">=2.4.0" },
{ name = "pytest-xdist", specifier = ">=3.8.0" },
{ name = "python-dotenv", specifier = ">=1.2.1" },
{ name = "ruff", specifier = ">=0.8.0" },
]
[[package]]
name = "hindsight-client"
version = "0.1.4"
version = "0.1.5"
source = { editable = "hindsight-clients/python" }
dependencies = [
{ name = "aiohttp" },
@@ -1297,7 +1301,7 @@ provides-extras = ["test"]
[[package]]
name = "hindsight-dev"
version = "0.1.4"
version = "0.1.5"
source = { editable = "hindsight-dev" }
dependencies = [
{ name = "hindsight-api" },
@@ -2502,6 +2506,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9a/70/875f4a23bfc4731703a5835487d0d2fb999031bd415e7d17c0ae615c18b7/pathvalidate-3.3.1-py3-none-any.whl", hash = "sha256:5263baab691f8e1af96092fa5137ee17df5bdfbd6cff1fcac4d6ef4bc2e1735f", size = 24305 },
]
[[package]]
name = "pg0-embedded"
version = "0.11.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/ad/6c/ed900aeea802f6217d6979a16084903fb454d3d149b3f4dbe7ff019407db/pg0_embedded-0.11.0.tar.gz", hash = "sha256:f086e1980e142fddf540b9eabef156ffab432b41a2673e5e1e0c2fb97b83bfba", size = 17692 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/65/07/ee9cd32ec3a81c1fca01a83dcd8e92ff98dd5b21e9c3bee85d688ec18be2/pg0_embedded-0.11.0-py3-none-macosx_14_0_arm64.whl", hash = "sha256:4fb4a6ba596d84b19bebfcd1ccff0a531b6b716cf57209e1a016b3cbf1c04454", size = 13077882 },
{ url = "https://files.pythonhosted.org/packages/e6/88/444f74d883c6838420dc26f833146c4acd2bf52f029a41c66e7107fc94d8/pg0_embedded-0.11.0-py3-none-manylinux_2_35_aarch64.whl", hash = "sha256:cdb68aadb47938bc7e4cf3794ddcd36f3278a26aa2863ea6008288658b7d545a", size = 14788819 },
{ url = "https://files.pythonhosted.org/packages/9e/cb/f7f023942957f98e89e6d170bfe6fdeee92c4df6c93ba57b7d301b4c5226/pg0_embedded-0.11.0-py3-none-manylinux_2_35_x86_64.whl", hash = "sha256:c93871b38f0ae2e69e3ce1d58f3f30c5245e2b40b2dc8b9bf367e5942492f041", size = 15230448 },
{ url = "https://files.pythonhosted.org/packages/12/3c/81b7f01a2d008c0b842919ffbfab3bd582c55fed060ff07ef39a9a027742/pg0_embedded-0.11.0-py3-none-win_amd64.whl", hash = "sha256:b67639f4dd280936492c3ba409dff1ace6911ecad9f4a5a4139d11e4fd0dd913", size = 54980453 },
]
[[package]]
name = "pgvector"
version = "0.4.1"
@@ -3659,6 +3675,32 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/64/8d/0133e4eb4beed9e425d9a98ed6e081a55d195481b7632472be1af08d2f6b/rsa-4.9.1-py3-none-any.whl", hash = "sha256:68635866661c6836b8d39430f97a996acbd61bfa49406748ea243539fe239762", size = 34696 },
]
[[package]]
name = "ruff"
version = "0.14.9"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/f6/1b/ab712a9d5044435be8e9a2beb17cbfa4c241aa9b5e4413febac2a8b79ef2/ruff-0.14.9.tar.gz", hash = "sha256:35f85b25dd586381c0cc053f48826109384c81c00ad7ef1bd977bfcc28119d5b", size = 5809165 }
wheels = [
{ url = "https://files.pythonhosted.org/packages/b8/1c/d1b1bba22cffec02351c78ab9ed4f7d7391876e12720298448b29b7229c1/ruff-0.14.9-py3-none-linux_armv6l.whl", hash = "sha256:f1ec5de1ce150ca6e43691f4a9ef5c04574ad9ca35c8b3b0e18877314aba7e75", size = 13576541 },
{ url = "https://files.pythonhosted.org/packages/94/ab/ffe580e6ea1fca67f6337b0af59fc7e683344a43642d2d55d251ff83ceae/ruff-0.14.9-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:ed9d7417a299fc6030b4f26333bf1117ed82a61ea91238558c0268c14e00d0c2", size = 13779363 },
{ url = "https://files.pythonhosted.org/packages/7d/f8/2be49047f929d6965401855461e697ab185e1a6a683d914c5c19c7962d9e/ruff-0.14.9-py3-none-macosx_11_0_arm64.whl", hash = "sha256:d5dc3473c3f0e4a1008d0ef1d75cee24a48e254c8bed3a7afdd2b4392657ed2c", size = 12925292 },
{ url = "https://files.pythonhosted.org/packages/9e/e9/08840ff5127916bb989c86f18924fd568938b06f58b60e206176f327c0fe/ruff-0.14.9-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:84bf7c698fc8f3cb8278830fb6b5a47f9bcc1ed8cb4f689b9dd02698fa840697", size = 13362894 },
{ url = "https://files.pythonhosted.org/packages/31/1c/5b4e8e7750613ef43390bb58658eaf1d862c0cc3352d139cd718a2cea164/ruff-0.14.9-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:aa733093d1f9d88a5d98988d8834ef5d6f9828d03743bf5e338bf980a19fce27", size = 13311482 },
{ url = "https://files.pythonhosted.org/packages/5b/3a/459dce7a8cb35ba1ea3e9c88f19077667a7977234f3b5ab197fad240b404/ruff-0.14.9-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a1cfb04eda979b20c8c19550c8b5f498df64ff8da151283311ce3199e8b3648", size = 14016100 },
{ url = "https://files.pythonhosted.org/packages/a6/31/f064f4ec32524f9956a0890fc6a944e5cf06c63c554e39957d208c0ffc45/ruff-0.14.9-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:1e5cb521e5ccf0008bd74d5595a4580313844a42b9103b7388eca5a12c970743", size = 15477729 },
{ url = "https://files.pythonhosted.org/packages/7a/6d/f364252aad36ccd443494bc5f02e41bf677f964b58902a17c0b16c53d890/ruff-0.14.9-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:cd429a8926be6bba4befa8cdcf3f4dd2591c413ea5066b1e99155ed245ae42bb", size = 15122386 },
{ url = "https://files.pythonhosted.org/packages/20/02/e848787912d16209aba2799a4d5a1775660b6a3d0ab3944a4ccc13e64a02/ruff-0.14.9-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ab208c1b7a492e37caeaf290b1378148f75e13c2225af5d44628b95fd7834273", size = 14497124 },
{ url = "https://files.pythonhosted.org/packages/f3/51/0489a6a5595b7760b5dbac0dd82852b510326e7d88d51dbffcd2e07e3ff3/ruff-0.14.9-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:72034534e5b11e8a593f517b2f2f2b273eb68a30978c6a2d40473ad0aaa4cb4a", size = 14195343 },
{ url = "https://files.pythonhosted.org/packages/f6/53/3bb8d2fa73e4c2f80acc65213ee0830fa0c49c6479313f7a68a00f39e208/ruff-0.14.9-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:712ff04f44663f1b90a1195f51525836e3413c8a773574a7b7775554269c30ed", size = 14346425 },
{ url = "https://files.pythonhosted.org/packages/ad/04/bdb1d0ab876372da3e983896481760867fc84f969c5c09d428e8f01b557f/ruff-0.14.9-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:a111fee1db6f1d5d5810245295527cda1d367c5aa8f42e0fca9a78ede9b4498b", size = 13258768 },
{ url = "https://files.pythonhosted.org/packages/40/d9/8bf8e1e41a311afd2abc8ad12be1b6c6c8b925506d9069b67bb5e9a04af3/ruff-0.14.9-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:8769efc71558fecc25eb295ddec7d1030d41a51e9dcf127cbd63ec517f22d567", size = 13326939 },
{ url = "https://files.pythonhosted.org/packages/f4/56/a213fa9edb6dd849f1cfbc236206ead10913693c72a67fb7ddc1833bf95d/ruff-0.14.9-py3-none-musllinux_1_2_i686.whl", hash = "sha256:347e3bf16197e8a2de17940cd75fd6491e25c0aa7edf7d61aa03f146a1aa885a", size = 13578888 },
{ url = "https://files.pythonhosted.org/packages/33/09/6a4a67ffa4abae6bf44c972a4521337ffce9cbc7808faadede754ef7a79c/ruff-0.14.9-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:7715d14e5bccf5b660f54516558aa94781d3eb0838f8e706fb60e3ff6eff03a8", size = 14314473 },
{ url = "https://files.pythonhosted.org/packages/12/0d/15cc82da5d83f27a3c6b04f3a232d61bc8c50d38a6cd8da79228e5f8b8d6/ruff-0.14.9-py3-none-win32.whl", hash = "sha256:df0937f30aaabe83da172adaf8937003ff28172f59ca9f17883b4213783df197", size = 13202651 },
{ url = "https://files.pythonhosted.org/packages/32/f7/c78b060388eefe0304d9d42e68fab8cffd049128ec466456cef9b8d4f06f/ruff-0.14.9-py3-none-win_amd64.whl", hash = "sha256:c0b53a10e61df15a42ed711ec0bda0c582039cf6c754c49c020084c55b5b0bc2", size = 14702079 },
{ url = "https://files.pythonhosted.org/packages/26/09/7a9520315decd2334afa65ed258fed438f070e31f05a2e43dd480a5e5911/ruff-0.14.9-py3-none-win_arm64.whl", hash = "sha256:8e821c366517a074046d92f0e9213ed1c13dbc5b37a7fc20b07f79b64d62cc84", size = 13744730 },
]
[[package]]
name = "safetensors"
version = "0.6.2"