同步完整源码 - 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
+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])