Add web chat server and functional tests for HippocampAI#5
Closed
rexdivakar wants to merge 9 commits intomainfrom
Closed
Add web chat server and functional tests for HippocampAI#5rexdivakar wants to merge 9 commits intomainfrom
rexdivakar wants to merge 9 commits intomainfrom
Conversation
- Implemented a Flask web server for a memory-enhanced chat interface with REST API endpoints for sending messages, retrieving history, managing memories, and session control. - Created functional test script to validate HippocampAI installation and basic functionality, including memory creation, configuration loading, and module imports. - Added legacy functional tests to ensure core functionalities work without a running Qdrant instance. - Updated test retrieval to use UTC for datetime handling.
Reviewer's GuideThis PR overhauls project structure and developer workflows by introducing a Flask-based web chat server with functional tests, migrating configuration to Pydantic v2 with helper utilities, enforcing timezone-aware UTC handling, tightening dependency pinning and automated health checks, and standardizing module invocation and documentation across the codebase. Sequence diagram for web chat server REST API interactionssequenceDiagram
participant actor User
participant WebChatServer
participant MemoryEnhancedChat
participant MemoryStore
participant SessionManager
User->>WebChatServer: POST /api/chat/send (message)
WebChatServer->>MemoryEnhancedChat: send_message(user_id, message)
MemoryEnhancedChat->>MemoryStore: store_message(user_id, message)
MemoryEnhancedChat->>SessionManager: update_session(user_id, message)
MemoryEnhancedChat-->>WebChatServer: response
WebChatServer-->>User: chat response
User->>WebChatServer: GET /api/chat/history
WebChatServer->>SessionManager: get_session_history(user_id)
SessionManager-->>WebChatServer: history
WebChatServer-->>User: history response
Class diagram for updated Config and Settings modelsclassDiagram
class Config {
+qdrant_url: str
+collection_facts: str
+collection_prefs: str
+hnsw_m: int
+ef_construction: int
+ef_search: int
+embed_model: str
+embed_quantized: bool
+embed_batch_size: int
+embed_dimension: int
+reranker_model: str
+rerank_cache_ttl: int
+bm25_backend: str
+llm_provider: str
+llm_model: str
+llm_base_url: str
+allow_cloud: bool
+top_k_qdrant: int
+top_k_final: int
+rrf_k: int
+weight_sim: float
+weight_rerank: float
+weight_recency: float
+weight_importance: float
+half_life_prefs: int
+half_life_facts: int
+half_life_events: int
+enable_scheduler: bool
+decay_cron: str
+consolidate_cron: str
+snapshot_cron: str
+get_weights(): Dict[str, float]
+get_half_lives(): Dict[str, int]
}
class Settings {
+project_root: Path
+env_file: str
+config_file: str
+_load_env_file(env_file)
+_load_config_file(config_file)
}
Config <|-- Settings
Class diagram for Memory model with UTC-aware timestampsclassDiagram
class Memory {
+id: str
+user_id: str
+text: str
+memory_type: MemoryType
+category: str
+importance: float
+confidence: float
+tags: List[str]
+created_at: datetime (UTC)
+updated_at: datetime (UTC)
+access_count: int
+metadata: Dict[str, Any]
}
class MemoryType {
<<enum>>
PREFERENCE
FACT
EVENT
}
MemoryType <|-- Memory
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey there - I've reviewed your changes - here's some feedback:
- This PR bundles large refactors, documentation updates, dependency pinning, and a new web server—consider splitting it into smaller focused PRs (e.g. docs/invocation changes, config modernization, web server & tests) to simplify review and tracking.
- There’s duplication between pyproject.toml and requirements.txt—consider removing the requirements.txt or automating its generation from your pyproject to avoid drift.
- Rather than relying on a standalone functional script, add automated integration tests for the new Flask web chat endpoints and include them in CI so that API regressions get caught early.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- This PR bundles large refactors, documentation updates, dependency pinning, and a new web server—consider splitting it into smaller focused PRs (e.g. docs/invocation changes, config modernization, web server & tests) to simplify review and tracking.
- There’s duplication between pyproject.toml and requirements.txt—consider removing the requirements.txt or automating its generation from your pyproject to avoid drift.
- Rather than relying on a standalone functional script, add automated integration tests for the new Flask web chat endpoints and include them in CI so that API regressions get caught early.
## Individual Comments
### Comment 1
<location> `src/hippocampai/utils/time.py:12` </location>
<code_context>
+ return datetime.now(UTC)
+
+
+def ensure_utc(dt: datetime) -> datetime:
+ """Coerce a datetime into UTC."""
+ if dt.tzinfo is None:
</code_context>
<issue_to_address>
**issue:** ensure_utc may not handle datetimes with non-UTC tzinfo as expected.
Replacing tzinfo with UTC does not adjust the time value, so if naive datetimes represent local time, this may cause incorrect conversions.
</issue_to_address>
### Comment 2
<location> `src/hippocampai/utils/scoring.py:17` </location>
<code_context>
def recency_score(created_at: datetime, half_life_days: int) -> float:
"""Exponential decay based on half-life."""
- age_days = (datetime.utcnow() - created_at).total_seconds() / 86400
</code_context>
<issue_to_address>
**issue (bug_risk):** recency_score now expects aware datetimes; ensure all callers provide them.
Passing naive datetimes will result in ensure_utc assigning UTC tzinfo without adjusting the time, potentially causing incorrect age calculations.
</issue_to_address>
### Comment 3
<location> `tests/test_retrieval.py:29` </location>
<code_context>
def test_recency_score():
"""Test recency decay."""
- now = datetime.utcnow()
+ now = datetime.now(UTC)
old = now - timedelta(days=30)
</code_context>
<issue_to_address>
**suggestion (testing):** Consider adding tests for edge cases in recency_score, such as naive datetimes and future dates.
Please add tests for naive datetimes, future dates, and dates far in the past to verify recency_score handles these cases correctly.
</issue_to_address>
### Comment 4
<location> `src/hippocampai/utils/time.py:14-16` </location>
<code_context>
def ensure_utc(dt: datetime) -> datetime:
"""Coerce a datetime into UTC."""
if dt.tzinfo is None:
return dt.replace(tzinfo=UTC)
return dt.astimezone(UTC)
</code_context>
<issue_to_address>
**suggestion (code-quality):** We've found these issues:
- Lift code into else after jump in control flow ([`reintroduce-else`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/reintroduce-else/))
- Replace if statement with if expression ([`assign-if-exp`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/assign-if-exp/))
```suggestion
return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
```
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
…cy_install.py for cleaner output.
…est_install.py for core module imports
… and update import statement for pytest
… pipeline components, and utility functions - Implement tests for configuration loading and validation in `test_config.py` - Create tests for memory models and their functionalities in `test_models.py` - Add tests for package structure and import integrity in `test_package.py` - Develop tests for pipeline components including scoring, extraction, and consolidation in `test_pipeline.py` - Introduce tests for utility functions covering time, scoring, and caching in `test_utils.py`
…es and test files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This pull request introduces several documentation improvements and workflow enhancements to streamline contributor onboarding, clarify project usage, and ensure robust dependency management and testing practices. The most important changes include the addition of a contributor guide, updates to usage instructions to use module-based invocation, and the introduction of an automated dependency health workflow.
Contributor Experience & Documentation:
CONTRIBUTING.mdguide detailing environment setup, coding standards, pull request process, and issue reporting.README.md,docs/CHAT_INTEGRATION.md,docs/CHAT_README.md, anddocs/CONFIGURATION.mdto consistently usepython -m hippocampai.<module>for running CLI and web chat, and to reference code locations within thesrc/hippocampaipackage. [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24]Dependency Management & Testing:
.github/workflows/dependency-health.ymlworkflow to automatically audit dependencies for vulnerabilities and license compliance usingpip-auditandliccheck, running weekly and on relevant pull requests.README.md, including usage of extras for installing optional groups and documenting the CI testing workflow.Logging & Configuration:
logging_config.yamltoconfig/logging_config.yamland updated logger names to use thehippocampainamespace for consistency. Updated documentation references accordingly. [1] [2] [3]Changelog & Packaging:
docs/CHANGELOG.mdto reflect the addition of the contributor guide, standardized timestamps, and improved testing documentation.MANIFEST.into include HTML files in the source distribution.These changes collectively improve onboarding, documentation clarity, dependency safety, and package organization for the project.- Implemented a Flask web server for a memory-enhanced chat interface with REST API endpoints for sending messages, retrieving history, managing memories, and session control.
Summary by Sourcery
Provide Flask-based web chat server and comprehensive test suite for HippocampAI; modernize configuration and timestamp handling; tighten dependency pinning; add CI vulnerability and license audits; and enhance documentation and onboarding resources.
New Features:
Enhancements:
Build:
CI:
Documentation:
Tests: