diff --git a/docs/v2/documentation/features/advanced/configuration.mdx b/docs/v2/documentation/features/advanced/configuration.mdx
index bc8635b9..d86cb8c7 100644
--- a/docs/v2/documentation/features/advanced/configuration.mdx
+++ b/docs/v2/documentation/features/advanced/configuration.mdx
@@ -1,14 +1,146 @@
---
title: 'Configure Reasoning'
-description: 'Customizing how Honcho handles peers and sessions'
+description: 'Customizing how Honcho handles peers, sessions, and messages'
icon: 'wrench'
---
-Entities in Honcho can sometimes be configured to change the behavior of the deriver, which is responsible for generating and storing facts, summaries, and user representations.
+TODO: remove deriver references
-These configurations can be set at the peer, session, and session-peer level (AKA the state of a peer within a specific session).
+Honcho's reasoning engine can be configured at multiple levels to control how it processes messages, generates facts, creates summaries, and builds peer representations.
-### Peer Configuration
+Configuration follows a hierarchy: **message > session > workspace > global defaults**. Settings at lower levels override those at higher levels, giving you fine-grained control over behavior.
+
+## Configuration Hierarchy
+
+Honcho uses a hierarchical configuration system where more specific settings override more general ones:
+
+1. **Global Defaults**: Built-in system defaults
+2. **Workspace Configuration**: Settings that apply to all sessions in a workspace
+3. **Session Configuration**: Settings that apply to all messages in a session
+4. **Message Configuration**: Settings that apply to a specific message
+
+
+All configuration fields are optional. If not specified, the value is inherited from the next level up in the hierarchy.
+
+
+## Configuration Options
+
+### Deriver Configuration
+
+Controls the core reasoning engine that extracts facts and insights from messages.
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `enabled` | `bool` | Whether to enable deriver functionality. When disabled, no facts or representations are generated. |
+
+
+```python Python
+from honcho import Honcho
+
+honcho = Honcho()
+
+# Disable deriver at session level
+session = honcho.session("private-session", config={
+ "deriver": {"enabled": False}
+})
+```
+```typescript TypeScript
+import { Honcho } from "@honcho-ai/sdk";
+
+const honcho = new Honcho({});
+
+// Disable deriver at session level
+const session = await honcho.session("private-session", {
+ config: {
+ deriver: { enabled: false }
+ }
+});
+```
+
+
+### Peer Card Configuration
+
+Controls how peer cards (concise summaries of what's known about a peer) are generated and used.
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `use` | `bool` | Whether to use peer cards during the deriver process. |
+| `create` | `bool` | Whether to generate peer cards based on message content. |
+
+
+```python Python
+# Disable peer card generation but still use existing cards
+session = honcho.session("my-session", config={
+ "peer_card": {"create": False, "use": True}
+})
+```
+```typescript TypeScript
+// Disable peer card generation but still use existing cards
+const session = await honcho.session("my-session", {
+ config: {
+ peer_card: { create: false, use: true }
+ }
+});
+```
+
+
+### Summary Configuration
+
+Controls automatic conversation summarization. Available at workspace and session levels only.
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `enabled` | `bool` | Whether to enable summary functionality. |
+| `messages_per_short_summary` | `int` | Number of messages between short summaries. Must be ≥ 10. |
+| `messages_per_long_summary` | `int` | Number of messages between long summaries. Must be ≥ 20 and greater than `messages_per_short_summary`. |
+
+
+```python Python
+# Customize summary frequency
+session = honcho.session("verbose-session", config={
+ "summary": {
+ "enabled": True,
+ "messages_per_short_summary": 15,
+ "messages_per_long_summary": 45
+ }
+})
+```
+```typescript TypeScript
+// Customize summary frequency
+const session = await honcho.session("verbose-session", {
+ config: {
+ summary: {
+ enabled: true,
+ messages_per_short_summary: 15,
+ messages_per_long_summary: 45
+ }
+ }
+});
+```
+
+
+### Dream Configuration
+
+Controls the "dreaming" process that consolidates and refines representations. Available at workspace and session levels only.
+
+| Field | Type | Description |
+|-------|------|-------------|
+| `enabled` | `bool` | Whether to enable dream functionality. Automatically disabled if deriver is disabled. |
+
+
+```python Python
+# Disable dreams for a workspace
+# (done via API when creating/updating workspace)
+```
+```typescript TypeScript
+// Disable dreams for a workspace
+// (done via API when creating/updating workspace)
+```
+
+
+---
+
+## Peer Configuration
By default, all peers are "observed" by Honcho. This means that Honcho will derive facts from messages sent by the peer and generate a representation of them. In most cases, this is why you use Honcho! However, sometimes an application requires a peer that should not be observed: for example, an assistant or game NPC that your program will never need to ask questions about.
@@ -27,7 +159,7 @@ honcho = Honcho()
peer = honcho.peer("my-peer", config={"observe_me": False})
# Change peer's configuration
-peer.set_peer_config({"observe_me": True})
+peer.set_config({"observe_me": True})
# Note: creating the same peer again will also replace the configuration
peer = honcho.peer("my-peer", config={"observe_me": False})
@@ -43,7 +175,7 @@ import { Honcho } from "@honcho-ai/sdk";
const peer = await honcho.peer("my-peer", { config: { observe_me: false } });
// Change peer's configuration
- await peer.setPeerConfig({ observe_me: true });
+ await peer.setConfig({ observe_me: true });
// Note: creating the same peer again will also replace the configuration
await honcho.peer("my-peer", { config: { observe_me: false } });
@@ -51,9 +183,9 @@ import { Honcho } from "@honcho-ai/sdk";
```
-### Session Configuration
+## Session Configuration
-By default, all sessions have the deriver enabled, much like peers. You may create a session that escapes the deriver's watchful eye by setting the `deriver_disabled` flag to `true`. You can update the flag by calling `get_or_create` on the session with a new configuration.
+Sessions support the full configuration schema. You can disable the deriver entirely for a session, customize summary behavior, or adjust peer card settings.
```python Python
@@ -62,8 +194,18 @@ from honcho import Honcho
# Initialize client
honcho = Honcho()
-# Create session with configuration
-session = honcho.session("my-session", config={"deriver_disabled": True})
+# Create session with deriver disabled
+session = honcho.session("my-session", config={
+ "deriver": {"enabled": False}
+})
+
+# Create session with custom summary settings
+session = honcho.session("detailed-session", config={
+ "summary": {
+ "messages_per_short_summary": 10,
+ "messages_per_long_summary": 30
+ }
+})
```
```typescript TypeScript
import { Honcho } from "@honcho-ai/sdk";
@@ -72,15 +214,73 @@ import { Honcho } from "@honcho-ai/sdk";
// Initialize client
const honcho = new Honcho({});
- // Create session with configuration
- const session = await honcho.session("my-session", { config: { deriver_disabled: true } });
+ // Create session with deriver disabled
+ const session = await honcho.session("my-session", {
+ config: { deriver: { enabled: false } }
+ });
+
+ // Create session with custom summary settings
+ const detailedSession = await honcho.session("detailed-session", {
+ config: {
+ summary: {
+ messages_per_short_summary: 10,
+ messages_per_long_summary: 30
+ }
+ }
+ });
})();
```
-### Session-Peer Configuration
+## Message Configuration
-Configuration at the session-peer level is the most common use case for configuration flags. You will often want to arrange a session such that certain peers observe others in order to form "local representations" of them. There are two flags that can be set at the session-peer level:
+Individual messages can override session and workspace configuration for fine-grained control. This is useful for excluding specific messages from processing or adjusting behavior on a per-message basis.
+
+
+```python Python
+from honcho import Honcho
+
+honcho = Honcho()
+session = honcho.session("my-session")
+user = honcho.peer("user")
+
+# Create a message that skips deriver processing
+session.add_messages([
+ user.message("This message won't be analyzed", config={
+ "deriver": {"enabled": False}
+ })
+])
+
+# Create a message with custom peer card settings
+session.add_messages([
+ user.message("Use existing card but don't update it", config={
+ "peer_card": {"use": True, "create": False}
+ })
+])
+```
+```typescript TypeScript
+import { Honcho } from "@honcho-ai/sdk";
+
+(async () => {
+ const honcho = new Honcho({});
+ const session = await honcho.session("my-session");
+ const user = await honcho.peer("user");
+
+ // Create a message that skips deriver processing
+ await session.addMessages([
+ user.message("This message won't be analyzed", {
+ configuration: { deriver: { enabled: false } }
+ })
+ ]);
+})();
+```
+
+
+## Session-Peer Configuration
+
+Configuration at the session-peer level controls how peers observe each other within a specific session. This is the most common use case for enabling "local representations" — where one peer forms a model of another peer based only on what they observe in that session.
+
+There are two flags that can be set at the session-peer level:
- `observe_me`: Whether this peer should *be observed* by others in the session. By default, this is `true`. This overrides the peer-level `observe_me` flag.
@@ -96,7 +296,7 @@ You can dynamically change the configuration of a session-peer by calling `set_p
```python Python
-from honcho import Honcho
+from honcho import Honcho, SessionPeerConfig
# Initialize client
honcho = Honcho()
@@ -113,11 +313,11 @@ session.add_peers([alice, bob])
# Add another peer to the session with a custom configuration
charlie = honcho.peer("charlie")
-session.add_peers([charlie, {"observe_me": False, "observe_others": True}])
+session.add_peers([(charlie, SessionPeerConfig(observe_me=False, observe_others=True))])
# Set session-peer configuration
-session.set_peer_config(alice, {"observe_others": True})
-session.set_peer_config(bob, {"observe_me": False})
+session.set_peer_config(alice, SessionPeerConfig(observe_others=True))
+session.set_peer_config(bob, SessionPeerConfig(observe_me=False))
# Get session-peer configuration
charlie_config = session.get_peer_config(charlie)
@@ -142,7 +342,7 @@ import { Honcho } from "@honcho-ai/sdk";
// Add another peer to the session with a custom configuration
const charlie = await honcho.peer("charlie");
- await session.addPeers([charlie, { observe_me: false, observe_others: true }]);
+ await session.addPeers([[charlie, { observe_me: false, observe_others: true }]]);
// Set session-peer configuration
await session.setPeerConfig(alice, { observe_others: true });
@@ -154,3 +354,45 @@ import { Honcho } from "@honcho-ai/sdk";
})();
```
+
+## Full Configuration Schema Reference
+
+### Workspace & Session Configuration
+
+```json
+{
+ "deriver": {
+ "enabled": true
+ },
+ "peer_card": {
+ "use": true,
+ "create": true
+ },
+ "summary": {
+ "enabled": true,
+ "messages_per_short_summary": 20,
+ "messages_per_long_summary": 60
+ },
+ "dream": {
+ "enabled": true
+ }
+}
+```
+
+### Message Configuration
+
+```json
+{
+ "deriver": {
+ "enabled": true
+ },
+ "peer_card": {
+ "use": true,
+ "create": true
+ }
+}
+```
+
+
+Message configuration only supports `deriver` and `peer_card` settings. Summary and dream configurations are session/workspace-level only.
+
\ No newline at end of file
diff --git a/docs/v2/documentation/features/get-context.mdx b/docs/v2/documentation/features/get-context.mdx
index 1630b71f..fc6a6ece 100644
--- a/docs/v2/documentation/features/get-context.mdx
+++ b/docs/v2/documentation/features/get-context.mdx
@@ -1,239 +1,91 @@
---
title: 'Get Context'
description: 'Learn how to use get_context() to retrieve and format conversation context for LLM integration'
-icon: 'list-timeline'
+icon: 'messages'
---
-The `get_context()` method is your one-stop-shop for solving memory in LLM applications. It curates the LLM's context window with everything needed for contextually-aware conversations: recent messages, relevant historical context, and conversation summaries. When you add a `peer_target`, it also includes peer cards and Honcho's reasoning about participants.
+The `get_context()` method is a powerful feature that retrieves formatted conversation context from sessions, making it easy to integrate with LLMs like OpenAI, Anthropic, and others. This guide covers everything you need to know about working with session context.
-## The Simple Default
+By default, the context includes a blend of summary and messages which covers the entire history of the session. Summaries are automatically generated at intervals and recent messages are included depending on how many tokens the context is intended to be. You can specify any token limit you want, and can disable summaries to fill that limit entirely with recent messages.
-The simplest implementation is just calling `get_context()` with a `peer_target` - this gives you an optimized blend of everything Honcho knows about your conversation:
+## Basic Usage
+
+The `get_context()` method is available on all Session objects and returns a `SessionContext` that contains the formatted conversation history.
```python Python
from honcho import Honcho
+# Initialize client and create session
honcho = Honcho()
session = honcho.session("conversation-1")
-user = honcho.peer("user-123")
-assistant = honcho.peer("assistant")
-# Add some conversation
-session.add_messages([
- user.message("I prefer concise responses"),
- assistant.message("Understood! I'll keep it brief.")
-])
-
-# Get context with personalization - the recommended default
-context = session.get_context(peer_target=user)
-messages = context.to_openai(assistant=assistant)
-
-# Ready to send to your LLM
+# Get basic context (not very useful before adding any messages!)
+context = session.get_context()
```
```typescript TypeScript
import { Honcho } from "@honcho-ai/sdk";
(async () => {
+ // Initialize client and create session
const honcho = new Honcho({});
const session = await honcho.session("conversation-1");
- const user = await honcho.peer("user-123");
- const assistant = await honcho.peer("assistant");
- // Add some conversation
- await session.addMessages([
- user.message("I prefer concise responses"),
- assistant.message("Understood! I'll keep it brief.")
- ]);
-
- // Get context with personalization - the recommended default
- const context = await session.getContext({ peerTarget: user });
- const messages = context.toOpenAI(assistant);
-
- // Ready to send to your LLM
+ // Get basic context (not very useful before adding any messages!)
+ const context = await session.getContext();
})();
```
-**What's included:**
-- **Recent messages** from the conversation (token-limited)
-- **Conversation summaries** for older history (automatically generated)
-- **Working representation** of the user - Honcho's conclusions and insights
-- **Peer card** - Structured metadata about the user
-- Formatted for your target LLM (OpenAI, Anthropic, etc.)
+## Context Parameters
-This is the recommended default for most applications - it gives your LLM everything it needs to provide personalized, context-aware responses.
+The `get_context()` method accepts several optional parameters to customize the retrieved context:
-## Advanced Context Control
+### Token Limits
-Build on the default by adding more sophisticated features to control what context your LLM receives.
-
-### Semantic Retrieval
-
-Use `last_user_message` to pull in relevant observations from past conversations:
+Control the size of the context by setting a maximum token count:
```python Python
-# User asks about something from weeks ago
-user_question = "What was that Italian restaurant I mentioned?"
+# Limit context to 1500 tokens
+context = session.get_context(tokens=1500)
-context = session.get_context(
- peer_target=user,
- last_user_message=user_question,
- tokens=2000
-)
-
-# Context includes observations semantically relevant to restaurants
-# Even if the conversation was weeks ago
+# Limit context to 3000 tokens for larger conversations
+context = session.get_context(tokens=3000)
```
```typescript TypeScript
(async () => {
- // User asks about something from weeks ago
- const userQuestion = "What was that Italian restaurant I mentioned?";
+ // Limit context to 1500 tokens
+ const context = await session.getContext({ tokens: 1500 });
+ // Limit context to 3000 tokens for larger conversations
+ const context = await session.getContext({ tokens: 3000 });
+})();
+```
+
+
+### Summary Mode
+
+Enable summary mode (on by default) to get a condensed version of the conversation:
+
+
+```python Python
+# Get context with summary enabled -- will contain both summary and messages
+context = session.get_context(summary=True)
+
+# Combine summary=False with token limits to get more messages
+context = session.get_context(summary=False, tokens=2000)
+```
+
+```typescript TypeScript
+(async () => {
+ // Get context with summary enabled -- will contain both summary and messages
+ const context = await session.getContext({ summary: true });
+
+ // Combine summary=False with token limits to get more messages
const context = await session.getContext({
- peerTarget: user,
- lastUserMessage: userQuestion,
- tokens: 2000
- });
-
- // Context includes observations semantically relevant to restaurants
- // Even if the conversation was weeks ago
-})();
-```
-
-
-You can pass either a string or a Message object. This is particularly useful for recall-style queries where users reference past conversations.
-
-### Perspective-Based Views
-
-In multi-agent scenarios, get context from a specific agent's perspective:
-
-
-```python Python
-# Different agents, different perspectives on the same user
-sales_agent = honcho.peer("sales-bot")
-support_agent = honcho.peer("support-bot")
-
-# Sales agent's view - includes conclusions about purchase intent
-sales_context = session.get_context(
- peer_target=user,
- peer_perspective=sales_agent
-)
-
-# Support agent's view - includes conclusions about technical needs
-support_context = session.get_context(
- peer_target=user,
- peer_perspective=support_agent
-)
-
-# Each agent reasons independently about the user
-```
-
-```typescript TypeScript
-(async () => {
- // Different agents, different perspectives on the same user
- const salesAgent = await honcho.peer("sales-bot");
- const supportAgent = await honcho.peer("support-bot");
-
- // Sales agent's view - includes conclusions about purchase intent
- const salesContext = await session.getContext({
- peerTarget: user,
- peerPerspective: salesAgent
- });
-
- // Support agent's view - includes conclusions about technical needs
- const supportContext = await session.getContext({
- peerTarget: user,
- peerPerspective: supportAgent
- });
-
- // Each agent reasons independently about the user
-})();
-```
-
-
-Use this pattern when you have multiple specialized agents that need different mental models of the same user.
-
-### Combining Advanced Features
-
-Stack multiple advanced parameters for maximum context awareness:
-
-
-```python Python
-current_message = "Can you recommend a restaurant for tonight?"
-
-context = session.get_context(
- peer_target=user, # User's representation & card
- last_user_message=current_message, # Relevant observations
- peer_perspective=assistant, # Assistant's perspective
- tokens=3000 # Generous limit
-)
-
-# Includes: user insights, relevant past observations,
-# assistant's conclusions, recent messages, summaries
-```
-
-```typescript TypeScript
-(async () => {
- const currentMessage = "Can you recommend a restaurant for tonight?";
-
- const context = await session.getContext({
- peerTarget: user, // User's representation & card
- lastUserMessage: currentMessage, // Relevant observations
- peerPerspective: assistant, // Assistant's perspective
- tokens: 3000 // Generous limit
- });
-
- // Includes: user insights, relevant past observations,
- // assistant's conclusions, recent messages, summaries
-})();
-```
-
-
-## Tuning & Simplification
-
-When you need to adjust the default behavior or reduce context complexity.
-
-### Adjusting Token Limits
-
-Control how much context to include by setting a token budget:
-
-
-```python Python
-# Adjust context size for your model's limits
-context = session.get_context(peer_target=user, tokens=1500) # Smaller models
-context = session.get_context(peer_target=user, tokens=4000) # Larger models
-```
-
-```typescript TypeScript
-(async () => {
- // Adjust context size for your model's limits
- const context = await session.getContext({ peerTarget: user, tokens: 1500 });
- const context = await session.getContext({ peerTarget: user, tokens: 4000 });
-})();
-```
-
-
-**When to adjust:** When you're hitting model context limits or want more/less conversation history.
-
-### Disabling Summaries
-
-Turn off summaries to get only raw messages:
-
-
-```python Python
-# Get more recent messages instead of summaries
-context = session.get_context(peer_target=user, summary=False, tokens=2000)
-```
-
-```typescript TypeScript
-(async () => {
- // Get more recent messages instead of summaries
- const context = await session.getContext({
- peerTarget: user,
summary: false,
tokens: 2000
});
@@ -241,69 +93,255 @@ context = session.get_context(peer_target=user, summary=False, tokens=2000)
```
-**When to use:** Short conversations where full message history fits in context, or when you prefer verbatim exchanges over summarized history.
+### Peer Representation in Context
-### Removing Personalization
-
-Omit `peer_target` for just messages and summaries without peer reasoning:
+You can include a peer's representation and peer card in the context by specifying `peer_target`. This is useful for providing the LLM with knowledge about a specific peer.
```python Python
-# Just messages and summaries, no peer-specific reasoning
-context = session.get_context()
-messages = context.to_openai(assistant=assistant)
+# Get context with peer representation included
+context = session.get_context(
+ tokens=2000,
+ peer_target="user-123" # Include representation of user-123
+)
+
+# Access the representation and peer card
+print(context.peer_representation) # String representation
+print(context.peer_card) # List of peer card items
+
+# Get representation from a specific peer's perspective
+context = session.get_context(
+ tokens=2000,
+ peer_target="user-123",
+ peer_perspective="assistant" # From assistant's viewpoint
+)
```
```typescript TypeScript
(async () => {
- // Just messages and summaries, no peer-specific reasoning
- const context = await session.getContext();
- const messages = context.toOpenAI(assistant);
+ // Get context with peer representation included
+ const context = await session.getContext({
+ tokens: 2000,
+ peerTarget: "user-123" // Include representation of user-123
+ });
+
+ // Access the representation and peer card
+ console.log(context.peerRepresentation); // String representation
+ console.log(context.peerCard); // Array of peer card items
+
+ // Get representation from a specific peer's perspective
+ const perspectiveContext = await session.getContext({
+ tokens: 2000,
+ peerTarget: "user-123",
+ peerPerspective: "assistant" // From assistant's viewpoint
+ });
})();
```
-**When to use:** When you explicitly don't want personalization or need to reduce context size. Most applications benefit from including `peer_target`.
+### Semantic Search with Last Message
-## Complete Integration Examples
+Use `last_user_message` to fetch semantically relevant observations based on the most recent message:
-### OpenAI Integration
+
+```python Python
+# Get context with semantic search based on last message
+context = session.get_context(
+ tokens=2000,
+ peer_target="user-123",
+ last_user_message="What are my account preferences?",
+ search_top_k=10, # Number of relevant observations
+ search_max_distance=0.8, # Max semantic distance (0.0-1.0)
+ include_most_derived=True, # Include most recent observations
+ max_observations=25 # Cap total observations
+)
+```
+
+```typescript TypeScript
+(async () => {
+ // Get context with semantic search based on last message
+ const context = await session.getContext({
+ tokens: 2000,
+ peerTarget: "user-123",
+ lastUserMessage: "What are my account preferences?",
+ searchTopK: 10, // Number of relevant observations
+ searchMaxDistance: 0.8, // Max semantic distance (0.0-1.0)
+ includeMostDerived: true, // Include most recent observations
+ maxObservations: 25 // Cap total observations
+ });
+})();
+```
+
+
+### Session-Scoped Representations
+
+Use `limit_to_session` to only include observations from the current session:
+
+
+```python Python
+# Get context limited to this session's observations only
+context = session.get_context(
+ tokens=2000,
+ peer_target="user-123",
+ limit_to_session=True # Only observations from this session
+)
+```
+
+```typescript TypeScript
+(async () => {
+ // Get context limited to this session's observations only
+ const context = await session.getContext({
+ tokens: 2000,
+ peerTarget: "user-123",
+ limitToSession: true // Only observations from this session
+ });
+})();
+```
+
+
+### All Parameters Reference
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `summary` | `bool` | Include summary in context (default: true) |
+| `tokens` | `int` | Maximum tokens to include |
+| `peer_target` | `str` | Peer ID to include representation for |
+| `peer_perspective` | `str` | Peer ID for perspective (requires peer_target) |
+| `last_user_message` | `str` | Message for semantic search (requires peer_target) |
+| `limit_to_session` | `bool` | Limit to session observations only |
+| `search_top_k` | `int` | Semantic search results to include (1-100) |
+| `search_max_distance` | `float` | Max semantic distance (0.0-1.0) |
+| `include_most_derived` | `bool` | Include most recently derived observations |
+| `max_observations` | `int` | Maximum observations to include (1-100) |
+
+## Converting to LLM Formats
+
+The `SessionContext` object provides methods to convert the context into formats compatible with popular LLM APIs. When converting to OpenAI format, you must specify the assistant peer to format the context in such a way that the LLM can understand it.
+
+### OpenAI Format
+
+Convert context to OpenAI's chat completion format:
+
+
+```python Python
+# Create peers
+alice = honcho.peer("alice")
+assistant = honcho.peer("assistant")
+
+# Add some conversation
+session.add_messages([
+ alice.message("What's the weather like today?"),
+ assistant.message("It's sunny and 75°F outside!")
+])
+
+# Get context and convert to OpenAI format
+context = session.get_context()
+openai_messages = context.to_openai(assistant=assistant)
+
+# The messages are now ready for OpenAI API
+print(openai_messages)
+# [
+# {"role": "user", "content": "What's the weather like today?"},
+# {"role": "assistant", "content": "It's sunny and 75°F outside!"}
+# ]
+```
+
+```typescript TypeScript
+(async () => {
+ // Create peers
+ const alice = await honcho.peer("alice");
+ const assistant = await honcho.peer("assistant");
+
+ // Add some conversation
+ await session.addMessages([
+ alice.message("What's the weather like today?"),
+ assistant.message("It's sunny and 75°F outside!")
+ ]);
+
+ // Get context and convert to OpenAI format
+ const context = await session.getContext();
+ const openaiMessages = context.toOpenAI(assistant);
+
+ // The messages are now ready for OpenAI API
+ console.log(openaiMessages);
+ // [
+ // {"role": "user", "content": "What's the weather like today?"},
+ // {"role": "assistant", "content": "It's sunny and 75°F outside!"}
+ // ]
+})();
+```
+
+
+### Anthropic Format
+
+Convert context to Anthropic's Claude format:
+
+
+```python Python
+# Get context and convert to Anthropic format
+context = session.get_context()
+anthropic_messages = context.to_anthropic(assistant=assistant)
+
+# Ready for Anthropic API
+print(anthropic_messages)
+```
+
+```typescript TypeScript
+(async () => {
+ // Get context and convert to Anthropic format
+ const context = await session.getContext();
+ const anthropicMessages = context.toAnthropic(assistant);
+
+ // Ready for Anthropic API
+ console.log(anthropicMessages);
+})();
+```
+
+
+## Complete LLM Integration Examples
+
+### Using with OpenAI
```python Python
import openai
from honcho import Honcho
+# Initialize clients
honcho = Honcho()
openai_client = openai.OpenAI()
-session = honcho.session("chat")
+# Set up conversation
+session = honcho.session("support-chat")
user = honcho.peer("user-123")
-assistant = honcho.peer("assistant")
+assistant = honcho.peer("support-bot")
-# Get new user input
-user_input = "Can you help me with Python?"
-session.add_messages([user.message(user_input)])
+# Add conversation history
+session.add_messages([
+ user.message("I'm having trouble with my account login"),
+ assistant.message("I can help you with that. What error message are you seeing?"),
+ user.message("It says 'Invalid credentials' but I'm sure my password is correct")
+])
-# Get context with personalization
-context = session.get_context(
- peer_target=user,
- last_user_message=user_input,
- tokens=2000
-)
+# Get context for LLM
+messages = session.get_context(tokens=2000).to_openai(assistant=assistant)
-# Convert to OpenAI format (specifies which peer is the assistant)
-messages = context.to_openai(assistant=assistant)
+# Add new user message and get AI response
+messages.append({
+ "role": "user",
+ "content": "Can you reset my password?"
+})
-# Get AI response
response = openai_client.chat.completions.create(
model="gpt-4",
messages=messages
)
-# Save response back to Honcho
-ai_response = response.choices[0].message.content
-session.add_messages([assistant.message(ai_response)])
+# Add AI response back to session
+session.add_messages([
+ user.message("Can you reset my password?"),
+ assistant.message(response.choices[0].message.content)
+])
```
```typescript TypeScript
@@ -311,238 +349,303 @@ import OpenAI from 'openai';
import { Honcho } from "@honcho-ai/sdk";
(async () => {
+ // Initialize clients
const honcho = new Honcho({});
const openai = new OpenAI();
- const session = await honcho.session("chat");
+ // Set up conversation
+ const session = await honcho.session("support-chat");
const user = await honcho.peer("user-123");
- const assistant = await honcho.peer("assistant");
+ const assistant = await honcho.peer("support-bot");
- // Get new user input
- const userInput = "Can you help me with Python?";
- await session.addMessages([user.message(userInput)]);
+ // Add conversation history
+ await session.addMessages([
+ user.message("I'm having trouble with my account login"),
+ assistant.message("I can help you with that. What error message are you seeing?"),
+ user.message("It says 'Invalid credentials' but I'm sure my password is correct")
+ ]);
- // Get context with personalization
- const context = await session.getContext({
- peerTarget: user,
- lastUserMessage: userInput,
- tokens: 2000
- });
+ // Get context for LLM
+ const messages = await session.getContext({ tokens: 2000 }).toOpenAI(assistant);
- // Convert to OpenAI format (specifies which peer is the assistant)
- const messages = context.toOpenAI(assistant);
-
- // Get AI response
+ // Add new user message and get AI response
const response = await openai.chat.completions.create({
model: "gpt-4",
- messages: messages
+ messages: [
+ ...messages,
+ { role: "user", content: "Can you reset my password?" }
+ ]
});
- // Save response back to Honcho
- const aiResponse = response.choices[0].message.content;
- await session.addMessages([assistant.message(aiResponse)]);
+ // Add AI response back to session
+ await session.addMessages([
+ user.message("Can you reset my password?"),
+ assistant.message(response.choices[0].message.content)
+ ]);
})();
```
-### Anthropic Integration
-
-
-```python Python
-import anthropic
-from honcho import Honcho
-
-honcho = Honcho()
-anthropic_client = anthropic.Anthropic()
-
-session = honcho.session("chat")
-user = honcho.peer("user-123")
-assistant = honcho.peer("assistant")
-
-user_input = "Tell me about quantum computing"
-session.add_messages([user.message(user_input)])
-
-context = session.get_context(peer_target=user)
-
-# Convert to Anthropic format
-messages = context.to_anthropic(assistant=assistant)
-
-response = anthropic_client.messages.create(
- model="claude-3-5-sonnet-20241022",
- max_tokens=1024,
- messages=messages
-)
-
-ai_response = response.content[0].text
-session.add_messages([assistant.message(ai_response)])
-```
-
-```typescript TypeScript
-import Anthropic from '@anthropic-ai/sdk';
-import { Honcho } from "@honcho-ai/sdk";
-
-(async () => {
- const honcho = new Honcho({});
- const anthropic = new Anthropic();
-
- const session = await honcho.session("chat");
- const user = await honcho.peer("user-123");
- const assistant = await honcho.peer("assistant");
-
- const userInput = "Tell me about quantum computing";
- await session.addMessages([user.message(userInput)]);
-
- const context = await session.getContext({ peerTarget: user });
-
- // Convert to Anthropic format
- const messages = context.toAnthropic(assistant);
-
- const response = await anthropic.messages.create({
- model: "claude-3-5-sonnet-20241022",
- max_tokens: 1024,
- messages: messages
- });
-
- const aiResponse = response.content[0].text;
- await session.addMessages([assistant.message(aiResponse)]);
-})();
-```
-
-
-### Chat Loop Example
+### Multi-Turn Conversation Loop
```python Python
def chat_loop():
- session = honcho.session("chat")
+ """Example of a continuous chat loop using get_context()"""
+
+ session = honcho.session("chat-session")
user = honcho.peer("user")
- assistant = honcho.peer("assistant")
+ assistant = honcho.peer("ai-assistant")
while True:
+ # Get user input
user_input = input("You: ")
if user_input.lower() in ['quit', 'exit']:
break
+ # Add user message to session
session.add_messages([user.message(user_input)])
- context = session.get_context(
- peer_target=user,
- last_user_message=user_input,
- tokens=2000
- )
+ # Get conversation context
+ context = session.get_context(tokens=2000)
+ messages = context.to_openai(assistant=assistant)
+ # Get AI response
response = openai_client.chat.completions.create(
model="gpt-4",
- messages=context.to_openai(assistant=assistant)
+ messages=messages
)
ai_response = response.choices[0].message.content
print(f"Assistant: {ai_response}")
+
+ # Add AI response to session
session.add_messages([assistant.message(ai_response)])
+# Start the chat loop
chat_loop()
```
```typescript TypeScript
(async () => {
async function chatLoop() {
- const session = await honcho.session("chat");
+ const session = await honcho.session("chat-session");
const user = await honcho.peer("user");
- const assistant = await honcho.peer("assistant");
+ const assistant = await honcho.peer("ai-assistant");
- // In a real app, use actual input handling
- const userInputs = ["Hello!", "What's the weather?", "Tell me a joke"];
+ // This would be replaced with actual user input handling in a real app
+ const userInputs = [
+ "Hello, how are you?",
+ "What's the weather like?",
+ "Tell me a joke"
+ ];
for (const userInput of userInputs) {
console.log(`You: ${userInput}`);
+
+ // Add user message to session
await session.addMessages([user.message(userInput)]);
- const context = await session.getContext({
- peerTarget: user,
- lastUserMessage: userInput,
- tokens: 2000
- });
+ // Get conversation context
+ const context = await session.getContext({ tokens: 2000 });
+ const messages = context.toOpenAI(assistant);
+ // Get AI response
const response = await openai.chat.completions.create({
model: "gpt-4",
- messages: context.toOpenAI(assistant)
+ messages: messages
});
const aiResponse = response.choices[0].message.content;
console.log(`Assistant: ${aiResponse}`);
+
+ // Add AI response to session
await session.addMessages([assistant.message(aiResponse)]);
}
}
+ // Start the chat loop
await chatLoop();
})();
```
+## Advanced Context Usage
+
+### Context with Summaries for Long Conversations
+
+For very long conversations, use summaries to maintain context while controlling token usage:
+
+
+```python Python
+# For long conversations, use summary mode
+long_session = honcho.session("long-conversation")
+
+# Get summarized context to fit within token limits
+context = long_session.get_context(summary=True, tokens=1500)
+messages = context.to_openai(assistant=assistant)
+
+# This will include a summary of older messages and recent full messages
+print(f"Context contains {len(messages)} formatted messages")
+```
+
+```typescript TypeScript
+(async () => {
+ // For long conversations, use summary mode
+ const longSession = await honcho.session("long-conversation");
+
+ // Get summarized context to fit within token limits
+ const context = await longSession.getContext({
+ summary: true,
+ tokens: 1500
+ });
+ const messages = context.toOpenAI(assistant);
+
+ // This will include a summary of older messages and recent full messages
+ console.log(`Context contains ${messages.length} formatted messages`);
+})();
+```
+
+
+### Context for Different Assistant Types
+
+You can get context formatted for different types of assistants in the same session:
+
+
+```python Python
+# Create different assistant peers
+chatbot = honcho.peer("chatbot")
+analyzer = honcho.peer("data-analyzer")
+moderator = honcho.peer("moderator")
+
+# Get context formatted for each assistant type
+chatbot_context = session.get_context().to_openai(assistant=chatbot)
+analyzer_context = session.get_context().to_openai(assistant=analyzer)
+moderator_context = session.get_context().to_openai(assistant=moderator)
+
+# Each context will format the conversation from that assistant's perspective
+```
+
+```typescript TypeScript
+(async () => {
+ // Create different assistant peers
+ const chatbot = await honcho.peer("chatbot");
+ const analyzer = await honcho.peer("data-analyzer");
+ const moderator = await honcho.peer("moderator");
+
+ // Get context formatted for each assistant type
+ const context = await session.getContext();
+ const chatbotContext = context.toOpenAI(chatbot);
+ const analyzerContext = context.toOpenAI(analyzer);
+ const moderatorContext = context.toOpenAI(moderator);
+
+ // Each context will format the conversation from that assistant's perspective
+})();
+```
+
+
## Best Practices
-### Start with peer_target
-Use `get_context(peer_target=user)` as your default - it gives your LLM personalized context with minimal code.
+### 1. Token Management
-### Include peer_target for almost all use cases
-Most applications benefit from including `peer_target=user` to get Honcho's reasoning about the user. Only omit it if you explicitly don't want personalization.
+Always set appropriate token limits to control costs and ensure context fits within LLM limits:
-### Set token limits based on your model
-Match your token limit to your LLM's context window:
-- Small models: `tokens=1500`
-- GPT-4 / Claude: `tokens=3000-4000`
-- Remember: peer cards and representations use some of these tokens
+
+```python Python
+# Good: Set reasonable token limits based on your model
+context = session.get_context(tokens=3000) # For GPT-4
+context = session.get_context(tokens=1500) # For smaller models
-### Use last_user_message for recall queries
-When users ask about past conversations ("What did I say about...?"), add `last_user_message` for semantic retrieval.
-
-### Perspective requires a target
-`peer_perspective` only works when combined with `peer_target` - you need both to specify whose view of whom.
-
-### Cache context objects
-If you need multiple formats (OpenAI and Anthropic), get context once and convert twice:
-```python
-context = session.get_context()
-openai_msgs = context.to_openai(assistant)
-anthropic_msgs = context.to_anthropic(assistant)
+# Good: Use summaries for very long conversations
+context = session.get_context(summary=True, tokens=2000)
```
-## Reference
+```typescript TypeScript
+(async () => {
+ // Good: Set reasonable token limits based on your model
+ const context = await session.getContext({ tokens: 3000 }); // For GPT-4
+ const context = await session.getContext({ tokens: 1500 }); // For smaller models
-### What's Actually Included in Context
+ // Good: Use summaries for very long conversations
+ const context = await session.getContext({ summary: true, tokens: 2000 });
+})();
+```
+
-When you call `get_context()` with default settings:
+### 2. Context Caching
-1. **Recent messages** - Token-limited conversation history
-2. **Summaries** (if `summary=True`) - Auto-generated at intervals (every ~20 messages)
-3. **Working representation** (if `peer_target` set) - Honcho's conclusions about the target peer:
- - Observations from interactions
- - Inferred insights and preferences
- - Things explicitly stated with certainty
-4. **Peer card** (if `peer_target` set) - Structured metadata:
- - User preferences and settings
- - Demographics
- - Custom fields
+For applications with frequent context retrieval, consider caching context when appropriate:
-### Parameter Reference
+
+```python Python
+# Cache context for multiple LLM calls within the same request
+context = session.get_context(tokens=2000)
+openai_messages = context.to_openai(assistant=assistant)
+anthropic_messages = context.to_anthropic(assistant=assistant)
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `tokens` | int | 1500 | Maximum tokens for the context |
-| `summary` | bool | True | Include auto-generated summaries |
-| `peer_target` | Peer | None | Include this peer's representation & card |
-| `peer_perspective` | Peer | None | Get target peer from this peer's POV (requires `peer_target`) |
-| `last_user_message` | str \| Message | None | Retrieve observations relevant to this message (works best with `peer_target`) |
+# Use the same context object for multiple format conversions
+```
-### Format Conversion Methods
+```typescript TypeScript
+(async () => {
+ // Cache context for multiple LLM calls within the same request
+ const context = await session.getContext({ tokens: 2000 });
+ const openaiMessages = context.toOpenAI(assistant);
+ const anthropicMessages = context.toAnthropic(assistant);
-**`context.to_openai(assistant)`** - Converts to OpenAI format
-- Requires: `assistant` peer to determine role mapping
-- Returns: List of dicts with `{"role": "...", "content": "..."}`
-- Messages from `assistant` → `role: "assistant"`
-- All other peers → `role: "user"`
+ // Use the same context object for multiple format conversions
+})();
+```
+
-**`context.to_anthropic(assistant)`** - Converts to Anthropic format
-- Requires: `assistant` peer to determine role mapping
-- Returns: List of dicts in Claude's message format
-- Same role mapping as OpenAI
+### 3. Error Handling
+
+Always handle potential errors when working with context:
+
+
+```python Python
+try:
+ context = session.get_context(tokens=2000)
+ messages = context.to_openai(assistant=assistant)
+
+ # Use messages with LLM API
+ response = openai_client.chat.completions.create(
+ model="gpt-4",
+ messages=messages
+ )
+
+except Exception as e:
+ print(f"Error getting context: {e}")
+ # Handle error appropriately
+```
+
+```typescript TypeScript
+(async () => {
+ try {
+ const context = await session.getContext({ tokens: 2000 });
+ const messages = context.toOpenAI(assistant);
+
+ // Use messages with LLM API
+ const response = await openai.chat.completions.create({
+ model: "gpt-4",
+ messages: messages
+ });
+
+ } catch (error) {
+ console.error(`Error getting context: ${error}`);
+ // Handle error appropriately
+ }
+})();
+```
+
+
+## Conclusion
+
+The `get_context()` method is essential for integrating Honcho sessions with LLMs. By understanding how to:
+
+- Retrieve context with appropriate parameters
+- Convert context to LLM-specific formats
+- Manage token limits and summaries
+- Handle multi-turn conversations
+
+You can build sophisticated AI applications that maintain conversation history and context across interactions while integrating seamlessly with popular LLM providers.
\ No newline at end of file
diff --git a/docs/v2/documentation/reference/sdk.mdx b/docs/v2/documentation/reference/sdk.mdx
index 47d13150..d9a8ad15 100644
--- a/docs/v2/documentation/reference/sdk.mdx
+++ b/docs/v2/documentation/reference/sdk.mdx
@@ -278,6 +278,17 @@ results = alice.search("programming")
metadata = alice.get_metadata()
metadata["location"] = "Paris"
alice.set_metadata(metadata)
+
+# Get peer context (representation + peer card in one call)
+context = alice.get_context()
+context = alice.get_context(target="bob") # What alice knows about bob
+
+# Get working representation with semantic search
+rep = alice.working_rep(search_query="preferences", search_top_k=10)
+
+# Access observations
+self_observations = alice.observations.list() # Self-observations
+bob_observations = alice.observations_of("bob").list() # Observations of bob
```
```typescript TypeScript
@@ -318,6 +329,109 @@ await alice.setMetadata({
...metadata,
location: "Paris"
});
+
+// Get peer context (representation + peer card in one call)
+const context = await alice.getContext();
+const targetContext = await alice.getContext("bob"); // What alice knows about bob
+
+// Get working representation with semantic search
+const rep = await alice.workingRep(undefined, undefined, {
+ searchQuery: "preferences",
+ searchTopK: 10
+});
+
+// Access observations
+const selfObs = await alice.observations.list(); // Self-observations
+const bobObs = await alice.observationsOf("bob").list(); // Observations of bob
+```
+
+
+### Peer Context
+
+The `get_context()` method on peers retrieves both the working representation and peer card in a single API call:
+
+
+```python Python
+# Get peer's own context
+context = alice.get_context()
+print(context.representation) # Working representation
+print(context.peer_card) # Peer card as list of strings
+
+# Get context about another peer (what alice knows about bob)
+bob_context = alice.get_context(target="bob")
+
+# Get context with semantic search
+context = alice.get_context(
+ target="bob",
+ search_query="work preferences",
+ search_top_k=10,
+ search_max_distance=0.8,
+ include_most_derived=True,
+ max_observations=50
+)
+```
+
+```typescript TypeScript
+// Get peer's own context
+const context = await alice.getContext();
+console.log(context.representation); // Working representation
+console.log(context.peerCard); // Peer card as array of strings
+
+// Get context about another peer (what alice knows about bob)
+const bobContext = await alice.getContext("bob");
+
+// Get context with semantic search
+const searchedContext = await alice.getContext("bob", {
+ searchQuery: "work preferences",
+ searchTopK: 10,
+ searchMaxDistance: 0.8,
+ includeMostDerived: true,
+ maxObservations: 50
+});
+```
+
+
+### Observations
+
+Peers can access their observations (facts derived from messages) through the `observations` property and `observations_of()` method:
+
+
+```python Python
+# Access self-observations (what honcho knows about alice)
+self_obs = alice.observations
+
+# List self-observations
+obs_list = self_obs.list()
+
+# Search self-observations semantically
+results = self_obs.query("food preferences")
+
+# Delete an observation
+self_obs.delete("observation-id")
+
+# Access observations of another peer (what alice knows about bob)
+bob_obs = alice.observations_of("bob")
+bob_obs_list = bob_obs.list()
+bob_search = bob_obs.query("work history")
+```
+
+```typescript TypeScript
+// Access self-observations (what honcho knows about alice)
+const selfObs = alice.observations;
+
+// List self-observations
+const obsList = await selfObs.list();
+
+// Search self-observations semantically
+const results = await selfObs.query("food preferences");
+
+// Delete an observation
+await selfObs.delete("observation-id");
+
+// Access observations of another peer (what alice knows about bob)
+const bobObs = alice.observationsOf("bob");
+const bobObsList = await bobObs.list();
+const bobSearch = await bobObs.query("work history");
```
@@ -361,12 +475,42 @@ messages = session.get_messages()
# Get conversation context
context = session.get_context(summary=True, tokens=2000)
+# Get context with peer representation included
+context = session.get_context(
+ tokens=2000,
+ peer_target="user",
+ peer_perspective="assistant",
+ last_user_message="What are my preferences?",
+ limit_to_session=True,
+ search_top_k=10,
+ search_max_distance=0.8,
+ include_most_derived=True,
+ max_observations=25
+)
+
# Search session content
results = session.search("help")
-# Working representation queries
+# Working representation queries with semantic search
global_rep = session.working_rep("alice")
-targeted_rep = session.working_rep(alice, bob)
+targeted_rep = session.working_rep(alice, target=bob)
+searched_rep = session.working_rep(
+ "alice",
+ search_query="preferences",
+ search_top_k=10,
+ include_most_derived=True
+)
+
+# Upload a file to create messages
+messages = session.upload_file(
+ file=open("document.pdf", "rb"),
+ peer_id="user",
+ metadata={"source": "upload"},
+ created_at="2024-01-15T10:30:00Z"
+)
+
+# Delete session (async - returns 202)
+session.delete()
# Metadata management
session.set_metadata({"topic": "product planning", "status": "active"})
@@ -402,12 +546,43 @@ const messages = await session.getMessages();
// Get conversation context
const context = await session.getContext({ summary: true, tokens: 2000 });
+// Get context with peer representation included
+const richContext = await session.getContext({
+ tokens: 2000,
+ peerTarget: "user",
+ peerPerspective: "assistant",
+ lastUserMessage: "What are my preferences?",
+ limitToSession: true,
+ searchTopK: 10,
+ searchMaxDistance: 0.8,
+ includeMostDerived: true,
+ maxObservations: 25
+});
+
// Search session content
const results = await session.search("help");
-// Working representation queries
+// Working representation queries with semantic search
const globalRep = await session.workingRep("alice");
-const targetedRep = await session.workingRep(alice, bob);
+const targetedRep = await session.workingRep(alice, { target: bob });
+const searchedRep = await session.workingRep("alice", undefined, {
+ searchQuery: "preferences",
+ searchTopK: 10,
+ includeMostDerived: true
+});
+
+// Upload a file to create messages
+const messages = await session.uploadFile(
+ fileBuffer,
+ "user",
+ {
+ metadata: { source: "upload" },
+ createdAt: "2024-01-15T10:30:00Z"
+ }
+);
+
+// Delete session (async - returns 202)
+await session.delete();
// Metadata management
await session.setMetadata({
@@ -494,10 +669,27 @@ The SessionContext object has the following structure:
"message_id": 123,
"summary_type": "short|long",
"created_at": "2024-01-15T10:30:00Z"
- }
+ },
+ "peer_representation": "string (optional)",
+ "peer_card": ["string"] // optional, included when peer_target is provided
}
```
+**Session Context Parameters:**
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `summary` | `bool` | Whether to include summary (default: true) |
+| `tokens` | `int` | Maximum tokens to include |
+| `peer_target` | `str` | Peer ID to get representation for |
+| `peer_perspective` | `str` | Peer ID for perspective (requires peer_target) |
+| `last_user_message` | `str` | Most recent message for semantic search |
+| `limit_to_session` | `bool` | Limit representation to session only |
+| `search_top_k` | `int` | Number of semantic search results (1-100) |
+| `search_max_distance` | `float` | Max semantic distance (0.0-1.0) |
+| `include_most_derived` | `bool` | Include most derived observations |
+| `max_observations` | `int` | Max observations to include (1-100) |
+
## Advanced Usage
### Multi-Party Conversations
@@ -757,4 +949,4 @@ for await (const peer of await honcho.getPeers()) {
// Process one peer at a time without loading all into memory
}
```
-
+
\ No newline at end of file
diff --git a/docs/v2/documentation/scratch/working-rep.mdx b/docs/v2/documentation/scratch/working-rep.mdx
index 0f7dc2c5..43659074 100644
--- a/docs/v2/documentation/scratch/working-rep.mdx
+++ b/docs/v2/documentation/scratch/working-rep.mdx
@@ -22,7 +22,7 @@ Working representations are automatically generated and cached through Honcho's
## Basic Usage
-Working representations are accessed through the `working_rep()` method on Session objects:
+Working representations are accessed through the `working_rep()` method on Session or Peer objects:
```python Python
@@ -50,6 +50,9 @@ response = user.chat("What is this user's main concern right now?", session_id=s
# Retrieve the cached working representation for the user
user_representation = session.working_rep("user-123")
print("Cached user representation:", user_representation)
+
+# Or access from the peer directly
+peer_representation = user.working_rep()
```
```typescript TypeScript
@@ -77,7 +80,76 @@ const response = await user.chat("What is this user's main concern right now?",
// Retrieve the cached working representation for the user
const userRepresentation = await session.workingRep("user-123");
console.log("Cached user representation:", userRepresentation);
-// Returns: { representation: Object }
+
+// Or access from the peer directly
+const peerRepresentation = await user.workingRep();
+```
+
+
+## Semantic Search in Representations
+
+Working representations support semantic search to retrieve the most relevant observations for a given query. This is useful when you want to focus the representation on specific topics.
+
+### Parameters
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `search_query` | `str` | Semantic search query to filter relevant observations |
+| `search_top_k` | `int` | Number of semantic search results to include (1-100) |
+| `search_max_distance` | `float` | Maximum semantic distance threshold (0.0-1.0) |
+| `include_most_derived` | `bool` | Whether to include the most recently derived observations |
+| `max_observations` | `int` | Maximum number of observations to include (1-100) |
+
+
+```python Python
+# Get representation focused on a specific topic
+billing_rep = session.working_rep(
+ "user-123",
+ search_query="billing and payment issues",
+ search_top_k=10,
+ search_max_distance=0.8,
+ include_most_derived=True,
+ max_observations=25
+)
+
+# Get representation from peer with target
+# What user-123 knows about the assistant
+local_rep = session.working_rep(
+ "user-123",
+ target="ai-assistant",
+ search_query="support interactions"
+)
+
+# Access from peer object with semantic search
+user_rep = user.working_rep(
+ session=session,
+ search_query="preferences",
+ search_top_k=5
+)
+```
+
+```typescript TypeScript
+// Get representation focused on a specific topic
+const billingRep = await session.workingRep("user-123", {
+ searchQuery: "billing and payment issues",
+ searchTopK: 10,
+ searchMaxDistance: 0.8,
+ includeMostDerived: true,
+ maxObservations: 25
+});
+
+// Get representation from peer with target
+// What user-123 knows about the assistant
+const localRep = await session.workingRep("user-123", {
+ target: "ai-assistant",
+ searchQuery: "support interactions"
+});
+
+// Access from peer object with semantic search
+const userRep = await user.workingRep(session, undefined, {
+ searchQuery: "preferences",
+ searchTopK: 5
+});
```
@@ -272,4 +344,4 @@ Working representations provide fast access to cached psychological models that
- Handle cases where representations aren't available
- Combine cached and fresh analysis appropriately
-You can build efficient applications that leverage Honcho's continuous learning about peer knowledge and mental states without the latency of real-time generation.
+You can build efficient applications that leverage Honcho's continuous learning about peer knowledge and mental states without the latency of real-time generation.
\ No newline at end of file
diff --git a/docs/v2/guides/storing-data.mdx b/docs/v2/guides/storing-data.mdx
index a68fbd3f..c8dca007 100644
--- a/docs/v2/guides/storing-data.mdx
+++ b/docs/v2/guides/storing-data.mdx
@@ -18,7 +18,7 @@ A `Message` is sent by a `Peer` and saved in a `Session`
session = honcho.session("sample-session")
- message = peer.message("Hello, world!", session_id=session.id)
+ message = peer.message("Hello, world!")
session.add_messages([message])
```
@@ -42,7 +42,7 @@ Once a `Message` is saved in Honcho, it will kick off a background task that
looks at the new data to generate insights about the `Peer` that sent the `Message`
This is the default behavior of Honcho and can be turned off by [configuring the
-Peer or Session](/v2/documentation/features/advanced/configuration)
+Peer or Session](/v2/documentation/core-concepts/configuration)
This pattern of having a Peer, Session, and Messages is highly flexible and
works for many different use cases and agent setups. Some use cases may only
@@ -58,4 +58,4 @@ In this case you can simply
- Make a `Peer` for the AI
Then you can make a `Session` for each thread of conversation and save
-`Messages` from the user and assistant in each turn of conversation
+`Messages` from the user and assistant in each turn of conversation
\ No newline at end of file