Adding crewAI integration guide (#279)
* docs: adding crewAI integration guide * docs: adding a honcho_crewai package * docs: Using session.search and session summaries to enhance the honcho storage class * docs: updating to use honcho_crewai package * docs: Added honcho_crewAI tools. Updated honcho_crewai tests to better match the specific integration. Built out the package definition more. * docs: Adding all the honcho sdk parameters to crewAI tools, also adding tools and a simple example. * docs: adding logging to HonchoStorage class * docs: updating mdx file to match examples and fixing explanations * Docs: removing session summaries from search * docs: adding files package * docs: simplifying language specifically for theory-of-mind. * chore: code rabbit suggestions. * chore: code rabbit * fix: removing nanoid crewai dependency * docs: adding filtering capability to honcho crewai package and tool examples. * fix: remove factory class in favor of direct class instantiation * docs: adding hybrid memory example * fix: fixing redundent calls to honcho for saving message history * chore: code rabbit fixes
This commit is contained in:
parent
093444c38c
commit
34957d7885
18
CLAUDE.md
18
CLAUDE.md
|
|
@ -6,7 +6,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||
|
||||
## What is Honcho?
|
||||
|
||||
Honcho is an infrastructure layer for building AI agents with social cognition and theory of mind capabilities. Its primary purposes include:
|
||||
Honcho is an infrastructure layer for building AI agents with memory and social cognition. Its primary purposes include:
|
||||
|
||||
- Imbuing agents with a sense of identity
|
||||
- Personalizing user experiences through understanding user psychology
|
||||
|
|
@ -14,7 +14,7 @@ Honcho is an infrastructure layer for building AI agents with social cognition a
|
|||
- Supporting development of LLM-powered applications that adapt to end users
|
||||
- Enabling multi-peer sessions where multiple participants (users or agents) can interact
|
||||
|
||||
Honcho leverages the inherent theory-of-mind capabilities of LLMs to build coherent models of user psychology over time, enabling more personalized and effective AI interactions.
|
||||
Honcho leverages the inherent reasoning capabilities of LLMs to build coherent models of user psychology over time, enabling more personalized and effective AI interactions.
|
||||
|
||||
## Core Concepts
|
||||
|
||||
|
|
@ -32,7 +32,7 @@ Honcho uses a peer-based model where both users and agents are represented as "p
|
|||
- **Peer** (formerly User): Any participant in the system (human or AI)
|
||||
- **Session**: A conversation context that can involve multiple peers
|
||||
- **Message**: Data units that can represent communication between peers OR arbitrary data ingested by a peer to enhance its global representation
|
||||
- **Collections & Documents**: Internal vector storage for theory-of-mind representations (not exposed via API)
|
||||
- **Collections & Documents**: Internal vector storage for peer representations (not exposed via API)
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
|
|
@ -50,7 +50,7 @@ All API routes follow the pattern: `/v1/{resource}/{id}/{action}`
|
|||
|
||||
#### Dialectic API (`/peers/{peer_id}/chat`)
|
||||
|
||||
- Provides theory-of-mind informed responses
|
||||
- Provides bespoke responses informed by the representation
|
||||
- Integrates long-term facts from vector storage
|
||||
- Supports streaming responses
|
||||
- Configurable LLM providers
|
||||
|
|
@ -59,18 +59,11 @@ All API routes follow the pattern: `/v1/{resource}/{id}/{action}`
|
|||
|
||||
1. Messages created via API (batch or single)
|
||||
2. Enqueued for background processing:
|
||||
- `representation`: Update peer's theory of mind
|
||||
- `representation`: Update peer's context
|
||||
- `summary`: Create session summaries
|
||||
3. Session-based queue processing ensures order
|
||||
4. Results stored internally in vector DB
|
||||
|
||||
#### Theory of Mind System
|
||||
|
||||
- Multiple implementation methods (conversational, single_prompt, long_term)
|
||||
- Facts extracted from messages and stored in collections
|
||||
- Representations combine short-term inference with long-term facts
|
||||
- Configurable via peer and session feature flags
|
||||
|
||||
### Configuration
|
||||
|
||||
- Hierarchical config: config.toml + environment variables
|
||||
|
|
@ -179,7 +172,6 @@ src/
|
|||
### Key Architectural Decisions
|
||||
|
||||
1. **Multi-Peer Sessions**: Sessions can have multiple participants with different observation settings
|
||||
2. **Flexible Theory of Mind**: Pluggable ToM implementations (conversational, single_prompt, long_term)
|
||||
3. **Background Processing**: Async queue system for expensive operations
|
||||
4. **Provider Abstraction**: Model client supports multiple LLM providers
|
||||
5. **Scoped Authentication**: JWTs can be scoped to workspace, peer, or session level
|
||||
|
|
|
|||
15
README.md
15
README.md
|
|
@ -429,7 +429,7 @@ Then modify the values as needed. The TOML file is organized into sections:
|
|||
- `[cache]` - Redis cache configuration
|
||||
- `[llm]` - LLM provider API keys and general settings
|
||||
- `[dialectic]` - Dialectic API configuration (provider, model, search settings)
|
||||
- `[deriver]` - Background worker settings and theory of mind configuration
|
||||
- `[deriver]` - Background worker settings and representation configuration
|
||||
- `[peer_card]` - Peer card generation settings
|
||||
- `[summary]` - Session summarization settings
|
||||
- `[dream]` - Dream processing configuration
|
||||
|
|
@ -501,8 +501,8 @@ Honcho uses a peer-based model where both users and agents are represented as "p
|
|||
|
||||
#### Key Features
|
||||
|
||||
- **Theory-of-Mind System**: Multiple implementation methods that extract facts from interactions and build comprehensive models of peer psychology
|
||||
- **Dialectic API**: Provides theory-of-mind informed responses that integrate long-term facts with current context
|
||||
- **Rich Reasoning System**: Multiple implementation methods that extract facts from interactions and build comprehensive models of peer psychology
|
||||
- **Dialectic API**: Provides reasoned informed responses that integrate long-term facts with current context
|
||||
- **Background Processing**: Asynchronous processing pipeline for expensive operations like representation updates and session summarization
|
||||
- **Multi-Provider Support**: Configurable LLM providers for different use cases
|
||||
|
||||
|
|
@ -567,7 +567,7 @@ The `Message` represents an atomic data unit that can exist at two levels:
|
|||
- **Session-level Messages**: Communication between peers within a session context
|
||||
|
||||
All messages are labeled by their source peer and can be processed
|
||||
asynchronously to update theory-of-mind models. This flexible design allows for
|
||||
asynchronously to update their representations. This flexible design allows for
|
||||
both conversational interactions and broader data ingestion for personality
|
||||
modeling.
|
||||
|
||||
|
|
@ -578,8 +578,7 @@ familiar with RAG based applications will be familiar with these. `Collections`
|
|||
store vector embedded data that developers and agents can retrieve against using
|
||||
functions like cosine similarity.
|
||||
|
||||
Collections are also used internally by Honcho while creating theory-of-mind
|
||||
representations of peers.
|
||||
Collections are also used internally by Honcho while creating representations of peers.
|
||||
|
||||
#### Documents
|
||||
|
||||
|
|
@ -596,7 +595,7 @@ A high level summary of the pipeline is as follows:
|
|||
|
||||
1. Messages are created via the API
|
||||
2. Derivation Tasks are enqueued for background processing including:
|
||||
- `representation`: To update theory-of-mind representations of `Peers`
|
||||
- `representation`: To update representations of `Peers`
|
||||
- `summary`: To create summaries of `Sessions`
|
||||
3. Session-based queue processing ensures proper ordering
|
||||
4. Results are stored internally
|
||||
|
|
@ -638,7 +637,7 @@ A developer's application can treat Honcho as an oracle to the `Peer` and
|
|||
consult it when necessary. Some examples of how to leverage the Dialectic
|
||||
API include:
|
||||
|
||||
- Asking Honcho for a theory-of-mind insight about the `Peer`
|
||||
- Asking Honcho for a generic or specific insight about the `Peer`
|
||||
- Asking Honcho to hydrate a prompt with data about the `Peer`s behavior
|
||||
- Asking Honcho for a 2nd opinion or approach about how to respond to the Peer
|
||||
- Getting personalized responses that incorporate long-term facts and context
|
||||
|
|
|
|||
|
|
@ -74,10 +74,7 @@
|
|||
},
|
||||
{
|
||||
"group": "Integrations",
|
||||
"pages": [
|
||||
"v2/integrations/langgraph",
|
||||
"v2/integrations/mcp"
|
||||
]
|
||||
"pages": ["v2/integrations/crewai", "v2/integrations/langgraph", "v2/integrations/mcp"]
|
||||
},
|
||||
{
|
||||
"group": "Application Interfaces",
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
||||
<Note>
|
||||
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)
|
||||
</Note>
|
||||
|
||||
## 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.
|
||||
|
||||
<Note>
|
||||
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.
|
||||
</Note>
|
||||
|
||||
## Setup
|
||||
|
||||
Install required packages:
|
||||
|
||||
<CodeGroup>
|
||||
```bash Python (uv)
|
||||
uv add honcho-crewai crewai python-dotenv
|
||||
```
|
||||
|
||||
```bash Python (pip)
|
||||
pip install honcho-crewai crewai python-dotenv
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Use any LLM provider for your Crew. Create a `.env` file with your API keys:
|
||||
|
||||
```bash
|
||||
OPENAI_API_KEY=your_openai_key
|
||||
```
|
||||
|
||||
<Note>
|
||||
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"`.
|
||||
</Note>
|
||||
|
||||
## CrewAI Honcho Storage
|
||||
|
||||
The `honcho_crewai` package provides `HonchoStorage`, a storage provider that implements CrewAI's `Storage` interface using Honcho's session-based memory.
|
||||
|
||||
<Note>
|
||||
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.
|
||||
</Note>
|
||||
|
||||
`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.
|
||||
|
||||
<Note>
|
||||
For comprehensive details about CrewAI's memory system, see the [official CrewAI Memory documentation](https://docs.crewai.com/en/concepts/memory).
|
||||
</Note>
|
||||
|
||||
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?"
|
||||
|
||||
<Tip>
|
||||
Agents can use multiple tools in sequence: search for topics, query dialectic for preferences, then get full context for generation.
|
||||
</Tip>
|
||||
|
||||
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.
|
||||
|
||||
<Note>
|
||||
**Multi-Agent Memory:** Use Honcho tools with different `peer_id` values to give each agent distinct memory and identity.
|
||||
</Note>
|
||||
|
||||
## 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
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Honcho Architecture" icon="sitemap" href="/v2/documentation/core-concepts/architecture">
|
||||
Understand Honcho's peer-based model and core primitives
|
||||
</Card>
|
||||
<Card title="Get Context" icon="messages" href="/v2/documentation/core-concepts/features/get-context">
|
||||
Learn about retrieving and formatting conversation context
|
||||
</Card>
|
||||
<Card title="Dialectic API" icon="brain" href="/v2/documentation/core-concepts/features/dialectic">
|
||||
Query `peer` representations for deeper understanding
|
||||
</Card>
|
||||
<Card title="LangGraph Integration" icon="diagram-project" href="/v2/integrations/langgraph">
|
||||
Build stateful agents with LangGraph and Honcho
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
|
@ -232,9 +232,9 @@ The [`get_context()`](/v2/documentation/core-concepts/features/get-context) meth
|
|||
- **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 theory-of-mind representations and peer cards when requested
|
||||
- **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:
|
||||
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:**
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
# Honcho CrewAI Integration
|
||||
|
||||
Build CrewAI agents with persistent memory and reasoning capabilities powered by Honcho.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install honcho-crewai
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew, Process
|
||||
from crewai.memory.external.external_memory import ExternalMemory
|
||||
from honcho_crewai import HonchoStorage
|
||||
|
||||
# Initialize Honcho storage
|
||||
storage = HonchoStorage(user_id="user-123")
|
||||
external_memory = ExternalMemory(storage=storage)
|
||||
|
||||
# Create agent with memory
|
||||
agent = Agent(
|
||||
role="AI Assistant",
|
||||
goal="Help users with persistent memory",
|
||||
backstory="You remember past conversations.",
|
||||
)
|
||||
|
||||
# Create crew with external memory
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
external_memory=external_memory
|
||||
)
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **Automatic Memory**: CrewAI agents automatically store and retrieve conversation context
|
||||
- **Semantic Search**: Find relevant past messages using vector similarity
|
||||
- **Logical Reasoning**: Query what the system knows about users via the Dialectic API
|
||||
- **Multi-Agent Support**: Give each agent distinct memory and identity
|
||||
- **Tools Integration**: `HonchoGetContextTool`, `HonchoDialecticTool`, and `HonchoSearchTool` for explicit memory control
|
||||
|
||||
## Documentation
|
||||
|
||||
For comprehensive guides, examples, and API reference, visit:
|
||||
**[https://docs.honcho.dev/v2/integrations/crewai](https://docs.honcho.dev/v2/integrations/crewai)**
|
||||
|
||||
## Examples
|
||||
|
||||
Check out complete examples in the [GitHub repository](https://github.com/plastic-labs/honcho/tree/main/examples/crewai/python/examples).
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0-or-later
|
||||
|
||||
## Support
|
||||
|
||||
- Report issues: [GitHub Issues](https://github.com/plastic-labs/honcho/issues)
|
||||
- Documentation: [docs.honcho.dev](https://docs.honcho.dev)
|
||||
- Website: [honcho.dev](https://honcho.dev)
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
"""
|
||||
Hybrid Memory Example: Combining Automatic Memory + Explicit Tools
|
||||
|
||||
Demonstrates combining automatic memory (HonchoStorage) with explicit memory tools.
|
||||
The agent gets baseline context automatically but can also make targeted queries.
|
||||
"""
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from crewai import Agent, Task, Crew, Process
|
||||
from crewai.memory.external.external_memory import ExternalMemory
|
||||
from honcho import Honcho
|
||||
from honcho_crewai import (
|
||||
HonchoStorage,
|
||||
HonchoSearchTool,
|
||||
HonchoDialecticTool,
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def main():
|
||||
"""Hybrid memory example with automatic baseline + explicit tools."""
|
||||
# Initialize Honcho
|
||||
honcho = Honcho()
|
||||
user_id = "hybrid-demo-user"
|
||||
session_id = "hybrid-demo-session"
|
||||
|
||||
# Setup automatic memory
|
||||
storage = HonchoStorage(
|
||||
user_id=user_id,
|
||||
session_id=session_id,
|
||||
honcho_client=honcho
|
||||
)
|
||||
external_memory = ExternalMemory(storage=storage)
|
||||
|
||||
# Add conversation history
|
||||
messages = [
|
||||
("user", "I'm planning a trip to Japan next spring"),
|
||||
("assistant", "How exciting! Japan is beautiful in spring."),
|
||||
("user", "I love Japanese cuisine, especially ramen and sushi"),
|
||||
("assistant", "You'll find amazing food there!"),
|
||||
("user", "My budget is around $3000 for the whole trip"),
|
||||
("assistant", "That's a good budget for a memorable trip."),
|
||||
("user", "I prefer cultural experiences over touristy attractions"),
|
||||
]
|
||||
|
||||
for role, message in messages:
|
||||
external_memory.save(message, metadata={"agent": role})
|
||||
|
||||
# Create memory tools for targeted queries
|
||||
search_tool = HonchoSearchTool(honcho=honcho, session_id=session_id)
|
||||
dialectic_tool = HonchoDialecticTool(
|
||||
honcho=honcho, session_id=session_id, peer_id=user_id
|
||||
)
|
||||
|
||||
# Create agent with both automatic memory AND tools
|
||||
travel_agent = Agent(
|
||||
role="Travel Advisor",
|
||||
goal="Create personalized travel recommendations using memory",
|
||||
backstory=(
|
||||
"You are a travel advisor with access to conversation history. "
|
||||
"You can use tools to search for specific details or understand preferences."
|
||||
),
|
||||
tools=[search_tool, dialectic_tool],
|
||||
verbose=True,
|
||||
allow_delegation=False
|
||||
)
|
||||
|
||||
# Create task
|
||||
task = Task(
|
||||
description=(
|
||||
"Create a 3-day Tokyo itinerary for the user.\n\n"
|
||||
"Use search_tool to find their budget and food preferences.\n"
|
||||
"Use query_peer_knowledge to understand their travel style.\n"
|
||||
"Then create a personalized itinerary with activities and restaurant recommendations."
|
||||
),
|
||||
expected_output="A 3-day Tokyo itinerary with daily activities and dining suggestions",
|
||||
agent=travel_agent
|
||||
)
|
||||
|
||||
# Execute with hybrid memory: automatic baseline + explicit tools
|
||||
crew = Crew(
|
||||
agents=[travel_agent],
|
||||
tasks=[task],
|
||||
process=Process.sequential,
|
||||
external_memory=external_memory, # Automatic memory!
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("RESULT")
|
||||
print("=" * 70)
|
||||
print(result.raw)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
"""
|
||||
CrewAI Integration with Honcho and OpenAI
|
||||
|
||||
This example demonstrates how to build AI agents with persistent memory using
|
||||
CrewAI for agent orchestration, OpenAI for the AI model, and Honcho for memory
|
||||
management via the honcho_crewai package.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
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()
|
||||
|
||||
|
||||
def run_conversation_turn(
|
||||
user_id: str,
|
||||
user_input: str,
|
||||
session_id: Optional[str] = None,
|
||||
storage: Optional[HonchoStorage] = None
|
||||
) -> tuple[str, HonchoStorage]:
|
||||
"""
|
||||
Run a single conversation turn with the CrewAI agent.
|
||||
|
||||
Args:
|
||||
user_id: Unique identifier for the user
|
||||
user_input: User's message
|
||||
session_id: Optional session ID for conversation continuity
|
||||
storage: Optional existing HonchoStorage instance
|
||||
|
||||
Returns:
|
||||
Tuple of (agent_response, storage_instance)
|
||||
"""
|
||||
# Initialize or reuse storage
|
||||
if storage is None:
|
||||
if not session_id:
|
||||
session_id = f"session_{user_id}"
|
||||
storage = HonchoStorage(user_id=user_id, session_id=session_id)
|
||||
|
||||
# Create ExternalMemory wrapper for automatic context retrieval
|
||||
external_memory = ExternalMemory(storage=storage)
|
||||
|
||||
# Save user input to memory
|
||||
external_memory.save(user_input, metadata={"agent": "user"})
|
||||
|
||||
# Create an agent with memory
|
||||
agent = Agent(
|
||||
role="AI Assistant",
|
||||
goal="Help users with their questions and remember context from previous conversations",
|
||||
backstory=(
|
||||
"You are a helpful AI assistant with the ability to remember past conversations. "
|
||||
"You use context from previous interactions to provide personalized and relevant responses."
|
||||
),
|
||||
verbose=False,
|
||||
allow_delegation=False
|
||||
)
|
||||
|
||||
# Create task for the agent
|
||||
task = Task(
|
||||
description=f"Respond to the user's message: {user_input}",
|
||||
expected_output="A helpful and contextually relevant response that considers conversation history",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
# Create crew with external memory - enables automatic context retrieval
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
process=Process.sequential,
|
||||
external_memory=external_memory,
|
||||
verbose=False
|
||||
)
|
||||
|
||||
# Execute - CrewAI automatically retrieves relevant context from Honcho
|
||||
result = crew.kickoff()
|
||||
|
||||
# Save assistant response back to memory
|
||||
response_text = str(result.raw)
|
||||
external_memory.save(response_text, metadata={"agent": "assistant"})
|
||||
|
||||
return response_text, storage
|
||||
|
||||
|
||||
def main():
|
||||
"""Interactive chat loop with CrewAI agent powered by Honcho memory."""
|
||||
print("Welcome to the AI Assistant powered by CrewAI and Honcho!")
|
||||
print("Type 'quit' or 'exit' to end the conversation.\n")
|
||||
|
||||
user_id = "demo-user-123"
|
||||
storage = None
|
||||
|
||||
while True:
|
||||
user_input = input("You: ")
|
||||
if user_input.lower() in ['quit', 'exit']:
|
||||
print("Goodbye!")
|
||||
break
|
||||
|
||||
if not user_input.strip():
|
||||
continue
|
||||
|
||||
try:
|
||||
response, storage = run_conversation_turn(
|
||||
user_id=user_id,
|
||||
user_input=user_input,
|
||||
storage=storage
|
||||
)
|
||||
print(f"Assistant: {response}\n")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
"""
|
||||
Simple Honcho + CrewAI Example
|
||||
|
||||
A minimal example showing how to use Honcho's ExternalMemory with CrewAI agents.
|
||||
This demonstrates the basic pattern for persistent conversation memory.
|
||||
"""
|
||||
|
||||
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()
|
||||
|
||||
|
||||
def main():
|
||||
"""Simple example of CrewAI agent with Honcho memory."""
|
||||
# Initialize Honcho storage
|
||||
storage = HonchoStorage(user_id="simple-demo-user")
|
||||
external_memory = ExternalMemory(storage=storage)
|
||||
|
||||
# Add some conversation history
|
||||
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})
|
||||
|
||||
# Create agent with memory
|
||||
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
|
||||
)
|
||||
|
||||
# Create task
|
||||
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
|
||||
)
|
||||
|
||||
# Execute with memory - CrewAI automatically retrieves relevant context!
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
process=Process.sequential,
|
||||
external_memory=external_memory,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
|
||||
print("\n" + "=" * 70)
|
||||
print("RESULT")
|
||||
print("=" * 70)
|
||||
print(result.raw)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
"""
|
||||
Honcho Tools with CrewAI Example
|
||||
|
||||
Demonstrates how to equip CrewAI agents with Honcho's memory tools:
|
||||
- HonchoGetContextTool: Retrieve session context with token limits
|
||||
- HonchoDialecticTool: Query representations about peers
|
||||
- HonchoSearchTool: Perform semantic search across session messages
|
||||
|
||||
These tools give agents explicit control over memory retrieval, beyond the
|
||||
automatic memory provided by ExternalMemory.
|
||||
"""
|
||||
|
||||
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()
|
||||
|
||||
|
||||
def main():
|
||||
"""Demonstrate Honcho tools with CrewAI agents."""
|
||||
print("=" * 70)
|
||||
print("HONCHO TOOLS + CREWAI EXAMPLE")
|
||||
print("=" * 70 + "\n")
|
||||
|
||||
# Step 1: Setup session with conversation history
|
||||
print("1. Setting up session with conversation history...\n")
|
||||
|
||||
honcho = Honcho()
|
||||
user_id = "demo-user-45"
|
||||
session_id = "tools-demo-session"
|
||||
|
||||
user = honcho.peer(user_id)
|
||||
session = honcho.session(session_id)
|
||||
|
||||
# Add conversation history
|
||||
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:
|
||||
print(f" • {msg}")
|
||||
session.add_messages([user.message(msg)])
|
||||
|
||||
print("\n ✓ Session created with 5 messages\n")
|
||||
|
||||
# Step 2: Create Honcho tools
|
||||
print("2. Creating Honcho memory tools...\n")
|
||||
|
||||
context_tool = HonchoGetContextTool(
|
||||
honcho=honcho, session_id=session_id, peer_id=user_id
|
||||
)
|
||||
print(" ✓ get_session_context - Retrieve conversation context")
|
||||
|
||||
dialectic_tool = HonchoDialecticTool(
|
||||
honcho=honcho, session_id=session_id, peer_id=user_id
|
||||
)
|
||||
print(" ✓ query_peer_knowledge - Ask about user preferences")
|
||||
|
||||
search_tool = HonchoSearchTool(honcho=honcho, session_id=session_id)
|
||||
print(" ✓ search_session_messages - Semantic search messages\n")
|
||||
|
||||
# Step 3: Create agent with tools
|
||||
print("3. Creating travel planning agent with memory tools...\n")
|
||||
|
||||
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
|
||||
)
|
||||
print(" ✓ Agent created with 3 Honcho tools\n")
|
||||
|
||||
# Step 4: Create task
|
||||
print("4. Creating task...\n")
|
||||
|
||||
task = Task(
|
||||
description=(
|
||||
"Create a personalized 3-day Tokyo itinerary. "
|
||||
"Use the memory tools to understand:\n"
|
||||
" • Food preferences (search for 'cuisine' or 'food')\n"
|
||||
" • Travel style and budget (query user knowledge)\n"
|
||||
" • Recent context (get conversation context)\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
|
||||
)
|
||||
print(" ✓ Task created\n")
|
||||
|
||||
# Step 5: Execute
|
||||
print("5. Executing crew (agent will use tools to retrieve memory)...\n")
|
||||
print("-" * 70 + "\n")
|
||||
|
||||
crew = Crew(
|
||||
agents=[travel_agent],
|
||||
tasks=[task],
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
crew.kickoff()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
[project]
|
||||
name = "honcho-crewai"
|
||||
version = "0.1.0"
|
||||
description = "CrewAI integration with Honcho for persistent agent memory"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
license = {text = "AGPL-3.0-or-later"}
|
||||
authors = [
|
||||
{name = "Plastic Labs", email = "hello@plasticlabs.ai"}
|
||||
]
|
||||
maintainers = [
|
||||
{name = "Plastic Labs", email = "hello@plasticlabs.ai"}
|
||||
]
|
||||
keywords = [
|
||||
"honcho",
|
||||
"crewai",
|
||||
"ai-agents",
|
||||
"memory",
|
||||
"agent-memory",
|
||||
"persistent-memory"
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 4 - Beta",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
"Framework :: Pydantic",
|
||||
]
|
||||
dependencies = [
|
||||
"crewai>=0.134.0",
|
||||
"honcho-ai>=0.2.0",
|
||||
"openai>=1.0.0",
|
||||
"python-dotenv>=1.0.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://honcho.dev"
|
||||
Documentation = "https://docs.honcho.dev/v2/integrations/crewai"
|
||||
Repository = "https://github.com/plastic-labs/honcho"
|
||||
"Bug Tracker" = "https://github.com/plastic-labs/honcho/issues"
|
||||
Changelog = "https://github.com/plastic-labs/honcho/blob/main/CHANGELOG.md"
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
"""
|
||||
Honcho CrewAI Integration
|
||||
|
||||
This package provides seamless integration between Honcho and CrewAI,
|
||||
enabling AI agents to maintain persistent memory across conversations.
|
||||
|
||||
Example:
|
||||
```python
|
||||
from honcho_crewai import HonchoStorage, HonchoSearchTool, HonchoGetContextTool, HonchoDialecticTool
|
||||
from crewai.memory.external.external_memory import ExternalMemory
|
||||
from crewai import Agent, Task, Crew
|
||||
from honcho import Honcho
|
||||
|
||||
# Initialize Honcho client and storage
|
||||
honcho = Honcho()
|
||||
storage = HonchoStorage(user_id="user123", honcho_client=honcho)
|
||||
external_memory = ExternalMemory(storage=storage)
|
||||
|
||||
# Create tools for agents
|
||||
search_tool = HonchoSearchTool(honcho=honcho, session_id=storage.session_id)
|
||||
context_tool = HonchoGetContextTool(honcho=honcho, session_id=storage.session_id, peer_id="user123")
|
||||
dialectic_tool = HonchoDialecticTool(honcho=honcho, session_id=storage.session_id, peer_id="user123")
|
||||
|
||||
# Create agent with memory and tools
|
||||
agent = Agent(
|
||||
role="AI Assistant",
|
||||
goal="Help users with persistent memory",
|
||||
backstory="You remember past conversations.",
|
||||
tools=[search_tool, context_tool, dialectic_tool],
|
||||
)
|
||||
|
||||
# Define a task for the crew
|
||||
task = Task(
|
||||
description="Help the user with their request",
|
||||
expected_output="A helpful response",
|
||||
agent=agent,
|
||||
)
|
||||
|
||||
# Create crew with external memory
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
external_memory=external_memory
|
||||
)
|
||||
```
|
||||
"""
|
||||
|
||||
from honcho_crewai.exceptions import HonchoDependencyError
|
||||
from honcho_crewai.storage import HonchoStorage
|
||||
from honcho_crewai.tools import (
|
||||
HonchoDialecticTool,
|
||||
HonchoGetContextTool,
|
||||
HonchoSearchTool,
|
||||
)
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__all__ = [
|
||||
"HonchoDependencyError",
|
||||
"HonchoDialecticTool",
|
||||
"HonchoGetContextTool",
|
||||
"HonchoSearchTool",
|
||||
"HonchoStorage",
|
||||
]
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
"""
|
||||
Exception classes for CrewAI integration.
|
||||
"""
|
||||
|
||||
|
||||
class HonchoDependencyError(ImportError):
|
||||
"""Raised when required CrewAI dependencies are not installed."""
|
||||
|
||||
def __init__(self, framework: str, install_command: str) -> None:
|
||||
self.framework = framework
|
||||
self.install_command = install_command
|
||||
super().__init__(
|
||||
f"{framework} dependencies not found. Install with: {install_command}"
|
||||
)
|
||||
|
|
@ -0,0 +1,188 @@
|
|||
"""
|
||||
Honcho Storage for CrewAI External Memory
|
||||
|
||||
This module provides a Honcho-backed storage provider for CrewAI's external memory
|
||||
system, enabling AI agents to maintain persistent conversation memory across sessions.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from crewai.memory.storage.interface import Storage
|
||||
from honcho import Honcho
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HonchoStorage(Storage):
|
||||
"""
|
||||
Honcho-backed storage provider for CrewAI external memory.
|
||||
|
||||
Implements CrewAI's Storage interface using Honcho's session-based memory,
|
||||
allowing agents to maintain context across conversations.
|
||||
|
||||
Attributes:
|
||||
honcho: The Honcho client instance
|
||||
user: Peer representing the user
|
||||
assistant: Peer representing the AI assistant
|
||||
session: The conversation session
|
||||
session_id: Unique identifier for the session
|
||||
|
||||
Example:
|
||||
```python
|
||||
from honcho_crewai import HonchoStorage
|
||||
from crewai.memory.external.external_memory import ExternalMemory
|
||||
|
||||
# Initialize storage
|
||||
storage = HonchoStorage(user_id="user123")
|
||||
|
||||
# Use with CrewAI's external memory
|
||||
external_memory = ExternalMemory(storage=storage)
|
||||
```
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
user_id: str,
|
||||
session_id: Optional[str] = None,
|
||||
honcho_client: Optional[Honcho] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Initialize Honcho storage for a specific user and session.
|
||||
|
||||
Args:
|
||||
user_id: Unique identifier for the user
|
||||
session_id: Optional session ID. If not provided, a UUID will be generated
|
||||
honcho_client: Optional Honcho client instance. If not provided, creates one
|
||||
using the demo environment (https://demo.honcho.dev)
|
||||
"""
|
||||
self.honcho = honcho_client or Honcho()
|
||||
|
||||
# Initialize user and assistant peers
|
||||
self.user = self.honcho.peer(user_id)
|
||||
self.assistant = self.honcho.peer("assistant")
|
||||
|
||||
# Create or use existing session
|
||||
if not session_id:
|
||||
session_id = str(uuid.uuid4())
|
||||
self.session = self.honcho.session(session_id)
|
||||
self.session_id = session_id
|
||||
|
||||
def save(self, value: Any, metadata: dict[str, Any]) -> None:
|
||||
"""
|
||||
Save a message to Honcho session.
|
||||
|
||||
This method is called by CrewAI to store messages and context. Messages
|
||||
are associated with the appropriate peer (user or assistant) based on
|
||||
the metadata.
|
||||
|
||||
Args:
|
||||
value: Message content to save
|
||||
metadata: Metadata dict that may contain 'role', 'agent', or 'type' info
|
||||
Common keys: 'role', 'agent', 'type'
|
||||
"""
|
||||
try:
|
||||
# Determine if this is from user or assistant based on metadata
|
||||
# Check various metadata keys that might indicate the role
|
||||
role = metadata.get("role", metadata.get("agent", "assistant"))
|
||||
is_user = role == "user"
|
||||
peer = self.user if is_user else self.assistant
|
||||
|
||||
content_str = str(value)
|
||||
|
||||
# Add message to session
|
||||
self.session.add_messages([peer.message(content_str, metadata=metadata)])
|
||||
|
||||
logger.debug(
|
||||
"Saved message from %s: %s...",
|
||||
metadata.get("name", role),
|
||||
content_str[:100],
|
||||
)
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error saving to Honcho")
|
||||
raise
|
||||
|
||||
def search(
|
||||
self,
|
||||
query: str,
|
||||
limit: int = 10,
|
||||
score_threshold: float = 0.5,
|
||||
filters: Optional[dict[str, Any]] = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Search for relevant messages using semantic search.
|
||||
|
||||
This method uses Honcho's semantic vector search to find messages most
|
||||
relevant to the query.
|
||||
|
||||
Args:
|
||||
query: Search query used for semantic matching
|
||||
limit: Maximum number of messages to retrieve
|
||||
score_threshold: Minimum relevance score (not currently used by Honcho API)
|
||||
filters: Optional filters to scope the search. Supports Honcho's filter syntax
|
||||
including logical operators (AND, OR, NOT), comparison operators
|
||||
(gt, gte, lt, lte, eq, ne), and metadata filtering.
|
||||
Example: {"peer_id": "user123"} or {"metadata": {"type": "important"}}
|
||||
See: https://docs.honcho.dev/v2/documentation/core-concepts/features/using-filters
|
||||
|
||||
Returns:
|
||||
List of message dictionaries in CrewAI expected format.
|
||||
Each dict contains:
|
||||
- content: The message content
|
||||
- memory: The message content (required by CrewAI)
|
||||
- context: The message content (for compatibility)
|
||||
- metadata: Message metadata including peer_id, created_at, and custom metadata
|
||||
"""
|
||||
try:
|
||||
results = []
|
||||
# Use semantic search to find relevant messages
|
||||
# This performs vector similarity search on message content
|
||||
messages = self.session.search(query=query, filters=filters, limit=limit)
|
||||
|
||||
# Convert to CrewAI expected format
|
||||
for msg in messages:
|
||||
# Build base metadata with peer_id and created_at
|
||||
metadata = {
|
||||
"peer_id": msg.peer_id,
|
||||
"created_at": str(msg.created_at) if hasattr(msg, "created_at") else None,
|
||||
}
|
||||
|
||||
# Merge custom metadata if present
|
||||
if hasattr(msg, "metadata") and msg.metadata:
|
||||
metadata.update(msg.metadata)
|
||||
|
||||
results.append(
|
||||
{
|
||||
"content": msg.content,
|
||||
"memory": msg.content,
|
||||
"context": msg.content,
|
||||
"metadata": metadata,
|
||||
}
|
||||
)
|
||||
|
||||
logger.debug("Search for '%s' returned %d results", query, len(results))
|
||||
return results
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error searching Honcho")
|
||||
raise
|
||||
|
||||
def reset(self) -> None:
|
||||
"""
|
||||
Create a new session, effectively resetting memory.
|
||||
|
||||
This creates a new Honcho session with a fresh UUID, allowing the agent
|
||||
to start a new conversation without the previous context.
|
||||
"""
|
||||
try:
|
||||
new_session_id = str(uuid.uuid4())
|
||||
self.session = self.honcho.session(new_session_id)
|
||||
self.session_id = new_session_id
|
||||
|
||||
logger.debug("Reset session. New session ID: %s", new_session_id)
|
||||
|
||||
except Exception:
|
||||
logger.exception("Error resetting Honcho session")
|
||||
raise
|
||||
|
|
@ -0,0 +1,303 @@
|
|||
"""
|
||||
Honcho Tools for CrewAI
|
||||
|
||||
This module provides tools that allow CrewAI agents to interact with Honcho's
|
||||
session context, dialectic API, and semantic search capabilities.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
|
||||
from crewai.tools import BaseTool
|
||||
from honcho import Honcho
|
||||
from pydantic import BaseModel, Field, PrivateAttr
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Input Schemas
|
||||
class GetContextInput(BaseModel):
|
||||
"""Input schema for get_context tool."""
|
||||
|
||||
tokens: Optional[int] = Field(
|
||||
default=None, gt=0, description="Maximum number of tokens to include in the context"
|
||||
)
|
||||
peer_target: Optional[str] = Field(
|
||||
default=None, description="A peer ID to get context for (retrieves representation and peer card)"
|
||||
)
|
||||
summary: bool = Field(
|
||||
default=True, description="Whether to include session summary in the context"
|
||||
)
|
||||
peer_perspective: Optional[str] = Field(
|
||||
default=None, description="Peer ID to use as the perspective for context retrieval"
|
||||
)
|
||||
|
||||
|
||||
class DialecticInput(BaseModel):
|
||||
"""Input schema for dialectic (chat) tool."""
|
||||
|
||||
query: str = Field(..., min_length=1, description="Natural language question to ask")
|
||||
target: Optional[str] = Field(
|
||||
default=None, description="Optional target peer for local representation query"
|
||||
)
|
||||
session_id: Optional[str] = Field(
|
||||
default=None, description="Optional session ID to scope query to specific session"
|
||||
)
|
||||
|
||||
|
||||
class SearchInput(BaseModel):
|
||||
"""Input schema for search tool."""
|
||||
|
||||
query: str = Field(..., min_length=1, description="Search query for semantic matching")
|
||||
limit: int = Field(default=10, ge=1, le=100, description="Number of results to return (1-100)")
|
||||
filters: Optional[dict[str, Any]] = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"Optional filters to scope the search. Supports Honcho's filter syntax including "
|
||||
"logical operators (AND, OR, NOT), comparison operators (gt, gte, lt, lte, eq, ne), "
|
||||
"and metadata filtering. Examples: {'peer_id': 'user123'}, {'metadata': {'priority': 'high'}}, "
|
||||
"{'created_at': {'gte': '2024-01-01'}}"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
# Tool Implementations
|
||||
class HonchoGetContextTool(BaseTool):
|
||||
"""
|
||||
Tool to retrieve session context with token limits.
|
||||
|
||||
This tool fetches the conversation history and session summary within
|
||||
a specified token budget, optimized for LLM context windows.
|
||||
"""
|
||||
|
||||
name: str = "get_session_context"
|
||||
description: str = (
|
||||
"Retrieve recent conversation context within token limits. "
|
||||
"Returns formatted messages with optional summary and peer information. "
|
||||
"Useful for getting optimized context that fits within token budgets."
|
||||
)
|
||||
args_schema: type[BaseModel] = GetContextInput
|
||||
|
||||
_honcho: Honcho = PrivateAttr()
|
||||
_session_id: str = PrivateAttr()
|
||||
_peer_id: str = PrivateAttr()
|
||||
|
||||
def __init__(self, honcho: Honcho, session_id: str, peer_id: str) -> None:
|
||||
"""
|
||||
Initialize the get_context tool.
|
||||
|
||||
Args:
|
||||
honcho: Honcho client instance
|
||||
session_id: ID of the session to get context from
|
||||
peer_id: ID of the peer requesting context
|
||||
"""
|
||||
super().__init__()
|
||||
self._honcho = honcho
|
||||
self._session_id = session_id
|
||||
self._peer_id = peer_id
|
||||
|
||||
def _run(
|
||||
self,
|
||||
tokens: Optional[int] = None,
|
||||
peer_target: Optional[str] = None,
|
||||
*,
|
||||
summary: bool = True,
|
||||
peer_perspective: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Execute get_context and format results.
|
||||
|
||||
Args:
|
||||
tokens: Maximum tokens to include
|
||||
peer_target: Target peer ID for representation
|
||||
summary: Whether to include summary
|
||||
peer_perspective: Peer ID to use as perspective
|
||||
|
||||
Returns:
|
||||
Formatted string containing context information
|
||||
"""
|
||||
try:
|
||||
session = self._honcho.session(self._session_id)
|
||||
context = session.get_context(
|
||||
summary=summary,
|
||||
tokens=tokens,
|
||||
peer_target=peer_target,
|
||||
peer_perspective=peer_perspective,
|
||||
)
|
||||
|
||||
# Format for agent consumption
|
||||
result = []
|
||||
|
||||
# Add summary if present
|
||||
if context.summary:
|
||||
result.append("=== Session Summary ===")
|
||||
result.append(context.summary.content)
|
||||
result.append("")
|
||||
|
||||
# Add peer representation if present
|
||||
if context.peer_representation:
|
||||
result.append("=== Peer Representation ===")
|
||||
result.append(context.peer_representation)
|
||||
result.append("")
|
||||
|
||||
# Add peer card if present
|
||||
if context.peer_card:
|
||||
result.append("=== Peer Card ===")
|
||||
result.extend(context.peer_card)
|
||||
result.append("")
|
||||
|
||||
# Add messages
|
||||
if context.messages:
|
||||
result.append(f"=== Messages ({len(context.messages)}) ===")
|
||||
for msg in context.messages:
|
||||
result.append(f"{msg.peer_id}: {msg.content}")
|
||||
|
||||
return "\n".join(result) if result else "No context available"
|
||||
|
||||
except Exception as e:
|
||||
logger.exception("Error retrieving context")
|
||||
return f"Error retrieving context: {e!s}"
|
||||
|
||||
|
||||
class HonchoDialecticTool(BaseTool):
|
||||
"""
|
||||
Tool to query Honcho's dialectic API (peer representations).
|
||||
|
||||
This tool allows agents to ask questions about what the system knows
|
||||
about users or other peers, leveraging Honcho's reasoning capabilities.
|
||||
"""
|
||||
|
||||
name: str = "query_peer_knowledge"
|
||||
description: str = (
|
||||
"Query the system's representation about peers. "
|
||||
"Ask questions like 'What does the user like?' or 'What are their preferences?' "
|
||||
"to retrieve information from the peer's long-term representation. "
|
||||
"Can optionally query what one peer knows about another (local representation)."
|
||||
)
|
||||
args_schema: type[BaseModel] = DialecticInput
|
||||
|
||||
_honcho: Honcho = PrivateAttr()
|
||||
_session_id: str = PrivateAttr()
|
||||
_peer_id: str = PrivateAttr()
|
||||
|
||||
def __init__(self, honcho: Honcho, session_id: str, peer_id: str) -> None:
|
||||
"""
|
||||
Initialize the dialectic tool.
|
||||
|
||||
Args:
|
||||
honcho: Honcho client instance
|
||||
session_id: Default session ID for scoped queries
|
||||
peer_id: ID of the peer to query about
|
||||
"""
|
||||
super().__init__()
|
||||
self._honcho = honcho
|
||||
self._session_id = session_id
|
||||
self._peer_id = peer_id
|
||||
|
||||
def _run(
|
||||
self,
|
||||
query: str,
|
||||
target: Optional[str] = None,
|
||||
session_id: Optional[str] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Execute dialectic query.
|
||||
|
||||
Args:
|
||||
query: Natural language question to ask
|
||||
target: Optional target peer for local representation
|
||||
session_id: Optional session ID to scope the query
|
||||
|
||||
Returns:
|
||||
String response from the dialectic API
|
||||
"""
|
||||
try:
|
||||
peer = self._honcho.peer(self._peer_id)
|
||||
|
||||
# Use provided session_id or fall back to default
|
||||
scope_session_id = session_id or self._session_id
|
||||
|
||||
# Query the dialectic API (non-streaming)
|
||||
response = peer.chat(
|
||||
query=query,
|
||||
stream=False,
|
||||
target=target,
|
||||
session_id=scope_session_id,
|
||||
)
|
||||
|
||||
# Return the response or a default message
|
||||
if response:
|
||||
return str(response)
|
||||
else:
|
||||
return "No relevant information found."
|
||||
|
||||
except Exception as e:
|
||||
logger.exception("Error querying dialectic API")
|
||||
return f"Error querying peer knowledge: {e!s}"
|
||||
|
||||
|
||||
class HonchoSearchTool(BaseTool):
|
||||
"""
|
||||
Tool to perform semantic search across session messages.
|
||||
|
||||
This tool enables agents to find relevant past messages using
|
||||
semantic similarity search, useful for retrieving specific information
|
||||
from conversation history.
|
||||
"""
|
||||
|
||||
name: str = "search_session_messages"
|
||||
description: str = (
|
||||
"Search through session messages using semantic similarity. "
|
||||
"Finds messages that are semantically related to the query, "
|
||||
"useful for retrieving specific information from past conversations."
|
||||
)
|
||||
args_schema: type[BaseModel] = SearchInput
|
||||
|
||||
_honcho: Honcho = PrivateAttr()
|
||||
_session_id: str = PrivateAttr()
|
||||
|
||||
def __init__(self, honcho: Honcho, session_id: str) -> None:
|
||||
"""
|
||||
Initialize the search tool.
|
||||
|
||||
Args:
|
||||
honcho: Honcho client instance
|
||||
session_id: ID of the session to search in
|
||||
"""
|
||||
super().__init__()
|
||||
self._honcho = honcho
|
||||
self._session_id = session_id
|
||||
|
||||
def _run(self, query: str, limit: int = 10, filters: Optional[dict[str, Any]] = None) -> str:
|
||||
"""
|
||||
Execute semantic search.
|
||||
|
||||
Args:
|
||||
query: Search query for semantic matching
|
||||
limit: Number of results to return (1-100)
|
||||
filters: Optional filters to apply to search results
|
||||
|
||||
Returns:
|
||||
Formatted string with search results
|
||||
"""
|
||||
try:
|
||||
session = self._honcho.session(self._session_id)
|
||||
|
||||
# Perform semantic search
|
||||
messages = session.search(query=query, limit=limit, filters=filters)
|
||||
|
||||
if not messages:
|
||||
return f"No messages found matching '{query}'"
|
||||
|
||||
# Format results for agent consumption
|
||||
result = [f"=== Search Results for '{query}' ({len(messages)} found) ==="]
|
||||
for i, msg in enumerate(messages, 1):
|
||||
result.append(f"\n{i}. [{msg.peer_id}] {msg.content}")
|
||||
if hasattr(msg, "created_at") and msg.created_at:
|
||||
result.append(f" Created: {msg.created_at}")
|
||||
|
||||
return "\n".join(result)
|
||||
|
||||
except Exception as e:
|
||||
logger.exception("Error searching messages: %s", e)
|
||||
return f"Error searching messages: {e!s}"
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
"""
|
||||
Basic tests for honcho_crewai package
|
||||
|
||||
Validates package structure, imports, and basic functionality.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_package_import():
|
||||
"""Test that honcho_crewai imports successfully."""
|
||||
import honcho_crewai
|
||||
|
||||
assert honcho_crewai is not None
|
||||
|
||||
|
||||
def test_storage_import():
|
||||
"""Test that HonchoStorage can be imported."""
|
||||
from honcho_crewai import HonchoStorage
|
||||
|
||||
assert HonchoStorage is not None
|
||||
|
||||
|
||||
def test_tools_import():
|
||||
"""Test that tool classes can be imported."""
|
||||
from honcho_crewai import (
|
||||
HonchoGetContextTool,
|
||||
HonchoDialecticTool,
|
||||
HonchoSearchTool,
|
||||
)
|
||||
|
||||
assert HonchoGetContextTool is not None
|
||||
assert HonchoDialecticTool is not None
|
||||
assert HonchoSearchTool is not None
|
||||
|
||||
|
||||
class TestPackageMetadata:
|
||||
"""Test package metadata and structure."""
|
||||
|
||||
def test_package_has_version(self):
|
||||
"""Test that package exposes version information."""
|
||||
import honcho_crewai
|
||||
|
||||
assert hasattr(honcho_crewai, "__version__")
|
||||
assert isinstance(honcho_crewai.__version__, str)
|
||||
assert len(honcho_crewai.__version__) > 0
|
||||
|
||||
def test_package_all_exports(self):
|
||||
"""Test that __all__ contains expected exports."""
|
||||
import honcho_crewai
|
||||
|
||||
assert hasattr(honcho_crewai, "__all__")
|
||||
expected_exports = [
|
||||
"HonchoStorage",
|
||||
"HonchoGetContextTool",
|
||||
"HonchoDialecticTool",
|
||||
"HonchoSearchTool",
|
||||
"HonchoDependencyError",
|
||||
]
|
||||
|
||||
for export in expected_exports:
|
||||
assert export in honcho_crewai.__all__, f"{export} not in __all__"
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
"""
|
||||
Tests for HonchoStorage
|
||||
|
||||
Tests the CrewAI-Honcho integration layer, focusing on:
|
||||
- CrewAI Storage interface compliance
|
||||
- Metadata mapping (agent/role -> peer_id)
|
||||
- Format conversion (Honcho -> CrewAI format)
|
||||
"""
|
||||
|
||||
from honcho_crewai import HonchoStorage
|
||||
|
||||
|
||||
class TestHonchoStorage:
|
||||
"""Tests for HonchoStorage integration layer."""
|
||||
|
||||
def test_initialization(self):
|
||||
"""Test that HonchoStorage initializes with correct peers and session."""
|
||||
storage = HonchoStorage(user_id="test_user")
|
||||
|
||||
assert storage is not None
|
||||
assert storage.session_id is not None
|
||||
assert storage.user is not None
|
||||
assert storage.assistant is not None
|
||||
assert storage.session is not None
|
||||
|
||||
def test_initialization_with_custom_session(self):
|
||||
"""Test that custom session_id is preserved."""
|
||||
custom_session_id = "my_custom_session"
|
||||
storage = HonchoStorage(user_id="test_user", session_id=custom_session_id)
|
||||
|
||||
assert storage.session_id == custom_session_id
|
||||
|
||||
def test_save_with_different_roles(self):
|
||||
"""Test that save handles different agent/role metadata."""
|
||||
storage = HonchoStorage(user_id="test_user_roles")
|
||||
|
||||
# Save with different metadata patterns
|
||||
storage.save("User via agent", metadata={"agent": "user"})
|
||||
storage.save("User via role", metadata={"role": "user"})
|
||||
storage.save("Assistant via agent", metadata={"agent": "assistant"})
|
||||
storage.save("Default (no metadata)", metadata={})
|
||||
|
||||
# If no exceptions raised, metadata mapping works
|
||||
|
||||
def test_search_returns_crewai_format(self):
|
||||
"""Test that search returns results in CrewAI format."""
|
||||
storage = HonchoStorage(user_id="test_user_search")
|
||||
|
||||
# Add a message
|
||||
storage.save("Test message", metadata={"agent": "user"})
|
||||
|
||||
# Search
|
||||
results = storage.search("test", limit=10)
|
||||
|
||||
# Verify CrewAI format
|
||||
assert isinstance(results, list)
|
||||
for result in results:
|
||||
# Required keys for CrewAI
|
||||
assert "memory" in result
|
||||
assert "context" in result
|
||||
assert "content" in result
|
||||
assert "metadata" in result
|
||||
|
||||
def test_search_includes_all_required_fields(self):
|
||||
"""Test that all search results have required CrewAI fields."""
|
||||
storage = HonchoStorage(user_id="test_user_format")
|
||||
|
||||
# Add a message
|
||||
storage.save("Test message", metadata={"agent": "user"})
|
||||
|
||||
# Search
|
||||
results = storage.search("test", limit=5)
|
||||
|
||||
# Verify all results have required fields with correct types
|
||||
for result in results:
|
||||
assert isinstance(result["content"], str)
|
||||
assert isinstance(result["memory"], str)
|
||||
assert isinstance(result["context"], str)
|
||||
assert isinstance(result["metadata"], dict)
|
||||
|
||||
def test_search_formats_summaries_correctly(self):
|
||||
"""Test that session summaries are formatted with [Session Summary] prefix."""
|
||||
storage = HonchoStorage(user_id="test_user_summaries")
|
||||
|
||||
# Add enough messages to potentially trigger summaries
|
||||
for i in range(25):
|
||||
storage.save(
|
||||
f"Message {i}",
|
||||
metadata={"agent": "user" if i % 2 == 0 else "assistant"},
|
||||
)
|
||||
|
||||
# Search
|
||||
results = storage.search("message", limit=10)
|
||||
|
||||
# Check summary formatting (if summaries exist)
|
||||
summary_results = [r for r in results if r["metadata"].get("type") == "summary"]
|
||||
|
||||
for summary in summary_results:
|
||||
# Verify our formatting logic
|
||||
assert "summary_type" in summary["metadata"]
|
||||
assert "[Session Summary]" in summary["context"] # Our formatting
|
||||
|
||||
def test_reset_creates_new_session_id(self):
|
||||
"""Test that reset() creates a new session with different ID."""
|
||||
storage = HonchoStorage(user_id="test_user_reset")
|
||||
|
||||
original_session_id = storage.session_id
|
||||
|
||||
# Reset
|
||||
storage.reset()
|
||||
|
||||
# Verify new session ID was created
|
||||
assert storage.session_id != original_session_id
|
||||
|
||||
def test_search_with_filters(self):
|
||||
"""Test that search accepts and uses filters parameter."""
|
||||
storage = HonchoStorage(user_id="test_user_filters")
|
||||
|
||||
# Add messages with different metadata
|
||||
storage.save("User question about Python", metadata={"agent": "user", "topic": "python"})
|
||||
storage.save("Assistant answer about Python", metadata={"agent": "assistant", "topic": "python"})
|
||||
storage.save("User question about JavaScript", metadata={"agent": "user", "topic": "javascript"})
|
||||
|
||||
# Search with peer_id filter - filter to only user messages
|
||||
results = storage.search(
|
||||
"programming",
|
||||
limit=10,
|
||||
filters={"peer_id": storage.user.id}
|
||||
)
|
||||
|
||||
# Verify results are returned and in correct format
|
||||
assert isinstance(results, list)
|
||||
for result in results:
|
||||
assert "memory" in result
|
||||
assert "content" in result
|
||||
assert "context" in result
|
||||
assert "metadata" in result
|
||||
|
||||
def test_search_with_metadata_filters(self):
|
||||
"""Test that search works with metadata filters."""
|
||||
storage = HonchoStorage(user_id="test_user_metadata_filters")
|
||||
|
||||
# Add messages with specific metadata
|
||||
storage.save("Important message", metadata={"agent": "user", "priority": "high"})
|
||||
storage.save("Regular message", metadata={"agent": "user", "priority": "low"})
|
||||
|
||||
# Search with metadata filter
|
||||
results = storage.search(
|
||||
"message",
|
||||
limit=10,
|
||||
filters={"metadata": {"priority": "high"}}
|
||||
)
|
||||
|
||||
# Verify results are in correct format
|
||||
assert isinstance(results, list)
|
||||
for result in results:
|
||||
assert "memory" in result
|
||||
assert "metadata" in result
|
||||
|
||||
def test_search_without_filters(self):
|
||||
"""Test that search works without filters."""
|
||||
storage = HonchoStorage(user_id="test_user_no_filters")
|
||||
|
||||
# Add a message
|
||||
storage.save("Test message for search", metadata={"agent": "user"})
|
||||
|
||||
# Search without filters
|
||||
results = storage.search("test", limit=5)
|
||||
|
||||
# Verify it works and returns correct format
|
||||
assert isinstance(results, list)
|
||||
for result in results:
|
||||
assert "memory" in result
|
||||
assert "content" in result
|
||||
|
|
@ -0,0 +1,194 @@
|
|||
"""
|
||||
Tests for Honcho CrewAI Tools
|
||||
|
||||
Tests the CrewAI-Honcho tool integration layer using real Honcho SDK.
|
||||
Focuses on tool interface compliance and result formatting.
|
||||
"""
|
||||
|
||||
from honcho import Honcho
|
||||
from honcho_crewai import (
|
||||
HonchoDialecticTool,
|
||||
HonchoGetContextTool,
|
||||
HonchoSearchTool,
|
||||
)
|
||||
|
||||
|
||||
class TestGetContextTool:
|
||||
"""Tests for HonchoGetContextTool."""
|
||||
|
||||
def test_initialization(self):
|
||||
"""Test that tool initializes with correct attributes."""
|
||||
honcho = Honcho()
|
||||
tool = HonchoGetContextTool(
|
||||
honcho=honcho, session_id="test_session", peer_id="test_peer"
|
||||
)
|
||||
|
||||
assert tool is not None
|
||||
assert tool.name == "get_session_context"
|
||||
assert tool.description is not None
|
||||
assert tool.args_schema is not None
|
||||
|
||||
def test_returns_formatted_context(self):
|
||||
"""Test that tool returns formatted context string."""
|
||||
honcho = Honcho()
|
||||
peer = honcho.peer("context_test_user")
|
||||
session_id = "context_test_session"
|
||||
session = honcho.session(session_id)
|
||||
|
||||
# Add test message
|
||||
session.add_messages([peer.message("Test message for context")])
|
||||
|
||||
# Create and execute tool
|
||||
tool = HonchoGetContextTool(
|
||||
honcho=honcho, session_id=session_id, peer_id="context_test_user"
|
||||
)
|
||||
result = tool._run()
|
||||
|
||||
# Verify result is a formatted string
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
|
||||
class TestDialecticTool:
|
||||
"""Tests for HonchoDialecticTool."""
|
||||
|
||||
def test_initialization(self):
|
||||
"""Test that tool initializes with correct attributes."""
|
||||
honcho = Honcho()
|
||||
tool = HonchoDialecticTool(
|
||||
honcho=honcho, session_id="test_session", peer_id="test_peer"
|
||||
)
|
||||
|
||||
assert tool is not None
|
||||
assert tool.name == "query_peer_knowledge"
|
||||
assert tool.description is not None
|
||||
|
||||
def test_returns_response(self):
|
||||
"""Test that tool returns a response string."""
|
||||
honcho = Honcho()
|
||||
peer = honcho.peer("dialectic_test_user")
|
||||
session_id = "dialectic_test_session"
|
||||
session = honcho.session(session_id)
|
||||
|
||||
# Add test messages
|
||||
session.add_messages([peer.message("I love pizza and Italian food")])
|
||||
|
||||
# Create and execute tool
|
||||
tool = HonchoDialecticTool(
|
||||
honcho=honcho, session_id=session_id, peer_id="dialectic_test_user"
|
||||
)
|
||||
result = tool._run(query="What does the user like?")
|
||||
|
||||
# Verify result is a string
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
|
||||
class TestSearchTool:
|
||||
"""Tests for HonchoSearchTool."""
|
||||
|
||||
def test_initialization(self):
|
||||
"""Test that tool initializes with correct attributes."""
|
||||
honcho = Honcho()
|
||||
tool = HonchoSearchTool(honcho=honcho, session_id="test_session")
|
||||
|
||||
assert tool is not None
|
||||
assert tool.name == "search_session_messages"
|
||||
assert tool.description is not None
|
||||
|
||||
def test_returns_formatted_results(self):
|
||||
"""Test that tool returns formatted search results."""
|
||||
honcho = Honcho()
|
||||
peer = honcho.peer("search_test_user")
|
||||
session_id = "search_test_session"
|
||||
session = honcho.session(session_id)
|
||||
|
||||
# Add test messages
|
||||
session.add_messages([peer.message("I love pizza and pasta")])
|
||||
|
||||
# Create and execute tool
|
||||
tool = HonchoSearchTool(honcho=honcho, session_id=session_id)
|
||||
result = tool._run(query="food", limit=5)
|
||||
|
||||
# Verify result is a formatted string
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
# Should have either results or "No messages found"
|
||||
assert "Search Results" in result or "No messages found" in result
|
||||
|
||||
def test_search_with_filters(self):
|
||||
"""Test that search tool accepts and uses filters parameter."""
|
||||
honcho = Honcho()
|
||||
peer = honcho.peer("search_filter_test_user")
|
||||
session_id = "search_filter_test_session"
|
||||
session = honcho.session(session_id)
|
||||
|
||||
# Add test messages
|
||||
session.add_messages([peer.message("Important message about Python")])
|
||||
|
||||
# Create and execute tool with filters
|
||||
tool = HonchoSearchTool(honcho=honcho, session_id=session_id)
|
||||
result = tool._run(
|
||||
query="Python",
|
||||
limit=5,
|
||||
filters={"peer_id": peer.id}
|
||||
)
|
||||
|
||||
# Verify result is a formatted string
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
def test_search_with_metadata_filters(self):
|
||||
"""Test that search tool works with metadata filters."""
|
||||
honcho = Honcho()
|
||||
peer = honcho.peer("search_metadata_filter_user")
|
||||
session_id = "search_metadata_filter_session"
|
||||
session = honcho.session(session_id)
|
||||
|
||||
# Add test messages with metadata
|
||||
session.add_messages([peer.message("High priority task", metadata={"priority": "high"})])
|
||||
|
||||
# Create and execute tool with metadata filter
|
||||
tool = HonchoSearchTool(honcho=honcho, session_id=session_id)
|
||||
result = tool._run(
|
||||
query="task",
|
||||
limit=5,
|
||||
filters={"metadata": {"priority": "high"}}
|
||||
)
|
||||
|
||||
# Verify result is a formatted string
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
|
||||
class TestToolsWorkTogether:
|
||||
"""Test that all tools can work together."""
|
||||
|
||||
def test_all_tools_in_same_session(self):
|
||||
"""Test that all three tools can be used in the same session."""
|
||||
honcho = Honcho()
|
||||
peer = honcho.peer("combo_test_user")
|
||||
session_id = "combo_test_session"
|
||||
session = honcho.session(session_id)
|
||||
|
||||
# Add messages
|
||||
session.add_messages([peer.message("I enjoy coding in Python")])
|
||||
|
||||
# Create all tools
|
||||
context_tool = HonchoGetContextTool(
|
||||
honcho=honcho, session_id=session_id, peer_id="combo_test_user"
|
||||
)
|
||||
dialectic_tool = HonchoDialecticTool(
|
||||
honcho=honcho, session_id=session_id, peer_id="combo_test_user"
|
||||
)
|
||||
search_tool = HonchoSearchTool(honcho=honcho, session_id=session_id)
|
||||
|
||||
# Execute all tools
|
||||
context_result = context_tool._run()
|
||||
dialectic_result = dialectic_tool._run(query="What does the user like?")
|
||||
search_result = search_tool._run(query="coding", limit=5)
|
||||
|
||||
# Verify all return valid strings
|
||||
assert isinstance(context_result, str) and len(context_result) > 0
|
||||
assert isinstance(dialectic_result, str) and len(dialectic_result) > 0
|
||||
assert isinstance(search_result, str) and len(search_result) > 0
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
## What is Honcho?
|
||||
|
||||
Honcho is an infrastructure layer for building AI agents with social cognition and theory of mind capabilities. It enables personalized AI interactions by building coherent models of user psychology over time. The Honcho MCP server simplifies the integration to just 3 essential functions. Here's how to use them:
|
||||
Honcho is an infrastructure layer for building AI agents with memory and social cognition. It enables personalized AI interactions by building coherent models of user psychology over time. The Honcho MCP server simplifies the integration to just 3 essential functions. Here's how to use them:
|
||||
|
||||
### Step 1: Start New Conversation (First Message Only)
|
||||
|
||||
|
|
@ -21,7 +21,7 @@ Before responding to any user message, you can query for personalization insight
|
|||
```text
|
||||
get_personalization_insights
|
||||
session_id: [SESSION_ID_FROM_STEP_1]
|
||||
query: [YOUR_THEORY_OF_MIND_QUESTION]
|
||||
query: [YOUR_QUESTION]
|
||||
```
|
||||
|
||||
This query takes a bit of time, so it's best to only perform it when you need personalized insights. If the query can be responded to effectively using what you already know about the user, just go ahead and answer it. However, the insights endpoint is extremely perceptive. It has the capability to reveal aspects of the user's personality, historical use of the application you are operating in, and more.
|
||||
|
|
@ -129,7 +129,7 @@ For subsequent messages in the same conversation:
|
|||
|
||||
## Best Practices for Personalization Queries
|
||||
|
||||
Ask theory-of-mind questions that reveal:
|
||||
Ask questions that reveal:
|
||||
|
||||
**Communication Style**: "How formal/casual should I be?" "What does this reveal about their preferences?"
|
||||
|
||||
|
|
@ -151,6 +151,6 @@ Ask theory-of-mind questions that reveal:
|
|||
1. **Always start with `start_conversation` for new conversations**
|
||||
2. **Store every message exchange with `add_turn`**
|
||||
3. **Use `get_personalization_insights` strategically for better responses**
|
||||
4. **Ask thoughtful theory-of-mind questions**
|
||||
4. **Ask thoughtful questions about `peer` representation**
|
||||
5. **Never expose technical details to the user**
|
||||
6. **The system maintains context automatically between sessions**
|
||||
|
|
|
|||
Loading…
Reference in New Issue