同步完整源码 - 2026-05-24

This commit is contained in:
xiaoxue
2026-05-24 17:22:17 +08:00
commit f74585aa9d
863 changed files with 224495 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
.vscode
.DS_Store
__pycache__
.mypy_cache
.ruff_cache
*.egg-info
dist
.venv
.env
+182
View File
@@ -0,0 +1,182 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [2.1.2] - 2026-05-21
### Added
- `page`, `size`, and `reverse` pagination parameters on `Honcho.workspaces()` and `HonchoAio.workspaces()`, closing the gap from 2.1.0 which added these to `peers()`, `sessions()`, `messages()`, and `conclusions.list()` but not to `workspaces()`. Honoring `reverse` on the workspace/peer/session list routes also requires a Honcho server with the matching API fix; older servers silently ignore the parameter.
- `peers` parameter on `Honcho.session()` and `HonchoAio.session()` — attach peers to a session at creation time instead of needing a follow-up `session.add_peers()` call. Accepts the same shapes as `Session.add_peers` (peer ID string, `Peer` object, list of either, or tuples with `SessionPeerConfig`).
### Changed
- `WorkspaceCreateParams`, `PeerCreateParams`, and `SessionCreateParams` now accept IDs up to 512 characters (was 100), matching the server-side schema change in Honcho v3.0.7.
## [2.1.1] - 2026-04-01
### Fixed
- Broadened HTTP retry logic to cover `httpx.NetworkError` and `httpx.RemoteProtocolError` in addition to `httpx.TimeoutException` and `httpx.ConnectError`, improving resilience against transient network failures
## [2.1.0] - 2026-03-25
### Added
- `created_at` property on `Peer` and `Session` objects
- `is_active` property on `Session` objects
- `get_message(message_id)` method on `Session` (sync and async) to fetch a single message by ID
- `page`, `size`, and `reverse` pagination parameters on all list methods: `peers()`, `sessions()`, `messages()`, and `conclusions.list()`
### Changed
- **Breaking**: `peer()` and `session()` now always make a get-or-create API call. Previously, calling without metadata/configuration returned a lazy object with no API call. All Peer/Session objects now have `created_at` populated immediately.
- Response configuration models (`WorkspaceConfigurationResponse`, `SessionConfigurationResponse`) now tolerate unknown fields from newer servers for forward compatibility
### Fixed
- Sync and async `Session.get_metadata()`, `get_configuration()`, and `refresh()` now refresh cached `created_at` and `is_active` values along with metadata and configuration.
- `honcho.__version__` now derives from package metadata, with a `pyproject.toml` fallback in source checkouts, so it stays aligned with SDK releases.
## [2.0.2] - 2026-03-10
### Changed
- All input models now reject unknown fields via `extra="forbid"` Pydantic validation. Previously, misspelled or extraneous fields were silently ignored. Now a `ValidationError` is raised with the unrecognized field name.
## [2.0.1] - 2026-02-09
### Added
- `set_peer_card` method
### Changed
- `card` is now `get_card` with `card` kept for backwards compatibility and marked as deprecated
## [2.0.0] - 2026-01-13
### Added
- `ConclusionScope` object for CRUD operations on conclusions (renamed from observations)
- Representation configuration support
### Changed
- Observations renamed to Conclusions across the SDK
- Major SDK refactoring and cleanup
- Simplified method signatures throughout
- Representation endpoints now return `string` instead of old Representation object
### Removed
- Standalone types module (now uses honcho-core types)
- Representation object
## [1.6.0] - 2025-12-03
### Added
- metadata and configuration fields to Workspace, Peer, Session, and Message objects
- Session Clone methods
- Peer level get_context method
- `ObservationScope` object to perform CRUD operations on observations
- Representation object for WorkingRepresentations
### Changed
- methods that take IDs, can all optionally take an object of the same type
## [1.5.0] - 2025-10-09
### Added
- Delete workspace method
### Changed
- message_id of `Summary` model is a string nanoid
- Get Context can return Peer Card & Peer Representation
## [1.4.1] — 2025-10-01
### Added
- Get Peer Card method
- Update Message metadata method
- Session level deriver status methods
- Delete session message
### Fixed
- Dialectic Stream returns Iterators
- Type warnings
### Changed
- Pagination class to match core implementation
## [1.4.0] — 2025-08-12
### Added
- getSummaries API returning structured summaries
- Webhook support
### Changed
- Messages can take an optional `created_at` value, defaulting to the current
time (UTC ISO 8601)
## [1.3.0] - 2025-08-04
### Added
- Added get_peer_config to sessions module
### Changed
- Summaries are now included in `toOpenAI` and `toAnthropic` functions
- `SessionContext.__len__` now counts the summary in its total
- `filter` keyword changed to `filters`
### Fixed
- Added missing metadata inputs in many places
- Better documentation all over
## [1.2.2] - 2025-07-21
### Added
- Filter parameter to various endpoints
## [1.2.1] - 2025-07-17
### Fixed
- honcho utils import path
## [1.2.0] - 2025-07-16
### Added
- Get/poll deriver queue status endpoints added to workspace
- Added endpoint to upload files as messages
### Removed
- Removed peer messages in accordance with Honcho 2.1.0
### Changed
- Updated chat endpoint to use singular `query` in accordance with Honcho 2.1.0
## [1.1.0] - 2025-07-08
### Fixed
- Properly handle AsyncClient
+164
View File
@@ -0,0 +1,164 @@
# Honcho Python SDK
The official Python library for the [Honcho](https://github.com/plastic-labs/honcho) conversational memory platform. Honcho provides tools for managing peers, sessions, and conversation context across multi-party interactions, enabling advanced conversational AI applications with persistent memory and theory-of-mind capabilities.
## Installation
```bash
pip install honcho-ai
```
## Quick Start
```python
from honcho import Honcho
# Initialize client
client = Honcho(api_key="your-api-key")
# Create peers (participants in conversations)
alice = client.peer("alice")
bob = client.peer("bob")
# Create a session for group conversations
session = client.session("conversation-1")
# Add messages to the session
session.add_messages([
alice.message("Hello, Bob!"),
bob.message("Hi Alice, how are you?")
])
# Query conversation context
response = alice.chat("What did Bob say to the user?")
print(response)
```
## Core Concepts
### Peers
Peers represent participants in conversations.
```python
# Create peers
assistant = client.peer("assistant")
user = client.peer("user-123")
# Chat with global context
response = user.chat("What did I talk about yesterday?")
# Chat with perspective of another peer
response = user.chat("Does the assistant know my preferences?", target=assistant)
```
### Sessions
Sessions group related conversations and messages:
```python
# Create a session
session = client.session("project-discussion")
# Add peers to session
session.add_peers([alice, bob])
# Add messages
session.add_messages([
alice.message("Let's discuss the project timeline"),
bob.message("I think we need two more weeks")
])
# Get conversation context
context = session.context()
```
### Messages and Context
Retrieve and use conversation history:
```python
# Get messages from a session
messages = session.messages()
# Convert to OpenAI format for further prompting
openai_messages = context.to_openai(assistant="assistant")
# Convert to Anthropic format for further prompting
anthropic_messages = context.to_anthropic(assistant="assistant")
```
### Async Support
The SDK provides async access via the `.aio` accessor on any instance:
```python
from honcho import Honcho
async def main():
client = Honcho(api_key="your-api-key")
# Async peer and session creation
peer = await client.aio.peer("user-123")
session = await client.aio.session("conversation-1")
# Async chat
response = await peer.aio.chat("What does this user prefer?")
# Async iteration
async for p in client.aio.peers():
print(p.id)
```
### Metadata Management
```python
# Set peer metadata
user.set_metadata({"location": "San Francisco", "preferences": {"theme": "dark"}})
# Session metadata
session.set_metadata({"topic": "project-planning", "priority": "high"})
```
### Multi-Perspective Queries
```python
# Alice's view of what Bob knows
response = alice.chat("Does Bob remember our discussion about the budget?", target=bob)
# Session-specific perspective
response = alice.chat("What does Bob think about this project?",
target=bob,
session=session)
```
## Configuration
### Environment Variables
```bash
export HONCHO_API_KEY="your-api-key"
export HONCHO_BASE_URL="https://api.honcho.dev" # Optional
export HONCHO_WORKSPACE_ID="your-workspace" # Optional
```
### Client Options
```python
client = Honcho(
api_key="your-api-key",
environment="production", # or "local"
workspace_id="custom-workspace",
base_url="https://api.honcho.dev"
)
```
## License
Apache 2.0 - see [LICENSE](../../LICENSE) for details.
## Support
- [Documentation](https://honcho.dev/docs)
- [GitHub Issues](https://github.com/plastic-labs/honcho/issues)
- [Discord Community](https://discord.gg/honcho)
+41
View File
@@ -0,0 +1,41 @@
import random
import uuid
from honcho import Honcho, MessageCreateParams
# Create a Honcho client with the default workspace
honcho = Honcho(environment="local")
peers = [
honcho.peer("alice"),
honcho.peer("bob"),
honcho.peer("charlie"),
]
# Create a new session
session = honcho.session("chat_test_" + str(uuid.uuid4()))
# Generate some random messages from alice, bob, and charlie and add them to the session
messages: list[MessageCreateParams] = []
for i in range(10):
random_peer = random.choice(peers)
messages.append(
random_peer.message(f"Hello from {random_peer}! This is message {i}.")
)
session.add_messages(messages)
# Chat with alice
alice = peers[0]
response = alice.chat("what did alice have for breakfast today?")
print("response returned:", response)
# Chat with alice in the session
response = alice.chat("what did alice have for breakfast today?", session=session)
print("response returned:", response)
# Chat with alice in the session with a target
# This means you are querying alice's theory-of-mind representation of bob
bob = peers[1]
response = alice.chat("what did bob have for breakfast today?", target=bob)
print("response returned:", response)
+19
View File
@@ -0,0 +1,19 @@
import uuid
from honcho import Honcho
# Create a Honcho client with the default workspace
honcho = Honcho(environment="local")
# Create a new session
session = honcho.session("file_upload_test_" + str(uuid.uuid4()))
# Upload the current file directly using a file object
with open(__file__, "rb") as file:
session.upload_file(file, peer="alice")
# get the messages from the session
# should contain the contents of this file!
messages = session.messages()
for message in messages:
print(str(message))
+31
View File
@@ -0,0 +1,31 @@
import random
import uuid
from honcho import Honcho, MessageCreateParams
# Create a Honcho client with the default workspace
honcho = Honcho(environment="local")
peers = [
honcho.peer("alice"),
honcho.peer("bob"),
honcho.peer("charlie"),
]
# Create a new session
session = honcho.session("context_test_" + str(uuid.uuid4()))
# Generate some random messages from alice, bob, and charlie and add them to the session
messages: list[MessageCreateParams] = []
for i in range(10):
random_peer = random.choice(peers)
messages.append(
random_peer.message(f"Hello from {random_peer}! This is message {i}.")
)
session.add_messages(messages)
# Get some context of the session
# Set the token limit super low so we only get a few of the tiny messages created
context = session.context(summary=True, tokens=50)
print("context returned:", context)
+84
View File
@@ -0,0 +1,84 @@
"""
Example of getting session summaries using the Honcho Python SDK.
This example demonstrates how to retrieve both short and long summaries
for a session, including their metadata like message ID, creation timestamp,
and token count.
"""
import asyncio
import os
from honcho import Honcho, SessionSummaries
# Initialize the Honcho client
api_key = os.getenv("HONCHO_API_KEY")
if not api_key:
raise ValueError("Please set HONCHO_API_KEY environment variable")
client = Honcho(api_key=api_key)
# Get a session (replace with your actual session ID)
session = client.session("my-conversation-session")
# Get summaries for the session
summaries: SessionSummaries = session.summaries()
print(f"Session ID: {summaries.id}")
print("-" * 50)
# Check and display short summary
if summaries.short_summary:
print("SHORT SUMMARY:")
print(f" Content: {summaries.short_summary.content[:200]}...") # First 200 chars
print(f" Covers up to message ID: {summaries.short_summary.message_id}")
print(f" Created at: {summaries.short_summary.created_at}")
print(f" Token count: {summaries.short_summary.token_count}")
print(f" Type: {summaries.short_summary.summary_type}")
else:
print("No short summary available yet")
print("-" * 50)
# Check and display long summary
if summaries.long_summary:
print("LONG SUMMARY:")
print(f" Content: {summaries.long_summary.content[:200]}...") # First 200 chars
print(f" Covers up to message ID: {summaries.long_summary.message_id}")
print(f" Created at: {summaries.long_summary.created_at}")
print(f" Token count: {summaries.long_summary.token_count}")
print(f" Type: {summaries.long_summary.summary_type}")
else:
print("No long summary available yet")
# Example with async client using .aio accessor
print("\n" + "=" * 50)
print("ASYNC EXAMPLE:")
print("=" * 50)
async def summaries_async():
# Use the same Honcho client with .aio accessor for async operations
async_client = Honcho(api_key=api_key)
# Get a session using .aio accessor
async_session = await async_client.aio.session("my-conversation-session")
# Get summaries asynchronously using .aio accessor
summaries = await async_session.aio.summaries()
print(f"Session ID (async): {summaries.id}")
if summaries.short_summary:
print(
f"Short summary available with {summaries.short_summary.token_count} tokens"
)
if summaries.long_summary:
print(
f"Long summary available with {summaries.long_summary.token_count} tokens"
)
# Run the async example
asyncio.run(summaries_async())
@@ -0,0 +1,77 @@
import time
import uuid
from honcho import Honcho, MessageCreateParams
from honcho.session import SessionPeerConfig
# Create a Honcho client with the default workspace
honcho = Honcho(environment="local")
alice = honcho.peer("alice")
bob = honcho.peer("bob")
# Create a new session
session = honcho.session("chat_test_" + str(uuid.uuid4()))
session.add_peers(
[
(alice, SessionPeerConfig(observe_me=True, observe_others=True)),
(bob, SessionPeerConfig(observe_me=True, observe_others=True)),
]
)
# Generate messages with personal information
messages: list[MessageCreateParams] = []
messages.append(alice.message("I had a great breakfast today!"))
messages.append(bob.message("What did you eat?"))
messages.append(alice.message("I had pancakes and eggs and bacon."))
session.add_messages(messages)
# sleep to get later timestamps on these "future" messages
time.sleep(5)
# Create a separate session
session2 = honcho.session("chat_test_" + str(uuid.uuid4()))
session2.add_peers(
[
(alice, SessionPeerConfig(observe_me=True, observe_others=True)),
(bob, SessionPeerConfig(observe_me=True, observe_others=True)),
]
)
session2.add_messages(
[
alice.message(
"Hey remember when I told you I had a great breakfast today? I lied. I actually skipped breakfast."
),
bob.message("WTF is wrong with you??"),
]
)
# # Chat with alice's honcho-level representation
print(
"\n\n\033[1m asking alice's honcho-level representation what she had for breakfast \033[0m"
)
response = alice.chat("what did alice have for breakfast today?", session=session)
print("response:", response)
# Chat with bob's internal representation of alice
print(
"\n\n\033[1m asking bob what alice had for breakfast -- scoped to session 1 \033[0m"
)
response = bob.chat(
"what did alice have for breakfast today?", target=alice, session=session
)
print("response:", response)
print(
"\n\n\033[1m asking bob what alice had for breakfast -- scoped to session 2 \033[0m"
)
response = bob.chat(
"what did alice have for breakfast today?", target=alice, session=session2
)
print("response:", response)
print("\n\n\033[1m asking bob what alice had for breakfast -- global scope \033[0m")
response = bob.chat("what did alice have for breakfast today?", target=alice)
print("response:", response)
@@ -0,0 +1,147 @@
"""
Example demonstrating Pydantic validation in the Honcho SDK.
This example shows how the SDK now uses Pydantic to validate inputs at runtime,
providing better error messages and type safety.
"""
import datetime
import logging
from pydantic import ValidationError
from honcho import Honcho
logging.basicConfig(level=logging.INFO)
def demonstrate_validation():
"""Demonstrate various validation scenarios with the Pydantic-enhanced SDK."""
print("=== Pydantic Validation Examples ===\n")
# Example 1: Valid initialization
print("1. Valid initialization:")
try:
honcho = Honcho(
environment="local",
workspace_id="test_workspace",
timeout=30.0,
max_retries=3,
)
print(f"✅ Successfully created client: {honcho}")
except ValidationError as e:
print(f"❌ Validation error: {e}")
print("\n" + "=" * 50 + "\n")
# Example 2: Invalid timeout (negative)
print("2. Invalid timeout (negative value):")
try:
honcho = Honcho(environment="local", timeout=-5.0)
print("✅ This shouldn't happen!")
except ValidationError as e:
print(f"❌ Validation caught invalid timeout: {e.errors()[0]['msg']}")
print("\n" + "=" * 50 + "\n")
# Example 3: Invalid max_retries (negative)
print("3. Invalid max_retries (negative value):")
try:
honcho = Honcho(environment="local", max_retries=-1)
print("✅ This shouldn't happen!")
except ValidationError as e:
print(f"❌ Validation caught invalid max_retries: {e.errors()[0]['msg']}")
print("\n" + "=" * 50 + "\n")
# Example 4: Invalid peer ID (empty)
print("4. Invalid peer ID (empty string):")
try:
honcho = Honcho(environment="local", workspace_id="test")
peer = honcho.peer("")
print("✅ This shouldn't happen!")
except ValidationError as e:
print(f"❌ Validation caught empty peer ID: {e.errors()[0]['msg']}")
print("\n" + "=" * 50 + "\n")
# Example 5: Invalid session ID (empty)
print("5. Invalid session ID (empty string):")
try:
honcho = Honcho(environment="local", workspace_id="test")
session = honcho.session("")
print("✅ This shouldn't happen!")
except ValidationError as e:
print(f"❌ Validation caught empty session ID: {e.errors()[0]['msg']}")
print("\n" + "=" * 50 + "\n")
# Example 6: Valid peer and session creation
print("6. Valid peer and session creation:")
try:
honcho = Honcho(environment="local", workspace_id="test")
peer = honcho.peer("alice")
session = honcho.session("conversation_1")
print(f"✅ Created peer: {peer}")
print(f"✅ Created session: {session}")
except ValidationError as e:
print(f"❌ Validation error: {e}")
print("\n" + "=" * 50 + "\n")
# Example 7: Invalid message content (empty)
print("7. Invalid message content (empty string):")
try:
honcho = Honcho(environment="local", workspace_id="test")
peer = honcho.peer("alice")
message = peer.message("")
print("✅ This shouldn't happen!")
except ValidationError as e:
print(f"❌ Validation caught empty message content: {e.errors()[0]['msg']}")
print("\n" + "=" * 50 + "\n")
# Example 9: Valid operations
print("9. Valid operations (no API calls made):")
try:
honcho = Honcho(environment="local", workspace_id="test")
peer = honcho.peer("alice")
session = honcho.session("conversation_1")
# Create a valid message
message = peer.message("Hello, world!", metadata={"type": "greeting"})
print(
f"✅ Created message: peer_id={message.peer_id}, content='{message.content}'"
)
# Valid peer operations (validation passes, but no API calls made)
print("✅ All validations passed for standard operations")
except ValidationError as e:
print(f"❌ Validation error: {e}")
# Example 10: Custom created_at timestamps
print("10. Custom created_at timestamps:")
try:
honcho = Honcho(environment="local", workspace_id="test")
peer = honcho.peer("alice")
message = peer.message("Hello, world!", created_at=datetime.datetime.now())
print(f"✅ Created message: {message}")
message = peer.message(
"Hello, world!",
created_at=datetime.datetime(1999, 1, 1, tzinfo=datetime.timezone.utc),
)
print(f"✅ Created message: {message}")
session = honcho.session("conversation_1")
session.add_messages([message])
print(f"✅ Added message to session: {session}")
except ValidationError as e:
print(f"❌ Validation error: {e}")
print("\n" + "=" * 50 + "\n")
print("🎉 Pydantic validation examples completed!")
if __name__ == "__main__":
demonstrate_validation()
+47
View File
@@ -0,0 +1,47 @@
import random
import uuid
from honcho import Honcho, MessageCreateParams
# Create a Honcho client with the default workspace
honcho = Honcho(environment="local")
peers = [
honcho.peer("alice"),
honcho.peer("bob"),
honcho.peer("charlie"),
]
alice = peers[0]
# Create a new session
session = honcho.session("search_test_" + str(uuid.uuid4()))
# Create a message with our special keyword
keyword = f"~special-{str(uuid.uuid4())}~"
session.add_messages(alice.message(f"I am a {keyword} message"))
# Generate some random messages from alice, bob, and charlie and add them to the session
messages: list[MessageCreateParams] = []
for i in range(10):
random_peer = random.choice(peers)
messages.append(
random_peer.message(f"Hello from {random_peer}! This is message {i}.")
)
session.add_messages(messages)
# Search the session for the special keyword
search_results = session.search(keyword)
print("searching the session")
print("search results returned:", [message for message in search_results])
# Search the workspace for the special keyword
search_results = honcho.search(keyword)
print("searching the workspace")
print("search results returned:", [message for message in search_results])
# Search alice's messages for the special keyword
search_results = alice.search(keyword)
print("searching alice's messages")
print("search results returned:", [message for message in search_results])
+72
View File
@@ -0,0 +1,72 @@
[project]
name = "honcho-ai"
version = "2.1.2"
description = "Official DX Optimized Python SDK for Honcho"
dynamic = ["readme"]
license = "Apache-2.0"
authors = [
{ name = "Plastic Labs", email = "hello@plasticlabs.ai" },
]
dependencies = [
"httpx>=0.28.0, <1",
"pydantic>=2.0.0, <3",
"typing-extensions>=4.12.0; python_version < \"3.12\"",
]
requires-python = ">= 3.8"
classifiers = [
"Typing :: Typed",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Operating System :: OS Independent",
"Operating System :: POSIX",
"Operating System :: MacOS",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Topic :: Software Development :: Libraries :: Python Modules",
]
[project.optional-dependencies]
cli = ["honcho-cli>=0.1.0"]
[project.urls]
Homepage = "https://github.com/plastic-labs/honcho"
Repository = "https://github.com/plastic-labs/honcho"
[dependency-groups]
dev = [
"ruff>=0.11.13",
]
[tool.ruff.lint]
ignore = ["E501", "B008", "COM812"]
[tool.setuptools.dynamic]
readme = {file = ["README.md"], content-type = "text/markdown"}
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
[tool.basedpyright]
# BasedPyright currently seems like the best type checker option, much faster
# https://docs.basedpyright.com/latest/configuration/config-files/#sample-pyprojecttoml-file
include = ["src"]
reportUnusedCallResult = false
reportCallInDefaultInitializer = false
reportAny = false
reportExplicitAny = false
reportImportCycles = false
[[tool.uv.index]]
name = "testpypi"
url = "https://test.pypi.org/simple/"
publish-url = "https://test.pypi.org/legacy/"
explicit = true
[tool.setuptools.packages.find]
where = ["src"]
include = ["honcho", "honcho.async_client", "honcho.http", "honcho.utils"]
+134
View File
@@ -0,0 +1,134 @@
"""
Honcho Python SDK
A Python client library for the Honcho conversational memory platform.
Provides tools for managing peers, sessions, and conversation context
across multi-party interactions.
Usage:
from honcho import Honcho
# Initialize client
client = Honcho(api_key="your-api-key")
# Create peers
alice = client.peer("alice")
bob = client.peer("bob")
# Create a session
session = client.session("conversation-1")
# Add peers to session
session.add_peers([alice, bob])
# Add messages
session.add_messages([
alice.message("Hello, Bob!"),
bob.message("Hi Alice, how are you?")
])
# Query conversation context
response = alice.chat("What did Bob say to me?", session=session)
# Async operations via .aio accessor
peer = await client.aio.peer("user-123")
await peer.aio.chat("query", session=session)
async for p in client.aio.peers():
print(p.id)
"""
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
import re
from .aio import ConclusionScopeAio, HonchoAio, PeerAio, SessionAio
from .api_types import MessageCreateParams
from .base import PeerBase, SessionBase
from .client import Honcho
from .conclusions import Conclusion, ConclusionScope
from .http.exceptions import (
APIError,
AuthenticationError,
BadRequestError,
ConflictError,
ConnectionError,
HonchoError,
NotFoundError,
PermissionDeniedError,
RateLimitError,
ServerError,
TimeoutError,
UnprocessableEntityError,
)
from .message import Message
from .pagination import AsyncPage, SyncPage
from .peer import Peer
from .session import Session
from .session_context import SessionContext, SessionSummaries, Summary
from .types import (
AsyncDialecticStreamResponse,
DialecticStreamResponse,
)
def _detect_version() -> str:
try:
return version("honcho-ai")
except PackageNotFoundError:
try:
pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"
pyproject_text = pyproject_path.read_text(encoding="utf-8")
match = re.search(r'^version\s*=\s*"([^"]+)"', pyproject_text, re.MULTILINE)
if match:
return match.group(1)
except OSError:
pass
return "0.0.0"
__version__ = _detect_version()
__author__ = "Plastic Labs"
__email__ = "hello@plasticlabs.ai"
__all__ = [
# Client
"Honcho",
# Domain classes
"Conclusion",
"ConclusionScope",
"Message",
"MessageCreateParams",
"Peer",
"Session",
# Aio views (for type hints)
"ConclusionScopeAio",
"HonchoAio",
"PeerAio",
"SessionAio",
# Base classes
"PeerBase",
"SessionBase",
# Response types
"SessionContext",
"SessionSummaries",
"Summary",
# Pagination
"AsyncPage",
"SyncPage",
# Streaming
"AsyncDialecticStreamResponse",
"DialecticStreamResponse",
# Exceptions
"APIError",
"AuthenticationError",
"BadRequestError",
"ConflictError",
"ConnectionError",
"HonchoError",
"NotFoundError",
"PermissionDeniedError",
"RateLimitError",
"ServerError",
"TimeoutError",
"UnprocessableEntityError",
]
File diff suppressed because it is too large Load Diff
+554
View File
@@ -0,0 +1,554 @@
"""API types for Honcho SDK.
These types mirror the server's Pydantic schemas for API responses and requests.
"""
from __future__ import annotations
import datetime
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
# ==============================================================================
# Configuration Types
# ==============================================================================
class ReasoningConfiguration(BaseModel):
"""Configuration for reasoning functionality."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
enabled: bool | None = None
custom_instructions: str | None = None
class PeerCardConfiguration(BaseModel):
"""Configuration for peer card functionality."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
use: bool | None = None
create: bool | None = None
class SummaryConfiguration(BaseModel):
"""Configuration for summary functionality."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
enabled: bool | None = None
messages_per_short_summary: int | None = None
messages_per_long_summary: int | None = None
class DreamConfiguration(BaseModel):
"""Configuration for dream functionality."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
enabled: bool | None = None
class WorkspaceConfiguration(BaseModel):
"""Workspace-level configuration options."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
reasoning: ReasoningConfiguration | None = None
peer_card: PeerCardConfiguration | None = None
summary: SummaryConfiguration | None = None
dream: DreamConfiguration | None = None
class SessionConfiguration(WorkspaceConfiguration):
"""Session-level configuration options."""
pass
class WorkspaceConfigurationResponse(WorkspaceConfiguration):
"""Workspace configuration for response parsing — tolerates unknown fields from newer servers."""
model_config = ConfigDict(extra="ignore") # pyright: ignore[reportUnannotatedClassAttribute]
class SessionConfigurationResponse(SessionConfiguration):
"""Session configuration for response parsing — tolerates unknown fields from newer servers."""
model_config = ConfigDict(extra="ignore") # pyright: ignore[reportUnannotatedClassAttribute]
class MessageConfiguration(BaseModel):
"""Message-level configuration options."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
reasoning: ReasoningConfiguration | None = None
# ==============================================================================
# Peer Config Types
# ==============================================================================
class PeerConfig(BaseModel):
"""Configuration for peer-level settings."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
observe_me: bool | None = None
"""Whether Honcho will use reasoning to form a representation of this peer."""
class SessionPeerConfig(BaseModel):
"""Configuration for a peer within a session."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
observe_others: bool | None = Field(
None,
description="Whether this peer should form a session-level theory-of-mind representation of other peers in the session",
)
observe_me: bool | None = Field(
None,
description="Whether other peers in this session should try to form a session-level theory-of-mind representation of this peer",
)
# ==============================================================================
# Workspace Types
# ==============================================================================
class WorkspaceResponse(BaseModel):
"""Workspace API response."""
model_config = ConfigDict(populate_by_name=True) # pyright: ignore[reportUnannotatedClassAttribute]
id: str
metadata: dict[str, Any] = Field(default_factory=dict)
configuration: WorkspaceConfigurationResponse = Field(
default_factory=WorkspaceConfigurationResponse
)
created_at: datetime.datetime
class WorkspaceCreateParams(BaseModel):
"""Parameters for creating a workspace."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
id: str = Field(min_length=1, max_length=512)
metadata: dict[str, Any] = Field(default_factory=dict)
configuration: WorkspaceConfiguration = Field(
default_factory=WorkspaceConfiguration
)
class WorkspaceUpdateParams(BaseModel):
"""Parameters for updating a workspace."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
metadata: dict[str, Any] | None = None
configuration: WorkspaceConfiguration | None = None
class WorkspaceListParams(BaseModel):
"""Parameters for listing workspaces."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
filters: dict[str, Any] | None = None
# ==============================================================================
# Peer Types
# ==============================================================================
class PeerResponse(BaseModel):
"""Peer API response."""
model_config = ConfigDict(populate_by_name=True) # pyright: ignore[reportUnannotatedClassAttribute]
id: str
workspace_id: str
created_at: datetime.datetime
metadata: dict[str, Any] = Field(default_factory=dict)
configuration: PeerConfig = Field(default_factory=PeerConfig)
class PeerCreateParams(BaseModel):
"""Parameters for creating a peer."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
id: str = Field(min_length=1, max_length=512)
metadata: dict[str, Any] | None = None
configuration: PeerConfig | None = None
class PeerUpdateParams(BaseModel):
"""Parameters for updating a peer."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
metadata: dict[str, Any] | None = None
configuration: PeerConfig | None = None
class PeerListParams(BaseModel):
"""Parameters for listing peers."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
filters: dict[str, Any] | None = None
class PeerRepresentationParams(BaseModel):
"""Parameters for getting peer representation."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
session_id: str | None = None
target: str | None = None
search_query: str | None = None
search_top_k: int | None = Field(default=None, ge=1, le=100)
search_max_distance: float | None = Field(default=None, ge=0.0, le=1.0)
include_most_frequent: bool | None = None
max_conclusions: int | None = Field(default=25, ge=1, le=100)
class RepresentationResponse(BaseModel):
"""Representation API response."""
representation: str
class PeerCardResponse(BaseModel):
"""Peer card API response."""
peer_card: list[str] | None = None
class PeerContextResponse(BaseModel):
"""Peer context API response."""
peer_id: str
target_id: str
representation: str | None = None
peer_card: list[str] | None = None
# ==============================================================================
# Session Types
# ==============================================================================
class SessionResponse(BaseModel):
"""Session API response."""
model_config = ConfigDict(populate_by_name=True) # pyright: ignore[reportUnannotatedClassAttribute]
id: str
is_active: bool
workspace_id: str
metadata: dict[str, Any] = Field(default_factory=dict)
configuration: SessionConfigurationResponse = Field(
default_factory=SessionConfigurationResponse
)
created_at: datetime.datetime
class SessionCreateParams(BaseModel):
"""Parameters for creating a session."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
id: str = Field(min_length=1, max_length=512)
metadata: dict[str, Any] | None = None
peers: dict[str, SessionPeerConfig] | None = None
configuration: SessionConfiguration | None = None
class SessionUpdateParams(BaseModel):
"""Parameters for updating a session."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
metadata: dict[str, Any] | None = None
configuration: SessionConfiguration | None = None
class SessionListParams(BaseModel):
"""Parameters for listing sessions."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
filters: dict[str, Any] | None = None
# ==============================================================================
# Summary Types
# ==============================================================================
class Summary(BaseModel):
"""Summary model."""
content: str
message_id: str
summary_type: str
created_at: str
token_count: int
class SessionSummariesResponse(BaseModel):
"""Session summaries API response."""
model_config = ConfigDict(populate_by_name=True) # pyright: ignore[reportUnannotatedClassAttribute]
id: str
short_summary: Summary | None = None
long_summary: Summary | None = None
# ==============================================================================
# Session Context Types
# ==============================================================================
class SessionContextResponse(BaseModel):
"""Session context API response."""
model_config = ConfigDict(populate_by_name=True) # pyright: ignore[reportUnannotatedClassAttribute]
id: str
messages: list["MessageResponse"]
summary: Summary | None = None
peer_representation: str | None = None
peer_card: list[str] | None = None
# ==============================================================================
# Message Types
# ==============================================================================
class MessageResponse(BaseModel):
"""Message API response."""
model_config = ConfigDict(populate_by_name=True) # pyright: ignore[reportUnannotatedClassAttribute]
id: str
content: str
peer_id: str
session_id: str
metadata: dict[str, Any] = Field(default_factory=dict)
created_at: datetime.datetime
workspace_id: str
token_count: int
class MessageCreateParams(BaseModel):
"""Parameters for creating a message."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
content: str
peer_id: str
metadata: dict[str, Any] | None = None
configuration: MessageConfiguration | None = None
created_at: datetime.datetime | None = None
class MessageBatchCreateParams(BaseModel):
"""Parameters for batch message creation."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
messages: list[MessageCreateParams] = Field(min_length=1, max_length=100)
class MessageUpdateParams(BaseModel):
"""Parameters for updating a message."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
metadata: dict[str, Any] | None = None
class MessageListParams(BaseModel):
"""Parameters for listing messages."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
filters: dict[str, Any] | None = None
class MessageSearchParams(BaseModel):
"""Parameters for searching messages."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
query: str
filters: dict[str, Any] | None = None
limit: int = Field(default=10, ge=1, le=100)
# ==============================================================================
# Conclusion Types
# ==============================================================================
class ConclusionResponse(BaseModel):
"""Conclusion API response."""
model_config = ConfigDict(populate_by_name=True) # pyright: ignore[reportUnannotatedClassAttribute]
id: str
content: str
observer_id: str
observed_id: str
session_id: str | None = None
created_at: datetime.datetime
class ConclusionCreateParams(BaseModel):
"""Parameters for creating a conclusion."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
content: str = Field(min_length=1, max_length=65535)
observer_id: str
observed_id: str
session_id: str | None = None
class ConclusionBatchCreateParams(BaseModel):
"""Parameters for batch conclusion creation."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
conclusions: list[ConclusionCreateParams] = Field(min_length=1, max_length=100)
class ConclusionListParams(BaseModel):
"""Parameters for listing conclusions."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
filters: dict[str, Any] | None = None
class ConclusionQueryParams(BaseModel):
"""Parameters for querying conclusions."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
query: str
top_k: int = Field(default=10, ge=1, le=100)
distance: float | None = Field(default=None, ge=0.0, le=1.0)
filters: dict[str, Any] | None = None
# ==============================================================================
# Queue Status Types
# ==============================================================================
class SessionQueueStatus(BaseModel):
"""Status for a specific session in the queue."""
session_id: str | None = None
total_work_units: int
completed_work_units: int
in_progress_work_units: int
pending_work_units: int
class QueueStatusResponse(BaseModel):
"""Queue status API response."""
total_work_units: int
completed_work_units: int
in_progress_work_units: int
pending_work_units: int
sessions: dict[str, SessionQueueStatus] | None = None
# ==============================================================================
# Dialectic (Chat) Types
# ==============================================================================
ReasoningLevel = Literal["minimal", "low", "medium", "high", "max"]
class DialecticParams(BaseModel):
"""Parameters for dialectic chat."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
session_id: str | None = None
target: str | None = None
query: str = Field(min_length=1, max_length=10000)
stream: bool = False
reasoning_level: ReasoningLevel = "low"
class DialecticResponse(BaseModel):
"""Dialectic chat API response."""
content: str | None
class DialecticStreamDelta(BaseModel):
"""Delta for streaming dialectic responses."""
content: str | None = None
class DialecticStreamChunk(BaseModel):
"""Chunk in a streaming dialectic response."""
delta: DialecticStreamDelta
done: bool = False
# ==============================================================================
# Pagination Types
# ==============================================================================
class PageResponse(BaseModel):
"""Generic paginated response."""
items: list[Any]
page: int
size: int
total: int
pages: int
# ==============================================================================
# File Upload Types
# ==============================================================================
class MessageUploadParams(BaseModel):
"""Parameters for file upload message creation."""
model_config = ConfigDict(extra="forbid") # pyright: ignore[reportUnannotatedClassAttribute]
peer_id: str
metadata: dict[str, Any] | None = None
configuration: MessageConfiguration | None = None
created_at: datetime.datetime | None = None
# Update forward reference
SessionContextResponse.model_rebuild()
+45
View File
@@ -0,0 +1,45 @@
"""Base classes for Honcho SDK entities.
This module provides base classes that contain only the essential data fields
shared by both sync and async variants of Peer and Session. These base classes
can be imported anywhere without causing circular import issues, enabling
type-safe method signatures like `str | PeerBase`.
"""
from pydantic import BaseModel, Field
class PeerBase(BaseModel):
"""Base class for Peer objects (sync and async variants).
This class contains only the essential data fields shared by both
Peer and AsyncPeer. Use this type in method signatures to accept
either a peer ID string or any Peer object.
Attributes:
id: Unique identifier for this peer
workspace_id: Workspace ID for scoping operations
"""
id: str = Field(..., min_length=1, description="Unique identifier for this peer")
workspace_id: str = Field(
..., min_length=1, description="Workspace ID for scoping operations"
)
class SessionBase(BaseModel):
"""Base class for Session objects (sync and async variants).
This class contains only the essential data fields shared by both
Session and AsyncSession. Use this type in method signatures to accept
either a session ID string or any Session object.
Attributes:
id: Unique identifier for this session
workspace_id: Workspace ID for scoping operations
"""
id: str = Field(..., min_length=1, description="Unique identifier for this session")
workspace_id: str = Field(
..., min_length=1, description="Workspace ID for scoping operations"
)
+710
View File
@@ -0,0 +1,710 @@
"""Sync Honcho client."""
from __future__ import annotations
import logging
import os
from collections.abc import Mapping
from typing import Any, Literal
import httpx
from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, validate_call
from .aio import HonchoAio
from .api_types import (
MessageResponse,
PeerConfig,
PeerResponse,
QueueStatusResponse,
SessionConfiguration,
SessionPeerConfig,
SessionResponse,
WorkspaceConfiguration,
WorkspaceResponse,
)
from .base import PeerBase, SessionBase
from .http import AsyncHonchoHTTPClient, HonchoHTTPClient, routes
from .message import Message
from .mixins import MetadataConfigMixin
from .pagination import SyncPage
from .peer import Peer
from .session import Session
from .utils import normalize_peers_to_dict, resolve_id
logger = logging.getLogger(__name__)
# Environment configuration
ENVIRONMENTS = {
"local": "http://localhost:8000",
"production": "https://api.honcho.dev",
}
class Honcho(BaseModel, MetadataConfigMixin): # pyright: ignore[reportUnsafeMultipleInheritance]
"""
Main client for the Honcho SDK.
Provides access to peers, sessions, and workspace operations with configuration
from environment variables or explicit parameters. This is the primary entry
point for interacting with the Honcho conversational memory platform.
Attributes:
workspace_id: Workspace ID for scoping operations
metadata: Cached metadata for this workspace. May be stale if not recently
fetched. Call get_metadata() for fresh data.
configuration: Cached configuration for this workspace. May be stale if not
recently fetched. Call get_configuration() for fresh data.
"""
model_config = ConfigDict(extra="forbid") # pyright: ignore
workspace_id: str = Field(
...,
min_length=1,
description="Workspace ID for scoping operations",
)
_metadata: dict[str, object] | None = PrivateAttr(default=None)
_configuration: WorkspaceConfiguration | None = PrivateAttr(default=None)
_http: HonchoHTTPClient = PrivateAttr()
_async_http: AsyncHonchoHTTPClient | None = PrivateAttr(default=None)
_http_config: dict[str, Any] = PrivateAttr()
_base_url: str = PrivateAttr()
_workspace_ensured: bool = PrivateAttr(default=False)
@property
def metadata(self) -> dict[str, object] | None:
"""Cached metadata for this workspace. May be stale. Use get_metadata() for fresh data."""
return self._metadata
@property
def configuration(self) -> WorkspaceConfiguration | None:
"""Cached configuration for this workspace. May be stale. Use get_configuration() for fresh data."""
return self._configuration
# MetadataConfigMixin implementation
def _get_http_client(self):
"""Return the sync HTTP client used by metadata helpers."""
return self._http
def _get_fetch_route(self) -> str:
"""Return the workspace fetch route for metadata helpers."""
return routes.workspaces()
def _get_update_route(self) -> str:
"""Return the workspace update route for metadata helpers."""
return routes.workspace(self.workspace_id)
def _get_fetch_body(self) -> dict[str, Any]:
"""Return the request body used to fetch this workspace."""
return {"id": self.workspace_id}
def _parse_response(
self, data: dict[str, Any]
) -> tuple[dict[str, object], dict[str, object]]:
"""Parse workspace metadata and configuration from an API response."""
workspace = WorkspaceResponse.model_validate(data)
# Return configuration as dict for mixin compatibility
return workspace.metadata or {}, workspace.configuration.model_dump(
exclude_none=True
)
def get_configuration(self) -> WorkspaceConfiguration: # pyright: ignore[reportIncompatibleMethodOverride]
"""
Get configuration from the server and update the cache.
Returns:
A WorkspaceConfiguration object containing the configuration settings.
"""
data = self._get_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
workspace = WorkspaceResponse.model_validate(data)
self._metadata = workspace.metadata or {}
self._configuration = workspace.configuration
return self._configuration
@validate_call
def set_configuration( # pyright: ignore[reportIncompatibleMethodOverride]
self,
configuration: WorkspaceConfiguration = Field(
..., description="Configuration to set"
),
) -> None:
"""
Set configuration on the server and update the cache.
Args:
configuration: A WorkspaceConfiguration object with configuration settings.
"""
self._get_http_client().put(
self._get_update_route(),
body={"configuration": configuration.model_dump(exclude_none=True)},
)
self._configuration = configuration # pyright: ignore[reportIncompatibleVariableOverride]
@property
def base_url(self) -> str:
"""The base URL of the Honcho API."""
return self._base_url
@property
def _async_http_client(self) -> AsyncHonchoHTTPClient:
"""Lazily create and return the async HTTP client."""
if self._async_http is None:
self._async_http = AsyncHonchoHTTPClient(**self._http_config)
return self._async_http
@property
def aio(self) -> HonchoAio:
"""
Access async versions of all Honcho methods.
Returns an HonchoAio view that provides async versions of all methods
while sharing state with this Honcho instance.
Example:
```python
honcho = Honcho(workspace_id="my-workspace")
# Async operations
peer = await honcho.aio.peer("user-123")
async for p in honcho.aio.peers():
print(p.id)
```
"""
return HonchoAio(self)
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def __init__(
self,
api_key: str | None = None,
environment: Literal["local", "production"] | None = None,
base_url: str | None = Field(None, description="Base URL for the Honcho API"),
workspace_id: str | None = Field(
None, min_length=1, description="Workspace ID for scoping operations"
),
timeout: float | None = Field(None, gt=0, description="Timeout in seconds"),
max_retries: int | None = Field(
None, ge=0, description="Maximum number of retries"
),
default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
http_client: httpx.Client | None = Field(
None, description="Custom HTTP client"
),
) -> None:
"""
Initialize the Honcho client.
Args:
api_key:
API key for authentication. If not provided, will attempt to
read from HONCHO_API_KEY environment variable
environment:
Environment to use (local or production)
base_url:
Base URL for the Honcho API. If not provided, will attempt to
read from HONCHO_URL environment variable or default to the
production API URL
workspace_id:
Workspace ID to use for operations. If not provided, will
attempt to read from HONCHO_WORKSPACE_ID environment variable
or default to "default"
timeout:
Optional custom timeout for the HTTP client.
max_retries:
Optional custom maximum number of retries for the HTTP client.
default_headers:
Optional custom default headers for the HTTP client.
default_query:
Optional custom default query parameters for the HTTP client.
http_client:
Optional custom httpx client.
"""
# Resolve workspace_id before calling super().__init__
resolved_workspace_id = workspace_id or os.getenv(
"HONCHO_WORKSPACE_ID", "default"
)
super().__init__(workspace_id=resolved_workspace_id)
# Resolve API key
resolved_api_key = api_key or os.getenv("HONCHO_API_KEY")
# Resolve base URL
if base_url:
resolved_base_url = base_url
elif environment:
resolved_base_url = ENVIRONMENTS[environment]
else:
resolved_base_url = os.getenv("HONCHO_URL", ENVIRONMENTS["production"])
self._base_url = resolved_base_url
# Build HTTP client kwargs
http_kwargs: dict[str, Any] = {
"base_url": resolved_base_url,
"api_key": resolved_api_key,
}
if timeout is not None:
http_kwargs["timeout"] = timeout
if max_retries is not None:
http_kwargs["max_retries"] = max_retries
if default_headers is not None:
http_kwargs["default_headers"] = dict(default_headers)
if default_query is not None:
http_kwargs["default_query"] = dict(default_query)
# Store config for lazy async client creation (without custom http_client)
self._http_config = dict(http_kwargs)
if http_client is not None:
http_kwargs["http_client"] = http_client
self._http = HonchoHTTPClient(**http_kwargs)
def _ensure_workspace(self) -> None:
"""
Ensure the workspace exists on the server.
The Honcho API uses get-or-create semantics for workspaces via
`POST /v3/workspaces`. This SDK uses that endpoint once per client
instance to guarantee that subsequent workspace-scoped calls (peers,
sessions, queue status, etc.) operate on an existing workspace.
"""
if self._workspace_ensured:
return
self._http.post(routes.workspaces(), body={"id": self.workspace_id})
self._workspace_ensured = True
async def _ensure_workspace_async(self) -> None:
"""
Async version of `_ensure_workspace`.
This performs the same get-or-create call, but via the async HTTP client
used by `honcho.aio`.
"""
if self._workspace_ensured:
return
await self._async_http_client.post(
routes.workspaces(), body={"id": self.workspace_id}
)
self._workspace_ensured = True
@validate_call
def peer(
self,
id: str = Field(
..., min_length=1, description="Unique identifier for the peer"
),
*,
metadata: dict[str, object] | None = Field(
None,
description="Optional metadata dictionary to associate with this peer. If set, will get/create peer immediately with metadata.",
),
configuration: PeerConfig | None = Field(
None,
description="Optional configuration to set for this peer. If set, will get/create peer immediately with flags.",
),
) -> Peer:
"""
Get or create a peer with the given ID.
Makes an API call to get or create the peer, then returns a Peer object
with cached values from the response.
Args:
id: Unique identifier for the peer within the workspace.
metadata: Optional metadata dictionary to associate with this peer.
configuration: Optional configuration to set for this peer.
Returns:
A Peer object with cached metadata, configuration, and created_at.
"""
self._ensure_workspace()
body: dict[str, Any] = {"id": id}
if metadata is not None:
body["metadata"] = metadata
if configuration is not None:
body["configuration"] = configuration.model_dump(exclude_none=True)
data = self._http.post(routes.peers(self.workspace_id), body=body)
peer_data = PeerResponse.model_validate(data)
return Peer(
id,
self,
metadata=peer_data.metadata,
configuration=peer_data.configuration,
created_at=peer_data.created_at,
)
def peers(
self,
filters: dict[str, object] | None = None,
*,
page: int = 1,
size: int = 50,
reverse: bool = False,
) -> SyncPage[PeerResponse, Peer]:
"""
Get all peers in the current workspace.
Args:
filters: Optional filter criteria.
page: Page number (1-indexed). Default: 1.
size: Number of items per page. Default: 50.
reverse: If True, reverses the default ordering. Default: False.
Returns:
A SyncPage of Peer objects representing all peers in the workspace
"""
self._ensure_workspace()
query: dict[str, Any] = {"page": page, "size": size}
if reverse:
query["reverse"] = "true"
data = self._http.post(
routes.peers_list(self.workspace_id),
body={"filters": filters} if filters else None,
query=query,
)
def transform(peer: PeerResponse) -> Peer:
"""Convert a peer API response into a Peer SDK object."""
return Peer(
peer.id,
self,
metadata=peer.metadata,
configuration=peer.configuration,
created_at=peer.created_at,
)
def fetch_next(next_page: int) -> SyncPage[PeerResponse, Peer]:
"""Fetch the next page while preserving filters and ordering."""
next_query: dict[str, Any] = {"page": next_page, "size": size}
if reverse:
next_query["reverse"] = "true"
next_data = self._http.post(
routes.peers_list(self.workspace_id),
body={"filters": filters} if filters else None,
query=next_query,
)
return SyncPage(next_data, PeerResponse, transform, fetch_next)
return SyncPage(data, PeerResponse, transform, fetch_next)
@validate_call
def session(
self,
id: str = Field(
..., min_length=1, description="Unique identifier for the session"
),
*,
metadata: dict[str, object] | None = Field(
None,
description="Optional metadata dictionary to associate with this session. If set, will get/create session immediately with metadata.",
),
configuration: SessionConfiguration | None = Field(
None,
description="Optional configuration to set for this session. If set, will get/create session immediately with flags.",
),
peers: str
| PeerBase
| tuple[str, SessionPeerConfig]
| tuple[PeerBase, SessionPeerConfig]
| list[PeerBase | str]
| list[tuple[PeerBase | str, SessionPeerConfig]]
| list[PeerBase | str | tuple[PeerBase | str, SessionPeerConfig]]
| None = Field(
None,
description="Optional peers to attach to the session at creation. Accepts the same shape as Session.add_peers.",
),
) -> Session:
"""
Get or create a session with the given ID.
Makes an API call to get or create the session, then returns a Session object
with cached values from the response.
Args:
id: Unique identifier for the session within the workspace.
metadata: Optional metadata dictionary to associate with this session.
configuration: Optional configuration to set for this session.
peers: Optional peers to attach to the session at creation. Accepts the
same shape as Session.add_peers (peer ID string, Peer object, list
of either, or tuples with SessionPeerConfig).
Returns:
A Session object with cached metadata, configuration, created_at, and is_active.
"""
self._ensure_workspace()
body: dict[str, Any] = {"id": id}
if metadata is not None:
body["metadata"] = metadata
if configuration is not None:
body["configuration"] = configuration.model_dump(exclude_none=True)
if peers is not None:
body["peers"] = normalize_peers_to_dict(peers)
data = self._http.post(routes.sessions(self.workspace_id), body=body)
session_data = SessionResponse.model_validate(data)
return Session(
id,
self,
metadata=session_data.metadata,
configuration=SessionConfiguration.model_validate(
session_data.configuration.model_dump()
),
created_at=session_data.created_at,
is_active=session_data.is_active,
)
def sessions(
self,
filters: dict[str, object] | None = None,
*,
page: int = 1,
size: int = 50,
reverse: bool = False,
) -> SyncPage[SessionResponse, Session]:
"""
Get all sessions in the current workspace.
Args:
filters: Optional filter criteria.
page: Page number (1-indexed). Default: 1.
size: Number of items per page. Default: 50.
reverse: If True, reverses the default ordering. Default: False.
Returns:
A SyncPage of Session objects representing all sessions in the workspace.
"""
self._ensure_workspace()
query: dict[str, Any] = {"page": page, "size": size}
if reverse:
query["reverse"] = "true"
data = self._http.post(
routes.sessions_list(self.workspace_id),
body={"filters": filters} if filters else None,
query=query,
)
def transform(session: SessionResponse) -> Session:
"""Convert a session API response into a Session SDK object."""
return Session(
session.id,
self,
metadata=session.metadata,
configuration=session.configuration,
created_at=session.created_at,
is_active=session.is_active,
)
def fetch_next(next_page: int) -> SyncPage[SessionResponse, Session]:
"""Fetch the next page while preserving filters and ordering."""
next_query: dict[str, Any] = {"page": next_page, "size": size}
if reverse:
next_query["reverse"] = "true"
next_data = self._http.post(
routes.sessions_list(self.workspace_id),
body={"filters": filters} if filters else None,
query=next_query,
)
return SyncPage(next_data, SessionResponse, transform, fetch_next)
return SyncPage(data, SessionResponse, transform, fetch_next)
def workspaces(
self,
filters: dict[str, object] | None = None,
*,
page: int = 1,
size: int = 50,
reverse: bool = False,
) -> SyncPage[WorkspaceResponse, str]:
"""
Get all workspace IDs from the Honcho instance.
Makes an API call to retrieve all workspace IDs that the authenticated
user has access to.
Args:
filters: Optional filter criteria.
page: Page number (1-indexed). Default: 1.
size: Number of items per page. Default: 50.
reverse: If True, reverses the default ordering. Default: False.
Returns:
A paginated SyncPage of workspace ID strings
"""
query: dict[str, Any] = {"page": page, "size": size}
if reverse:
query["reverse"] = "true"
data = self._http.post(
routes.workspaces_list(),
body={"filters": filters} if filters else None,
query=query,
)
def transform(workspace: WorkspaceResponse) -> str:
"""Convert a workspace API response into its workspace ID."""
return workspace.id
def fetch_next(next_page: int) -> SyncPage[WorkspaceResponse, str]:
"""Fetch the next page while preserving filters and ordering."""
next_query: dict[str, Any] = {"page": next_page, "size": size}
if reverse:
next_query["reverse"] = "true"
next_data = self._http.post(
routes.workspaces_list(),
body={"filters": filters} if filters else None,
query=next_query,
)
return SyncPage(next_data, WorkspaceResponse, transform, fetch_next)
return SyncPage(data, WorkspaceResponse, transform, fetch_next)
@validate_call
def delete_workspace(
self,
workspace_id: str = Field(
..., min_length=1, description="ID of the workspace to delete"
),
) -> None:
"""
Delete a workspace.
Makes an API call to delete the specified workspace. This action cannot be undone.
Args:
workspace_id: The ID of the workspace to delete
"""
self._http.delete(routes.workspace(workspace_id))
@validate_call
def search(
self,
query: str = Field(..., min_length=1, description="The search query to use"),
filters: dict[str, object] | None = Field(
None, description="Filters to scope the search"
),
limit: int = Field(
default=10, ge=1, le=100, description="Number of results to return"
),
) -> list[Message]:
"""
Search for messages in the current workspace.
Makes an API call to search for messages in the current workspace.
Args:
query: The search query to use
filters: Filters to scope the search. See [search filters documentation](https://honcho.dev/docs/v3/documentation/core-concepts/features/using-filters).
limit: Number of results to return (1-100, default: 10)
Returns:
A list of Message objects representing the search results.
Returns an empty list if no messages are found.
"""
self._ensure_workspace()
data = self._http.post(
routes.workspace_search(self.workspace_id),
body={"query": query, "filters": filters, "limit": limit},
)
return [
Message.from_api_response(MessageResponse.model_validate(item))
for item in data
]
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def queue_status(
self,
observer: str | PeerBase | None = None,
sender: str | PeerBase | None = None,
session: str | SessionBase | None = None,
) -> QueueStatusResponse:
"""
Get the queue processing status, optionally scoped to an observer, sender, and/or session.
Args:
observer: Optional observer (ID string or Peer object) to scope the status check
sender: Optional sender (ID string or Peer object) to scope the status check
session: Optional session (ID string or Session object) to scope the status check
"""
self._ensure_workspace()
resolved_observer_id = resolve_id(observer)
resolved_sender_id = resolve_id(sender)
resolved_session_id = resolve_id(session)
query: dict[str, Any] = {}
if resolved_observer_id:
query["observer_id"] = resolved_observer_id
if resolved_sender_id:
query["sender_id"] = resolved_sender_id
if resolved_session_id:
query["session_id"] = resolved_session_id
data = self._http.get(
routes.workspace_queue_status(self.workspace_id),
query=query if query else None,
)
return QueueStatusResponse.model_validate(data)
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def schedule_dream(
self,
observer: str | PeerBase,
session: str | SessionBase | None = None,
observed: str | PeerBase | None = None,
) -> None:
"""
Schedule a dream task for memory consolidation.
Dreams are background processes that consolidate observations into higher-level
insights and update peer cards. This method schedules a dream task for immediate
processing.
Args:
observer: The observer peer (ID string or Peer object) whose perspective
to use for the dream.
session: Optional session (ID string or Session object) to scope the dream to.
observed: Optional observed peer (ID string or Peer object). If not provided,
defaults to the observer (self-reflection).
"""
self._ensure_workspace()
resolved_observer_id = resolve_id(observer)
resolved_session_id = resolve_id(session)
resolved_observed_id = (
resolve_id(observed) if observed else resolved_observer_id
)
self._http.post(
routes.workspace_schedule_dream(self.workspace_id),
body={
"observer": resolved_observer_id,
"observed": resolved_observed_id,
"session_id": resolved_session_id,
"dream_type": "omni",
},
)
def __repr__(self) -> str:
"""
Return a string representation of the Honcho client.
Returns:
A string representation suitable for debugging
"""
return (
f"Honcho(workspace_id='{self.workspace_id}', base_url='{self._base_url}')"
)
def __str__(self) -> str:
"""
Return a human-readable string representation of the Honcho client.
Returns:
A string showing the workspace ID
"""
return f"Honcho Client (workspace: {self.workspace_id})"
+394
View File
@@ -0,0 +1,394 @@
# pyright: reportPrivateUsage=false
"""Conclusion types and scoped access for the Honcho SDK."""
from __future__ import annotations
import datetime
from typing import TYPE_CHECKING, Any
from pydantic import BaseModel
from .api_types import ConclusionResponse, RepresentationResponse
from .base import SessionBase
from .http import routes
from .pagination import SyncPage
from .utils import resolve_id
if TYPE_CHECKING:
from .aio import ConclusionScopeAio
from .client import Honcho
__all__ = [
"Conclusion",
"ConclusionScope",
"ConclusionCreateParams",
]
class ConclusionCreateParams(BaseModel):
content: str
session_id: str | None = None
class Conclusion:
"""
A conclusion from Honcho's reasoning system.
Conclusions are facts derived from messages that help build a representation
of a peer.
Attributes:
id: Unique identifier for this conclusion
content: The conclusion content/text
observer_id: The peer ID who made this conclusion
observed_id: The peer ID this conclusion is about
session_id: The session this conclusion relates to
created_at: Timestamp for when the conclusion was created
"""
id: str
content: str
observer_id: str
observed_id: str
session_id: str | None = None
created_at: datetime.datetime
def __init__(
self,
id: str,
content: str,
observer_id: str,
observed_id: str,
session_id: str | None,
created_at: datetime.datetime,
) -> None:
self.id = id
self.content = content
self.observer_id = observer_id
self.observed_id = observed_id
self.session_id = session_id
self.created_at = created_at
@classmethod
def from_api_response(cls, data: ConclusionResponse) -> "Conclusion":
"""Create a Conclusion from an API response."""
return cls(
id=data.id,
content=data.content,
observer_id=data.observer_id,
observed_id=data.observed_id,
session_id=data.session_id,
created_at=data.created_at,
)
def __repr__(self) -> str:
truncated = (
f"{self.content[:50]}..." if len(self.content) > 50 else self.content
)
return f"Conclusion(id='{self.id}', content='{truncated}')"
def __str__(self) -> str:
return self.content
class ConclusionScope:
"""
Scoped access to conclusions for a specific observer/observed relationship.
This class provides convenient methods to list, query, create, and delete conclusions
that are automatically scoped to a specific observer/observed pair.
Typically accessed via `peer.conclusions` (for self-conclusions) or
`peer.conclusions_of(target)` (for conclusions about another peer).
Example:
```python
# Get self-conclusions
conclusions = peer.conclusions
obs_list = conclusions.list()
search_results = conclusions.query("preferences")
# Get conclusions about another peer
bob_conclusions = peer.conclusions_of("bob")
bob_list = bob_conclusions.list()
# Async operations via .aio accessor
obs_list = await peer.conclusions.aio.list()
```
"""
_honcho: "Honcho"
workspace_id: str
observer: str
observed: str
def __init__(
self,
honcho: "Honcho",
workspace_id: str,
observer: str,
observed: str,
):
"""
Initialize a ConclusionScope.
Args:
honcho: The Honcho client instance
workspace_id: The workspace ID
observer: The observer peer ID
observed: The observed peer ID
"""
self._honcho = honcho
self.workspace_id = workspace_id
self.observer = observer
self.observed = observed
@property
def aio(self) -> "ConclusionScopeAio":
"""
Access async versions of all ConclusionScope methods.
Returns a ConclusionScopeAio view that provides async versions of all methods
while sharing state with this ConclusionScope instance.
Example:
```python
# Async operations
obs_list = await scope.aio.list()
results = await scope.aio.query("preferences")
```
"""
# Import here to avoid circular import (aio.py imports from this module)
from .aio import ConclusionScopeAio
return ConclusionScopeAio(self)
def list(
self,
page: int = 1,
size: int = 50,
session: str | SessionBase | None = None,
*,
reverse: bool = False,
) -> SyncPage[ConclusionResponse, Conclusion]:
"""
List conclusions in this scope.
Args:
page: Page number (1-indexed)
size: Number of results per page
session: Optional session (ID string or Session object) to filter by
reverse: If True, reverses the default ordering. Default: False.
Returns:
Paginated response containing Conclusion objects
"""
self._honcho._ensure_workspace()
resolved_session_id = resolve_id(session)
filters: dict[str, Any] = {
"observer_id": self.observer,
"observed_id": self.observed,
}
if resolved_session_id:
filters["session_id"] = resolved_session_id
query: dict[str, Any] = {"page": page, "size": size}
if reverse:
query["reverse"] = "true"
data = self._honcho._http.post(
routes.conclusions_list(self.workspace_id),
body={"filters": filters},
query=query,
)
def transform(response: ConclusionResponse) -> Conclusion:
return Conclusion.from_api_response(response)
def fetch_next(
next_page: int,
) -> SyncPage[ConclusionResponse, Conclusion]:
next_query: dict[str, Any] = {"page": next_page, "size": size}
if reverse:
next_query["reverse"] = "true"
next_data = self._honcho._http.post(
routes.conclusions_list(self.workspace_id),
body={"filters": filters},
query=next_query,
)
return SyncPage(next_data, ConclusionResponse, transform, fetch_next)
return SyncPage(data, ConclusionResponse, transform, fetch_next)
def query(
self,
query: str,
top_k: int = 10,
distance: float | None = None,
) -> list[Conclusion]:
"""
Semantic search for conclusions in this scope.
Args:
query: The search query string
top_k: Maximum number of results to return
distance: Maximum cosine distance threshold (0.0-1.0)
Returns:
List of matching Conclusion objects
"""
self._honcho._ensure_workspace()
filters: dict[str, Any] = {
"observer_id": self.observer,
"observed_id": self.observed,
}
body: dict[str, Any] = {
"query": query,
"top_k": top_k,
"filters": filters,
}
if distance is not None:
body["distance"] = distance
data = self._honcho._http.post(
routes.conclusions_query(self.workspace_id),
body=body,
)
return [
Conclusion.from_api_response(ConclusionResponse.model_validate(item))
for item in data
]
def delete(self, conclusion_id: str) -> None:
"""
Delete a conclusion by ID.
Args:
conclusion_id: The ID of the conclusion to delete
"""
self._honcho._ensure_workspace()
self._honcho._http.delete(routes.conclusion(self.workspace_id, conclusion_id))
def create(
self,
conclusions: list[ConclusionCreateParams | dict[str, Any]],
) -> list[Conclusion]:
"""
Create conclusions in this scope.
Args:
conclusions: List of conclusions to create.
Each conclusion can be a ConclusionCreateParams object or a dictionary
with a required 'content' key and an optional 'session_id' key.
Returns:
List of created Conclusion objects
Example:
```python
conclusions = peer.conclusions.create([
{"content": "User prefers dark mode", "session_id": "session1"},
{"content": "User is interested in AI"},
])
```
"""
self._honcho._ensure_workspace()
def build_conclusion_payload(
item: ConclusionCreateParams | dict[str, Any],
) -> dict[str, Any]:
"""
Build a single conclusion create payload.
This normalizes both `ConclusionCreateParams` instances and plain dictionaries
into the wire format expected by the Honcho API.
Notes:
- `content` is required.
- `session_id` is optional; when not provided it is omitted from the payload.
- `observer_id` and `observed_id` are always injected from this scope.
Args:
item: A `ConclusionCreateParams` instance or a dict with a required
`content` key and an optional `session_id` key.
Returns:
A dictionary suitable for inclusion in the `conclusions` array for the
create conclusions endpoint.
"""
payload: dict[str, Any] = {
"observer_id": self.observer,
"observed_id": self.observed,
}
if isinstance(item, ConclusionCreateParams):
payload["content"] = item.content
if item.session_id is not None:
payload["session_id"] = item.session_id
return payload
payload["content"] = item["content"]
session_id = item.get("session_id")
if session_id is not None:
payload["session_id"] = session_id
return payload
conclusion_params = [build_conclusion_payload(c) for c in conclusions]
data = self._honcho._http.post(
routes.conclusions(self.workspace_id),
body={"conclusions": conclusion_params},
)
return [
Conclusion.from_api_response(ConclusionResponse.model_validate(item))
for item in data
]
def representation(
self,
search_query: str | None = None,
search_top_k: int | None = None,
search_max_distance: float | None = None,
include_most_frequent: bool | None = None,
max_conclusions: int | None = None,
) -> str:
"""
Get the computed representation for this scope.
This returns the working representation (narrative) built from the
conclusions in this scope.
Args:
search_query: Optional semantic search query to curate the representation
search_top_k: Number of semantically relevant facts to return
search_max_distance: Maximum semantic distance for search results (0.0-1.0)
include_most_frequent: Whether to include the most frequent conclusions
max_conclusions: Maximum number of conclusions to include
Returns:
A Representation string
"""
self._honcho._ensure_workspace()
body: dict[str, Any] = {"target": self.observed}
if search_query is not None:
body["search_query"] = search_query
if search_top_k is not None:
body["search_top_k"] = search_top_k
if search_max_distance is not None:
body["search_max_distance"] = search_max_distance
if include_most_frequent is not None:
body["include_most_frequent"] = include_most_frequent
if max_conclusions is not None:
body["max_conclusions"] = max_conclusions
data = self._honcho._http.post(
routes.peer_representation(self.workspace_id, self.observer),
body=body,
)
response = RepresentationResponse.model_validate(data)
return response.representation
def __repr__(self) -> str:
return (
f"ConclusionScope(workspace_id={self.workspace_id!r}, "
f"observer={self.observer!r}, observed={self.observed!r})"
)
+37
View File
@@ -0,0 +1,37 @@
"""HTTP client module for Honcho SDK."""
from .async_client import AsyncHonchoHTTPClient
from .client import HonchoHTTPClient
from .exceptions import (
APIError,
AuthenticationError,
BadRequestError,
ConflictError,
ConnectionError,
HonchoError,
NotFoundError,
PermissionDeniedError,
RateLimitError,
ServerError,
TimeoutError,
UnprocessableEntityError,
)
__all__ = [
# Errors
"HonchoError",
"APIError",
"BadRequestError",
"AuthenticationError",
"PermissionDeniedError",
"NotFoundError",
"ConflictError",
"UnprocessableEntityError",
"RateLimitError",
"ServerError",
"TimeoutError",
"ConnectionError",
# Clients
"HonchoHTTPClient",
"AsyncHonchoHTTPClient",
]
+384
View File
@@ -0,0 +1,384 @@
"""Async HTTP client for Honcho SDK."""
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
from typing import Any, cast
import httpx
from .exceptions import (
ConnectionError,
RateLimitError,
ServerError,
TimeoutError,
create_error_from_response,
)
DEFAULT_TIMEOUT = 60.0 # 60 seconds
DEFAULT_MAX_RETRIES = 2
RETRY_STATUS_CODES = {429, 500, 502, 503, 504}
INITIAL_RETRY_DELAY = 0.5 # 500ms
class AsyncHonchoHTTPClient:
"""Async HTTP client for the Honcho API with retry logic and timeout support."""
base_url: str
api_key: str | None
timeout: float
max_retries: int
default_headers: dict[str, str]
default_query: dict[str, Any] | None
_owns_client: bool
_client: httpx.AsyncClient
def __init__(
self,
*,
base_url: str,
api_key: str | None = None,
timeout: float = DEFAULT_TIMEOUT,
max_retries: int = DEFAULT_MAX_RETRIES,
default_headers: dict[str, str] | None = None,
default_query: dict[str, Any] | None = None,
http_client: httpx.AsyncClient | None = None,
) -> None:
# Remove trailing slash from base_url
self.base_url = base_url.rstrip("/")
self.api_key = api_key
self.timeout = timeout
self.max_retries = max_retries
self.default_headers = {
"Content-Type": "application/json",
**(default_headers or {}),
}
self.default_query = default_query
self._owns_client = http_client is None
self._client = http_client or httpx.AsyncClient( # nosec B113
base_url=self.base_url,
timeout=httpx.Timeout(timeout),
)
async def close(self) -> None:
"""Close the HTTP client if we own it."""
if self._owns_client:
await self._client.aclose()
async def __aenter__(self) -> "AsyncHonchoHTTPClient":
return self
async def __aexit__(self, *args: Any) -> None:
await self.close()
async def request(
self,
method: str,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make an HTTP request with automatic retries and timeout handling."""
url = self._build_url(path)
request_headers = self._build_headers(headers)
request_timeout = timeout if timeout is not None else self.timeout
merged_query = {**(self.default_query or {}), **(query or {})} or None
last_error: Exception | None = None
attempt = 0
while attempt <= self.max_retries:
try:
response = await self._client.request(
method,
url,
json=body if body is not None else None,
params=self._clean_query_params(merged_query),
headers=request_headers,
timeout=request_timeout,
)
if response.is_success:
# Handle empty responses
text = response.text
if not text:
return None
return response.json()
# Handle error responses
error_body = self._parse_error_body(response)
retry_after = self._parse_retry_after(response)
error = create_error_from_response(
response.status_code,
error_body.get("message") or f"HTTP {response.status_code}",
body=error_body,
retry_after=retry_after,
)
# Only retry on specific status codes
if (
response.status_code in RETRY_STATUS_CODES
and attempt < self.max_retries
):
last_error = error
await asyncio.sleep(self._get_retry_delay(attempt, retry_after))
attempt += 1
continue
raise error
except (
httpx.TimeoutException,
httpx.NetworkError,
httpx.RemoteProtocolError,
) as e:
if isinstance(e, httpx.TimeoutException):
error = TimeoutError(f"Request timed out after {request_timeout}s")
else:
error = ConnectionError(f"Connection error: {e}")
if attempt < self.max_retries:
last_error = error
await asyncio.sleep(self._get_retry_delay(attempt))
attempt += 1
continue
raise error from e
except (TimeoutError, ConnectionError, RateLimitError, ServerError):
raise
except Exception as e:
# Re-raise API errors
if hasattr(e, "status"):
raise
raise ConnectionError(str(e)) from e
# If we exhausted retries, raise the last error
if last_error:
raise last_error
raise ConnectionError("Request failed after retries")
async def get(
self,
path: str,
*,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a GET request."""
return await self.request(
"GET", path, query=query, headers=headers, timeout=timeout
)
async def post(
self,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a POST request."""
return await self.request(
"POST", path, body=body, query=query, headers=headers, timeout=timeout
)
async def put(
self,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a PUT request."""
return await self.request(
"PUT", path, body=body, query=query, headers=headers, timeout=timeout
)
async def patch(
self,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a PATCH request."""
return await self.request(
"PATCH", path, body=body, query=query, headers=headers, timeout=timeout
)
async def delete(
self,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a DELETE request."""
return await self.request(
"DELETE", path, body=body, query=query, headers=headers, timeout=timeout
)
async def stream(
self,
method: str,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> AsyncIterator[bytes]:
"""Make a streaming request that yields raw bytes for SSE parsing."""
url = self._build_url(path)
request_headers = {
**self._build_headers(headers),
"Accept": "text/event-stream",
}
request_timeout = timeout if timeout is not None else self.timeout
merged_query = {**(self.default_query or {}), **(query or {})} or None
async with self._client.stream(
method,
url,
json=body if body is not None else None,
params=self._clean_query_params(merged_query),
headers=request_headers,
timeout=request_timeout,
) as response:
if not response.is_success:
# Read error body
await response.aread()
error_body = self._parse_error_body(response)
raise create_error_from_response(
response.status_code,
error_body.get("message") or f"HTTP {response.status_code}",
body=error_body,
)
async for chunk in response.aiter_bytes():
yield chunk
async def upload(
self,
path: str,
*,
files: dict[str, Any],
data: dict[str, Any] | None = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a multipart form data request (for file uploads)."""
url = self._build_url(path)
# Don't set Content-Type for multipart - httpx will set it with boundary
request_headers = self._build_headers(headers)
request_headers.pop("Content-Type", None)
request_timeout = timeout if timeout is not None else self.timeout
merged_query = {**(self.default_query or {}), **(query or {})} or None
response = await self._client.post(
url,
files=files,
data=data,
params=self._clean_query_params(merged_query),
headers=request_headers,
timeout=request_timeout,
)
if not response.is_success:
error_body = self._parse_error_body(response)
raise create_error_from_response(
response.status_code,
error_body.get("message") or f"HTTP {response.status_code}",
body=error_body,
)
text = response.text
if not text:
return None
return response.json()
def _build_url(self, path: str) -> str:
"""Build the full URL from path."""
if path.startswith("/"):
return f"{self.base_url}{path}"
return f"{self.base_url}/{path}"
def _build_headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
"""Build request headers including auth."""
headers = {**self.default_headers}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
if extra:
headers.update(extra)
return headers
def _clean_query_params(
self, params: dict[str, Any] | None
) -> dict[str, Any] | None:
"""Remove None values from query params."""
if params is None:
return None
return {k: v for k, v in params.items() if v is not None}
def _parse_error_body(self, response: httpx.Response) -> dict[str, Any]:
"""Parse error body from response."""
try:
body: Any = response.json()
if isinstance(body, dict):
body_dict: dict[str, Any] = cast(dict[str, Any], body)
return {
"message": body_dict.get("detail")
or body_dict.get("message")
or body_dict.get("error"),
**body_dict,
}
return {"message": str(body)}
except Exception:
return {"message": f"HTTP {response.status_code}"}
def _parse_retry_after(self, response: httpx.Response) -> float | None:
"""Parse Retry-After header."""
header = response.headers.get("Retry-After")
if not header:
return None
try:
# Try parsing as seconds
return float(header)
except ValueError:
pass
try:
# Try parsing as HTTP date
import time
from datetime import datetime
from email.utils import parsedate_to_datetime
dt: datetime = parsedate_to_datetime(header)
timestamp: float = dt.timestamp()
return max(0.0, timestamp - time.time())
except Exception:
return None
def _get_retry_delay(self, attempt: int, retry_after: float | None = None) -> float:
"""Calculate delay before next retry."""
if retry_after is not None:
return retry_after
# Exponential backoff: 0.5s, 1s, 2s, etc.
return INITIAL_RETRY_DELAY * (2**attempt)
+381
View File
@@ -0,0 +1,381 @@
"""Sync HTTP client for Honcho SDK."""
from __future__ import annotations
import time
from collections.abc import Iterator
from typing import Any, cast
import httpx
from .exceptions import (
ConnectionError,
RateLimitError,
ServerError,
TimeoutError,
create_error_from_response,
)
DEFAULT_TIMEOUT = 60.0 # 60 seconds
DEFAULT_MAX_RETRIES = 2
RETRY_STATUS_CODES = {429, 500, 502, 503, 504}
INITIAL_RETRY_DELAY = 0.5 # 500ms
class HonchoHTTPClient:
"""Sync HTTP client for the Honcho API with retry logic and timeout support."""
base_url: str
api_key: str | None
timeout: float
max_retries: int
default_headers: dict[str, str]
default_query: dict[str, Any] | None
_owns_client: bool
_client: httpx.Client
def __init__(
self,
*,
base_url: str,
api_key: str | None = None,
timeout: float = DEFAULT_TIMEOUT,
max_retries: int = DEFAULT_MAX_RETRIES,
default_headers: dict[str, str] | None = None,
default_query: dict[str, Any] | None = None,
http_client: httpx.Client | None = None,
) -> None:
# Remove trailing slash from base_url
self.base_url = base_url.rstrip("/")
self.api_key = api_key
self.timeout = timeout
self.max_retries = max_retries
self.default_headers = {
"Content-Type": "application/json",
**(default_headers or {}),
}
self.default_query = default_query
self._owns_client = http_client is None
self._client = http_client or httpx.Client( # nosec B113
base_url=self.base_url,
timeout=httpx.Timeout(timeout),
)
def close(self) -> None:
"""Close the HTTP client if we own it."""
if self._owns_client:
self._client.close()
def __enter__(self) -> "HonchoHTTPClient":
return self
def __exit__(self, *args: Any) -> None:
self.close()
def request(
self,
method: str,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make an HTTP request with automatic retries and timeout handling."""
url = self._build_url(path)
request_headers = self._build_headers(headers)
request_timeout = timeout if timeout is not None else self.timeout
merged_query = {**(self.default_query or {}), **(query or {})} or None
last_error: Exception | None = None
attempt = 0
while attempt <= self.max_retries:
try:
response = self._client.request(
method,
url,
json=body if body is not None else None,
params=self._clean_query_params(merged_query),
headers=request_headers,
timeout=request_timeout,
)
if response.is_success:
# Handle empty responses
text = response.text
if not text:
return None
return response.json()
# Handle error responses
error_body = self._parse_error_body(response)
retry_after = self._parse_retry_after(response)
error = create_error_from_response(
response.status_code,
error_body.get("message") or f"HTTP {response.status_code}",
body=error_body,
retry_after=retry_after,
)
# Only retry on specific status codes
if (
response.status_code in RETRY_STATUS_CODES
and attempt < self.max_retries
):
last_error = error
time.sleep(self._get_retry_delay(attempt, retry_after))
attempt += 1
continue
raise error
except (
httpx.TimeoutException,
httpx.NetworkError,
httpx.RemoteProtocolError,
) as e:
if isinstance(e, httpx.TimeoutException):
error = TimeoutError(f"Request timed out after {request_timeout}s")
else:
error = ConnectionError(f"Connection error: {e}")
if attempt < self.max_retries:
last_error = error
time.sleep(self._get_retry_delay(attempt))
attempt += 1
continue
raise error from e
except (TimeoutError, ConnectionError, RateLimitError, ServerError):
raise
except Exception as e:
# Re-raise API errors
if hasattr(e, "status"):
raise
raise ConnectionError(str(e)) from e
# If we exhausted retries, raise the last error
if last_error:
raise last_error
raise ConnectionError("Request failed after retries")
def get(
self,
path: str,
*,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a GET request."""
return self.request("GET", path, query=query, headers=headers, timeout=timeout)
def post(
self,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a POST request."""
return self.request(
"POST", path, body=body, query=query, headers=headers, timeout=timeout
)
def put(
self,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a PUT request."""
return self.request(
"PUT", path, body=body, query=query, headers=headers, timeout=timeout
)
def patch(
self,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a PATCH request."""
return self.request(
"PATCH", path, body=body, query=query, headers=headers, timeout=timeout
)
def delete(
self,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a DELETE request."""
return self.request(
"DELETE", path, body=body, query=query, headers=headers, timeout=timeout
)
def stream(
self,
method: str,
path: str,
*,
body: Any = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Iterator[bytes]:
"""Make a streaming request that yields raw bytes for SSE parsing."""
url = self._build_url(path)
request_headers = {
**self._build_headers(headers),
"Accept": "text/event-stream",
}
request_timeout = timeout if timeout is not None else self.timeout
merged_query = {**(self.default_query or {}), **(query or {})} or None
with self._client.stream(
method,
url,
json=body if body is not None else None,
params=self._clean_query_params(merged_query),
headers=request_headers,
timeout=request_timeout,
) as response:
if not response.is_success:
# Read error body
response.read()
error_body = self._parse_error_body(response)
raise create_error_from_response(
response.status_code,
error_body.get("message") or f"HTTP {response.status_code}",
body=error_body,
)
for chunk in response.iter_bytes():
yield chunk
def upload(
self,
path: str,
*,
files: dict[str, Any],
data: dict[str, Any] | None = None,
query: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
timeout: float | None = None,
) -> Any:
"""Make a multipart form data request (for file uploads)."""
url = self._build_url(path)
# Don't set Content-Type for multipart - httpx will set it with boundary
request_headers = self._build_headers(headers)
request_headers.pop("Content-Type", None)
request_timeout = timeout if timeout is not None else self.timeout
merged_query = {**(self.default_query or {}), **(query or {})} or None
response = self._client.post(
url,
files=files,
data=data,
params=self._clean_query_params(merged_query),
headers=request_headers,
timeout=request_timeout,
)
if not response.is_success:
error_body = self._parse_error_body(response)
raise create_error_from_response(
response.status_code,
error_body.get("message") or f"HTTP {response.status_code}",
body=error_body,
)
text = response.text
if not text:
return None
return response.json()
def _build_url(self, path: str) -> str:
"""Build the full URL from path."""
if path.startswith("/"):
return f"{self.base_url}{path}"
return f"{self.base_url}/{path}"
def _build_headers(self, extra: dict[str, str] | None = None) -> dict[str, str]:
"""Build request headers including auth."""
headers = {**self.default_headers}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
if extra:
headers.update(extra)
return headers
def _clean_query_params(
self, params: dict[str, Any] | None
) -> dict[str, Any] | None:
"""Remove None values from query params."""
if params is None:
return None
return {k: v for k, v in params.items() if v is not None}
def _parse_error_body(self, response: httpx.Response) -> dict[str, Any]:
"""Parse error body from response."""
try:
body: Any = response.json()
if isinstance(body, dict):
body_dict: dict[str, Any] = cast(dict[str, Any], body)
return {
"message": body_dict.get("detail")
or body_dict.get("message")
or body_dict.get("error"),
**body_dict,
}
return {"message": str(body)}
except Exception:
return {"message": f"HTTP {response.status_code}"}
def _parse_retry_after(self, response: httpx.Response) -> float | None:
"""Parse Retry-After header."""
header = response.headers.get("Retry-After")
if not header:
return None
try:
# Try parsing as seconds
return float(header)
except ValueError:
pass
try:
# Try parsing as HTTP date
from datetime import datetime
from email.utils import parsedate_to_datetime
dt: datetime = parsedate_to_datetime(header)
timestamp: float = dt.timestamp()
return max(0.0, timestamp - time.time())
except Exception:
return None
def _get_retry_delay(self, attempt: int, retry_after: float | None = None) -> float:
"""Calculate delay before next retry."""
if retry_after is not None:
return retry_after
# Exponential backoff: 0.5s, 1s, 2s, etc.
return INITIAL_RETRY_DELAY * (2**attempt)
+158
View File
@@ -0,0 +1,158 @@
"""Exception classes for Honcho SDK errors."""
from __future__ import annotations
from typing import Any
class HonchoError(Exception):
"""Base error class for all Honcho SDK errors."""
message: str
status: int
code: str | None
body: Any
def __init__(
self,
message: str,
*,
status: int = 0,
code: str | None = None,
body: Any = None,
) -> None:
super().__init__(message)
self.message = message
self.status = status
self.code = code
self.body = body
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}(message={self.message!r}, status={self.status})"
)
class APIError(HonchoError):
"""Error from an API response with HTTP status code."""
def __init__(
self,
message: str,
*,
status: int,
body: Any = None,
) -> None:
super().__init__(message, status=status, code="api_error", body=body)
class BadRequestError(APIError):
"""Error thrown when request validation fails (400)."""
def __init__(self, message: str = "Bad request", body: Any = None) -> None:
super().__init__(message, status=400, body=body)
self.code = "bad_request" # pyright: ignore[reportUnannotatedClassAttribute]
class AuthenticationError(APIError):
"""Error thrown when authentication fails (401)."""
def __init__(self, message: str = "Authentication failed") -> None:
super().__init__(message, status=401)
self.code = "authentication_error" # pyright: ignore[reportUnannotatedClassAttribute]
class PermissionDeniedError(APIError):
"""Error thrown when the user lacks permission (403)."""
def __init__(self, message: str = "Permission denied") -> None:
super().__init__(message, status=403)
self.code = "permission_denied" # pyright: ignore[reportUnannotatedClassAttribute]
class NotFoundError(APIError):
"""Error thrown when a resource is not found (404)."""
def __init__(self, message: str = "Resource not found") -> None:
super().__init__(message, status=404)
self.code = "not_found" # pyright: ignore[reportUnannotatedClassAttribute]
class ConflictError(APIError):
"""Error thrown on resource conflict (409)."""
def __init__(self, message: str = "Resource conflict", body: Any = None) -> None:
super().__init__(message, status=409, body=body)
self.code = "conflict" # pyright: ignore[reportUnannotatedClassAttribute]
class UnprocessableEntityError(APIError):
"""Error thrown when entity cannot be processed (422)."""
def __init__(self, message: str = "Unprocessable entity", body: Any = None) -> None:
super().__init__(message, status=422, body=body)
self.code = "unprocessable_entity" # pyright: ignore[reportUnannotatedClassAttribute]
class RateLimitError(APIError):
"""Error thrown when rate limited (429)."""
retry_after: float | None = None
def __init__(
self,
message: str = "Rate limit exceeded",
retry_after: float | None = None,
) -> None:
super().__init__(message, status=429)
self.code = "rate_limit_exceeded" # pyright: ignore[reportUnannotatedClassAttribute]
self.retry_after = retry_after
class ServerError(APIError):
"""Error thrown on server errors (5xx)."""
def __init__(self, message: str = "Server error", status: int = 500) -> None:
super().__init__(message, status=status)
self.code = "server_error" # pyright: ignore[reportUnannotatedClassAttribute]
class TimeoutError(HonchoError):
"""Error thrown when a request times out."""
def __init__(self, message: str = "Request timed out") -> None:
super().__init__(message, code="timeout")
class ConnectionError(HonchoError):
"""Error thrown when a connection fails."""
def __init__(self, message: str = "Connection failed") -> None:
super().__init__(message, code="connection_error")
def create_error_from_response(
status: int,
message: str,
body: Any = None,
retry_after: float | None = None,
) -> HonchoError:
"""Create the appropriate error type based on HTTP status code."""
if status == 400:
return BadRequestError(message, body=body)
elif status == 401:
return AuthenticationError(message)
elif status == 403:
return PermissionDeniedError(message)
elif status == 404:
return NotFoundError(message)
elif status == 409:
return ConflictError(message, body=body)
elif status == 422:
return UnprocessableEntityError(message, body=body)
elif status == 429:
return RateLimitError(message, retry_after=retry_after)
elif status >= 500:
return ServerError(message, status=status)
else:
return APIError(message, status=status, body=body)
+138
View File
@@ -0,0 +1,138 @@
"""API route constants for Honcho SDK."""
API_VERSION = "v3"
# Workspace routes
def workspaces() -> str:
return f"/{API_VERSION}/workspaces"
def workspaces_list() -> str:
return f"/{API_VERSION}/workspaces/list"
def workspace(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}"
def workspace_search(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/search"
def workspace_queue_status(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/queue/status"
def workspace_schedule_dream(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/schedule_dream"
# Peer routes
def peers(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers"
def peers_list(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers/list"
def peer(workspace_id: str, peer_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers/{peer_id}"
def peer_chat(workspace_id: str, peer_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers/{peer_id}/chat"
def peer_representation(workspace_id: str, peer_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers/{peer_id}/representation"
def peer_card(workspace_id: str, peer_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers/{peer_id}/card"
def peer_context(workspace_id: str, peer_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers/{peer_id}/context"
def peer_search(workspace_id: str, peer_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers/{peer_id}/search"
def peer_sessions_list(workspace_id: str, peer_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/peers/{peer_id}/sessions"
# Session routes
def sessions(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions"
def sessions_list(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/list"
def session(workspace_id: str, session_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}"
def session_clone(workspace_id: str, session_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/clone"
def session_context(workspace_id: str, session_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/context"
def session_summaries(workspace_id: str, session_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/summaries"
def session_search(workspace_id: str, session_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/search"
def session_peers(workspace_id: str, session_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/peers"
def session_peer_config(workspace_id: str, session_id: str, peer_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/peers/{peer_id}/config"
# Message routes
def messages(workspace_id: str, session_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/messages"
def messages_list(workspace_id: str, session_id: str) -> str:
return (
f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/messages/list"
)
def message(workspace_id: str, session_id: str, message_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/messages/{message_id}"
def messages_upload(workspace_id: str, session_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/sessions/{session_id}/messages/upload"
# Conclusion routes
def conclusions(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/conclusions"
def conclusions_list(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/conclusions/list"
def conclusions_query(workspace_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/conclusions/query"
def conclusion(workspace_id: str, conclusion_id: str) -> str:
return f"/{API_VERSION}/workspaces/{workspace_id}/conclusions/{conclusion_id}"
+81
View File
@@ -0,0 +1,81 @@
"""Message class for Honcho SDK."""
from __future__ import annotations
import datetime
from typing import Any
from .api_types import MessageResponse
class Message:
"""
A message in a Honcho session.
Messages represent communication between peers within a session.
This class wraps the API response with convenient attribute access.
Attributes:
id: Unique identifier for this message
content: The message content
peer_id: The peer ID who authored this message
session_id: The session ID this message belongs to
workspace_id: The workspace ID this message belongs to
metadata: Metadata associated with this message
created_at: Timestamp for when the message was created
token_count: Number of tokens in this message
"""
id: str
content: str
peer_id: str
session_id: str
workspace_id: str
metadata: dict[str, Any]
created_at: datetime.datetime
token_count: int
def __init__(
self,
id: str,
content: str,
peer_id: str,
session_id: str,
workspace_id: str,
metadata: dict[str, Any],
created_at: datetime.datetime,
token_count: int,
) -> None:
self.id = id
self.content = content
self.peer_id = peer_id
self.session_id = session_id
self.workspace_id = workspace_id
self.metadata = metadata
self.created_at = created_at
self.token_count = token_count
@classmethod
def from_api_response(cls, data: MessageResponse) -> "Message":
"""Create a Message from an API response."""
return cls(
id=data.id,
content=data.content,
peer_id=data.peer_id,
session_id=data.session_id,
workspace_id=data.workspace_id,
metadata=data.metadata,
created_at=data.created_at,
token_count=data.token_count,
)
def __repr__(self) -> str:
truncated = (
f"{self.content[:50]}..." if len(self.content) > 50 else self.content
)
return (
f"Message(id='{self.id}', peer_id='{self.peer_id}', content='{truncated}')"
)
def __str__(self) -> str:
return self.content
+248
View File
@@ -0,0 +1,248 @@
"""Mixins for common SDK functionality."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any
from pydantic import Field, validate_call
class MetadataConfigMixin(ABC):
"""
Mixin providing get/set/refresh methods for metadata and configuration.
Classes using this mixin must implement:
- _get_http_client() -> HTTPClientProtocol
- _get_fetch_route() -> str
- _get_update_route() -> str
- _get_fetch_body() -> dict[str, Any]
- _parse_response(data: dict[str, Any]) -> tuple[dict, dict]
And must have these attributes:
- _metadata: dict[str, object] | None
- _configuration: dict[str, object] | None
"""
_metadata: dict[str, object] | None
_configuration: dict[str, object] | None
@abstractmethod
def _get_http_client(self) -> Any:
"""Get the HTTP client for making requests."""
...
@abstractmethod
def _get_fetch_route(self) -> str:
"""Get the route for fetching metadata/configuration."""
...
@abstractmethod
def _get_update_route(self) -> str:
"""Get the route for updating metadata/configuration."""
...
@abstractmethod
def _get_fetch_body(self) -> dict[str, Any]:
"""Get the body for fetching metadata/configuration."""
...
@abstractmethod
def _parse_response(
self, data: dict[str, Any]
) -> tuple[dict[str, object], dict[str, object]]:
"""Parse the response to extract metadata and configuration."""
...
def get_metadata(self) -> dict[str, object]:
"""
Get metadata from the server and update the cache.
Returns:
A dictionary containing the metadata. Returns an empty dictionary
if no metadata is set.
"""
data = self._get_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
metadata, configuration = self._parse_response(data)
self._metadata = metadata
self._configuration = configuration
return self._metadata
@validate_call
def set_metadata(
self,
metadata: dict[str, object] = Field(
..., description="Metadata dictionary to set"
),
) -> None:
"""
Set metadata on the server and update the cache.
Args:
metadata: A dictionary of metadata to set.
Keys must be strings, values can be any JSON-serializable type.
"""
self._get_http_client().put(
self._get_update_route(),
body={"metadata": metadata},
)
self._metadata = metadata
def get_configuration(self) -> dict[str, object]:
"""
Get configuration from the server and update the cache.
Returns:
A dictionary containing the configuration. Returns an empty dictionary
if no configuration is set.
"""
data = self._get_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
metadata, configuration = self._parse_response(data)
self._metadata = metadata
self._configuration = configuration
return self._configuration
@validate_call
def set_configuration(
self,
configuration: dict[str, object] = Field(
..., description="Configuration dictionary to set"
),
) -> None:
"""
Set configuration on the server and update the cache.
Args:
configuration: A dictionary of configuration to set.
Keys must be strings, values can be any JSON-serializable type.
"""
self._get_http_client().put(
self._get_update_route(),
body={"configuration": configuration},
)
self._configuration = configuration
def refresh(self) -> None:
"""
Refresh cached metadata and configuration from the server.
Makes a single API call to retrieve the latest metadata and configuration
and updates the cached attributes.
"""
data = self._get_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
metadata, configuration = self._parse_response(data)
self._metadata = metadata
self._configuration = configuration
class AsyncMetadataConfigMixin(ABC):
"""
Async mixin providing get/set/refresh methods for metadata and configuration.
Classes using this mixin must implement:
- _get_async_http_client() -> AsyncHTTPClientProtocol
- _get_fetch_route() -> str
- _get_update_route() -> str
- _get_fetch_body() -> dict[str, Any]
- _parse_response(data: dict[str, Any]) -> tuple[dict, dict]
- _set_metadata(metadata: dict[str, object]) -> None
- _set_configuration(configuration: dict[str, object]) -> None
"""
@abstractmethod
def _get_async_http_client(self) -> Any:
"""Get the async HTTP client for making requests."""
...
@abstractmethod
def _get_fetch_route(self) -> str:
"""Get the route for fetching metadata/configuration."""
...
@abstractmethod
def _get_update_route(self) -> str:
"""Get the route for updating metadata/configuration."""
...
@abstractmethod
def _get_fetch_body(self) -> dict[str, Any]:
"""Get the body for fetching metadata/configuration."""
...
@abstractmethod
def _parse_response(
self, data: dict[str, Any]
) -> tuple[dict[str, object], dict[str, object]]:
"""Parse the response to extract metadata and configuration."""
...
@abstractmethod
def _set_metadata(self, metadata: dict[str, object]) -> None:
"""Set metadata on the parent object."""
...
@abstractmethod
def _set_configuration(self, configuration: dict[str, object]) -> None:
"""Set configuration on the parent object."""
...
@abstractmethod
def _get_metadata(self) -> dict[str, object]:
"""Get cached metadata from the parent object."""
...
@abstractmethod
def _get_configuration(self) -> dict[str, object]:
"""Get cached configuration from the parent object."""
...
async def get_metadata(self) -> dict[str, object]:
"""Get metadata from the server asynchronously."""
data = await self._get_async_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
metadata, configuration = self._parse_response(data)
self._set_metadata(metadata)
self._set_configuration(configuration)
return self._get_metadata()
async def set_metadata(self, metadata: dict[str, object]) -> None:
"""Set metadata on the server asynchronously."""
await self._get_async_http_client().put(
self._get_update_route(),
body={"metadata": metadata},
)
self._set_metadata(metadata)
async def get_configuration(self) -> dict[str, object]:
"""Get configuration from the server asynchronously."""
data = await self._get_async_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
metadata, configuration = self._parse_response(data)
self._set_metadata(metadata)
self._set_configuration(configuration)
return self._get_configuration()
async def set_configuration(self, configuration: dict[str, object]) -> None:
"""Set configuration on the server asynchronously."""
await self._get_async_http_client().put(
self._get_update_route(),
body={"configuration": configuration},
)
self._set_configuration(configuration)
async def refresh(self) -> None:
"""Refresh cached metadata and configuration asynchronously."""
data = await self._get_async_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
metadata, configuration = self._parse_response(data)
self._set_metadata(metadata)
self._set_configuration(configuration)
+250
View File
@@ -0,0 +1,250 @@
"""Pagination wrapper for Honcho SDK."""
from __future__ import annotations
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from typing import Any, Generic
from pydantic import BaseModel
from typing_extensions import TypeVar
T = TypeVar("T", bound=BaseModel)
U = TypeVar("U", default=T)
__all__ = ["SyncPage", "AsyncPage"]
class SyncPage(Generic[T, U]):
"""
Paginated result wrapper that transforms objects from type T to type U.
Provides iteration and transformation capabilities for paginated API responses.
"""
def __init__(
self,
data: dict[str, Any],
item_type: type[T],
transform_func: Callable[[T], U] | None = None,
fetch_next: Callable[[int], "SyncPage[T, U]"] | None = None,
) -> None:
"""
Initialize the page.
Args:
data: Raw paginated response data with items, page, size, total, pages
item_type: Type to parse items as
transform_func: Optional function to transform objects from type T to type U.
If None, objects are passed through unchanged.
fetch_next: Optional callback to fetch the next page. Takes page number.
"""
self._data: dict[str, Any] = data
self._item_type: type[T] = item_type
self._transform_func: Callable[[T], U] | None = transform_func
self._fetch_next: Callable[[int], "SyncPage[T, U]"] | None = fetch_next
# Parse items
raw_items = data.get("items", [])
self._raw_items: list[T] = [
item_type.model_validate(item) for item in raw_items
]
def __iter__(self) -> Iterator[U] | Iterator[T]:
"""
Iterate over all transformed items across all pages.
Warning:
This iterator automatically fetches ALL subsequent pages as you iterate.
For large datasets, this may result in many API calls. If you only need
the current page, use the `items` property instead.
"""
page: SyncPage[T, U] | None = self
while page is not None:
for item in page._raw_items:
if self._transform_func is not None:
yield self._transform_func(item)
else:
yield item
page = page.get_next_page()
def __getitem__(self, index: int) -> U | T:
"""Get a transformed item by index on the current page."""
item = self._raw_items[index]
if self._transform_func is not None:
return self._transform_func(item)
return item
def __len__(self) -> int:
"""Get the number of items on the current page."""
return len(self._raw_items)
@property
def items(self) -> list[U] | list[T]:
"""Get all transformed items on the current page."""
if self._transform_func is not None:
return [self._transform_func(item) for item in self._raw_items]
return list(self._raw_items)
@property
def total(self) -> int | None:
"""Get the total number of items across all pages."""
return self._data.get("total")
@property
def page(self) -> int | None:
"""Get the current page number."""
return self._data.get("page")
@property
def size(self) -> int | None:
"""Get the page size."""
return self._data.get("size")
@property
def pages(self) -> int | None:
"""Get the total number of pages."""
return self._data.get("pages")
def has_next_page(self) -> bool:
"""Check if there's a next page."""
current_page = self.page
total_pages = self.pages
if current_page is None or total_pages is None:
return False
return current_page < total_pages
def get_next_page(self) -> "SyncPage[T, U] | None":
"""
Fetch the next page of results.
Returns None if there are no more pages or no fetch callback.
"""
if not self.has_next_page():
return None
if self._fetch_next is None:
return None
current_page = self.page
if current_page is None:
return None
return self._fetch_next(current_page + 1)
class AsyncPage(Generic[T, U]):
"""
Async paginated result wrapper that transforms objects from type T to type U.
Provides async iteration and transformation capabilities for paginated API responses.
"""
def __init__(
self,
data: dict[str, Any],
item_type: type[T],
transform_func: Callable[[T], U] | None = None,
fetch_next: Callable[[int], Awaitable["AsyncPage[T, U]"]] | None = None,
) -> None:
"""
Initialize the async page.
Args:
data: Raw paginated response data with items, page, size, total, pages
item_type: Type to parse items as
transform_func: Optional function to transform objects from type T to type U.
If None, objects are passed through unchanged.
fetch_next: Optional async callback to fetch the next page. Takes page number.
"""
self._data: dict[str, Any] = data
self._item_type: type[T] = item_type
self._transform_func: Callable[[T], U] | None = transform_func
self._fetch_next: Callable[[int], Awaitable["AsyncPage[T, U]"]] | None = (
fetch_next
)
# Parse items
raw_items = data.get("items", [])
self._raw_items: list[T] = [
item_type.model_validate(item) for item in raw_items
]
async def __aiter__(self) -> AsyncIterator[U] | AsyncIterator[T]:
"""
Async iterate over all transformed items across all pages.
Warning:
This iterator automatically fetches ALL subsequent pages as you iterate.
For large datasets, this may result in many API calls. If you only need
the current page, use the `items` property instead.
"""
page: AsyncPage[T, U] | None = self
while page is not None:
for item in page._raw_items:
if self._transform_func is not None:
yield self._transform_func(item)
else:
yield item
page = await page.get_next_page()
def __getitem__(self, index: int) -> U | T:
"""Get a transformed item by index on the current page."""
item = self._raw_items[index]
if self._transform_func is not None:
return self._transform_func(item)
return item
def __len__(self) -> int:
"""Get the number of items on the current page."""
return len(self._raw_items)
@property
def items(self) -> list[U] | list[T]:
"""Get all transformed items on the current page."""
if self._transform_func is not None:
return [self._transform_func(item) for item in self._raw_items]
return list(self._raw_items)
@property
def total(self) -> int | None:
"""Get the total number of items across all pages."""
return self._data.get("total")
@property
def page(self) -> int | None:
"""Get the current page number."""
return self._data.get("page")
@property
def size(self) -> int | None:
"""Get the page size."""
return self._data.get("size")
@property
def pages(self) -> int | None:
"""Get the total number of pages."""
return self._data.get("pages")
def has_next_page(self) -> bool:
"""Check if there's a next page."""
current_page = self.page
total_pages = self.pages
if current_page is None or total_pages is None:
return False
return current_page < total_pages
async def get_next_page(self) -> "AsyncPage[T, U] | None":
"""
Fetch the next page of results.
Returns None if there are no more pages or no fetch callback.
"""
if not self.has_next_page():
return None
if self._fetch_next is None:
return None
current_page = self.page
if current_page is None:
return None
return await self._fetch_next(current_page + 1)
+780
View File
@@ -0,0 +1,780 @@
# pyright: reportPrivateUsage=false
"""Sync Peer class for Honcho SDK."""
from __future__ import annotations
import datetime
import logging
import warnings
from collections.abc import Generator
from typing import TYPE_CHECKING, Any, Literal
from pydantic import ConfigDict, Field, PrivateAttr, validate_call
from .api_types import (
MessageCreateParams,
MessageResponse,
PeerCardResponse,
PeerConfig,
PeerContextResponse,
PeerResponse,
RepresentationResponse,
SessionConfiguration,
SessionResponse,
)
from .base import PeerBase, SessionBase
from .conclusions import ConclusionScope
from .http import routes
from .message import Message
from .mixins import MetadataConfigMixin
from .pagination import SyncPage
from .types import DialecticStreamResponse
from .utils import parse_datetime, parse_sse_stream, resolve_id
if TYPE_CHECKING:
from .aio import PeerAio
from .client import Honcho
from .session import Session
logger = logging.getLogger(__name__)
class Peer(PeerBase, MetadataConfigMixin):
"""
Represents a peer in the Honcho system.
Peers can send messages, participate in sessions, and maintain both global
and local representations for contextual interactions. A peer represents
an entity (user, assistant, etc.) that can communicate within the system.
Attributes:
id: Unique identifier for this peer
workspace_id: Workspace ID for scoping operations
metadata: Cached metadata for this peer. May be stale if not recently
fetched. Call get_metadata() for fresh data.
configuration: Cached configuration for this peer. May be stale if not
recently fetched. Call get_configuration() for fresh data.
"""
_metadata: dict[str, object] | None = PrivateAttr(default=None)
_configuration: PeerConfig | None = PrivateAttr(default=None)
_created_at: datetime.datetime | None = PrivateAttr(default=None)
_honcho: "Honcho" = PrivateAttr()
@property
def metadata(self) -> dict[str, object] | None:
"""Cached metadata for this peer. May be stale. Use get_metadata() for fresh data."""
return self._metadata
@property
def configuration(self) -> PeerConfig | None:
"""Cached configuration for this peer. May be stale. Use get_configuration() for fresh data."""
return self._configuration
@property
def created_at(self) -> datetime.datetime | None:
"""Timestamp when this peer was created. Only available if fetched from the API."""
return self._created_at
# MetadataConfigMixin implementation
def _get_http_client(self):
self._honcho._ensure_workspace()
return self._honcho._http
def _get_fetch_route(self) -> str:
return routes.peers(self.workspace_id)
def _get_update_route(self) -> str:
return routes.peer(self.workspace_id, self.id)
def _get_fetch_body(self) -> dict[str, Any]:
return {"id": self.id}
def _parse_response(
self, data: dict[str, Any]
) -> tuple[dict[str, object], dict[str, object]]:
peer = PeerResponse.model_validate(data)
# Return configuration as dict for mixin compatibility
return peer.metadata or {}, peer.configuration.model_dump(exclude_none=True)
def _apply_peer_response(self, peer: PeerResponse) -> None:
self._metadata = peer.metadata or {}
self._configuration = peer.configuration
self._created_at = peer.created_at
def get_metadata(self) -> dict[str, object]:
"""Get metadata from the server and update the cache."""
self._honcho._ensure_workspace()
data = self._get_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
peer = PeerResponse.model_validate(data)
self._apply_peer_response(peer)
return self._metadata or {}
def get_configuration(self) -> PeerConfig: # pyright: ignore[reportIncompatibleMethodOverride]
"""
Get configuration from the server and update the cache.
Returns:
A PeerConfig object containing the configuration settings.
"""
self._honcho._ensure_workspace()
data = self._get_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
peer = PeerResponse.model_validate(data)
self._apply_peer_response(peer)
return self._configuration or PeerConfig()
def refresh(self) -> None:
"""Refresh cached metadata, configuration, and created_at from the server."""
self._honcho._ensure_workspace()
data = self._get_http_client().post(
self._get_fetch_route(), body=self._get_fetch_body()
)
peer = PeerResponse.model_validate(data)
self._apply_peer_response(peer)
@validate_call
def set_configuration( # pyright: ignore[reportIncompatibleMethodOverride]
self,
configuration: PeerConfig = Field(..., description="Configuration to set"),
) -> None:
"""
Set configuration on the server and update the cache.
Args:
configuration: A PeerConfig object with configuration settings.
"""
self._get_http_client().put(
self._get_update_route(),
body={"configuration": configuration.model_dump(exclude_none=True)},
)
self._configuration = configuration
@property
def aio(self) -> "PeerAio":
"""
Access async versions of all Peer methods.
Returns a PeerAio view that provides async versions of all methods
while sharing state with this Peer instance.
Example:
```python
peer = honcho.peer("user-123")
# Async operations
await peer.aio.chat("query")
await peer.aio.get_metadata()
```
"""
# Import here to avoid circular import (aio.py imports Peer)
from .aio import PeerAio
return PeerAio(self)
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def __init__(
self,
peer_id: str = Field(
...,
min_length=1,
description="Unique identifier for this peer within the workspace",
),
honcho: Any = Field(..., description="Honcho client instance"),
*,
metadata: dict[str, object] | None = Field(
None,
description="Optional metadata dictionary to associate with this peer. If set, will get/create peer immediately with metadata.",
),
configuration: PeerConfig | None = Field(
None,
description="Optional configuration to set for this peer. If set, will get/create peer immediately with flags.",
),
created_at: datetime.datetime | None = Field(
None,
description="Timestamp when this peer was created.",
),
) -> None:
"""
Initialize a new Peer.
Provided metadata and configuration will overwrite any existing data in those
locations if given.
Args:
peer_id: Unique identifier for this peer within the workspace
honcho: Honcho client instance
metadata: Optional metadata dictionary to associate with this peer.
If set, will get/create peer immediately with metadata.
configuration: Optional configuration to set for this peer.
If set, will get/create peer immediately with flags.
"""
super().__init__(
id=peer_id,
workspace_id=honcho.workspace_id,
)
self._honcho = honcho
self._metadata = metadata
self._configuration = configuration # pyright: ignore[reportIncompatibleVariableOverride]
self._created_at = created_at
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def chat(
self,
query: str = Field(..., min_length=1, description="The natural language query"),
*,
target: str | PeerBase | None = None,
session: str | SessionBase | None = None,
reasoning_level: Literal["minimal", "low", "medium", "high", "max"]
| None = None,
) -> str | None:
"""
Query the peer's representation with a natural language question.
Makes an API call to the Honcho dialectic endpoint to query either the peer's
global representation (all content associated with this peer) or their local
representation of another peer (what this peer knows about the target peer).
Args:
query: The natural language question to ask.
target: Optional target peer for local representation query. If provided,
queries what this peer knows about the target peer rather than
querying the peer's global representation. Can be a peer ID string
or a Peer object.
session: Optional session to scope the query to. If provided, only
information from that session is considered. Can be a session
ID string or a Session object.
reasoning_level: Optional reasoning level for the query: "minimal", "low", "medium",
"high", or "max". Defaults to "low" if not provided.
Returns:
Response string containing the answer, or None if no relevant information
"""
self._honcho._ensure_workspace()
target_id = resolve_id(target)
resolved_session_id = resolve_id(session)
body: dict[str, Any] = {"query": query, "stream": False}
if target_id:
body["target"] = target_id
if resolved_session_id:
body["session_id"] = resolved_session_id
if reasoning_level:
body["reasoning_level"] = reasoning_level
data = self._honcho._http.post(
routes.peer_chat(self.workspace_id, self.id),
body=body,
)
content = data.get("content")
if not content:
return None
return content
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def chat_stream(
self,
query: str = Field(..., min_length=1, description="The natural language query"),
*,
target: str | PeerBase | None = None,
session: str | SessionBase | None = None,
reasoning_level: Literal["minimal", "low", "medium", "high", "max"]
| None = None,
) -> DialecticStreamResponse:
"""
Query the peer's representation with a natural language question, streaming the response.
Makes an API call to the Honcho dialectic endpoint to query either the peer's
global representation (all content associated with this peer) or their local
representation of another peer (what this peer knows about the target peer).
Args:
query: The natural language question to ask.
target: Optional target peer for local representation query. If provided,
queries what this peer knows about the target peer rather than
querying the peer's global representation. Can be a peer ID string
or a Peer object.
session: Optional session to scope the query to. If provided, only
information from that session is considered. Can be a session
ID string or a Session object.
reasoning_level: Optional reasoning level for the query: "minimal", "low", "medium",
"high", or "max". Defaults to "low" if not provided.
Returns:
DialecticStreamResponse object that can be iterated over and provides final response
"""
self._honcho._ensure_workspace()
target_id = resolve_id(target)
resolved_session_id = resolve_id(session)
body: dict[str, Any] = {"query": query, "stream": True}
if target_id:
body["target"] = target_id
if resolved_session_id:
body["session_id"] = resolved_session_id
if reasoning_level:
body["reasoning_level"] = reasoning_level
def stream_response() -> Generator[str, None, None]:
yield from parse_sse_stream(
self._honcho._http.stream(
"POST",
routes.peer_chat(self.workspace_id, self.id),
body=body,
)
)
return DialecticStreamResponse(stream_response())
def sessions(
self,
filters: dict[str, object] | None = None,
*,
page: int = 1,
size: int = 50,
reverse: bool = False,
) -> SyncPage[SessionResponse, "Session"]:
"""
Get all sessions this peer is a member of.
Args:
filters: Optional filter criteria.
page: Page number (1-indexed). Default: 1.
size: Number of items per page. Default: 50.
reverse: If True, reverses the default ordering. Default: False.
Returns:
A paginated list of Session objects this peer belongs to.
"""
self._honcho._ensure_workspace()
# Import here to avoid circular import (session.py imports Peer)
from .session import Session
query: dict[str, Any] = {"page": page, "size": size}
if reverse:
query["reverse"] = "true"
data = self._honcho._http.post(
routes.peer_sessions_list(self.workspace_id, self.id),
body={"filters": filters} if filters else None,
query=query,
)
def transform(session: SessionResponse) -> Session:
return Session(
session.id,
self._honcho,
metadata=session.metadata,
configuration=SessionConfiguration.model_validate(
session.configuration.model_dump()
),
created_at=session.created_at,
is_active=session.is_active,
)
def fetch_next(next_page: int) -> SyncPage[SessionResponse, Session]:
next_query: dict[str, Any] = {"page": next_page, "size": size}
if reverse:
next_query["reverse"] = "true"
next_data = self._honcho._http.post(
routes.peer_sessions_list(self.workspace_id, self.id),
body={"filters": filters} if filters else None,
query=next_query,
)
return SyncPage(next_data, SessionResponse, transform, fetch_next)
return SyncPage(data, SessionResponse, transform, fetch_next)
@validate_call
def message(
self,
content: str = Field(
..., min_length=0, description="The text content for the message"
),
*,
metadata: dict[str, object] | None = Field(
None, description="Optional metadata dictionary"
),
configuration: dict[str, Any] | None = Field(
None,
description="Optional configuration dictionary to associate with the message",
),
created_at: datetime.datetime | str | None = Field(
None,
description="Optional created-at timestamp for the message. Accepts a datetime which will be converted to an ISO 8601 string, or a preformatted string.",
),
) -> MessageCreateParams:
"""
Build a message object attributed to this peer (synchronous, no API call).
This is a convenience method for creating message objects with this peer's ID
already set. The returned object can then be passed to `session.add_messages()`.
Note:
This method is synchronous and does NOT send the message to Honcho.
To actually create the message on the server, pass the returned object to
`session.add_messages()`.
Args:
content: The text content for the message
metadata: Optional metadata dictionary to associate with the message
configuration: Optional configuration dictionary (e.g., reasoning settings)
created_at: Optional created-at timestamp
Returns:
A MessageCreateParams object ready to be passed to `session.add_messages()`
Example:
```python
msg = peer.message("Hello!")
await session.add_messages(msg)
# Or batch multiple messages:
await session.add_messages([
alice.message("Hi Bob"),
bob.message("Hey Alice!"),
])
```
"""
from .api_types import MessageConfiguration
if content != "" and content.strip() == "":
raise ValueError("Message content cannot be only whitespace")
created_at_dt = parse_datetime(created_at)
config_obj = MessageConfiguration(**configuration) if configuration else None
return MessageCreateParams(
peer_id=self.id,
content=content,
configuration=config_obj,
metadata=metadata,
created_at=created_at_dt,
)
@validate_call
def search(
self,
query: str = Field(..., min_length=1, description="The search query to use"),
filters: dict[str, object] | None = Field(
None, description="Filters to scope the search"
),
limit: int = Field(
default=10, ge=1, le=100, description="Number of results to return"
),
) -> list[Message]:
"""
Search across all messages in the workspace with this peer as author.
Makes an API call to search endpoint.
Args:
query: The search query to use
filters: Filters to scope the search. See [search filters documentation](https://honcho.dev/docs/v3/documentation/core-concepts/features/using-filters).
limit: Number of results to return (1-100, default: 10)
Returns:
A list of Message objects representing the search results.
Returns an empty list if no messages are found.
"""
self._honcho._ensure_workspace()
data = self._honcho._http.post(
routes.peer_search(self.workspace_id, self.id),
body={"query": query, "filters": filters, "limit": limit},
)
return [
Message.from_api_response(MessageResponse.model_validate(item))
for item in data
]
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def get_card(
self,
target: str | PeerBase | None = None,
) -> list[str] | None:
"""
Get the peer card for this peer.
Makes an API call to retrieve the peer card, which contains a representation
of what this peer knows. If a target is provided, returns this peer's local
representation of the target peer.
Args:
target: Optional target peer for local card. If provided, returns this
peer's card of the target peer. Can be a Peer object or peer ID string.
Returns:
A list of strings representing the peer card, or None if none is available
"""
self._honcho._ensure_workspace()
target_id = resolve_id(target)
query = {"target": target_id} if target_id else None
data = self._honcho._http.get(
routes.peer_card(self.workspace_id, self.id),
query=query,
)
response = PeerCardResponse.model_validate(data)
return response.peer_card
def card(
self,
target: str | PeerBase | None = None,
) -> list[str] | None:
"""Deprecated: use get_card() instead."""
warnings.warn(
"card() is deprecated, use get_card() instead",
DeprecationWarning,
stacklevel=2,
)
return self.get_card(target=target)
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def set_card(
self,
peer_card: list[str],
target: str | PeerBase | None = None,
) -> list[str] | None:
"""
Set the peer card for this peer.
Makes an API call to set the peer card. If a target is provided, sets this
peer's local card of the target peer.
Args:
peer_card: A list of strings to set as the peer card.
target: Optional target peer for local card. If provided, sets this
peer's card of the target peer. Can be a Peer object or peer ID string.
Returns:
A list of strings representing the updated peer card, or None if none is available
"""
self._honcho._ensure_workspace()
target_id = resolve_id(target)
query = {"target": target_id} if target_id else None
data = self._honcho._http.put(
routes.peer_card(self.workspace_id, self.id),
body={"peer_card": peer_card},
query=query,
)
response = PeerCardResponse.model_validate(data)
return response.peer_card
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def representation(
self,
session: str | SessionBase | None = None,
target: str | PeerBase | None = None,
search_query: str | None = None,
search_top_k: int | None = Field(None, ge=1, le=100),
search_max_distance: float | None = Field(None, ge=0.0, le=1.0),
include_most_frequent: bool | None = None,
max_conclusions: int | None = Field(None, ge=1, le=100),
) -> str:
"""
Get a subset of the representation of the peer.
Args:
session: Optional session to scope the representation to.
target: Optional target peer to get the representation of. If provided,
returns the representation of the target from the perspective of this peer.
search_query: Semantic search query to filter relevant conclusions
search_top_k: Number of semantically relevant facts to return
search_max_distance: Maximum semantic distance for search results (0.0-1.0)
include_most_frequent: Whether to include the most frequent conclusions
max_conclusions: Maximum number of conclusions to include
Returns:
A Representation string
Example:
```python
# Get global representation
rep = peer.representation()
print(rep)
# Get representation scoped to a session
session_rep = peer.representation(session='session-123')
# Get representation with semantic search
searched_rep = peer.representation(
search_query='preferences',
search_top_k=10,
max_conclusions=50
)
```
"""
self._honcho._ensure_workspace()
session_id = resolve_id(session)
target_id = resolve_id(target)
body: dict[str, Any] = {}
if session_id:
body["session_id"] = session_id
if target_id:
body["target"] = target_id
if search_query is not None:
body["search_query"] = search_query
if search_top_k is not None:
body["search_top_k"] = search_top_k
if search_max_distance is not None:
body["search_max_distance"] = search_max_distance
if include_most_frequent is not None:
body["include_most_frequent"] = include_most_frequent
if max_conclusions is not None:
body["max_conclusions"] = max_conclusions
data = self._honcho._http.post(
routes.peer_representation(self.workspace_id, self.id),
body=body,
)
response = RepresentationResponse.model_validate(data)
return response.representation
@validate_call(config=ConfigDict(arbitrary_types_allowed=True))
def context(
self,
target: str | PeerBase | None = None,
search_query: str | None = None,
search_top_k: int | None = Field(None, ge=1, le=100),
search_max_distance: float | None = Field(None, ge=0.0, le=1.0),
include_most_frequent: bool | None = None,
max_conclusions: int | None = Field(None, ge=1, le=100),
) -> PeerContextResponse:
"""
Get context for this peer, including representation and peer card.
This is a convenience method that retrieves both the working representation
and peer card in a single API call.
Args:
target: Optional target peer to get context for. If provided, returns
the context for the target from this peer's perspective.
Can be a Peer object or peer ID string.
search_query: Semantic search query to filter relevant conclusions
search_top_k: Number of semantically relevant facts to return
search_max_distance: Maximum semantic distance for search results (0.0-1.0)
include_most_frequent: Whether to include the most frequent conclusions
max_conclusions: Maximum number of conclusions to include
Returns:
A PeerContext object containing the representation and peer card
Example:
```python
# Get own context
context = peer.context()
print(context.representation)
print(context.peer_card)
# Get context for another peer
context = peer.context(target='other-peer-id')
# Get context with semantic search
context = peer.context(
search_query='preferences',
search_top_k=10
)
```
"""
self._honcho._ensure_workspace()
target_id = resolve_id(target)
query: dict[str, Any] = {}
if target_id:
query["target"] = target_id
if search_query is not None:
query["search_query"] = search_query
if search_top_k is not None:
query["search_top_k"] = search_top_k
if search_max_distance is not None:
query["search_max_distance"] = search_max_distance
if include_most_frequent is not None:
query["include_most_frequent"] = include_most_frequent
if max_conclusions is not None:
query["max_conclusions"] = max_conclusions
data = self._honcho._http.get(
routes.peer_context(self.workspace_id, self.id),
query=query if query else None,
)
return PeerContextResponse.model_validate(data)
@property
def conclusions(self) -> ConclusionScope:
"""
Access this peer's self-conclusions (where observer == observed == self).
This property provides a convenient way to access conclusions that this peer
has made about themselves. Use this for self-conclusion scenarios.
Returns:
A ConclusionScope scoped to this peer's self-conclusions
Example:
```python
# List self-conclusions
obs_list = peer.conclusions.list()
# Search self-conclusions
results = peer.conclusions.query("preferences")
# Delete a self-conclusion
peer.conclusions.delete("obs-123")
```
"""
return ConclusionScope(self._honcho, self.workspace_id, self.id, self.id)
def conclusions_of(self, target: str | PeerBase) -> ConclusionScope:
"""
Access conclusions this peer has made about another peer.
This method provides scoped access to conclusions where this peer is the
observer and the target is the observed peer.
Args:
target: The target peer (either a Peer object or peer ID string)
Returns:
A ConclusionScope scoped to this peer's conclusions of the target
Example:
```python
# Get conclusions about another peer
bob_conclusions = peer.conclusions_of("bob")
# List conclusions
obs_list = bob_conclusions.list()
# Search conclusions
results = bob_conclusions.query("work history")
# Get the representation from these conclusions
rep = bob_conclusions.get_representation()
```
"""
target_id = target.id if isinstance(target, PeerBase) else target
return ConclusionScope(self._honcho, self.workspace_id, self.id, target_id)
def __repr__(self) -> str:
"""
Return a string representation of the Peer.
Returns:
A string representation suitable for debugging
"""
return f"Peer(id='{self.id}')"
def __str__(self) -> str:
"""
Return a human-readable string representation of the Peer.
Returns:
The peer's ID
"""
return self.id
File diff suppressed because it is too large Load Diff
+208
View File
@@ -0,0 +1,208 @@
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar
from pydantic import BaseModel, ConfigDict, Field
from .message import Message
if TYPE_CHECKING:
from .peer import Peer
class Summary(BaseModel):
"""Represents a summary of a session's conversation."""
content: str = Field(..., description="The summary text")
message_id: str = Field(
..., description="The ID of the message that this summary covers up to"
)
summary_type: str = Field(..., description="The type of summary (short or long)")
created_at: str = Field(
..., description="The timestamp of when the summary was created (ISO format)"
)
token_count: int = Field(
..., description="The number of tokens in the summary text"
)
class SessionSummaries(BaseModel):
"""Contains both short and long summaries for a session."""
id: str = Field(..., description="The session ID")
short_summary: Summary | None = Field(
None, description="The short summary if available"
)
long_summary: Summary | None = Field(
None, description="The long summary if available"
)
class SessionContext(BaseModel):
"""
Represents the context of a session containing a curated list of messages.
The SessionContext provides methods to convert message history into formats
compatible with different LLM providers while staying within token limits
and providing optimal conversation context.
Attributes:
messages: List of Message objects representing the conversation context
"""
model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True)
session_id: str = Field(
..., description="ID of the session this context belongs to"
)
messages: list[Message] = Field(
..., description="List of Message objects to include in the context"
)
summary: Summary | None = Field(
None, description="Summary of the session history prior to the message cutoff"
)
peer_representation: str | None = Field(
None,
description="The peer representation, if context is requested from a specific perspective",
)
peer_card: list[str] | None = Field(
None,
description="The peer card, if context is requested from a specific perspective",
)
def to_openai(
self,
*,
assistant: str | Peer,
) -> list[dict[str, str]]:
"""
Convert the context to OpenAI-compatible message format.
Transforms the message history and summary into the format expected by
OpenAI's Chat Completions API, with proper role assignments based on the
assistant's identity.
Args:
assistant: The assistant peer (Peer object or peer ID string) to use
for determining message roles. Messages from this peer will be marked
as "assistant", others as "user"
Returns:
A list of dictionaries in OpenAI format, where each dictionary contains
"role" and "content" keys suitable for the OpenAI API
"""
assistant_id = assistant if isinstance(assistant, str) else assistant.id
messages = [
{
"role": "assistant" if message.peer_id == assistant_id else "user",
"name": message.peer_id,
"content": message.content,
}
for message in self.messages
]
system_messages: list[dict[str, str]] = []
if self.peer_representation:
peer_representation_message = {
"role": "system",
"content": f"<peer_representation>{self.peer_representation}</peer_representation>",
}
system_messages.append(peer_representation_message)
if self.peer_card:
peer_card_message = {
"role": "system",
"content": f"<peer_card>{self.peer_card}</peer_card>",
}
system_messages.append(peer_card_message)
if self.summary:
summary_message = {
"role": "system",
"content": f"<summary>{self.summary.content}</summary>",
}
system_messages.append(summary_message)
return system_messages + messages
def to_anthropic(
self,
*,
assistant: str | Peer,
) -> list[dict[str, str]]:
"""
Convert the context to Anthropic-compatible message format.
Transforms the message history into the format expected by Anthropic's
Claude API, with proper role assignments based on the assistant's identity.
Args:
assistant: The assistant peer (Peer object or peer ID string) to use
for determining message roles. Messages from this peer will
be marked as "assistant", others as "user"
Returns:
A list of dictionaries in Anthropic format, where each dictionary contains
"role" and "content" keys suitable for the Anthropic API
Note:
Future versions may implement role alternation requirements for
Anthropic's API compatibility
"""
assistant_id = assistant if isinstance(assistant, str) else assistant.id
messages = [
{
"role": "assistant",
"content": message.content,
}
if message.peer_id == assistant_id
else {
"role": "user",
"content": f"{message.peer_id}: {message.content}",
}
for message in self.messages
]
system_messages: list[dict[str, str]] = []
if self.peer_representation:
peer_representation_message = {
"role": "user",
"content": f"<peer_representation>{self.peer_representation}</peer_representation>",
}
system_messages.append(peer_representation_message)
if self.peer_card:
peer_card_message = {
"role": "user",
"content": f"<peer_card>{self.peer_card}</peer_card>",
}
system_messages.append(peer_card_message)
if self.summary:
summary_message = {
"role": "user",
"content": f"<summary>{self.summary.content}</summary>",
}
system_messages.append(summary_message)
return system_messages + messages
def __len__(self) -> int:
"""
Return the number of messages in the context.
Returns:
The number of messages in this context
"""
return len(self.messages) + (1 if self.summary else 0)
def __repr__(self) -> str:
"""
Return a string representation of the SessionContext.
Returns:
A string representation suitable for debugging
"""
return f"SessionContext(messages={len(self.messages)}, summary={'present' if self.summary else 'None'})"
+133
View File
@@ -0,0 +1,133 @@
"""Shared types for the Honcho SDK."""
from __future__ import annotations
from collections.abc import AsyncIterator, Iterator
from typing import Self
__all__ = [
"DialecticStreamResponse",
"AsyncDialecticStreamResponse",
]
class DialecticStreamResponse:
"""
Sync streaming response for dialectic queries.
Allows iterating over chunks as they arrive and accessing the final
accumulated response after streaming completes.
Example:
```python
stream = peer.chat_stream("Hello")
# Stream chunks
for chunk in stream:
print(chunk, end="", flush=True)
# Get final response object
final = stream.get_final_response()
print(f"\\nFull content: {final['content']}")
```
"""
_iterator: Iterator[str]
_accumulated_content: list[str]
_is_complete: bool
def __init__(self, iterator: Iterator[str]) -> None:
self._iterator = iterator
self._accumulated_content = []
self._is_complete = False
def __iter__(self) -> Self:
return self
def __next__(self) -> str:
try:
chunk = next(self._iterator)
self._accumulated_content.append(chunk)
return chunk
except StopIteration:
self._is_complete = True
raise
def get_final_response(self) -> dict[str, str]:
"""
Get the final accumulated response after streaming completes.
Returns:
A dictionary with the full content: {"content": "full accumulated text"}
Note:
This should be called after the stream has been fully consumed.
If called before completion, it returns the content accumulated so far.
"""
return {"content": "".join(self._accumulated_content)}
@property
def is_complete(self) -> bool:
"""Check if the stream has finished."""
return self._is_complete
class AsyncDialecticStreamResponse:
"""
Async streaming response for dialectic queries.
Allows iterating over chunks as they arrive and accessing the final
accumulated response after streaming completes.
Example:
```python
stream = await peer.aio.chat_stream("Hello")
# Stream chunks
async for chunk in stream:
print(chunk, end="", flush=True)
# Get final response object
final = stream.get_final_response()
print(f"\\nFull content: {final['content']}")
```
"""
_iterator: AsyncIterator[str]
_accumulated_content: list[str]
_is_complete: bool
def __init__(self, iterator: AsyncIterator[str]) -> None:
self._iterator = iterator
self._accumulated_content = []
self._is_complete = False
def __aiter__(self) -> Self:
return self
async def __anext__(self) -> str:
try:
chunk = await self._iterator.__anext__()
self._accumulated_content.append(chunk)
return chunk
except StopAsyncIteration:
self._is_complete = True
raise
def get_final_response(self) -> dict[str, str]:
"""
Get the final accumulated response after streaming completes.
Returns:
A dictionary with the full content: {"content": "full accumulated text"}
Note:
This should be called after the stream has been fully consumed.
If called before completion, it returns the content accumulated so far.
"""
return {"content": "".join(self._accumulated_content)}
@property
def is_complete(self) -> bool:
"""Check if the stream has finished."""
return self._is_complete
+22
View File
@@ -0,0 +1,22 @@
"""
Utility modules for the Honcho Python SDK.
"""
from .datetime import datetime_to_iso, parse_datetime
from .file_upload import normalize_file_input, prepare_file_for_upload
from .peers import normalize_peers_to_dict
from .resolve import resolve_id
from .sse import SSEStreamParser, parse_sse_astream, parse_sse_chunk, parse_sse_stream
__all__ = [
"datetime_to_iso",
"parse_datetime",
"normalize_file_input",
"normalize_peers_to_dict",
"SSEStreamParser",
"parse_sse_astream",
"parse_sse_chunk",
"parse_sse_stream",
"prepare_file_for_upload",
"resolve_id",
]
+49
View File
@@ -0,0 +1,49 @@
"""DateTime utilities for the Honcho Python SDK."""
from datetime import datetime
def datetime_to_iso(value: datetime | str | None) -> str | None:
"""
Convert a datetime value to an ISO 8601 formatted string.
Args:
value: A datetime object, an ISO 8601 string, or None
Returns:
An ISO 8601 formatted string, or None if input is None
"""
if value is None:
return None
if isinstance(value, str):
return value
return value.isoformat()
def parse_datetime(value: datetime | str | None) -> datetime | None:
"""
Parse an ISO 8601 datetime string into a `datetime` instance.
This accepts timestamps in the forms commonly produced by APIs and JS runtimes,
including a trailing "Z" UTC designator (e.g. "2024-01-15T10:30:00Z") and
offsets (e.g. "2024-01-15T10:30:00+00:00").
Args:
value: A datetime object, an ISO 8601 string, or None.
Returns:
A `datetime` instance if provided, otherwise None.
Raises:
ValueError: If the string cannot be parsed as ISO 8601.
"""
if value is None:
return None
if isinstance(value, datetime):
return value
normalized = value.replace("Z", "+00:00")
try:
return datetime.fromisoformat(normalized)
except ValueError as e:
raise ValueError(f"Invalid ISO 8601 datetime: {value!r}") from e
@@ -0,0 +1,75 @@
"""
File upload utilities for the Honcho Python SDK.
This module provides shared functionality for handling file uploads across
both sync and async client implementations.
"""
import mimetypes
from io import BytesIO, IOBase
def normalize_file_input(
file: tuple[str, bytes, str] | tuple[str, IOBase, str] | IOBase,
) -> tuple[str, IOBase, str]:
"""
Normalize various file input formats to a standard tuple format.
Args:
file: File to normalize. Can be:
- a file object (must have .name and .read())
- a tuple (filename, bytes, content_type)
- a tuple (filename, fileobj, content_type)
Returns:
A normalized tuple of (filename, fileobj, content_type)
Raises:
ValueError: If the file input format is not supported
"""
# If it's a tuple (filename, bytes, content_type)
if isinstance(file, tuple) and len(file) == 3:
filename, file_content, content_type = file
if isinstance(file_content, bytes):
fileobj = BytesIO(file_content)
fileobj.name = filename
return (filename, fileobj, content_type)
elif isinstance(file_content, IOBase): # pyright: ignore -- needed for return type
return (filename, file_content, content_type)
else:
raise ValueError("File content must be bytes or a file-like object.")
# If it's a file object (not str/bytes/bytearray/memoryview)
elif isinstance(file, IOBase): # pyright: ignore -- needed for return type
filename = getattr(file, "name", None)
if not filename:
raise ValueError("File object must have a .name attribute.")
content_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
return (filename, file, content_type)
def prepare_file_for_upload(
file: tuple[str, bytes, str] | tuple[str, IOBase, str] | IOBase,
) -> tuple[str, bytes, str]:
"""
Prepare a file for upload by normalizing and reading its content.
Args:
file: File to prepare. Can be:
- a file object (must have .name and .read())
- a tuple (filename, bytes, content_type)
- a tuple (filename, fileobj, content_type)
Returns:
A tuple of (filename, content_bytes, content_type) ready for API upload
Raises:
ValueError: If the file input format is not supported
"""
normalized_file = normalize_file_input(file)
# Read the file content
normalized_file[1].seek(0) # Reset file position
content_bytes = normalized_file[1].read()
return (normalized_file[0], content_bytes, normalized_file[2])
+49
View File
@@ -0,0 +1,49 @@
"""Peer-related utility functions."""
from __future__ import annotations
from typing import Any
from ..api_types import SessionPeerConfig
from ..base import PeerBase
def normalize_peers_to_dict(
peers: str
| PeerBase
| tuple[str, SessionPeerConfig]
| tuple[PeerBase, SessionPeerConfig]
| list[PeerBase | str]
| list[tuple[PeerBase | str, SessionPeerConfig]]
| list[PeerBase | str | tuple[PeerBase | str, SessionPeerConfig]],
) -> dict[str, Any]:
"""
Normalize various peer input formats into a dict mapping peer IDs to configs.
Accepts:
- str: Single peer ID
- PeerBase: Single Peer object
- tuple[str, SessionPeerConfig]: Single peer ID with config
- tuple[PeerBase, SessionPeerConfig]: Single Peer object with config
- list[PeerBase | str]: List of peers/IDs
- list[tuple[PeerBase | str, SessionPeerConfig]]: List of peers with configs
- Mixed lists combining all of the above
Returns:
Dict mapping peer IDs to their config dicts (empty dict if no config)
"""
if not isinstance(peers, list):
peers = [peers]
peer_dict: dict[str, Any] = {}
for peer in peers:
if isinstance(peer, tuple):
peer_id = peer[0] if isinstance(peer[0], str) else peer[0].id
peer_config = peer[1]
peer_dict[peer_id] = peer_config.model_dump(exclude_none=True)
else:
peer_id = peer if isinstance(peer, str) else peer.id
peer_dict[peer_id] = {}
return peer_dict
+50
View File
@@ -0,0 +1,50 @@
"""ID resolution utilities for the Honcho Python SDK."""
from __future__ import annotations
from typing import TYPE_CHECKING, overload
if TYPE_CHECKING:
from ..base import PeerBase, SessionBase
@overload
def resolve_id(obj: None) -> None: ...
@overload
def resolve_id(obj: str) -> str: ...
@overload
def resolve_id(obj: "PeerBase | SessionBase") -> str: ...
def resolve_id(obj: "str | PeerBase | SessionBase | None") -> str | None:
"""
Resolve an ID from a string, PeerBase, SessionBase, or None.
This utility function extracts the ID from an object that may be:
- A string (returned as-is)
- An object with an `id` attribute (the id is extracted)
- None (returns None)
Args:
obj: A string ID, an object with an `id` attribute (like Peer or Session), or None
Returns:
The resolved string ID, or None if input is None
Example:
>>> resolve_id("user-123")
'user-123'
>>> resolve_id(peer) # where peer.id == "user-123"
'user-123'
>>> resolve_id(None)
None
"""
if obj is None:
return None
if isinstance(obj, str):
return obj
return obj.id
+228
View File
@@ -0,0 +1,228 @@
"""SSE (Server-Sent Events) parsing utilities."""
from __future__ import annotations
import codecs
import json
import logging
from collections.abc import AsyncGenerator, AsyncIterable, Generator, Iterable
from typing import Any, cast
logger = logging.getLogger(__name__)
class SSEStreamParser:
"""
Incrementally parse an SSE byte stream into content strings.
This parser is designed for real network streaming where byte chunks may split UTF-8
codepoints and/or split lines arbitrarily. It maintains:
- An incremental UTF-8 decoder to safely decode across chunk boundaries.
- A text buffer to safely assemble complete lines across chunk boundaries.
The Honcho streaming format is expected to include lines in the form `data:<json>` or
`data: <json>`. Each data line should contain a JSON object with:
- `done: true` to indicate stream completion.
- `delta.content` containing incremental text.
Any JSON decoding failures are logged with the same warning format as the legacy
parser, including a preview of the data payload.
"""
def __init__(self) -> None:
self._decoder: codecs.IncrementalDecoder = codecs.getincrementaldecoder(
"utf-8"
)(errors="replace")
self._text_buffer: str = ""
self._done: bool = False
@property
def done(self) -> bool:
"""Whether the stream has emitted a `done: true` message."""
return self._done
def feed(self, chunk: bytes) -> Generator[str, None, None]:
"""
Feed the next bytes from the SSE stream and yield any newly available content.
Args:
chunk: Raw bytes from the SSE stream.
Yields:
Content strings extracted from any complete `data:` lines decoded from this
chunk (and any previously buffered partial data).
"""
if self._done or not chunk:
return
decoded = self._decoder.decode(chunk, final=False)
if decoded:
self._text_buffer += decoded
yield from self._drain_complete_lines()
def finalize(self) -> Generator[str, None, None]:
"""
Finalize the stream and yield any remaining content.
This should be called once the underlying byte stream is finished to flush any
remaining decoder/buffer state.
"""
if self._done:
return
decoded = self._decoder.decode(b"", final=True)
if decoded:
self._text_buffer += decoded
yield from self._drain_complete_lines(flush_partial=True)
def _drain_complete_lines(
self, *, flush_partial: bool = False
) -> Generator[str, None, None]:
while not self._done:
line = self._pop_line(flush_partial=flush_partial)
if line is None:
return
yield from self._handle_line(line)
def _pop_line(self, *, flush_partial: bool) -> str | None:
if not self._text_buffer:
return None
idx_n = self._text_buffer.find("\n")
idx_r = self._text_buffer.find("\r")
if idx_n == -1 and idx_r == -1:
if not flush_partial:
return None
line = self._text_buffer
self._text_buffer = ""
return line
if idx_n == -1:
idx = idx_r
elif idx_r == -1:
idx = idx_n
else:
idx = min(idx_n, idx_r)
sep = self._text_buffer[idx]
if sep == "\n":
line = self._text_buffer[:idx]
self._text_buffer = self._text_buffer[idx + 1 :]
if line.endswith("\r"):
line = line[:-1]
return line
if idx == len(self._text_buffer) - 1 and not flush_partial:
return None
if idx + 1 < len(self._text_buffer) and self._text_buffer[idx + 1] == "\n":
line = self._text_buffer[:idx]
self._text_buffer = self._text_buffer[idx + 2 :]
return line
line = self._text_buffer[:idx]
self._text_buffer = self._text_buffer[idx + 1 :]
return line
def _handle_line(self, line: str) -> Generator[str, None, None]:
if not line.startswith("data:"):
return
json_str = line[len("data:") :].lstrip(" ")
if not json_str:
return
try:
parsed: object = json.loads(json_str)
if not isinstance(parsed, dict):
return
chunk_data = cast(dict[str, Any], parsed)
if chunk_data.get("done"):
self._done = True
return
delta_obj = chunk_data.get("delta", {})
if not isinstance(delta_obj, dict):
return
delta_data = cast(dict[str, Any], delta_obj)
content = delta_data.get("content")
if isinstance(content, str) and content:
yield content
except json.JSONDecodeError as e:
logger.warning(
"Failed to decode streaming chunk: %s (data: %s)",
e,
json_str[:100],
)
def parse_sse_chunk(
chunk: bytes, *, parser: SSEStreamParser | None = None
) -> Generator[str, None, None]:
"""
Parse bytes from an SSE stream and yield content strings.
For correct handling of UTF-8 and line boundaries across network chunks, construct
one `SSEStreamParser` per stream and pass it for each call:
- `yield from parse_sse_chunk(chunk, parser=parser)`
Args:
chunk: Raw bytes from the SSE stream.
parser: Optional persistent parser instance. If omitted, a temporary parser is
created and finalized for this single chunk.
Yields:
Content strings extracted from delta objects.
"""
if parser is None:
tmp = SSEStreamParser()
yield from tmp.feed(chunk)
yield from tmp.finalize()
return
yield from parser.feed(chunk)
def parse_sse_stream(chunks: Iterable[bytes]) -> Generator[str, None, None]:
"""
Parse an SSE byte stream and yield content strings.
Args:
chunks: An iterable of raw byte chunks from an SSE stream.
Yields:
Content strings extracted from delta objects, in order.
"""
parser = SSEStreamParser()
for chunk in chunks:
yield from parser.feed(chunk)
if parser.done:
return
yield from parser.finalize()
async def parse_sse_astream(chunks: AsyncIterable[bytes]) -> AsyncGenerator[str, None]:
"""
Parse an async SSE byte stream and yield content strings.
Args:
chunks: An async iterable of raw byte chunks from an SSE stream.
Yields:
Content strings extracted from delta objects, in order.
"""
parser = SSEStreamParser()
async for chunk in chunks:
for content in parser.feed(chunk):
yield content
if parser.done:
return
for content in parser.finalize():
yield content