diff --git a/docs/docs.json b/docs/docs.json index e8651ecd..c57b1f3e 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -41,28 +41,19 @@ "group": "Core Concepts", "pages": [ "v2/documentation/core-concepts/architecture", - "v2/documentation/core-concepts/reasoning", - "v2/documentation/core-concepts/representation" - ] - }, - { - "group": "Features", - "pages": [ - "v2/documentation/features/get-context", - "v2/documentation/features/chat", - { - "group": "Advanced", - "pages": [ - "v2/documentation/features/advanced/overview", - "v2/documentation/features/advanced/queue-status", - "v2/documentation/features/advanced/toggle-reasoning", - "v2/documentation/features/advanced/representation-scopes", - "v2/documentation/features/advanced/summarizer", - "v2/documentation/features/advanced/search", - "v2/documentation/features/advanced/using-filters", - "v2/documentation/features/advanced/streaming-response" - ] - } + "v2/documentation/core-concepts/features/storing-data", + "v2/documentation/core-concepts/features/dialectic-endpoint", + "v2/documentation/core-concepts/features/get-context", + "v2/documentation/core-concepts/features/search", + "v2/documentation/core-concepts/features/working-rep", + "v2/documentation/core-concepts/features/streaming-response", + "v2/documentation/core-concepts/features/using-filters", + "v2/documentation/core-concepts/features/file-uploads", + "v2/documentation/core-concepts/features/queue-status", + "v2/documentation/core-concepts/features/local-vs-global", + "v2/documentation/core-concepts/configuration", + "v2/documentation/core-concepts/summarizer", + "v2/documentation/core-concepts/glossary" ] }, { @@ -75,32 +66,30 @@ ] }, { - "tab": "Guides", + "tab": "Spellbooks", "groups": [ { - "group": "Overview", + "group": "Getting Started", "pages": [ - "v2/guides/overview", - "v2/guides/file-uploads", - "v2/guides/storing-data" - ] - }, - { - "group": "Integrations", - "pages": [ - "v2/guides/integrations/crewai", - "v2/guides/integrations/langgraph", - "v2/guides/integrations/mcp" + "v2/guides/overview" ] }, { "group": "Migrations", "pages": [ - "v2/guides/migrations/mem0" + "v2/migrations/from-mem0" ] }, { - "group": "Chatbots", + "group": "Integrations", + "pages": [ + "v2/integrations/crewai", + "v2/integrations/langgraph", + "v2/integrations/mcp" + ] + }, + { + "group": "Application Interfaces", "pages": [ "v2/guides/discord", "v2/guides/telegram" @@ -108,25 +97,6 @@ } ] }, - { - "tab": "Open Source", - "groups": [ - { - "group": "Self-Hosting", - "pages": [ - "v2/contributing/self-hosting", - "v2/contributing/configuration" - ] - }, - { - "group": "Contributing", - "pages": [ - "v2/contributing/guidelines", - "v2/contributing/license" - ] - } - ] - }, { "tab": "API Reference", "groups": [ @@ -219,6 +189,235 @@ } ] }, + { + "tab": "Changelog", + "groups": [ + { + "group": "Overview", + "pages": [ + "changelog/introduction", + "changelog/compatibility-guide" + ] + } + ] + }, + { + "tab": "Contributing", + "groups": [ + { + "group": "Contributing", + "pages": [ + "v2/contributing/guidelines", + "v2/contributing/self-hosting", + "v2/contributing/configuration", + "v2/contributing/license" + ] + } + ] + } + ] + }, + { + "version": "v2.6.0-alpha", + "api": { + "openapi": [ + "openapi.json" + ] + }, + "tabs": [ + { + "tab": "Documentation", + "groups": [ + { + "group": "Introduction", + "pages": [ + "v2.6.0-alpha/documentation/introduction/overview", + "v2.6.0-alpha/documentation/introduction/quickstart", + "v2.6.0-alpha/documentation/introduction/vibecoding" + ] + }, + { + "group": "Core Concepts", + "pages": [ + "v2.6.0-alpha/documentation/core-concepts/architecture", + "v2.6.0-alpha/documentation/core-concepts/reasoning", + "v2.6.0-alpha/documentation/core-concepts/representation" + ] + }, + { + "group": "Features", + "pages": [ + "v2.6.0-alpha/documentation/features/get-context", + "v2.6.0-alpha/documentation/features/chat", + { + "group": "Advanced", + "pages": [ + "v2.6.0-alpha/documentation/features/advanced/overview", + "v2.6.0-alpha/documentation/features/advanced/queue-status", + "v2.6.0-alpha/documentation/features/advanced/toggle-reasoning", + "v2.6.0-alpha/documentation/features/advanced/representation-scopes", + "v2.6.0-alpha/documentation/features/advanced/summarizer", + "v2.6.0-alpha/documentation/features/advanced/search", + "v2.6.0-alpha/documentation/features/advanced/using-filters", + "v2.6.0-alpha/documentation/features/advanced/streaming-response" + ] + } + ] + }, + { + "group": "Reference", + "pages": [ + "v2.6.0-alpha/documentation/reference/platform", + "v2.6.0-alpha/documentation/reference/sdk" + ] + } + ] + }, + { + "tab": "Guides", + "groups": [ + { + "group": "Overview", + "pages": [ + "v2.6.0-alpha/guides/overview", + "v2.6.0-alpha/guides/file-uploads", + "v2.6.0-alpha/guides/storing-data" + ] + }, + { + "group": "Integrations", + "pages": [ + "v2.6.0-alpha/guides/integrations/crewai", + "v2.6.0-alpha/guides/integrations/langgraph", + "v2.6.0-alpha/guides/integrations/mcp" + ] + }, + { + "group": "Migrations", + "pages": [ + "v2.6.0-alpha/guides/migrations/mem0" + ] + }, + { + "group": "Chatbots", + "pages": [ + "v2.6.0-alpha/guides/discord", + "v2.6.0-alpha/guides/telegram" + ] + } + ] + }, + { + "tab": "Open Source", + "groups": [ + { + "group": "Self-Hosting", + "pages": [ + "v2.6.0-alpha/contributing/self-hosting", + "v2.6.0-alpha/contributing/configuration" + ] + }, + { + "group": "Contributing", + "pages": [ + "v2.6.0-alpha/contributing/guidelines", + "v2.6.0-alpha/contributing/license" + ] + } + ] + }, + { + "tab": "API Reference", + "groups": [ + { + "group": "API Documentation", + "pages": [ + "v2.6.0-alpha/api-reference/introduction" + ] + }, + { + "group": "workspaces", + "pages": [ + "v2.6.0-alpha/api-reference/endpoint/workspaces/get-or-create-workspace", + "v2.6.0-alpha/api-reference/endpoint/workspaces/get-all-workspaces", + "v2.6.0-alpha/api-reference/endpoint/workspaces/update-workspace", + "v2.6.0-alpha/api-reference/endpoint/workspaces/delete-workspace", + "v2.6.0-alpha/api-reference/endpoint/workspaces/search-workspace", + "v2.6.0-alpha/api-reference/endpoint/workspaces/get-deriver-status", + "v2.6.0-alpha/api-reference/endpoint/workspaces/trigger-dream" + ] + }, + { + "group": "peers", + "pages": [ + "v2.6.0-alpha/api-reference/endpoint/peers/get-peers", + "v2.6.0-alpha/api-reference/endpoint/peers/get-or-create-peer", + "v2.6.0-alpha/api-reference/endpoint/peers/update-peer", + "v2.6.0-alpha/api-reference/endpoint/peers/get-sessions-for-peer", + "v2.6.0-alpha/api-reference/endpoint/peers/chat", + "v2.6.0-alpha/api-reference/endpoint/peers/get-working-representation", + "v2.6.0-alpha/api-reference/endpoint/peers/get-peer-card", + "v2.6.0-alpha/api-reference/endpoint/peers/set-peer-card", + "v2.6.0-alpha/api-reference/endpoint/peers/get-peer-context", + "v2.6.0-alpha/api-reference/endpoint/peers/search-peer" + ] + }, + { + "group": "sessions", + "pages": [ + "v2.6.0-alpha/api-reference/endpoint/sessions/get-or-create-session", + "v2.6.0-alpha/api-reference/endpoint/sessions/get-sessions", + "v2.6.0-alpha/api-reference/endpoint/sessions/update-session", + "v2.6.0-alpha/api-reference/endpoint/sessions/delete-session", + "v2.6.0-alpha/api-reference/endpoint/sessions/clone-session", + "v2.6.0-alpha/api-reference/endpoint/sessions/get-session-peers", + "v2.6.0-alpha/api-reference/endpoint/sessions/set-session-peers", + "v2.6.0-alpha/api-reference/endpoint/sessions/add-peers-to-session", + "v2.6.0-alpha/api-reference/endpoint/sessions/remove-peers-from-session", + "v2.6.0-alpha/api-reference/endpoint/sessions/get-peer-config", + "v2.6.0-alpha/api-reference/endpoint/sessions/set-peer-config", + "v2.6.0-alpha/api-reference/endpoint/sessions/get-session-context", + "v2.6.0-alpha/api-reference/endpoint/sessions/get-session-summaries", + "v2.6.0-alpha/api-reference/endpoint/sessions/search-session" + ] + }, + { + "group": "messages", + "pages": [ + "v2.6.0-alpha/api-reference/endpoint/messages/create-messages-for-session", + "v2.6.0-alpha/api-reference/endpoint/messages/get-messages", + "v2.6.0-alpha/api-reference/endpoint/messages/get-message", + "v2.6.0-alpha/api-reference/endpoint/messages/update-message", + "v2.6.0-alpha/api-reference/endpoint/messages/create-messages-with-file" + ] + }, + { + "group": "observations", + "pages": [ + "v2.6.0-alpha/api-reference/endpoint/observations/create-observations", + "v2.6.0-alpha/api-reference/endpoint/observations/list-observations", + "v2.6.0-alpha/api-reference/endpoint/observations/query-observations", + "v2.6.0-alpha/api-reference/endpoint/observations/delete-observation" + ] + }, + { + "group": "webhooks", + "pages": [ + "v2.6.0-alpha/api-reference/endpoint/webhooks/list-webhook-endpoints", + "v2.6.0-alpha/api-reference/endpoint/webhooks/get-or-create-webhook-endpoint", + "v2.6.0-alpha/api-reference/endpoint/webhooks/delete-webhook-endpoint", + "v2.6.0-alpha/api-reference/endpoint/webhooks/test-emit" + ] + }, + { + "group": "miscellaneous", + "pages": [ + "v2.6.0-alpha/api-reference/endpoint/keys/create-key", + "v2.6.0-alpha/api-reference/endpoint/metrics" + ] + } + ] + }, { "tab": "Changelog", "groups": [ diff --git a/docs/v2.6.0-alpha/README.md b/docs/v2.6.0-alpha/README.md new file mode 100644 index 00000000..8939faa1 --- /dev/null +++ b/docs/v2.6.0-alpha/README.md @@ -0,0 +1 @@ +This subdirectory contains the peer-paradigm documentation for Honcho (Honcho v2.0.0 onwards). diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/keys/create-key.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/keys/create-key.mdx new file mode 100644 index 00000000..41b759f7 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/keys/create-key.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/keys +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/messages/create-messages-for-session.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/messages/create-messages-for-session.mdx new file mode 100644 index 00000000..19e9c9cb --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/messages/create-messages-for-session.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/sessions/{session_id}/messages/ +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/messages/create-messages-with-file.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/messages/create-messages-with-file.mdx new file mode 100644 index 00000000..55ca55a8 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/messages/create-messages-with-file.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/sessions/{session_id}/messages/upload +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/messages/get-message.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/messages/get-message.mdx new file mode 100644 index 00000000..53765daa --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/messages/get-message.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/sessions/{session_id}/messages/{message_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/messages/get-messages.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/messages/get-messages.mdx new file mode 100644 index 00000000..612c7aab --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/messages/get-messages.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/sessions/{session_id}/messages/list +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/messages/update-message.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/messages/update-message.mdx new file mode 100644 index 00000000..77a296b2 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/messages/update-message.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/workspaces/{workspace_id}/sessions/{session_id}/messages/{message_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/metrics.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/metrics.mdx new file mode 100644 index 00000000..00ca0fca --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/metrics.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /metrics +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/observations/create-observations.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/observations/create-observations.mdx new file mode 100644 index 00000000..1aafec44 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/observations/create-observations.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/observations +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/observations/delete-observation.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/observations/delete-observation.mdx new file mode 100644 index 00000000..172ef679 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/observations/delete-observation.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /v2/workspaces/{workspace_id}/observations/{observation_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/observations/list-observations.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/observations/list-observations.mdx new file mode 100644 index 00000000..3063a96e --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/observations/list-observations.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/observations/list +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/observations/query-observations.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/observations/query-observations.mdx new file mode 100644 index 00000000..d5d15a14 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/observations/query-observations.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/observations/query +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/chat.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/chat.mdx new file mode 100644 index 00000000..8fe3cd18 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/chat.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/peers/{peer_id}/chat +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-or-create-peer.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-or-create-peer.mdx new file mode 100644 index 00000000..724d8100 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-or-create-peer.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/peers +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peer-card.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peer-card.mdx new file mode 100644 index 00000000..ef12d719 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peer-card.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/peers/{peer_id}/card +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peer-context.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peer-context.mdx new file mode 100644 index 00000000..ed6563c2 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peer-context.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/peers/{peer_id}/context +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peers.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peers.mdx new file mode 100644 index 00000000..954e89b2 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-peers.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/peers/list +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-sessions-for-peer.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-sessions-for-peer.mdx new file mode 100644 index 00000000..8b33a832 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-sessions-for-peer.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/peers/{peer_id}/sessions +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-working-representation.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-working-representation.mdx new file mode 100644 index 00000000..b712a032 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/get-working-representation.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/peers/{peer_id}/representation +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/search-peer.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/search-peer.mdx new file mode 100644 index 00000000..c8c25451 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/search-peer.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/peers/{peer_id}/search +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/set-peer-card.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/set-peer-card.mdx new file mode 100644 index 00000000..c209ca8c --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/set-peer-card.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/workspaces/{workspace_id}/peers/{peer_id}/card +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/peers/update-peer.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/peers/update-peer.mdx new file mode 100644 index 00000000..91b6da61 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/peers/update-peer.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/workspaces/{workspace_id}/peers/{peer_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/add-peers-to-session.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/add-peers-to-session.mdx new file mode 100644 index 00000000..e73ece96 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/add-peers-to-session.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/sessions/{session_id}/peers +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/clone-session.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/clone-session.mdx new file mode 100644 index 00000000..e06f19a1 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/clone-session.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/sessions/{session_id}/clone +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/delete-session.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/delete-session.mdx new file mode 100644 index 00000000..2d1252fb --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/delete-session.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /v2/workspaces/{workspace_id}/sessions/{session_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-or-create-session.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-or-create-session.mdx new file mode 100644 index 00000000..c013803e --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-or-create-session.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/sessions +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-peer-config.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-peer-config.mdx new file mode 100644 index 00000000..e84f5cea --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-peer-config.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/sessions/{session_id}/peers/{peer_id}/config +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-context.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-context.mdx new file mode 100644 index 00000000..c8c1bdd1 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-context.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/sessions/{session_id}/context +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-peers.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-peers.mdx new file mode 100644 index 00000000..18beb221 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-peers.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/sessions/{session_id}/peers +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-summaries.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-summaries.mdx new file mode 100644 index 00000000..9ae150bc --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-session-summaries.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/sessions/{session_id}/summaries +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-sessions.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-sessions.mdx new file mode 100644 index 00000000..75dc7eba --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/get-sessions.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/sessions/list +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/remove-peers-from-session.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/remove-peers-from-session.mdx new file mode 100644 index 00000000..31acf6bf --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/remove-peers-from-session.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /v2/workspaces/{workspace_id}/sessions/{session_id}/peers +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/search-session.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/search-session.mdx new file mode 100644 index 00000000..308138d5 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/search-session.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/sessions/{session_id}/search +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/set-peer-config.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/set-peer-config.mdx new file mode 100644 index 00000000..6e6ee462 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/set-peer-config.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/sessions/{session_id}/peers/{peer_id}/config +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/set-session-peers.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/set-session-peers.mdx new file mode 100644 index 00000000..475db5b9 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/set-session-peers.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/workspaces/{workspace_id}/sessions/{session_id}/peers +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/sessions/update-session.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/update-session.mdx new file mode 100644 index 00000000..94d14d1b --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/sessions/update-session.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/workspaces/{workspace_id}/sessions/{session_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/delete-webhook-endpoint.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/delete-webhook-endpoint.mdx new file mode 100644 index 00000000..03663d39 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/delete-webhook-endpoint.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /v2/workspaces/{workspace_id}/webhooks/{endpoint_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/get-or-create-webhook-endpoint.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/get-or-create-webhook-endpoint.mdx new file mode 100644 index 00000000..3eca8afb --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/get-or-create-webhook-endpoint.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/webhooks +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/list-webhook-endpoints.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/list-webhook-endpoints.mdx new file mode 100644 index 00000000..a205df80 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/list-webhook-endpoints.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/webhooks +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/test-emit.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/test-emit.mdx new file mode 100644 index 00000000..8c2cbddd --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/webhooks/test-emit.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/webhooks/test +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/delete-workspace.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/delete-workspace.mdx new file mode 100644 index 00000000..f8eb6168 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/delete-workspace.mdx @@ -0,0 +1,3 @@ +--- +openapi: delete /v2/workspaces/{workspace_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-all-workspaces.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-all-workspaces.mdx new file mode 100644 index 00000000..12e3d931 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-all-workspaces.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/list +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-deriver-status.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-deriver-status.mdx new file mode 100644 index 00000000..0b7a32b9 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-deriver-status.mdx @@ -0,0 +1,3 @@ +--- +openapi: get /v2/workspaces/{workspace_id}/deriver/status +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-or-create-workspace.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-or-create-workspace.mdx new file mode 100644 index 00000000..513f4fbb --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/get-or-create-workspace.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/search-workspace.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/search-workspace.mdx new file mode 100644 index 00000000..f17e4e52 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/search-workspace.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/search +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/trigger-dream.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/trigger-dream.mdx new file mode 100644 index 00000000..138c58be --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/trigger-dream.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /v2/workspaces/{workspace_id}/trigger_dream +--- diff --git a/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/update-workspace.mdx b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/update-workspace.mdx new file mode 100644 index 00000000..07d3b75e --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/endpoint/workspaces/update-workspace.mdx @@ -0,0 +1,3 @@ +--- +openapi: put /v2/workspaces/{workspace_id} +--- diff --git a/docs/v2.6.0-alpha/api-reference/introduction.mdx b/docs/v2.6.0-alpha/api-reference/introduction.mdx new file mode 100644 index 00000000..6765e7a3 --- /dev/null +++ b/docs/v2.6.0-alpha/api-reference/introduction.mdx @@ -0,0 +1,27 @@ +--- +title: 'Introduction' +--- + +This section documents all available API endpoints in the Honcho Server. Each +endpoint provides CRUD operations for our core primitives. For information +about these primitives, see +[Architecture](/v2/documentation/core-concepts/architecture). + + + We strongly recommend using our official SDKs instead of calling these APIs directly. The SDKs provide better error handling, type safety, and developer experience. + + +## Recommended approach + +Use our official SDKs for the best development experience: +- [Python SDK](https://pypi.org/project/honcho-ai/) +- [TypeScript SDK](https://www.npmjs.com/package/@honcho-ai/sdk) + +## When to use this API reference + +This reference is primarily useful for: +- Debugging SDK behavior +- Building integrations in unsupported languages +- Understanding the underlying data structures + +The endpoints pages are autogenerated and include interactive examples for testing. diff --git a/docs/v2.6.0-alpha/contributing/configuration.mdx b/docs/v2.6.0-alpha/contributing/configuration.mdx new file mode 100644 index 00000000..59cf5a73 --- /dev/null +++ b/docs/v2.6.0-alpha/contributing/configuration.mdx @@ -0,0 +1,638 @@ +--- +title: "Configuration Guide" +description: "Complete guide to configuring Honcho for development and production" +icon: "gear" +--- + +Honcho uses a flexible configuration system that supports both TOML files and environment variables. Configuration values are loaded in the following priority order (highest to lowest): + +1. Environment variables (always take precedence) +2. `.env` file (for local development) +3. `config.toml` file (base configuration) +4. Default values + +## Recommended Configuration Approaches + +### Option 1: Environment Variables Only (Production) +- Use environment variables for all configuration +- No config files needed +- Ideal for containerized deployments (Docker, Kubernetes) +- Secrets managed by your deployment platform + +### Option 2: config.toml (Development/Simple Deployments) +- Use config.toml for base configuration +- Override sensitive values with environment variables +- Good for development and simple deployments + +### Option 3: Hybrid Approach +- Use config.toml for non-sensitive base settings +- Use .env file for sensitive values (API keys, secrets) +- Good for development teams + +### Option 4: .env Only (Local Development) +- Use .env file for all configuration +- Simple for local development +- Never commit .env files to version control + +## Configuration Methods + +### Using config.toml + +Copy the example configuration file to get started: + +```bash +cp config.toml.example config.toml +``` + +Then modify the values as needed. The TOML file is organized into sections: + +- `[app]` - Application-level settings (log level, session limits, embedding settings, Langfuse integration, local metrics collection) +- `[db]` - Database connection and pool settings (connection URI, pool size, timeouts, connection recycling) +- `[auth]` - Authentication configuration (enable/disable auth, JWT secret) +- `[cache]` - Redis cache configuration (enable/disable caching, Redis URL, TTL settings, lock configuration for cache stampede prevention) +- `[llm]` - LLM provider API keys (Anthropic, OpenAI, Gemini, Groq, OpenAI-compatible endpoints) and general LLM settings +- `[dialectic]` - Dialectic API configuration (provider, model, query generation settings, semantic search parameters, context window size) +- `[deriver]` - Background worker settings (worker count, polling intervals, queue management) and theory of mind configuration (model, tokens, observation limits) +- `[peer_card]` - Peer card generation settings (provider, model, token limits) +- `[summary]` - Session summarization settings (frequency thresholds, provider, model, token limits for short and long summaries) +- `[dream]` - Dream processing configuration (enable/disable, thresholds, idle timeouts, dream types, LLM settings) +- `[webhook]` - Webhook configuration (webhook secret, workspace limits) +- `[metrics]` - Metrics collection settings (enable/disable metrics, namespace) +- `[sentry]` - Error tracking and monitoring settings (enable/disable, DSN, environment, sample rates) + +### Using Environment Variables + +All configuration values can be overridden using environment variables. The environment variable names follow this pattern: + +- `{SECTION}_{KEY}` for nested settings +- Just `{KEY}` for app-level settings + +Examples: + +- `DB_CONNECTION_URI` → `[db].CONNECTION_URI` +- `DB_POOL_SIZE` → `[db].POOL_SIZE` +- `AUTH_JWT_SECRET` → `[auth].JWT_SECRET` +- `DIALECTIC_MODEL` → `[dialectic].MODEL` +- `LOG_LEVEL` (no section) → `[app].LOG_LEVEL` + +### Configuration Priority + +When a configuration value is set in multiple places, Honcho uses this priority: + +1. **Environment variables** - Always take precedence +2. **.env file** - Loaded for local development +3. **config.toml** - Base configuration +4. **Default values** - Built-in defaults + +This allows you to: + +- Use `config.toml` for base configuration +- Override specific values with environment variables in production +- Use `.env` files for local development without modifying config.toml + +### Example + +If you have this in `config.toml`: + +```toml +[db] +CONNECTION_URI = "postgresql://localhost/honcho_dev" +POOL_SIZE = 10 +``` + +You can override just the connection URI in production: + +```bash +export DB_CONNECTION_URI="postgresql://prod-server/honcho_prod" +``` + +The application will use the production connection URI while keeping the pool size from config.toml. + +## Core Configuration + +### Application Settings + +Application-level settings control core behavior of the Honcho server including logging, session limits, message handling, and optional integrations. + +**Basic Application Configuration:** +```bash +# Logging and server settings +LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL + +# Session and context limits +SESSION_OBSERVERS_LIMIT=10 # Maximum number of observers per session +GET_CONTEXT_MAX_TOKENS=100000 # Maximum tokens for context retrieval +MAX_MESSAGE_SIZE=25000 # Maximum message size in characters + +# Embedding settings +EMBED_MESSAGES=true # Enable vector embeddings for messages +MAX_EMBEDDING_TOKENS=8192 # Maximum tokens per embedding +MAX_EMBEDDING_TOKENS_PER_REQUEST=300000 # Batch embedding limit +``` + +**Optional Integrations:** +```bash +# Langfuse integration for LLM observability +LANGFUSE_HOST=https://cloud.langfuse.com +LANGFUSE_PUBLIC_KEY=your-langfuse-public-key + +# Local metrics collection +COLLECT_METRICS_LOCAL=false +LOCAL_METRICS_FILE=metrics.jsonl +``` + +### Database Configuration + +**Required Database Settings:** +```bash +# PostgreSQL connection string (required) +DB_CONNECTION_URI=postgresql+psycopg://username:password@host:port/database + +# Example for local development +DB_CONNECTION_URI=postgresql+psycopg://postgres:postgres@localhost:5432/honcho + +# Example for production +DB_CONNECTION_URI=postgresql+psycopg://honcho_user:secure_password@db.example.com:5432/honcho_prod +``` + +**Database Pool Settings:** +```bash +# Connection pool configuration +DB_SCHEMA=public +DB_POOL_SIZE=10 +DB_MAX_OVERFLOW=20 +DB_POOL_TIMEOUT=30 +DB_POOL_RECYCLE=300 +DB_POOL_PRE_PING=true +DB_SQL_DEBUG=false +DB_TRACING=false +``` + +**Docker Compose for PostgreSQL:** +```yaml +# docker-compose.yml +version: '3.8' +services: + database: + image: pgvector/pgvector:pg15 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: honcho + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + - ./init.sql:/docker-entrypoint-initdb.d/init.sql + +volumes: + postgres_data: +``` + +### Authentication Configuration + +**JWT Authentication:** +```bash +# Enable/disable authentication +AUTH_USE_AUTH=false # Set to true for production + +# JWT settings (required if AUTH_USE_AUTH is true) +AUTH_JWT_SECRET=your-super-secret-jwt-key +``` + +**Generate JWT Secret:** +```bash +# Generate a secure JWT secret +python scripts/generate_jwt_secret.py +``` + +### Cache Configuration + +Honcho supports Redis caching to improve performance by caching frequently accessed data like peers, sessions, and working representations. Caching also includes lock mechanisms to prevent cache stampede scenarios. + +**Redis Cache Settings:** +```bash +# Enable/disable Redis caching +CACHE_ENABLED=false # Set to true to enable caching + +# Redis connection +CACHE_URL=redis://localhost:6379/0?suppress=true + +# Cache namespace and TTL +CACHE_NAMESPACE=honcho # Prefix for all cache keys +CACHE_DEFAULT_TTL_SECONDS=300 # How long items stay in cache (5 minutes) + +# Lock settings for preventing cache stampede +CACHE_DEFAULT_LOCK_TTL_SECONDS=5 # Lock duration when fetching from DB on cache miss +``` + +**When to Enable Caching:** +- High-traffic production environments +- Applications with many repeated reads of the same data +- When you need to reduce database load + +**Note:** Caching requires a Redis instance. You can run Redis locally with Docker: +```bash +docker run -d -p 6379:6379 redis:latest +``` + +## LLM Provider Configuration + +Honcho supports multiple LLM providers for different tasks. API keys are configured in the `[llm]` section, while specific features use their own configuration sections. + +### API Keys + +All provider API keys use the `LLM_` prefix: + +```bash +# Provider API Keys +LLM_ANTHROPIC_API_KEY=your-anthropic-api-key +LLM_OPENAI_API_KEY=your-openai-api-key +LLM_GEMINI_API_KEY=your-gemini-api-key +LLM_GROQ_API_KEY=your-groq-api-key + +# OpenAI-compatible endpoints +LLM_OPENAI_COMPATIBLE_API_KEY=your-api-key +LLM_OPENAI_COMPATIBLE_BASE_URL=https://your-openai-compatible-endpoint.com +``` + +### General LLM Settings + +```bash +# Default settings for all LLM calls +LLM_DEFAULT_MAX_TOKENS=2500 + +# Embedding provider (used when EMBED_MESSAGES=true) +LLM_EMBEDDING_PROVIDER=openai # Options: openai, gemini +``` + +### Feature-Specific Model Configuration + +Different features can use different providers and models: + +**Dialectic API:** + +The Dialectic API provides theory-of-mind informed responses by integrating long-term facts with current context. + +```bash +# Main dialectic model (default: Anthropic) +DIALECTIC_PROVIDER=anthropic +DIALECTIC_MODEL=claude-sonnet-4-20250514 +DIALECTIC_MAX_OUTPUT_TOKENS=2500 +DIALECTIC_THINKING_BUDGET_TOKENS=1024 # Only used with Anthropic provider +DIALECTIC_CONTEXT_WINDOW_SIZE=100000 # Maximum context window tokens + +# Query generation for dialectic searches +DIALECTIC_PERFORM_QUERY_GENERATION=false # Enable query generation for semantic search +DIALECTIC_QUERY_GENERATION_PROVIDER=groq +DIALECTIC_QUERY_GENERATION_MODEL=llama-3.1-8b-instant + +# Semantic search settings +DIALECTIC_SEMANTIC_SEARCH_TOP_K=10 # Number of results to retrieve +DIALECTIC_SEMANTIC_SEARCH_MAX_DISTANCE=0.85 # Maximum distance for relevance +``` + +**Deriver (Theory of Mind):** + +The Deriver is a background processing system that extracts facts from messages and builds theory-of-mind representations of peers. + +```bash +# LLM settings for deriver +DERIVER_PROVIDER=google +DERIVER_MODEL=gemini-2.5-flash-lite +DERIVER_MAX_OUTPUT_TOKENS=10000 +DERIVER_THINKING_BUDGET_TOKENS=1024 # Only used with Anthropic provider +DERIVER_MAX_INPUT_TOKENS=23000 # Maximum input tokens for deriver + +# Worker settings +DERIVER_WORKERS=1 # Number of background worker processes +DERIVER_POLLING_SLEEP_INTERVAL_SECONDS=1.0 # Time between queue checks +DERIVER_STALE_SESSION_TIMEOUT_MINUTES=5 # Timeout for stale sessions + +# Queue management +DERIVER_QUEUE_ERROR_RETENTION_SECONDS=2592000 # Keep errored items for 30 days + +# Working representation settings +DERIVER_WORKING_REPRESENTATION_MAX_OBSERVATIONS=50 # Max observations stored +DERIVER_REPRESENTATION_BATCH_MAX_TOKENS=4096 # Max tokens per batch +``` + +**Peer Card:** + +Peer cards are short, structured summaries of peer identity and characteristics. + +```bash +# Enable/disable peer card generation +PEER_CARD_ENABLED=true + +# LLM settings for peer card generation +PEER_CARD_PROVIDER=openai +PEER_CARD_MODEL=gpt-5-nano-2025-08-07 +PEER_CARD_MAX_OUTPUT_TOKENS=4000 # Includes thinking tokens for GPT-5 models +``` + +**Summary Generation:** + +Session summaries provide compressed context for long conversations. Honcho creates two types: short summaries (frequent) and long summaries (comprehensive). + +```bash +# Enable/disable summarization +SUMMARY_ENABLED=true + +# LLM settings for summary generation +SUMMARY_PROVIDER=openai +SUMMARY_MODEL=gpt-4o-mini-2024-07-18 +SUMMARY_MAX_TOKENS_SHORT=1000 # Max tokens for short summaries +SUMMARY_MAX_TOKENS_LONG=4000 # Max tokens for long summaries +SUMMARY_THINKING_BUDGET_TOKENS=512 # Only used with Anthropic provider + +# Summary frequency thresholds +SUMMARY_MESSAGES_PER_SHORT_SUMMARY=20 # Create short summary every N messages +SUMMARY_MESSAGES_PER_LONG_SUMMARY=60 # Create long summary every N messages +``` + +### Default Provider Usage + +By default, Honcho uses: +- **Anthropic** (Claude) for dialectic API responses +- **Groq** for query generation (fast, cost-effective) +- **Google** (Gemini) for theory of mind derivation +- **OpenAI** (GPT) for peer cards and summarization +- **OpenAI** for embeddings (if `EMBED_MESSAGES=true`) + +You only need to set the API keys for the providers you plan to use. All providers are configurable per feature. + +## Additional Features Configuration + +### Dream Processing + +Dream processing consolidates and refines peer representations during idle periods, similar to how human memory consolidation works during sleep. + +**Dream Settings:** +```bash +# Enable/disable dream processing +DREAM_ENABLED=true + +# Trigger thresholds +DREAM_DOCUMENT_THRESHOLD=50 # Minimum documents to trigger a dream +DREAM_IDLE_TIMEOUT_MINUTES=60 # Minutes of inactivity before dream can start +DREAM_MIN_HOURS_BETWEEN_DREAMS=8 # Minimum hours between dreams for a peer + +# Dream types to enable +DREAM_ENABLED_TYPES=["consolidate"] # Currently supported: consolidate + +# LLM settings for dream processing +DREAM_PROVIDER=openai +DREAM_MODEL=gpt-4o-mini-2024-07-18 +DREAM_MAX_OUTPUT_TOKENS=2000 +``` + +### Webhook Configuration + +Webhooks allow you to receive real-time notifications when events occur in Honcho (e.g., new messages, session updates). + +**Webhook Settings:** +```bash +# Webhook secret for signing payloads (optional but recommended) +WEBHOOK_SECRET=your-webhook-signing-secret + +# Limit on webhooks per workspace +WEBHOOK_MAX_WORKSPACE_LIMIT=10 +``` + +### Metrics Collection + +Enable metrics collection for monitoring Honcho performance and usage. + +**Metrics Settings:** +```bash +# Enable/disable metrics collection +METRICS_ENABLED=false + +# Namespace for metrics (used in metric names) +METRICS_NAMESPACE=honcho +``` + +## Monitoring Configuration + +### Sentry Error Tracking + +**Sentry Settings:** +```bash +# Enable/disable Sentry error tracking +SENTRY_ENABLED=false + +# Sentry configuration +SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id +SENTRY_RELEASE=2.4.0 # Optional: track which version errors come from +SENTRY_ENVIRONMENT=production # Environment name (development, staging, production) + +# Sampling rates (0.0 to 1.0) +SENTRY_TRACES_SAMPLE_RATE=0.1 # 10% of transactions tracked +SENTRY_PROFILES_SAMPLE_RATE=0.1 # 10% of transactions profiled +``` + +## Environment-Specific Examples + +### Development Configuration + +**config.toml for development:** +```toml +[app] +LOG_LEVEL = "DEBUG" +SESSION_OBSERVERS_LIMIT = 10 +EMBED_MESSAGES = false + +[db] +CONNECTION_URI = "postgresql+psycopg://postgres:postgres@localhost:5432/honcho_dev" +POOL_SIZE = 5 + +[auth] +USE_AUTH = false + +[cache] +ENABLED = false + +[dialectic] +PROVIDER = "anthropic" +MODEL = "claude-sonnet-4-20250514" +PERFORM_QUERY_GENERATION = false +MAX_OUTPUT_TOKENS = 2500 + +[deriver] +WORKERS = 1 +PROVIDER = "google" +MODEL = "gemini-2.5-flash-lite" + +[peer_card] +ENABLED = true +PROVIDER = "openai" +MODEL = "gpt-5-nano-2025-08-07" + +[summary] +ENABLED = true +PROVIDER = "openai" +MODEL = "gpt-4o-mini-2024-07-18" +MAX_TOKENS_SHORT = 1000 +MAX_TOKENS_LONG = 4000 + +[dream] +ENABLED = true + +[webhook] +MAX_WORKSPACE_LIMIT = 10 + +[metrics] +ENABLED = false + +[sentry] +ENABLED = false +``` + +**Environment variables for development:** +```bash +# .env.development +LOG_LEVEL=DEBUG +DB_CONNECTION_URI=postgresql+psycopg://postgres:postgres@localhost:5432/honcho_dev +AUTH_USE_AUTH=false +CACHE_ENABLED=false + +# LLM Provider API Keys +LLM_ANTHROPIC_API_KEY=your-dev-anthropic-key +LLM_OPENAI_API_KEY=your-dev-openai-key +LLM_GEMINI_API_KEY=your-dev-gemini-key +``` + +### Production Configuration + +**config.toml for production:** +```toml +[app] +LOG_LEVEL = "WARNING" +SESSION_OBSERVERS_LIMIT = 10 +EMBED_MESSAGES = true + +[db] +CONNECTION_URI = "postgresql+psycopg://honcho_user:secure_password@prod-db:5432/honcho_prod" +POOL_SIZE = 20 +MAX_OVERFLOW = 40 + +[auth] +USE_AUTH = true + +[cache] +ENABLED = true +URL = "redis://redis:6379/0" +DEFAULT_TTL_SECONDS = 300 + +[dialectic] +PROVIDER = "anthropic" +MODEL = "claude-sonnet-4-20250514" +PERFORM_QUERY_GENERATION = false +MAX_OUTPUT_TOKENS = 2500 + +[deriver] +WORKERS = 4 +PROVIDER = "google" +MODEL = "gemini-2.5-flash-lite" + +[peer_card] +ENABLED = true +PROVIDER = "openai" +MODEL = "gpt-5-nano-2025-08-07" + +[summary] +ENABLED = true +PROVIDER = "openai" +MODEL = "gpt-4o-mini-2024-07-18" +MAX_TOKENS_SHORT = 1000 +MAX_TOKENS_LONG = 4000 + +[dream] +ENABLED = true +PROVIDER = "openai" +MODEL = "gpt-4o-mini-2024-07-18" + +[webhook] +MAX_WORKSPACE_LIMIT = 10 + +[metrics] +ENABLED = true + +[sentry] +ENABLED = true +ENVIRONMENT = "production" +TRACES_SAMPLE_RATE = 0.1 +PROFILES_SAMPLE_RATE = 0.1 +``` + +**Environment variables for production:** +```bash +# .env.production +LOG_LEVEL=WARNING +DB_CONNECTION_URI=postgresql+psycopg://honcho_user:secure_password@prod-db:5432/honcho_prod + +# Authentication +AUTH_USE_AUTH=true +AUTH_JWT_SECRET=your-super-secret-jwt-key + +# Cache +CACHE_ENABLED=true +CACHE_URL=redis://redis:6379/0 + +# LLM Provider API Keys +LLM_ANTHROPIC_API_KEY=your-prod-anthropic-key +LLM_OPENAI_API_KEY=your-prod-openai-key +LLM_GEMINI_API_KEY=your-prod-gemini-key +LLM_GROQ_API_KEY=your-prod-groq-key + +# Webhooks +WEBHOOK_SECRET=your-webhook-signing-secret + +# Monitoring +SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id +SENTRY_ENVIRONMENT=production +``` + +## Migration Management + +**Running Database Migrations:** +```bash +# Check current migration status +uv run alembic current + +# Upgrade to latest +uv run alembic upgrade head + +# Downgrade to specific revision +uv run alembic downgrade revision_id + +# Create new migration +uv run alembic revision --autogenerate -m "Description of changes" +``` + +## Troubleshooting + +**Common Configuration Issues:** + +1. **Database Connection Errors** + - Ensure `DB_CONNECTION_URI` uses `postgresql+psycopg://` prefix + - Verify database is running and accessible + - Check pgvector extension is installed + +2. **Authentication Issues** + - Set `AUTH_USE_AUTH=true` for production + - Generate and set `AUTH_JWT_SECRET` if authentication is enabled + - Use `python scripts/generate_jwt_secret.py` to create a secure secret + +3. **LLM Provider Issues** + - Verify API keys are set correctly + - Check model names match provider specifications + - Ensure provider is enabled in configuration + +4. **Deriver Issues** + - Increase `DERIVER_WORKERS` for better performance + - Check `DERIVER_STALE_SESSION_TIMEOUT_MINUTES` for session cleanup + - Monitor background processing logs + +This configuration guide covers all the settings available in Honcho. Always use environment-specific configuration files and never commit sensitive values like API keys or JWT secrets to version control. diff --git a/docs/v2.6.0-alpha/contributing/guidelines.mdx b/docs/v2.6.0-alpha/contributing/guidelines.mdx new file mode 100644 index 00000000..f064e51b --- /dev/null +++ b/docs/v2.6.0-alpha/contributing/guidelines.mdx @@ -0,0 +1,172 @@ +--- +title: 'Contributing Guidelines' +icon: 'handshake' +--- + +Thank you for your interest in contributing to Honcho! This guide outlines the process for contributing to the project and our development conventions. + +## Getting Started + +Before you start contributing, please: + +1. **Set up your development environment** - Follow the [Local Development guide](https://github.com/plastic-labs/honcho/blob/main/CONTRIBUTING.md#local-development) in the Honcho repository to get Honcho running locally. + +2. **Join our community** - Feel free to join us in our [Discord](http://discord.gg/plasticlabs) to discuss your changes, get help, or ask questions. + +3. **Review existing issues** - Check the [issues tab](https://github.com/plastic-labs/honcho/issues) to see what's already being worked on or to find something to contribute to. + +## Contribution Workflow + +### 1. Fork and Clone + +1. Fork the repository on GitHub +2. Clone your fork locally: + ```bash + git clone https://github.com/YOUR_USERNAME/honcho.git + cd honcho + ``` +3. Add the upstream repository as a remote: + ```bash + git remote add upstream https://github.com/plastic-labs/honcho.git + ``` + +### 2. Create a Branch + +Create a new branch for your feature or bug fix: + +```bash +git checkout -b feature/your-feature-name +# or +git checkout -b fix/your-bug-fix-name +``` + +**Branch naming conventions:** +- `feature/description` - for new features +- `fix/description` - for bug fixes +- `docs/description` - for documentation updates +- `refactor/description` - for code refactoring +- `test/description` - for adding or updating tests + +### 3. Make Your Changes + +- Write clean, readable code that follows our coding standards (see below) +- Add tests for new functionality +- Update documentation as needed +- Make sure your changes don't break existing functionality + +### 4. Commit Your Changes + +We follow conventional commit standards. Format your commit messages as: + +``` +type(scope): description + +[optional body] + +[optional footer] +``` + +**Types:** +- `feat`: A new feature +- `fix`: A bug fix +- `docs`: Documentation only changes +- `style`: Changes that do not affect the meaning of the code +- `refactor`: A code change that neither fixes a bug nor adds a feature +- `test`: Adding missing tests or correcting existing tests +- `chore`: Changes to the build process or auxiliary tools + +**Examples:** +```bash +git commit -m "feat(api): add new dialectic endpoint for user insights" +git commit -m "fix(db): resolve connection pool timeout issue" +git commit -m "docs(readme): update installation instructions" +``` + +### 5. Submit a Pull Request + +1. Push your branch to your fork: + ```bash + git push origin your-branch-name + ``` + +2. Create a pull request on GitHub from your branch to the `main` branch + +3. Fill out the pull request template with: + - A clear description of what changes you've made + - The motivation for the changes + - Any relevant issue numbers (use "Closes #123" to auto-close issues) + - Screenshots or examples if applicable + +## Coding Standards + +### Python Code Style + +- Follow [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guidelines +- Use [Black](https://black.readthedocs.io/) for code formatting (we may add this to CI in the future) +- Use type hints where possible +- Write docstrings for functions and classes using Google style docstrings + +### Code Organization + +- Keep functions focused and single-purpose +- Use meaningful variable and function names +- Add comments for complex logic +- Follow existing patterns in the codebase + +### Testing + +- Write unit tests for new functionality +- Ensure existing tests pass before submitting +- Use descriptive test names that explain what is being tested +- Mock external dependencies appropriately + +### Documentation + +- Update relevant documentation for new features +- Include examples in docstrings where helpful +- Keep README and other docs up to date with changes + +## Review Process + +1. **Automated checks** - Your PR will run through automated checks including tests and linting +2. **Project maintainer review** - A project maintainer will review your code for: + - Code quality and adherence to standards + - Functionality and correctness + - Test coverage + - Documentation completeness +3. **Discussion and iteration** - You may be asked to make changes or clarifications +4. **Approval and merge** - Once approved, your PR will be merged into `main` + +## Types of Contributions + +We welcome various types of contributions: + +- **Bug fixes** - Help us squash bugs and improve stability +- **New features** - Add functionality that benefits the community +- **Documentation** - Improve or expand our documentation +- **Tests** - Increase test coverage and reliability +- **Performance improvements** - Help make Honcho faster and more efficient +- **Examples and tutorials** - Help other developers use Honcho + +## Issue Reporting + +When reporting bugs or requesting features: + +1. Check if the issue already exists +2. Use the appropriate issue template +3. Provide clear reproduction steps for bugs +4. Include relevant environment information +5. Be specific about expected vs actual behavior + +## Questions and Support + +- **General questions** - Join our [Discord](http://discord.gg/plasticlabs) +- **Bug reports** - Use GitHub issues +- **Feature requests** - Use GitHub issues with the feature request template +- **Security issues** - Please email us privately rather than opening a public issue + +## License + +By contributing to Honcho, you agree that your contributions will be licensed under the same [AGPL-3.0 License](./license) that covers the project. + +Thank you for helping make Honcho better! 🫡 diff --git a/docs/v2.6.0-alpha/contributing/license.mdx b/docs/v2.6.0-alpha/contributing/license.mdx new file mode 100644 index 00000000..6855347e --- /dev/null +++ b/docs/v2.6.0-alpha/contributing/license.mdx @@ -0,0 +1,671 @@ +--- +title: 'License' +icon: 'scroll' +--- + +Honcho is licensed under the AGPL-3.0 License. This is copied below for convenience and also present in the +[GitHub Repository](https://github.com/plastic-labs/honcho) + +``` + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. +``` diff --git a/docs/v2.6.0-alpha/contributing/self-hosting.mdx b/docs/v2.6.0-alpha/contributing/self-hosting.mdx new file mode 100644 index 00000000..3e5e1e42 --- /dev/null +++ b/docs/v2.6.0-alpha/contributing/self-hosting.mdx @@ -0,0 +1,324 @@ +--- +title: 'Local Environment Setup' +sidebarTitle: 'Local Environment' +description: 'Set up a local environment to run Honcho for development, testing, or self-hosting' +icon: 'computer' +--- + +This guide helps you set up a local environment to run Honcho for development, testing, or self-hosting. + +## Overview + +By the end of this guide, you'll have: +- A local Honcho server running on your machine +- A PostgreSQL database with pgvector extension +- Basic configuration to connect your applications +- A working environment for development or testing + +## Prerequisites + +Before you begin, ensure you have the following installed: + +### Required Software +- **uv** - Python package manager: `pip install uv` (manages Python installations automatically) +- **Git** - [Download from git-scm.com](https://git-scm.com/downloads) +- **Docker** (optional) - [Download from docker.com](https://www.docker.com/products/docker-desktop/) + +### Database Options +You'll need a PostgreSQL database with the pgvector extension. Choose one: + +- **Local PostgreSQL** - Install locally or use Docker +- **Supabase** - Free cloud PostgreSQL with pgvector +- **Railway** - Simple cloud PostgreSQL hosting +- **Your own PostgreSQL server** + +## Docker Setup (Recommended) + +The easiest way to get started is using Docker Compose, which handles both the database and Honcho server. + +### 1. Clone the Repository + +```bash +git clone https://github.com/plastic-labs/honcho.git +cd honcho +``` + +### 2. Set Up Environment Variables + +Copy the example environment file and configure it: + +```bash +cp .env.template .env +``` + +Edit `.env` and set your API keys (if using LLM features): + +```bash +# Optional API keys (required for LLM features) +OPENAI_API_KEY=your-openai-api-key +ANTHROPIC_API_KEY=your-anthropic-api-key + +# Database will be created automatically by Docker +DB_CONNECTION_URI=postgresql+psycopg://postgres:postgres@database:5432/honcho + +# Disable auth for local development +AUTH_USE_AUTH=false +``` + +### 3. Start the Services + +```bash +# Copy the example docker-compose file +cp docker-compose.yml.example docker-compose.yml + +# Start PostgreSQL and Honcho +docker compose up -d +``` + +### 4. Verify It's Working + +Check that both services are running: + +```bash +docker compose ps +``` + +Test the Honcho API: + +```bash +curl http://localhost:8000/health +``` + +You should see a response indicating the service is healthy. + +## Manual Setup + +For more control over your environment, you can set up everything manually. + +### 1. Clone and Install Dependencies + +```bash +git clone https://github.com/plastic-labs/honcho.git +cd honcho + +# Install dependencies using uv (this will also set up Python if needed) +uv sync + +# Activate the virtual environment +source .venv/bin/activate # On Windows: .venv\Scripts\activate +``` + +### 2. Set Up PostgreSQL + +#### Option A: Local PostgreSQL Installation + +Install PostgreSQL and pgvector on your system: + +**macOS (using Homebrew):** +```bash +brew install postgresql +brew install pgvector +``` + +**Ubuntu/Debian:** +```bash +sudo apt update +sudo apt install postgresql postgresql-contrib +# Install pgvector extension (see pgvector docs for your version) +``` + +**Windows:** +Download from [postgresql.org](https://www.postgresql.org/download/windows/) + +#### Option B: Docker PostgreSQL + +```bash +docker run --name honcho-db \ + -e POSTGRES_DB=honcho \ + -e POSTGRES_USER=postgres \ + -e POSTGRES_PASSWORD=postgres \ + -p 5432:5432 \ + -d pgvector/pgvector:pg15 +``` + +### 3. Create Database and Enable Extensions + +Connect to PostgreSQL and set up the database: + +```bash +# Connect to PostgreSQL +psql -U postgres + +# Create database and enable extensions +CREATE DATABASE honcho; +\c honcho +CREATE EXTENSION IF NOT EXISTS vector; +CREATE EXTENSION IF NOT EXISTS pg_trgm; +\q +``` + +### 4. Configure Environment + +Create a `.env` file with your settings: + +```bash +cp .env.template .env +``` + +Edit `.env` with your configuration: + +```bash +# Database connection +DB_CONNECTION_URI=postgresql+psycopg://postgres:postgres@localhost:5432/honcho + +# Optional API keys (required for LLM features) +OPENAI_API_KEY=your-openai-api-key +ANTHROPIC_API_KEY=your-anthropic-api-key + +# Development settings +AUTH_USE_AUTH=false +LOG_LEVEL=DEBUG +``` + +### 5. Run Database Migrations + +```bash +# Run migrations to create tables +uv run alembic upgrade head +``` + +### 6. Start the Server + +```bash +# Start the development server +fastapi dev src/main.py +``` + +The server will be available at `http://localhost:8000`. + +## Cloud Database Setup + +If you prefer to use a managed PostgreSQL service: + +### Supabase (Recommended) + +1. **Create a Supabase project** at [supabase.com](https://supabase.com) +2. **Enable pgvector extension** in the SQL editor: + ```sql + CREATE EXTENSION IF NOT EXISTS vector; + CREATE EXTENSION IF NOT EXISTS pg_trgm; + ``` +3. **Get your connection string** from Settings > Database +4. **Update your `.env` file** with the connection string + +### Railway + +1. **Create a Railway project** at [railway.app](https://railway.app) +2. **Add a PostgreSQL service** +3. **Enable pgvector** in the PostgreSQL console +4. **Get your connection string** from the service variables +5. **Update your `.env` file** + +## Verify Your Setup + +Once your Honcho server is running, verify everything is working: + +### 1. Health Check + +```bash +curl http://localhost:8000/health +``` + +### 2. API Documentation + +Visit `http://localhost:8000/docs` to see the interactive API documentation. + +### 3. Test with SDK + +Create a simple test script: + +```python +from honcho import Honcho + +# Connect to your local instance +client = Honcho(base_url="http://localhost:8000") + +# Create a test peer +peer = client.peer("test-user") +print(f"Created peer: {peer.id}") +``` + +## Connect Your Application + +Now that Honcho is running locally, you can connect your applications: + +### Update SDK Configuration + +```python +# Python SDK +from honcho import Honcho + +client = Honcho( + base_url="http://localhost:8000", # Your local instance + api_key="your-api-key" # If auth is enabled +) +``` + +```typescript +// TypeScript SDK +import { Honcho } from '@honcho-ai/sdk'; + +const client = new Honcho({ + baseUrl: 'http://localhost:8000', // Your local instance + apiKey: 'your-api-key' // If auth is enabled +}); +``` + +### Next Steps + +- **Explore the API**: Check out the [API Reference](/v2/api-reference/introduction) +- **Try the SDKs**: See our [guides](/v2/guides) for examples +- **Configure Honcho**: Visit the [Configuration Guide](./configuration) for detailed settings +- **Join the community**: [Discord](https://discord.gg/plasticlabs) + +## Troubleshooting + +### Common Issues + +**Database Connection Errors** +- Ensure PostgreSQL is running +- Verify the connection string format: `postgresql+psycopg://...` +- Check that pgvector extension is installed + +**API Key Issues** +- Verify your OpenAI and Anthropic API keys are valid +- Check that the keys have sufficient credits/quota + +**Port Already in Use** +- Pass a different port to FastAPI or stop other services using port 8000 + +**Docker Issues** +- Ensure Docker is running +- Check container logs: `docker compose logs` +- Restart containers: `docker compose down && docker compose up -d` + +**Migration Errors** +- Ensure the database exists and pgvector is enabled +- Check database permissions +- Run migrations manually: `uv run alembic upgrade head` + +### Getting Help + +- **GitHub Issues**: [Report bugs](https://github.com/plastic-labs/honcho/issues) +- **Discord**: [Join our community](https://discord.gg/plasticlabs) +- **Documentation**: Check the [Configuration Guide](./configuration) for detailed settings + +## Production Considerations + +When self-hosting for production, consider: + +- **Security**: Enable authentication, use HTTPS, secure your database +- **Scaling**: Use connection pooling, consider load balancing +- **Monitoring**: Set up logging, error tracking, health checks +- **Backups**: Regular database backups, disaster recovery plan +- **Updates**: Keep Honcho and dependencies updated diff --git a/docs/v2.6.0-alpha/documentation/core-concepts/architecture.mdx b/docs/v2.6.0-alpha/documentation/core-concepts/architecture.mdx new file mode 100644 index 00000000..b0eb7dc3 --- /dev/null +++ b/docs/v2.6.0-alpha/documentation/core-concepts/architecture.mdx @@ -0,0 +1,102 @@ +--- +title: "Architecture & Intuition" +description: "Understanding Honcho's core concepts and data model." +icon: "sitemap" +sidebarTitle: "Architecture" +--- + +Honcho is memory infrastructure that continuously [*reasons*](/v2/documentation/core-concepts/reasoning) about data to build rich representations of peers (users, agents, or any entity) over time. This document explains the data model, system components, and how data flows through Honcho. + +## Data Model + +Honcho has a hierarchical data model centered around the entities below. + +```mermaid + graph LR + W[Workspaces] -->|have| P[Peers] + W -->|have| S[Sessions] + + S -->|have| SM[Messages] + + P <-.->|many-to-many| S + + style W fill:#B6DBFF,stroke:#333,color:#000 + style P fill:#B6DBFF,stroke:#333,color:#000 + style S fill:#B6DBFF,stroke:#333,color:#000 + style SM fill:#B6DBFF,stroke:#333,color:#000 +``` + +- A Workspace has Peers & Sessions +- A Peer can be in multiple Sessions and can send Messages in a Session +- A Session can have many Peers and stores Messages sent by its Peers + +### Workspaces + +Workspaces are the top-level containers in Honcho. They provide complete isolation between different applications or environments, essentially serving as a namespace to keep different workloads separate. You might use separate workspaces for development, staging, and production environments, or to isolate different product lines. They also enable multi-tenant SaaS applications where each customer gets their own isolated workspace with complete data separation. + +Authentication is scoped to the workspace level, and configuration settings can be applied workspace-wide to control behavior across all peers and sessions within that workspace. + +--- + +### Peers + +Peers are the most important entity in Honcho--everything revolves around building and maintaining their [*representations*](/v2/documentation/core-concepts/representation). A peer represents any individual user, agent, or entity in a workspace. Treating humans and agents the same way lets you build arbitrary combinations for multi-agent or group chat scenarios. + +Each peer has a unique identifier within a workspace and is a container for reasoning across all their sessions. This cross-session context means conclusions drawn about a peer in one session can inform interactions in completely different sessions. Peers can be configured to control whether Honcho reasons about them. + +You can use peers for any entity that persists over time--individual users in chatbot applications, AI agents interacting with users or other agents, customer profiles in support systems, student profiles in educational platforms, or even NPCs in role-playing games. + +--- + +### Sessions + +Sessions represent interaction threads or contexts between peers. A session can involve multiple peers and provides temporal boundaries for when a set of interactions starts and ends. This lets you scope context and memory to specific interactions while still maintaining longer-term peer representations that span sessions. + +Use sessions to scope things like support tickets, meeting transcripts, learning sessions, or conversations. You can also use single-peer sessions as a way to import external data--create a session with just one peer and structure emails, documents, or files as messages to enrich that peer's representation. + +Session-level configuration gives you fine-grained control over perspective-taking behavior. You can configure whether a peer should form representations of other peers in the session, and whether other peers should form representations of them. + +--- + +### Messages + +Messages are the fundamental units of interaction within sessions. While they typically represent back-and-forth communication between peers, you can also use messages to ingest any information that provides context--emails, documents, files, user actions, system notifications, or rich media content. + +Every message is attributed to a specific peer and ordered chronologically within its session. When messages are created, they trigger automatic background reasoning that updates peer representations. Messages support rich metadata and structured data through JSONB fields, making them flexible enough to capture whatever information matters for your use case. + +## Data Flow + +Understanding how data moves through Honcho helps clarify the architecture. + +When you create messages, they're immediately written to PostgreSQL and reasoning tasks are added to background queues. Background workers then generate logic, summaries, and new insights to improve representations. These conclusions and insights get stored in vector collections for retrieval. This async approach ensures fast writes while still providing rich reasoning capabilities. + +When you need context from Honcho, you query through the "Chat" endpoint or "Get Context" endpoint. Honcho retrieves relevant conclusions from vector storage along with recent messages, then assembles everything into coherent context ready to inject into agent prompts. + +![Honcho Architecture](/images/architecture.png) + +The diagram above shows how agents write messages to Honcho, which triggers reasoning that updates peer representations. Agents can then query representations to get additional context for their next response. Black arrows represent read/write of regular data (messages, storage), while red arrows represent read/write of reasoned-over data (logic, peer representations). + +## Configuration & Extensibility + +Honcho is designed to be flexible. Settings cascade hierarchically from workspace to peer to session, so you can set defaults at the workspace level and override them for specific peers or sessions. Feature flags let you enable or disable reasoning modes, perspective tracking, and other capabilities. You can bring your own LLM provider--OpenAI, Anthropic, or custom endpoints--and metadata fields let you extend any primitive with custom JSON data. Batch operations let you create up to 100 messages in a single API call for efficient bulk ingestion. + +## Design Principles + +Honcho's architecture follows a few core principles. Everything revolves around building representations of peers (peer-centric). Memory isn't just storage--it's continual learning (reasoning-first). Long-lived operations happen in the background so they don't block user interactions (async by default). The system works with any LLM provider (provider-agnostic) and is built for isolation and scalability from the ground up (multi-tenant). Users and agents are both represented as peers, which enables flexible scenarios you couldn't easily model with a traditional user-assistant paradigm (unified paradigm). + +## Next Steps + + + + Sign up for the Honcho platform and start building + + + Get started with your first integration + + + Learn how Honcho reasons about messages to build memory + + + Understand what peer representations are and how they work + + diff --git a/docs/v2/documentation/core-concepts/reasoning.mdx b/docs/v2.6.0-alpha/documentation/core-concepts/reasoning.mdx similarity index 100% rename from docs/v2/documentation/core-concepts/reasoning.mdx rename to docs/v2.6.0-alpha/documentation/core-concepts/reasoning.mdx diff --git a/docs/v2/documentation/core-concepts/representation.mdx b/docs/v2.6.0-alpha/documentation/core-concepts/representation.mdx similarity index 100% rename from docs/v2/documentation/core-concepts/representation.mdx rename to docs/v2.6.0-alpha/documentation/core-concepts/representation.mdx diff --git a/docs/v2/documentation/features/advanced/overview.mdx b/docs/v2.6.0-alpha/documentation/features/advanced/overview.mdx similarity index 100% rename from docs/v2/documentation/features/advanced/overview.mdx rename to docs/v2.6.0-alpha/documentation/features/advanced/overview.mdx diff --git a/docs/v2/documentation/features/advanced/queue-status.mdx b/docs/v2.6.0-alpha/documentation/features/advanced/queue-status.mdx similarity index 100% rename from docs/v2/documentation/features/advanced/queue-status.mdx rename to docs/v2.6.0-alpha/documentation/features/advanced/queue-status.mdx diff --git a/docs/v2/documentation/features/advanced/representation-scopes.mdx b/docs/v2.6.0-alpha/documentation/features/advanced/representation-scopes.mdx similarity index 100% rename from docs/v2/documentation/features/advanced/representation-scopes.mdx rename to docs/v2.6.0-alpha/documentation/features/advanced/representation-scopes.mdx diff --git a/docs/v2/documentation/features/advanced/search.mdx b/docs/v2.6.0-alpha/documentation/features/advanced/search.mdx similarity index 100% rename from docs/v2/documentation/features/advanced/search.mdx rename to docs/v2.6.0-alpha/documentation/features/advanced/search.mdx diff --git a/docs/v2/documentation/features/advanced/streaming-response.mdx b/docs/v2.6.0-alpha/documentation/features/advanced/streaming-response.mdx similarity index 100% rename from docs/v2/documentation/features/advanced/streaming-response.mdx rename to docs/v2.6.0-alpha/documentation/features/advanced/streaming-response.mdx diff --git a/docs/v2/documentation/features/advanced/summarizer.mdx b/docs/v2.6.0-alpha/documentation/features/advanced/summarizer.mdx similarity index 100% rename from docs/v2/documentation/features/advanced/summarizer.mdx rename to docs/v2.6.0-alpha/documentation/features/advanced/summarizer.mdx diff --git a/docs/v2/documentation/features/advanced/toggle-reasoning.mdx b/docs/v2.6.0-alpha/documentation/features/advanced/toggle-reasoning.mdx similarity index 100% rename from docs/v2/documentation/features/advanced/toggle-reasoning.mdx rename to docs/v2.6.0-alpha/documentation/features/advanced/toggle-reasoning.mdx diff --git a/docs/v2/documentation/features/advanced/using-filters.mdx b/docs/v2.6.0-alpha/documentation/features/advanced/using-filters.mdx similarity index 100% rename from docs/v2/documentation/features/advanced/using-filters.mdx rename to docs/v2.6.0-alpha/documentation/features/advanced/using-filters.mdx diff --git a/docs/v2/documentation/features/chat.mdx b/docs/v2.6.0-alpha/documentation/features/chat.mdx similarity index 100% rename from docs/v2/documentation/features/chat.mdx rename to docs/v2.6.0-alpha/documentation/features/chat.mdx diff --git a/docs/v2/documentation/features/get-context.mdx b/docs/v2.6.0-alpha/documentation/features/get-context.mdx similarity index 100% rename from docs/v2/documentation/features/get-context.mdx rename to docs/v2.6.0-alpha/documentation/features/get-context.mdx diff --git a/docs/v2.6.0-alpha/documentation/introduction/overview.mdx b/docs/v2.6.0-alpha/documentation/introduction/overview.mdx new file mode 100644 index 00000000..3d9624f9 --- /dev/null +++ b/docs/v2.6.0-alpha/documentation/introduction/overview.mdx @@ -0,0 +1,99 @@ +--- +title: "Honcho Overview" +icon: "brain" +sidebarTitle: "Overview" +--- + +Honcho is an open source memory library with a managed service for building stateful agents. Use it with any model, framework, or architecture. It enables agents to build and maintain state about any entity--users, agents, groups, ideas, and more. And because it's a continual learning system, it understands entities that change over time. Using Honcho as your memory system will earn your agents higher retention, more trust, and help you build data moats to out-compete incumbents. + + + + Sign up and start building with Honcho + + + Build your first stateful agent in minutes + + + + +Honcho is a memory system that reasons. Read more on the approach [here](https://blog.plasticlabs.ai/blog/Memory-as-Reasoning). + + +## Why Use Honcho? + +Honcho streamlines the agent building process by offering elegant, flexible primitives for managing context. It also reasons over that context to give developers access to far richer insights only accessible through reasoning. + +Take the following scenario: + +- You find a use case for LLMs and build an agent around it +- It works well initially but can't maintain context across sessions +- You spend weeks engineering a RAG solution that seems to help +- Then the cycle begins... + - Users report the agent forgetting things, contradicting itself, or losing context mid-session + - You build evals to quantify the problem + - You re-engineer your entire RAG pipeline with better chunking, embeddings, retrieval strategies + - The problems shift but don't disappear + - Repeat + +Eventually you realize the issue isn't engineering—-it's that you're not extracting all the latent information from your data. You need to reason exhaustively, handle contradictions, track patterns over time, and maintain coherent state. In other words, you'd need to build Honcho. + +Break free from this cycle. Honcho is a general solution to context engineering, memory, and statefulness. + +## How Honcho Works + +Honcho has four storage primitives that work together: + +```mermaid + graph LR + W[Workspaces] -->|have| P[Peers] + W -->|have| S[Sessions] + + S -->|have| SM[Messages] + + P <-.->|many-to-many| S + + style W fill:#B6DBFF,stroke:#333,color:#000 + style P fill:#B6DBFF,stroke:#333,color:#000 + style S fill:#B6DBFF,stroke:#333,color:#000 + style SM fill:#B6DBFF,stroke:#333,color:#000 +``` + +- **Workspaces** - Top-level containers that isolate different applications or environments +- **Peers** - Any entity that persists but changes over time (users, agents, objects, and more) +- **Sessions** - Interaction threads between peers with temporal boundaries +- **Messages** - Units of data that trigger reasoning (conversations, events, activity, documents, and more) + +When you write messages to Honcho, they're stored and processed in the background. Custom reasoning models perform formal logical [*reasoning*](/v2/documentation/core-concepts/reasoning) to generate conclusions about each peer. These conclusions are stored as [*representations*](/v2/documentation/core-concepts/representation) that you can query to provide rich context for your agents. + +![Honcho Architecture](/images/architecture.png) + +The diagram above shows the flow: agents write messages to Honcho, which triggers reasoning that updates what's stored in representations. Developers (or agents) can then query to get additional context for their next response. + +## Why Reasoning? + +Traditional RAG systems retrieve what was explicitly said, but they miss what matters most—the insights only accessible by *rigorously thinking* about your data. Without reasoning, you're leaving latent information on the table. Static retrieval can't surface implicit connections, struggles when new information contradicts old data, and fails when you need to make predictions under uncertainty. + +Honcho uses formal logic to extract all that latent information. This reasoning is AI-native—it performs the rigorous, compute-intensive thinking that humans struggle with, instantly and consistently. The result is memory that goes beyond simple RAG recall to provide exhaustive context for statefulness. + +## Get Started + +Honcho gives you maximum control over your agent's context and memory. The data model is flexible and composable, the reasoning backend is powerful yet cost-effective, and everything is built to give developers levers to manage token usage, latency, and reasoning depth. + +We're just scratching the surface. Dive into the quickstart to see Honcho in action, explore the architecture to understand how it all fits together, or jump straight to building. + +Welcome to Honcho. We're excited to have you at the frontier of AI with us 🫡. + + + + Sign up for the Honcho platform and get your API key + + + Build your first stateful agent in minutes + + + Deep dive into how Honcho's primitives fit together + + + Learn how Honcho reasons about data to build memory + + diff --git a/docs/v2.6.0-alpha/documentation/introduction/quickstart.mdx b/docs/v2.6.0-alpha/documentation/introduction/quickstart.mdx new file mode 100644 index 00000000..927e0ba1 --- /dev/null +++ b/docs/v2.6.0-alpha/documentation/introduction/quickstart.mdx @@ -0,0 +1,404 @@ +--- +title: "Quickstart" +icon: "bolt" +sidebarTitle: "Quickstart" +--- + +Let's get started with Honcho. In this quickstart, you will: + +- Set up a workspace with peers (user and assistant) +- Ingest messages from across multiple sessions +- Query the reasoning Honcho produces to get synthesized insights about the user + + +Running the code below requires an API key. Create and account and get your API key at [app.honcho.dev](https://app.honcho.dev) under "API KEYS". + +Every new tenant gets \$100.00 in free credits on sign up. The code below costs ~\$0.04 to run, so don't worry--still plenty of free credits for iterating. + + +#### 1. Install the SDK + + +```bash Python (uv) +uv add honcho-ai +``` + +```bash Python (pip) +pip install honcho-ai +``` + +```bash TypeScript (npm) +npm install @honcho-ai/sdk +``` + +```bash TypeScript (yarn) +yarn add @honcho-ai/sdk +``` + +```bash TypeScript (pnpm) +pnpm add @honcho-ai/sdk +``` + + +#### 2. Initialize the Client + +The Honcho client is the main entry point for interacting with Honcho's API. It uses a workspace called `default` unless specified, so let's create a `first-honcho-test` workspace for this quickstart. + + +```python Python +from honcho import Honcho + +# Initialize client +honcho = Honcho(workspace="first-honcho-test", api_key=HONCHO_API_KEY) + +``` + +```typescript TypeScript +import { Honcho } from '@honcho-ai/sdk'; + +// Initialize client +const honcho = new Honcho({ workspace = "first-honcho-test", apiKey = HONCHO_API_KEY }); +``` + + + +#### 3. Create Peers + + +```python Python +user = honcho.peer("user") +assistant = honcho.peer("assistant") +``` + +```typescript TypeScript +const user = await honcho.peer("user") +const assistant = await honcho.peer("assistant") +``` + + +#### 4. Add Messages to Sessions + +We've generated an example conversation dataset with 14 messages across 4 sessions. At a high level, the conversation contains a user chatting with an assistant to get help debugging software infrastructure problems for work *and* jam strategy on a side project they're working on. Spoiler alert--the user is way more interested in their side project. + +Create a file called `conversation.json` and add the content in the accordion below. Then we'll loop through the sessions and messages in that file and write them to Honcho. + + + + + ```json Example Conversation + { + "sessions": [ + { + "id": "session_1", + "messages": [ + { + "role": "user", + "content": "containers getting OOM killed in CI after someone on my team updated the base image. quick fix?" + }, + { + "role": "assistant", + "content": "OOM kills after a base image update usually means the new image has higher memory requirements. Quick fix: bump the memory limit in your CI config. If you need to unblock fast, you could also pin back to the previous base image version temporarily." + } + ] + }, + { + "id": "session_2", + "messages": [ + { + "role": "user", + "content": "hey, been playing with honcho for a side project. do you know if there's a limit on how many users i can have?" + }, + { + "role": "assistant", + "content": "Honcho's free tier is based on context ingested, not number of users - so you can have as many users as you want, you're just limited by how much content you're processing. What are you building?" + }, + { + "role": "user", + "content": "ok so basically it's a personal finance assistant that actually remembers your situation - like it knows you're saving for a house, that you hate subscriptions, that you always regret impulse buys over $50. i've been thinking a lot about the UX, like when should it proactively bring up past context vs wait for you to ask? and how do you balance feeling \"known\" vs feeling surveilled? i have a whole notion doc on this lol" + }, + { + "role": "assistant", + "content": "That's a really thoughtful approach to the personalization problem! The \"known vs surveilled\" tension is exactly right - the best experiences feel like talking to a friend who remembers, not a system that tracks. Proactive context works best when it's in service of the user's stated goals." + } + ] + }, + { + "id": "session_3", + "messages": [ + { + "role": "user", + "content": "do i need to update docker-compose too or just the CI yaml for that memory thing" + }, + { + "role": "assistant", + "content": "Just the CI yaml for the memory limit - docker-compose is separate and only matters if you're hitting the same OOM issue locally." + }, + { + "role": "user", + "content": "k. oh btw 3 friends are using the finance app now, they keep asking when they can pay me lol. one of them said it's the first budgeting thing that \"gets\" her" + }, + { + "role": "assistant", + "content": "That's awesome - \"when can I pay you\" is the best kind of validation. And that quote about it being the first thing that \"gets\" her is exactly the value prop of personalized memory. Sounds like you're onto something real." + } + ] + }, + { + "id": "session_4", + "messages": [ + { + "role": "user", + "content": "if i wanted to charge like $5/mo for the finance app, would honcho's pricing still make sense at that price point? trying to figure out unit economics early" + }, + { + "role": "assistant", + "content": "You should be fine at that price point. Unlike other memory frameworks that charge you to access your own data, Honcho only charges for the reasoning layer - ingestion and inference. Storage and retrieval are free. So your unit economics are mostly about how often you're synthesizing insights, not how much history you're keeping." + }, + { + "role": "user", + "content": "ok interesting. wish i had more time to work on this" + }, + { + "role": "assistant", + "content": "Yeah, sounds like you've got something worth making time for. The early traction is real." + } + ] + } + ] + } + ``` + + + + +```python Python +import json + +# Load conversation data +with open("conversation.json", "r") as f: + data = json.load(f) + +# Process each session +for session_data in data["sessions"]: + session = honcho.session(session_data["id"]) + session.add_peers([user, assistant]) + + # Add messages with correct roles + messages = [] + for msg in session_data["messages"]: + if msg["role"] == "user": + messages.append(user.message(msg["content"])) + elif msg["role"] == "assistant": + messages.append(assistant.message(msg["content"])) + + session.add_messages(messages) +``` + +```typescript TypeScript +import * as fs from 'fs'; + +const data = JSON.parse(fs.readFileSync("conversation.json", "utf-8")); + +for (const sessionData of data.sessions) { + const session = honcho.session(sessionData.id); + session.addPeers([user, assistant]); + + const messages = sessionData.messages.map((msg: any) => + msg.role === "user" ? user.message(msg.content) : assistant.message(msg.content) + ); + + session.addMessages(messages); +} +``` + + +#### 5. Query for Insights + +Now ask Honcho what it's learned--this is where the magic happens: + + +```python Python +response = user.chat("What should I know about this user? 3 sentences max") +print(response) +``` + +```typescript TypeScript +user.chat("What should I know about this user? 3 sentences max").then((response) => { + console.log(response); +}) +``` + + + +Honcho needs a short amount of time to process messages you write to it. There are several utilities to [check the status](/v2/documentation/features/advanced/queue-status) of the queue. Honcho also offers numerous ways to query reasoning to fit latency needs: see the [Get Context](/v2/documentation/features/get-context) page. + + +The response will look something like this: + +> User is a personal finance app developer building a personalized finance assistant that's generating real demand (friends are already asking when they can pay). They're notably thoughtful about product design, carefully considering the UX balance between making users feel "known" versus "surveilled" when their app proactively surfaces remembered context like savings goals and spending regrets. They're business-minded and working through unit economics early, exploring a $5/month subscription model with usage-based cost structure focused on insight generation frequency rather than data storage—though they wish they had more time to dedicate to the project. + +Honcho synthesizes signal by reasoning about the user to draw conclusions beyond what was explicitly stated. It identifies the user as "notably thoughtful about product design", "business-minded" from the discussion of unit economics, and surfaces the signal that they desire to work on the project more. + +This is rich personal context for domain-specific agents to do what they want with. +- A life coach agent might see "they wish they had more time to dedicate to the project" and "friends are already asking when they can pay" and ask "have you thought about what it would take to go full-time?" +- A productivity agent might see the same pattern and say "let's protect your weekend time for the finance app." +- A financial advisor agent might see it and ask "what runway would you need to make the leap?" + +Honcho acts almost like a detective--it reasons about new and existing evidence in order to form conclusions that can be used to make a *case*. These conclusions wait to be composed dynamically based on how you, the ~~judge~~ developer, query it. This approach is what drives our [pareto-frontier](TODO: link to evals page here) performance on memory benchmarks, and our custom models allow us to optimize speed and cost. + + +## Next Steps + +You just saw how Honcho reasons about data to build rich peer representations. In this quickstart, you: + +- Set up a workspace with peers (user and assistant) +- Ingested messages across multiple sessions +- Queried the reasoning to get synthesized insights about the user + +Here's the full working code if you want to run it yourself: + + + + + +```python Python +# uv sync +# uv run python test.py + +import json +import time +import uuid + +from honcho import Honcho +from dotenv import load_dotenv + +load_dotenv() + +# Initialize Honcho client with a unique workspace +workspace_id = f"docs-example-{uuid.uuid4().hex[:8]}" +honcho = Honcho(environment="production", workspace_id=workspace_id) + +# Create peers to represent the user and assistant +user = honcho.peer("user") +assistant = honcho.peer("assistant") + +# Load conversation data from JSON file +with open("conversation.json", "r") as f: + conversation_data = json.load(f) + +# Import historical conversation sessions +for session_data in conversation_data["sessions"]: + session = honcho.session(session_data["id"]) + session.add_peers([user, assistant]) + + # Convert messages to peer messages with correct attribution + messages = [] + for msg in session_data["messages"]: + if msg["role"] == "user": + messages.append(user.message(msg["content"])) + elif msg["role"] == "assistant": + messages.append(assistant.message(msg["content"])) + + session.add_messages(messages) + +# Wait for Honcho to process the conversation history +def wait_for_processing(): + status = honcho.get_deriver_status() + while status.pending_work_units > 0 or status.in_progress_work_units > 0: + time.sleep(1) + status = honcho.poll_deriver_status() + +print("Processing conversation history...") +start_time = time.time() +wait_for_processing() +elapsed = int(time.time() - start_time) +print(f"Done in {elapsed}s! Querying user insights...\n") + +# Query insights about the user based on conversation history +response = user.chat("What should I know about this user? 3 sentences max") +print(response) +``` + +```typescript Typescript +// npm install +// npx ts-node test.ts + +import * as fs from 'fs'; +import { randomUUID } from 'crypto'; +import * as dotenv from 'dotenv'; +import { Honcho } from '@honcho-ai/sdk'; + +dotenv.config(); + +// Initialize Honcho client with a unique workspace +const workspaceId = `docs-example-${randomUUID().slice(0, 8)}`; +const honcho = new Honcho({ + environment: "production", + workspaceId, +}); + +// Create peers to represent the user and assistant +const user = await honcho.peer("user"); +const assistant = await honcho.peer("assistant"); + +// Load conversation data from JSON file +const conversationData = JSON.parse(fs.readFileSync("conversation.json", "utf-8")); + +// Import historical conversation sessions +for (const sessionData of conversationData.sessions) { + const session = await honcho.session(sessionData.id); + await session.addPeers([user, assistant]); + + // Convert messages to peer messages with correct attribution + const messages = []; + for (const msg of sessionData.messages) { + if (msg.role === "user") { + messages.push(user.message(msg.content)); + } else if (msg.role === "assistant") { + messages.push(assistant.message(msg.content)); + } + } + + await session.addMessages(messages); +} + +// Wait for Honcho to process the conversation history +async function waitForProcessing() { + let status = await honcho.getDeriverStatus(); + while (status.pendingWorkUnits > 0 || status.inProgressWorkUnits > 0) { + await new Promise(resolve => setTimeout(resolve, 1000)); + status = await honcho.pollDeriverStatus(); + } +} + +console.log("Processing conversation history..."); +const startTime = Date.now(); +await waitForProcessing(); +const elapsed = Math.floor((Date.now() - startTime) / 1000); +console.log(`Done in ${elapsed}s! Querying user insights...\n`); + +// Query insights about the user based on conversation history +const response = await user.chat("What should I know about this user? 3 sentences max"); +console.log(response); + +``` + + + + +From here, you can explore how to use Honcho's features in your own applications: + + + + Learn how to fetch the right context for your agent's next response + + + Deep dive into how Honcho's primitives fit together + + + Query representations with natural language + + + Integration patterns and advanced use cases + + diff --git a/docs/v2.6.0-alpha/documentation/introduction/vibecoding.mdx b/docs/v2.6.0-alpha/documentation/introduction/vibecoding.mdx new file mode 100644 index 00000000..1c0ae6ec --- /dev/null +++ b/docs/v2.6.0-alpha/documentation/introduction/vibecoding.mdx @@ -0,0 +1,59 @@ +--- +title: "AI-Powered Honcho Setup" +icon: "wand-magic-sparkles" +description: "Universal starter prompt for building with Honcho" +sidebarTitle: 'Vibecoding Setup' +--- + +These docs are designed to be easily consumable by LLMs. Each page has a button that lets you copy the page as Markdown or paste directly into ChatGPT or Claude. + +We follow the llms.txt standard. There are both an llms.txt and llms-full.txt available: + +- [llms.txt](/llms.txt) +- [llms-full.txt](/llms-full.txt) + +We also provide a starter prompt to paste into a coding assistant to quickly get started building with Honcho. + +## Universal Starter Prompt + +``` +I want to start building with Honcho - an open source memory library for building stateful agents. + +## Honcho Resources + +**Documentation:** +- Main docs: https://docs.honcho.dev +- API Reference: https://docs.honcho.dev/v2/api-reference/introduction +- Quickstart: https://docs.honcho.dev/v2/documentation/introduction/quickstart +- Architecture: https://docs.honcho.dev/v2/documentation/core-concepts/architecture + +**Code & Examples:** +- Core repo: https://github.com/plastic-labs/honcho +- Python SDK: https://github.com/plastic-labs/honcho-python +- TypeScript SDK: https://github.com/plastic-labs/honcho-node +- Discord bot starter: https://github.com/plastic-labs/discord-python-starter +- Telegram bot example: https://github.com/plastic-labs/telegram-python-starter + +**What Honcho Does:** +Honcho is an open source memory library with a managed service for building stateful agents. It enables agents to build and maintain state about any entity--users, agents, groups, ideas, and more. Because it's a continual learning system, it understands entities that change over time. + +When you write messages to Honcho, they're stored and processed in the background. Custom reasoning models perform formal logical reasoning to generate conclusions about each peer. These conclusions are stored as representations that you can query to provide rich context for your agents. + +**Architecture Overview:** +- Core primitives: Workspaces contain Peers (any entity that persists but changes) and Sessions (interaction threads between peers) +- Peers can observe other peers in sessions (configurable with observe_me and observe_others) +- Background reasoning processes messages to extract premises, draw conclusions, and build representations +- Representations enable continuous improvement as new messages refine existing conclusions and scaffold new ones over time +- Chat endpoint provides personalized responses based on learned context +- Supports any LLM (OpenAI, Anthropic, open source) +- Can use managed service or self-host + +Please assess the resources above and ask me relevant questions to help build a well-structured application using Honcho. Consider asking about: +- What I'm trying to build +- My technical preferences and stack +- Whether I want to use the managed service or self-host +- My experience level with the technologies involved +- Specific features I need (multi-peer sessions, perspective-taking, streaming, etc.) + +Once you understand my needs, help me create a working implementation with proper memory and statefulness. +``` diff --git a/docs/v2.6.0-alpha/documentation/reference/platform.mdx b/docs/v2.6.0-alpha/documentation/reference/platform.mdx new file mode 100644 index 00000000..426af86f --- /dev/null +++ b/docs/v2.6.0-alpha/documentation/reference/platform.mdx @@ -0,0 +1,181 @@ +--- +title: "The Honcho Dashboard" +icon: "rocket" +description: "Build socially intelligent agents without worrying about infrastructure" +sidebarTitle: "Dashboard Overview" +--- + + + Start using the platform to manage Honcho instances for your workspace or app. + + +The quickest way to begin using Honcho in production is with the +[Honcho Cloud Platform](https://app.honcho.dev). Sign up, generate an API key, +and start building with Honcho. + +## 1. Go to [app.honcho.dev](https://app.honcho.dev) + +Create an account to start using Honcho. If a teammate already uses Honcho, ask +them to invite you to their organization. Otherwise, you'll see a banner +prompting you to create a new one. + +
+ + Honcho Platform Dashboard + +
+ + +Once you've created an organization, you'll be taken to the dashboard and see +the Welcome page with integration guidance and links to documentation. + + + Honcho Dashboard Getting Started + + +Each organization has dedicated infrastructure running to isolate your +workloads. Once you add a valid payment method under the +[Billing](https://app.honcho.dev/billing) page, your instance will turn on. + +## 2. Activate your Honcho instance + +Navigate to the [Billing](https://app.honcho.dev/billing) page to add a payment method. Your Honcho instance provisions automatically, and you can monitor the deployment on the [Instance Status](https://app.honcho.dev/status) page until all systems show a green check mark. + + + Instance Status Page + + +You can also upgrade Honcho when new versions are made available directly from the status page. + +
+ + Upgrade Honcho + +
+ +The **Performance** page provides comprehensive monitoring with usage metrics, health analytics, API response times, and endpoint usage across Honcho. + + + Performance Analytics Dashboard + + +## 3. Manage API Keys +The [API Keys](https://app.honcho.dev/api-keys) page allows you to create and manage authentication tokens for different environments. You can create admin-level keys with full instance access or scope keys to specific `Workspaces`, `Peers`, or `Sessions`. + + + API Key Management Dashboard + + +## 4. Test with API Playground +The [API Playground](https://app.honcho.dev/playground) provides a Postman-like interface to test queries, explore endpoints, and validate your integration. Authenticate with an API key and send requests directly to your Honcho instance with real-time responses and full request/response logging. + + + API Playground Interface + + +## 5. Workspaces +The [Explore](https://app.honcho.dev/explore) page provides comprehensive `Workspace` management where you can create workspaces and begin exploring the platform. Each `Workspace` serves as a container for organizing your Honcho data. + + + Workspace Table + + +Click into any workspace to access a general overview of `Peers` and `Sessions`. Here you can quickly create `Peers`, `Sessions`, and add multiple `Peers` to any `Session`. Edit the metadata and configuration for a `Workspace` with the Edit Config button. Click into any entity to navigate to their respective utilities pages or click the expand icon to view Workspace-wide `Peers` and `Sessions` data tables with more details. + + + Workspace Dashboard Overview + + +## 6. Peer Dashboard & Utilities +Expand the `Peers` list from the `Workspace` dashboard to see a detailed view of `Peers`. + + + Peer Dashboard + + +Click into any peer to navigate to their respective utilities page. Next to the `Peer` name you can edit the [Global Peer Configuration](/v2/documentation/core-concepts/configuration), and in the tabs below, explore all utilities for the `Peer`. + + + Peer Management Dashboard + + +Utilities include: +- **Message search** across all sessions for a `Peer` +- **Dialectic Chat** to query `Peer` representations globally or session-scoped (results vary dependant on the `Peer`'s configuration) + + + Chat Endpoint + + +- **Session logs** view which `Sessions` the `Peer` is active +- **Peer configuration and metadata management** including [Session-Peer Configuration](/v2/documentation/core-concepts/configuration#session-peer-configuration) + + + Peer Management Dashboard + + +## 7. Session Dashboard & Utilities +Click into the sessions view within a workspace to see a table of all of your `Sessions` data. + + + Sessions Table + + +Click into a `Session` to open its utilities page. + + + Session Utilities + + +Here you can: +- **View and add Messages** within the `Session`; filter messages by `Peer` +- **Advanced search** across `Session` messages +- **Peer management** for adding/removing `Peers` and editing a `Peer`'s Session-level configuration +- **Get Context** to generate LLM-ready context with customizable token limits + + + Get Context + + +## 8. Webhooks Integration +The [Webhooks](https://app.honcho.dev/webhooks) page enables Webhook creation and management. + + + Webhooks Dashboard + + +## 9. Organization Member Access +The [Members](https://app.honcho.dev/members) page provides organization administration to manage your team's access to Honcho with the ability to grant admin permissions. + + + Members Dashboard + + +## Go Further + +View the [Architecture](/v2/documentation/core-concepts/architecture) to see how Honcho works under the hood. + +Dive into our [API Reference](/v2/api-reference) to explore all available endpoints. + +## Next Steps + + + + Get started with managed Honcho instances + + + Connect with 1000+ developers building with Honcho + + + View our guidelines and explore the codebase + + + See Honcho in action with real examples + + + +We're excited to see what you'll build with Honcho Platform. Let's create smarter, more personalized AI experiences together! + +--- + +*Ready to build personally aligned AI? [Get started with Honcho →](https://app.honcho.dev)* diff --git a/docs/v2.6.0-alpha/documentation/reference/sdk.mdx b/docs/v2.6.0-alpha/documentation/reference/sdk.mdx new file mode 100644 index 00000000..038e3cbc --- /dev/null +++ b/docs/v2.6.0-alpha/documentation/reference/sdk.mdx @@ -0,0 +1,1110 @@ +--- +title: 'SDK Reference' +description: 'Complete SDK documentation and examples for Python and TypeScript' +icon: 'code' +--- + +The Honcho SDKs provide ergonomic interfaces for building agentic AI applications with Honcho in Python and TypeScript/JavaScript. + +## Installation + + +```bash Python (uv) +uv add honcho-ai +``` + +```bash Python (pip) +pip install honcho-ai +``` + +```bash TypeScript (npm) +npm install @honcho-ai/sdk +``` + +```bash TypeScript (yarn) +yarn add @honcho-ai/sdk +``` + +```bash TypeScript (pnpm) +pnpm add @honcho-ai/sdk +``` + + +## Quickstart + + +Without configuration, the SDK defaults to the demo server. For production use: +1. Get your API key at [app.honcho.dev/api-keys](https://app.honcho.dev/api-keys) +2. Set `environment="production"` and provide your `api_key` + + + +```python Python +from honcho import Honcho + +# Initialize client (using the default workspace) +honcho = Honcho() + +# Create peers +alice = honcho.peer("alice") +assistant = honcho.peer("assistant") + +# Create a session for conversation +session = honcho.session("conversation-1") + +# Add messages to conversation +session.add_messages([ + alice.message("What's the weather like today?"), + assistant.message("It's sunny and 75°F outside!") +]) + +# Query peer representations in natural language +response = alice.chat("What did the assistant tell this user about the weather?") + +# Get conversation context for LLM completions +context = session.get_context() +openai_messages = context.to_openai(assistant=assistant) +``` + +```typescript TypeScript +import { Honcho } from "@honcho-ai/sdk"; + +// Initialize client (using the default workspace) +const honcho = new Honcho({}); + +// Create peers +const alice = await honcho.peer("alice"); +const assistant = await honcho.peer("assistant"); + +// Create a session for conversation +const session = await honcho.session("conversation-1"); + +// Add messages to conversation +await session.addMessages([ + alice.message("What's the weather like today?"), + assistant.message("It's sunny and 75°F outside!") +]); + +// Query peer representations in natural language +const response = await alice.chat("What did the assistant tell this user about the weather?"); + +// Get conversation context for LLM completions +const context = await session.getContext(); +const openaiMessages = context.toOpenAI(assistant); +``` + + +## Core Concepts + +### Peers and Representations + + +**Representations** are how Honcho models what peers know. Each peer has a **global representation** (everything they know across all sessions) and **local representations** (what other specific peers know about them, scoped by session or globally). + + + +```python Python +# Query alice's global knowledge +response = alice.chat("What does the user know about weather?") + +# Query what alice knows about the assistant (local representation) +response = alice.chat("What does the user know about the assistant?", target=assistant) + +# Query scoped to a specific session +response = alice.chat("What happened in our conversation?", session=session.id) +``` + +```typescript TypeScript +// Query alice's global knowledge +const response = await alice.chat("What does the user know about weather?"); + +// Query what alice knows about the assistant (local representation) +const targetResponse = await alice.chat("What does the user know about the assistant?", { + target: assistant +}); + +// Query scoped to a specific session +const sessionResponse = await alice.chat("What happened in our conversation?", { + sessionId: session.id +}); +``` + + +## Core Classes + +### Honcho Client + +The main entry point for workspace operations: + + +```python Python +from honcho import Honcho + +# Basic initialization (uses environment variables) +honcho = Honcho(workspace_id="my-app-name") + +# Full configuration +honcho = Honcho( + workspace_id="my-app-name", + api_key="my-api-key", + environment="production", # or "local", "demo" + base_url="https://api.honcho.dev", + timeout=30.0, + max_retries=3 +) +``` + +```typescript TypeScript +import { Honcho } from "@honcho-ai/sdk"; + +// Basic initialization (uses environment variables) +const honcho = new Honcho({ + workspaceId: "my-app-name" +}); + +// Full configuration +const honcho = new Honcho({ + workspaceId: "my-app-name", + apiKey: "my-api-key", + environment: "production", // or "local", "demo" + baseURL: "https://api.honcho.dev", + timeout: 30000, + maxRetries: 3, + defaultHeaders: { "X-Custom-Header": "value" }, + defaultQuery: { "param": "value" } +}); +``` + + +**Environment Variables:** +- `HONCHO_API_KEY` - API key for authentication +- `HONCHO_BASE_URL` - Base URL for the Honcho API +- `HONCHO_WORKSPACE_ID` - Default workspace ID + +**Key Methods:** + + +```python Python +# Get or create a peer +peer = honcho.peer(id) + +# Get or create a session +session = honcho.session(id) + +# List all peers in workspace +peers = honcho.get_peers() + +# List all sessions in workspace +sessions = honcho.get_sessions() + +# Search across all content in workspace +results = honcho.search(query) + +# Workspace metadata management +metadata = honcho.get_metadata() +honcho.set_metadata(dict) + +# Get list of all workspace IDs +workspaces = honcho.get_workspaces() +``` + +```typescript TypeScript +// Get or create a peer +const peer = await honcho.peer(id); + +// Get or create a session +const session = await honcho.session(id); + +// List all peers in workspace (returns Page) +const peers = await honcho.getPeers(); + +// List all sessions in workspace (returns Page) +const sessions = await honcho.getSessions(); + +// Search across all content in workspace (returns Page) +const results = await honcho.search(query); + +// Workspace metadata management +const metadata = await honcho.getMetadata(); +await honcho.setMetadata(metadata); + +// Get list of all workspace IDs +const workspaces = await honcho.getWorkspaces(); +``` + + + +Peer and session creation is **lazy** - no API calls are made until you actually use the peer or session. + + +### Peer + +Represents an entity that can participate in conversations: + + +```python Python +# Create peers (lazy creation - no API call yet) +alice = honcho.peer("alice") +assistant = honcho.peer("assistant") + +# Create with immediate configuration +# This will make an API call to create the peer with the custom configuration and/or metadata +alice = honcho.peer("bob", config={"role": "user", "active": True}, metadata={"location": "NYC", "role": "developer"}) + +# Peer properties +print(f"Peer ID: {alice.id}") +print(f"Workspace: {alice.workspace_id}") + +# Chat with peer's representations (supports streaming) +response = alice.chat("What did I have for breakfast?") +response = alice.chat("What do I know about Bob?", target="bob") +response = alice.chat("What happened in session-1?", session="session-1") + +# Add content to a session with a peer +session = honcho.session("session-1") +session.add_messages([ + alice.message("I love Python programming"), + alice.message("Today I learned about async programming"), + alice.message("I prefer functional programming patterns") +]) + +# Get peer's sessions +sessions = alice.get_sessions() + +# Search peer's messages +results = alice.search("programming") + +# Metadata management +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 +// Create peers (returns Promise) +const alice = await honcho.peer("alice"); +const assistant = await honcho.peer("assistant"); + +// Peer properties +console.log(`Peer ID: ${alice.id}`); + +// Chat with peer's representations (supports streaming) +const response = await alice.chat("What did I have for breakfast?"); +const targetResponse = await alice.chat("What do I know about Bob?", { target: "bob" }); +const sessionResponse = await alice.chat("What happened in session-1?", { + sessionId: "session-1" +}); + +// Chat with streaming support +const streamResponse = await alice.chat("Tell me a story", { stream: true }); + +// Add content to a session with a peer +const session = await honcho.session("session-1"); +await session.addMessages([ + alice.message("I love TypeScript programming"), + alice.message("Today I learned about async programming"), + alice.message("I prefer functional programming patterns") +]); + +// Get peer's sessions +const sessions = await alice.getSessions(); + +// Search peer's messages +const results = await alice.search("programming"); + +// Metadata management +const metadata = await alice.getMetadata(); +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"); +``` + + +### 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"); +``` + + +#### Creating Observations Manually + +You can also create observations directly, which is useful for importing data or adding explicit facts: + + +```python Python +# Create observations for what alice knows about bob +bob_obs = alice.observations_of("bob") + +# Create a single observation +created = bob_obs.create([ + {"content": "User prefers dark mode", "session_id": "session-1"} +]) + +# Create multiple observations in batch +created = bob_obs.create([ + {"content": "User prefers dark mode", "session_id": "session-1"}, + {"content": "User works late at night", "session_id": "session-1"}, + {"content": "User enjoys programming", "session_id": "session-1"}, +]) + +# Returns list of created Observation objects with IDs +for obs in created: + print(f"Created observation: {obs.id} - {obs.content}") +``` + +```typescript TypeScript +// Create observations for what alice knows about bob +const bobObs = alice.observationsOf("bob"); + +// Create a single observation +const created = await bobObs.create([ + { content: "User prefers dark mode", sessionId: "session-1" } +]); + +// Create multiple observations in batch +const batchCreated = await bobObs.create([ + { content: "User prefers dark mode", sessionId: "session-1" }, + { content: "User works late at night", sessionId: "session-1" }, + { content: "User enjoys programming", sessionId: "session-1" }, +]); + +// Returns array of created Observation objects with IDs +for (const obs of batchCreated) { + console.log(`Created observation: ${obs.id} - ${obs.content}`); +} +``` + + + +Manually created observations are marked as "explicit" and are treated the same as system-derived observations. Each observation must be tied to a session and the content length is validated against the embedding token limit. + + +### Session + +Manages multi-party conversations: + + +```python Python +# Create session (like peers, lazy creation) +session = honcho.session("conversation-1") + +# Create with immediate configuration +# This will make an API call to create the session with the custom configuration and/or metadata +session = honcho.session("meeting-1", config={"type": "meeting", "max_peers": 10}) + +# Session properties +print(f"Session ID: {session.id}") +print(f"Workspace: {session.workspace_id}") + +# Peer management +session.add_peers([alice, assistant]) +session.add_peers([(alice, SessionPeerConfig(observe_others=True))]) +session.set_peers([alice, bob, charlie]) # Replace all peers +session.remove_peers([alice]) + +# Get session peers and their configurations +peers = session.get_peers() +peer_config = session.get_peer_config(alice) +session.set_peer_config(alice, SessionPeerConfig(observe_me=False)) + +# Message management +session.add_messages([ + alice.message("Hello everyone!"), + assistant.message("Hi Alice! How can I help today?") +]) + +# Get messages +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 with semantic search +global_rep = session.working_rep("alice") +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="user", + metadata={"source": "upload"}, + created_at="2024-01-15T10:30:00Z" +) + +# Clone a session (creates a copy with all data) +# Copies: messages, metadata, configuration, peers, and peer configurations +cloned = session.clone() + +# Clone up to a specific message (inclusive) +# Only messages up to and including the specified message are copied +cloned_partial = session.clone(message_id="msg-123") + +# Delete session (async - returns 202) +session.delete() + +# Metadata management +session.set_metadata({"topic": "product planning", "status": "active"}) +metadata = session.get_metadata() +``` + +```typescript TypeScript +// Create session (returns Promise) +const session = await honcho.session("conversation-1"); + +// Session properties +console.log(`Session ID: ${session.id}`); + +// Peer management +await session.addPeers([alice, assistant]); +await session.addPeers("single-peer-id"); +await session.setPeers([alice, bob, charlie]); // Replace all peers +await session.removePeers([alice]); +await session.removePeers("single-peer-id"); + +// Get session peers +const peers = await session.getPeers(); + +// Message management +await session.addMessages([ + alice.message("Hello everyone!"), + assistant.message("Hi Alice! How can I help today?") +]); + +// Get messages +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 with semantic search +const globalRep = await session.workingRep("alice"); +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" + } +); + +// Clone a session (creates a copy with all data) +// Copies: messages, metadata, configuration, peers, and peer configurations +const cloned = await session.clone(); + +// Clone up to a specific message (inclusive) +// Only messages up to and including the specified message are copied +const clonedPartial = await session.clone("msg-123"); + +// Delete session (async - returns 202) +await session.delete(); + +// Metadata management +await session.setMetadata({ + topic: "product planning", + status: "active" +}); +const metadata = await session.getMetadata(); +``` + + +**Session-Level Theory of Mind Configuration:** + + +**Theory of Mind** controls whether peers can form models of what other peers think. Use `observe_others=False` to prevent a peer from modeling others within a session, and `observe_me=False` to prevent others from modeling this peer within a session. + + + +```python Python +from honcho import SessionPeerConfig + +# Configure peer observation settings +config = SessionPeerConfig( + observe_others=False, # Form theory-of-mind of other peers -- False by default + observe_me=True # Don't let others form theory-of-mind of me -- True by default +) + +session.add_peers([(alice, config)]) +``` + +```typescript TypeScript +// Configure peer observation settings +const config = new SessionPeerConfig({ + observeOthers: false, // Form theory-of-mind of other peers -- False by default + observeMe: true // Don't let others form theory-of-mind of me -- True by default +}); + +await session.addPeers([alice, config]); +``` + + +### SessionContext + +Provides formatted conversation context for LLM integration: + + +```python Python +# Get session context +context = session.get_context(summary=True, tokens=1500) + +# Convert to LLM-friendly formats +openai_messages = context.to_openai(assistant=assistant) +anthropic_messages = context.to_anthropic(assistant=assistant) +``` + +```typescript TypeScript +// Get session context +const context = await session.getContext({ summary: true, tokens: 1500 }); + +// Convert to LLM-friendly formats +const openaiMessages = context.toOpenAI(assistant); +const anthropicMessages = context.toAnthropic(assistant); +``` + + +The SessionContext object has the following structure: + +```json +{ + "id": "string", + "messages": [ + { + "id": "string", + "content": "string", + "peer_id": "string", + "session_id": "string", + "workspace_id": "string", + "metadata": {}, + "created_at": "2024-01-15T10:30:00Z", + "token_count": 42 + } + ], + "summary": { + "content": "string", + "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 + + +```python Python +# Create multiple peers +users = [honcho.peer(f"user-{i}") for i in range(5)] +moderator = honcho.peer("moderator") + +# Create group session +group_chat = honcho.session("group-discussion") +group_chat.add_peers(users + [moderator]) + +# Add messages from different peers +group_chat.add_messages([ + users[0].message("What's our agenda for today?"), + moderator.message("We'll discuss the new feature roadmap"), + users[1].message("I have some concerns about the timeline") +]) + +# Query different perspectives +user_perspective = users[0].chat("What are people's concerns?") +moderator_view = moderator.chat("What feedback am I getting?", session=group_chat.id) +``` + +```typescript TypeScript +// Create multiple peers +const users = await Promise.all( + Array.from({ length: 5 }, (_, i) => honcho.peer(`user-${i}`)) +); +const moderator = await honcho.peer("moderator"); + +// Create group session +const groupChat = await honcho.session("group-discussion"); +await groupChat.addPeers([...users, moderator]); + +// Add messages from different peers +await groupChat.addMessages([ + users[0].message("What's our agenda for today?"), + moderator.message("We'll discuss the new feature roadmap"), + users[1].message("I have some concerns about the timeline") +]); + +// Query different perspectives +const userPerspective = await users[0].chat("What are people's concerns?"); +const moderatorView = await moderator.chat("What feedback am I getting?", { + sessionId: groupChat.id +}); +``` + + +### LLM Integration + + +```python Python +import openai + +# Get conversation context +context = session.get_context(tokens=3000) +messages = context.to_openai(assistant=assistant) + +# Call OpenAI API +response = openai.chat.completions.create( + model="gpt-4", + messages=messages + [ + {"role": "user", "content": "Summarize the key discussion points."} + ] +) +``` + +```typescript TypeScript +import OpenAI from 'openai'; + +const openai = new OpenAI(); + +// Get conversation context +const context = await session.getContext({ tokens: 3000 }); +const messages = context.toOpenAI(assistant); + +// Call OpenAI API +const response = await openai.chat.completions.create({ + model: "gpt-4", + messages: [ + ...messages, + { role: "user", content: "Summarize the key discussion points." } + ] +}); +``` + + +### Custom Message Timestamps + +When creating messages, you can optionally specify a custom `created_at` timestamp instead of using the server's current time: + +```bash +curl -X POST "https://api.honcho.dev/v2/workspaces/{workspace_id}/sessions/{session_id}/messages" \ + -H "Authorization: Bearer $API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "messages": [ + { + "peer_id": "user123", + "content": "This message happened yesterday", + "created_at": "2024-01-01T12:00:00Z", + "metadata": {"source": "historical_data"} + } + ] + }' +``` + +This is useful for: +- Importing historical conversation data +- Backfilling messages from other systems +- Maintaining accurate timeline ordering when processing batch data + +If `created_at` is not provided, messages will use the server's current timestamp. + +### Metadata and Filtering + +See [Using Filters](/v2/guides/using-filters) for more examples on how to use filters. + + +```python Python +# Add messages with metadata +session.add_messages([ + alice.message("Let's discuss the budget", metadata={ + "topic": "finance", + "priority": "high" + }), + assistant.message("I'll prepare the financial report", metadata={ + "action_item": True, + "due_date": "2024-01-15" + }) +]) + +# Filter messages by metadata +finance_messages = session.get_messages(filters={"metadata": {"topic": "finance"}}) +action_items = session.get_messages(filters={"metadata": {"action_item": True}}) +``` + +```typescript TypeScript +// Add messages with metadata +await session.addMessages([ + alice.message("Let's discuss the budget", { + metadata: { + topic: "finance", + priority: "high" + } + }), + assistant.message("I'll prepare the financial report", { + metadata: { + action_item: true, + due_date: "2024-01-15" + } + }) +]); + +// Filter messages by metadata +const financeMessages = await session.getMessages({ + filters: { metadata: { topic: "finance" } } +}); +const actionItems = await session.getMessages({ + filters: { metadata: { action_item: true } } +}); +``` + + +### Pagination + + +```python Python +# Iterate through all sessions +for session in honcho.get_sessions(): + print(f"Session: {session.id}") + + # Iterate through session messages + for message in session.get_messages(): + print(f" {message.peer_id}: {message.content}") +``` + +```typescript TypeScript +// Get paginated results +const peersPage = await honcho.getPeers(); + +// Iterate through all items +for await (const peer of peersPage) { + console.log(`Peer: ${peer.id}`); +} + +// Manual pagination +let currentPage = peersPage; +while (currentPage) { + const data = await currentPage.data(); + console.log(`Processing ${data.length} items`); + currentPage = await currentPage.nextPage(); +} +``` + + +## Best Practices + +### Resource Management + + +```python Python +# Peers and sessions are lightweight - create as needed +alice = honcho.peer("alice") +session = honcho.session("chat-1") + +# Use descriptive IDs for better debugging +user_session = honcho.session(f"user-{user_id}-support-{ticket_id}") +support_agent = honcho.peer(f"agent-{agent_id}") +``` + +```typescript TypeScript +// Peers and sessions are lightweight - create as needed +const alice = await honcho.peer("alice"); +const session = await honcho.session("chat-1"); + +// Use descriptive IDs for better debugging +const userSession = await honcho.session(`user-${userId}-support-${ticketId}`); +const supportAgent = await honcho.peer(`agent-${agentId}`); +``` + + +### Performance Optimization + + +```python Python +# Lazy creation - no API calls until needed +peers = [honcho.peer(f"user-{i}") for i in range(100)] # Fast + +# Batch operations when possible +session.add_messages([peer.message(f"Message {i}") for i, peer in enumerate(peers)]) + +# Use context limits to control token usage +context = session.get_context(tokens=1500) # Limit context size +``` + +```typescript TypeScript +// Lazy creation - no API calls until needed +const peers = await Promise.all( + Array.from({ length: 100 }, (_, i) => honcho.peer(`user-${i}`)) +); + +// Batch operations when possible +await session.addMessages( + peers.map((peer, i) => peer.message(`Message ${i}`)) +); + +// Use context limits to control token usage +const context = await session.getContext({ tokens: 1500 }); // Limit context size + +// Iterate efficiently with async iteration +for await (const peer of await honcho.getPeers()) { + // Process one peer at a time without loading all into memory +} +``` + diff --git a/docs/v2/documentation/reference/storage.mdx b/docs/v2.6.0-alpha/documentation/reference/storage.mdx similarity index 100% rename from docs/v2/documentation/reference/storage.mdx rename to docs/v2.6.0-alpha/documentation/reference/storage.mdx diff --git a/docs/v2/documentation/scratch/honcho-memory/advanced-retrieval/get-context.mdx b/docs/v2.6.0-alpha/documentation/scratch/honcho-memory/advanced-retrieval/get-context.mdx similarity index 100% rename from docs/v2/documentation/scratch/honcho-memory/advanced-retrieval/get-context.mdx rename to docs/v2.6.0-alpha/documentation/scratch/honcho-memory/advanced-retrieval/get-context.mdx diff --git a/docs/v2/documentation/scratch/honcho-memory/quickstart.mdx b/docs/v2.6.0-alpha/documentation/scratch/honcho-memory/quickstart.mdx similarity index 100% rename from docs/v2/documentation/scratch/honcho-memory/quickstart.mdx rename to docs/v2.6.0-alpha/documentation/scratch/honcho-memory/quickstart.mdx diff --git a/docs/v2/documentation/scratch/local-vs-global.mdx b/docs/v2.6.0-alpha/documentation/scratch/local-vs-global.mdx similarity index 100% rename from docs/v2/documentation/scratch/local-vs-global.mdx rename to docs/v2.6.0-alpha/documentation/scratch/local-vs-global.mdx diff --git a/docs/v2/documentation/scratch/working-rep.mdx b/docs/v2.6.0-alpha/documentation/scratch/working-rep.mdx similarity index 100% rename from docs/v2/documentation/scratch/working-rep.mdx rename to docs/v2.6.0-alpha/documentation/scratch/working-rep.mdx diff --git a/docs/v2.6.0-alpha/guides/discord.mdx b/docs/v2.6.0-alpha/guides/discord.mdx new file mode 100644 index 00000000..5b24dca8 --- /dev/null +++ b/docs/v2.6.0-alpha/guides/discord.mdx @@ -0,0 +1,254 @@ +--- +title: "Discord Bots with Honcho" +icon: 'discord' +description: "Use Honcho to build a Discord bot with conversational memory and context management." +sidebarTitle: 'Discord Bot' +--- + +> Example code is available on [GitHub](https://github.com/plastic-labs/discord-python-starter) + +Any application interface that defines logic based on events and supports +special commands can work easily with Honcho. Here's how to use Honcho with +**Discord** as an interface. If you're not familiar with Discord bot +application logic, the [py-cord](https://pycord.dev/) docs would be a good +place to start. + +## Events + +Most Discord bots have async functions that listen for specific events, the most common one being messages. We can use Honcho to store messages by user and session based on an interface's event logic. Take the following function definition for example: + +```python +@bot.event +async def on_message(message): + """ + Receive a message from Discord and respond with a message from our LLM assistant. + """ + if not validate_message(message): + return + + input = sanitize_message(message) + + # If the message is empty after sanitizing, ignore it + if not input: + return + + peer = honcho_client.peer(id=get_peer_id_from_discord(message)) + session = honcho_client.session(id=str(message.channel.id)) + + async with message.channel.typing(): + response = llm(session, input) + + await send_discord_message(message, response) + + # Save both the user's message and the bot's response to the session + session.add_messages( + [ + peer.message(input), + assistant.message(response), + ] + ) +``` + +Let's break down what this code is doing... + +```python +@bot.event +async def on_message(message): + if not validate_message(message): + return +``` + +This is how you define an event function in `py-cord` that listens for messages. We use a helper function `validate_message()` to check if the message should be processed. + +## Helper Functions + +The code uses several helper functions to keep the main logic clean and readable. Let's examine each one: + +### Message Validation + +```python +def validate_message(message) -> bool: + """ + Determine if the message is valid for the bot to respond to. + Return True if it is, False otherwise. Currently, the bot will + only respond to messages that tag it with an @mention in a + public channel and are not from the bot itself. + """ + if message.author == bot.user: + # ensure the bot does not reply to itself + return False + + if isinstance(message.channel, discord.DMChannel): + return False + + if not bot.user.mentioned_in(message): + return False + + return True +``` + +This function centralizes all the logic for determining whether the bot should respond to a message. It checks that: +- The message isn't from the bot itself +- The message isn't in a DM channel +- The bot is mentioned in the message + +### Message Sanitization + +```python +def sanitize_message(message) -> str | None: + """Remove the bot's mention from the message content if present""" + content = message.content.replace(f"<@{bot.user.id}>", "").strip() + if not content: + return None + return content +``` + +This helper removes the bot's mention from the message content, leaving just the actual user input. + +### Peer ID Generation + +```python +def get_peer_id_from_discord(message): + """Get a Honcho peer ID for the message author""" + return f"discord_{str(message.author.id)}" +``` + +This creates a unique peer identifier for each Discord user by prefixing their Discord ID. + +### LLM Integration + +```python +def llm(session, prompt) -> str: + """ + Call the LLM with the given prompt and chat history. + + You should expand this function with custom logic, prompts, etc. + """ + messages: list[dict[str, object]] = session.get_context().to_openai( + assistant=assistant + ) + messages.append({"role": "user", "content": prompt}) + + try: + completion = openai.chat.completions.create( + model=MODEL_NAME, + messages=messages, + ) + return completion.choices[0].message.content + except Exception as e: + print(e) + return f"Error: {e}" +``` + +This function handles the LLM interaction. It uses Honcho's built-in `to_openai()` method to automatically convert the session context into the format expected by OpenAI's chat completions API. + +### Message Sending + +```python +async def send_discord_message(message, response_content: str): + """Send a message to the Discord channel""" + if len(response_content) > 1500: + # Split response into chunks at newlines, keeping under 1500 chars + chunks = [] + current_chunk = "" + for line in response_content.splitlines(keepends=True): + if len(current_chunk) + len(line) > 1500: + chunks.append(current_chunk) + current_chunk = line + else: + current_chunk += line + if current_chunk: + chunks.append(current_chunk) + + for chunk in chunks: + await message.channel.send(chunk) + else: + await message.channel.send(response_content) +``` + +This function handles sending messages to Discord, automatically splitting long responses into multiple messages to stay within Discord's character limits. + +## Honcho Integration + +The new Honcho peer/session API makes integration much simpler: + +```python +peer = honcho_client.peer(id=get_peer_id_from_discord(message)) +session = honcho_client.session(id=str(message.channel.id)) +``` + +Here we create a peer object for the user and a session object using the Discord channel ID. This automatically handles user and session management. + +```python +# Save both the user's message and the bot's response to the session +session.add_messages( + [ + peer.message(input), + assistant.message(response), + ] +) +``` + +After generating the response, we save both the user's input and the bot's response to the session using the `add_messages()` method. The `peer.message()` creates a message from the user, while `assistant.message()` creates a message from the assistant. + +## Slash Commands + +Discord bots also offer slash command functionality. Here's an example using Honcho's chat endpoint feature: + +```python +@bot.slash_command( + name="chat", + description="Query the peer's representation in natural language.", +) +async def chat(ctx, query: str): + await ctx.defer() + + try: + peer = honcho_client.peer(id=get_peer_id_from_discord(ctx)) + session = honcho_client.session(id=str(ctx.channel.id)) + + response = peer.chat( + query=query, + session_id=session.id, + ) + + if response: + await ctx.followup.send(response) + else: + await ctx.followup.send( + f"I don't know anything about {ctx.author.name} because we haven't talked yet!" + ) + except Exception as e: + logger.error(f"Error calling Dialectic API: {e}") + await ctx.followup.send( + f"Sorry, there was an error processing your request: {str(e)}" + ) +``` + +This slash command uses Honcho's chat endpoint functionality to answer questions about the user based on their conversation history. + +## Setup and Configuration + +The bot requires several environment variables and setup: + +```python +honcho_client = Honcho() +assistant = honcho_client.peer(id="assistant", config={"observe_me": False}) +openai = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=MODEL_API_KEY) +``` + +- `honcho_client`: The main Honcho client +- `assistant`: A peer representing the bot/assistant +- `openai`: OpenAI client configured to use OpenRouter + +## Recap + +The new Honcho peer/session API makes Discord bot integration much simpler and more intuitive. Key patterns we learned: + +- **Peer/Session Model**: Users are represented as peers, conversations as sessions +- **Automatic Context Management**: `session.get_context().to_openai()` automatically formats chat history +- **Message Storage**: `session.add_messages()` stores both user and assistant messages +- **Representation Queries**: `peer.chat()` enables querying conversation history +- **Helper Functions**: Clean code organization with focused helper functions + +This approach provides a clean, maintainable structure for building Discord bots with conversational memory and context management. diff --git a/docs/v2/guides/file-uploads.mdx b/docs/v2.6.0-alpha/guides/file-uploads.mdx similarity index 100% rename from docs/v2/guides/file-uploads.mdx rename to docs/v2.6.0-alpha/guides/file-uploads.mdx diff --git a/docs/v2/guides/integrations/crewai.mdx b/docs/v2.6.0-alpha/guides/integrations/crewai.mdx similarity index 100% rename from docs/v2/guides/integrations/crewai.mdx rename to docs/v2.6.0-alpha/guides/integrations/crewai.mdx diff --git a/docs/v2/guides/integrations/langgraph.mdx b/docs/v2.6.0-alpha/guides/integrations/langgraph.mdx similarity index 100% rename from docs/v2/guides/integrations/langgraph.mdx rename to docs/v2.6.0-alpha/guides/integrations/langgraph.mdx diff --git a/docs/v2/guides/integrations/mcp.mdx b/docs/v2.6.0-alpha/guides/integrations/mcp.mdx similarity index 100% rename from docs/v2/guides/integrations/mcp.mdx rename to docs/v2.6.0-alpha/guides/integrations/mcp.mdx diff --git a/docs/v2/guides/migrations/mem0.mdx b/docs/v2.6.0-alpha/guides/migrations/mem0.mdx similarity index 100% rename from docs/v2/guides/migrations/mem0.mdx rename to docs/v2.6.0-alpha/guides/migrations/mem0.mdx diff --git a/docs/v2.6.0-alpha/guides/overview.mdx b/docs/v2.6.0-alpha/guides/overview.mdx new file mode 100644 index 00000000..bfd96981 --- /dev/null +++ b/docs/v2.6.0-alpha/guides/overview.mdx @@ -0,0 +1,37 @@ +--- +title: "Guides, Cookbooks, and Integrations" +sidebarTitle: 'Overview' +description: 'Helpful guides and design patterns for building with Honcho' +icon: 'hat-wizard' +--- + + Before you start a guide, follow [Quickstart](/v2/documentation/introduction/quickstart) to get up and running with Honcho in your language of choice. + +These guides provide concrete examples and implementation patterns for building with Honcho. Whether you're integrating Honcho into existing platforms, exploring advanced features, or getting up and running quickly, you'll find working code you can adapt to your needs. + +Each guide focuses on a specific use case with practical examples. The goal is to get you from idea to working prototype as quickly as possible, then provide the depth you need to scale and customize. + + +## Getting Started +Quick integration guides to get up and running: + + + + Get Honcho running with a single prompt in Claude Code + + + Add persistent memory and theory of mind to your LangGraph agents + + + +## Application Interfaces +Ready-to-use integration patterns for popular platforms: + + + + Build a Discord bot that remembers users across conversations + + + Create a Telegram bot with persistent user understanding + + diff --git a/docs/v2/guides/storing-data.mdx b/docs/v2.6.0-alpha/guides/storing-data.mdx similarity index 100% rename from docs/v2/guides/storing-data.mdx rename to docs/v2.6.0-alpha/guides/storing-data.mdx diff --git a/docs/v2.6.0-alpha/guides/telegram.mdx b/docs/v2.6.0-alpha/guides/telegram.mdx new file mode 100644 index 00000000..5c79c632 --- /dev/null +++ b/docs/v2.6.0-alpha/guides/telegram.mdx @@ -0,0 +1,359 @@ +--- +title: "Telegram Bots with Honcho" +icon: 'telegram' +description: "Use Honcho to build a Telegram bot with conversational memory and context management." +sidebarTitle: 'Telegram Bot' +--- + +> Example code is available on [GitHub](https://github.com/plastic-labs/telegram-python-starter) + +Any application interface that defines logic based on events and supports +special commands can work easily with Honcho. Here's how to use Honcho with +**Telegram** as an interface. If you're not familiar with Telegram bot +development, the [python-telegram-bot](https://docs.python-telegram-bot.org/en/stable/) docs would be a good +place to start. + +## Message Handling + +Most Telegram bots have async functions that handle incoming messages. We can use Honcho to store messages by user and session based on the chat context. Take the following function definition for example: + +```python +async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): + """ + Receive a message from Telegram and respond with a message from our LLM assistant. + """ + if not validate_message(update, context): + return + + message_text = update.effective_message.text + input_text = sanitize_message(message_text, context.bot.username) + + # If the message is empty after sanitizing, ignore it + if not input_text: + return + + peer = honcho_client.peer(id=get_peer_id_from_telegram(update)) + session = honcho_client.session(id=str(update.effective_chat.id)) + + # Send typing indicator + await context.bot.send_chat_action( + chat_id=update.effective_chat.id, action="typing" + ) + + response = llm(session, input_text) + + await send_telegram_message(update, context, response) + + # Save both the user's message and the bot's response to the session + session.add_messages( + [ + peer.message(input_text), + assistant.message(response), + ] + ) +``` + +Let's break down what this code is doing... + +```python +async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): + if not validate_message(update, context): + return +``` + +This is how you define a message handler in `python-telegram-bot` that processes incoming messages. We use a helper function `validate_message()` to check if the message should be processed. + +## Helper Functions + +The code uses several helper functions to keep the main logic clean and readable. Let's examine each one: + +### Message Validation + +```python +def validate_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> bool: + """ + Determine if the message is valid for the bot to respond to. + Return True if it is, False otherwise. The bot will respond to: + - Direct messages (private chats) + - Group messages that mention the bot or reply to it + - Messages that are not from the bot itself + """ + message = update.effective_message + + if not message or not message.text: + return False + + # Don't respond to our own messages + if message.from_user.id == context.bot.id: + return False + + # Always respond in private chats + if update.effective_chat.type == "private": + return True + + # In groups, only respond if mentioned or replied to + if ( + message.reply_to_message + and message.reply_to_message.from_user.id == context.bot.id + ): + return True + + # Check if bot is mentioned + if message.entities: + for entity in message.entities: + if entity.type == "mention": + username = message.text[entity.offset : entity.offset + entity.length] + if username == f"@{context.bot.username}": + return True + + return False +``` + +This function centralizes all the logic for determining whether the bot should respond to a message. It handles different chat types: +- **Private chats**: Always respond +- **Group chats**: Only respond when mentioned or when replying to the bot's messages +- **Bot prevention**: Never respond to the bot's own messages + +### Message Sanitization + +```python +def sanitize_message(message_text: str, bot_username: str) -> str | None: + """Remove the bot's mention from the message content if present""" + content = message_text.replace(f"@{bot_username}", "").strip() + if not content: + return None + return content +``` + +This helper removes the bot's mention from the message content, leaving just the actual user input. + +### Peer ID Generation + +```python +def get_peer_id_from_telegram(update: Update) -> str: + """Get a Honcho peer ID for the message author""" + return f"telegram_{update.effective_user.id}" +``` + +This creates a unique peer identifier for each Telegram user by prefixing their Telegram user ID. + +### LLM Integration + +```python +def llm(session, prompt) -> str: + """ + Call the LLM with the given prompt and chat history. + + You should expand this function with custom logic, prompts, etc. + """ + messages: list[dict[str, object]] = session.get_context().to_openai( + assistant=assistant + ) + messages.append({"role": "user", "content": prompt}) + + try: + completion = openai.chat.completions.create( + model=MODEL_NAME, + messages=messages, + ) + return completion.choices[0].message.content + except Exception as e: + logger.error(f"LLM error: {e}") + return f"Error: {e}" +``` + +This function handles the LLM interaction. It uses Honcho's built-in `to_openai()` method to automatically convert the session context into the format expected by OpenAI's chat completions API. + +### Message Sending + +```python +async def send_telegram_message( + update: Update, context: ContextTypes.DEFAULT_TYPE, response_content: str +): + """Send a message to the Telegram chat, splitting if necessary""" + # Telegram has a 4096 character limit, but we'll use 4000 to be safe + max_length = 4000 + + if len(response_content) <= max_length: + await update.effective_message.reply_text(response_content) + else: + # Split response into chunks at newlines, keeping under max_length chars + chunks = [] + current_chunk = "" + + for line in response_content.splitlines(keepends=True): + if len(current_chunk) + len(line) > max_length: + if current_chunk: + chunks.append(current_chunk) + current_chunk = line + else: + current_chunk += line + + if current_chunk: + chunks.append(current_chunk) + + for chunk in chunks: + await update.effective_message.reply_text(chunk) +``` + +This function handles sending messages to Telegram, automatically splitting long responses into multiple messages to stay within Telegram's 4096 character limit. It also includes a typing indicator to show the bot is processing. + +## Honcho Integration + +The new Honcho peer/session API makes integration much simpler: + +```python +peer = honcho_client.peer(id=get_peer_id_from_telegram(update)) +session = honcho_client.session(id=str(update.effective_chat.id)) +``` + +Here we create a peer object for the user and a session object using the Telegram chat ID. This automatically handles user and session management across both private chats and group conversations. + +```python +# Save both the user's message and the bot's response to the session +session.add_messages( + [ + peer.message(input_text), + assistant.message(response), + ] +) +``` + +After generating the response, we save both the user's input and the bot's response to the session using the `add_messages()` method. The `peer.message()` creates a message from the user, while `assistant.message()` creates a message from the assistant. + +## Commands + +Telegram bots support slash commands natively. Here's how to implement the `/dialectic` command using Honcho's dialectic feature: + +```python +async def dialectic_command(update: Update, context: ContextTypes.DEFAULT_TYPE): + """ + Handle the /dialectic command to query the Honcho Dialectic endpoint. + """ + if not context.args: + await update.message.reply_text( + "Please provide a query. Usage: /dialectic " + ) + return + + query = " ".join(context.args) + + try: + peer = honcho_client.peer(id=get_peer_id_from_telegram(update)) + session = honcho_client.session(id=str(update.effective_chat.id)) + + response = peer.chat( + query=query, + session_id=session.id, + ) + + if response: + await send_telegram_message(update, context, response) + else: + await update.message.reply_text( + f"I don't know anything about {update.effective_user.first_name} because we haven't talked yet!" + ) + except Exception as e: + logger.error(f"Error calling Dialectic API: {e}") + await update.message.reply_text( + f"Sorry, there was an error processing your request: {str(e)}" + ) +``` + +You can also add a `/start` command for user onboarding: + +```python +async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Handle the /start command""" + await update.message.reply_text( + "Hello! I'm your AI assistant. You can:\n" + "• Chat with me directly in private messages\n" + "• Mention me (@username) in groups to get my attention\n" + "• Use /dialectic to search our conversation history\n\n" + "Let's start chatting!" + ) +``` + +## Setup and Configuration + +The bot requires several environment variables and setup: + +```python +honcho_client = Honcho() +assistant = honcho_client.peer(id="assistant", config={"observe_me": False}) +openai = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=MODEL_API_KEY) +``` + +- `honcho_client`: The main Honcho client +- `assistant`: A peer representing the bot/assistant +- `openai`: OpenAI client configured to use OpenRouter + +### Application Setup + +Register your handlers with the Telegram application: + +```python +def main(): + """Start the bot""" + if not BOT_TOKEN: + logger.error("BOT_TOKEN not found in environment variables") + return + + # Create the Application + application = Application.builder().token(BOT_TOKEN).build() + + # Add handlers + application.add_handler(CommandHandler("start", start_command)) + application.add_handler(CommandHandler("dialectic", dialectic_command)) + application.add_handler( + MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message) + ) + + # Start the bot + logger.info("Starting Telegram bot...") + application.run_polling(allowed_updates=Update.ALL_TYPES) +``` + +## Environment Variables + +Your bot needs these environment variables: + +```env +# Your Telegram bot token from BotFather +BOT_TOKEN= + +# AI model to use (see OpenRouter for available models) +MODEL_NAME= + +# Your OpenRouter API key +MODEL_API_KEY= +``` + +## Chat Types and Behavior + +The bot handles different Telegram chat types intelligently: + +### Private Chats +- **Behavior**: Responds to all messages +- **Session ID**: Uses the private chat ID +- **Memory**: Maintains conversation history per user + +### Group Chats +- **Behavior**: Only responds when mentioned or replied to +- **Session ID**: Uses the group chat ID (shared across all members) +- **Memory**: Maintains group conversation context + +## Recap + +The new Honcho peer/session API makes Telegram bot integration much simpler and more intuitive. Key patterns we learned: + +- **Peer/Session Model**: Users are represented as peers, conversations as sessions +- **Chat Type Handling**: Different validation logic for private vs group chats +- **Automatic Context Management**: `session.get_context().to_openai()` automatically formats chat history +- **Message Storage**: `session.add_messages()` stores both user and assistant messages +- **Dialectic Queries**: `peer.chat()` enables querying conversation history +- **Command System**: Native Telegram command support with `/start` and `/dialectic` +- **Message Splitting**: Automatic handling of Telegram's character limits +- **Helper Functions**: Clean code organization with focused helper functions + +This approach provides a clean, maintainable structure for building Telegram bots with conversational memory and context management across both private conversations and group chats. diff --git a/docs/v2.6.0-alpha/migrations/from-mem0.mdx b/docs/v2.6.0-alpha/migrations/from-mem0.mdx new file mode 100644 index 00000000..76ab7514 --- /dev/null +++ b/docs/v2.6.0-alpha/migrations/from-mem0.mdx @@ -0,0 +1,296 @@ +--- +title: 'Migrating from Mem0' +description: 'A guide to migrate from Mem0 to Honcho' +icon: 'arrow-right-arrow-left' +--- + +Interested in transferring your data from Mem0 to Honcho? This guide covers why to switch, how to migrate your data, and differences between the two products. + + + +## Why Honcho? +Mem0 & Honcho both store your data. Only Honcho reasons about it. [Read more about our approach](https://blog.plasticlabs.ai/blog/Memory-as-Reasoning). + +**Compounding Insights** - Honcho extracts insights that build on each other over time. The more your users interact, the richer and more accurate their profiles become. + +**Superior Performance** - Higher accuracy on memory retrieval benchmarks with faster inference times (more details soon!). + +**Competitive Pricing** - Mem0 charges for retrieval, not ingestion. Meaning you pay to access your own data. Honcho offers straightforward pricing with a generous free tier. + +**Advanced Multi-Peer Sessions** - Honcho offers configurable observation settings (who builds memories about whom), representation-based queries between participants, and first-class peer objects. + + +We would love to support the transfer and cost—just [book a call!](https://cal.com/team/plasticlabs/migration-to-honcho) + + +## Quick Migration + +For the best results, we recommend importing your raw messages directly into Honcho. This gives Honcho the full context to build rich, accurate representations and enables features like session summaries. + +However, if you'd like to get started quickly, you can migrate your existing Mem0 memories directly as **observations**. + + +Get your API key at [app.honcho.dev/api-keys](https://app.honcho.dev/api-keys). New accounts start with $100 credits. + + + +```python Python +# pip install mem0ai honcho-ai +from mem0 import MemoryClient +from honcho import Honcho + +# Export from Mem0 +mem0 = MemoryClient(api_key="your-mem0-api-key") +memories = mem0.get_all(filters={"user_id": "user123"}, page_size=100) + +# Initialize Honcho +honcho = Honcho(api_key="your-honcho-api-key") +user = honcho.peer("user123") +session = honcho.session("imported") +session.add_peers([user]) + +# Import memories directly as observations +observations = [] +for memory in memories['results']: + content = memory.get("memory") or memory.get("messages", [{}])[0].get("content", "") + if content: + observations.append({"content": content, "session_id": "imported"}) + +# Batch create observations (up to 100 at a time) +if observations: + user.observations.create(observations) + +print(f"Migrated {len(observations)} memories as observations!") +``` + +```typescript TypeScript +// npm install mem0ai @honcho-ai/sdk +import MemoryClient from "mem0ai"; +import { Honcho } from "@honcho-ai/sdk"; + +// Export from Mem0 +const mem0 = new MemoryClient({ apiKey: "your-mem0-api-key" }); +const memories = await mem0.getAll({ filters: { user_id: "user123" }, page_size: 100 }); + +// Initialize Honcho +const honcho = new Honcho({ apiKey: "your-honcho-api-key" }); +const user = await honcho.peer("user123"); +const session = await honcho.session("imported"); +await session.addPeers([user]); + +// Import memories directly as observations +const observations = memories.results + .map(memory => ({ + content: memory.memory || memory.messages?.[0]?.content || "", + session_id: "imported" + })) + .filter(obs => obs.content); + +// Batch create observations (up to 100 at a time) +if (observations.length > 0) { + await user.observations.create(observations); +} + +console.log(`Migrated ${observations.length} memories as observations!`); +``` + + +That's it! The user's Mem0 memories are now searchable in Honcho as observations. For richer representations with deductive reasoning and session summaries, consider importing your raw messages as described in the [Step-by-Step Migration](#step-by-step-migration) section. + +For more details on replacing Mem0 API calls with Honcho equivalents go to [API Comparison](#api-comparison). + +## Step-by-Step Migration + +Prefer a more detailed walkthrough? Follow these steps: + +### 1. Export User Messages + +Importing raw user messages gives Honcho the full conversational context to build the most accurate representations. We recommend using a data structure that preserves the session and peer structure. + + +If you need any help with this transfer or have any questions, please reach out at hello@plasticlabs.ai or [book a call!](https://cal.com/team/plasticlabs/migration-to-honcho) + + +Alternatively, if you want to import the Mem0 memories, follow the example above and find more info in Mem0's [export API documentation](https://docs.mem0.ai/cookbooks/essentials/exporting-memories). + +### 2. Install the Honcho SDK + + +```bash Python (uv) +uv add honcho-ai +``` + +```bash Python (pip) +pip install honcho-ai +``` + +```bash TypeScript (npm) +npm install @honcho-ai/sdk +``` + +```bash TypeScript (yarn) +yarn add @honcho-ai/sdk +``` + +```bash TypeScript (pnpm) +pnpm add @honcho-ai/sdk +``` + + +### 3. Initialize the Honcho Client + + +Get your API key at [app.honcho.dev/api-keys](https://app.honcho.dev/api-keys). New accounts start with $100 credits. + + + +```python Python +from honcho import Honcho + +honcho = Honcho( api_key="your-api-key" ) +``` + +```typescript TypeScript +import { Honcho } from '@honcho-ai/sdk'; + +const honcho = new Honcho({apiKey: process.env.HONCHO_API_KEY!}); +``` + + +### 4. Import Your Data +This is a possible implementation using raw user messages. Adapt the data structure to match your exported format. + + +```python Python +# Example data structure (preserving message history with timestamps): +exported_data = { + "session-1": { + "user123": [ + {"content": "I prefer dark mode", "timestamp": "2024-01-15T10:30:00Z"}, + {"content": "My name is Alex", "timestamp": "2024-01-15T10:31:00Z"}, + ], + "user456": [ + {"content": "I work in finance", "timestamp": "2024-01-15T11:00:00Z"}, + {"content": "I like concise responses", "timestamp": "2024-01-15T11:02:00Z"}, + ], + }, + "session-2": { + "user123": [ + {"content": "Meeting notes from last week...", "timestamp": "2024-01-16T09:00:00Z"}, + ], + } +} + +# Import into Honcho +for session_name, users in exported_data.items(): + session = honcho.session(session_name) + + for user_id, messages in users.items(): + peer = honcho.peer(user_id) + session.add_peers([peer]) + + # Sort by timestamp to preserve message order + sorted_messages = sorted(messages, key=lambda m: m["timestamp"]) + session.add_messages([peer.message(m["content"]) for m in sorted_messages]) +``` + +```typescript TypeScript +// Example data structure (preserving message history with timestamps): +interface Message { + content: string; + timestamp: string; +} +const exportedData: Record> = { + "session-1": { + "user123": [ + { content: "I prefer dark mode", timestamp: "2024-01-15T10:30:00Z" }, + { content: "My name is Alex", timestamp: "2024-01-15T10:31:00Z" }, + ], + "user456": [ + { content: "I work in finance", timestamp: "2024-01-15T11:00:00Z" }, + { content: "I like concise responses", timestamp: "2024-01-15T11:02:00Z" }, + ], + }, + "session-2": { + "user123": [ + { content: "Meeting notes from last week...", timestamp: "2024-01-16T09:00:00Z" }, + ], + } +}; + +// Import into Honcho +for (const [sessionName, users] of Object.entries(exportedData)) { + const session = await honcho.session(sessionName); + + for (const [userId, messages] of Object.entries(users)) { + const peer = await honcho.peer(userId); + await session.addPeers([peer]); + + // Sort by timestamp to preserve message order + const sortedMessages = messages.sort((a, b) => + new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime() + ); + await session.addMessages(sortedMessages.map((m) => peer.message(m.content))); + } +} +``` + + +### 5. Update Your Application Code + +Reference the [API Comparison](#api-comparison) to replace your Mem0 API calls with the Honcho equivalents. + +## API Comparison + +### Core Operations + +| Operation | Mem0 | Honcho | Notes | +|-----------|------|--------|-------| +| **Initialize** | `MemoryClient(api_key=...)` | `Honcho(api_key=...)` | | +| **Identity** | `user_id` string param | `peer = honcho.peer("id")` | Peers can be users or AI agents | +| **Add messages** | `client.add(messages, user_id=...)` | `session.add_messages([peer.message(...)])` | Session-scoped, triggers reasoning | +| **Add observations** | | `peer.observations.create([...])` | Direct observation or "memory" import, no processing | +| **Search** | `client.search(query, filters={"user_id": ...})` | `peer.search(query)` or `peer.observations.query(...)` | Scoped to peer or session | +| **List all** | `client.get_all(filters={"user_id": ...})` | `session.get_messages()` or `peer.observations.list()` | Messages or observations | +| **Update** | `client.update(memory_id, data=...)` | `honcho.update_message(message, metadata=...)` | Metadata updates only | +| **Delete** | `client.delete(memory_id)` | `peer.observations.delete(id)` or `session.delete()` | Observation or session-level | + +### Honcho-Only Capabilities + +Mem0 requires manual assembly of context from `search()` results. Honcho's `session.get_context()` returns a ready-to-use `SessionContext` object with built-in token limits, auto-included summaries, and format helpers (`.to_openai()`, `.to_anthropic()`). + + + Learn more about token-optimized context retrieval + + + +Mem0's `search()` returns basic vector, semantic, or raw memory matches. Honcho's `peer.chat()` enables your agent to *reason* about what it knows—returning synthesized natural language insights with streaming support and scoped queries. + + + Learn more about inference-powered queries + + +Additional features with **no Mem0 equivalent**: + +| Honcho Method | Description | Use Case | +|---------------|-------------|----------| +| `peer.card()` | Stable biographical facts (name, preferences, background) | User profiles, personalization | +| `session.working_rep(peer)` | Cached psychological analysis (mental state, intentions) | Real-time adaptation | +| `session.get_summaries()` | Auto-generated short/long session summaries | Conversation continuity | +| `SessionPeerConfig` | Configure observation settings (who learns about whom) | Privacy controls, role-based learning | + +## Next Steps + + + + Understand peers and sessions + + + Inference responses + + + Integration examples + + + +Questions? Join our [Discord](https://discord.gg/honcho) or open an issue on [GitHub](https://github.com/plastic-labs/honcho/issues). diff --git a/docs/v2.6.0-alpha/openapi.json b/docs/v2.6.0-alpha/openapi.json new file mode 100644 index 00000000..bca1b8e9 --- /dev/null +++ b/docs/v2.6.0-alpha/openapi.json @@ -0,0 +1,4441 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Honcho API", + "summary": "The Identity Layer for the Agentic World", + "description": "Honcho is a platform for giving agents user-centric memory and social cognition", + "contact": { + "name": "Plastic Labs", + "url": "https://honcho.dev/", + "email": "hello@plasticlabs.ai" + }, + "version": "2.5.0" + }, + "servers": [ + { + "url": "http://localhost:8000", + "description": "Local Development Server" + }, + { "url": "https://demo.honcho.dev", "description": "Demo Server" }, + { + "url": "https://api.honcho.dev", + "description": "Production SaaS Platform" + } + ], + "paths": { + "/v2/workspaces": { + "post": { + "tags": ["workspaces"], + "summary": "Get Or Create Workspace", + "description": "Get a Workspace by ID.\n\nIf workspace_id is provided as a query parameter, it uses that (must match JWT workspace_id).\nOtherwise, it uses the workspace_id from the JWT.", + "operationId": "get_or_create_workspace_v2_workspaces_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkspaceCreate", + "description": "Workspace creation parameters" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Workspace" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + }, + "security": [{ "HTTPBearer": [] }] + } + }, + "/v2/workspaces/list": { + "post": { + "tags": ["workspaces"], + "summary": "Get All Workspaces", + "description": "Get all Workspaces", + "operationId": "get_all_workspaces_v2_workspaces_list_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "description": "Page number", + "default": 1, + "title": "Page" + }, + "description": "Page number" + }, + { + "name": "size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 100, + "minimum": 1, + "description": "Page size", + "default": 50, + "title": "Size" + }, + "description": "Page size" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { "$ref": "#/components/schemas/WorkspaceGet" }, + { "type": "null" } + ], + "description": "Filtering and pagination options for the workspaces list", + "title": "Options" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Page_Workspace_" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}": { + "put": { + "tags": ["workspaces"], + "summary": "Update Workspace", + "description": "Update a Workspace", + "operationId": "update_workspace_v2_workspaces__workspace_id__put", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace to update", + "title": "Workspace Id" + }, + "description": "ID of the workspace to update" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WorkspaceUpdate", + "description": "Updated workspace parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Workspace" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "delete": { + "tags": ["workspaces"], + "summary": "Delete Workspace", + "description": "Delete a Workspace", + "operationId": "delete_workspace_v2_workspaces__workspace_id__delete", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace to delete", + "title": "Workspace Id" + }, + "description": "ID of the workspace to delete" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Workspace" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/search": { + "post": { + "tags": ["workspaces"], + "summary": "Search Workspace", + "description": "Search a Workspace", + "operationId": "search_workspace_v2_workspaces__workspace_id__search_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace to search", + "title": "Workspace Id" + }, + "description": "ID of the workspace to search" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageSearchOptions", + "description": "Message search parameters " + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "$ref": "#/components/schemas/Message" }, + "title": "Response Search Workspace V2 Workspaces Workspace Id Search Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/deriver/status": { + "get": { + "tags": ["workspaces"], + "summary": "Get Deriver Status", + "description": "Get the deriver processing status, optionally scoped to an observer, sender, and/or session", + "operationId": "get_deriver_status_v2_workspaces__workspace_id__deriver_status_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "observer_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "Optional observer ID to filter by", + "title": "Observer Id" + }, + "description": "Optional observer ID to filter by" + }, + { + "name": "sender_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "Optional sender ID to filter by", + "title": "Sender Id" + }, + "description": "Optional sender ID to filter by" + }, + { + "name": "session_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "Optional session ID to filter by", + "title": "Session Id" + }, + "description": "Optional session ID to filter by" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/DeriverStatus" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/trigger_dream": { + "post": { + "tags": ["workspaces"], + "summary": "Trigger Dream", + "description": "Manually trigger a dream task immediately for a specific collection.\n\nThis endpoint bypasses all automatic dream conditions (document threshold,\nminimum hours between dreams) and executes the dream task immediately without delay.", + "operationId": "trigger_dream_v2_workspaces__workspace_id__trigger_dream_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TriggerDreamRequest", + "description": "Dream trigger parameters" + } + } + } + }, + "responses": { + "204": { "description": "Successful Response" }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers/list": { + "post": { + "tags": ["peers"], + "summary": "Get Peers", + "description": "Get All Peers for a Workspace", + "operationId": "get_peers_v2_workspaces__workspace_id__peers_list_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "description": "Page number", + "default": 1, + "title": "Page" + }, + "description": "Page number" + }, + { + "name": "size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 100, + "minimum": 1, + "description": "Page size", + "default": 50, + "title": "Size" + }, + "description": "Page size" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { "$ref": "#/components/schemas/PeerGet" }, + { "type": "null" } + ], + "description": "Filtering options for the peers list", + "title": "Options" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Page_Peer_" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers": { + "post": { + "tags": ["peers"], + "summary": "Get Or Create Peer", + "description": "Get a Peer by ID\n\nIf peer_id is provided as a query parameter, it uses that (must match JWT workspace_id).\nOtherwise, it uses the peer_id from the JWT.", + "operationId": "get_or_create_peer_v2_workspaces__workspace_id__peers_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PeerCreate", + "description": "Peer creation parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Peer" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers/{peer_id}": { + "put": { + "tags": ["peers"], + "summary": "Update Peer", + "description": "Update a Peer's name and/or metadata", + "operationId": "update_peer_v2_workspaces__workspace_id__peers__peer_id__put", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the peer to update", + "title": "Peer Id" + }, + "description": "ID of the peer to update" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PeerUpdate", + "description": "Updated peer parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Peer" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers/{peer_id}/sessions": { + "post": { + "tags": ["peers"], + "summary": "Get Sessions For Peer", + "description": "Get All Sessions for a Peer", + "operationId": "get_sessions_for_peer_v2_workspaces__workspace_id__peers__peer_id__sessions_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the peer", + "title": "Peer Id" + }, + "description": "ID of the peer" + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "description": "Page number", + "default": 1, + "title": "Page" + }, + "description": "Page number" + }, + { + "name": "size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 100, + "minimum": 1, + "description": "Page size", + "default": 50, + "title": "Size" + }, + "description": "Page size" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { "$ref": "#/components/schemas/SessionGet" }, + { "type": "null" } + ], + "description": "Filtering options for the sessions list", + "title": "Options" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Page_Session_" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers/{peer_id}/chat": { + "post": { + "tags": ["peers"], + "summary": "Chat", + "operationId": "chat_v2_workspaces__workspace_id__peers__peer_id__chat_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the peer", + "title": "Peer Id" + }, + "description": "ID of the peer" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DialecticOptions", + "description": "Dialectic Endpoint Parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Response to a question informed by Honcho's User Representation", + "content": { + "application/json": { + "schema": { + "properties": { + "content": { "title": "Content", "type": "string" } + }, + "required": ["content"], + "title": "DialecticResponse", + "type": "object" + } + }, + "text/event-stream": {} + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers/{peer_id}/representation": { + "post": { + "tags": ["peers"], + "summary": "Get Working Representation", + "description": "Get a peer's working representation for a session.\n\nIf a session_id is provided in the body, we get the working representation of the peer in that session.\nIf a target is provided, we get the representation of the target from the perspective of the peer.\nIf no target is provided, we get the omniscient Honcho representation of the peer.", + "operationId": "get_working_representation_v2_workspaces__workspace_id__peers__peer_id__representation_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the peer", + "title": "Peer Id" + }, + "description": "ID of the peer" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PeerRepresentationGet", + "description": "Options for getting the peer representation" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true, + "title": "Response Get Working Representation V2 Workspaces Workspace Id Peers Peer Id Representation Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers/{peer_id}/card": { + "get": { + "tags": ["peers"], + "summary": "Get Peer Card", + "description": "Get a peer card for a specific peer relationship.\n\nReturns the peer card that the observer peer has for the target peer if it exists.\nIf no target is specified, returns the observer's own peer card.", + "operationId": "get_peer_card_v2_workspaces__workspace_id__peers__peer_id__card_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the observer peer", + "title": "Peer Id" + }, + "description": "ID of the observer peer" + }, + { + "name": "target", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "The peer whose card to retrieve. If not provided, returns the observer's own card", + "title": "Target" + }, + "description": "The peer whose card to retrieve. If not provided, returns the observer's own card" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/PeerCardResponse" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "put": { + "tags": ["peers"], + "summary": "Set Peer Card", + "description": "Set a peer card for a specific peer relationship.\n\nSets the peer card that the observer peer has for the target peer.\nIf no target is specified, sets the observer's own peer card.", + "operationId": "set_peer_card_v2_workspaces__workspace_id__peers__peer_id__card_put", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the observer peer", + "title": "Peer Id" + }, + "description": "ID of the observer peer" + }, + { + "name": "target", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "The peer whose card to set. If not provided, sets the observer's own card", + "title": "Target" + }, + "description": "The peer whose card to set. If not provided, sets the observer's own card" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PeerCardSet", + "description": "Peer card data to set" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/PeerCardResponse" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers/{peer_id}/context": { + "get": { + "tags": ["peers"], + "summary": "Get Peer Context", + "description": "Get context for a peer, including their representation and peer card.\n\nThis endpoint returns the working representation and peer card for a peer.\nIf a target is specified, returns the context for the target from the\nobserver peer's perspective. If no target is specified, returns the\npeer's own context (self-observation).\n\nThis is useful for getting all the context needed about a peer without\nmaking multiple API calls.", + "operationId": "get_peer_context_v2_workspaces__workspace_id__peers__peer_id__context_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the peer (observer)", + "title": "Peer Id" + }, + "description": "ID of the peer (observer)" + }, + { + "name": "target", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "The target peer to get context for. If not provided, returns the peer's own context (self-observation)", + "title": "Target" + }, + "description": "The target peer to get context for. If not provided, returns the peer's own context (self-observation)" + }, + { + "name": "search_query", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "Optional query to curate the representation around semantic search results", + "title": "Search Query" + }, + "description": "Optional query to curate the representation around semantic search results" + }, + { + "name": "search_top_k", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { "type": "integer", "maximum": 100, "minimum": 1 }, + { "type": "null" } + ], + "description": "Only used if `search_query` is provided. Number of semantic-search-retrieved observations to include", + "title": "Search Top K" + }, + "description": "Only used if `search_query` is provided. Number of semantic-search-retrieved observations to include" + }, + { + "name": "search_max_distance", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { "type": "number", "maximum": 1.0, "minimum": 0.0 }, + { "type": "null" } + ], + "description": "Only used if `search_query` is provided. Maximum distance for semantically relevant observations", + "title": "Search Max Distance" + }, + "description": "Only used if `search_query` is provided. Maximum distance for semantically relevant observations" + }, + { + "name": "include_most_derived", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "description": "Whether to include the most derived observations in the representation", + "default": true, + "title": "Include Most Derived" + }, + "description": "Whether to include the most derived observations in the representation" + }, + { + "name": "max_observations", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { "type": "integer", "maximum": 100, "minimum": 1 }, + { "type": "null" } + ], + "description": "Maximum number of observations to include in the representation", + "title": "Max Observations" + }, + "description": "Maximum number of observations to include in the representation" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/PeerContext" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/peers/{peer_id}/search": { + "post": { + "tags": ["peers"], + "summary": "Search Peer", + "description": "Search a Peer", + "operationId": "search_peer_v2_workspaces__workspace_id__peers__peer_id__search_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the peer", + "title": "Peer Id" + }, + "description": "ID of the peer" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageSearchOptions", + "description": "Message search parameters " + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "$ref": "#/components/schemas/Message" }, + "title": "Response Search Peer V2 Workspaces Workspace Id Peers Peer Id Search Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions": { + "post": { + "tags": ["sessions"], + "summary": "Get Or Create Session", + "description": "Get a specific session in a workspace.\n\nIf session_id is provided as a query parameter, it verifies the session is in the workspace.\nOtherwise, it uses the session_id from the JWT for verification.", + "operationId": "get_or_create_session_v2_workspaces__workspace_id__sessions_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionCreate", + "description": "Session creation parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Session" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/list": { + "post": { + "tags": ["sessions"], + "summary": "Get Sessions", + "description": "Get All Sessions in a Workspace", + "operationId": "get_sessions_v2_workspaces__workspace_id__sessions_list_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "description": "Page number", + "default": 1, + "title": "Page" + }, + "description": "Page number" + }, + { + "name": "size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 100, + "minimum": 1, + "description": "Page size", + "default": 50, + "title": "Size" + }, + "description": "Page size" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { "$ref": "#/components/schemas/SessionGet" }, + { "type": "null" } + ], + "description": "Filtering and pagination options for the sessions list", + "title": "Options" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Page_Session_" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}": { + "put": { + "tags": ["sessions"], + "summary": "Update Session", + "description": "Update the metadata of a Session", + "operationId": "update_session_v2_workspaces__workspace_id__sessions__session_id__put", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session to update", + "title": "Session Id" + }, + "description": "ID of the session to update" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionUpdate", + "description": "Updated session parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Session" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "delete": { + "tags": ["sessions"], + "summary": "Delete Session", + "description": "Delete a session and all associated data.\n\nThe session is marked as inactive immediately and returns 202 Accepted. The actual\ndeletion of all related data (messages, embeddings, documents, etc.) happens\nasynchronously via the queue with retry support.\n\nThis action cannot be undone.", + "operationId": "delete_session_v2_workspaces__workspace_id__sessions__session_id__delete", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session to delete", + "title": "Session Id" + }, + "description": "ID of the session to delete" + } + ], + "responses": { + "202": { + "description": "Successful Response", + "content": { "application/json": { "schema": {} } } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/clone": { + "get": { + "tags": ["sessions"], + "summary": "Clone Session", + "description": "Clone a session, optionally up to a specific message", + "operationId": "clone_session_v2_workspaces__workspace_id__sessions__session_id__clone_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session to clone", + "title": "Session Id" + }, + "description": "ID of the session to clone" + }, + { + "name": "message_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "Message ID to cut off the clone at", + "title": "Message Id" + }, + "description": "Message ID to cut off the clone at" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Session" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/peers": { + "post": { + "tags": ["sessions"], + "summary": "Add Peers To Session", + "description": "Add peers to a session", + "operationId": "add_peers_to_session_v2_workspaces__workspace_id__sessions__session_id__peers_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/SessionPeerConfig" + }, + "description": "List of peer IDs to add to the session", + "title": "Peers" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Session" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "put": { + "tags": ["sessions"], + "summary": "Set Session Peers", + "description": "Set the peers in a session", + "operationId": "set_session_peers_v2_workspaces__workspace_id__sessions__session_id__peers_put", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/SessionPeerConfig" + }, + "description": "List of peer IDs to set for the session", + "title": "Peers" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Session" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "delete": { + "tags": ["sessions"], + "summary": "Remove Peers From Session", + "description": "Remove peers from a session", + "operationId": "remove_peers_from_session_v2_workspaces__workspace_id__sessions__session_id__peers_delete", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "type": "string" }, + "description": "List of peer IDs to remove from the session", + "title": "Peers" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Session" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "get": { + "tags": ["sessions"], + "summary": "Get Session Peers", + "description": "Get peers from a session", + "operationId": "get_session_peers_v2_workspaces__workspace_id__sessions__session_id__peers_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "description": "Page number", + "default": 1, + "title": "Page" + }, + "description": "Page number" + }, + { + "name": "size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 100, + "minimum": 1, + "description": "Page size", + "default": 50, + "title": "Size" + }, + "description": "Page size" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Page_Peer_" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/peers/{peer_id}/config": { + "get": { + "tags": ["sessions"], + "summary": "Get Peer Config", + "description": "Get the configuration for a peer in a session", + "operationId": "get_peer_config_v2_workspaces__workspace_id__sessions__session_id__peers__peer_id__config_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the peer", + "title": "Peer Id" + }, + "description": "ID of the peer" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/SessionPeerConfig" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "post": { + "tags": ["sessions"], + "summary": "Set Peer Config", + "description": "Set the configuration for a peer in a session", + "operationId": "set_peer_config_v2_workspaces__workspace_id__sessions__session_id__peers__peer_id__config_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + }, + { + "name": "peer_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the peer", + "title": "Peer Id" + }, + "description": "ID of the peer" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SessionPeerConfig", + "description": "Peer configuration" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { "application/json": { "schema": {} } } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/context": { + "get": { + "tags": ["sessions"], + "summary": "Get Session Context", + "description": "Produce a context object from the session. The caller provides an optional token limit which the entire context must fit into.\nIf not provided, the context will be exhaustive (within configured max tokens). To do this, we allocate 40% of the token limit\nto the summary, and 60% to recent messages -- as many as can fit. Note that the summary will usually take up less space than\nthis. If the caller does not want a summary, we allocate all the tokens to recent messages.", + "operationId": "get_session_context_v2_workspaces__workspace_id__sessions__session_id__context_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + }, + { + "name": "tokens", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { "type": "integer", "maximum": 100000 }, + { "type": "null" } + ], + "description": "Number of tokens to use for the context. Includes summary if set to true. Includes representation and peer card if they are included in the response. If not provided, the context will be exhaustive (within 100000 tokens)", + "title": "Tokens" + }, + "description": "Number of tokens to use for the context. Includes summary if set to true. Includes representation and peer card if they are included in the response. If not provided, the context will be exhaustive (within 100000 tokens)" + }, + { + "name": "last_message", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "The most recent message, used to fetch semantically relevant observations", + "title": "Last Message" + }, + "description": "The most recent message, used to fetch semantically relevant observations" + }, + { + "name": "summary", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "description": "Whether or not to include a summary *if* one is available for the session", + "default": true, + "title": "Summary" + }, + "description": "Whether or not to include a summary *if* one is available for the session" + }, + { + "name": "peer_target", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "The target of the perspective. If given without `peer_perspective`, will get the Honcho-level representation and peer card for this peer. If given with `peer_perspective`, will get the representation and card for this peer *from the perspective of that peer*.", + "title": "Peer Target" + }, + "description": "The target of the perspective. If given without `peer_perspective`, will get the Honcho-level representation and peer card for this peer. If given with `peer_perspective`, will get the representation and card for this peer *from the perspective of that peer*." + }, + { + "name": "peer_perspective", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "A peer to get context for. If given, response will attempt to include representation and card from the perspective of that peer. Must be provided with `peer_target`.", + "title": "Peer Perspective" + }, + "description": "A peer to get context for. If given, response will attempt to include representation and card from the perspective of that peer. Must be provided with `peer_target`." + }, + { + "name": "limit_to_session", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "description": "Only used if `last_message` is provided. Whether to limit the representation to the session (as opposed to everything known about the target peer)", + "default": false, + "title": "Limit To Session" + }, + "description": "Only used if `last_message` is provided. Whether to limit the representation to the session (as opposed to everything known about the target peer)" + }, + { + "name": "search_top_k", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { "type": "integer", "maximum": 100, "minimum": 1 }, + { "type": "null" } + ], + "description": "Only used if `last_message` is provided. The number of semantic-search-retrieved observations to include in the representation", + "title": "Search Top K" + }, + "description": "Only used if `last_message` is provided. The number of semantic-search-retrieved observations to include in the representation" + }, + { + "name": "search_max_distance", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { "type": "number", "maximum": 1.0, "minimum": 0.0 }, + { "type": "null" } + ], + "description": "Only used if `last_message` is provided. The maximum distance to search for semantically relevant observations", + "title": "Search Max Distance" + }, + "description": "Only used if `last_message` is provided. The maximum distance to search for semantically relevant observations" + }, + { + "name": "include_most_derived", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "description": "Only used if `last_message` is provided. Whether to include the most derived observations in the representation", + "default": false, + "title": "Include Most Derived" + }, + "description": "Only used if `last_message` is provided. Whether to include the most derived observations in the representation" + }, + { + "name": "max_observations", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { "type": "integer", "maximum": 100, "minimum": 1 }, + { "type": "null" } + ], + "description": "Only used if `last_message` is provided. The maximum number of observations to include in the representation", + "title": "Max Observations" + }, + "description": "Only used if `last_message` is provided. The maximum number of observations to include in the representation" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/SessionContext" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/summaries": { + "get": { + "tags": ["sessions"], + "summary": "Get Session Summaries", + "description": "Get available summaries for a session.\n\nReturns both short and long summaries if available, including metadata like\nthe message ID they cover up to, creation timestamp, and token count.", + "operationId": "get_session_summaries_v2_workspaces__workspace_id__sessions__session_id__summaries_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/SessionSummaries" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/search": { + "post": { + "tags": ["sessions"], + "summary": "Search Session", + "description": "Search a Session", + "operationId": "search_session_v2_workspaces__workspace_id__sessions__session_id__search_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageSearchOptions", + "description": "Message search parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "$ref": "#/components/schemas/Message" }, + "title": "Response Search Session V2 Workspaces Workspace Id Sessions Session Id Search Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/messages/": { + "post": { + "tags": ["messages"], + "summary": "Create Messages For Session", + "description": "Add new message(s) to a session.", + "operationId": "create_messages_for_session_v2_workspaces__workspace_id__sessions__session_id__messages__post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { "type": "string", "title": "Workspace Id" } + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { "type": "string", "title": "Session Id" } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/MessageBatchCreate" } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "$ref": "#/components/schemas/Message" }, + "title": "Response Create Messages For Session V2 Workspaces Workspace Id Sessions Session Id Messages Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/messages/upload": { + "post": { + "tags": ["messages"], + "summary": "Create Messages With File", + "description": "Create messages from uploaded files. Files are converted to text and split into multiple messages.", + "operationId": "create_messages_with_file_v2_workspaces__workspace_id__sessions__session_id__messages_upload_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { "type": "string", "title": "Workspace Id" } + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { "type": "string", "title": "Session Id" } + } + ], + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/Body_create_messages_with_file_v2_workspaces__workspace_id__sessions__session_id__messages_upload_post" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "$ref": "#/components/schemas/Message" }, + "title": "Response Create Messages With File V2 Workspaces Workspace Id Sessions Session Id Messages Upload Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/messages/list": { + "post": { + "tags": ["messages"], + "summary": "Get Messages", + "description": "Get all messages for a session", + "operationId": "get_messages_v2_workspaces__workspace_id__sessions__session_id__messages_list_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + }, + { + "name": "reverse", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "description": "Whether to reverse the order of results", + "default": false, + "title": "Reverse" + }, + "description": "Whether to reverse the order of results" + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "description": "Page number", + "default": 1, + "title": "Page" + }, + "description": "Page number" + }, + { + "name": "size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 100, + "minimum": 1, + "description": "Page size", + "default": 50, + "title": "Size" + }, + "description": "Page size" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { "$ref": "#/components/schemas/MessageGet" }, + { "type": "null" } + ], + "description": "Filtering options for the messages list", + "title": "Options" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Page_Message_" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/sessions/{session_id}/messages/{message_id}": { + "get": { + "tags": ["messages"], + "summary": "Get Message", + "description": "Get a Message by ID", + "operationId": "get_message_v2_workspaces__workspace_id__sessions__session_id__messages__message_id__get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + }, + { + "name": "message_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the message to retrieve", + "title": "Message Id" + }, + "description": "ID of the message to retrieve" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Message" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "put": { + "tags": ["messages"], + "summary": "Update Message", + "description": "Update the metadata of a Message", + "operationId": "update_message_v2_workspaces__workspace_id__sessions__session_id__messages__message_id__put", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "session_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the session", + "title": "Session Id" + }, + "description": "ID of the session" + }, + { + "name": "message_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the message to update", + "title": "Message Id" + }, + "description": "ID of the message to update" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessageUpdate", + "description": "Updated message parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Message" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/observations": { + "post": { + "tags": ["observations"], + "summary": "Create Observations", + "description": "Create one or more observations.\n\nCreates observations (theory-of-mind facts) for the specified observer/observed peer pairs.\nEach observation must reference existing peers and a session within the workspace.\nEmbeddings are automatically generated for semantic search.\n\nMaximum of 100 observations per request.", + "operationId": "create_observations_v2_workspaces__workspace_id__observations_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ObservationBatchCreate", + "description": "Batch of observations to create" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "$ref": "#/components/schemas/Observation" }, + "title": "Response Create Observations V2 Workspaces Workspace Id Observations Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/observations/list": { + "post": { + "tags": ["observations"], + "summary": "List Observations", + "description": "List all observations using custom filters. Observations are listed by recency unless `reverse` is set to `true`.\n\nObservations can be filtered by session_id, observer_id and observed_id using the filters parameter.", + "operationId": "list_observations_v2_workspaces__workspace_id__observations_list_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "reverse", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "description": "Whether to reverse the order of results", + "default": false, + "title": "Reverse" + }, + "description": "Whether to reverse the order of results" + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "description": "Page number", + "default": 1, + "title": "Page" + }, + "description": "Page number" + }, + { + "name": "size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 100, + "minimum": 1, + "description": "Page size", + "default": 50, + "title": "Size" + }, + "description": "Page size" + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { "$ref": "#/components/schemas/ObservationGet" }, + { "type": "null" } + ], + "description": "Filtering options for the observations list", + "title": "Options" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Page_Observation_" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/observations/query": { + "post": { + "tags": ["observations"], + "summary": "Query Observations", + "description": "Query observations using semantic search.\n\nPerforms vector similarity search on observations to find semantically relevant results.\nObserver and observed are required for semantic search and must be provided in filters.", + "operationId": "query_observations_v2_workspaces__workspace_id__observations_query_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ObservationQuery", + "description": "Semantic search parameters for observations" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { "$ref": "#/components/schemas/Observation" }, + "title": "Response Query Observations V2 Workspaces Workspace Id Observations Query Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/observations/{observation_id}": { + "delete": { + "tags": ["observations"], + "summary": "Delete Observation", + "description": "Delete a specific observation.\n\nThis permanently deletes the observation (document) from the theory-of-mind system.\nThis action cannot be undone.", + "operationId": "delete_observation_v2_workspaces__workspace_id__observations__observation_id__delete", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the workspace", + "title": "Workspace Id" + }, + "description": "ID of the workspace" + }, + { + "name": "observation_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "ID of the observation to delete", + "title": "Observation Id" + }, + "description": "ID of the observation to delete" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { "application/json": { "schema": {} } } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/keys": { + "post": { + "tags": ["keys"], + "summary": "Create Key", + "description": "Create a new Key", + "operationId": "create_key_v2_keys_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "ID of the workspace to scope the key to", + "title": "Workspace Id" + }, + "description": "ID of the workspace to scope the key to" + }, + { + "name": "peer_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "ID of the peer to scope the key to", + "title": "Peer Id" + }, + "description": "ID of the peer to scope the key to" + }, + { + "name": "session_id", + "in": "query", + "required": false, + "schema": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "description": "ID of the session to scope the key to", + "title": "Session Id" + }, + "description": "ID of the session to scope the key to" + }, + { + "name": "expires_at", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { "type": "string", "format": "date-time" }, + { "type": "null" } + ], + "title": "Expires At" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { "application/json": { "schema": {} } } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/webhooks": { + "post": { + "tags": ["webhooks"], + "summary": "Get Or Create Webhook Endpoint", + "description": "Get or create a webhook endpoint URL.", + "operationId": "get_or_create_webhook_endpoint_v2_workspaces__workspace_id__webhooks_post", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Workspace ID", + "title": "Workspace Id" + }, + "description": "Workspace ID" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/WebhookEndpointCreate", + "description": "Webhook endpoint parameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/WebhookEndpoint" } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + }, + "get": { + "tags": ["webhooks"], + "summary": "List Webhook Endpoints", + "description": "List all webhook endpoints, optionally filtered by workspace.", + "operationId": "list_webhook_endpoints_v2_workspaces__workspace_id__webhooks_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Workspace ID", + "title": "Workspace Id" + }, + "description": "Workspace ID" + }, + { + "name": "page", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "description": "Page number", + "default": 1, + "title": "Page" + }, + "description": "Page number" + }, + { + "name": "size", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "maximum": 100, + "minimum": 1, + "description": "Page size", + "default": 50, + "title": "Size" + }, + "description": "Page size" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Page_WebhookEndpoint_" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/webhooks/{endpoint_id}": { + "delete": { + "tags": ["webhooks"], + "summary": "Delete Webhook Endpoint", + "description": "Delete a specific webhook endpoint.", + "operationId": "delete_webhook_endpoint_v2_workspaces__workspace_id__webhooks__endpoint_id__delete", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Workspace ID", + "title": "Workspace Id" + }, + "description": "Workspace ID" + }, + { + "name": "endpoint_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Webhook endpoint ID", + "title": "Endpoint Id" + }, + "description": "Webhook endpoint ID" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { "application/json": { "schema": {} } } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/v2/workspaces/{workspace_id}/webhooks/test": { + "get": { + "tags": ["webhooks"], + "summary": "Test Emit", + "description": "Test publishing a webhook event.", + "operationId": "test_emit_v2_workspaces__workspace_id__webhooks_test_get", + "security": [{ "HTTPBearer": [] }], + "parameters": [ + { + "name": "workspace_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Workspace ID", + "title": "Workspace Id" + }, + "description": "Workspace ID" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { "application/json": { "schema": {} } } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/HTTPValidationError" } + } + } + } + } + } + }, + "/metrics": { + "get": { + "summary": "Metrics", + "description": "Prometheus metrics endpoint", + "operationId": "metrics_metrics_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { "application/json": { "schema": {} } } + } + } + } + } + }, + "components": { + "schemas": { + "Body_create_messages_with_file_v2_workspaces__workspace_id__sessions__session_id__messages_upload_post": { + "properties": { + "file": { "type": "string", "format": "binary", "title": "File" }, + "peer_id": { "type": "string", "title": "Peer Id" }, + "metadata": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Metadata" + }, + "configuration": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Configuration" + }, + "created_at": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Created At" + } + }, + "type": "object", + "required": ["file", "peer_id"], + "title": "Body_create_messages_with_file_v2_workspaces__workspace_id__sessions__session_id__messages_upload_post" + }, + "DeductiveObservation": { + "properties": { + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + }, + "message_ids": { + "items": { "type": "integer" }, + "type": "array", + "title": "Message Ids" + }, + "session_name": { "type": "string", "title": "Session Name" }, + "premises": { + "items": { "type": "string" }, + "type": "array", + "title": "Premises", + "description": "Supporting premises or evidence for this conclusion" + }, + "conclusion": { + "type": "string", + "title": "Conclusion", + "description": "The deductive conclusion" + } + }, + "type": "object", + "required": ["created_at", "message_ids", "session_name", "conclusion"], + "title": "DeductiveObservation", + "description": "Deductive observation with multiple premises and one conclusion, plus metadata." + }, + "DeriverConfiguration": { + "properties": { + "enabled": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "title": "Enabled", + "description": "Whether to enable deriver functionality." + }, + "custom_instructions": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Custom Instructions", + "description": "TODO: currently unused. Custom instructions to use for the deriver on this workspace/session/message." + } + }, + "type": "object", + "title": "DeriverConfiguration" + }, + "DeriverStatus": { + "properties": { + "total_work_units": { + "type": "integer", + "title": "Total Work Units", + "description": "Total work units" + }, + "completed_work_units": { + "type": "integer", + "title": "Completed Work Units", + "description": "Completed work units" + }, + "in_progress_work_units": { + "type": "integer", + "title": "In Progress Work Units", + "description": "Work units currently being processed" + }, + "pending_work_units": { + "type": "integer", + "title": "Pending Work Units", + "description": "Work units waiting to be processed" + }, + "sessions": { + "anyOf": [ + { + "additionalProperties": { + "$ref": "#/components/schemas/SessionDeriverStatus" + }, + "type": "object" + }, + { "type": "null" } + ], + "title": "Sessions", + "description": "Per-session status when not filtered by session" + } + }, + "type": "object", + "required": [ + "total_work_units", + "completed_work_units", + "in_progress_work_units", + "pending_work_units" + ], + "title": "DeriverStatus" + }, + "DialecticOptions": { + "properties": { + "session_id": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Session Id", + "description": "ID of the session to scope the representation to" + }, + "target": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Target", + "description": "Optional peer to get the representation for, from the perspective of this peer" + }, + "query": { + "type": "string", + "maxLength": 10000, + "minLength": 1, + "title": "Query", + "description": "Dialectic API Prompt" + }, + "stream": { "type": "boolean", "title": "Stream", "default": false } + }, + "type": "object", + "required": ["query"], + "title": "DialecticOptions" + }, + "DreamConfiguration": { + "properties": { + "enabled": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "title": "Enabled", + "description": "Whether to enable dream functionality. If deriver is disabled, dreams will also be disabled and this setting will be ignored." + } + }, + "type": "object", + "title": "DreamConfiguration" + }, + "DreamType": { + "type": "string", + "enum": ["consolidate", "agent"], + "title": "DreamType", + "description": "Types of dreams that can be triggered." + }, + "ExplicitObservation": { + "properties": { + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + }, + "message_ids": { + "items": { "type": "integer" }, + "type": "array", + "title": "Message Ids" + }, + "session_name": { "type": "string", "title": "Session Name" }, + "content": { + "type": "string", + "title": "Content", + "description": "The explicit observation" + } + }, + "type": "object", + "required": ["created_at", "message_ids", "session_name", "content"], + "title": "ExplicitObservation", + "description": "Explicit observation with content and metadata." + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": { "$ref": "#/components/schemas/ValidationError" }, + "type": "array", + "title": "Detail" + } + }, + "type": "object", + "title": "HTTPValidationError" + }, + "Message": { + "properties": { + "id": { "type": "string", "title": "Id" }, + "content": { "type": "string", "title": "Content" }, + "peer_id": { "type": "string", "title": "Peer Id" }, + "session_id": { "type": "string", "title": "Session Id" }, + "metadata": { + "additionalProperties": true, + "type": "object", + "title": "Metadata" + }, + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + }, + "workspace_id": { "type": "string", "title": "Workspace Id" }, + "token_count": { "type": "integer", "title": "Token Count" } + }, + "type": "object", + "required": [ + "id", + "content", + "peer_id", + "session_id", + "created_at", + "workspace_id", + "token_count" + ], + "title": "Message" + }, + "MessageBatchCreate": { + "properties": { + "messages": { + "items": { "$ref": "#/components/schemas/MessageCreate" }, + "type": "array", + "maxItems": 100, + "minItems": 1, + "title": "Messages" + } + }, + "type": "object", + "required": ["messages"], + "title": "MessageBatchCreate", + "description": "Schema for batch message creation with a max of 100 messages" + }, + "MessageConfiguration": { + "properties": { + "deriver": { + "anyOf": [ + { "$ref": "#/components/schemas/DeriverConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for deriver functionality." + }, + "peer_card": { + "anyOf": [ + { "$ref": "#/components/schemas/PeerCardConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for peer card functionality. If deriver is disabled, peer cards will also be disabled and these settings will be ignored." + } + }, + "type": "object", + "title": "MessageConfiguration", + "description": "The set of options that can be in a message DB-level configuration dictionary.\n\nAll fields are optional. Message-level configuration overrides all other configurations." + }, + "MessageCreate": { + "properties": { + "content": { + "type": "string", + "maxLength": 25000, + "minLength": 0, + "title": "Content" + }, + "peer_id": { "type": "string", "title": "Peer Id" }, + "metadata": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Metadata" + }, + "configuration": { + "anyOf": [ + { "$ref": "#/components/schemas/MessageConfiguration" }, + { "type": "null" } + ] + }, + "created_at": { + "anyOf": [ + { "type": "string", "format": "date-time" }, + { "type": "null" } + ], + "title": "Created At" + } + }, + "type": "object", + "required": ["content", "peer_id"], + "title": "MessageCreate" + }, + "MessageGet": { + "properties": { + "filters": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Filters" + } + }, + "type": "object", + "title": "MessageGet" + }, + "MessageSearchOptions": { + "properties": { + "query": { + "type": "string", + "title": "Query", + "description": "Search query" + }, + "filters": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Filters", + "description": "Filters to scope the search" + }, + "limit": { + "type": "integer", + "maximum": 100.0, + "minimum": 1.0, + "title": "Limit", + "description": "Number of results to return", + "default": 10 + } + }, + "type": "object", + "required": ["query"], + "title": "MessageSearchOptions" + }, + "MessageUpdate": { + "properties": { + "metadata": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Metadata" + } + }, + "type": "object", + "title": "MessageUpdate" + }, + "Observation": { + "properties": { + "id": { "type": "string", "title": "Id" }, + "content": { "type": "string", "title": "Content" }, + "observer_id": { + "type": "string", + "title": "Observer Id", + "description": "The peer who made the observation" + }, + "observed_id": { + "type": "string", + "title": "Observed Id", + "description": "The peer being observed" + }, + "session_id": { "type": "string", "title": "Session Id" }, + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + } + }, + "type": "object", + "required": [ + "id", + "content", + "observer_id", + "observed_id", + "session_id", + "created_at" + ], + "title": "Observation", + "description": "Observation response - external view of a document" + }, + "ObservationBatchCreate": { + "properties": { + "observations": { + "items": { "$ref": "#/components/schemas/ObservationCreate" }, + "type": "array", + "maxItems": 100, + "minItems": 1, + "title": "Observations" + } + }, + "type": "object", + "required": ["observations"], + "title": "ObservationBatchCreate", + "description": "Schema for batch observation creation with a max of 100 observations" + }, + "ObservationCreate": { + "properties": { + "content": { + "type": "string", + "maxLength": 65535, + "minLength": 1, + "title": "Content" + }, + "observer_id": { + "type": "string", + "title": "Observer Id", + "description": "The peer making the observation" + }, + "observed_id": { + "type": "string", + "title": "Observed Id", + "description": "The peer being observed" + }, + "session_id": { + "type": "string", + "title": "Session Id", + "description": "The session this observation relates to" + } + }, + "type": "object", + "required": ["content", "observer_id", "observed_id", "session_id"], + "title": "ObservationCreate", + "description": "Schema for creating a single observation" + }, + "ObservationGet": { + "properties": { + "filters": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Filters" + } + }, + "type": "object", + "title": "ObservationGet", + "description": "Schema for listing observations with optional filters" + }, + "ObservationQuery": { + "properties": { + "query": { + "type": "string", + "title": "Query", + "description": "Semantic search query" + }, + "top_k": { + "type": "integer", + "maximum": 100.0, + "minimum": 1.0, + "title": "Top K", + "description": "Number of results to return", + "default": 10 + }, + "distance": { + "anyOf": [ + { "type": "number", "maximum": 1.0, "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Distance", + "description": "Maximum cosine distance threshold for results" + }, + "filters": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Filters", + "description": "Additional filters to apply" + } + }, + "type": "object", + "required": ["query"], + "title": "ObservationQuery", + "description": "Query parameters for semantic search of observations" + }, + "Page_Message_": { + "properties": { + "items": { + "items": { "$ref": "#/components/schemas/Message" }, + "type": "array", + "title": "Items" + }, + "total": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Total" + }, + "page": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Page" + }, + "size": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Size" + }, + "pages": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Pages" + } + }, + "type": "object", + "required": ["items", "page", "size"], + "title": "Page[Message]" + }, + "Page_Observation_": { + "properties": { + "items": { + "items": { "$ref": "#/components/schemas/Observation" }, + "type": "array", + "title": "Items" + }, + "total": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Total" + }, + "page": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Page" + }, + "size": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Size" + }, + "pages": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Pages" + } + }, + "type": "object", + "required": ["items", "page", "size"], + "title": "Page[Observation]" + }, + "Page_Peer_": { + "properties": { + "items": { + "items": { "$ref": "#/components/schemas/Peer" }, + "type": "array", + "title": "Items" + }, + "total": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Total" + }, + "page": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Page" + }, + "size": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Size" + }, + "pages": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Pages" + } + }, + "type": "object", + "required": ["items", "page", "size"], + "title": "Page[Peer]" + }, + "Page_Session_": { + "properties": { + "items": { + "items": { "$ref": "#/components/schemas/Session" }, + "type": "array", + "title": "Items" + }, + "total": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Total" + }, + "page": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Page" + }, + "size": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Size" + }, + "pages": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Pages" + } + }, + "type": "object", + "required": ["items", "page", "size"], + "title": "Page[Session]" + }, + "Page_WebhookEndpoint_": { + "properties": { + "items": { + "items": { "$ref": "#/components/schemas/WebhookEndpoint" }, + "type": "array", + "title": "Items" + }, + "total": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Total" + }, + "page": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Page" + }, + "size": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Size" + }, + "pages": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Pages" + } + }, + "type": "object", + "required": ["items", "page", "size"], + "title": "Page[WebhookEndpoint]" + }, + "Page_Workspace_": { + "properties": { + "items": { + "items": { "$ref": "#/components/schemas/Workspace" }, + "type": "array", + "title": "Items" + }, + "total": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Total" + }, + "page": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Page" + }, + "size": { + "anyOf": [ + { "type": "integer", "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Size" + }, + "pages": { + "anyOf": [ + { "type": "integer", "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Pages" + } + }, + "type": "object", + "required": ["items", "page", "size"], + "title": "Page[Workspace]" + }, + "Peer": { + "properties": { + "id": { "type": "string", "title": "Id" }, + "workspace_id": { "type": "string", "title": "Workspace Id" }, + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + }, + "metadata": { + "additionalProperties": true, + "type": "object", + "title": "Metadata" + }, + "configuration": { + "additionalProperties": true, + "type": "object", + "title": "Configuration" + } + }, + "type": "object", + "required": ["id", "workspace_id", "created_at"], + "title": "Peer" + }, + "PeerCardConfiguration": { + "properties": { + "use": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "title": "Use", + "description": "Whether to use peer card related to this peer during deriver process." + }, + "create": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "title": "Create", + "description": "Whether to generate peer card based on content." + } + }, + "type": "object", + "title": "PeerCardConfiguration" + }, + "PeerCardResponse": { + "properties": { + "peer_card": { + "anyOf": [ + { "items": { "type": "string" }, "type": "array" }, + { "type": "null" } + ], + "title": "Peer Card", + "description": "The peer card content, or None if not found" + } + }, + "type": "object", + "title": "PeerCardResponse" + }, + "PeerCardSet": { + "properties": { + "peer_card": { + "items": { "type": "string" }, + "type": "array", + "title": "Peer Card", + "description": "The peer card content to set" + } + }, + "type": "object", + "required": ["peer_card"], + "title": "PeerCardSet" + }, + "PeerContext": { + "properties": { + "peer_id": { + "type": "string", + "title": "Peer Id", + "description": "The ID of the peer" + }, + "target_id": { + "type": "string", + "title": "Target Id", + "description": "The ID of the target peer being observed" + }, + "representation": { + "anyOf": [ + { "$ref": "#/components/schemas/Representation" }, + { "type": "null" } + ], + "description": "The working representation of the target peer from the observer's perspective" + }, + "peer_card": { + "anyOf": [ + { "items": { "type": "string" }, "type": "array" }, + { "type": "null" } + ], + "title": "Peer Card", + "description": "The peer card for the target peer from the observer's perspective" + } + }, + "type": "object", + "required": ["peer_id", "target_id"], + "title": "PeerContext", + "description": "Context for a peer, including representation and peer card." + }, + "PeerCreate": { + "properties": { + "id": { + "type": "string", + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-zA-Z0-9_-]+$", + "title": "Id" + }, + "metadata": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Metadata" + }, + "configuration": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Configuration" + } + }, + "type": "object", + "required": ["id"], + "title": "PeerCreate" + }, + "PeerGet": { + "properties": { + "filters": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Filters" + } + }, + "type": "object", + "title": "PeerGet" + }, + "PeerRepresentationGet": { + "properties": { + "session_id": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Session Id", + "description": "Get the working representation within this session" + }, + "target": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Target", + "description": "Optional peer ID to get the representation for, from the perspective of this peer" + }, + "search_query": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Search Query", + "description": "Optional input to curate the representation around semantic search results" + }, + "search_top_k": { + "anyOf": [ + { "type": "integer", "maximum": 100.0, "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Search Top K", + "description": "Only used if `search_query` is provided. Number of semantic-search-retrieved observations to include in the representation" + }, + "search_max_distance": { + "anyOf": [ + { "type": "number", "maximum": 1.0, "minimum": 0.0 }, + { "type": "null" } + ], + "title": "Search Max Distance", + "description": "Only used if `search_query` is provided. Maximum distance to search for semantically relevant observations" + }, + "include_most_derived": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "title": "Include Most Derived", + "description": "Only used if `search_query` is provided. Whether to include the most derived observations in the representation" + }, + "max_observations": { + "anyOf": [ + { "type": "integer", "maximum": 100.0, "minimum": 1.0 }, + { "type": "null" } + ], + "title": "Max Observations", + "description": "Only used if `search_query` is provided. Maximum number of observations to include in the representation", + "default": 25 + } + }, + "type": "object", + "title": "PeerRepresentationGet" + }, + "PeerUpdate": { + "properties": { + "metadata": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Metadata" + }, + "configuration": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Configuration" + } + }, + "type": "object", + "title": "PeerUpdate" + }, + "Representation": { + "properties": { + "explicit": { + "items": { "$ref": "#/components/schemas/ExplicitObservation" }, + "type": "array", + "title": "Explicit", + "description": "Facts LITERALLY stated by the user - direct quotes or clear paraphrases only, no interpretation or inference. Example: ['The user is 25 years old', 'The user has a dog']" + }, + "deductive": { + "items": { "$ref": "#/components/schemas/DeductiveObservation" }, + "type": "array", + "title": "Deductive", + "description": "Conclusions that MUST be true given explicit facts and premises - strict logical necessities. Each deduction should have premises and a single conclusion." + } + }, + "type": "object", + "title": "Representation", + "description": "A Representation is a traversable and diffable map of observations.\nAt the base, we have a list of explicit observations, derived from a peer's messages.\n\nFrom there, deductive observations can be made by establishing logical relationships between explicit observations.\n\nIn the future, we can add more levels of reasoning on top of these.\n\nAll of a peer's observations are stored as documents in a collection. These documents can be queried in various ways\nto produce this Representation object.\n\nAdditionally, a \"working representation\" is a version of this data structure representing the most recent observations\nwithin a single session.\n\nA representation can have a maximum number of observations, which is applied individually to each level of reasoning.\nIf a maximum is set, observations are added and removed in FIFO order." + }, + "Session": { + "properties": { + "id": { "type": "string", "title": "Id" }, + "is_active": { "type": "boolean", "title": "Is Active" }, + "workspace_id": { "type": "string", "title": "Workspace Id" }, + "metadata": { + "additionalProperties": true, + "type": "object", + "title": "Metadata" + }, + "configuration": { + "additionalProperties": true, + "type": "object", + "title": "Configuration" + }, + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + } + }, + "type": "object", + "required": ["id", "is_active", "workspace_id", "created_at"], + "title": "Session" + }, + "SessionConfiguration": { + "properties": { + "deriver": { + "anyOf": [ + { "$ref": "#/components/schemas/DeriverConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for deriver functionality." + }, + "peer_card": { + "anyOf": [ + { "$ref": "#/components/schemas/PeerCardConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for peer card functionality. If deriver is disabled, peer cards will also be disabled and these settings will be ignored." + }, + "summary": { + "anyOf": [ + { "$ref": "#/components/schemas/SummaryConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for summary functionality." + }, + "dream": { + "anyOf": [ + { "$ref": "#/components/schemas/DreamConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for dream functionality. If deriver is disabled, dreams will also be disabled and these settings will be ignored." + } + }, + "additionalProperties": true, + "type": "object", + "title": "SessionConfiguration", + "description": "The set of options that can be in a session DB-level configuration dictionary.\n\nAll fields are optional. Session-level configuration overrides workspace-level configuration, which overrides global configuration." + }, + "SessionContext": { + "properties": { + "id": { "type": "string", "title": "Id" }, + "messages": { + "items": { "$ref": "#/components/schemas/Message" }, + "type": "array", + "title": "Messages" + }, + "summary": { + "anyOf": [ + { "$ref": "#/components/schemas/Summary" }, + { "type": "null" } + ], + "description": "The summary if available" + }, + "peer_representation": { + "anyOf": [ + { "$ref": "#/components/schemas/Representation" }, + { "type": "null" } + ], + "description": "The peer representation, if context is requested from a specific perspective" + }, + "peer_card": { + "anyOf": [ + { "items": { "type": "string" }, "type": "array" }, + { "type": "null" } + ], + "title": "Peer Card", + "description": "The peer card, if context is requested from a specific perspective" + } + }, + "type": "object", + "required": ["id", "messages"], + "title": "SessionContext" + }, + "SessionCreate": { + "properties": { + "id": { + "type": "string", + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-zA-Z0-9_-]+$", + "title": "Id" + }, + "metadata": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Metadata" + }, + "peers": { + "anyOf": [ + { + "additionalProperties": { + "$ref": "#/components/schemas/SessionPeerConfig" + }, + "type": "object" + }, + { "type": "null" } + ], + "title": "Peers" + }, + "configuration": { + "anyOf": [ + { "$ref": "#/components/schemas/SessionConfiguration" }, + { "type": "null" } + ] + } + }, + "type": "object", + "required": ["id"], + "title": "SessionCreate" + }, + "SessionDeriverStatus": { + "properties": { + "session_id": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Session Id", + "description": "Session ID if filtered by session" + }, + "total_work_units": { + "type": "integer", + "title": "Total Work Units", + "description": "Total work units" + }, + "completed_work_units": { + "type": "integer", + "title": "Completed Work Units", + "description": "Completed work units" + }, + "in_progress_work_units": { + "type": "integer", + "title": "In Progress Work Units", + "description": "Work units currently being processed" + }, + "pending_work_units": { + "type": "integer", + "title": "Pending Work Units", + "description": "Work units waiting to be processed" + } + }, + "type": "object", + "required": [ + "total_work_units", + "completed_work_units", + "in_progress_work_units", + "pending_work_units" + ], + "title": "SessionDeriverStatus" + }, + "SessionGet": { + "properties": { + "filters": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Filters" + } + }, + "type": "object", + "title": "SessionGet" + }, + "SessionPeerConfig": { + "properties": { + "observe_me": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "title": "Observe Me", + "description": "Whether honcho should form a global theory-of-mind representation of this peer" + }, + "observe_others": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "title": "Observe Others", + "description": "Whether this peer should form a session-level theory-of-mind representation of other peers in the session" + } + }, + "type": "object", + "title": "SessionPeerConfig" + }, + "SessionSummaries": { + "properties": { + "id": { "type": "string", "title": "Id" }, + "short_summary": { + "anyOf": [ + { "$ref": "#/components/schemas/Summary" }, + { "type": "null" } + ], + "description": "The short summary if available" + }, + "long_summary": { + "anyOf": [ + { "$ref": "#/components/schemas/Summary" }, + { "type": "null" } + ], + "description": "The long summary if available" + } + }, + "type": "object", + "required": ["id"], + "title": "SessionSummaries" + }, + "SessionUpdate": { + "properties": { + "metadata": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Metadata" + }, + "configuration": { + "anyOf": [ + { "$ref": "#/components/schemas/SessionConfiguration" }, + { "type": "null" } + ] + } + }, + "type": "object", + "title": "SessionUpdate" + }, + "Summary": { + "properties": { + "content": { + "type": "string", + "title": "Content", + "description": "The summary text" + }, + "message_id": { + "type": "string", + "title": "Message Id", + "description": "The public ID of the message that this summary covers up to" + }, + "summary_type": { + "type": "string", + "title": "Summary Type", + "description": "The type of summary (short or long)" + }, + "created_at": { + "type": "string", + "title": "Created At", + "description": "The timestamp of when the summary was created (ISO format)" + }, + "token_count": { + "type": "integer", + "title": "Token Count", + "description": "The number of tokens in the summary text" + } + }, + "type": "object", + "required": [ + "content", + "message_id", + "summary_type", + "created_at", + "token_count" + ], + "title": "Summary" + }, + "SummaryConfiguration": { + "properties": { + "enabled": { + "anyOf": [{ "type": "boolean" }, { "type": "null" }], + "title": "Enabled", + "description": "Whether to enable summary functionality." + }, + "messages_per_short_summary": { + "anyOf": [ + { "type": "integer", "minimum": 10.0 }, + { "type": "null" } + ], + "title": "Messages Per Short Summary", + "description": "Number of messages per short summary. Must be positive, greater than or equal to 10, and less than messages_per_long_summary." + }, + "messages_per_long_summary": { + "anyOf": [ + { "type": "integer", "minimum": 20.0 }, + { "type": "null" } + ], + "title": "Messages Per Long Summary", + "description": "Number of messages per long summary. Must be positive, greater than or equal to 20, and greater than messages_per_short_summary." + } + }, + "type": "object", + "title": "SummaryConfiguration" + }, + "TriggerDreamRequest": { + "properties": { + "observer": { + "type": "string", + "title": "Observer", + "description": "Observer peer name" + }, + "observed": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Observed", + "description": "Observed peer name (defaults to observer if not specified)" + }, + "dream_type": { + "$ref": "#/components/schemas/DreamType", + "description": "Type of dream to trigger" + } + }, + "type": "object", + "required": ["observer", "dream_type"], + "title": "TriggerDreamRequest" + }, + "ValidationError": { + "properties": { + "loc": { + "items": { "anyOf": [{ "type": "string" }, { "type": "integer" }] }, + "type": "array", + "title": "Location" + }, + "msg": { "type": "string", "title": "Message" }, + "type": { "type": "string", "title": "Error Type" } + }, + "type": "object", + "required": ["loc", "msg", "type"], + "title": "ValidationError" + }, + "WebhookEndpoint": { + "properties": { + "id": { "type": "string", "title": "Id" }, + "workspace_id": { + "anyOf": [{ "type": "string" }, { "type": "null" }], + "title": "Workspace Id" + }, + "url": { "type": "string", "title": "Url" }, + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + } + }, + "type": "object", + "required": ["id", "workspace_id", "url", "created_at"], + "title": "WebhookEndpoint" + }, + "WebhookEndpointCreate": { + "properties": { "url": { "type": "string", "title": "Url" } }, + "type": "object", + "required": ["url"], + "title": "WebhookEndpointCreate" + }, + "Workspace": { + "properties": { + "id": { "type": "string", "title": "Id" }, + "metadata": { + "additionalProperties": true, + "type": "object", + "title": "Metadata" + }, + "configuration": { + "additionalProperties": true, + "type": "object", + "title": "Configuration" + }, + "created_at": { + "type": "string", + "format": "date-time", + "title": "Created At" + } + }, + "type": "object", + "required": ["id", "created_at"], + "title": "Workspace" + }, + "WorkspaceConfiguration": { + "properties": { + "deriver": { + "anyOf": [ + { "$ref": "#/components/schemas/DeriverConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for deriver functionality." + }, + "peer_card": { + "anyOf": [ + { "$ref": "#/components/schemas/PeerCardConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for peer card functionality. If deriver is disabled, peer cards will also be disabled and these settings will be ignored." + }, + "summary": { + "anyOf": [ + { "$ref": "#/components/schemas/SummaryConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for summary functionality." + }, + "dream": { + "anyOf": [ + { "$ref": "#/components/schemas/DreamConfiguration" }, + { "type": "null" } + ], + "description": "Configuration for dream functionality. If deriver is disabled, dreams will also be disabled and these settings will be ignored." + } + }, + "additionalProperties": true, + "type": "object", + "title": "WorkspaceConfiguration", + "description": "The set of options that can be in a workspace DB-level configuration dictionary.\n\nAll fields are optional. Session-level configuration overrides workspace-level configuration, which overrides global configuration." + }, + "WorkspaceCreate": { + "properties": { + "id": { + "type": "string", + "maxLength": 100, + "minLength": 1, + "pattern": "^[a-zA-Z0-9_-]+$", + "title": "Id" + }, + "metadata": { + "additionalProperties": true, + "type": "object", + "title": "Metadata", + "default": {} + }, + "configuration": { + "$ref": "#/components/schemas/WorkspaceConfiguration" + } + }, + "type": "object", + "required": ["id"], + "title": "WorkspaceCreate" + }, + "WorkspaceGet": { + "properties": { + "filters": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Filters" + } + }, + "type": "object", + "title": "WorkspaceGet" + }, + "WorkspaceUpdate": { + "properties": { + "metadata": { + "anyOf": [ + { "additionalProperties": true, "type": "object" }, + { "type": "null" } + ], + "title": "Metadata" + }, + "configuration": { + "anyOf": [ + { "$ref": "#/components/schemas/WorkspaceConfiguration" }, + { "type": "null" } + ] + } + }, + "type": "object", + "title": "WorkspaceUpdate" + } + }, + "securitySchemes": { "HTTPBearer": { "type": "http", "scheme": "bearer" } } + } +} diff --git a/docs/v2/documentation/core-concepts/architecture.mdx b/docs/v2/documentation/core-concepts/architecture.mdx index b0eb7dc3..3a58147d 100644 --- a/docs/v2/documentation/core-concepts/architecture.mdx +++ b/docs/v2/documentation/core-concepts/architecture.mdx @@ -5,14 +5,23 @@ icon: "sitemap" sidebarTitle: "Architecture" --- -Honcho is memory infrastructure that continuously [*reasons*](/v2/documentation/core-concepts/reasoning) about data to build rich representations of peers (users, agents, or any entity) over time. This document explains the data model, system components, and how data flows through Honcho. + The goal of this page is to build an intuition for the primitives in Honcho and how they fit together + +Honcho has 2 main components that work together to manage agent identity and context. + +- **The Memory Layer**: The Memory layer for storing interaction history for your agents +- **The Reasoning Layer**: The background processing layer that builds representations of users and agents + +Below we'll deep dive into these different areas, discussing the data +primitives, the flow of data through the system, artifacts Honcho produces, and +how to use them. ## Data Model Honcho has a hierarchical data model centered around the entities below. ```mermaid - graph LR + graph TD W[Workspaces] -->|have| P[Peers] W -->|have| S[Sessions] @@ -20,83 +29,228 @@ Honcho has a hierarchical data model centered around the entities below. P <-.->|many-to-many| S - style W fill:#B6DBFF,stroke:#333,color:#000 - style P fill:#B6DBFF,stroke:#333,color:#000 - style S fill:#B6DBFF,stroke:#333,color:#000 - style SM fill:#B6DBFF,stroke:#333,color:#000 + style W fill:#FF5A7E,stroke:#333,stroke-width:2px,color:#fff + style P fill:#e1f5fe,stroke:#0277bd,color:#000 + style S fill:#f3e5f5,stroke:#7b1fa2,color:#000 + style SM fill:#e8f5e9,stroke:#2e7d32,color:#000 ``` -- A Workspace has Peers & Sessions -- A Peer can be in multiple Sessions and can send Messages in a Session -- A Session can have many Peers and stores Messages sent by its Peers +- A `Workspaces` has `Peers` & `Sessions` +- A `Peer` can be in multiple `Sessions` and can send `Messages` in a `Session`. +- A `Session` can have many `Peers` and stores `Messages` sent by its `Peers`. ### Workspaces -Workspaces are the top-level containers in Honcho. They provide complete isolation between different applications or environments, essentially serving as a namespace to keep different workloads separate. You might use separate workspaces for development, staging, and production environments, or to isolate different product lines. They also enable multi-tenant SaaS applications where each customer gets their own isolated workspace with complete data separation. +Workspaces are the top-level containers that provide complete isolation between +different applications or environments; they essentially serve as a namespace +to isolate different workloads or environments -Authentication is scoped to the workspace level, and configuration settings can be applied workspace-wide to control behavior across all peers and sessions within that workspace. +**Key Features:** +- **Isolation**: Complete data separation between workspaces +- **Multi-tenancy**: Support multiple applications or environments +- **Configuration**: Workspace-level settings and metadata +- **Access Control**: Authentication scoped to workspace level + +**Use Cases:** +- Separate development/staging/production environments +- Multi-tenant SaaS applications +- Different product lines or use cases +- Complete data separation between teams --- ### Peers -Peers are the most important entity in Honcho--everything revolves around building and maintaining their [*representations*](/v2/documentation/core-concepts/representation). A peer represents any individual user, agent, or entity in a workspace. Treating humans and agents the same way lets you build arbitrary combinations for multi-agent or group chat scenarios. +Honcho has a Peer-Centric Architecture: Peers are the most important entity within Honcho, with everything revolving around Peers and their representations. -Each peer has a unique identifier within a workspace and is a container for reasoning across all their sessions. This cross-session context means conclusions drawn about a peer in one session can inform interactions in completely different sessions. Peers can be configured to control whether Honcho reasons about them. +Peers represent individual users, agents, or entities in a workspace. They are +the primary subjects for memory and context management. Treating humans and +agents the same lets us support arbitrary combinations of Peers for +multi-agent or group chat scenarios. -You can use peers for any entity that persists over time--individual users in chatbot applications, AI agents interacting with users or other agents, customer profiles in support systems, student profiles in educational platforms, or even NPCs in role-playing games. +**Key Features:** +- **Identity**: Unique identifier within a workspace +- **Memory Storage**: Personal memory and context accumulation +- **Configuration**: Per-peer behavioral settings +- **Cross-Session Context**: Memory persists across all sessions + +**Use Cases:** +- Individual users in chatbot applications +- AI agents interacting with users or other agents +- Customer profiles in support systems +- Student profiles in educational platforms +- NPCs in role-playing games --- ### Sessions -Sessions represent interaction threads or contexts between peers. A session can involve multiple peers and provides temporal boundaries for when a set of interactions starts and ends. This lets you scope context and memory to specific interactions while still maintaining longer-term peer representations that span sessions. +Sessions represent individual conversation threads or interaction contexts between peers. -Use sessions to scope things like support tickets, meeting transcripts, learning sessions, or conversations. You can also use single-peer sessions as a way to import external data--create a session with just one peer and structure emails, documents, or files as messages to enrich that peer's representation. +**Key Features:** +- **Multi-Peer**: Support multiple peers in a single session +- **Temporal Boundaries**: Clear start/end to conversation threads +- **Context Scoping**: Session-specific memory and context +- **Configuration**: Session-level behavioral controls -Session-level configuration gives you fine-grained control over perspective-taking behavior. You can configure whether a peer should form representations of other peers in the session, and whether other peers should form representations of them. +**Use Cases:** +- Individual chat conversations +- Support tickets +- Meeting transcripts +- Learning sessions +- Single-Peer onboarding sessions where data is imported from an external source --- ### Messages -Messages are the fundamental units of interaction within sessions. While they typically represent back-and-forth communication between peers, you can also use messages to ingest any information that provides context--emails, documents, files, user actions, system notifications, or rich media content. +Messages are the fundamental units of interaction within sessions. They may +also be used to ingest information of any kind that is not related to a specific interaction, but provides +important context for a peer (emails, docs, files, etc.). Simple make a session +with a single peer and structure the data as messages. -Every message is attributed to a specific peer and ordered chronologically within its session. When messages are created, they trigger automatic background reasoning that updates peer representations. Messages support rich metadata and structured data through JSONB fields, making them flexible enough to capture whatever information matters for your use case. +**Key Features:** +- **Rich Content**: Support for text, metadata, and structured data +- **Attribution**: Clear association with sending peer +- **Ordering**: Chronological sequence within sessions +- **Processing**: Automatic background analysis and insight derivation -## Data Flow +**Message Types:** +- User messages +- AI responses +- System notifications +- Rich media content +- User actions (clicked, reacted, etc.) +- File uploads (PDFs, text files, JSON documents) -Understanding how data moves through Honcho helps clarify the architecture. -When you create messages, they're immediately written to PostgreSQL and reasoning tasks are added to background queues. Background workers then generate logic, summaries, and new insights to improve representations. These conclusions and insights get stored in vector collections for retrieval. This async approach ensures fast writes while still providing rich reasoning capabilities. +## Reasoning Layer -When you need context from Honcho, you query through the "Chat" endpoint or "Get Context" endpoint. Honcho retrieves relevant conclusions from vector storage along with recent messages, then assembles everything into coherent context ready to inject into agent prompts. +The raw data you store in Honcho is useful, but it's not in a format that's most +useful for an LLM to consume. There may be too many tokens that need to be +compacted, key facts about what happened may be hard to piece together because +they involve messages from across different sessions, etc. -![Honcho Architecture](/images/architecture.png) +To solve this problem, Honcho has a reasoning layer that continually processes +incoming data to form the most informationally dense and useful representations of `Peers` +that we can then expose to agents. Honcho does the following tasks in +the reasoning engine. -The diagram above shows how agents write messages to Honcho, which triggers reasoning that updates peer representations. Agents can then query representations to get additional context for their next response. Black arrows represent read/write of regular data (messages, storage), while red arrows represent read/write of reasoned-over data (logic, peer representations). +- **Fact Derivation** +- **Generate Summaries** +- **Generate Peer Cards** +- **Dreaming** -## Configuration & Extensibility -Honcho is designed to be flexible. Settings cascade hierarchically from workspace to peer to session, so you can set defaults at the workspace level and override them for specific peers or sessions. Feature flags let you enable or disable reasoning modes, perspective tracking, and other capabilities. You can bring your own LLM provider--OpenAI, Anthropic, or custom endpoints--and metadata fields let you extend any primitive with custom JSON data. Batch operations let you create up to 100 messages in a single API call for efficient bulk ingestion. +Honcho will reason about each `Message` it +ingests to generate new facts and insights that are spelled out and easy to +consume in an LLM prompt. -## Design Principles +We refer to this module of Honcho as the `Deriver`, because it's constantly +deriving new insights from messages. The sum total of all these generated +insights are what we refer to as a `Representation`, all the data related to who +and what a `Peer` is. -Honcho's architecture follows a few core principles. Everything revolves around building representations of peers (peer-centric). Memory isn't just storage--it's continual learning (reasoning-first). Long-lived operations happen in the background so they don't block user interactions (async by default). The system works with any LLM provider (provider-agnostic) and is built for isolation and scalability from the ground up (multi-tenant). Users and agents are both represented as peers, which enables flexible scenarios you couldn't easily model with a traditional user-assistant paradigm (unified paradigm). +Depending on the configuration of a `Peer` or `Session`, the deriver will behave +differently and update different representations. + +Facts derived here are used in the Dialectic chat endpoint, get_context +endpoint, + + +Deriver tasks are processed in parallel, but tasks affecting the same peer representation will always be processed serially in order of message creation, so as to properly understand their cumulative effect. + + +There are two types of tasks that the deriver currently does: + +- **Representation Tasks**: Generate/update peer representations +- **Summary Tasks**: Generate conversation summaries + +### Local & Global Representations + +Peer representations are more of an abstract concept, as they are made up of +various pieces of data stored throughout Honcho. There are however +multiple types of representations that Honcho can produce. + +Honcho handles both **local** and **global** representations of Peers, where +**local** representations are specific to a single Peer's view of another Peer, +while Global Representations are based on any message ever produced by a Peer. + +Peer Representations + +Everything is framed with regards to perspective. Alice owns her own global +representation, but she also maintains a local representation of Bob based on what she +observes and similarly Bob has a global representation of himself and local +representation of Alice. So in the example above, when Alice sends a message to +Bob it triggers an update to both Alice's global representation of herself and Bob's local +representation of Alice. + +If Alice were to have another conversation with a different Peer, Nico, and +sent them a message, this action would trigger an update to Alice's Global +Representation and Nico's local representation of Alice. Bob's local +representation of Alice would not change since Bob would never receive that +message. + +By default, local representations are disabled, but can be enabled in a +Peer or Session level configuration + +Depending on the use case, a developer may choose to only use global +representation, only use local, or a combination. + +### Summary + +Summary tasks create conversation summaries. Periodically, a +"short" summary will be created for each session as messages are added -- every +20 messages by default. "Long" summaries are created every 60 messages by +default and maintain a total overview of the session by including the previous +summary in a recursive fashion. These summaries are accessed in the +`get_context` endpoint along with recent messages, allowing developers to +easily fetch everything necessary to generate the next LLM completion for an +agent. + +The system defaults are also the checkpoints used on the managed version of +Honcho hosted at [https://api.honcho.dev](https://api.honcho.dev) + + +## Dialectic API + +The Dialectic API is one of the most integral components of Honcho and acts as +the main way to leverage Peer Representations. By using the `/chat` endpoint, +developers can directly talk to Honcho about any Peer in a workspace to get +insights into the psychology of a Peer and help them steer their behavior. + +This allows us to use this one endpoint for a wide variety of use cases. Model +steering, personalization, hydrating a prompt, etc. Additionally, since the +endpoint works through natural language, a developer can allow an agent to +backchannel directly with Honcho, via MCP or a direct API call. + +Developers should frame the Dialectic as talking to an expert on the Peer rather than addressing the Peer itself, meaning: + +```python +alice.chat("What is the user's mood today?") # ✅ Ideal + +alice.chat("What is alice's mood today?") # ✅ Works -- but make sure to consider what peer "Alice" has been saying in their messages about name/identity. + +alice.chat("What is your mood today?") # ❌ Likely to fail -- the dialectic agent may conflate itself and the user. +``` + + +Think of Dialectic Chat as an assisting agent that your main agent can consult for contextual information about any actor in your application. + ## Next Steps - - Sign up for the Honcho platform and start building + + Learn how to use the SDK to interact with the data model + + + Reference for all technical terms and concepts + + + Detailed API documentation and examples Get started with your first integration - - Learn how Honcho reasons about messages to build memory - - - Understand what peer representations are and how they work - diff --git a/docs/v2/documentation/core-concepts/configuration.mdx b/docs/v2/documentation/core-concepts/configuration.mdx new file mode 100644 index 00000000..7edf4230 --- /dev/null +++ b/docs/v2/documentation/core-concepts/configuration.mdx @@ -0,0 +1,396 @@ +--- +title: 'Configure Reasoning' +description: 'Customizing how Honcho handles peers, sessions, and messages' +icon: 'wrench' +--- + +Honcho's reasoning engine (the "deriver") can be configured at multiple levels to control how it processes messages, generates facts, creates summaries, and builds peer representations. + +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. + +You may therefore disable observation of a peer by setting the `observe_me` flag in their configuration to `false`. + +If the peer has a session-level configuration, it will override this configuration. If the flag is not set, or is set to `true`, the peer will be observed. + + +```python Python +from honcho import Honcho + +# Initialize client +honcho = Honcho() + +# Create peer with configuration +peer = honcho.peer("my-peer", config={"observe_me": False}) + +# Change peer's configuration +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}) +``` +```typescript TypeScript +import { Honcho } from "@honcho-ai/sdk"; + +(async () => { + // Initialize client + const honcho = new Honcho({}); + + // Create peer with configuration + const peer = await honcho.peer("my-peer", { config: { observe_me: false } }); + + // Change peer's configuration + 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 } }); +})(); +``` + + +## Session 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 +from honcho import Honcho + +# Initialize client +honcho = Honcho() + +# 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"; + +(async () => { + // Initialize client + const honcho = new Honcho({}); + + // 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 + } + } + }); +})(); +``` + + +## Message Configuration + +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. + +- `observe_others`: Whether this peer should produce local representations of others in the session. By default, this is `false`. Other peers will only be observed if their `observe_me` flag is `true`. + +You can combine these flags across multiple peers to arrange any possible permutation of directional observation. Note that in the default case, no local representations are produced. To produce local representations, you must set the `observe_others` flag to `true` for at least one peer in the session and at least one other peer must have their `observe_me` flag set to `true`. + +Many applications will work best without local representations, preferring to chat with Honcho's top-down representation of each peer. Only enable local representations via the `observe_others` flag if you are doing advanced reasoning on user perspectives. + +Peer Representations + +You can dynamically change the configuration of a session-peer by calling `set_peer_config` on the session with the peer and the configuration you want to set. + + +```python Python +from honcho import Honcho, SessionPeerConfig + +# Initialize client +honcho = Honcho() + +# Create session +session = honcho.session("my-session") + +# Create peers +alice = honcho.peer("alice") +bob = honcho.peer("bob") + +# Add peers to session with default configuration +session.add_peers([alice, bob]) + +# Add another peer to the session with a custom configuration +charlie = honcho.peer("charlie") +session.add_peers([(charlie, SessionPeerConfig(observe_me=False, observe_others=True))]) + +# Set session-peer configuration +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) +print(charlie_config) +``` +```typescript TypeScript +import { Honcho } from "@honcho-ai/sdk"; + +(async () => { + // Initialize client + const honcho = new Honcho({}); + + // Create session + const session = await honcho.session("my-session"); + + // Create peers + const alice = await honcho.peer("alice"); + const bob = await honcho.peer("bob"); + + // Add peers to session + await session.addPeers([alice, bob]); + + // 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 }]]); + + // Set session-peer configuration + await session.setPeerConfig(alice, { observe_others: true }); + await session.setPeerConfig(bob, { observe_me: false }); + + // Get session-peer configuration + const charlieConfig = await session.getPeerConfig(charlie); + console.log(charlieConfig); +})(); +``` + + +## 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. + diff --git a/docs/v2/documentation/core-concepts/features/dialectic-endpoint.mdx b/docs/v2/documentation/core-concepts/features/dialectic-endpoint.mdx new file mode 100644 index 00000000..add5921f --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/dialectic-endpoint.mdx @@ -0,0 +1,87 @@ +--- +title: "Dialectic Endpoint" +description: "An endpoint for reasoning about your users" +icon: "comments" +--- + +Honcho by default runs ambient inference on top of the `message` objects you store. Those messages serve as the ground truth upon which facts about the user are derived and stored. The **Dialectic Endpoint** is the natural language interface through which insights are synthesized from those facts. We believe [intellectual respect](https://blog.plasticlabs.ai/extrusions/Extrusion-02.24) for LLMs is paramount in building effective AI agents/apps. It follows that the LLM should know better than any human what would aid them in their generation task. Thus, the Dialectic endpoint exists for flexible agent-to-agent communication. + +## Automatic Fact Derivation + +On every message written to a session, an automatic callback is run that will reason about the conversation and store facts in a `collection` named `honcho`. This is a reserved `collection` specifically for the backend Honcho agent to interact with. + +## Dialectic Endpoint + +The Dialectic endpoint allows you to define logic enabling your agent to talk to our agent that automatically retrieves and synthesizes facts from the collection. You can use the response as part of your reasoning process for your agent–add it to your next prompt to inject critical context about the user. + +This chat interface is exposed via the `peer.chat()` endpoint. It accepts a string query. Below is some example code on how this works. + +## Prerequisites + + +```python Python +from honcho import Honcho + +# use the default workspace +honcho = Honcho() + +# get/create a peer +peer = honcho.peer("demo-user") + +# get/create a session +session = honcho.session("demo-session") + +# (assuming some messages have been written to Honcho for the deriver to use) +``` + +```typescript TypeScript +import { Honcho } from '@honcho-ai/sdk'; + +// use the default workspace +const honcho = new Honcho({}); + +// get/create a peer +const peer = await honcho.peer('demo-user'); + +// get/create a session +const session = await honcho.session('demo-session'); + +// (assuming some messages have been written to Honcho for the deriver to use) +``` + +## Static Dialectic Call + + +```python Python +query = "What is the user's favorite way of completing the task?" +answer = peer.chat(query) +``` + +```typescript TypeScript +const query = "What is the user's favorite way of completing the task?" +const dialecticResponse = await peer.chat(query) +``` + + +## Streaming Dialectic Call + + +```python Python +query = "What do we know about the user?" +response_stream = peer.chat(query, stream=True) + +for line in response_stream.iter_text(): + print(line) +``` + +```typescript TypeScript +const query = "What do we know about the user?" +const responseStream = await peer.chat(query, { stream: true }) + +for await (const line of responseStream.iter_text()) { + console.log(line) +} +``` + + +We've designed the Dialectic endpoint to be infinitely flexible. We wrote an incomplete list of ideas on how to use it on our blog [here](https://blog.plasticlabs.ai/blog/Introducing-Honcho's-Dialectic-API#how-it-works). diff --git a/docs/v2/documentation/core-concepts/features/file-uploads.mdx b/docs/v2/documentation/core-concepts/features/file-uploads.mdx new file mode 100644 index 00000000..1f275fa6 --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/file-uploads.mdx @@ -0,0 +1,293 @@ +--- +title: 'File Uploads' +description: 'Upload PDFs, text files, and JSON documents to create messages in Honcho' +icon: 'upload' +--- + +Honcho's file upload feature allows you to convert documents into messages automatically. Upload PDFs, text files, or JSON documents, and Honcho will extract the text content, split it into appropriately sized chunks, and create messages that become part of your peer's knowledge or session context. + +This feature is perfect for ingesting documents, reports, research papers, or any text-based content that you want your AI agents to understand and reference. + +## How It Works + +When you upload a file, Honcho: + +1. **Extracts text** from the file using specialized processors based on file type +2. **Creates messages** with the extracted content split into chunks that fit within message limits (messages are limited to 50,000 characters) +3. **Queues processing** for background analysis and insight derivation like any other message + +The file content becomes part of the peer's representation, making it available for natural language queries and context retrieval. + +## Supported File Types + +Honcho currently supports the following file types with more to come: + +- **PDF files** (`application/pdf`) - Text extraction with page numbers +- **Text files** (`text/*`) - Plain text, markdown, code files, etc. +- **JSON files** (`application/json`) - Structured data converted to readable format + + +Files are processed in memory and not stored on disk. Only the extracted text content is preserved in Honcho's message system. + + +## Basic Usage + + +```python Python +from honcho import Honcho + +# Initialize client +honcho = Honcho() + +# Create session and peer +session = honcho.session("research-session") +user = honcho.peer("researcher") + +# Upload a PDF to a session +with open("research_paper.pdf", "rb") as file: + messages = session.upload_file( + file=file, + peer_id=user.id, + ) + +print(f"Created {len(messages)} messages from the PDF") +``` + +```typescript TypeScript +import { Honcho } from "@honcho-ai/sdk"; +import fs from "fs"; + +(async () => { + // Initialize client + const honcho = new Honcho({}); + + // Create session and peer + const session = await honcho.session("research-session"); + const user = await honcho.peer("researcher"); + + // Upload a PDF to a session + const fileStream = fs.createReadStream("research_paper.pdf"); + const messages = await session.uploadFile(fileStream, user.id); + + console.log(`Created ${messages.length} messages from the PDF`); +})(); +``` + + +## Upload Parameters + +The upload methods accept the following parameters: + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `file` | File | Yes | File to upload | +| `peer_id` | String | Yes | ID of the peer creating the messages | + +## File Processing Details + +### Text Extraction + +**PDF Files**: Text is extracted page by page with page numbers preserved: +``` +[Page 1] +Introduction +This document provides... + +[Page 2] +Methodology +Our approach involves... +``` + +**Text Files**: Content is decoded using UTF-8, UTF-16, or Latin-1 encoding as needed. + +**JSON Files**: Structured data is converted to string format. + +### Chunking Strategy + +Large files are automatically split into chunks of ~49,500 characters. The system seeks to break at natural boundaries if present: + +1. Paragraph breaks (`\n\n`) +2. Line breaks (`\n`) +3. Sentence endings (`. `) +4. Word boundaries (` `) + +Each chunk becomes a separate message, maintaining the original document structure. + +## Querying Uploaded Content + +Once files are uploaded, you can query the content using Honcho's natural language interface: + + +```python Python +# Query what was learned from the uploaded documents +response = user.chat("What are the key findings from the research papers I uploaded?") +print(response) + +# Ask about specific documents +response = user.chat("What does the quarterly report say about revenue growth?") +print(response) + +# Get context from the uploaded documents for LLM integration +context = session.get_context(tokens=3000) +messages = context.to_openai(assistant=assistant) +``` + +```typescript TypeScript +(async () => { + // Query what was learned from the uploaded documents + const response = await user.chat("What are the key findings from the research papers I uploaded?"); + console.log(response); + + // Ask about specific documents + const response2 = await user.chat("What does the quarterly report say about revenue growth?"); + console.log(response2); + + // Get context from the uploaded documents for LLM integration + const context = await session.getContext({ tokens: 3000 }); + const messages = context.toOpenAI(assistant); +})(); +``` + + +## Error Handling + +### Unsupported File Types + +Files with unsupported content types will raise an exception: + +```python +try: + messages = session.upload_file( + file=open("image.jpg", "rb"), + peer_id=user.id + ) +except Exception as e: + print(f"Upload failed: {e}") + # Error: "Could not process file image.jpg: Unsupported file type: image/jpeg" +``` + +### Missing Required Fields + +Session uploads require a `peer_id` parameter: + +```python +# This will fail for session uploads +try: + messages = session.upload_file(file=file) # Missing peer_id +except ValueError as e: + print(f"Validation error: {e}") +``` + +## Complete Example: Document Analysis Assistant + +Here's a complete example of building a document analysis assistant: + + +```python Python +from honcho import Honcho + +# Initialize +honcho = Honcho() +session = honcho.session("document-analysis") +user = honcho.peer("analyst") +assistant = honcho.peer("analysis-bot") + +def upload_document(file_path, description): + """Upload a document and add it to the session""" + with open(file_path, "rb") as file: + messages = session.upload_file( + file=file, + peer_id=user.id, + ) + return messages + +def analyze_documents(): + """Get AI analysis of uploaded documents""" + context = session.get_context(tokens=4000) + messages = context.to_openai(assistant=assistant) + # Add analysis request + messages.append({ + "role": "user", + "content": "Please analyze all the documents I've uploaded and provide a comprehensive summary of the key findings, trends, and recommendations." + }) + + # Call OpenAI (or your preferred LLM) + # response = openai.chat.completions.create(model="gpt-4", messages=messages) + # return response.choices[0].message.content + + return "Analysis would be generated here" + +# Upload multiple documents +documents = [ + ("quarterly_report.pdf", "Q3 2024 Quarterly Financial Report"), + ("market_research.pdf", "Market Analysis and Competitive Landscape"), + ("product_roadmap.pdf", "Product Development Roadmap 2024-2025") +] + +for file_path, description in documents: + messages = upload_document(file_path, description) + print(f"Uploaded {file_path}: {len(messages)} messages created") + +# Get AI analysis +analysis = analyze_documents() +print("Document Analysis:", analysis) +``` + +```typescript TypeScript +import { Honcho } from "@honcho-ai/sdk"; +import fs from "fs"; + +(async () => { + // Initialize + const honcho = new Honcho({}); + const session = await honcho.session("document-analysis"); + const user = await honcho.peer("analyst"); + const assistant = await honcho.peer("analysis-bot"); + + async function uploadDocument(filePath: string, description: string) { + const fileStream = fs.createReadStream(filePath); + const messages = await session.uploadFile(fileStream, user.id); + return messages; + } + + async function analyzeDocuments() { + const context = await session.getContext({ tokens: 4000 }); + const messages = context.toOpenAI(assistant); + // Add analysis request + messages.push({ + role: "user", + content: "Please analyze all the documents I've uploaded and provide a comprehensive summary of the key findings, trends, and recommendations." + }); + + // Call OpenAI (or your preferred LLM) + // const response = await openai.chat.completions.create({ model: "gpt-4", messages }); + // return response.choices[0].message.content; + + return "Analysis would be generated here"; + } + + // Upload multiple documents + const documents = [ + ["quarterly_report.pdf", "Q3 2024 Quarterly Financial Report"], + ["market_research.pdf", "Market Analysis and Competitive Landscape"], + ["product_roadmap.pdf", "Product Development Roadmap 2024-2025"] + ]; + + for (const [filePath, description] of documents) { + const messages = await uploadDocument(filePath, description); + console.log(`Uploaded ${filePath}: ${messages.length} messages created`); + } + + // Get AI analysis + const analysis = await analyzeDocuments(); + console.log("Document Analysis:", analysis); +})(); +``` + + +## Error Handling + +- **Always wrap uploads in try-catch blocks** for robust error handling +- **Validate file types** before upload to avoid processing errors +- **Handle large files gracefully** with progress indicators +- **Implement retry logic** for network failures diff --git a/docs/v2/documentation/core-concepts/features/get-context.mdx b/docs/v2/documentation/core-concepts/features/get-context.mdx new file mode 100644 index 00000000..566f5f1a --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/get-context.mdx @@ -0,0 +1,651 @@ +--- +title: 'Get Context' +description: 'Learn how to use get_context() to retrieve and format conversation context for LLM integration' +icon: 'messages' +--- + +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. + +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. + +## 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") + +# 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"); + + // Get basic context (not very useful before adding any messages!) + const context = await session.getContext(); +})(); +``` + + +## Context Parameters + +The `get_context()` method accepts several optional parameters to customize the retrieved context: + +### Token Limits + +Control the size of the context by setting a maximum token count: + + +```python Python +# Limit context to 1500 tokens +context = session.get_context(tokens=1500) + +# Limit context to 3000 tokens for larger conversations +context = session.get_context(tokens=3000) +``` + +```typescript TypeScript +(async () => { + // 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({ + summary: false, + tokens: 2000 + }); +})(); +``` + + +### Peer Representation in Context + +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 +# 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 () => { + // 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 + }); +})(); +``` + + +### Semantic Search with Last Message + +Use `last_user_message` to fetch semantically relevant observations based on the most recent message: + + +```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() + +# Set up conversation +session = honcho.session("support-chat") +user = honcho.peer("user-123") +assistant = honcho.peer("support-bot") + +# 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 for LLM +messages = session.get_context(tokens=2000).to_openai(assistant=assistant) + +# Add new user message and get AI response +messages.append({ + "role": "user", + "content": "Can you reset my password?" +}) + +response = openai_client.chat.completions.create( + model="gpt-4", + messages=messages +) + +# 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 +import OpenAI from 'openai'; +import { Honcho } from "@honcho-ai/sdk"; + +(async () => { + // Initialize clients + const honcho = new Honcho({}); + const openai = new OpenAI(); + + // Set up conversation + const session = await honcho.session("support-chat"); + const user = await honcho.peer("user-123"); + const assistant = await honcho.peer("support-bot"); + + // 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 for LLM + const messages = await session.getContext({ tokens: 2000 }).toOpenAI(assistant); + + // Add new user message and get AI response + const response = await openai.chat.completions.create({ + model: "gpt-4", + messages: [ + ...messages, + { role: "user", content: "Can you reset my password?" } + ] + }); + + // Add AI response back to session + await session.addMessages([ + user.message("Can you reset my password?"), + assistant.message(response.choices[0].message.content) + ]); +})(); +``` + + +### Multi-Turn Conversation Loop + + +```python Python +def chat_loop(): + """Example of a continuous chat loop using get_context()""" + + session = honcho.session("chat-session") + user = honcho.peer("user") + 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)]) + + # 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=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-session"); + const user = await honcho.peer("user"); + const assistant = await honcho.peer("ai-assistant"); + + // 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)]); + + // 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: 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 + +### 1. Token Management + +Always set appropriate token limits to control costs and ensure context fits within LLM limits: + + +```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 + +# Good: Use summaries for very long conversations +context = session.get_context(summary=True, tokens=2000) +``` + +```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 + + // Good: Use summaries for very long conversations + const context = await session.getContext({ summary: true, tokens: 2000 }); +})(); +``` + + +### 2. Context Caching + +For applications with frequent context retrieval, consider caching context when appropriate: + + +```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) + +# Use the same context object for multiple format conversions +``` + +```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); + + // Use the same context object for multiple format conversions +})(); +``` + + +### 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. diff --git a/docs/v2/documentation/core-concepts/features/local-vs-global.mdx b/docs/v2/documentation/core-concepts/features/local-vs-global.mdx new file mode 100644 index 00000000..e5670229 --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/local-vs-global.mdx @@ -0,0 +1,68 @@ +--- +title: Local vs Global Representations +description: Model directional relationships between Peers in Honcho +icon: location-pin +--- + +One of the unique affordances of Honcho is that it allows developers to model +directional relationships between Peers. What I mean by this is you can model +how one `Peer` thinks about another `Peer`. + +There are many use cases where you don't want every agent or human to know +everything about another user such as games or multi-agent workflows. To +illustrate this, the following examples shows 2 conversations. + +Conversation #1 (With Bob and Alice) +``` +Alice: I had a great breakfast today. +Bob: What did you eat? +Alice: I had pancakes and eggs and bacon +``` + +Conversation #2 (With Alice and Charlie) +``` +Alice: I actually didn't eat any breakfast today. +Charlie: Oh that's too bad. +Alice: But I lied to Bob and told him I did, so back me up if you see them. +``` + +Alice told Bob a lie in this conversation. If we stored both of these +conversations in Honcho with Alice, Bob, and Charlie as `Peers` and let them +use Honcho to get insights on each other then Bob would immediately know this +deception. For example: + + + ```python Python + # Bob could run + alice.chat("What did Alice eat today?") + # Response: Alice did not eat anything today + ``` + + +This is a problem. Bob shouldn't be able to know everything about Alice in this +situation. So to support these situations we support what we call **Local +Representations**. + +By default insights generated for a `Peer` are scoped globally. This means every +message sent by that `Peer` in any conversation updates the same representation +of that `Peer`. However, we can enable **Local Representations** so Bob can +form a representation Alice based only on what they observe Alice do. + +This feature is illustrated in the graphic below: +Peer Representations + +We can enable local representation for a `Peer` by setting `observe_others=True`. +This is shown in the [Configure +Reasoning](/v2/documentation/core-concepts/configuration) page. + +Now if we used Bob's local representation of Alice then Bob would only get +insights on what they've seen Alice say to them. + +```python +bob.chat(target="alice", query="What did Alice eat today?") +# Response: Alice ate pancakes, eggs, and bacon +``` + + + Local Representations are turned off by default + diff --git a/docs/v2/documentation/core-concepts/features/queue-status.mdx b/docs/v2/documentation/core-concepts/features/queue-status.mdx new file mode 100644 index 00000000..ed28161f --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/queue-status.mdx @@ -0,0 +1,132 @@ +--- +title: Queue Status +description: Learn how to check the status of the Deriver +icon: lines-leaning +--- + +Whenever `Messages` are stored in Honcho, a background process called the +[Deriver](/docs/v2/documentation/core-concepts/architecture#reasoning-layer) is +triggered to reason about the conversation and generate insights. + +The Deriver is an asynchronous process and, depending on load may not immediately +generated insights for the latest message you've sent. To help with this, Honcho +provides several utilities to check the status of the Deriver. + + +```python Python +from honcho import Honcho +honcho = Honcho() + +status = honcho.get_deriver_status() +honcho.poll_deriver_status() +``` + +```typescript typescript +import { Honcho } from '@honcho-ai/sdk'; + +const honcho = new Honcho({}); + +const status = await honcho.getDeriverStatus(); +await honcho.pollDeriverStatus(); +``` + + +Output types + + +```python Python +class DeriverStatus(BaseModel): + completed_work_units: int + """Completed work units""" + + in_progress_work_units: int + """Work units currently being processed""" + + pending_work_units: int + """Work units waiting to be processed""" + + total_work_units: int + """Total work units""" + + sessions: Optional[Dict[str, Sessions]] = None + """Per-session status when not filtered by session""" +``` +```typescript TypeScript +Promise<{ + totalWorkUnits: number + completedWorkUnits: number + inProgressWorkUnits: number + pendingWorkUnits: number + sessions?: Record + }> + +``` + + +Whenever a `Message` is sent it will generate several tasks. These could +be tasks such as generating insights, cleaning up a representation, summarizing +a conversation etc. These tasks are defined based on who is sending the +message, what `Session` the message is in, and potentially who is observing the +message. We call the combination of these parameters a `work_unit` + +This has a few different implications. + +- tasks within the same work_unit are processed sequentially, but multiple +work_units will be processed in parallel +- If local representations are turned in a Session then a `Message` will + generate an additional work unit for every `Peer` that has `observe_others=True` + +The `get_deriver_status` and `poll_deriver_status` methods can take additional +parameters to scope the status to a specific work unit + + +```python Python +def get_deriver_status( + self, + observer_id: str | None = None, + sender_id: str | None = None, + session_id: str | None = None, + ) -> DeriverStatus: +``` +```typescript TypeScript + +export const DeriverStatusOptionsSchema = z.object({ + observerId: z.string().optional(), + senderId: z.string().optional(), + sessionId: z.string().optional(), + timeoutMs: z + .number() + .positive('Timeout must be a positive number') + .optional(), +}) + +``` + + +Additionally, there are deriver status and polling deriver status methods +available on the `Session` objects in each of the SDKs. + +Below are the function signatures for the session level deriver status method + + +```python python +@validate_call + def get_deriver_status( + self, + observer_id: str | None = None, + sender_id: str | None = None, + ) -> DeriverStatus: +``` + +```typescript TypeScript +async getDeriverStatus( + options?: Omit + ): Promise<{ + totalWorkUnits: number + completedWorkUnits: number + inProgressWorkUnits: number + pendingWorkUnits: number + sessions?: Record + }> +``` + diff --git a/docs/v2/documentation/core-concepts/features/search.mdx b/docs/v2/documentation/core-concepts/features/search.mdx new file mode 100644 index 00000000..c82b3bd7 --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/search.mdx @@ -0,0 +1,246 @@ +--- +title: 'Search' +description: 'Learn how to search across workspaces, sessions, and peers to find relevant conversations and content' +icon: 'magnifying-glass' +--- + +Honcho's search functionality allows you to find relevant messages and conversations across different scopes - from entire workspaces down to specific peers or sessions. + +## Search Scopes + +### Workspace Search + +Search across all content in your workspace - sessions, peers, and messages: + + +```python Python +from honcho import Honcho + +# Initialize client +honcho = Honcho() + +# Search across entire workspace +results = honcho.search("budget planning") + +# Iterate through all results +for result in results: + print(f"Found: {result}") +``` + +```typescript TypeScript +import { Honcho } from "@honcho-ai/sdk"; + +(async () => { + // Initialize client + const honcho = new Honcho({}); + + // Search across entire workspace + const results = await honcho.search("budget planning"); + + // Iterate through all results + for (const result of results) { + console.log(`Found: ${result}`); + } +})(); +``` + + +### Session Search + +Search within a specific session's conversation history: + + +```python Python +# Create or get a session +session = honcho.session("team-meeting-jan") + +# Search within this session only +results = session.search("action items") + +# Process results +for result in results: + print(f"Session result: {result}") +``` + +```typescript TypeScript +(async () => { + // Create or get a session + const session = await honcho.session("team-meeting-jan"); + + // Search within this session only + const results = await session.search("action items"); + + // Process results + for (const result of results) { + console.log(`Session result: ${result}`); + } +})(); +``` + + +### Peer Search + +Search across all content associated with a specific peer: + + +```python Python +# Create or get a peer +alice = honcho.peer("alice") + +# Search across all of Alice's messages and interactions +results = alice.search("programming") + +# View results +for result in results: + print(f"Alice's content: {result}") +``` + +```typescript TypeScript +import { Message } from "@honcho-ai/sdk"; + +(async () => { + // Create or get a peer + const alice = await honcho.peer("alice"); + + // Search across all of Alice's messages and interactions + const results: Message[] = await alice.search("programming"); + + // View results + for (const result of results) { + console.log(`Alice's content: ${result.content}`); + } +})(); +``` + + +## Filters and Limits + +### Get a specific number of results + +You can specify the number of results you want to return by passing the `limit` parameter to the search method. The default is 10 results, with a maximum of 100. + + +```python Python +results = honcho.search("budget planning", limit=20) +``` + +```typescript TypeScript +(async () => { + const results = await honcho.search("budget planning", { limit: 20 }); +})(); +``` + + +### Get messages from a Peer in a specific Session + +Combine Peer-level search with a `session_id` filter to get messages from a Peer in a specific Session. + + +```python Python +my_peer = honcho.peer("my-peer") +my_session = honcho.session("team-meeting-jan") +results = my_peer.search("budget planning", filters={"session_id": my_session.id}) +``` + +```typescript TypeScript +(async () => { + const my_peer = await honcho.peer("my-peer"); + const my_session = await honcho.session("team-meeting-jan"); + const results = await my_peer.search("budget planning", { filters: { session_id: my_session.id } }); +})(); +``` + + +Search returns an object containing an `items` array of message objects: + +```json +{ + "items": [ + { + "id": "", + "content": "", + "peer_id": "", + "session_id": "", + "metadata": {}, + "created_at": "2023-11-07T05:31:56Z", + "workspace_id": "", + "token_count": 123 + } + ] +} +``` + +### Filter results by time range + + +```python Python +results = honcho.search("budget planning", filters={"created_at": {"gte": "2024-01-01", "lte": "2024-01-31"}}) +``` + +```typescript TypeScript +(async () => { + const results = await honcho.search("budget planning", { filters: { created_at: { gte: "2024-01-01", lte: "2024-01-31" } } }); +})(); +``` + + +### Filter results by metadata + + +```python Python +results = honcho.search("budget planning", filters={"metadata": {"key": "value"}}) +``` + +```typescript TypeScript +(async () => { + const results = await honcho.search("budget planning", { filters: { metadata: { key: "value" } } }); +})(); +``` + + +### Best Practices + +### Handle Empty Results Gracefully + + +```python Python +# Always check for empty results +results = honcho.search("very specific query") +result_list = list(results) + +if result_list: + print(f"Found {len(result_list)} results") + for result in result_list: + print(f"- {result}") +else: + print("No results found - try a broader search") +``` + +```typescript TypeScript +import { Message } from "@honcho-ai/sdk"; + +(async () => { + // Always check for empty results + const results: Message[] = await honcho.search("very specific query"); + + if (results.length > 0) { + console.log(`Found ${results.length} results`); + for (const result of results) { + console.log(`- ${result.content}`); + } + } else { + console.log("No results found - try a broader search"); + } +})(); +``` + + +## Conclusion + +Honcho's search functionality provides powerful discovery capabilities across your conversational data. By understanding how to: + +- Choose the appropriate search scope (workspace, session, or peer) +- Handle paginated results effectively +- Combine search with context building + +You can build applications that provide intelligent insights and context-aware responses based on historical conversations and interactions. diff --git a/docs/v2/documentation/core-concepts/features/storing-data.mdx b/docs/v2/documentation/core-concepts/features/storing-data.mdx new file mode 100644 index 00000000..7f280473 --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/storing-data.mdx @@ -0,0 +1,61 @@ +--- +title: Storing Data +description: "Store Data in Honcho to Generate Memories and Insights" +icon: "memory" +--- + +The most basic building block of Honcho's data model is the `Message` object. +A `Message` is sent by a `Peer` and saved in a `Session` + + + + ```python Python + from honcho import Honcho + + honcho = Honcho() + + peer = honcho.peer("sample-peer") + + session = honcho.session("sample-session") + + message = peer.message("Hello, world!") + + session.add_messages([message]) + ``` + + ```typescript TypeScript + import { Honcho } from '@honcho-ai/sdk'; + + const honcho = new Honcho({}); + + const peer = await honcho.peer('sample-peer'); + + const session = await honcho.session('sample-session'); + + const message = peer.message('Hello, world!'); + + await session.addMessages([message]); +``` + + +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/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 +need a single Peer, but many Sessions. Others will only use a single `Session` +for their entire app. These are flexible components that work in any situation. + +## Chat Bots + +A common use case for Honcho to is to build a chatbot like ChatGPT or Claude. +In this case you can simply + +- Make a `Peer` for the User +- 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 diff --git a/docs/v2/documentation/core-concepts/features/streaming-response.mdx b/docs/v2/documentation/core-concepts/features/streaming-response.mdx new file mode 100644 index 00000000..4e53cf9a --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/streaming-response.mdx @@ -0,0 +1,249 @@ +--- +title: "Streaming Responses" +description: "Using streaming responses with Honcho SDKs" +icon: "wave-sine" +--- + +When working with AI-generated content, streaming the response as it's generated can significantly improve the user experience. Honcho provides streaming functionality in its SDKs that allows your application to display content as it's being generated, rather than waiting for the complete response. + +## When to Use Streaming + +Streaming is particularly useful for: + +- Real-time chat interfaces +- Long-form content generation +- Applications where perceived speed is important +- Interactive agent experiences +- Reducing time-to-first-word in user interactions + +## Streaming with the Dialectic Endpoint + +One of the primary use cases for streaming in Honcho is with the Dialectic endpoint. This allows you to stream the AI's reasoning about a user in real-time. + +### Prerequisites + + +```python Python +from honcho import Honcho + +# Initialize client (using the default workspace) +honcho = Honcho() + +# Create or get peers +user = honcho.peer("demo-user") +assistant = honcho.peer("assistant") + +# Create a new session +session = honcho.session("demo-session") + +# Add peers to the session +session.add_peers([user, assistant]) + +# Store some messages for context (optional) +session.add_messages([ + user.message("Hello, I'm testing the streaming functionality") +]) +``` + +```typescript TypeScript +import { Honcho } from '@honcho-ai/sdk'; + +(async () => { + // Initialize client (using the default workspace) + const honcho = new Honcho({}); + + // Create or get peers + const user = await honcho.peer('demo-user'); + const assistant = await honcho.peer('assistant'); + + // Create a new session + const session = await honcho.session('demo-session'); + + // Add peers to the session + await session.addPeers([user, assistant]); + + // Store some messages for context (optional) + await session.addMessages([ + user.message("Hello, I'm testing the streaming functionality") + ]); +})(); +``` + + +## Streaming from the Dialectic Endpoint + + +```python Python +import time + +# Basic streaming example +response_stream = user.chat("What can you tell me about this user?", stream=True) + +for chunk in response_stream.iter_text(): + print(chunk, end="", flush=True) # Print each chunk as it arrives + time.sleep(0.01) # Optional delay for demonstration +``` + +```typescript TypeScript +(async () => { + // Basic streaming example + const responseStream = await user.chat("What can you tell me about this user?", { + stream: true + }); + + // Process the stream + for await (const chunk of responseStream.iter_text()) { + process.stdout.write(chunk); // Write to console without newlines + } +})(); +``` + + +## Working with Streaming Data + +When working with streaming responses, consider these patterns: + +1. **Progressive Rendering** - Update your UI as chunks arrive instead of waiting for the full response +2. **Buffered Processing** - Accumulate chunks until a logical break (like a sentence or paragraph) +3. **Token Counting** - Monitor token usage in real-time for applications with token limits +4. **Error Handling** - Implement appropriate error handling for interrupted streams + +## Example: Restaurant Recommendation Chat + + +```python Python +import asyncio +from honcho import Honcho + +async def restaurant_recommendation_chat(): + # Initialize client + honcho = Honcho() + + # Create peers + user = honcho.peer("food-lover") + assistant = honcho.peer("restaurant-assistant") + + # Create session + session = honcho.session("food-preferences-session") + + # Add peers to session + await session.add_peers([user, assistant]) + + # Store multiple user messages about food preferences + user_messages = [ + "I absolutely love spicy Thai food, especially curries with coconut milk.", + "Italian cuisine is another favorite - fresh pasta and wood-fired pizza are my weakness!", + "I try to eat vegetarian most of the time, but occasionally enjoy seafood.", + "I can't handle overly sweet desserts, but love something with dark chocolate." + ] + + # Add the user's messages to the session + session_messages = [user.message(message) for message in user_messages] + await session.add_messages(session_messages) + + # Print the user messages + for message in user_messages: + print(f"User: {message}") + + # Ask for restaurant recommendations based on preferences + print("\nRequesting restaurant recommendations...") + print("Assistant: ", end="", flush=True) + full_response = "" + + # Stream the response using the user's peer to get recommendations + response_stream = user.chat( + "Based on this user's food preferences, recommend 3 restaurants they might enjoy in the Lower East Side.", + stream=True, + session_id=session.id + ) + + for chunk in response_stream.iter_text(): + print(chunk, end="", flush=True) + full_response += chunk + await asyncio.sleep(0.01) + + # Store the assistant's complete response + await session.add_messages([ + assistant.message(full_response) + ]) + +# Run the async function +if __name__ == "__main__": + asyncio.run(restaurant_recommendation_chat()) +``` + +```typescript TypeScript +import { Honcho } from '@honcho-ai/sdk'; + +(async () => { + async function restaurantRecommendationChat() { + // Initialize client + const honcho = new Honcho({}); + + // Create peers + const user = await honcho.peer('food-lover'); + const assistant = await honcho.peer('restaurant-assistant'); + + // Create session + const session = await honcho.session('food-preferences-session'); + + // Add peers to session + await session.addPeers([user, assistant]); + + // Store multiple user messages about food preferences + const userMessages = [ + "I absolutely love spicy Thai food, especially curries with coconut milk.", + "Italian cuisine is another favorite - fresh pasta and wood-fired pizza are my weakness!", + "I try to eat vegetarian most of the time, but occasionally enjoy seafood.", + "I can't handle overly sweet desserts, but love something with dark chocolate." + ]; + + // Add the user's messages to the session + const sessionMessages = userMessages.map(message => user.message(message)); + await session.addMessages(sessionMessages); + + // Print the user messages + for (const message of userMessages) { + console.log(`User: ${message}`); + } + + // Ask for restaurant recommendations based on preferences + console.log("\nRequesting restaurant recommendations..."); + process.stdout.write("Assistant: "); + let fullResponse = ""; + + // Stream the response using the user's peer to get recommendations + const responseStream = await user.chat( + "Based on this user's food preferences, recommend 3 restaurants they might enjoy in the Lower East Side.", + { + stream: true, + sessionId: session.id + } + ); + + for await (const chunk of responseStream.iter_text()) { + process.stdout.write(chunk); + fullResponse += chunk; + } + + // Store the assistant's complete response + await session.addMessages([ + assistant.message(fullResponse) + ]); + } + + await restaurantRecommendationChat(); +})(); +``` + + +## Performance Considerations + +When implementing streaming: + +- Consider connection stability for mobile or unreliable networks +- Implement appropriate timeouts for stream operations +- Be mindful of memory usage when accumulating large responses +- Use appropriate error handling for network interruptions + +Streaming responses provide a more interactive and engaging user experience. By implementing streaming in your Honcho applications, you can create more responsive AI-powered features that feel natural and immediate to your users. diff --git a/docs/v2/documentation/core-concepts/features/using-filters.mdx b/docs/v2/documentation/core-concepts/features/using-filters.mdx new file mode 100644 index 00000000..6c5143d0 --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/using-filters.mdx @@ -0,0 +1,683 @@ +--- +title: 'Using Filters' +description: "Learn how to filter workspaces, peers, sessions, and messages using Honcho's powerful filtering system" +icon: 'filter' +--- + +Honcho provides a sophisticated filtering system that allows you to query workspaces, peers, sessions, and messages with precise control. The filtering system supports logical operators, comparison operators, metadata filtering, and wildcards to help you find exactly what you need. + +## Basic Filtering Concepts + +Filters in Honcho are expressed as dictionaries that define conditions for matching resources. The system supports both simple equality filters and complex queries with multiple conditions. + +### Simple Filters + +The most basic filters check for exact matches: + + +```python Python +from honcho import Honcho + +# Initialize client +honcho = Honcho() + +# Simple peer filter +peers = honcho.get_peers(filters={"peer_id": "alice"}) + +# Simple session filter with metadata +sessions = honcho.get_sessions(filters={ + "metadata": {"type": "support"} +}) + +# Simple message filter +messages = honcho.get_messages(filters={ + "session_id": "support-chat-1", + "peer_id": "alice" +}) +``` + +```typescript TypeScript +import { Honcho } from "@honcho-ai/sdk"; + +(async () => { + // Initialize client + const honcho = new Honcho({}); + + // Simple peer filter + const peers = await honcho.getPeers({ + filters: { peerId: "alice" } + }); + + // Simple session filter with metadata + const sessions = await honcho.getSessions({ + filters: { + metadata: { type: "support" } + } + }); + + // Simple message filter + const messages = await honcho.getMessages({ + filters: { + sessionId: "support-chat-1", + peerId: "alice" + } + }); +})(); +``` + + +## Logical Operators + +Combine multiple conditions using logical operators for complex queries: + +### AND Operator + +Use AND to require all conditions to be true: + + +```python Python +messages = honcho.get_messages(filters={ + "AND": [ + {"session_id": "chat-1"}, + {"created_at": {"gte": "2024-01-01"}} + ] +}) +``` + +```typescript TypeScript +(async () => { + const messages = await honcho.getMessages({ + filters: { + AND: [ + { sessionId: "chat-1" }, + { createdAt: { gte: "2024-01-01" } } + ] + } + }); +})(); +``` + + +### OR Operator + +Use OR to match any of the specified conditions: + + +```python Python +# Find messages from either alice or bob +messages = session.get_messages(filters={ + "OR": [ + {"peer_id": "alice"}, + {"peer_id": "bob"} + ] +}) + +# Complex OR with metadata conditions +sessions = honcho.get_sessions(filters={ + "OR": [ + {"metadata": {"priority": "high"}}, + {"metadata": {"urgent": True}}, + {"metadata": {"escalated": True}} + ] +}) +``` + +```typescript TypeScript +(async () => { + // Find messages from either alice or bob + const messages = await session.getMessages({ + filters: { + OR: [ + { peerId: "alice" }, + { peerId: "bob" } + ] + } + }); + + // Complex OR with metadata conditions + const sessions = await honcho.getSessions({ + filters: { + OR: [ + { metadata: { priority: "high" } }, + { metadata: { urgent: true } }, + { metadata: { escalated: true } } + ] + } + }); +})(); +``` + + +### NOT Operator + +Use NOT to exclude specific conditions: + + +```python Python +# Find all peers except alice +peers = honcho.get_peers(filters={ + "NOT": [ + {"peer_id": "alice"} + ] +}) + +# Find sessions that are NOT completed +sessions = honcho.get_sessions(filters={ + "NOT": [ + {"metadata": {"status": "completed"}} + ] +}) +``` + +```typescript TypeScript +(async () => { + // Find all peers except alice + const peers = await honcho.getPeers({ + filters: { + NOT: [ + { peerId: "alice" } + ] + } + }); + + // Find sessions that are NOT completed + const sessions = await honcho.getSessions({ + filters: { + NOT: [ + { metadata: { status: "completed" } } + ] + } + }); +})(); +``` + + +### Combining Logical Operators + +Create sophisticated queries by combining different logical operators: + + +```python Python +# Find messages from alice OR bob, but NOT where message has archived set to true in metadata +messages = session.get_messages(filters={ + "AND": [ + { + "OR": [ + {"peer_id": "alice"}, + {"peer_id": "bob"} + ] + }, + { + "NOT": [ + {"metadata": {"archived": True}} + ] + } + ] +}) +``` + +```typescript TypeScript +(async () => { + // Find messages from alice OR bob, but NOT where message has archived set to true in metadata + const messages = await session.getMessages({ + filters: { + AND: [ + { + OR: [ + { peerId: "alice" }, + { peerId: "bob" } + ] + }, + { + NOT: [ + { metadata: { archived: true } } + ] + } + ] + } + }); +})(); +``` + + +## Comparison Operators + +Use comparison operators for range queries and advanced matching: + +### Numeric Comparisons + + +```python Python +# Find sessions created after a specific date +sessions = honcho.get_sessions(filters={ + "created_at": {"gte": "2024-01-01"} +}) + +# Find messages within a date range +messages = session.get_messages(filters={ + "created_at": { + "gte": "2024-01-01", + "lte": "2024-12-31" + } +}) + +# Metadata numeric comparisons +sessions = honcho.get_sessions(filters={ + "metadata": { + "score": {"gt": 8.5}, + "duration": {"lte": 3600} + } +}) +``` + +```typescript TypeScript +(async () => { + // Find sessions created after a specific date + const sessions = await honcho.getSessions({ + filters: { + createdAt: { gte: "2024-01-01" } + } + }); + + // Find messages within a date range + const messages = await session.getMessages({ + filters: { + createdAt: { + gte: "2024-01-01", + lte: "2024-12-31" + } + } + }); + + // Metadata numeric comparisons + const sessions = await honcho.getSessions({ + filters: { + metadata: { + score: { gt: 8.5 }, + duration: { lte: 3600 } + } + } + }); +})(); +``` + + +### List Membership + + +```python Python +# Find messages from specific peers in a session +messages = session.get_messages(filters={ + "peer_id": {"in": ["alice", "bob", "charlie"]} +}) + +# Find sessions with specific tags +sessions = honcho.get_sessions(filters={ + "metadata": { + "tag": {"in": ["important", "urgent", "follow-up"]} + } +}) + +# Not equal comparisons +peers = honcho.get_peers(filters={ + "metadata": { + "status": {"ne": "inactive"} + } +}) +``` + +```typescript TypeScript +(async () => { + // Find messages from specific peers in a session + const messages = await session.getMessages({ + filters: { + peerId: { in: ["alice", "bob", "charlie"] } + } + }); + + // Find sessions with specific tags + const sessions = await honcho.getSessions({ + filters: { + metadata: { + tag: { in: ["important", "urgent", "follow-up"] } + } + } + }); + + // Not equal comparisons + const peers = await honcho.getPeers({ + filters: { + metadata: { + status: { ne: "inactive" } + } + } + }); +})(); +``` + + +## Metadata Filtering + +Metadata filtering is particularly powerful in Honcho, supporting nested conditions and complex queries: + +### Basic Metadata Filtering + + +```python Python +# Simple metadata equality +sessions = honcho.get_sessions(filters={ + "metadata": { + "type": "customer_support", + "priority": "high" + } +}) + +# Nested metadata objects +peers = honcho.get_peers(filters={ + "metadata": { + "profile": { + "role": "admin", + "department": "engineering" + } + } +}) +``` + +```typescript TypeScript +(async () => { + // Simple metadata equality + const sessions = await honcho.getSessions({ + filters: { + metadata: { + type: "customer_support", + priority: "high" + } + } + }); + + // Nested metadata objects + const peers = await honcho.getPeers({ + filters: { + metadata: { + profile: { + role: "admin", + department: "engineering" + } + } + } + }); +})(); +``` + + +### Advanced Metadata Queries + + +If you want to do advanced queries like these, make sure not to create metadata fields that use the same names as the included comparison operators! For example, if you have a metadata field called `contains`, it will conflict with the `contains` operator. + + + +```python Python +# Metadata with comparison operators +sessions = honcho.get_sessions(filters={ + "metadata": { + "score": {"gte": 4.0, "lte": 5.0}, + "created_by": {"ne": "system"}, + "tags": {"contains": "important"} + } +}) + +# Complex metadata conditions +messages = session.get_messages(filters={ + "AND": [ + {"metadata": {"sentiment": {"in": ["positive", "neutral"]}}}, + {"metadata": {"confidence": {"gt": 0.8}}}, + {"content": {"icontains": "thank"}} + ] +}) +``` + +```typescript TypeScript +(async () => { + // Metadata with comparison operators + const sessions = await honcho.getSessions({ + filters: { + metadata: { + score: { gte: 4.0, lte: 5.0 }, + createdBy: { ne: "system" }, + tags: { contains: "important" } + } + } + }); + + // Complex metadata conditions + const messages = await session.getMessages({ + filters: { + AND: [ + { metadata: { sentiment: { in: ["positive", "neutral"] } } }, + { metadata: { confidence: { gt: 0.8 } } }, + { content: { icontains: "thank" } } + ] + } + }); +})(); +``` + + +## Wildcards + +Use wildcards (*) to match any value for a field: + + +```python Python +# Find all sessions with any peer_id (essentially all sessions) +sessions = honcho.get_sessions(filters={ + "peer_id": "*" +}) + +# Wildcard in lists - matches everything +messages = session.get_messages(filters={ + "peer_id": {"in": ["alice", "bob", "*"]} +}) + +# Metadata wildcards +sessions = honcho.get_sessions(filters={ + "metadata": { + "type": "*", # Any type + "status": "active" # But status must be active + } +}) +``` + +```typescript TypeScript +(async () => { + // Find all sessions with any peer_id (essentially all sessions) + const sessions = await honcho.getSessions({ + filters: { + peerId: "*" + } + }); + + // Wildcard in lists - matches everything + const messages = await session.getMessages({ + filters: { + peerId: { in: ["alice", "bob", "*"] } + } + }); + + // Metadata wildcards + const sessions = await honcho.getSessions({ + filters: { + metadata: { + type: "*", // Any type + status: "active" // But status must be active + } + } + }); +})(); +``` + + +## Resource-Specific Examples + +### Filtering Workspaces + + +```python Python +# Find workspaces by name pattern +workspaces = honcho.get_workspaces(filters={ + "name": {"contains": "prod"} +}) + +# Filter by metadata +workspaces = honcho.get_workspaces(filters={ + "metadata": { + "environment": "production", + "team": {"in": ["backend", "frontend", "devops"]} + } +}) +``` + +```typescript TypeScript +(async () => { + // Find workspaces by name pattern + const workspaces = await honcho.getWorkspaces({ + filters: { + name: { contains: "prod" } + } + }); + + // Filter by metadata + const workspaces = await honcho.getWorkspaces({ + filters: { + metadata: { + environment: "production", + team: { in: ["backend", "frontend", "devops"] } + } + } + }); +})(); +``` + + +### Filtering Messages + + +```python Python +# Find error messages from the last week +from datetime import datetime, timedelta + +week_ago = (datetime.now() - timedelta(days=7)).isoformat() +messages = session.get_messages(filters={ + "AND": [ + {"content": {"icontains": "error"}}, + {"created_at": {"gte": week_ago}}, + {"metadata": {"level": {"in": ["error", "critical"]}}} + ] +}) + +# Find messages in specific sessions with sentiment analysis +messages = session.get_messages(filters={ + "AND": [ + {"session_id": {"in": ["support-1", "support-2", "support-3"]}}, + {"metadata": {"sentiment": "negative"}}, + {"metadata": {"confidence": {"gte": 0.7}}} + ] +}) +``` + +```typescript TypeScript +(async () => { + // Find error messages from the last week + const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(); + const messages = await session.getMessages({ + filters: { + AND: [ + { content: { icontains: "error" } }, + { createdAt: { gte: weekAgo } }, + { metadata: { level: { in: ["error", "critical"] } } } + ] + } + }); + + // Find messages in specific sessions with sentiment analysis + const messages = await session.getMessages({ + filters: { + AND: [ + { sessionId: { in: ["support-1", "support-2", "support-3"] } }, + { metadata: { sentiment: "negative" } }, + { metadata: { confidence: { gte: 0.7 } } } + ] + } + }); +})(); +``` + + +## Error Handling + +Handle filter errors gracefully: + + +```python Python +from honcho.exceptions import FilterError + +try: + # Invalid filter - unsupported operator + messages = session.get_messages(filters={ + "created_at": {"invalid_operator": "2024-01-01"} + }) +except FilterError as e: + print(f"Filter error: {e}") + # Handle the error appropriately + +try: + # Invalid column name + sessions = honcho.get_sessions(filters={ + "nonexistent_field": "value" + }) +except FilterError as e: + print(f"Invalid field: {e}") +``` + +```typescript TypeScript +(async () => { + try { + // Invalid filter - unsupported operator + const messages = await session.getMessages({ + filters: { + createdAt: { invalidOperator: "2024-01-01" } + } + }); + } catch (error) { + if (error.message.includes("filters")) { + console.error(`Filter error: ${error.message}`); + // Handle the error appropriately + } + } + + try { + // Invalid column name + const sessions = await honcho.getSessions({ + filters: { + nonexistentField: "value" + } + }); + } catch (error) { + console.error(`Invalid field: ${error.message}`); + } +})(); +``` + + +## Conclusion + +Honcho's filtering system provides powerful capabilities for querying your conversational data. By understanding how to: + +- Use simple equality filters and complex logical operators +- Apply comparison operators for range and pattern matching +- Filter metadata with nested conditions +- Handle wildcards and dynamic filter construction +- Follow best practices for performance and validation + +You can build sophisticated applications that efficiently find and process exactly the conversations, messages, and insights you need from your Honcho data. diff --git a/docs/v2/documentation/core-concepts/features/working-rep.mdx b/docs/v2/documentation/core-concepts/features/working-rep.mdx new file mode 100644 index 00000000..f3ea09b6 --- /dev/null +++ b/docs/v2/documentation/core-concepts/features/working-rep.mdx @@ -0,0 +1,347 @@ +--- +title: 'Working Representations' +description: "Learn how to retrieve cached peer knowledge and understanding using Honcho's working representation system" +icon: 'brain' +--- + +Working representations are Honcho's system for accessing cached psychological models that capture what peers know, think, and remember. Unlike the `chat()` method which generates fresh representations on-demand, the `working_rep()` method retrieves pre-computed representations that have been automatically built and stored as conversations progress. + +## How Working Representations Are Created + +Working representations are automatically generated and cached through Honcho's background processing system: + +1. **Automatic Generation**: When messages are added to sessions, they trigger background jobs that analyze conversations using theory of mind inference and long-term memory integration + +2. **Cached Storage**: The generated representations are stored in the database as metadata on `Peer` objects (for global representations) or `SessionPeer` objects (for session-scoped representations) + +3. **Retrieval**: The `working_rep()` method provides fast access to these cached representations without requiring LLM processing + + +**Cached vs On-Demand**: `working_rep()` retrieves cached representations for fast access, while `peer.chat()` generates fresh representations using the dialectic system. Use `working_rep()` when you need fast access to stored knowledge, and `chat()` when you need current analysis with custom queries. + + +## Basic Usage + +Working representations are accessed through the `working_rep()` method on Session or Peer objects: + + +```python Python +from honcho import Honcho + +# Initialize client +honcho = Honcho() + +# Create peers and session +user = honcho.peer("user-123") +assistant = honcho.peer("ai-assistant") +session = honcho.session("support-conversation") + +# Add conversation to trigger representation generation +session.add_messages([ + user.message("I'm having trouble with my billing account"), + assistant.message("I can help with that. What specific issue are you seeing?"), + user.message("My credit card was charged twice last month"), + assistant.message("I see duplicate charges on your account. Let me refund one of them.") +]) + +# Chat to generate a working representation +response = user.chat("What is this user's main concern right now?", session_id=session.id) + +# 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 +import { Honcho } from "@honcho-ai/sdk"; + +// Initialize client +const honcho = new Honcho({}); + +// Create peers and session +const user = await honcho.peer("user-123"); +const assistant = await honcho.peer("ai-assistant"); +const session = await honcho.session("support-conversation"); + +// Add conversation to trigger representation generation +await session.addMessages([ + user.message("I'm having trouble with my billing account"), + assistant.message("I can help with that. What specific issue are you seeing?"), + user.message("My credit card was charged twice last month"), + assistant.message("I see duplicate charges on your account. Let me refund one of them.") +]); + +// Chat to generate a working representation +const response = await user.chat("What is this user's main concern right now?", { sessionId: session.id }); + +// Retrieve the cached working representation for the user +const userRepresentation = await session.workingRep("user-123"); +console.log("Cached user representation:", userRepresentation); + +// 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 +}); +``` + + +## Understanding Representation Content + +Cached working representations contain structured psychological analysis based on conversation history. The format typically includes: + +### Current Mental State Predictions +Information about what the peer is currently thinking, feeling, or focused on based on recent messages. + +### Relevant Long-term Facts +Facts about the peer that have been extracted and stored over time from various conversations. + +### Example Representation Structure + + +```python Python +# Example of what a cached representation might contain +representation = session.working_rep("user-123") + +# Typical content structure: +""" +PREDICTION ABOUT THE USER'S CURRENT MENTAL STATE: +The user appears frustrated with a billing issue, specifically concerning duplicate charges. +They seem to have some confidence in the support process as they provided specific details. + +RELEVANT LONG-TERM FACTS ABOUT THE USER: +- User has had previous billing inquiries +- User prefers direct, specific communication +- User is detail-oriented when reporting issues +""" + +print("Full representation:", representation) +``` + +```typescript TypeScript +// Example of what a cached representation might contain +const representation = await session.workingRep("user-123"); + +// Typical content structure: +/* +PREDICTION ABOUT THE USER'S CURRENT MENTAL STATE: +The user appears frustrated with a billing issue, specifically concerning duplicate charges. +They seem to have some confidence in the support process as they provided specific details. + +RELEVANT LONG-TERM FACTS ABOUT THE USER: +- User has had previous billing inquiries +- User prefers direct, specific communication +- User is detail-oriented when reporting issues +*/ + +console.log("Full representation:", representation); +``` + + +## When Representations Are Updated + +Working representations are automatically updated through Honcho's background processing system: + +### Message Processing Pipeline + +1. **Message Creation**: When messages are added via `session.add_messages()` or similar methods +2. **Background Queuing**: Messages are queued for processing in the background +3. **Theory of Mind Analysis**: The system analyzes conversation patterns and psychological states +4. **Fact Extraction**: Long-term facts are extracted and stored in vector embeddings +5. **Representation Generation**: New representations are created combining current analysis with historical facts +6. **Cache Update**: The new representation is stored in the database metadata + +### Processing Triggers + +Representations are updated when: +- New messages are added to sessions +- Sufficient new content has accumulated +- The background processing system determines an update is needed + +## Comparison with Chat Method + +Understanding when to use `working_rep()` vs `peer.chat()`: + +### Use `working_rep()` when: +- You need fast access to stored psychological models +- You want to see what the system has already learned about a peer +- You're building dashboards or analytics that display peer understanding +- You need consistent representations that don't change between calls + +### Use `peer.chat()` when: +- You need to ask specific questions about a peer +- You want fresh analysis based on current conversation state +- You need customized insights for specific use cases +- You want to query about relationships between peers + + +```python Python +# Fast cached access +cached_rep = session.working_rep("user-123") +print("Cached:", cached_rep[:100] + "...") + +# Custom query with fresh analysis +custom_analysis = user.chat("What is this user's main concern right now?", session_id=session.id) +print("Fresh analysis:", custom_analysis) +``` + +```typescript TypeScript +// Fast cached access +const cachedRep = await session.workingRep("user-123"); +console.log("Cached:", cachedRep.substring(0, 100) + "..."); + +// Custom query with fresh analysis +const customAnalysis = await user.chat("What is this user's main concern right now?", { sessionId: session.id }); +console.log("Fresh analysis:", customAnalysis); +``` + + +## Best Practices + +### 1. Ensure Availability Before Using + +Make sure that a representation exists before processing it by using the chat endpoint first. + +### 2. Use for Fast Analytics + +Cached representations are ideal for analytics dashboards: + + +```python Python +# Good: Fast dashboard updates using cached data +def update_analytics_dashboard(sessions): + analytics = {} + for session in sessions: + for peer_id in session.get_peer_ids(): + rep = session.working_rep(peer_id) + analytics[peer_id] = analyze_representation(rep) + return analytics +``` + +```typescript TypeScript +// Good: Fast dashboard updates using cached data +async function updateAnalyticsDashboard(sessions) { + const analytics: Record = {}; + for (const session of sessions) { + const peerIds = await session.getPeerIds(); + for (const peerId of peerIds) { + const rep = await session.workingRep(peerId); + analytics[peerId] = analyzeRepresentation(rep); + } + } + return analytics; +} +``` + + +### 3. Combine with Fresh Analysis When Needed + +Use cached representations for baseline understanding, and fresh analysis for current insights: + + +```python Python +# Get baseline understanding from cache +baseline = session.working_rep("user-123") + +# Get current specific insights +current_state = user.chat("How is this user feeling right now?", session_id=session.id) + +# Combine for comprehensive view +comprehensive_view = { + "baseline_knowledge": baseline, + "current_analysis": current_state +} +``` + +```typescript TypeScript +// Get baseline understanding from cache +const baseline = await session.workingRep("user-123"); + +// Get current specific insights +const currentState = await user.chat("How is this user feeling right now?", { sessionId: session.id }); + +// Combine for comprehensive view +const comprehensiveView = { + baselineKnowledge: baseline, + currentAnalysis: currentState +}; +``` + + +## Conclusion + +Working representations provide fast access to cached psychological models that Honcho automatically builds and maintains. By understanding how to: + +- Retrieve cached representations using `session.working_rep()` +- Parse and interpret representation content +- 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. diff --git a/docs/v2/documentation/core-concepts/glossary.mdx b/docs/v2/documentation/core-concepts/glossary.mdx new file mode 100644 index 00000000..177a1510 --- /dev/null +++ b/docs/v2/documentation/core-concepts/glossary.mdx @@ -0,0 +1,55 @@ +--- +title: "Terminology" +description: "Glossary of AI and Honcho Specific Terms" +icon: "book" +--- + +## AI Development Basics + +Essential terms for developers new to building AI applications. + +#### LLM (Large Language Model) +The AI model that generates text responses, like GPT-4, Claude, or Llama. Think of it as the "brain" that powers your chatbot or AI assistant. + +#### Prompt +The text you send to an AI model to get a response. This includes user messages, system instructions, and any context you provide. + +#### Token +How AI models count and limit text. Roughly 1 token = 0.75 words. Models have token limits (like 4,000 or 128,000 tokens) that determine how much text they can process at once. + +#### Context Window +The maximum amount of text an AI model can "remember" in one conversation. Once you exceed this limit, the model starts "forgetting" earlier parts of the conversation. + +#### Embedding +Converting text into numerical vectors that computers can understand and compare. Enables "smart search" that finds similar content based on meaning, not just keywords. + +#### Semantic Search +Search based on meaning rather than exact keyword matching, often using embeddings. + +#### Agent +An AI system that can take actions and make decisions, not just generate text responses. Agents can use tools, call APIs, and interact with external systems. + +## Honcho Terms + +#### Global Representation +Derived context of a specific peer, synthesizing insights from interactions across all sessions, including arbitrary data ingested by this specific peer. With arbitrary data, a global representation can be made independent of sessions. + +#### Local Representation +One peer's persistent context of another based on observed interactions/messages. + +## Cognitive Science Terms + +Cognitive science terms that are used throughout the inspiration and +implementation of Honcho + +#### Theory of Mind +The ability of a computer to understand, remember, and interact with its own mind, enabling it to form representations of the world and make decisions based on its own knowledge and behavior. + +#### Social Cognition +The mental processes by which we perceive, interpret, and respond to information about others and social situations. It includes the encoding, storage, retrieval, and application of social knowledge. + +#### Cognitive Architecture +In CogSci, frameworks describing fixed structures & mechanisms underlying human cognition. Such frameworks aim to explain how various components of the mind—perception, memory, reasoning, learning, etc—combine to produce intelligent behavior across diverse environments. In AI, it’s a computational implementation of these theories—a designed framework to replicate human cognitive functions. + +#### Predictive Coding +A theory in CogSci proposing the brain is an active prediction machine, continually generating & updating internal world models to anticipate sensory input, rather than passively receiving it—closely linked to Bayesian brain hypotheses, which hold that the brain interprets the world probabilistically, weighing prior knowledge against new evidence to minimize uncertainty. diff --git a/docs/v2/documentation/core-concepts/summarizer.mdx b/docs/v2/documentation/core-concepts/summarizer.mdx new file mode 100644 index 00000000..0e14d1ac --- /dev/null +++ b/docs/v2/documentation/core-concepts/summarizer.mdx @@ -0,0 +1,49 @@ +--- +title: 'Summarizer' +description: 'How Honcho creates summaries of conversations' +icon: 'code' +--- + +Almost all agents require, in addition to personalization and memory, a way to quickly prime a context window with a summary of the conversation (in Honcho, this is equivalent to a `session`). The general strategy for summarization is to combine a list of recent messages verbatim with a compressed LLM-generated summary of the older messages not included. Implementing this correctly, in such a way that the resulting context is: + +* Exhaustive: the combination of recent messages and summary should cover the entire conversation +* Dynamically sized: the tokens used on both summary and recent messages should be malleable based on desired token usage +* Performant: while creation of the summary by LLM introduces necessary latency, this should never add latency to an arbitrary end-user request + +...is a non-trivial problem. Summarization should not be necessary to re-implement for every new agent you build, so Honcho comes with a built-in solution. + +### Creating Summaries + +Honcho already has an asynchronous task queue for the purpose of deriving facts from messages. This is the ideal place to create summaries where they won't add latency to a message. Currently, Honcho has two configurable summary types: + +* Short summaries: by default, enqueued every 20 messages and given a token limit of 1000 +* Long summaries: by default, enqueued every 60 messages and given a token limit of 4000 + +Both summaries are designed to be exhaustive: when enqueued, they are given the *prior* summary of their type plus every message after that summary. This recursive compression process naturally biases the summary towards recent messages while still covering the entire conversation. + +For example, if message 160 in a conversation triggers a short summary, as it would with default settings, the summary task would retrieve the prior short summary (message 140) plus messages 141-160. It would then produce a summary of messages 0-160 and store that in the short summary slot on the session. Every session has a single slot for each summary type: new summaries replace old ones. + +It's important to keep in mind that summary tasks run in the background and are not guaranteed to complete before the next message. However, they are guaranteed to complete in order, so that if a user saves 100 messages in a single batch, the short summary will first be created for messages 0-20, then 21-40, and so on, in our desired recursive way. + +### Retrieving Summaries + +Summaries are retrieved from the session by the `get_context` method. This method has two parameters: + +* `summary`: A boolean indicating whether to include the summary in the return type. The default is true. +* `tokens`: An integer indicating the maximum number of tokens to use for the context. **If not provided, `get_context` will retrieve as many tokens as are required to create exhaustive conversation coverage.** + +The return type is simply a list of recent messages and a summary if the flag is used. These two components are dynamically sized based on the token limit. Combined, they will always be below the given token limit. Honcho reserves 60% of the context size for recent messages and 40% for the summary. + +There's a critical trade-off to understand between exhaustiveness and token usage. Let's go through some scenarios: + +* If the *last message* contains more tokens than the context token limit, no summary *or* message list is possible -- both will be empty. + +* If the *last few messages* contain more tokens than the context token limit, no summary is possible -- the context will only contain the last 1 or 2 messages that fit in the token limit. + +* If the summaries contain more tokens than the context token limit, no summary is possible -- the context will only contain the X most recent messages that fit in the token limit. Note that while summaries will often be smaller than their token limits, avoiding this scenario means passing a higher token limit than the Honcho-configured summary size(s). For this reason, the default token limit for `get_context` is a few times larger than the configured long summary size. + +The above scenarios indicate where summarization is not possible -- therefore, the context retrieved will almost certainly **not** be exhaustive. + +Sometimes, gaps in context aren't an issue. In these cases, it's best to pass a reasonable token limit depending on your needs. Other cases demand exhaustive context -- don't pass a token limit and just let Honcho retrieve the ideal combination of summary and recent messages. Finally, if you don't care about the conversation at large and just want the last few messages, set `summary` to false and `tokens` to some multiple of your desired message count. Note that context messages are not paginated, so there's a hard limit on the number of messages that can be retrieved (currently 100,000 tokens). + +As a final note, remember that summaries are generated asynchronously and therefore may not be available immediately. If you batch-save a large number of messages, assume that summaries will not be available until those messages are processed, which can take seconds to minutes depending on the number of messages and the configured LLM provider. Exhaustive `get_context` calls performed during this time will likely just return the messages in the session. diff --git a/docs/v2/documentation/introduction/overview.mdx b/docs/v2/documentation/introduction/overview.mdx index 3d9624f9..e94a85de 100644 --- a/docs/v2/documentation/introduction/overview.mdx +++ b/docs/v2/documentation/introduction/overview.mdx @@ -1,99 +1,119 @@ --- -title: "Honcho Overview" +title: "Honcho" +description: "Go beyond memory to agents with actual social intelligence" icon: "brain" sidebarTitle: "Overview" --- -Honcho is an open source memory library with a managed service for building stateful agents. Use it with any model, framework, or architecture. It enables agents to build and maintain state about any entity--users, agents, groups, ideas, and more. And because it's a continual learning system, it understands entities that change over time. Using Honcho as your memory system will earn your agents higher retention, more trust, and help you build data moats to out-compete incumbents. +Honcho is an AI-native memory library for building agents with +[state-of-the-art](https://blog.plasticlabs.ai/research/Introducing-Neuromancer-XR) +long-term memory. - - - Sign up and start building with Honcho - - - Build your first stateful agent in minutes - - +Agents using Honcho have perfect recall with a wide variety of tools to traverse +their history and get the exact context they need when they need it. - -Honcho is a memory system that reasons. Read more on the approach [here](https://blog.plasticlabs.ai/blog/Memory-as-Reasoning). - +It then goes beyond basic memory by reasoning about the stored history +to expand the latent information available to your agent. Agents using Honcho +will understand who they are, who they are interacting with, what happened, and +when it happened — all without you having to think about it. -## Why Use Honcho? +Use it to build -Honcho streamlines the agent building process by offering elegant, flexible primitives for managing context. It also reasons over that context to give developers access to far richer insights only accessible through reasoning. +- Highly personalized experiences +- Agents with social cognition +- Agents with rich identity that evolve over time +- Multi-agent systems with complex social dynamics -Take the following scenario: -- You find a use case for LLMs and build an agent around it -- It works well initially but can't maintain context across sessions -- You spend weeks engineering a RAG solution that seems to help -- Then the cycle begins... - - Users report the agent forgetting things, contradicting itself, or losing context mid-session - - You build evals to quantify the problem - - You re-engineer your entire RAG pipeline with better chunking, embeddings, retrieval strategies - - The problems shift but don't disappear - - Repeat +```python +# Start simple by just adding messages +session.add_messages([alice.message("I learn best with examples")]) -Eventually you realize the issue isn't engineering—-it's that you're not extracting all the latent information from your data. You need to reason exhaustively, handle contradictions, track patterns over time, and maintain coherent state. In other words, you'd need to build Honcho. +# Honcho will automatically reason about the message to generate insights about Alice -Break free from this cycle. Honcho is a general solution to context engineering, memory, and statefulness. - -## How Honcho Works - -Honcho has four storage primitives that work together: - -```mermaid - graph LR - W[Workspaces] -->|have| P[Peers] - W -->|have| S[Sessions] - - S -->|have| SM[Messages] - - P <-.->|many-to-many| S - - style W fill:#B6DBFF,stroke:#333,color:#000 - style P fill:#B6DBFF,stroke:#333,color:#000 - style S fill:#B6DBFF,stroke:#333,color:#000 - style SM fill:#B6DBFF,stroke:#333,color:#000 +# Get insights by chatting with the agent +insight = peer.chat("How should I explain this concept?") +# > "This user learns best through concrete examples..." ``` -- **Workspaces** - Top-level containers that isolate different applications or environments -- **Peers** - Any entity that persists but changes over time (users, agents, objects, and more) -- **Sessions** - Interaction threads between peers with temporal boundaries -- **Messages** - Units of data that trigger reasoning (conversations, events, activity, documents, and more) +Designed for developers and agents alike: +- **Natural Language Queries**: Chat with Honcho in natural language via the [Dialectic API](../core-concepts/architecture#dialectic-api) to get insights about your users and agents +- **Automatic Context Management**: Smart conversation summaries to have infinite chats +- **Native multi-agent support**: Sessions can natively have as many participants as you need +- **Agent-first interfaces**: MCP connections and APIs designed for agents to consume and use as tools +- **Provider Agnostic**: Works with any LLM or Agent Framework -When you write messages to Honcho, they're stored and processed in the background. Custom reasoning models perform formal logical [*reasoning*](/v2/documentation/core-concepts/reasoning) to generate conclusions about each peer. These conclusions are stored as [*representations*](/v2/documentation/core-concepts/representation) that you can query to provide rich context for your agents. +## How It Works -![Honcho Architecture](/images/architecture.png) + + + High Level Honcho Diagram + + -The diagram above shows the flow: agents write messages to Honcho, which triggers reasoning that updates what's stored in representations. Developers (or agents) can then query to get additional context for their next response. +At a high level Honcho works very simply: -## Why Reasoning? +1. Store messages sent by users and agents in Honcho +2. Honcho reasons about the messages to generate insights about each entity in +the system +3. At runtime your agents can leverage insights from Honcho to get the exact +context they need -Traditional RAG systems retrieve what was explicitly said, but they miss what matters most—the insights only accessible by *rigorously thinking* about your data. Without reasoning, you're leaving latent information on the table. Static retrieval can't surface implicit connections, struggles when new information contradicts old data, and fails when you need to make predictions under uncertainty. +There are several API endpoints to leverage the memory & insights in Honcho. -Honcho uses formal logic to extract all that latent information. This reasoning is AI-native—it performs the rigorous, compute-intensive thinking that humans struggle with, instantly and consistently. The result is memory that goes beyond simple RAG recall to provide exhaustive context for statefulness. +### Get Context -## Get Started +This is the easiest way to leverage Honcho. simply call get context and get the +most relevant information for your conversation. This endpoint is highly +customizable so you can specify parameters such as: -Honcho gives you maximum control over your agent's context and memory. The data model is flexible and composable, the reasoning backend is powerful yet cost-effective, and everything is built to give developers levers to manage token usage, latency, and reasoning depth. +- A number of tokens you want +- An option to include summaries of the conversation +- An option to get a profile of a specific user (Peer Card & Representation) -We're just scratching the surface. Dive into the quickstart to see Honcho in action, explore the architecture to understand how it all fits together, or jump straight to building. +### Search -Welcome to Honcho. We're excited to have you at the frontier of AI with us 🫡. +This endpoint lets you search across Honcho for relevant messages using a +hybrid search strategy that combines full-text and semantic search. - - - Sign up for the Honcho platform and get your API key - - - Build your first stateful agent in minutes - - - Deep dive into how Honcho's primitives fit together - - - Learn how Honcho reasons about data to build memory - - +You can optionally scope the endpoint to a specific workspace, peer, or session. + +### Working Representation + +This endpoint gives you a snapshot of a user or what we call a +**Representation**. Essentially, a list of explicit and deductive facts about +the user that are relevant to the current conversation. + +Plug this into your prompt to get a quick overview of the user. + +### Dialectic API + +This endpoint lets you chat with Honcho about any entity in your system. Honcho +will leverage what it has remembered and learned about the entity to provide in-context actionable insights. + +This is especially helpful when you want your agent to back-channel with Honcho to +change its behavior at runtime. + +Example Queries: +- "What's the best way to explain technical concepts to this user?" +- "Is this user more task-oriented or relationship-oriented?" +- "What time of day is this user most engaged?" +- "How does this user prefer to receive feedback?" +- "What are this user's core values based on our conversations?" + + +## Getting Started + +Ready to integrate Honcho into your application? + + Get up and running with +Honcho in minutes Understand Honcho's +fundamental concepts + +## Community & Support + +- **GitHub**: [plastic-labs/honcho](https://github.com/plastic-labs/honcho) +- **Discord**: [Join our community](http://discord.gg/plasticlabs) +- **Issues**: Report bugs and request features on GitHub diff --git a/docs/v2/documentation/introduction/quickstart.mdx b/docs/v2/documentation/introduction/quickstart.mdx index 927e0ba1..fb5ff35a 100644 --- a/docs/v2/documentation/introduction/quickstart.mdx +++ b/docs/v2/documentation/introduction/quickstart.mdx @@ -1,22 +1,33 @@ --- -title: "Quickstart" -icon: "bolt" -sidebarTitle: "Quickstart" +title: 'Quickstart' +description: 'Start building with Honcho in under 5 minutes.' +icon: 'bolt' --- -Let's get started with Honcho. In this quickstart, you will: +For production-level use, Honcho offers two powerful ways to leverage ambient personalization: our managed platform and our open source solution. Read further if you want to explore the quickstart demo. -- Set up a workspace with peers (user and assistant) -- Ingest messages from across multiple sessions -- Query the reasoning Honcho produces to get synthesized insights about the user + + + Fully managed, hassle-free solution with one-click deployment + + + Self-hosted, fully customizable, and open source + + - -Running the code below requires an API key. Create and account and get your API key at [app.honcho.dev](https://app.honcho.dev) under "API KEYS". +# Getting Started -Every new tenant gets \$100.00 in free credits on sign up. The code below costs ~\$0.04 to run, so don't worry--still plenty of free credits for iterating. - +Have your project use Honcho's ambient personalization capabilities in just a few steps. No signup required! -#### 1. Install the SDK + +By default, the SDK uses the demo server hosted at demo.honcho.dev. The demo server is meant for quick experimentation and the data is cleared on a regular basis. Do not use for production applications. + +For production use: +1. Get your API key at [app.honcho.dev/api-keys](https://app.honcho.dev/api-keys) +2. Set `environment="production"` and provide your `api_key` + + +## 1. Install the SDK ```bash Python (uv) @@ -40,365 +51,259 @@ pnpm add @honcho-ai/sdk ``` -#### 2. Initialize the Client +## 2. Initialize the Client -The Honcho client is the main entry point for interacting with Honcho's API. It uses a workspace called `default` unless specified, so let's create a `first-honcho-test` workspace for this quickstart. +The Honcho client is the main entry point for interacting with Honcho's API. By default, it uses the demo environment and a default workspace. + +### Demo Environment (Default) ```python Python from honcho import Honcho -# Initialize client -honcho = Honcho(workspace="first-honcho-test", api_key=HONCHO_API_KEY) +# Initialize client (uses demo environment and default workspace) +honcho = Honcho() ``` ```typescript TypeScript import { Honcho } from '@honcho-ai/sdk'; -// Initialize client -const honcho = new Honcho({ workspace = "first-honcho-test", apiKey = HONCHO_API_KEY }); +// Initialize client (uses demo environment and default workspace) +const honcho = new Honcho({}); + ``` - -#### 3. Create Peers +### Production Environment ```python Python -user = honcho.peer("user") -assistant = honcho.peer("assistant") +import os +from honcho import Honcho + +# Production environment with API key +honcho = Honcho( + api_key=os.environ["HONCHO_API_KEY"], + environment="production", + # Create a workspace, otherwise set to "default" + # workspaceId="your-workspace-id" +) ``` ```typescript TypeScript -const user = await honcho.peer("user") -const assistant = await honcho.peer("assistant") +import { Honcho } from '@honcho-ai/sdk'; + +// Production environment with API key +const honcho = new Honcho({ + apiKey: process.env.HONCHO_API_KEY!, + environment: "production", + // Create a workspace, otherwise set to "default" + // workspace: "your-workspace-id" +}); ``` -#### 4. Add Messages to Sessions - -We've generated an example conversation dataset with 14 messages across 4 sessions. At a high level, the conversation contains a user chatting with an assistant to get help debugging software infrastructure problems for work *and* jam strategy on a side project they're working on. Spoiler alert--the user is way more interested in their side project. - -Create a file called `conversation.json` and add the content in the accordion below. Then we'll loop through the sessions and messages in that file and write them to Honcho. - - - - - ```json Example Conversation - { - "sessions": [ - { - "id": "session_1", - "messages": [ - { - "role": "user", - "content": "containers getting OOM killed in CI after someone on my team updated the base image. quick fix?" - }, - { - "role": "assistant", - "content": "OOM kills after a base image update usually means the new image has higher memory requirements. Quick fix: bump the memory limit in your CI config. If you need to unblock fast, you could also pin back to the previous base image version temporarily." - } - ] - }, - { - "id": "session_2", - "messages": [ - { - "role": "user", - "content": "hey, been playing with honcho for a side project. do you know if there's a limit on how many users i can have?" - }, - { - "role": "assistant", - "content": "Honcho's free tier is based on context ingested, not number of users - so you can have as many users as you want, you're just limited by how much content you're processing. What are you building?" - }, - { - "role": "user", - "content": "ok so basically it's a personal finance assistant that actually remembers your situation - like it knows you're saving for a house, that you hate subscriptions, that you always regret impulse buys over $50. i've been thinking a lot about the UX, like when should it proactively bring up past context vs wait for you to ask? and how do you balance feeling \"known\" vs feeling surveilled? i have a whole notion doc on this lol" - }, - { - "role": "assistant", - "content": "That's a really thoughtful approach to the personalization problem! The \"known vs surveilled\" tension is exactly right - the best experiences feel like talking to a friend who remembers, not a system that tracks. Proactive context works best when it's in service of the user's stated goals." - } - ] - }, - { - "id": "session_3", - "messages": [ - { - "role": "user", - "content": "do i need to update docker-compose too or just the CI yaml for that memory thing" - }, - { - "role": "assistant", - "content": "Just the CI yaml for the memory limit - docker-compose is separate and only matters if you're hitting the same OOM issue locally." - }, - { - "role": "user", - "content": "k. oh btw 3 friends are using the finance app now, they keep asking when they can pay me lol. one of them said it's the first budgeting thing that \"gets\" her" - }, - { - "role": "assistant", - "content": "That's awesome - \"when can I pay you\" is the best kind of validation. And that quote about it being the first thing that \"gets\" her is exactly the value prop of personalized memory. Sounds like you're onto something real." - } - ] - }, - { - "id": "session_4", - "messages": [ - { - "role": "user", - "content": "if i wanted to charge like $5/mo for the finance app, would honcho's pricing still make sense at that price point? trying to figure out unit economics early" - }, - { - "role": "assistant", - "content": "You should be fine at that price point. Unlike other memory frameworks that charge you to access your own data, Honcho only charges for the reasoning layer - ingestion and inference. Storage and retrieval are free. So your unit economics are mostly about how often you're synthesizing insights, not how much history you're keeping." - }, - { - "role": "user", - "content": "ok interesting. wish i had more time to work on this" - }, - { - "role": "assistant", - "content": "Yeah, sounds like you've got something worth making time for. The early traction is real." - } - ] - } - ] - } - ``` - +## 3. Create Peers +Peers represent individual users, AI agents, or any conversational entity in your system: ```python Python -import json - -# Load conversation data -with open("conversation.json", "r") as f: - data = json.load(f) - -# Process each session -for session_data in data["sessions"]: - session = honcho.session(session_data["id"]) - session.add_peers([user, assistant]) - - # Add messages with correct roles - messages = [] - for msg in session_data["messages"]: - if msg["role"] == "user": - messages.append(user.message(msg["content"])) - elif msg["role"] == "assistant": - messages.append(assistant.message(msg["content"])) - - session.add_messages(messages) +alice = honcho.peer("alice") +bob = honcho.peer("bob") ``` ```typescript TypeScript -import * as fs from 'fs'; - -const data = JSON.parse(fs.readFileSync("conversation.json", "utf-8")); - -for (const sessionData of data.sessions) { - const session = honcho.session(sessionData.id); - session.addPeers([user, assistant]); - - const messages = sessionData.messages.map((msg: any) => - msg.role === "user" ? user.message(msg.content) : assistant.message(msg.content) - ); - - session.addMessages(messages); -} +const alice = await honcho.peer("alice") +const bob = await honcho.peer("bob") ``` -#### 5. Query for Insights +## 4. Create a Session -Now ask Honcho what it's learned--this is where the magic happens: +Sessions are independent conversations that can include multiple peers: ```python Python -response = user.chat("What should I know about this user? 3 sentences max") +session = honcho.session("session_1") +session.add_peers([alice, bob]) +``` + +```typescript TypeScript +const session = await honcho.session("session_1") +await session.addPeers([alice, bob]) +``` + + +## 5. Add Messages + +Add some conversation messages. Honcho automatically learns from these interactions: + + +```python Python +session.add_messages([ + alice.message("Hi Bob, how are you?"), + bob.message("I'm good, thank you!"), + alice.message("What are you doing today after work?"), + bob.message("I'm going to the gym! I've been trying to get back in shape."), + alice.message("That's great! I should probably start exercising too."), + bob.message("You should! I find that evening workouts help me relax."), +]) +``` + +```typescript TypeScript +await session.addMessages([ + alice.message("Hi Bob, how are you?"), + bob.message("I'm good, thank you!"), + alice.message("What are you doing today after work?"), + bob.message("I'm going to the gym! I've been trying to get back in shape."), + alice.message("That's great! I should probably start exercising too."), + bob.message("You should! I find that evening workouts help me relax."), +]) +``` + + +## 6. Query for Insights + +Now ask Honcho what it's learned - this is where the magic happens: + + +```python Python +# Ask what Bob is like +response = bob.chat("Tell me about Bob's interests and habits") print(response) + +# Returns rich context like: +# "Bob is health-conscious and has been working on getting back in shape. +# He regularly goes to the gym, particularly in the evenings, and finds +# exercise helps him relax. He's encouraging about fitness and willing +# to share advice about workout routines." ``` ```typescript TypeScript -user.chat("What should I know about this user? 3 sentences max").then((response) => { +bob.chat("Tell me about Bob's interests and habits").then((response) => { console.log(response); + // Returns rich context like: + // "Bob is health-conscious and has been working on getting back in shape. + // He regularly goes to the gym, particularly in the evenings, and finds + // exercise helps him relax. He's encouraging about fitness and willing + // to share advice about workout routines." }) ``` - -Honcho needs a short amount of time to process messages you write to it. There are several utilities to [check the status](/v2/documentation/features/advanced/queue-status) of the queue. Honcho also offers numerous ways to query reasoning to fit latency needs: see the [Get Context](/v2/documentation/features/get-context) page. - - -The response will look something like this: - -> User is a personal finance app developer building a personalized finance assistant that's generating real demand (friends are already asking when they can pay). They're notably thoughtful about product design, carefully considering the UX balance between making users feel "known" versus "surveilled" when their app proactively surfaces remembered context like savings goals and spending regrets. They're business-minded and working through unit economics early, exploring a $5/month subscription model with usage-based cost structure focused on insight generation frequency rather than data storage—though they wish they had more time to dedicate to the project. - -Honcho synthesizes signal by reasoning about the user to draw conclusions beyond what was explicitly stated. It identifies the user as "notably thoughtful about product design", "business-minded" from the discussion of unit economics, and surfaces the signal that they desire to work on the project more. - -This is rich personal context for domain-specific agents to do what they want with. -- A life coach agent might see "they wish they had more time to dedicate to the project" and "friends are already asking when they can pay" and ask "have you thought about what it would take to go full-time?" -- A productivity agent might see the same pattern and say "let's protect your weekend time for the finance app." -- A financial advisor agent might see it and ask "what runway would you need to make the leap?" - -Honcho acts almost like a detective--it reasons about new and existing evidence in order to form conclusions that can be used to make a *case*. These conclusions wait to be composed dynamically based on how you, the ~~judge~~ developer, query it. This approach is what drives our [pareto-frontier](TODO: link to evals page here) performance on memory benchmarks, and our custom models allow us to optimize speed and cost. - - -## Next Steps - -You just saw how Honcho reasons about data to build rich peer representations. In this quickstart, you: - -- Set up a workspace with peers (user and assistant) -- Ingested messages across multiple sessions -- Queried the reasoning to get synthesized insights about the user - -Here's the full working code if you want to run it yourself: - - - - +## 7. Putting it all together + ```python Python -# uv sync -# uv run python test.py - -import json -import time -import uuid - +import os from honcho import Honcho -from dotenv import load_dotenv -load_dotenv() +# Create your client +honcho = Honcho( + api_key=os.environ["HONCHO_API_KEY"], + environment="production", + # Create a workspace, otherwise set to "default" + # workspaceId="your-workspace-id" +) -# Initialize Honcho client with a unique workspace -workspace_id = f"docs-example-{uuid.uuid4().hex[:8]}" -honcho = Honcho(environment="production", workspace_id=workspace_id) +# Get your Peers +alice = honcho.peer("alice") +bob = honcho.peer("bob") -# Create peers to represent the user and assistant -user = honcho.peer("user") -assistant = honcho.peer("assistant") +# Make a Session and add your Peers +session = honcho.session("session_1") +session.add_peers([alice, bob]) -# Load conversation data from JSON file -with open("conversation.json", "r") as f: - conversation_data = json.load(f) +# Add messages sent by your Peers +session.add_messages([ + alice.message("Hi Bob, how are you?"), + bob.message("I'm good, thank you!"), + alice.message("What are you doing today after work?"), + bob.message("I'm going to the gym! I've been trying to get back in shape."), + alice.message("That's great! I should probably start exercising too."), + bob.message("You should! I find that evening workouts help me relax."), +]) -# Import historical conversation sessions -for session_data in conversation_data["sessions"]: - session = honcho.session(session_data["id"]) - session.add_peers([user, assistant]) - - # Convert messages to peer messages with correct attribution - messages = [] - for msg in session_data["messages"]: - if msg["role"] == "user": - messages.append(user.message(msg["content"])) - elif msg["role"] == "assistant": - messages.append(assistant.message(msg["content"])) - - session.add_messages(messages) - -# Wait for Honcho to process the conversation history -def wait_for_processing(): - status = honcho.get_deriver_status() - while status.pending_work_units > 0 or status.in_progress_work_units > 0: - time.sleep(1) - status = honcho.poll_deriver_status() - -print("Processing conversation history...") -start_time = time.time() -wait_for_processing() -elapsed = int(time.time() - start_time) -print(f"Done in {elapsed}s! Querying user insights...\n") - -# Query insights about the user based on conversation history -response = user.chat("What should I know about this user? 3 sentences max") +# Get insights about your Peers +response = bob.chat("Tell me about Bob's interests and habits") print(response) + +# Returns rich context like: +# "Bob is health-conscious and has been working on getting back in shape. +# He regularly goes to the gym, particularly in the evenings, and finds +# exercise helps him relax. He's encouraging about fitness and willing +# to share advice about workout routines." ``` -```typescript Typescript -// npm install -// npx ts-node test.ts - -import * as fs from 'fs'; -import { randomUUID } from 'crypto'; -import * as dotenv from 'dotenv'; +```typescript TypeScript import { Honcho } from '@honcho-ai/sdk'; -dotenv.config(); - -// Initialize Honcho client with a unique workspace -const workspaceId = `docs-example-${randomUUID().slice(0, 8)}`; +// Create your client const honcho = new Honcho({ - environment: "production", - workspaceId, + apiKey: process.env.HONCHO_API_KEY!, + environment: "production", + // Create a workspace, otherwise set to "default" + // workspace: "your-workspace-id" }); -// Create peers to represent the user and assistant -const user = await honcho.peer("user"); -const assistant = await honcho.peer("assistant"); +// Get your Peers +const alice = await honcho.peer("alice") +const bob = await honcho.peer("bob") -// Load conversation data from JSON file -const conversationData = JSON.parse(fs.readFileSync("conversation.json", "utf-8")); +// Make a Session and add your peers +const session = await honcho.session("session_1") +await session.addPeers([alice, bob]) -// Import historical conversation sessions -for (const sessionData of conversationData.sessions) { - const session = await honcho.session(sessionData.id); - await session.addPeers([user, assistant]); - - // Convert messages to peer messages with correct attribution - const messages = []; - for (const msg of sessionData.messages) { - if (msg.role === "user") { - messages.push(user.message(msg.content)); - } else if (msg.role === "assistant") { - messages.push(assistant.message(msg.content)); - } - } - - await session.addMessages(messages); -} - -// Wait for Honcho to process the conversation history -async function waitForProcessing() { - let status = await honcho.getDeriverStatus(); - while (status.pendingWorkUnits > 0 || status.inProgressWorkUnits > 0) { - await new Promise(resolve => setTimeout(resolve, 1000)); - status = await honcho.pollDeriverStatus(); - } -} - -console.log("Processing conversation history..."); -const startTime = Date.now(); -await waitForProcessing(); -const elapsed = Math.floor((Date.now() - startTime) / 1000); -console.log(`Done in ${elapsed}s! Querying user insights...\n`); - -// Query insights about the user based on conversation history -const response = await user.chat("What should I know about this user? 3 sentences max"); -console.log(response); +// Add messages sent by your Peers +await session.addMessages([ + alice.message("Hi Bob, how are you?"), + bob.message("I'm good, thank you!"), + alice.message("What are you doing today after work?"), + bob.message("I'm going to the gym! I've been trying to get back in shape."), + alice.message("That's great! I should probably start exercising too."), + bob.message("You should! I find that evening workouts help me relax."), +]) +// Get insights about your peers +bob.chat("Tell me about Bob's interests and habits").then((response) => { + console.log(response); + // Returns rich context like: + // "Bob is health-conscious and has been working on getting back in shape. + // He regularly goes to the gym, particularly in the evenings, and finds + // exercise helps him relax. He's encouraging about fitness and willing + // to share advice about workout routines." +}) ``` - +## What Just Happened? -From here, you can explore how to use Honcho's features in your own applications: +You just got through building a simple conversation between two people, Alice +and Bob. We: - - - Learn how to fetch the right context for your agent's next response +1. Set up our connection to Honcho. +2. Setup who the participants of our conversation are, these are called `Peers`. +3. Made a `Session` and added our `Peers` to it. +4. Sent messages from our `Peers` +5. Chat with Honcho to get insights about one of the `Peers` in the conversation + +As soon as you save a message in Honcho, it will start to reason about it to +pull out insights and develop a profile of the user. This is the default +behavior and can be toggled off via [the configuration](/v2/documentation/core-concepts/configuration). + +## Next Steps + + + + Learn about the data primitives in Honcho and how they work together - - Deep dive into how Honcho's primitives fit together - - - Query representations with natural language + + Sign up for Managed Honcho and get started building agents now. - Integration patterns and advanced use cases - + Check out spellbooks to see different examples apps built with Honcho + diff --git a/docs/v2/documentation/introduction/vibecoding.mdx b/docs/v2/documentation/introduction/vibecoding.mdx index 1c0ae6ec..7127c8e6 100644 --- a/docs/v2/documentation/introduction/vibecoding.mdx +++ b/docs/v2/documentation/introduction/vibecoding.mdx @@ -5,19 +5,22 @@ description: "Universal starter prompt for building with Honcho" sidebarTitle: 'Vibecoding Setup' --- -These docs are designed to be easily consumable by LLMs. Each page has a button that lets you copy the page as Markdown or paste directly into ChatGPT or Claude. +These docs are designed to be easily consumable for LLMs. Each page has a button +the lets you copy the page as Markdown or paste directly into ChatGPT or Claude. -We follow the llms.txt standard. There are both an llms.txt and llms-full.txt available: +Additionally, we follow the llms.txt standard. There are both an llms.txt and +llms-full.txt available. - [llms.txt](/llms.txt) - [llms-full.txt](/llms-full.txt) -We also provide a starter prompt to paste into a coding assistant to quickly get started building with Honcho. +Additionally, we provide a starter prompt to paste into a coding assistant to +quickly get started building with Honcho. -## Universal Starter Prompt +## 🚀 Universal Starter Prompt ``` -I want to start building with Honcho - an open source memory library for building stateful agents. +I want to start building with Honcho - a memory and personalization platform for AI applications. ## Honcho Resources @@ -25,7 +28,7 @@ I want to start building with Honcho - an open source memory library for buildin - Main docs: https://docs.honcho.dev - API Reference: https://docs.honcho.dev/v2/api-reference/introduction - Quickstart: https://docs.honcho.dev/v2/documentation/introduction/quickstart -- Architecture: https://docs.honcho.dev/v2/documentation/core-concepts/architecture +- Architecture: https://docs.honcho.dev/v2/documentation/reference/architecture **Code & Examples:** - Core repo: https://github.com/plastic-labs/honcho @@ -35,25 +38,27 @@ I want to start building with Honcho - an open source memory library for buildin - Telegram bot example: https://github.com/plastic-labs/telegram-python-starter **What Honcho Does:** -Honcho is an open source memory library with a managed service for building stateful agents. It enables agents to build and maintain state about any entity--users, agents, groups, ideas, and more. Because it's a continual learning system, it understands entities that change over time. - -When you write messages to Honcho, they're stored and processed in the background. Custom reasoning models perform formal logical reasoning to generate conclusions about each peer. These conclusions are stored as representations that you can query to provide rich context for your agents. +Honcho provides persistent memory and personalization for AI apps. It automatically: +- Stores conversation history across sessions +- Learns facts about users from conversations +- Builds user representations for personalized responses +- Manages multi-user sessions with theory of mind +- Provides context injection for any LLM **Architecture Overview:** -- Core primitives: Workspaces contain Peers (any entity that persists but changes) and Sessions (interaction threads between peers) -- Peers can observe other peers in sessions (configurable with observe_me and observe_others) -- Background reasoning processes messages to extract premises, draw conclusions, and build representations -- Representations enable continuous improvement as new messages refine existing conclusions and scaffold new ones over time -- Chat endpoint provides personalized responses based on learned context +- Core primitives: Workspaces contain Peers (users/agents) and Sessions (conversations) +- Peers can observe other peers in sessions (configurable with observe_me_observe_others) +- Background deriver processes messages to extract facts and update representations +- Dialectic API provides personalized responses based on learned context - Supports any LLM (OpenAI, Anthropic, open source) -- Can use managed service or self-host +- Can use demo server or self-host Please assess the resources above and ask me relevant questions to help build a well-structured application using Honcho. Consider asking about: - What I'm trying to build - My technical preferences and stack -- Whether I want to use the managed service or self-host +- Whether I want to use the demo server or self-host - My experience level with the technologies involved -- Specific features I need (multi-peer sessions, perspective-taking, streaming, etc.) +- Specific features I need (multi-user, voice, web UI, etc.) -Once you understand my needs, help me create a working implementation with proper memory and statefulness. +Once you understand my needs, help me create a working implementation with proper memory persistence. ``` diff --git a/docs/v2/documentation/reference/guided-tutorial.mdx b/docs/v2/documentation/reference/guided-tutorial.mdx new file mode 100644 index 00000000..a7cac2f5 --- /dev/null +++ b/docs/v2/documentation/reference/guided-tutorial.mdx @@ -0,0 +1,425 @@ +--- +title: 'Guided Tutorial' +description: 'Step-by-step tutorial for building with Honcho' +icon: 'graduation-cap' +--- + +This comprehensive tutorial will walk you through building a complete AI application with Honcho, from basic setup to advanced features. + +## What We'll Build + +By the end of this tutorial, you'll have created a personal AI assistant that: +- Learns about users through conversation and remembers facts across sessions +- Automatically formats conversation context for any LLM (OpenAI, Anthropic, etc.) +- Answers questions about what it knows using natural language queries +- Handles multi-party conversations with theory-of-mind modeling + +## Prerequisites + +- Python 3.8 or higher +- Basic understanding of Python +- OpenAI API key (or another LLM provider) + +## Part 1: Basic Setup + +### Install Dependencies + + +```bash pip +pip install honcho-ai openai python-dotenv +``` + +```bash poetry +poetry add honcho-ai openai python-dotenv +``` + + +### Environment Setup + +Create a `.env` file in your project directory: + +```bash +OPENAI_API_KEY=your_openai_api_key_here +HONCHO_API_KEY=your_honcho_api_key_here +``` + +### Initialize Honcho + +```python +import os +from dotenv import load_dotenv +from honcho import Honcho +import openai + +# Load environment variables +load_dotenv() +openai.api_key = os.getenv("OPENAI_API_KEY") + +# Initialize Honcho with your app workspace +honcho = Honcho(workspace_id="personal-assistant-tutorial") +``` + +## Part 2: Peer Management + +### Create and Manage Peers + +```python +def get_user_peer(username): + """Get or create a peer representing a user""" + # Peers are created lazily - no API call until used + user_peer = honcho.peer(f"user-{username}") + print(f"Created peer for user: {username}") + return user_peer + +def get_assistant_peer(): + """Get or create the assistant peer""" + assistant_peer = honcho.peer("assistant") + print("Created assistant peer") + return assistant_peer + +# Create peers for our conversation +alice = get_user_peer("alice") +assistant = get_assistant_peer() + +print(f"User peer ID: {alice.id}") +print(f"Assistant peer ID: {assistant.id}") +``` + +## Part 3: Session Management + +### Create Conversation Sessions + +```python +def start_new_session(session_name=None): + """Start a new conversation session""" + # Create session with descriptive ID + session_id = session_name or f"chat-{int(time.time())}" + session = honcho.session(session_id) + + # Add both peers to the session + session.add_peers([alice, assistant]) + + print(f"Started new session: {session.id}") + return session + +import time +# Start a session +session = start_new_session("daily-checkin") +``` + +### Message Handling + +```python +def add_conversation_turn(session, user_message, assistant_response=None): + """Add a conversation turn to the session""" + messages_to_add = [alice.message(user_message)] + + if assistant_response: + messages_to_add.append(assistant.message(assistant_response)) + + session.add_messages(messages_to_add) + print(f"Added {len(messages_to_add)} messages to session") + +# Add user message +add_conversation_turn(session, "Hi! I'm working on a Python project today.") +``` + +## Part 4: LLM Integration with Context + +### Store Information in Peer Representations + +```python +def teach_assistant_about_user(assistant_peer, user_peer, facts): + """Add facts about the user to the assistant's knowledge""" + # Format facts as messages to build the assistant's representation + fact_messages = [] + for fact in facts: + fact_messages.append(assistant_peer.message(f"I learned that {user_peer.id} {fact}")) + + # Add these to the assistant's global knowledge + assistant_peer.add_messages(fact_messages) + print(f"Taught assistant {len(facts)} facts about {user_peer.id}") + +def extract_facts_from_message(user_message): + """Extract facts about the user from their message using LLM""" + prompt = f""" + Extract discrete facts about the user from this message: + "{user_message}" + + Return only factual statements about the user, no inferences. + Format as a simple list of facts starting with action verbs or descriptors. + If no facts can be extracted, return an empty list. + Example: "is working on a Python project", "likes morning coffee" + """ + + response = openai.chat.completions.create( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": prompt}], + temperature=0.1 + ) + + facts_text = response.choices[0].message.content.strip() + + # Parse facts (simple line-by-line approach) + facts = [fact.strip("- ").strip() for fact in facts_text.split('\n') if fact.strip()] + return [fact for fact in facts if fact and len(fact) > 5] + +# Extract and store facts +user_input = "Hi! I'm working on a Python project today." +facts = extract_facts_from_message(user_input) +print(f"Extracted facts: {facts}") + +# Teach the assistant these facts +if facts: + teach_assistant_about_user(assistant, alice, facts) +``` + +## Part 5: LLM Integration with Context + +### Generate Responses Using Built-in Context + +```python +def generate_response_with_context(session, assistant_peer, user_message): + """Generate AI response using Honcho's built-in context management""" + + # Get formatted conversation context - Honcho handles the complexity! + context = session.get_context(tokens=2000) + messages = context.to_openai(assistant=assistant_peer) + + # Add the current user message + messages.append({"role": "user", "content": user_message}) + + # Call your LLM with the properly formatted context + response = openai.chat.completions.create( + model="gpt-3.5-turbo", + messages=messages, + temperature=0.7 + ) + + return response.choices[0].message.content + +# Generate response using built-in context +user_input = "How's my project going?" +ai_response = generate_response_with_context(session, assistant, user_input) + +print(f"AI Response: {ai_response}") + +# Add the complete conversation turn to the session +add_conversation_turn(session, user_input, ai_response) +``` + +### Query Peer Knowledge Directly + +```python +def get_personalized_insight(assistant_peer, user_peer, query): + """Query what the assistant knows about a specific user""" + # Honcho's chat handles context retrieval automatically + response = assistant_peer.chat( + f"Based on what I know about {user_peer.id}: {query}", + target=user_peer + ) + return response + +# Get personalized insights without manual context building +insight = get_personalized_insight( + assistant, + alice, + "What programming projects has this user worked on?" +) +print(f"Programming insights: {insight}") +``` + +## Part 6: Complete Conversation Loop + +### Put It All Together + +```python +def chat_with_assistant(user_peer, assistant_peer, message_text, session=None): + """Complete conversation flow with memory and personalization""" + + # Use existing session or create new one + if not session: + session = start_new_session() + + # Extract facts from user message and teach assistant + facts = extract_facts_from_message(message_text) + if facts: + teach_assistant_about_user(assistant_peer, user_peer, facts) + + # Generate response using Honcho's built-in context management + ai_response = generate_response_with_context(session, assistant_peer, message_text) + + # Add the conversation turn to session + add_conversation_turn(session, message_text, ai_response) + + return ai_response + +# Test the complete flow +response = chat_with_assistant( + alice, + assistant, + "I finished the authentication module for my Python project!" +) +print(f"Assistant: {response}") + +# Continue the conversation +response2 = chat_with_assistant( + alice, + assistant, + "What should I work on next?", + session # Continue in same session +) +print(f"Assistant: {response2}") +``` + +## Part 7: Advanced Features + +### Multi-Session Memory + +```python +def query_user_history(assistant_peer, user_peer, query): + """Query what the assistant knows about the user across all sessions""" + response = assistant_peer.chat( + f"Based on everything I know about {user_peer.id}, {query}", + target=user_peer + ) + return response + +# Query across all conversations +history_query = query_user_history( + assistant, + alice, + "what programming languages and technologies has this user mentioned?" +) +print(f"User's programming history: {history_query}") +``` + +### Session-Specific Context + +```python +def query_session_specific(assistant_peer, session, query): + """Query what happened in a specific session""" + response = assistant_peer.chat( + query, + session_id=session.id + ) + return response + +# Query about current session +session_summary = query_session_specific( + assistant, + session, + "What did we discuss in this conversation?" +) +print(f"Session summary: {session_summary}") +``` + +### Working with Multiple Users + +```python +def create_group_session(user_peers, assistant_peer): + """Create a session with multiple users and an assistant""" + group_session = honcho.session("group-discussion") + + # Add all peers to the session + all_peers = user_peers + [assistant_peer] + group_session.add_peers(all_peers) + + return group_session + +# Create multiple user peers +bob = honcho.peer("user-bob") +charlie = honcho.peer("user-charlie") + +# Create group session +group_session = create_group_session([alice, bob, charlie], assistant) + +# Add group conversation +group_session.add_messages([ + alice.message("I think we should use Python for the backend"), + bob.message("I prefer TypeScript, it's more type-safe"), + charlie.message("What about performance considerations?"), + assistant.message("Both are good choices. Let me help you compare them based on your requirements.") +]) + +# Query different perspectives +alice_view = assistant.chat( + "What does alice think about the technology discussion?", + target=alice, + session_id=group_session.id +) +print(f"Alice's perspective: {alice_view}") +``` + +## Part 8: Advanced Features + +### Direct Knowledge Queries + +```python +# Instead of complex manual context building, use peer.chat() directly +response = assistant.chat("What programming languages does alice prefer and why?", target=alice) +print(f"Alice's language preferences: {response}") + +# Query session-specific knowledge +session_insights = assistant.chat( + "What was the main topic of discussion in this session?", + session_id=session.id +) +print(f"Session insights: {session_insights}") +``` + +### Alternative LLM Formats + +```python +# Honcho supports multiple LLM formats out of the box +def use_anthropic_format(session, assistant_peer, user_message): + """Example using Anthropic's message format""" + context = session.get_context(tokens=1500) + messages = context.to_anthropic(assistant=assistant_peer) + + # Now you can use these messages with Anthropic's API + # anthropic_response = anthropic.messages.create(...) + + return messages + +# Get Anthropic-formatted messages +anthropic_messages = use_anthropic_format(session, assistant, "Hello!") +print(f"Formatted for Anthropic: {len(anthropic_messages)} messages") +``` + +## Next Steps + +Congratulations! You've built a complete personal AI assistant with Honcho that automatically handles memory, context, and LLM integration. Here are some ideas to extend it further: + +1. **Web Interface**: Build a web UI using Flask/FastAPI - the SDK makes it easy to integrate +2. **Streaming Responses**: Use `peer.chat(..., stream=True)` for real-time conversations +3. **Multi-Modal Support**: Integrate with vision models while leveraging Honcho's memory +4. **Advanced Theory-of-Mind**: Explore peer modeling with `observe_others=False` configurations +5. **Production Deployment**: Scale with workspaces, metadata, and batch operations + +## Troubleshooting + +### Common Issues + +**"No module named 'honcho'"** +- Make sure you installed the package: `pip install honcho-ai` + +**API authentication errors** +- Check your `HONCHO_API_KEY` environment variable +- Verify your API key is valid + +**Empty context or knowledge queries** +- Ensure you've added messages to peers before querying +- Check that peers are added to sessions before conversation +- Verify session has messages before getting context + +**Rate limiting or timeout issues** +- The SDK handles retries automatically +- Consider adding delays between large batch operations + +## Resources + +- [SDK Reference](/v2/documentation/reference/sdk) +- [API Reference](/v2/api-reference/introduction) +- [More Examples](/v2/guides/overview) +- [Discord Community](http://discord.gg/plasticlabs) diff --git a/docs/v2/documentation/reference/sdk.mdx b/docs/v2/documentation/reference/sdk.mdx index 038e3cbc..87c574e4 100644 --- a/docs/v2/documentation/reference/sdk.mdx +++ b/docs/v2/documentation/reference/sdk.mdx @@ -435,95 +435,6 @@ const bobSearch = await bobObs.query("work history"); ``` -### 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"); -``` - - #### Creating Observations Manually You can also create observations directly, which is useful for importing data or adding explicit facts: diff --git a/docs/v2/guides/discord.mdx b/docs/v2/guides/discord.mdx index 5b24dca8..a87826ac 100644 --- a/docs/v2/guides/discord.mdx +++ b/docs/v2/guides/discord.mdx @@ -193,14 +193,14 @@ After generating the response, we save both the user's input and the bot's respo ## Slash Commands -Discord bots also offer slash command functionality. Here's an example using Honcho's chat endpoint feature: +Discord bots also offer slash command functionality. Here's an example using Honcho's dialectic feature: ```python @bot.slash_command( - name="chat", - description="Query the peer's representation in natural language.", + name="dialectic", + description="Query the Honcho Dialectic endpoint.", ) -async def chat(ctx, query: str): +async def dialectic(ctx, query: str): await ctx.defer() try: @@ -225,7 +225,7 @@ async def chat(ctx, query: str): ) ``` -This slash command uses Honcho's chat endpoint functionality to answer questions about the user based on their conversation history. +This slash command uses Honcho's dialectic functionality to answer questions about the user based on their conversation history. ## Setup and Configuration @@ -248,7 +248,7 @@ The new Honcho peer/session API makes Discord bot integration much simpler and m - **Peer/Session Model**: Users are represented as peers, conversations as sessions - **Automatic Context Management**: `session.get_context().to_openai()` automatically formats chat history - **Message Storage**: `session.add_messages()` stores both user and assistant messages -- **Representation Queries**: `peer.chat()` enables querying conversation history +- **Dialectic Queries**: `peer.chat()` enables querying conversation history - **Helper Functions**: Clean code organization with focused helper functions This approach provides a clean, maintainable structure for building Discord bots with conversational memory and context management. diff --git a/docs/v2/guides/overview.mdx b/docs/v2/guides/overview.mdx index bfd96981..cdd4dbbd 100644 --- a/docs/v2/guides/overview.mdx +++ b/docs/v2/guides/overview.mdx @@ -1,15 +1,17 @@ --- -title: "Guides, Cookbooks, and Integrations" +title: "Spellbooks and Tutorials" sidebarTitle: 'Overview' description: 'Helpful guides and design patterns for building with Honcho' icon: 'hat-wizard' --- - Before you start a guide, follow [Quickstart](/v2/documentation/introduction/quickstart) to get up and running with Honcho in your language of choice. + Before you start a tutorial, follow [Quickstart](/v2/documentation/introduction/quickstart) to get up and running with Honcho in your language of choice. -These guides provide concrete examples and implementation patterns for building with Honcho. Whether you're integrating Honcho into existing platforms, exploring advanced features, or getting up and running quickly, you'll find working code you can adapt to your needs. +AI development often feels like magic - you craft the right prompt and get exactly what you need. Our Spellbooks are practical guides that show you how to cast effective spells with Honcho. -Each guide focuses on a specific use case with practical examples. The goal is to get you from idea to working prototype as quickly as possible, then provide the depth you need to scale and customize. +Whether you're integrating Honcho into existing platforms, exploring advanced features, or getting up and running quickly, these guides provide concrete examples and implementation patterns. + +Each spellbook focuses on a specific use case with working code you can adapt to your needs. The goal is to get you from idea to working prototype as quickly as possible, then provide the depth you need to scale and customize. ## Getting Started diff --git a/docs/v2/integrations/crewai.mdx b/docs/v2/integrations/crewai.mdx new file mode 100644 index 00000000..6d39d983 --- /dev/null +++ b/docs/v2/integrations/crewai.mdx @@ -0,0 +1,294 @@ +--- +title: "CrewAI" +icon: 'users-gear' +description: "Build AI agents with persistent memory using CrewAI and Honcho" +sidebarTitle: 'CrewAI' +--- + +Integrate Honcho with CrewAI to build AI agents that maintain memory across sessions. This guide shows you how to use Honcho's memory layer with CrewAI's agent orchestration framework. + + +The full code is available on [GitHub](https://github.com/plastic-labs/honcho/tree/main/examples/crewai) with examples in [Python](https://github.com/plastic-labs/honcho/tree/main/examples/crewai/python/examples) + + +## What We're Building + +We'll create AI agents that remember and reason over past conversations. Here's how the pieces fit together: + +- **CrewAI** orchestrates agent behavior and task execution +- **Honcho** stores messages and retrieves relevant context + +The key benefit: CrewAI automatically retrieves relevant conversation history from Honcho without you needing to manually manage context, token limits, or message formatting. + + +This tutorial demonstrates single-agent setup to show how Honcho integrates with CrewAI. For production applications, you can extend this to multi-agent crews with shared or individual memory using Honcho's `peer` system. + + +## Setup + +Install required packages: + + +```bash Python (uv) +uv add honcho-crewai crewai python-dotenv +``` + +```bash Python (pip) +pip install honcho-crewai crewai python-dotenv +``` + + +Use any LLM provider for your Crew. Create a `.env` file with your API keys: + +```bash +OPENAI_API_KEY=your_openai_key +``` + + +This tutorial uses the Honcho demo server at https://demo.honcho.dev which runs a small instance of Honcho on the latest version. For production, get your Honcho API key at [app.honcho.dev](https://app.honcho.dev). For local development, use `environment="local"`. + + +## CrewAI Honcho Storage + +The `honcho_crewai` package provides `HonchoStorage`, a storage provider that implements CrewAI's `Storage` interface using Honcho's session-based memory. + + +Before proceeding, it's important to understand Honcho's core concepts (`Peers` and `Sessions`). Review the [Honcho Architecture](/v2/documentation/core-concepts/architecture) to familiarize yourself with these primitives. + + +`HonchoStorage` implements CrewAI's `Storage` interface using Honcho's `peer` and `session` primitives. + +```python +storage = HonchoStorage( + user_id="demo-user", # Required: Honcho `peer` ID for the user + session_id=None, # Optional: Specific `session` ID (auto-generated UUID if None) + honcho_client=None, # Optional: Pre-configured Honcho client instance +) +``` + +The `HonchoStorage` class implements three key methods: + +- **`save()`** - Stores messages in Honcho's `session`, associating them with the appropriate `peer` (user or assistant) +- **`search()`** - Performs semantic vector search using `session.search()` to find messages most relevant to the query. Supports optional `filters` parameter for fine-grained scoping. +- **`reset()`** - Creates a new `session` to start fresh conversations + +CrewAI automatically calls these methods when agents need to store or retrieve memory, creating a seamless integration. + +### Search with Filters + +The `search()` method supports an optional `filters` parameter for fine-grained scoping of search results: + +```python +# Search with peer_id filter (only messages from a specific peer) +results = storage.search("query", filters={"peer_id": "user123"}) + +# Search with metadata filter +results = storage.search("query", filters={"metadata": {"priority": "high"}}) + +# Search with time range filter +results = storage.search("query", filters={"created_at": {"gte": "2024-01-01"}}) + +# Complex filter with logical operators +results = storage.search("query", filters={ + "AND": [ + {"peer_id": "user123"}, + {"metadata": {"topic": "python"}} + ] +}) +``` + +For the full filter syntax including logical operators (AND, OR, NOT), comparison operators, and metadata filtering, see the [Using Filters](https://docs.honcho.dev/v2/documentation/core-concepts/features/using-filters) documentation. + + +For comprehensive details about CrewAI's memory system, see the [official CrewAI Memory documentation](https://docs.crewai.com/en/concepts/memory). + + +Let's create a basic example showing how CrewAI agents use Honcho's memory automatically: + +```python Python +from dotenv import load_dotenv +from crewai import Agent, Task, Crew, Process +from crewai.memory.external.external_memory import ExternalMemory +from honcho_crewai import HonchoStorage + +load_dotenv() + +storage = HonchoStorage(user_id="simple-demo-user") +external_memory = ExternalMemory(storage=storage) + +messages = [ + ("user", "I'm learning Python programming"), + ("assistant", "Great! Python is an excellent language to learn."), + ("user", "I'm particularly interested in web development"), +] + +for role, message in messages: + external_memory.save(message, metadata={"agent": role}) + +agent = Agent( + role="Programming Mentor", + goal="Help users learn programming by remembering their interests and progress", + backstory=( + "You are a patient programming mentor who remembers what students " + "have told you about their learning journey and interests." + ), + verbose=True, + allow_delegation=False +) + +task = Task( + description=( + "Based on what you know about the user's interests, " + "suggest a simple web development project they could build to practice Python." + ), + expected_output="A specific project suggestion with brief explanation", + agent=agent +) + +crew = Crew( + agents=[agent], + tasks=[task], + process=Process.sequential, + external_memory=external_memory, + verbose=True +) + +result = crew.kickoff() +print(result.raw) +``` + +## CrewAI Tool Integration + +Honcho provides specialized tools that give CrewAI agents explicit control over memory retrieval: + +- **`HonchoGetContextTool`** - Retrieves comprehensive conversation history with token limits. Use for tasks needing broad conversation understanding. +- **`HonchoDialecticTool`** - Queries representations about `peer`s. Use for understanding user preferences and characteristics without full message history. +- **`HonchoSearchTool`** - Performs semantic search for specific information. Supports optional `filters` parameter for fine-grained scoping. Use for targeted queries like "what did the user say about budget?" + + +Agents can use multiple tools in sequence: search for topics, query dialectic for preferences, then get full context for generation. + + +Here's an example demonstrating all three tools: + +```python Python +from dotenv import load_dotenv +from crewai import Agent, Task, Crew, Process +from honcho import Honcho +from honcho_crewai import ( + HonchoGetContextTool, + HonchoDialecticTool, + HonchoSearchTool, +) + +load_dotenv() + +honcho = Honcho() +user_id = "demo-user-45" +session_id = "tools-demo-session" + +user = honcho.peer(user_id) +session = honcho.session(session_id) + +messages = [ + "I'm planning a trip to Japan in March", + "I love trying authentic local cuisine, especially ramen and sushi", + "My budget is around $3000 for a 10-day trip", + "I'm interested in visiting both Tokyo and Kyoto", + "I prefer staying in traditional ryokans over hotels", +] + +for msg in messages: + session.add_messages([user.message(msg)]) + +context_tool = HonchoGetContextTool( + honcho=honcho, session_id=session_id, peer_id=user_id +) + +dialectic_tool = HonchoDialecticTool( + honcho=honcho, session_id=session_id, peer_id=user_id +) + +search_tool = HonchoSearchTool(honcho=honcho, session_id=session_id) + +# Note: The search tool supports optional filters for fine-grained scoping +# Agents can use filters like {"peer_id": "user123"} or {"metadata": {"priority": "high"}} + +travel_agent = Agent( + role="Travel Planning Specialist", + goal="Create personalized travel recommendations using memory tools", + backstory=( + "You are an expert travel planner with access to conversation memory tools. " + "Use the tools to understand the user's preferences before making recommendations." + ), + tools=[context_tool, dialectic_tool, search_tool], + verbose=True, + allow_delegation=False +) + +task = Task( + description=( + "Create a personalized 3-day Tokyo itinerary. " + "Use the memory tools to understand:\n" + " • Food preferences (use search_tool for 'cuisine' or 'food')\n" + " • Travel style and budget (use dialectic_tool to query user knowledge)\n" + " • Recent context (use context_tool to get conversation history)\n" + "Then create a detailed plan matching their interests." + ), + expected_output=( + "A 3-day Tokyo itinerary with:\n" + " • Daily activities matching user interests\n" + " • Restaurant recommendations\n" + " • Accommodation suggestions\n" + " • Budget considerations" + ), + agent=travel_agent +) + +crew = Crew( + agents=[travel_agent], + tasks=[task], + process=Process.sequential, + verbose=True +) + +crew.kickoff() +``` + +## Tool-Based vs Automatic Memory + +**Use `HonchoStorage`** for automatic memory - CrewAI handles everything transparently. Best for simple conversational flows. + +**Use Honcho Tools** for strategic control - agents decide when and how to query memory. Best for multi-step reasoning, when different query types are needed, or multi-agent systems. + +You can combine both: automatic memory for baseline context, tools for specific queries. See the [hybrid memory example](https://github.com/plastic-labs/honcho/blob/main/examples/crewai/python/examples/hybrid_memory_example.py) for a complete implementation. + + +**Multi-Agent Memory:** Use Honcho tools with different `peer_id` values to give each agent distinct memory and identity. + + +## Next Steps + +Now that you have a working CrewAI integration with Honcho, you can: + +- **Create specialized agents** with domain-specific memory and context +- **Use CrewAI's advanced features** like hierarchical processes, tool delegation, and conditional task execution +- **Leverage logical reasoning** via the Dialectic API for deep `peer` understanding +- **Implement custom tools** to give agents explicit control over memory retrieval + +## Related Resources + + + + Understand Honcho's peer-based model and core primitives + + + Learn about retrieving and formatting conversation context + + + Query `peer` representations for deeper understanding + + + Build stateful agents with LangGraph and Honcho + + diff --git a/docs/v2/integrations/langgraph.mdx b/docs/v2/integrations/langgraph.mdx new file mode 100644 index 00000000..26af8c17 --- /dev/null +++ b/docs/v2/integrations/langgraph.mdx @@ -0,0 +1,363 @@ +--- +title: "LangGraph" +icon: 'diagram-project' +description: "Build a stateful conversational AI agent with LangGraph and Honcho" +sidebarTitle: 'LangGraph' +--- + +Integrate Honcho with LangGraph to build a conversational AI agent that maintains memory across sessions. This guide shows you how to use Honcho's memory layer with LangGraph's orchestration. + + +The full code is available on [GitHub](https://github.com/plastic-labs/honcho/tree/main/examples/langgraph) with examples in both [Python](https://github.com/plastic-labs/honcho/blob/main/examples/langgraph/python/main.py) and [TypeScript](https://github.com/plastic-labs/honcho/blob/main/examples/langgraph/typescript/main.ts) + + +## What We're Building + +We'll create a conversational agent that remembers and reasons over past exchanges with the user. Here's how the pieces fit together: + +- **LangGraph** orchestrates the conversation flow +- **Honcho** stores messages and retrieves relevant context +- **Your LLM** generates responses using Honcho's formatted context + +The key benefit: You don't manually manage conversation history, token limits, or message formatting. Honcho handles memory so you can focus on your agent's logic. + + +This tutorial demonstrates a simple linear conversation flow to show +how Honcho integrates with LangGraph. For production applications, +you'll likely want to add LangGraph features like conditional routing, +tool calling, and multi-agent orchestration. + + +## Setup + +Install required packages: + + +```bash Python (uv) +uv add honcho-ai langgraph langchain-core openai python-dotenv +``` + +```bash Python (pip) +pip install honcho-ai langgraph langchain-core openai python-dotenv +``` + +```bash TypeScript (npm) +npm install @honcho-ai/sdk @langchain/langgraph openai dotenv +``` + +```bash TypeScript (yarn) +yarn add @honcho-ai/sdk @langchain/langgraph openai dotenv +``` + +```bash TypeScript (pnpm) +pnpm add @honcho-ai/sdk @langchain/langgraph openai dotenv +``` + + +This tutorial uses OpenAI, but Honcho works with any LLM provider. Create a `.env` file with your API keys: + +```bash +OPENAI_API_KEY=your_openai_key +``` + + +This tutorial uses the Honcho demo server at https://demo.honcho.dev which runs a small instance of Honcho on the latest version. For production, get your Honcho API key at [app.honcho.dev](https://app.honcho.dev). For local development, use `environment="local"`. + + +## Initialize Clients + + +```python Python +import os +from dotenv import load_dotenv +from typing_extensions import TypedDict +from honcho import Honcho, Peer, Session +from openai import OpenAI +from langgraph.graph import StateGraph, START, END + +load_dotenv() + +# Initialize Honcho +honcho = Honcho() + +# Initialize OpenAI +llm = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) +``` + +```typescript TypeScript +import * as dotenv from "dotenv"; +import { Honcho, Peer, Session } from "@honcho-ai/sdk"; +import OpenAI from "openai"; +import { Annotation } from "@langchain/langgraph"; +import { StateGraph, START, END } from "@langchain/langgraph"; +import * as readline from "readline/promises"; + +dotenv.config(); + +// Initialize Honcho +const honcho = new Honcho({}); + +// Initialize OpenAI +const llm = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY +}); +``` + + +## Define LangGraph State + +Define your state schema to pass data through the graph. The state stores Honcho objects directly along with the current user message and assistant response. + + +Before proceeding, it's important to understand Honcho's core concepts (`Peers` and `Sessions`). Review the [Honcho Architecture](/v2/documentation/core-concepts/architecture) to familiarize yourself with these primitives. + + + +```python Python +class State(TypedDict): + user_message: str + assistant_response: str + user: Peer + assistant: Peer + session: Session +``` + +```typescript TypeScript +const StateAnnotation = Annotation.Root({ + userMessage: Annotation(), + assistantResponse: Annotation(), + user: Annotation(), + assistant: Annotation(), + session: Annotation(), +}); + +type State = typeof StateAnnotation.State; +``` + + +## Build the LangGraph + +Define your chatbot logic, using Honcho to retrieve conversation context. This function demonstrates how Honcho can store messages, retrieve context, and generate responses. + + +```python Python +def chatbot(state: State): + user_message = state["user_message"] + + # Get objects from state + user = state["user"] + assistant = state["assistant"] + session = state["session"] + + # Step 1: Store the user's message in the session + # This adds it to Honcho's memory for future context retrieval + session.add_messages([user.message(user_message)]) + + # Step 2: Get context in OpenAI format with token limit + # get_context() retrieves relevant conversation history + # tokens=2000 limits the context to 2000 tokens to manage costs and fit within model limits + # to_openai() converts it to the format expected by OpenAI's API + messages = session.get_context(tokens=2000).to_openai(assistant=assistant) + + # Step 3: Generate response using the context + response = llm.chat.completions.create( + model="gpt-5.1", + messages=messages + ) + assistant_response = response.choices[0].message.content + + # Step 4: Store assistant response in Honcho for future context + session.add_messages([assistant.message(assistant_response)]) + + return {"assistant_response": assistant_response} +``` + +```typescript TypeScript +async function chatbot(state: State) { + const userMessage = state.userMessage; + + // Get objects from state + const user = state.user; + const assistant = state.assistant; + const session = state.session; + + // Step 1: Store the user's message in the session + // This adds it to Honcho's memory for future context retrieval + await session.addMessages([user.message(userMessage)]); + + // Step 2: Get context in OpenAI format with token limit + // getContext() retrieves relevant conversation history + // tokens: 2000 limits the context to 2000 tokens to manage costs and fit within model limits + // toOpenAI() converts it to the format expected by OpenAI's API + const messages = (await session.getContext({ tokens: 2000 })).toOpenAI(assistant); + + // Step 3: Generate response using the context + const response = await llm.chat.completions.create({ + model: "gpt-5.1", + messages: messages + }); + const assistantResponse = response.choices[0].message.content!; + + // Step 4: Store assistant response for future context + await session.addMessages([assistant.message(assistantResponse)]); + + return { assistantResponse: assistantResponse }; +} +``` + + +Now let's build the LangGraph: + +```python Python +graph = StateGraph(State) \ + .add_node("chatbot", chatbot) \ + .add_edge(START, "chatbot") \ + .add_edge("chatbot", END) \ + .compile() +``` + +```typescript TypeScript +const graph = new StateGraph(StateAnnotation) + .addNode("chatbot", chatbot) + .addEdge(START, "chatbot") + .addEdge("chatbot", END) + .compile(); +``` + + +### Understanding get_context() + +The [`get_context()`](/v2/documentation/core-concepts/features/get-context) method retrieves comprehensive conversation context and formats it for your LLM. It automatically: + +- **Manages conversation history** - Tracks all messages and determines what's relevant +- **Respects token limits** - Stays within context window constraints without manual counting +- **Handles long conversations** - Combines recent detailed messages with summaries of older exchanges +- **Provides `peer` understanding** - Includes representations and `peer` cards when requested + +The `SessionContext` object always includes fields for messages, summaries, `peer` representations, and `peer` cards. By default, only `messages` and `summary` are populated. To populate peer-specific context, pass a `peer_target` parameter: + +**Using `peer_target` for Context:** + +- **Without `peer_perspective`**: Returns Honcho's omniscient view of `peer_target` (all observations and context) +- **With `peer_perspective`**: Returns what `peer_perspective` knows about `peer_target` (perspective-based observations and context) + +That's it. Call `session.get_context().to_openai(assistant)` and you get properly formatted context tailored for your assistant. + + +**Adding System Prompts:** Since `get_context()` returns conversation messages, you can easily prepend custom system instructions. Just add your system prompt to the beginning of the messages array before sending it to your LLM: `[{"role": "system", "content": "..."}, ...context_messages]`. + + + +For more details on all available parameters, see [`get_context() documentation`](/v2/documentation/core-concepts/features/get-context) + + +## Chat Loop + +Now we'll create the main conversation function. To simplify logic, we initialize Honcho objects once per conversation and pass them through the LangGraph state. + +The `run_conversation_turn` function initializes a Honcho `Session` and `Peer` objects, passes them to the LangGraph, and returns the assistant's response. By calling it repeatedly with the same `user_id` and in the same session, the chat builds context over time. + + +**Production Usage:** Honcho accepts any nanoid-compatible string for `user_id` and `session_id`. You can use IDs directly from your authentication system (Auth0, Firebase, Clerk, etc.) and session management without modification. + +This tutorial uses hardcoded values for simplicity. + + + +```python Python +def run_conversation_turn(user_id: str, user_input: str, session_id: str | None = None): + if not session_id: + session_id = f"session_{user_id}" + + # Initialize Honcho objects + user = honcho.peer(user_id) + assistant = honcho.peer("assistant") + session = honcho.session(session_id) + + result = graph.invoke({ + "user_message": user_input, + "user": user, + "assistant": assistant, + "session": session + }) + + return result["assistant_response"] + +if __name__ == "__main__": + print("Welcome to the AI Assistant! How can I help you today?") + user_id = "test-user-123" + while True: + user_input = input("You: ") + if user_input.lower() in ['quit', 'exit']: + break + response = run_conversation_turn(user_id, user_input) + print(f"Assistant: {response}\n") +``` + +```typescript TypeScript +async function runConversationTurn( + userId: string, + userInput: string, + sessionId?: string +): Promise { + if (!sessionId) { + sessionId = `session_${userId}`; + } + + // Initialize Honcho objects + const user = await honcho.peer(userId); + const assistant = await honcho.peer("assistant"); + const session = await honcho.session(sessionId); + + const result = await graph.invoke({ + userMessage: userInput, + user: user, + assistant: assistant, + session: session, + }); + + return result.assistantResponse; +} + +// Interactive chat loop +async function main() { + console.log("Welcome to the AI Assistant! How can I help you today?"); + const userId = "test-user-123"; + + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + + while (true) { + const userInput = await rl.question("You: "); + if (userInput.toLowerCase() === "quit" || userInput.toLowerCase() === "exit") { + rl.close(); + break; + } + const response = await runConversationTurn(userId, userInput); + console.log(`Assistant: ${response}\n`); + } +} + +main(); +``` + + +## Next Steps + +Now that you have a working LangGraph integration with Honcho, you can: + +- **Create custom [LangChain tools](https://docs.langchain.com/oss/python/langchain/tools#customize-tool-properties) for your agent** - to fully utilize Honcho's memory & context management features +- **Build a multi-agent LangGraph** where each agent is a Honcho `Peer` with its own memory + +## Related Resources + + + + Learn more about retrieving and formatting conversation context + + + Use Honcho in Claude Desktop with MCP + + diff --git a/docs/v2/integrations/mcp.mdx b/docs/v2/integrations/mcp.mdx new file mode 100644 index 00000000..9c828580 --- /dev/null +++ b/docs/v2/integrations/mcp.mdx @@ -0,0 +1,73 @@ +--- +title: "Model Context Protocol (MCP)" +icon: 'star-of-life' +description: "Use Honcho in Claude Desktop" +sidebarTitle: 'MCP' +--- + +You can let Claude use Honcho to manage its own memory in the native desktop app by using the Honcho MCP integration! Follow these steps: + +1. Go to https://app.honcho.dev and get an API key. Then go to Claude Desktop and navigate to custom MCP servers. + + +If you don't have node installed you will need to do that. Claude Desktop or Claude Code can help! + + +2. Add Honcho to your Claude desktop config. You must provide a username for Honcho to refer to you as -- preferably what you want Claude to actually call you. +```json +{ + "mcpServers": { + "honcho": { + "command": "npx", + "args": [ + "mcp-remote", + "https://mcp.honcho.dev", + "--header", + "Authorization:${AUTH_HEADER}", + "--header", + "X-Honcho-User-Name:${USER_NAME}" + ], + "env": { + "AUTH_HEADER": "Bearer ", + "USER_NAME": "" + } + } + } +} +``` + +You may customize your assistant name and/or workspace ID. Both are optional. + +```json +{ + "mcpServers": { + "honcho": { + "command": "npx", + "args": [ + "mcp-remote", + "https://mcp.honcho.dev", + "--header", + "Authorization:${AUTH_HEADER}", + "--header", + "X-Honcho-User-Name:${USER_NAME}", + "--header", + "X-Honcho-Assistant-Name:${ASSISTANT_NAME}", + "--header", + "X-Honcho-Workspace-ID:${WORKSPACE_ID}" + ], + "env": { + "AUTH_HEADER": "Bearer ", + "USER_NAME": "", + "ASSISTANT_NAME": "", + "WORKSPACE_ID": "" + } + } + } +} +``` + +3. Restart the Claude Desktop app. Upon relaunch, it should start Honcho and the tools should be available! + +4. Finally, Claude needs instructions on how to use Honcho. The Desktop app doesn't allow you to add system prompts directly, but you can create a project and paste these [instructions](https://raw.githubusercontent.com/plastic-labs/honcho/refs/heads/main/mcp/instructions.md) into the "Project Instructions" field. + +Claude should then query for insights before responding and write your messages to storage! If you come up with more creative ways to get Claude to manage its own memory with Honcho, feel free to [let us know](https://discord.gg/plasticlabs) or make a PR on this [repo](https://github.com/plastic-labs/honcho/tree/main/mcp)!