Typing#137
Conversation
WalkthroughThis update introduces extensive type annotation improvements across the codebase, replacing Changes
Sequence Diagram(s)sequenceDiagram
participant API
participant Agent
participant MirascopeLLM
participant PydanticModel
API->>Agent: chat(query, options)
Agent->>MirascopeLLM: dialectic_call(query, user_repr, context)
MirascopeLLM-->>Agent: LLM response (PydanticModel)
Agent-->>API: Return response/stream
sequenceDiagram
participant Agent
participant MirascopeLLM
participant PydanticModel
Agent->>MirascopeLLM: generate_semantic_queries_llm(query)
MirascopeLLM-->>Agent: SemanticQueries (PydanticModel)
Agent-->>Agent: Extract queries list
Possibly related PRs
Suggested reviewers
Poem
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
src/schemas.py (1)
1-1: Suppressing missing type argument warnings for the entire file
The Pyright directive silences missing type argument errors across this file. If only specific generics require suppression, consider using localized# pyright: ignore[...]comments instead of a file-wide disable.pyproject.toml (1)
68-96: Review BasedPyright configuration
The[tool.basedpyright]section scopes type checking tosrcandtestsand silences ignore-comment warnings. Evaluate if additional noisy checks (e.g.,reportMissingImports,reportUnknownMemberType) should be toggled here to balance strictness and developer ergonomics.src/deriver/queue.py (1)
9-9: Remove unused import.The
typing.Anyimport is not used in this file and should be removed to keep imports clean.-from typing import Any
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (13)
.github/workflows/staticanalysis.yml(1 hunks)migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py(1 hunks)pyproject.toml(2 hunks)src/crud.py(14 hunks)src/deriver/consumer.py(3 hunks)src/deriver/queue.py(4 hunks)src/models.py(10 hunks)src/routers/messages.py(2 hunks)src/routers/sessions.py(5 hunks)src/schemas.py(1 hunks)src/utils/cache.py(4 hunks)src/utils/model_client.py(4 hunks)tests/test_schema_validations.py(1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/routers/sessions.py (1)
Learnt from: dr-frmr
PR: plastic-labs/honcho#131
File: src/routers/sessions.py:206-213
Timestamp: 2025-06-18T20:42:06.406Z
Learning: The `get_or_create_session` function in this codebase is designed to handle both session creation and adding peers to existing sessions. When called with peers, it will add those peers to an existing session rather than creating a duplicate session.
🪛 GitHub Actions: Static Analysis
src/routers/sessions.py
[warning] 2-788: Deprecated types, partially unknown types, missing parameter types, unused parameters, unknown variable types, function calls in default parameter values, and unknown argument types (reportDeprecated, reportUnknownVariableType, reportMissingParameterType, reportUnusedParameter, reportUnknownMemberType, reportCallInDefaultInitializer, reportAny)
src/deriver/queue.py
[warning] 9-377: Multiple warnings about unused call results, unannotated class attributes, partially unknown types, and Any types (reportUnusedCallResult, reportUnannotatedClassAttribute, reportUnknownVariableType, reportAny)
src/routers/messages.py
[warning] 3-364: Deprecated types, partially unknown types, missing parameter types, unused parameters, unknown variable types, and function calls in default parameter values (reportDeprecated, reportUnknownVariableType, reportMissingParameterType, reportUnusedParameter, reportUnknownMemberType, reportCallInDefaultInitializer, reportAny)
src/deriver/consumer.py
[warning] 6-47: Stub file not found for "langfuse.decorators" and multiple Any or partially unknown types and unannotated class attributes (reportMissingTypeStubs, reportAny, reportUnknownVariableType, reportUnannotatedClassAttribute, reportExplicitAny)
src/models.py
[warning] 8-367: Missing stubs, Any types, unannotated class attributes, deprecated types, unknown parameter types, and implicit overrides (reportMissingTypeStubs, reportAny, reportUnannotatedClassAttribute, reportDeprecated, reportUnknownParameterType, reportImplicitOverride, reportExplicitAny)
src/crud.py
[warning] 5-10: "Select" is imported more than once and some types are deprecated or unused imports (reportDuplicateImport, reportDeprecated, reportUnusedImport)
[warning] 23-1231: Multiple warnings about partially unknown types, unused call results, argument types as Any, and deprecated types (reportUnknownMemberType, reportUnusedCallResult, reportAny, reportExplicitAny, reportDeprecated)
🪛 Ruff (0.11.9)
src/deriver/queue.py
9-9: typing.Any imported but unused
Remove unused import: typing.Any
(F401)
src/crud.py
5-5: Redefinition of unused Select from line 4
Remove definition: Select
(F811)
6-6: Redefinition of unused Select from line 5
Remove definition: Select
(F811)
8-8: Redefinition of unused Select from line 6
Remove definition: Select
(F811)
10-10: typing.Tuple imported but unused
Remove unused import: typing.Tuple
(F401)
🪛 Pylint (3.3.7)
src/routers/messages.py
[refactor] 56-56: Too many local variables (25/15)
(R0914)
[refactor] 56-56: Too many branches (14/12)
(R0912)
[refactor] 56-56: Too many statements (61/50)
(R0915)
🪛 GitHub Check: CodeQL
.github/workflows/staticanalysis.yml
[warning] 5-21: Workflow does not contain permissions
Actions job or workflow does not limit the permissions of the GITHUB_TOKEN. Consider setting an explicit permissions block, using the following as a minimal starting point: {{contents: read}}
[warning] 22-37: Workflow does not contain permissions
Actions job or workflow does not limit the permissions of the GITHUB_TOKEN. Consider setting an explicit permissions block, using the following as a minimal starting point: {{contents: read}}
🔇 Additional comments (37)
migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py (1)
8-10: Confirm typing import adjustments
SwitchingSequenceto come fromcollections.abcand isolatingUnionfromtypingaligns with PEP 585 backport conventions on Python 3.9+. Ensure this import pattern is consistently applied in other migration scripts for uniformity.src/utils/cache.py (2)
8-8: Formatting-only change; no effect on functionality.
13-13: Formatting-only change; no effect on functionality.pyproject.toml (1)
39-39: Add BasedPyright as a dev dependency
Pinningbasedpyright>=1.29.4ensures the new static analyzer is installed for both CI and local development. Confirm that this version is compatible with youruv.lockand update accordingly.src/utils/model_client.py (4)
211-211: LGTM: Appropriate use of pyright ignore directive.The
# pyright: ignorecomment correctly suppresses type checking warnings for the Anthropic client call, which is likely due to typing issues in the external library rather than actual code problems.
351-351: LGTM: Consistent type checking suppression.The pyright ignore directive is appropriately applied to the streaming method call, maintaining consistency with the non-streaming method.
456-458: LGTM: Improved code formatting.The parentheses around the conditional expression improve readability while preserving the original logic.
535-537: LGTM: Consistent formatting improvement.The formatting change matches the non-streaming method and enhances code consistency.
tests/test_schema_validations.py (1)
33-36: LGTM: Appropriate test formatting and type suppression.The multi-line formatting improves readability, and the
# pyright: ignorecomment is correctly used since this test intentionally passes invalid data ("not a dict") to verify validation behavior.src/models.py (8)
3-3: LGTM: Necessary import for improved type annotations.The
Anyimport supports the enhanced dictionary type annotations throughout the file.
105-109: LGTM: Enhanced type safety for dictionary fields.The change from
Mapped[dict]toMapped[dict[str, Any]]provides better type clarity for metadata and configuration fields in the Workspace model.
122-132: LGTM: Consistent type improvements for Peer model.The type annotations match the improvements made to the Workspace model, ensuring consistency across the codebase.
157-168: LGTM: Type annotation consistency maintained.The Session model follows the same improved typing pattern as other models in the file.
195-196: LGTM: Message model type improvements.Consistent application of the enhanced dictionary typing pattern.
256-257: LGTM: Collection model type consistency.The type annotations align with the established pattern throughout the file.
287-287: LGTM: Document model type improvement.The
internal_metadatafield follows the same typing enhancement pattern.
338-338: LGTM: QueueItem model type enhancement.The
payloadfield type annotation completes the consistent typing improvements across all models.src/crud.py (5)
77-90: LGTM: Improved type annotations for workspace functions.The enhanced type annotations for filter parameters and return types improve type safety and code clarity.
231-240: LGTM: Consistent type improvements for peer functions.The type annotations follow the same improvement pattern established in the workspace functions.
283-315: LGTM: Enhanced session function type annotations.The type annotations for session-related functions improve type safety and maintain consistency.
719-730: LGTM: Precise return type annotations.The specific tuple type annotations for the session peer configuration function provide clear type information.
1247-1251: LGTM: Comprehensive parameter type annotations.The type annotations for the
get_messagesfunction parameters improve type safety across the message handling functionality.src/routers/sessions.py (5)
208-216: LGTM: Eliminated redundant variable assignments.The code now directly uses
session_idandworkspace_idparameters instead of creating unnecessary local variables, improving code clarity.
239-252: LGTM: Consistent cleanup of redundant assignments.The same improvement pattern is applied consistently across peer management functions.
276-288: LGTM: Continued code simplification.The removal of redundant variable assignments maintains consistency with other functions in the file.
362-366: LGTM: Final cleanup of redundant patterns.The code cleanup is applied consistently throughout all session peer management functions.
448-448: ```shell
#!/bin/bashFind where
messagesis assigned in the function returning SessionContextrg -n "messages\s*=" -A3 src/routers/sessions.py
</details> <details> <summary>src/deriver/consumer.py (4)</summary> `3-3`: **LGTM: Improved typing imports.** Adding `Any` and `Literal` imports supports the more specific type annotations throughout the file. --- `44-44`: **LGTM: Enhanced type specificity.** The change from `dict` to `dict[str, Any]` provides better type safety by explicitly indicating string keys with any value type. --- `64-72`: **LGTM: Improved code clarity and maintainability.** The refactoring from collecting arguments in a list to explicit keyword arguments makes the code more readable and maintainable. This approach is less error-prone and makes the function call more self-documenting. --- `77-81`: **LGTM: Cleaner formatting.** The parentheses around the conditional expression improve readability. </details> <details> <summary>src/routers/messages.py (2)</summary> `28-28`: **LGTM: Consistent typing improvements.** The refinement from `dict` to `dict[str, Any]` for both parameter and return type annotations improves type safety and consistency with similar changes across the codebase. Also applies to: 32-32 --- `56-56`: **LGTM: Enhanced type specificity for payload parameter.** The change from `list[dict]` to `list[dict[str, Any]]` provides better type safety and aligns with the typing improvements made throughout the codebase. </details> <details> <summary>src/deriver/queue.py (4)</summary> `1-1`: **LGTM: Appropriate import for explicit Task typing.** The import of `Task` from `_asyncio` supports the improved type annotations for asyncio tasks. --- `50-50`: **LGTM: More specific asyncio Task typing.** The change from `set[asyncio.Task]` to `set[asyncio.Task[None]]` provides better type specificity by indicating the task return type. --- `68-68`: **LGTM: Consistent Task typing improvement.** The parameter type annotation change from `asyncio.Task` to `asyncio.Task[None]` aligns with the class attribute typing and improves type safety. --- `245-245`: **LGTM: Explicit local variable typing.** The explicit typing of the task variable as `Task[None]` improves code clarity and type checking. </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/crud.py (1)
12-12: Remove duplicate Select import.The
Selectimport fromsqlalchemy.sql.selectableon line 12 is redundant sinceSelectis already imported fromsqlalchemyon line 9. This duplicate import should be removed.Apply this diff to fix the duplicate import:
-from sqlalchemy.sql.selectable import Select
🧹 Nitpick comments (1)
src/routers/sessions.py (1)
447-447: Consider investigating the type mismatch.The
# pyright: ignorecomment suggests there's a type mismatch between the expectedmessagesfield type and what's being assigned. While the ignore is acceptable for now, consider investigating if the type definitions need alignment.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (16)
pyproject.toml(3 hunks)src/agent.py(2 hunks)src/crud.py(18 hunks)src/db.py(1 hunks)src/deriver/queue.py(4 hunks)src/deriver/tom/long_term.py(1 hunks)src/deriver/tom/single_prompt.py(3 hunks)src/exceptions.py(1 hunks)src/routers/messages.py(4 hunks)src/routers/peers.py(3 hunks)src/routers/sessions.py(8 hunks)src/routers/workspaces.py(1 hunks)src/schemas.py(3 hunks)src/security.py(4 hunks)src/utils/history.py(5 hunks)src/utils/model_client.py(13 hunks)
✅ Files skipped from review due to trivial changes (5)
- src/db.py
- src/exceptions.py
- src/deriver/tom/single_prompt.py
- src/utils/history.py
- src/security.py
🚧 Files skipped from review as they are similar to previous changes (4)
- src/schemas.py
- pyproject.toml
- src/deriver/queue.py
- src/utils/model_client.py
🧰 Additional context used
🧠 Learnings (1)
src/routers/sessions.py (1)
Learnt from: dr-frmr
PR: plastic-labs/honcho#131
File: src/routers/sessions.py:206-213
Timestamp: 2025-06-18T20:42:06.406Z
Learning: The `get_or_create_session` function in this codebase is designed to handle both session creation and adding peers to existing sessions. When called with peers, it will add those peers to an existing session rather than creating a duplicate session.
🪛 GitHub Actions: Static Analysis
src/agent.py
[warning] 10-10: Type of "observe" is partially unknown (reportUnknownVariableType)
[warning] 16-16: Type of "tracked_db" is partially unknown (reportUnknownVariableType)
[warning] 17-17: Type of "get_tom_inference" is partially unknown (reportUnknownVariableType)
[warning] 45-51: Type annotation for attributes agent_input, user_representation, chat_history, client, and system_prompt is required because this class is not decorated with @final (reportUnannotatedClassAttribute)
[warning] 327-335: Type of variables and arguments such as "retrieved_facts", "update", and argument types are partially unknown (reportUnknownVariableType, reportUnknownMemberType, reportUnknownArgumentType)
[warning] 418-423: Type of "append" and argument types are partially unknown (reportUnknownMemberType, reportUnknownArgumentType, reportUnknownVariableType)
src/deriver/tom/long_term.py
[warning] 5-211: Type of "observe" is partially unknown; return type partially unknown (reportUnknownVariableType)
src/crud.py
[warning] 12-489: "Select" is imported more than once and types of "metadata" and "configuration" are partially unknown in multiple lines (reportDuplicateImport, reportUnknownMemberType)
src/routers/messages.py
[warning] 7-367: Type of "paginate" and "tracked_db" partially unknown; function calls and mutable objects not allowed within parameter default value expressions; missing type annotations for parameters like "db"; type of variables like "filter" partially unknown (reportUnknownVariableType, reportCallInDefaultInitializer, reportMissingParameterType, reportUnknownMemberType)
src/routers/peers.py
[warning] 12-283: Type of "paginate" partially unknown; function calls and mutable objects not allowed within parameter default value expressions; missing type annotations for parameters like "db"; type of variables like "filter_param", "filter" partially unknown (reportUnknownVariableType, reportCallInDefaultInitializer, reportMissingParameterType, reportUnknownMemberType)
src/routers/sessions.py
[warning] 5-463: Type of "paginate" partially unknown; function calls and mutable objects not allowed within parameter default value expressions; missing type annotations for parameters like "db"; type of variables like "filter", "filter_param" partially unknown (reportUnknownVariableType, reportCallInDefaultInitializer, reportMissingParameterType, reportUnknownMemberType)
src/routers/workspaces.py
[warning] 5-101: Type of "paginate" partially unknown; function calls and mutable objects not allowed within parameter default value expressions; missing type annotations for parameters like "db"; type of variables like "filter_param", "filter" partially unknown (reportUnknownVariableType, reportCallInDefaultInitializer, reportMissingParameterType, reportUnknownMemberType)
🪛 Ruff (0.11.9)
src/crud.py
12-12: Redefinition of unused Select from line 9
(F811)
src/routers/messages.py
313-315: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/peers.py
38-40: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
120-122: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
241-243: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/sessions.py
79-81: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/workspaces.py
55-57: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
🪛 Pylint (3.3.7)
src/routers/messages.py
[refactor] 56-56: Too many local variables (25/15)
(R0914)
[refactor] 56-56: Too many branches (14/12)
(R0912)
[refactor] 56-56: Too many statements (61/50)
(R0915)
🔇 Additional comments (17)
src/agent.py (2)
5-5: LGTM! Modern typing import cleanup.Good removal of unused
Optionalimport as part of the modernization to Python 3.10+ union syntax.
437-437: LGTM! Type annotation modernized correctly.Excellent update from
Optional[str]tostr | None, aligning with modern Python 3.10+ union syntax.src/deriver/tom/long_term.py (1)
30-30: LGTM! Type annotation modernized correctly.Good update from
Optional[list[str]]tolist[str] | None, following the modern Python 3.10+ union syntax.src/routers/workspaces.py (1)
55-55: LGTM! Type annotation modernized correctly.Excellent update from
Optional[schemas.WorkspaceGet]toschemas.WorkspaceGet | None, aligning with modern Python 3.10+ union syntax.src/routers/sessions.py (4)
79-79: LGTM! Type annotation modernized correctly.Good update to
schemas.SessionGet | Nonefollowing modern Python 3.10+ union syntax.
167-167: LGTM! Type annotation modernized correctly.Excellent update from
Optional[str]tostr | None, aligning with modern union syntax.
207-216: LGTM! Clean code improvement.Good cleanup removing redundant variable assignments and using the original parameters directly. This makes the code more concise and clear.
379-379: LGTM! Type annotation modernized correctly.Good update to
int | Nonefollowing modern Python 3.10+ union syntax.src/routers/messages.py (4)
3-3: LGTM! Import statement optimized.Good cleanup removing unused
Optionalimport while keepingAnyfor the explicit type annotations.
28-32: LGTM! Type annotations modernized correctly.Excellent updates to use
dict[str, Any]andstr | Nonesyntax, replacing the olderOptionalpatterns with modern Python 3.10+ union types.
56-56: LGTM! Function signature improved.Good type annotation using
list[dict[str, Any]]for better type clarity and consistency with the modernized typing approach.
313-316: LGTM! Parameter types modernized correctly.Excellent updates from
Optionalto union syntax (schemas.MessageGet | Noneandbool | None), aligning with modern Python 3.10+ standards.src/routers/peers.py (2)
38-40: LGTM! Type annotations successfully modernized.The migration from
Optional[T]toT | Nonesyntax is correct and aligns with modern Python 3.10+ typing conventions.Also applies to: 120-122, 241-243
244-246: Type annotation update looks good.The
bool | Nonesyntax is the modern equivalent ofOptional[bool]and is correctly applied here.src/crud.py (3)
4-4: Good addition of necessary imports.The import of
Anyfrom typing and the explicit model imports (Session,Workspace) are appropriate additions to support the enhanced type annotations.Also applies to: 15-16
74-75: Excellent type annotation modernization.The migration from
Optional[dict[str, str]]todict[str, str] | Noneand similar patterns follows modern Python 3.10+ typing conventions and improves code clarity.Also applies to: 228-229, 280-282, 324-326
75-75: Enhanced return type annotations provide better type safety.The specific
Select[tuple[...]]return type annotations make the expected return types explicit and improve IDE support and type checking accuracy.Also applies to: 229-229, 282-282, 326-326, 689-689
There was a problem hiding this comment.
Actionable comments posted: 2
🔭 Outside diff range comments (1)
src/deriver/tom/embeddings.py (1)
15-21: Remove unusedreplace_duplicatesparameter.The
replace_duplicatesparameter is defined but never used in the method implementation, as flagged by the static analysis.async def save_facts( self, facts: list[str], - replace_duplicates: bool = True, similarity_threshold: float = 0.85, message_id: int | None = None, ) -> None:If this parameter is intended for future use, consider either implementing the functionality or adding a
# noqacomment with an explanation.
🧹 Nitpick comments (3)
src/deriver/tom/embeddings.py (1)
89-89: Consider explicit type annotation for better static analysis.The static analysis is reporting unknown types for the
unique_factslist. Adding an explicit type annotation may help resolve the type inference issues.- unique_facts = [] + unique_facts: list[str] = []src/utils/types.py (1)
10-18: Consider simplifying the decorator implementation.The current implementation adds an unnecessary layer of complexity. The
trackfunction essentially just wrapsai_trackwith a description parameter.Consider this simplified implementation:
def track(description: str) -> Callable[[Callable[P, R]], Callable[P, R]]: - def decorator(f: Callable[P, R]) -> Callable[P, R]: - def _inner(*args: P.args, **kwargs: P.kwargs) -> R: - result: R = ai_track(description)(f)(*args, **kwargs) # pyright: ignore - return result - - return _inner - - return decorator + return ai_track(description)This achieves the same functionality with much cleaner code. If the additional wrapper is intentional for future extensibility, please add comments explaining the design decision.
src/utils/model_client.py (1)
456-458: Improve conditional expression formatting.The parenthesized conditional expressions are well-formatted but could benefit from clearer logic documentation.
Consider adding a comment explaining the logic:
contents=( + # Use list for multiple messages, single content for one message gemini_messages if len(gemini_messages) > 1 else gemini_messages[0] ),Also applies to: 535-537
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (11)
pyproject.toml(3 hunks)src/agent.py(5 hunks)src/dependencies.py(1 hunks)src/deriver/consumer.py(3 hunks)src/deriver/tom/__init__.py(0 hunks)src/deriver/tom/embeddings.py(1 hunks)src/deriver/tom/long_term.py(3 hunks)src/deriver/tom/single_prompt.py(3 hunks)src/utils/history.py(6 hunks)src/utils/model_client.py(14 hunks)src/utils/types.py(1 hunks)
💤 Files with no reviewable changes (1)
- src/deriver/tom/init.py
✅ Files skipped from review due to trivial changes (1)
- src/dependencies.py
🚧 Files skipped from review as they are similar to previous changes (6)
- src/deriver/consumer.py
- src/deriver/tom/long_term.py
- src/agent.py
- src/deriver/tom/single_prompt.py
- pyproject.toml
- src/utils/history.py
🧰 Additional context used
🪛 GitHub Actions: Static Analysis
src/deriver/tom/embeddings.py
[warning] 18-117: "replace_duplicates" is not accessed; Type of "append" is partially unknown; Return type "list[Unknown]" is partially unknown (reportUnusedParameter, reportUnknownMemberType, reportUnknownVariableType)
src/utils/model_client.py
[warning] 92-536: Type annotation for attribute client is required; "extra_headers" is not accessed; Type of variables and functions such as "content", "content_block", "type", "text", "append", "extend", "generate_content", "generate_content_stream" is partially unknown or unknown; Argument type is partially unknown for parameters such as "obj", "messages"; Return type is Any or unknown; Function calls and mutable objects not allowed within parameter default value expression (reportUnannotatedClassAttribute, reportUnusedParameter, reportUnknownMemberType, reportUnknownVariableType, reportUnknownArgumentType, reportAny, reportUnknownParameterType)
🪛 Pylint (3.3.7)
src/utils/model_client.py
[error] 12-12: No name 'genai' in module 'google'
(E0611)
[error] 13-13: No name 'genai' in module 'google'
(E0611)
🔇 Additional comments (5)
src/deriver/tom/embeddings.py (1)
11-13: LGTM! Clean type annotations added.The explicit type annotations for the instance variables are consistent with the constructor parameters and improve type clarity.
src/utils/types.py (1)
13-13: ```shell
#!/bin/bashInstall the Sentry SDK to inspect ai_track’s runtime signature and annotations
pip install sentry-sdk --quiet
python3 - << 'EOF'
import sentry_sdk.ai.monitoring as m
import inspect
from pprint import pprintprint("ai_track signature:", inspect.signature(m.ai_track))
print("ai_track annotations:")
pprint(m.ai_track.annotations)
EOF</details> <details> <summary>src/utils/model_client.py (3)</summary> `68-70`: **Good modernization of type annotations.** The update from `Optional[...]` to `type | None` syntax follows modern Python 3.10+ best practices and improves readability. --- `14-14`: **Address the langfuse import type suppression.** The `# pyright: ignore` comment on the langfuse import suggests type checking issues that should be resolved properly. ```web What is the correct way to import and use langfuse decorators with proper type annotations?
211-211: ```shell
#!/bin/bashLocate import and class definitions for ModelClient and AsyncAnthropic
rg -n "AsyncAnthropic" src/utils/model_client.py
rg -n "class ModelClient" src/utils/model_client.pyShow top of file to inspect imports
sed -n '1,50p' src/utils/model_client.py
</details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
| from google import genai | ||
| from google.genai import types as genai_types |
There was a problem hiding this comment.
Fix the Google Genai import issues.
Static analysis tools report that genai doesn't exist in the google module, which could cause runtime errors.
#!/bin/bash
# Description: Verify the correct import path for Google Genai
# Expected: Find the correct import path or confirm package installation
# Check if the google-generativeai package is installed and what modules it provides
pip show google-generativeai 2>/dev/null || echo "Package not found"
# Search for actual genai imports in the codebase
rg "from google" --type py
# Check the correct import path
python -c "
try:
from google import genai
print('Import successful')
except ImportError as e:
print(f'Import failed: {e}')
try:
import google.generativeai as genai
print('Alternative import successful: google.generativeai')
except ImportError as e2:
print(f'Alternative import failed: {e2}')
"🧰 Tools
🪛 Pylint (3.3.7)
[error] 12-12: No name 'genai' in module 'google'
(E0611)
[error] 13-13: No name 'genai' in module 'google'
(E0611)
🤖 Prompt for AI Agents
In src/utils/model_client.py at lines 12 to 13, the import statement 'from
google import genai' is incorrect and causes static analysis errors. Replace
this import with the correct one: 'import google.generativeai as genai' to match
the actual package structure and avoid runtime import errors. Also, update any
references to 'genai' accordingly to reflect this change.
| self.provider: ModelProvider = provider | ||
| self.model: str = model or DEFAULT_MODELS[provider] | ||
| self.base_url: str | None = base_url | ||
| self.openai_client: AsyncOpenAI | None = None | ||
| self.gemini_client: genai.Client | None = None |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add missing type annotation for the client attribute.
The pipeline failure indicates that the client attribute lacks proper type annotation, which affects type safety.
class ModelClient:
"""A client for interacting with various language model APIs."""
def __init__(
self,
provider: ModelProvider = ModelProvider.ANTHROPIC,
model: str | None = None,
api_key: str | None = None,
base_url: str | None = None,
):
+ self.client: AsyncAnthropic | None = None
self.provider: ModelProvider = provider
self.model: str = model or DEFAULT_MODELS[provider]
self.base_url: str | None = base_url
self.openai_client: AsyncOpenAI | None = None
self.gemini_client: genai.Client | None = NoneCommittable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In src/utils/model_client.py around lines 81 to 85, the attribute `client` is
missing a type annotation, causing type safety issues. Add an explicit type
annotation for the `client` attribute consistent with its expected type,
ensuring it matches the usage context and aligns with other client attributes
like `openai_client` and `gemini_client`.
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (2)
src/deriver/tom/long_term.py (1)
45-104: Clean refactoring to declarative LLM pattern.The migration to mirascope's declarative pattern is well-executed. The prompt structure is clear and comprehensive.
Consider simplifying line 56 for better readability:
- facts_str = "\n".join(f"- {fact}" for fact in facts) if facts else "None available" + facts_str = "\n".join(f"- {fact}" for fact in (facts or [])) or "None available"src/agent.py (1)
209-226: Remove unnecessaryelseblock afterreturn.The
elseblock is redundant since theifblock contains areturnstatement.Apply this diff to improve code readability:
if stream: logger.debug("Calling Dialectic with streaming") response = await dialectic_stream( final_query, user_representation, chat_history ) logger.debug( f"Dialectic stream started after {asyncio.get_event_loop().time() - query_start_time:.2f}s" ) return response - else: - logger.debug("Calling Dialectic with non-streaming") - response = await dialectic_call(final_query, user_representation, chat_history) - query_time = asyncio.get_event_loop().time() - query_start_time - total_time = asyncio.get_event_loop().time() - start_time - logger.debug( - f"Dialectic response received in {query_time:.2f}s (total: {total_time:.2f}s)" - ) - return response + + logger.debug("Calling Dialectic with non-streaming") + response = await dialectic_call(final_query, user_representation, chat_history) + query_time = asyncio.get_event_loop().time() - query_start_time + total_time = asyncio.get_event_loop().time() - start_time + logger.debug( + f"Dialectic response received in {query_time:.2f}s (total: {total_time:.2f}s)" + ) + return response
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (38)
.vscode/settings.json(1 hunks)docs/contributing/error-handling.mdx(3 hunks)migrations/utils.py(5 hunks)migrations/versions/20f89a421aff_rename_metamessage_type_to_label.py(1 hunks)migrations/versions/556a16564f50_add_user_id_and_app_id_to_tables.py(1 hunks)migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py(1 hunks)migrations/versions/a1b2c3d4e5f6_initial_schema.py(1 hunks)migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py(1 hunks)migrations/versions/c3828084f472_add_indexes_for_messages_and_.py(1 hunks)migrations/versions/d429de0e5338_adopt_peer_paradigm.py(1 hunks)pyproject.toml(4 hunks)src/agent.py(11 hunks)src/crud.py(19 hunks)src/deriver/consumer.py(4 hunks)src/deriver/queue.py(4 hunks)src/deriver/tom/__init__.py(0 hunks)src/deriver/tom/conversational.py(1 hunks)src/deriver/tom/embeddings.py(4 hunks)src/deriver/tom/long_term.py(4 hunks)src/deriver/tom/single_prompt.py(3 hunks)src/exceptions.py(1 hunks)src/main.py(7 hunks)src/models.py(13 hunks)src/routers/messages.py(7 hunks)src/routers/peers.py(10 hunks)src/routers/sessions.py(15 hunks)src/routers/workspaces.py(5 hunks)src/schemas.py(6 hunks)src/security.py(5 hunks)src/utils/cache.py(0 hunks)src/utils/history.py(6 hunks)src/utils/model_client.py(0 hunks)src/utils/types.py(1 hunks)tests/conftest.py(5 hunks)tests/routes/test_peers.py(26 hunks)tests/test_agent.py(1 hunks)tests/test_tom.py(1 hunks)tests/utils/test_model_client.py(0 hunks)
💤 Files with no reviewable changes (4)
- src/deriver/tom/init.py
- tests/utils/test_model_client.py
- src/utils/cache.py
- src/utils/model_client.py
✅ Files skipped from review due to trivial changes (11)
- src/deriver/tom/conversational.py
- .vscode/settings.json
- migrations/versions/20f89a421aff_rename_metamessage_type_to_label.py
- migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py
- migrations/versions/c3828084f472_add_indexes_for_messages_and_.py
- migrations/versions/556a16564f50_add_user_id_and_app_id_to_tables.py
- migrations/versions/d429de0e5338_adopt_peer_paradigm.py
- docs/contributing/error-handling.mdx
- migrations/utils.py
- migrations/versions/a1b2c3d4e5f6_initial_schema.py
- src/security.py
🚧 Files skipped from review as they are similar to previous changes (8)
- migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py
- src/utils/types.py
- src/deriver/consumer.py
- src/deriver/tom/embeddings.py
- src/exceptions.py
- src/deriver/queue.py
- pyproject.toml
- src/crud.py
🧰 Additional context used
🪛 Pylint (3.3.7)
tests/conftest.py
[refactor] 265-265: Too many local variables (16/15)
(R0914)
src/deriver/tom/long_term.py
[refactor] 14-14: Too few public methods (0/2)
(R0903)
[refactor] 20-20: Too few public methods (0/2)
(R0903)
[refactor] 28-28: Too few public methods (0/2)
(R0903)
[refactor] 35-35: Too few public methods (0/2)
(R0903)
[refactor] 40-40: Too few public methods (0/2)
(R0903)
src/agent.py
[refactor] 209-226: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
src/deriver/tom/single_prompt.py
[refactor] 27-27: Too few public methods (0/2)
(R0903)
[refactor] 33-33: Too few public methods (0/2)
(R0903)
[refactor] 38-38: Too few public methods (0/2)
(R0903)
[refactor] 43-43: Too few public methods (0/2)
(R0903)
[refactor] 47-47: Too few public methods (0/2)
(R0903)
[refactor] 53-53: Too few public methods (0/2)
(R0903)
[refactor] 61-61: Too few public methods (0/2)
(R0903)
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 72-72: Too few public methods (0/2)
(R0903)
[refactor] 78-78: Too few public methods (0/2)
(R0903)
[refactor] 84-84: Too few public methods (0/2)
(R0903)
[refactor] 88-88: Too few public methods (0/2)
(R0903)
[refactor] 94-94: Too few public methods (0/2)
(R0903)
[refactor] 100-100: Too few public methods (0/2)
(R0903)
src/main.py
[error] 75-75: Using variable 'Event' before assignment
(E0601)
[error] 75-75: Using variable 'Hint' before assignment
(E0601)
src/models.py
[refactor] 100-100: Too few public methods (0/2)
(R0903)
[refactor] 122-122: Too few public methods (1/2)
(R0903)
[refactor] 157-157: Too few public methods (1/2)
(R0903)
[refactor] 191-191: Too few public methods (1/2)
(R0903)
[refactor] 256-256: Too few public methods (0/2)
(R0903)
[refactor] 293-293: Too few public methods (0/2)
(R0903)
[refactor] 340-340: Too few public methods (0/2)
(R0903)
[refactor] 353-353: Too few public methods (0/2)
(R0903)
[refactor] 379-379: Too few public methods (0/2)
(R0903)
src/routers/messages.py
[refactor] 57-57: Too many local variables (25/15)
(R0914)
[refactor] 57-57: Too many branches (14/12)
(R0912)
[refactor] 57-57: Too many statements (61/50)
(R0915)
src/schemas.py
[refactor] 25-25: Too few public methods (0/2)
(R0903)
[refactor] 29-29: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 62-62: Too few public methods (0/2)
(R0903)
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 71-71: Too few public methods (0/2)
(R0903)
[refactor] 85-85: Too few public methods (0/2)
(R0903)
[refactor] 112-112: Too few public methods (0/2)
(R0903)
[refactor] 116-116: Too few public methods (0/2)
(R0903)
[refactor] 120-120: Too few public methods (0/2)
(R0903)
[refactor] 170-170: Too few public methods (0/2)
(R0903)
[refactor] 175-175: Too few public methods (0/2)
(R0903)
[refactor] 180-180: Too few public methods (0/2)
(R0903)
[refactor] 195-195: Too few public methods (0/2)
(R0903)
[error] 226-226: Method 'validate_queries' should have "self" as first argument
(E0213)
[refactor] 214-214: Too few public methods (1/2)
(R0903)
🪛 GitHub Actions: FastAPI Tests with PostgreSQL and uv
tests/routes/test_peers.py
[error] 426-426: Test failure in test_chat: TypeError: object MagicMock can't be used in 'await' expression. The error occurs at 'await dialectic_call' in src/agent.py line 220, indicating a mocked object was incorrectly awaited.
🪛 Ruff (0.11.9)
src/routers/messages.py
314-316: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/peers.py
39-41: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
121-123: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
242-244: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/sessions.py
80-82: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/workspaces.py
56-58: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
🔇 Additional comments (33)
src/routers/workspaces.py (3)
6-6: LGTM! Explicit AsyncSession import added.Good addition for improved type clarity.
27-27: Excellent type annotation improvements!Adding explicit
AsyncSessiontyping to alldbparameters improves type safety and IDE support.Also applies to: 59-59, 84-84, 102-102
56-56: Good modernization of type syntax.Using native union type syntax (
| None) instead ofOptionalis consistent with modern Python typing practices.Note: The static analysis hint about B008 (function calls in argument defaults) can be safely ignored here as this is the standard FastAPI pattern for dependency injection with
Body().src/schemas.py (4)
1-1: Good addition of pyright directive.This helps suppress false positives for Pydantic model attributes.
3-3: LGTM! Import cleanup for modern typing.Removing
Optionalin favor of union syntax is consistent with the modernization goals.
19-20: Excellent dictionary type refinements!Specifying
dict[str, Any]instead of genericdictgreatly improves type safety and clarity throughout the schemas.Also applies to: 26-26, 30-31, 36-39, 56-57, 63-63, 67-68, 75-78, 109-109, 113-113, 117-117, 125-127, 163-163, 165-165, 171-171, 176-177, 184-187, 211-211
22-22: Good addition of pyright ignore comments.These suppress expected warnings for Pydantic
ConfigDictusage patterns.Also applies to: 42-44, 59-59, 80-82, 132-134, 167-167, 190-192, 200-202
src/routers/sessions.py (5)
6-6: LGTM! AsyncSession import added.Consistent with other router files for improved typing.
36-36: Excellent type annotation improvements!Adding explicit
AsyncSessiontyping to all database parameters improves type safety consistently across all endpoints.Also applies to: 83-83, 120-120, 143-143, 167-167, 201-201, 233-233, 269-269, 303-303, 325-325, 357-357, 388-388, 464-464
80-80: Good modernization with union type syntax.Using native union types (
| None) instead ofOptionalis consistent with modern Python practices.Also applies to: 168-169, 380-380
208-217: Good code simplification!Removing redundant variable assignments and using parameters directly makes the code cleaner while maintaining the same functionality.
Also applies to: 239-253, 276-289
448-448: Appropriate pyright ignore comment.This suppresses expected type checking issues for the messages field assignment.
tests/test_tom.py (1)
1-72: Well-structured test module!The tests effectively verify the existence and basic callable behavior of the tom module functions with proper async/await patterns and mocking to avoid actual LLM calls.
Key strengths:
- Proper use of
pytest.mark.asynciofor async functions- Appropriate mocking with
unittest.mock.patch- Clear test documentation with descriptive names
- Verification of both function calls and return values
tests/test_agent.py (1)
1-86: Excellent test coverage for agent module!The tests provide comprehensive coverage of the agent module functions with sophisticated mocking strategies:
Key strengths:
- Proper async/await testing patterns
- Appropriate use of
AsyncMockfor streaming functions- Complex Pydantic object mocking in
test_run_tom_inference_function- Clear separation of concerns with focused test functions
- Good verification of both function calls and data extraction
The Pydantic object mocking in the ToM inference test demonstrates thorough understanding of the new typed interfaces.
src/routers/messages.py (3)
3-3: Excellent type annotation improvements.The addition of explicit imports for
AnyandAsyncSessionsupports the enhanced type safety throughout the file.Also applies to: 8-8
28-33: Good modernization of type annotations.The replacement of
Optional[T]withT | Noneand explicitdict[str, Any]typing improves code clarity and aligns with modern Python typing standards.
272-272: Excellent explicit database session typing.The addition of
AsyncSessiontyping fordbparameters enhances type safety and makes the database dependency explicit.Also applies to: 320-320, 348-348, 368-368
src/main.py (2)
15-16: Excellent use of TYPE_CHECKING for conditional imports.This pattern properly imports Sentry types only for static analysis while avoiding runtime imports.
32-32: Comprehensive function signature typing improvements.The addition of explicit type annotations for parameters and return types enhances code clarity and enables better static analysis.
Also applies to: 75-75, 107-107, 158-158, 168-168, 180-182
tests/conftest.py (2)
207-207: Good explicit typing for async generator.The
AsyncGenerator[tuple[Workspace, Peer], Any]type annotation clearly specifies the fixture's return type.
265-342: Excellent migration to mirascope function mocking.The replacement of class-based
ModelClientmocking with granular function-level mocking for mirascope functions is well-executed. The mock return values are appropriate, including proper Pydantic model instances for ToM inference.src/utils/history.py (3)
61-95: Excellent migration to mirascope LLM framework.The new async functions with
@llm.calland@with_langfusedecorators follow mirascope best practices. The prompt templates are well-structured and the model configuration is appropriate.Also applies to: 98-132
140-140: Good modernization of type annotations.The consistent replacement of
Optional[T]withT | Nonesyntax aligns with modern Python typing standards.Also applies to: 175-177, 327-327
192-200: Well-implemented async LLM call integration.The updated
create_summaryfunction properly awaits the new mirascope functions and handles the response conversion appropriately.src/models.py (4)
99-99: Excellent addition of @Final decorators to model classes.The
@finaldecorator prevents inheritance of ORM models, which is a good practice for maintaining data integrity and preventing unintended modifications to the database schema.Also applies to: 121-121, 156-156, 190-190, 255-255, 292-292, 339-339, 352-352, 378-378
101-101: Good explicit typing of tablename attributes.Adding type annotations to
__tablename__class variables enhances static analysis and code clarity.Also applies to: 123-123, 158-158, 192-192, 257-257, 294-294, 341-341, 354-354
108-112: Excellent improvement of dictionary type annotations.The migration from generic
dictto explicitdict[str, Any]for mapped columns provides better type safety and clarity about the expected data structure.Also applies to: 126-129, 162-165, 201-204
244-244: Good addition of method decorators.The
@overridedecorator on__repr__and type annotations on the event listener function enhance code clarity and type safety.Also applies to: 250-250
src/deriver/tom/long_term.py (1)
14-43: LGTM! Well-structured Pydantic models for type safety.The Pydantic models provide excellent type safety and clear data contracts for the LLM responses. The hierarchical structure with nested models is well-designed.
src/routers/peers.py (1)
13-13: Type annotations improved with explicit AsyncSession typing.The migration from
Optional[T]toT | Noneand explicitAsyncSessiontyping improves code clarity and aligns with modern Python conventions.Also applies to: 39-42, 121-124, 242-248
src/agent.py (1)
35-62: Well-structured migration to mirascope decorators.The refactoring from class-based
Dialecticto decorated functionsdialectic_callanddialectic_streamis clean and follows the new architectural pattern consistently.tests/routes/test_peers.py (1)
3-3: Type annotations enhance test clarity.Adding explicit type annotations for the
sample_datafixture improves code readability and enables better IDE support.Also applies to: 6-6
src/deriver/tom/single_prompt.py (1)
14-107: Comprehensive type modeling with Pydantic.Excellent use of enums and nested Pydantic models to create a strongly-typed interface for ToM inference and user representation. The hierarchical structure clearly defines the expected outputs.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
.github/workflows/staticanalysis.yml (1)
1-20: Add a top-level permissions block to limit GITHUB_TOKEN scopeThis workflow lacks an explicit
permissionsblock, leaving the GITHUB_TOKEN with full write permissions by default. Restrict it to read-only to follow security best practices:+permissions: + contents: read + name: Static Analysis on: [push] jobs: basedpyright: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 # …
🧹 Nitpick comments (1)
.github/workflows/staticanalysis.yml (1)
1-2: Include pull_request trigger for PRsCurrently the workflow only runs on
push. To ensure static analysis runs on pull requests as well, expand the trigger:-on: [push] +on: + push: + pull_request:
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
.github/workflows/staticanalysis.yml(1 hunks)pyproject.toml(4 hunks)tests/conftest.py(13 hunks)tests/integration/test_enqueue.py(16 hunks)tests/routes/test_keys.py(3 hunks)tests/routes/test_messages.py(22 hunks)tests/routes/test_peers.py(26 hunks)tests/routes/test_scoped_api.py(11 hunks)tests/routes/test_sessions.py(29 hunks)tests/routes/test_validation_api.py(7 hunks)tests/routes/test_workspaces.py(16 hunks)tests/test_agent.py(1 hunks)
✅ Files skipped from review due to trivial changes (7)
- tests/routes/test_keys.py
- tests/routes/test_messages.py
- tests/routes/test_validation_api.py
- tests/routes/test_scoped_api.py
- tests/routes/test_workspaces.py
- tests/integration/test_enqueue.py
- tests/routes/test_sessions.py
🚧 Files skipped from review as they are similar to previous changes (3)
- tests/test_agent.py
- pyproject.toml
- tests/routes/test_peers.py
🧰 Additional context used
📓 Path-based instructions (1)
`tests/conftest.py`: Define pytest fixtures in tests/conftest.py.
tests/conftest.py: Define pytest fixtures in tests/conftest.py.
tests/conftest.py
🪛 Pylint (3.3.7)
tests/conftest.py
[refactor] 187-187: Too few public methods (0/2)
(R0903)
🪛 GitHub Check: CodeQL
.github/workflows/staticanalysis.yml
[warning] 5-20: Workflow does not contain permissions
Actions job or workflow does not limit the permissions of the GITHUB_TOKEN. Consider setting an explicit permissions block, using the following as a minimal starting point: {{contents: read}}
🔇 Additional comments (17)
tests/conftest.py (17)
3-6: LGTM! Well-organized import additions for type safety.The import additions properly support the comprehensive type annotation improvements throughout the file. The organization follows good practices with collections.abc imports for modern Python typing.
43-46: LGTM! Proper type annotations for the TestHandler class.The type annotations correctly specify
list[logging.LogRecord]using modern Python 3.10+ union syntax and properly type theemitmethod parameter.
75-76: LGTM! Consistent type annotation for database URL parameter.The function signature correctly uses the
URLtype from SQLAlchemy, maintaining consistency with other database-related functions.
96-96: LGTM! Proper async function type annotation.The function signature correctly types the database URL parameter and maintains consistency with the synchronous
create_test_databasefunction.
148-148: LGTM! Appropriate fixture dependency typing.The type annotation correctly specifies
AsyncEnginefor the database engine dependency, ensuring type safety in fixture usage.
157-157: LGTM! Consistent session typing for test client fixture.The type annotation properly specifies
AsyncSessionfor the database session dependency, maintaining type consistency across fixtures.
162-164: LGTM! Complete type annotations for exception handler.The exception handler function properly types both the request parameter and the exception parameter, with appropriate pyright ignore for the unused request parameter.
187-188: LGTM! Minimal but functional AuthClient extension.The AuthClient class appropriately extends TestClient with a single typed attribute for authentication type tracking. The minimal design is appropriate for its specific testing purpose.
199-203: LGTM! Comprehensive type annotations for auth fixture parameters.All fixture parameters are properly typed, including the pytest-specific types for
FixtureRequestandMonkeyPatch, ensuring complete type safety.
229-231: LGTM! Proper async generator typing for sample data.The return type annotation correctly specifies
AsyncGenerator[tuple[Workspace, Peer], Any], properly typing both the yielded value and the send type.
258-261: LGTM! Improved clarity by replacing lambda with named function.The change from a lambda to a proper named function improves readability and type safety while maintaining the same functionality for the Langfuse mock decorator.
373-373: LGTM! Proper session type annotation for mock fixture.The type annotation correctly specifies
AsyncSessionfor the database session parameter, maintaining consistency with other database-related fixtures.
378-378: LGTM! Appropriate optional parameter typing for mock context.The type annotation correctly uses the modern union syntax
str | Nonefor the optional parameter, maintaining consistency with the updated typing approach.
393-393: LGTM! Consistent parameter typing for mock CRUD function.The type annotations properly specify the parameter types while using an underscore for the unused session parameter, following good practices for mock implementations.
421-422: LGTM! Updated mocking to match agent refactoring.The changes from class method mocks (
Dialectic.call/Dialectic.stream) to function-level mocks (dialectic_call/dialectic_stream) correctly align with the broader refactoring mentioned in the AI summary.
436-436: LGTM! Consistent mock return value structure.The mock return value uses
MagicMock(content="...")structure, which aligns with the same pattern used in themock_mirascope_functionsfixture, ensuring consistency across mocks.
292-369: Comprehensive mirascope function mocking - verify import paths and function signatures.This extensive fixture replaces the previous ModelClient mocking with specific mirascope function mocks. The implementation is thorough and includes proper Pydantic object construction for type safety.
However, ensure that all the patched function paths and return value structures match the actual implementation.
#!/bin/bash # Verify that all mocked function paths exist and signatures are correct echo "Checking if mocked functions exist in the codebase..." # Check main mirascope functions echo "=== History functions ===" ast-grep --pattern 'def create_short_summary($$$)' ast-grep --pattern 'def create_long_summary($$$)' echo "=== Tom single prompt functions ===" ast-grep --pattern 'def tom_inference($$$)' ast-grep --pattern 'def user_representation_inference($$$)' ast-grep --pattern 'def get_tom_inference_single_prompt($$$)' ast-grep --pattern 'def get_user_representation_single_prompt($$$)' echo "=== Tom long term functions ===" ast-grep --pattern 'def get_user_representation_long_term($$$)' ast-grep --pattern 'def extract_facts_long_term($$$)' echo "=== Agent functions ===" ast-grep --pattern 'def dialectic_call($$$)' ast-grep --pattern 'def dialectic_stream($$$)' ast-grep --pattern 'def generate_semantic_queries_llm($$$)' echo "=== Checking Pydantic models ===" ast-grep --pattern 'class TomInferenceOutput($$$)' ast-grep --pattern 'class CurrentState($$$)' ast-grep --pattern 'class TentativeInference($$$)'
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
src/routers/peers.py (4)
42-45: Type annotation modernization looks good, but address the B008 warning.The union syntax
schemas.PeerGet | Noneis a good modernization, and the explicitAsyncSessiontyping improves type safety. However, the static analysis warning about usingBody()in argument defaults is valid.Consider refactoring to avoid function calls in defaults:
- options: schemas.PeerGet | None = Body( - None, description="Filtering options for the peers list" - ), + options: schemas.PeerGet | None = Body(None, description="Filtering options for the peers list"),Or move the
Body()call inside the function if more complex logic is needed.
124-127: Good type modernization, but address the B008 warning.The union syntax and explicit
AsyncSessiontyping are improvements. However, the same B008 warning applies here regardingBody()in argument defaults.Apply similar refactoring as suggested for the previous function.
266-272: Excellent type modernization, but address the B008 warning.All the type annotation updates are good improvements:
- Union syntax for optional parameters is more modern
- Explicit
AsyncSessiontyping improves clarity- Consistent pattern across the codebase
However, the B008 warning about
Body()in argument defaults should be addressed as mentioned in previous comments.
1-340: Excellent type annotation modernization with one concern to address.This PR successfully modernizes the type annotations across all peer endpoints:
✅ Achievements:
- Consistent migration from
Optional[T]toT | Noneunion syntax- Explicit
AsyncSessiontyping for alldbparameters- Improved type safety and static analysis support
- Consistent pattern across all endpoints
⚠️ Concern to address:
The Ruff B008 warnings aboutBody()function calls in argument defaults are valid. These should be refactored to avoid potential issues with FastAPI's dependency injection system.Overall, this is a high-quality modernization that significantly improves the codebase's type safety.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/routers/peers.py(10 hunks)tests/conftest.py(13 hunks)tests/test_agent.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/test_agent.py
🧰 Additional context used
📓 Path-based instructions (2)
`tests/conftest.py`: Define pytest fixtures in tests/conftest.py.
tests/conftest.py: Define pytest fixtures in tests/conftest.py.
tests/conftest.py
`src/routers/*.py`: API endpoints should be implemented as separate modules within the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) havi...
src/routers/*.py: API endpoints should be implemented as separate modules within the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own file.
src/routers/peers.py
🪛 Pylint (3.3.7)
tests/conftest.py
[refactor] 187-187: Too few public methods (0/2)
(R0903)
[refactor] 292-292: Too many local variables (16/15)
(R0914)
🪛 Ruff (0.11.9)
src/routers/peers.py
42-44: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
124-126: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
266-268: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
🔇 Additional comments (14)
tests/conftest.py (7)
3-28: LGTM! Comprehensive type annotation improvements.The import section has been properly updated with modern type annotations, including the use of
collections.abcimports and union syntax. The type annotations are consistent and follow Python 3.10+ best practices.
187-188: AuthClient class implementation is minimal but functional.The
AuthClientclass is a simple subclass ofTestClientwith an optionalauth_typeattribute. While pylint flags this for having too few public methods, this is appropriate for a test utility class that only needs to extend the base functionality with one additional attribute.
292-374: Excellent refactoring of mocking strategy from ModelClient to Mirascope.This comprehensive fixture successfully replaces the old
mock_model_clientwith targeted mocking of individual Mirascope functions. Key strengths:
- Proper Pydantic object creation: Creates actual
TomInferenceOutputobjects with correct structure- Comprehensive coverage: Mocks all necessary LLM functions from different modules
- Async support: Correctly handles async mocking with
AsyncMock- Return value diversity: Provides appropriate mock responses for different function types
The high number of local variables (16) is justified given the comprehensive nature of this mocking fixture.
417-452: Consistent updates to agent API call mocking.The changes properly align with the migration from class-based to function-based LLM calls:
- Updates
dialectic_callanddialectic_streammocking to use function-level patches- Maintains consistent mock return value structures
- Properly handles async mocking patterns
This maintains test isolation while supporting the new architecture.
162-164: Appropriate use of pyright ignore for test exception handler.The
pyright: ignorecomment is correctly used here since the test exception handler intentionally discards the request parameter, which is a common pattern in FastAPI exception handlers during testing.
148-153: Proper async fixture typing.The
db_sessionfixture is correctly typed withAsyncEngineparameter and proper async context management. The fixture scope and cleanup logic are appropriate for test isolation.
229-231: Well-typed sample data fixture.The
sample_datafixture has proper async generator typing withAsyncGenerator[tuple[Workspace, Peer], Any], which correctly represents the yielded tuple type and follows pytest async fixture patterns.src/routers/peers.py (7)
16-16: LGTM: Import supports type annotation improvements.The explicit import of
AsyncSessionis correctly added to support the type annotations throughout the file.
68-68: LGTM: Explicit type annotation improves clarity.The explicit
AsyncSessiontyping for thedbparameter enhances type safety and consistency across endpoints.
105-105: LGTM: Consistent type annotation improvement.The explicit
AsyncSessiontyping maintains consistency with other endpoints.
171-171: LGTM: Type annotation consistency maintained.The explicit
AsyncSessiontyping is consistent with the pattern across all endpoints.
219-219: LGTM: Consistent typing improvement.The explicit
AsyncSessiontype annotation maintains the pattern established across other endpoints.
308-308: LGTM: Type annotation consistency.The explicit
AsyncSessiontyping is consistent with the improvements across all endpoints.
334-334: LGTM: Final type annotation improvement.The explicit
AsyncSessiontyping completes the consistent pattern across all endpoints in the file.
|
Looks good to me. There's a few places in the deriver code where Coderabbit is saying we should switch from |
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (2)
src/deriver/tom/long_term.py (1)
107-111: Decorator migration completed successfully.The function now uses the
@trackdecorator as suggested in previous reviews, maintaining consistency with the new telemetry approach across the codebase.src/deriver/tom/single_prompt.py (1)
109-113: Decorator migration completed successfully.The function now uses the
@trackdecorator as suggested in previous reviews, replacing the legacy@ai_trackdecorator and maintaining consistency with the updated telemetry approach.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/deriver/tom/long_term.py(4 hunks)src/deriver/tom/single_prompt.py(3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/deriver/tom/*`: Implement different Theory of Mind (ToM) methods in src/deriver/tom/.
src/deriver/tom/*: Implement different Theory of Mind (ToM) methods in src/deriver/tom/.
src/deriver/tom/long_term.pysrc/deriver/tom/single_prompt.py
🪛 Ruff (0.11.9)
src/deriver/tom/long_term.py
6-6: sentry_sdk.ai.monitoring.ai_track imported but unused
Remove unused import: sentry_sdk.ai.monitoring.ai_track
(F401)
src/deriver/tom/single_prompt.py
7-7: sentry_sdk.ai.monitoring.ai_track imported but unused
Remove unused import: sentry_sdk.ai.monitoring.ai_track
(F401)
🪛 GitHub Check: basedpyright
src/deriver/tom/long_term.py
[warning] 6-6:
Import "ai_track" is not accessed (reportUnusedImport)
src/deriver/tom/single_prompt.py
[warning] 7-7:
Import "ai_track" is not accessed (reportUnusedImport)
🪛 Flake8 (7.2.0)
src/deriver/tom/long_term.py
[error] 6-6: 'sentry_sdk.ai.monitoring.ai_track' imported but unused
(F401)
src/deriver/tom/single_prompt.py
[error] 7-7: 'sentry_sdk.ai.monitoring.ai_track' imported but unused
(F401)
🪛 Pylint (3.3.7)
src/deriver/tom/long_term.py
[refactor] 14-14: Too few public methods (0/2)
(R0903)
[refactor] 20-20: Too few public methods (0/2)
(R0903)
[refactor] 28-28: Too few public methods (0/2)
(R0903)
[refactor] 35-35: Too few public methods (0/2)
(R0903)
[refactor] 40-40: Too few public methods (0/2)
(R0903)
src/deriver/tom/single_prompt.py
[refactor] 27-27: Too few public methods (0/2)
(R0903)
[refactor] 33-33: Too few public methods (0/2)
(R0903)
[refactor] 38-38: Too few public methods (0/2)
(R0903)
[refactor] 43-43: Too few public methods (0/2)
(R0903)
[refactor] 47-47: Too few public methods (0/2)
(R0903)
[refactor] 53-53: Too few public methods (0/2)
(R0903)
[refactor] 61-61: Too few public methods (0/2)
(R0903)
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 72-72: Too few public methods (0/2)
(R0903)
[refactor] 78-78: Too few public methods (0/2)
(R0903)
[refactor] 84-84: Too few public methods (0/2)
(R0903)
[refactor] 88-88: Too few public methods (0/2)
(R0903)
[refactor] 94-94: Too few public methods (0/2)
(R0903)
[refactor] 100-100: Too few public methods (0/2)
(R0903)
🪛 GitHub Actions: Static Analysis
src/deriver/tom/long_term.py
[warning] 6-6: Import "ai_track" is not accessed (reportUnusedImport)
src/deriver/tom/single_prompt.py
[warning] 7-7: Import "ai_track" is not accessed (reportUnusedImport)
🔇 Additional comments (8)
src/deriver/tom/long_term.py (3)
14-43: Well-structured Pydantic models for LLM responses.The introduction of strongly-typed Pydantic models (
PotentialSurprise,UserRepresentation,InformationPiece, etc.) is excellent for ensuring structured and validated LLM responses. The models follow good practices with appropriate field types and clear naming.
45-49: Good migration to declarative LLM calls.The function successfully uses the new
@trackdecorator and@llm.callpattern with structured response models, which is a significant improvement over the previous imperative approach.
54-54: Modern union syntax correctly applied.The use of
list[str] | Nonefollows Python 3.10+ type annotation best practices.src/deriver/tom/single_prompt.py (5)
14-24: Well-designed enums for type safety.The introduction of
InfoTypeandCertaintyLevelenums provides excellent type safety and makes the code more maintainable by preventing invalid values.
26-107: Comprehensive Pydantic model hierarchy.The extensive set of Pydantic models creates a well-structured schema for ToM inference and user representation outputs. The models are properly nested and use appropriate field types, providing strong typing for LLM responses.
158-163: Clean wrapper function implementation.The wrapper function provides a clean interface while leveraging the declarative LLM call underneath, returning the structured
TomInferenceOutputtype.
166-172: Consistent use of new decorator pattern.The
user_representation_inferencefunction correctly uses the@trackand@with_langfusedecorators with the@llm.callpattern, maintaining consistency across the codebase.
241-244: Appropriate JSON serialization for output.The function correctly returns
model_dump_json()to provide serialized output while maintaining the benefits of structured Pydantic validation internally.
There was a problem hiding this comment.
Actionable comments posted: 0
🔭 Outside diff range comments (2)
CLAUDE.md (2)
120-125: Doc still referencesutils/model_client.py, which was deleted in this PR
model_client.py(lines 124-125) is no longer part of the codebase, yet the file tree still lists it and labels it “LLM client abstraction”. This will quickly become stale and mislead new contributors.- └── model_client.py # LLM client abstraction + └── llm.py # Mirascope-based LLM helpers (see agent.py / utils/)Please update the tree (and any related prose) to match the new Mirascope integration.
140-145: Out-of-date architectural decision noteBullet 4 still says “Model client supports multiple LLM providers”, but the PR removed that abstraction in favour of direct Mirascope calls with decorators. Suggest aligning wording:
-4. **Provider Abstraction**: Model client supports multiple LLM providers +4. **Provider Abstraction**: Mirascope decorators allow swapping LLM providers behind a type-safe interface
🧹 Nitpick comments (1)
CLAUDE.md (1)
21-23: Minor wording duplication (“observe”)Language-tool flagged the phrase “observation settings (which peers observe which others)”. Consider a lighter wording:
-Configurable observation settings (which peers observe which others) +Configurable visibility settings (which peers can see one another)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
CLAUDE.md(10 hunks)
🧰 Additional context used
🪛 LanguageTool
CLAUDE.md
[style] ~22-~22: The words ‘observation’ and ‘observe’ are quite similar. Consider replacing ‘observe’ with a different word.
Context: ...rable observation settings (which peers observe which others) - Flexible identity manag...
(VERB_NOUN_SENT_LEVEL_REP)
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/agent.py (1)
203-212: Remove unnecessary else after return.The else clause is unnecessary since the if block returns. This improves code readability and follows Python best practices.
Apply this diff:
if stream: logger.debug("Calling Dialectic with streaming") response = await dialectic_stream( final_query, user_representation, chat_history ) return response - else: - logger.debug("Calling Dialectic with non-streaming") - response = await dialectic_call(final_query, user_representation, chat_history) - return response + logger.debug("Calling Dialectic with non-streaming") + response = await dialectic_call(final_query, user_representation, chat_history) + return response
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/agent.py(11 hunks)src/crud.py(19 hunks)src/deriver/tom/long_term.py(4 hunks)src/deriver/tom/single_prompt.py(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/crud.py
🧰 Additional context used
📓 Path-based instructions (2)
`src/deriver/tom/*`: Implement different Theory of Mind (ToM) methods in src/deriver/tom/.
src/deriver/tom/*: Implement different Theory of Mind (ToM) methods in src/deriver/tom/.
src/deriver/tom/long_term.pysrc/deriver/tom/single_prompt.py
`src/agent.py`: Implement the Dialectic API logic in src/agent.py.
src/agent.py: Implement the Dialectic API logic in src/agent.py.
src/agent.py
🪛 Pylint (3.3.7)
src/deriver/tom/long_term.py
[refactor] 13-13: Too few public methods (0/2)
(R0903)
[refactor] 19-19: Too few public methods (0/2)
(R0903)
[refactor] 27-27: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 39-39: Too few public methods (0/2)
(R0903)
src/deriver/tom/single_prompt.py
[refactor] 26-26: Too few public methods (0/2)
(R0903)
[refactor] 32-32: Too few public methods (0/2)
(R0903)
[refactor] 37-37: Too few public methods (0/2)
(R0903)
[refactor] 42-42: Too few public methods (0/2)
(R0903)
[refactor] 46-46: Too few public methods (0/2)
(R0903)
[refactor] 52-52: Too few public methods (0/2)
(R0903)
[refactor] 60-60: Too few public methods (0/2)
(R0903)
[refactor] 65-65: Too few public methods (0/2)
(R0903)
[refactor] 71-71: Too few public methods (0/2)
(R0903)
[refactor] 77-77: Too few public methods (0/2)
(R0903)
[refactor] 83-83: Too few public methods (0/2)
(R0903)
[refactor] 87-87: Too few public methods (0/2)
(R0903)
[refactor] 93-93: Too few public methods (0/2)
(R0903)
[refactor] 99-99: Too few public methods (0/2)
(R0903)
src/agent.py
[refactor] 203-212: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
🔇 Additional comments (17)
src/deriver/tom/long_term.py (4)
3-7: Excellent migration to mirascope and modern type annotations.The imports are clean and properly organized, using the new mirascope library and track decorator as intended by the refactoring.
13-42: Well-structured Pydantic models for LLM response parsing.The models provide strong typing for the LLM responses, with clear hierarchical structure from basic data types (
PotentialSurprise) to complex aggregations (FactExtraction). This eliminates the need for manual JSON/XML parsing and improves type safety.
44-54: Proper implementation of the new decorative LLM call pattern.The function correctly uses the new decorator stack (
@track,@with_langfuse,@llm.call) and modernized type annotations (list[str] | None). The decorator configuration specifies the appropriate model and provider.
106-111: Consistent decorator usage across functions.Good consistency in applying the same decorator pattern for the fact extraction function, using a different provider/model combination which is appropriate for this specific task.
src/agent.py (6)
6-18: Clean import organization with proper mirascope integration.The imports are well-organized and include all necessary components for the new mirascope-based approach. The transition from manual client management to declarative LLM calls is properly reflected.
35-48: Well-implemented dialectic call function with proper decorators.The function correctly implements the new declarative pattern with appropriate decorators and returns a well-structured prompt template. The provider and model selection is appropriate for the dialectic functionality.
50-63: Consistent streaming implementation.Good consistency with the non-streaming version, properly adding the
stream=Trueparameter to enable streaming responses while maintaining the same core functionality.
65-79: Effective semantic query generation with structured response.The function properly uses the
response_model=list[str]to ensure structured output parsing, eliminating the need for manual JSON parsing in the calling code.
290-308: Proper integration with new Pydantic response models.The code correctly handles the structured response from
get_tom_inference_single_prompt, extracting specific fields from the Pydantic model to create a coherent prediction summary. This shows good adaptation to the new schema-driven approach.
390-409: Robust response handling with backward compatibility.The implementation properly handles both new Pydantic response models and provides fallback to XML parsing for backward compatibility. This ensures smooth migration without breaking existing functionality.
src/deriver/tom/single_prompt.py (7)
2-8: Clean imports with proper mirascope integration.The imports are well-organized and include all necessary components for the new approach. The transition from manual client usage to declarative LLM calls is properly reflected in the import structure.
13-57: Comprehensive Pydantic model structure for ToM inference.The models provide excellent type safety and structure for Theory of Mind inference outputs. The hierarchical design from basic components (
CurrentState,TentativeInference) to the completeTomInferenceOutputensures robust parsing and validation of LLM responses.
59-106: Well-designed user representation models with proper categorization.The models effectively capture the complexity of user representation with appropriate enums (
InfoType,CertaintyLevel) and structured nested objects. This provides much better type safety than the previous XML/JSON parsing approach.
108-155: Proper implementation of the new LLM call pattern for ToM inference.The function correctly implements the decorator stack and returns a well-structured prompt. The use of
response_model=TomInferenceOutputensures automatic parsing into the defined Pydantic structure.
157-162: Clean wrapper function maintaining backward compatibility.The wrapper function provides a clean interface while leveraging the new decorated LLM call underneath. This maintains API compatibility while benefiting from the new structured approach.
165-233: Comprehensive user representation inference with detailed prompt structure.The function provides detailed instructions and structured output format that aligns perfectly with the Pydantic models. The prompt is well-designed to guide the LLM in producing the expected structured output.
235-243: Effective wrapper function with JSON serialization.The wrapper function properly calls the new decorated function and returns JSON serialization, maintaining compatibility with existing code that expects JSON output while leveraging the new structured approach.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
src/agent.py (1)
200-209: Consider simplifying the conditional logic.The explicit logging in both branches is helpful for debugging, but the conditional structure could be simplified.
- if stream: - logger.debug("Calling Dialectic with streaming") - response = await dialectic_stream( - final_query, user_representation, chat_history - ) - return response - else: - logger.debug("Calling Dialectic with non-streaming") - response = await dialectic_call(final_query, user_representation, chat_history) - return response + if stream: + logger.debug("Calling Dialectic with streaming") + return await dialectic_stream(final_query, user_representation, chat_history) + + logger.debug("Calling Dialectic with non-streaming") + return await dialectic_call(final_query, user_representation, chat_history)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (7)
.github/workflows/staticanalysis.yml(1 hunks).vscode/tasks.json(1 hunks)pyproject.toml(4 hunks)src/agent.py(10 hunks)src/deriver/tom/__init__.py(2 hunks)src/deriver/tom/conversational.py(3 hunks)src/routers/peers.py(11 hunks)
✅ Files skipped from review due to trivial changes (2)
- .vscode/tasks.json
- .github/workflows/staticanalysis.yml
🚧 Files skipped from review as they are similar to previous changes (2)
- src/deriver/tom/conversational.py
- src/deriver/tom/init.py
🧰 Additional context used
📓 Path-based instructions (1)
`src/routers/*.py`: API endpoints should be implemented in the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own module.
src/routers/*.py: API endpoints should be implemented in the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own module.
src/routers/peers.py
🪛 Pylint (3.3.7)
src/agent.py
[refactor] 58-58: Too few public methods (0/2)
(R0903)
[refactor] 200-209: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
🪛 Ruff (0.11.9)
src/routers/peers.py
42-44: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
124-126: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
267-269: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
🔇 Additional comments (14)
pyproject.toml (4)
9-9: LGTM: Python version upgrade enables modern type annotations.The upgrade to Python 3.10 minimum requirement is consistent with the codebase's adoption of native union syntax (
|) throughout the project.
25-27: LGTM: Dependency consolidation with mirascope.The replacement of individual LLM provider packages with the unified
mirascopepackage simplifies dependency management while maintaining provider support through extras.
38-38: LGTM: Enhanced static analysis with basedpyright.The addition of
basedpyrightfor improved type checking is a solid improvement over standard mypy.
67-98: LGTM: Well-configured basedpyright setup.The configuration is comprehensive and well-documented, with appropriate strictness levels and sensible exclusions for external libraries that may not have complete type stubs.
src/routers/peers.py (3)
15-16: LGTM: Updated imports for mirascope integration.The import changes align with the migration from custom streaming to mirascope's Stream abstraction.
42-45: LGTM: Modernized type annotations.The replacement of
Optional[T]withT | Nonesyntax is consistent with the Python 3.10+ modernization throughout the codebase.
192-196: LGTM: Improved streaming logic with mirascope.The streaming logic is more robust with explicit type checking and proper error handling for unexpected stream types.
src/agent.py (7)
28-40: LGTM: Clean migration to mirascope decorators.The new
@llm.calldecorator approach is much cleaner than the previous class-based implementation, with proper tracking and Langfuse integration.
43-55: LGTM: Consistent streaming implementation.The streaming function follows the same pattern as the non-streaming version, maintaining consistency in the API.
58-75: LGTM: Structured response with Pydantic models.The use of Pydantic models for structured LLM responses is a significant improvement over manual JSON parsing, providing better type safety and validation.
85-85: LGTM: Improved return type annotations.The union type
llm.Stream | llm.CallResponseclearly indicates the possible return types based on the streaming parameter.
287-301: LGTM: Improved structured response handling.The new approach using Pydantic model attributes is much more robust than XML parsing, with proper fallback handling for different response formats.
324-338: LGTM: Better error handling for LLM calls.The structured response handling with fallback to the original query on errors is a good defensive programming practice.
387-405: LGTM: Backward compatibility with structured responses.The implementation properly handles both new Pydantic response models and legacy XML parsing, ensuring smooth migration.
There was a problem hiding this comment.
Actionable comments posted: 8
🔭 Outside diff range comments (1)
src/agent.py (1)
293-293: Fix undefined function call.The pipeline failure indicates
get_tom_inferenceis not defined.The function call should likely be:
- tom_inference_response = await get_tom_inference( + tom_inference_response = await get_tom_inference_single_prompt(And add the missing import:
+from src.deriver.tom.single_prompt import get_tom_inference_single_prompt
♻️ Duplicate comments (2)
src/schemas.py (1)
231-231: The field validator method signature is correct.Despite the static analysis error, this method is correctly defined as a classmethod with
clsas the first parameter, which is the proper signature for@field_validatorin Pydantic v2. The static analysis tool is producing a false positive.src/routers/messages.py (1)
314-316: Body(...) usage in default arguments persists.This issue was previously identified and still needs to be addressed. Using
Body(...)in argument defaults causes the function to be called at import time rather than request time.
🧹 Nitpick comments (2)
migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py (1)
103-111: Consider wrapping raw SQL insa.text()for consistency & safety.Alembic happily accepts raw strings, but using
sqlalchemy.text()makes intent explicit, aligns with other calls in this file, and enables SQL-lint tooling to run parameter checks.- op.execute( - """ + op.execute( + sa.text( UPDATE metamessages m SET session_id = msg.session_id FROM messages msg WHERE m.message_id = msg.public_id AND m.session_id IS NULL - """ + ) )(Not blocking – optional polish.)
tests/conftest.py (1)
2-2: Remove unused import.Static analysis correctly identifies that
osis imported but not used.-import os
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (49)
.github/workflows/staticanalysis.yml(1 hunks).vscode/tasks.json(1 hunks)CLAUDE.md(1 hunks)docs/contributing/error-handling.mdx(3 hunks)migrations/utils.py(5 hunks)migrations/versions/20f89a421aff_rename_metamessage_type_to_label.py(1 hunks)migrations/versions/556a16564f50_add_user_id_and_app_id_to_tables.py(1 hunks)migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py(2 hunks)migrations/versions/a1b2c3d4e5f6_initial_schema.py(2 hunks)migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py(7 hunks)migrations/versions/c3828084f472_add_indexes_for_messages_and_.py(1 hunks)migrations/versions/d429de0e5338_adopt_peer_paradigm.py(1 hunks)pyproject.toml(4 hunks)src/agent.py(10 hunks)src/crud.py(19 hunks)src/db.py(2 hunks)src/dependencies.py(1 hunks)src/deriver/consumer.py(4 hunks)src/deriver/queue.py(4 hunks)src/deriver/tom/__init__.py(2 hunks)src/deriver/tom/conversational.py(3 hunks)src/deriver/tom/embeddings.py(4 hunks)src/deriver/tom/long_term.py(4 hunks)src/deriver/tom/single_prompt.py(3 hunks)src/exceptions.py(1 hunks)src/main.py(7 hunks)src/models.py(13 hunks)src/routers/messages.py(7 hunks)src/routers/peers.py(11 hunks)src/routers/sessions.py(15 hunks)src/routers/workspaces.py(5 hunks)src/schemas.py(7 hunks)src/security.py(5 hunks)src/utils/cache.py(0 hunks)src/utils/history.py(6 hunks)src/utils/model_client.py(0 hunks)src/utils/types.py(1 hunks)tests/conftest.py(14 hunks)tests/integration/test_enqueue.py(16 hunks)tests/routes/test_keys.py(3 hunks)tests/routes/test_messages.py(22 hunks)tests/routes/test_peers.py(26 hunks)tests/routes/test_scoped_api.py(11 hunks)tests/routes/test_sessions.py(29 hunks)tests/routes/test_validation_api.py(7 hunks)tests/routes/test_workspaces.py(16 hunks)tests/test_agent.py(1 hunks)tests/test_schema_validations.py(1 hunks)tests/utils/test_model_client.py(0 hunks)
💤 Files with no reviewable changes (3)
- src/utils/cache.py
- tests/utils/test_model_client.py
- src/utils/model_client.py
🚧 Files skipped from review as they are similar to previous changes (29)
- .vscode/tasks.json
- migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py
- CLAUDE.md
- src/dependencies.py
- .github/workflows/staticanalysis.yml
- src/utils/types.py
- tests/test_schema_validations.py
- migrations/versions/20f89a421aff_rename_metamessage_type_to_label.py
- tests/routes/test_keys.py
- src/deriver/tom/embeddings.py
- migrations/versions/556a16564f50_add_user_id_and_app_id_to_tables.py
- migrations/versions/c3828084f472_add_indexes_for_messages_and_.py
- src/deriver/queue.py
- src/deriver/consumer.py
- docs/contributing/error-handling.mdx
- tests/routes/test_messages.py
- src/exceptions.py
- src/deriver/tom/init.py
- migrations/versions/d429de0e5338_adopt_peer_paradigm.py
- migrations/utils.py
- tests/test_agent.py
- tests/routes/test_validation_api.py
- tests/routes/test_workspaces.py
- tests/routes/test_scoped_api.py
- pyproject.toml
- tests/integration/test_enqueue.py
- tests/routes/test_sessions.py
- tests/routes/test_peers.py
- src/crud.py
🧰 Additional context used
📓 Path-based instructions (6)
`src/utils/history.py`: Session history management utilities should be implemented in src/utils/history.py.
src/utils/history.py: Session history management utilities should be implemented in src/utils/history.py.
src/utils/history.py
`src/deriver/tom/*`: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/*: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/single_prompt.pysrc/deriver/tom/conversational.pysrc/deriver/tom/long_term.py
`tests/conftest.py`: Pytest fixtures should be defined in tests/conftest.py.
tests/conftest.py: Pytest fixtures should be defined in tests/conftest.py.
tests/conftest.py
`src/main.py`: Set up the FastAPI app, including middleware and global exception handlers, in src/main.py.
src/main.py: Set up the FastAPI app, including middleware and global exception handlers, in src/main.py.
src/main.py
`src/models.py`: Use explicit type hints with SQLAlchemy mapped_column annotations.
src/models.py: Use explicit type hints with SQLAlchemy mapped_column annotations.
src/models.py
`src/routers/*.py`: API endpoints should be implemented in the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own module.
src/routers/*.py: API endpoints should be implemented in the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own module.
src/routers/messages.pysrc/routers/peers.pysrc/routers/sessions.pysrc/routers/workspaces.py
🪛 Pylint (3.3.7)
src/deriver/tom/single_prompt.py
[refactor] 26-26: Too few public methods (0/2)
(R0903)
[refactor] 32-32: Too few public methods (0/2)
(R0903)
[refactor] 37-37: Too few public methods (0/2)
(R0903)
[refactor] 42-42: Too few public methods (0/2)
(R0903)
[refactor] 46-46: Too few public methods (0/2)
(R0903)
[refactor] 52-52: Too few public methods (0/2)
(R0903)
[refactor] 60-60: Too few public methods (0/2)
(R0903)
[refactor] 65-65: Too few public methods (0/2)
(R0903)
[refactor] 71-71: Too few public methods (0/2)
(R0903)
[refactor] 77-77: Too few public methods (0/2)
(R0903)
[refactor] 83-83: Too few public methods (0/2)
(R0903)
[refactor] 87-87: Too few public methods (0/2)
(R0903)
[refactor] 93-93: Too few public methods (0/2)
(R0903)
[refactor] 99-99: Too few public methods (0/2)
(R0903)
src/agent.py
[refactor] 62-62: Too few public methods (0/2)
(R0903)
[refactor] 204-213: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
tests/conftest.py
[refactor] 200-200: Too few public methods (0/2)
(R0903)
[refactor] 302-302: Too many local variables (16/15)
(R0914)
src/deriver/tom/long_term.py
[refactor] 13-13: Too few public methods (0/2)
(R0903)
[refactor] 19-19: Too few public methods (0/2)
(R0903)
[refactor] 27-27: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 39-39: Too few public methods (0/2)
(R0903)
src/main.py
[error] 72-72: Using variable 'Event' before assignment
(E0601)
[error] 72-72: Using variable 'Hint' before assignment
(E0601)
src/models.py
[refactor] 100-100: Too few public methods (0/2)
(R0903)
[refactor] 122-122: Too few public methods (1/2)
(R0903)
[refactor] 157-157: Too few public methods (1/2)
(R0903)
[refactor] 191-191: Too few public methods (1/2)
(R0903)
[refactor] 256-256: Too few public methods (0/2)
(R0903)
[refactor] 293-293: Too few public methods (0/2)
(R0903)
[refactor] 340-340: Too few public methods (0/2)
(R0903)
[refactor] 353-353: Too few public methods (0/2)
(R0903)
[refactor] 379-379: Too few public methods (0/2)
(R0903)
src/routers/messages.py
[refactor] 57-57: Too many local variables (25/15)
(R0914)
[refactor] 57-57: Too many branches (14/12)
(R0912)
[refactor] 57-57: Too many statements (61/50)
(R0915)
src/schemas.py
[refactor] 25-25: Too few public methods (0/2)
(R0903)
[refactor] 29-29: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 62-62: Too few public methods (0/2)
(R0903)
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 71-71: Too few public methods (0/2)
(R0903)
[refactor] 85-85: Too few public methods (0/2)
(R0903)
[refactor] 112-112: Too few public methods (0/2)
(R0903)
[refactor] 116-116: Too few public methods (0/2)
(R0903)
[refactor] 120-120: Too few public methods (0/2)
(R0903)
[refactor] 170-170: Too few public methods (0/2)
(R0903)
[refactor] 175-175: Too few public methods (0/2)
(R0903)
[refactor] 180-180: Too few public methods (0/2)
(R0903)
[refactor] 195-195: Too few public methods (0/2)
(R0903)
[error] 231-231: Method 'validate_queries' should have "self" as first argument
(E0213)
🪛 GitHub Check: basedpyright
src/agent.py
[warning] 23-23:
Import "get_tom_inference_single_prompt" is not accessed (reportUnusedImport)
[warning] 19-19:
"models" is imported more than once (reportDuplicateImport)
[warning] 19-19:
"crud" is imported more than once (reportDuplicateImport)
[warning] 17-17:
Import "schemas" is not accessed (reportUnusedImport)
[warning] 9-9:
Import "load_dotenv" is not accessed (reportUnusedImport)
🪛 Ruff (0.11.9)
src/agent.py
9-9: dotenv.load_dotenv imported but unused
Remove unused import: dotenv.load_dotenv
(F401)
10-10: Redefinition of unused langfuse_context from line 7
Remove definition: langfuse_context
(F811)
10-10: Redefinition of unused observe from line 7
Remove definition: observe
(F811)
17-17: src.schemas imported but unused
Remove unused import: src.schemas
(F401)
19-19: Redefinition of unused crud from line 17
Remove definition: crud
(F811)
19-19: Redefinition of unused models from line 17
Remove definition: models
(F811)
23-23: src.deriver.tom.single_prompt.get_tom_inference_single_prompt imported but unused
Remove unused import: src.deriver.tom.single_prompt.get_tom_inference_single_prompt
(F401)
tests/conftest.py
2-2: os imported but unused
Remove unused import: os
(F401)
migrations/versions/a1b2c3d4e5f6_initial_schema.py
11-11: os.getenv imported but unused
Remove unused import: os.getenv
(F401)
migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py
11-11: os.getenv imported but unused
Remove unused import: os.getenv
(F401)
src/db.py
3-3: os imported but unused
Remove unused import: os
(F401)
src/deriver/tom/conversational.py
7-7: Redefinition of unused MessageParam from line 5
Remove definition: MessageParam
(F811)
7-7: anthropic.types.TextBlock imported but unused
Remove unused import: anthropic.types.TextBlock
(F401)
8-8: Redefinition of unused langfuse_context from line 6
Remove definition: langfuse_context
(F811)
8-8: Redefinition of unused observe from line 6
Remove definition: observe
(F811)
src/main.py
10-10: fastapi.APIRouter imported but unused
Remove unused import: fastapi.APIRouter
(F401)
10-10: Redefinition of unused FastAPI from line 9
Remove definition: FastAPI
(F811)
10-10: Redefinition of unused Request from line 9
Remove definition: Request
(F811)
src/routers/messages.py
314-316: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/peers.py
42-44: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
124-126: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
267-269: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/sessions.py
80-82: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/workspaces.py
56-58: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/security.py
4-4: os imported but unused
Remove unused import: os
(F401)
5-5: Redefinition of unused Annotated from line 3
Remove definition: Annotated
(F811)
🪛 Flake8 (7.2.0)
src/agent.py
[error] 9-9: 'dotenv.load_dotenv' imported but unused
(F401)
[error] 10-10: redefinition of unused 'langfuse_context' from line 7
(F811)
[error] 10-10: redefinition of unused 'observe' from line 7
(F811)
[error] 17-17: 'src.schemas' imported but unused
(F401)
[error] 19-19: redefinition of unused 'crud' from line 17
(F811)
[error] 19-19: redefinition of unused 'models' from line 17
(F811)
[error] 23-23: 'src.deriver.tom.single_prompt.get_tom_inference_single_prompt' imported but unused
(F401)
[error] 32-32: too many blank lines (3)
(E303)
tests/conftest.py
[error] 2-2: 'os' imported but unused
(F401)
migrations/versions/a1b2c3d4e5f6_initial_schema.py
[error] 11-11: 'os.getenv' imported but unused
(F401)
migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py
[error] 11-11: 'os.getenv' imported but unused
(F401)
src/db.py
[error] 3-3: 'os' imported but unused
(F401)
src/deriver/tom/conversational.py
[error] 7-7: redefinition of unused 'MessageParam' from line 5
(F811)
[error] 7-7: 'anthropic.types.TextBlock' imported but unused
(F401)
[error] 8-8: redefinition of unused 'langfuse_context' from line 6
(F811)
[error] 8-8: redefinition of unused 'observe' from line 6
(F811)
src/main.py
[error] 10-10: redefinition of unused 'FastAPI' from line 9
(F811)
[error] 10-10: redefinition of unused 'Request' from line 9
(F811)
[error] 10-10: 'fastapi.APIRouter' imported but unused
(F401)
src/security.py
[error] 4-4: 'os' imported but unused
(F401)
[error] 5-5: redefinition of unused 'Annotated' from line 3
(F811)
🪛 GitHub Actions: Static Analysis
src/agent.py
[warning] 5-5: Import "sentry_sdk" is not accessed (reportUnusedImport)
[warning] 6-6: Import "MessageStreamManager" is not accessed (reportUnusedImport)
[warning] 7-7: Type of "observe" is partially unknown (reportUnknownVariableType)
[warning] 8-8: Import "ai_track" is not accessed (reportUnusedImport)
[warning] 9-9: Import "load_dotenv" is not accessed (reportUnusedImport)
[warning] 17-17: Import "schemas" is not accessed (reportUnusedImport)
[warning] 19-19: "crud" is imported more than once (reportDuplicateImport)
[warning] 19-19: "models" is imported more than once (reportDuplicateImport)
[warning] 23-23: Import "get_tom_inference_single_prompt" is not accessed (reportUnusedImport)
[warning] 253-253: Type of "AGENT" is unknown (reportUnknownMemberType)
[warning] 253-253: Type of "SEMANTIC_SEARCH_TOP_K" is unknown (reportUnknownMemberType)
[warning] 253-253: Argument type is unknown for parameter "top_k" in function "get_relevant_facts" (reportUnknownArgumentType)
[warning] 254-254: Type of "AGENT" is unknown (reportUnknownMemberType)
[warning] 254-254: Type of "SEMANTIC_SEARCH_MAX_DISTANCE" is unknown (reportUnknownMemberType)
[warning] 254-254: Argument type is unknown for parameter "max_distance" in function "get_relevant_facts" (reportUnknownArgumentType)
[warning] 293-293: Type of "tom_inference_response" is unknown (reportUnknownVariableType)
[error] 293-293: "get_tom_inference" is not defined (reportUndefinedVariable)
🪛 GitHub Actions: FastAPI Tests with PostgreSQL and uv
tests/conftest.py
[error] 30-30: ModuleNotFoundError: No module named 'pydantic_settings' while importing in tests/conftest.py
🔇 Additional comments (53)
migrations/versions/a1b2c3d4e5f6_initial_schema.py (1)
22-24: 👍 PEP 604 union syntax looks good.The switch to the
|syntax is correct and removes the need fortyping.Union.migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py (1)
22-24: Type-hint modernisation looks good here as well.The PEP 604 unions make the metadata cleaner and future-proof.
src/db.py (1)
15-17: LGTM! Good modernization of type annotations.The change from
Optional[str]tostr | Nonefollows modern Python typing practices and improves readability.src/deriver/tom/conversational.py (2)
10-10: LGTM! Good refactoring to centralized tracking.The import of
trackfromsrc.utils.typesaligns with the broader refactoring to centralize tracking functionality across the codebase.
23-23: LGTM! Consistent decorator migration.The change from
@ai_trackto@trackis consistent with the broader refactoring effort to standardize telemetry tracking across the project.Also applies to: 91-91
src/routers/workspaces.py (2)
6-6: LGTM! Excellent type annotation improvements.The explicit typing of
dbparameters asAsyncSessionand the import addition provide better type safety and IDE support.Also applies to: 27-27, 59-59, 84-84, 102-102
56-58: LGTM! Good modernization of type annotations.The change from
Optional[...]to union syntax (| None) follows modern Python typing practices. The static analysis warning aboutBody()in defaults can be ignored as this is standard FastAPI pattern for dependency injection.src/schemas.py (4)
1-1: Good practice for managing type checker warnings.The pyright directive helps suppress false positive warnings about unannotated class attributes in Pydantic models.
3-3: LGTM! Modernized typing imports.Removing
Optionalin favor of union syntax and addingAnyfor explicit type annotations is good practice.
19-19: Excellent type annotation improvements.The changes from generic
dicttodict[str, Any]provide much better type safety and clarity about the expected structure of these metadata and configuration fields.Also applies to: 36-39, 56-57, 75-78, 109-109, 125-127, 163-163, 184-187, 211-211
22-22: Good practice adding pyright ignore comments.These comments appropriately suppress type checker warnings for Pydantic's
ConfigDictusage while maintaining the necessary configuration.Also applies to: 42-44, 59-59, 80-82, 132-134, 167-167, 190-192, 200-202
src/routers/sessions.py (4)
6-6: LGTM! Comprehensive type annotation improvements.The explicit typing of
dbparameters asAsyncSessionprovides better type safety and consistency across all route handlers.Also applies to: 36-36, 83-83, 120-120, 143-143, 167-167, 201-201, 233-233, 269-269, 303-303, 325-325, 357-357, 388-388, 464-464
80-82: LGTM! Good modernization of type annotations.The change from
Optional[...]to union syntax (| None) follows modern Python typing practices. The static analysis warning aboutBody()in defaults can be ignored as this is standard FastAPI pattern.Also applies to: 168-170, 380-383
208-217: Excellent code cleanup.Removing the redundant local variable assignments and using the original parameters directly makes the code more concise and readable while maintaining the same functionality.
Also applies to: 239-253, 276-289
448-448: Appropriate use of pyright ignore comment.The pyright ignore comment is correctly placed to handle specific type checking issues with the messages field assignment.
src/security.py (3)
62-66: LGTM! Modern type annotations.The migration from
Optional[...]to... | Nonesyntax is a good modernization that improves readability and follows current Python typing best practices.
81-83: LGTM! Improved formatting.The reformatted
jwt.encodecall improves readability by breaking the arguments across multiple lines.
120-123: LGTM! Consistent type annotation modernization.The function parameters have been consistently updated to use the modern union syntax (
str | Noneinstead ofOptional[str]), which is excellent for maintainability and consistency.Also applies to: 164-167
src/routers/messages.py (3)
3-3: LGTM! Necessary imports for type annotations.The addition of
Anyfrom typing andAsyncSessionfrom SQLAlchemy supports the improved type annotations throughout the file.Also applies to: 8-8
29-33: LGTM! Modernized dictionary and union type annotations.The updates to use
dict[str, Any]andstr | Nonesyntax represent good modernization of type hints, improving clarity and following current Python typing best practices.Also applies to: 57-57
272-272: LGTM! Explicit database session typing.Adding explicit
AsyncSessiontype annotations for thedbparameters improves type safety and makes the dependency injection pattern clearer throughout the API endpoints.Also applies to: 320-320, 348-348, 368-368
src/main.py (5)
15-16: LGTM! Proper conditional imports for type checking.Using
TYPE_CHECKINGblock for Sentry types that are only needed for type annotations is a good practice that avoids runtime import overhead.
33-33: LGTM! Clear function signature with type annotations.Adding explicit type annotations for parameters and return type improves the function's clarity and type safety.
72-72: LGTM! Proper type annotations and variable naming.The Sentry callback function now has precise type hints and correctly ignores the unused exception type variable using the underscore convention.
Also applies to: 74-74
104-104: LGTM! Following unused parameter naming convention.Renaming unused parameters to use underscores (
_,_request) clearly indicates they are intentionally unused, following Python conventions.Also applies to: 158-158, 168-168
180-182: LGTM! Explicit middleware type annotations.Adding precise type annotations for the middleware function parameters, especially the
call_nextcallable type, improves type safety and documentation.src/utils/history.py (4)
6-7: LGTM! Proper mirascope imports for LLM integration.The imports support the migration from custom
ModelClientto the mirascope framework, enabling declarative LLM calls with proper tracking.
62-98: Excellent migration to declarative LLM calls.The new mirascope-based functions represent a significant architectural improvement:
- Declarative approach with
@llm.calldecorators- Proper model configuration (gemini-2.0-flash-lite) with token limits
- Langfuse integration for tracking
- Clean separation between short and long summary generation
- Well-structured prompts with clear instructions
This replaces the imperative ModelClient approach with a more maintainable and structured solution.
Also applies to: 100-134
142-142: LGTM! Consistent type annotation modernization.The migration from
Optional[...]to... | Nonesyntax throughout the file maintains consistency with the broader codebase typing improvements.Also applies to: 169-169, 177-179, 211-211, 286-286, 329-329, 383-383
194-202: LGTM! Streamlined summary creation logic.The refactored
create_summaryfunction properly integrates with the new mirascope-based functions, maintaining the same interface while leveraging the improved LLM integration architecture.src/models.py (6)
99-99: LGTM! Proper use of @Final decorators for ORM models.Adding
@finaldecorators to all ORM model classes is an excellent practice that:
- Prevents unintended inheritance of database models
- Improves type safety by making inheritance explicit
- Follows best practices for SQLAlchemy ORM models
Also applies to: 121-121, 156-156, 190-190, 255-255, 292-292, 339-339, 352-352, 378-378
101-101: LGTM! Explicit tablename typing.Adding type annotations for
__tablename__attributes improves static analysis and makes the table naming explicit and type-safe.Also applies to: 123-123, 158-158, 192-192, 257-257, 294-294, 341-341, 354-354
108-112: LGTM! Comprehensive dictionary type annotations.The migration to
dict[str, Any]for configuration and metadata fields provides:
- Better type safety than untyped dictionaries
- Clear indication of expected key-value types
- Consistency across all model definitions
Also applies to: 126-129, 136-136, 162-165, 173-173, 201-204, 264-267, 296-298, 348-348, 386-389
300-300: LGTM! Proper vector column typing.Using
MappedColumn[Any]for the embedding vector column appropriately handles the complex pgvector type while maintaining type safety.
244-244: LGTM! Proper decorator usage and type annotations.The
@overridedecorator on__repr__and type annotations on the event listener function improve code clarity and follow typing best practices.Also applies to: 250-250
380-389: LGTM! Comprehensive SessionPeer model typing.The detailed type annotations for all columns in the
SessionPeerclass provide excellent type safety for the association table mapping, making the model's structure explicit and type-safe.src/deriver/tom/long_term.py (4)
3-7: Excellent refactoring to modern LLM framework.The migration from manual model client usage to the
mirascopeframework with structured Pydantic models is well-executed. The imports are clean and properly organized.
13-42: Well-structured Pydantic models for type safety.The Pydantic models provide excellent type safety and structure for the LLM responses. The
PotentialSurprisemodel with confidence levels and the nested structure inFactExtractionare particularly well-designed.
44-103: Excellent implementation of declarative LLM calls.The function properly uses the new decorator pattern with
@track,@with_langfuse(), and@llm.call. The prompt template is well-structured and the return type matches the response model.
106-152: Clean migration to structured LLM calls.The function follows the same excellent pattern as
get_user_representation_long_term. The prompt is clear and the structured output will improve parsing reliability.src/deriver/tom/single_prompt.py (4)
2-8: Great addition of imports for the new architecture.The imports are well-organized and include all necessary components for the mirascope-based implementation.
13-106: Excellent comprehensive Pydantic model design.The extensive model hierarchy with strongly-typed enums (
InfoType,CertaintyLevel) and detailed nested structures provides exceptional type safety. The separation of concerns between ToM inference models and user representation models is well-architected.
108-154: Well-implemented LLM call with structured output.The
tom_inferencefunction properly uses the decorator pattern and provides a clear, structured prompt template that matches the expected Pydantic response model.
165-233: Excellent user representation inference implementation.The function provides comprehensive guidance for the LLM with clear output format specifications that align perfectly with the Pydantic models.
src/routers/peers.py (3)
15-16: Good modernization of imports.The replacement of
AsyncMessageStreamManagerwithStreamfrommirascope.llmand explicitAsyncSessionimport align well with the framework migration.
42-45: Excellent type annotation modernization.The use of modern union syntax (
T | None) and explicitAsyncSessiontyping improves code clarity and type safety throughout the endpoints.Also applies to: 124-127, 267-273
192-196: Verify Stream type handling.The streaming logic correctly checks for
Streamtype and handles chunk iteration. The error handling for invalid stream types is appropriate.src/agent.py (3)
32-59: Excellent LLM function implementations.The
dialectic_callanddialectic_streamfunctions properly use the new decorator pattern with clean prompt templates.
62-79: Well-structured semantic query generation.The
SemanticQueriesPydantic model andgenerate_semantic_queries_llmfunction follow the new pattern correctly.
304-313: Good adaptation to structured Pydantic responses.The code properly handles the new Pydantic model structure, extracting attributes directly instead of parsing XML. The fallback logic maintains backward compatibility.
tests/conftest.py (3)
2-37: Excellent type annotation improvements.The comprehensive addition of type hints throughout the imports and class definitions significantly improves code clarity and IDE support.
302-384: Excellent migration to mirascope function mocking.The replacement of
mock_model_clientwithmock_mirascope_functionsproperly aligns with the framework migration. The comprehensive mocking of individual LLM functions with appropriate return values is well-designed.
30-37: Let’s verify howsrc/config.pyis defining settings and inspectpyproject.tomlfor anypydantic-settingsentries:#!/bin/bash set -e echo "=== Looking for BaseSettings usage in config.py ===" grep -R "BaseSettings" -n src/config.py || echo "No BaseSettings reference found" echo echo "=== Full content of src/config.py (first 200 lines) ===" sed -n '1,200p' src/config.py echo echo "=== Checking for pydantic-settings in pyproject.toml ===" grep -R "pydantic-settings" -n pyproject.toml || echo "No pydantic-settings entry" echo "=== Checking for pydantic_settings in pyproject.toml ===" grep -R "pydantic_settings" -n pyproject.toml || echo "No pydantic_settings entry" echo echo "=== Dependencies section from pyproject.toml ===" awk '/\[tool.poetry.dependencies\]/,/\[tool.poetry.dev-dependencies\]/' pyproject.toml
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/schemas.py (1)
231-231: Field validator signature is correct.Despite the static analysis hint suggesting an issue, the
validate_queriesmethod is correctly defined as a classmethod withclsas the first parameter, which is the proper signature for Pydantic v2 field validators decorated with@field_validator.The past review comment identified this correctly - the method signature is appropriate for Pydantic v2 field validators.
🧹 Nitpick comments (3)
src/deriver/tom/conversational.py (1)
24-31: Consider extracting long prompt strings for maintainability.The embedded prompt strings are extremely long (hundreds of lines) and contain complex instructions. Consider extracting these to separate files or constants to improve code readability and maintainability.
Create prompt template files and load them:
# At module level def load_prompt_template(filename: str) -> str: """Load prompt template from file.""" prompt_dir = Path(__file__).parent / "prompts" return (prompt_dir / filename).read_text() TOM_INFERENCE_SYSTEM_PROMPT = load_prompt_template("tom_inference_system.txt") USER_REP_SYSTEM_PROMPT = load_prompt_template("user_rep_system.txt")Then use these constants in the Messages instead of the inline strings.
Also applies to: 55-62
src/agent.py (1)
198-207: Remove unnecessary else clause after return statement.The else clause after the return statement is unnecessary and reduces code readability.
Apply this diff to improve the code structure:
if stream: logger.debug("Calling Dialectic with streaming") response = await dialectic_stream( final_query, user_representation, chat_history ) return response - else: - logger.debug("Calling Dialectic with non-streaming") - response = await dialectic_call(final_query, user_representation, chat_history) - return response + + logger.debug("Calling Dialectic with non-streaming") + response = await dialectic_call(final_query, user_representation, chat_history) + return responsesrc/crud.py (1)
245-245: Consider usingdict[str, Any]for consistency.The
filterparameter here usesdict[str, str] | None, while other similar filter parameters in the file usedict[str, Any] | None. Based on past review feedback suggestingdict[str, Any]for consistency, consider aligning this parameter type.- filter: dict[str, str] | None = None, + filter: dict[str, Any] | None = None,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (20)
migrations/utils.py(5 hunks)migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py(1 hunks)migrations/versions/a1b2c3d4e5f6_initial_schema.py(2 hunks)migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py(7 hunks)migrations/versions/c3828084f472_add_indexes_for_messages_and_.py(1 hunks)pyproject.toml(4 hunks)src/agent.py(10 hunks)src/config.py(7 hunks)src/crud.py(19 hunks)src/db.py(2 hunks)src/deriver/queue.py(4 hunks)src/deriver/tom/__init__.py(2 hunks)src/deriver/tom/conversational.py(1 hunks)src/deriver/tom/long_term.py(4 hunks)src/deriver/tom/single_prompt.py(3 hunks)src/main.py(6 hunks)src/schemas.py(6 hunks)src/security.py(6 hunks)tests/conftest.py(14 hunks)tests/test_agent.py(1 hunks)
✅ Files skipped from review due to trivial changes (2)
- migrations/versions/c3828084f472_add_indexes_for_messages_and_.py
- migrations/versions/a1b2c3d4e5f6_initial_schema.py
🚧 Files skipped from review as they are similar to previous changes (8)
- src/db.py
- migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py
- src/deriver/queue.py
- tests/test_agent.py
- migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py
- src/deriver/tom/init.py
- migrations/utils.py
- src/security.py
🧰 Additional context used
📓 Path-based instructions (3)
`src/deriver/tom/*`: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/*: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/conversational.pysrc/deriver/tom/long_term.pysrc/deriver/tom/single_prompt.py
`tests/conftest.py`: Pytest fixtures should be defined in tests/conftest.py.
tests/conftest.py: Pytest fixtures should be defined in tests/conftest.py.
tests/conftest.py
`src/main.py`: Set up the FastAPI app, including middleware and global exception handlers, in src/main.py.
src/main.py: Set up the FastAPI app, including middleware and global exception handlers, in src/main.py.
src/main.py
🪛 Pylint (3.3.7)
src/deriver/tom/long_term.py
[refactor] 14-14: Too few public methods (0/2)
(R0903)
[refactor] 20-20: Too few public methods (0/2)
(R0903)
[refactor] 28-28: Too few public methods (0/2)
(R0903)
[refactor] 35-35: Too few public methods (0/2)
(R0903)
[refactor] 40-40: Too few public methods (0/2)
(R0903)
tests/conftest.py
[refactor] 199-199: Too few public methods (0/2)
(R0903)
src/deriver/tom/single_prompt.py
[refactor] 26-26: Too few public methods (0/2)
(R0903)
[refactor] 32-32: Too few public methods (0/2)
(R0903)
[refactor] 37-37: Too few public methods (0/2)
(R0903)
[refactor] 42-42: Too few public methods (0/2)
(R0903)
[refactor] 46-46: Too few public methods (0/2)
(R0903)
[refactor] 52-52: Too few public methods (0/2)
(R0903)
[refactor] 60-60: Too few public methods (0/2)
(R0903)
[refactor] 65-65: Too few public methods (0/2)
(R0903)
[refactor] 71-71: Too few public methods (0/2)
(R0903)
[refactor] 77-77: Too few public methods (0/2)
(R0903)
[refactor] 83-83: Too few public methods (0/2)
(R0903)
[refactor] 87-87: Too few public methods (0/2)
(R0903)
[refactor] 93-93: Too few public methods (0/2)
(R0903)
[refactor] 99-99: Too few public methods (0/2)
(R0903)
src/agent.py
[refactor] 56-56: Too few public methods (0/2)
(R0903)
[refactor] 198-207: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
src/config.py
[refactor] 99-99: Too many arguments (6/5)
(R0913)
[refactor] 99-99: Too many positional arguments (6/5)
(R0917)
[refactor] 152-152: Too few public methods (1/2)
(R0903)
[refactor] 161-161: Too few public methods (1/2)
(R0903)
src/crud.py
[refactor] 26-26: Too few public methods (1/2)
(R0903)
src/main.py
[error] 71-71: Using variable 'Event' before assignment
(E0601)
[error] 71-71: Using variable 'Hint' before assignment
(E0601)
src/schemas.py
[refactor] 25-25: Too few public methods (0/2)
(R0903)
[refactor] 29-29: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 62-62: Too few public methods (0/2)
(R0903)
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 71-71: Too few public methods (0/2)
(R0903)
[refactor] 85-85: Too few public methods (0/2)
(R0903)
[refactor] 112-112: Too few public methods (0/2)
(R0903)
[refactor] 116-116: Too few public methods (0/2)
(R0903)
[refactor] 120-120: Too few public methods (0/2)
(R0903)
[refactor] 170-170: Too few public methods (0/2)
(R0903)
[refactor] 175-175: Too few public methods (0/2)
(R0903)
[refactor] 180-180: Too few public methods (0/2)
(R0903)
[refactor] 195-195: Too few public methods (0/2)
(R0903)
[refactor] 214-214: Too few public methods (0/2)
(R0903)
[error] 231-231: Method 'validate_queries' should have "self" as first argument
(E0213)
[refactor] 219-219: Too few public methods (1/2)
(R0903)
🪛 GitHub Actions: FastAPI Tests with PostgreSQL and uv
src/agent.py
[error] 165-165: Exception raised during asyncio.gather call in chat function caused by missing GROQ_API_KEY environment variable.
[error] 287-287: Failure in run_tom_inference function due to groq.GroqError: missing api_key client option or GROQ_API_KEY environment variable.
src/main.py
[error] 191-191: Unhandled exception logged: groq.GroqError due to missing GROQ_API_KEY environment variable or api_key client option.
🔇 Additional comments (31)
pyproject.toml (3)
9-9: Python version requirement increase supports modern typing.The bump from Python 3.9 to 3.10 enables the use of native union syntax (
str | None) throughout the codebase, which aligns with the typing modernization goals of this PR.
25-28: Dependency consolidation with mirascope integration.The replacement of individual LLM provider packages with
mirascope[anthropic,google,groq,langfuse]>=1.25.1and updated versions of core dependencies supports the architectural shift to declarative LLM calls seen throughout the codebase.
68-99: Well-configured basedpyright static analysis setup.The basedpyright configuration appropriately balances strict type checking with practical project needs. The selective ignoring of warnings like
reportMissingTypeStubsandallowedUntypedLibrariesfor third-party packages is sensible for maintaining a clean development experience.src/schemas.py (2)
1-1: Added pyright directive for class attribute annotations.The directive
# pyright: reportUnannotatedClassAttribute=falseappropriately suppresses warnings for Pydantic model fields, which don't require explicit type annotations when using Field descriptors.
19-20: Improved dictionary type annotations throughout.The conversion from untyped
dictto explicitdict[str, Any]provides better type safety and IntelliSense support. This pattern is consistently applied across all model classes for metadata, configuration, and filter fields.Also applies to: 26-26, 30-31
src/main.py (4)
14-15: Proper conditional import for type checking.Using
TYPE_CHECKINGto conditionally import Sentry types avoids runtime import overhead while providing type information for static analysis. This is a best practice for type-only imports.
71-71: Enhanced type annotations and parameter naming.The explicit type annotations for
before_send,lifespan, and exception handler functions improve code clarity. The underscore prefix for unused parameters (_,_request) follows Python conventions for indicating intentionally unused variables.Also applies to: 103-103, 157-157, 167-167
179-181: Well-typed middleware function.The type annotation for the
call_nextparameter correctly specifies it as a callable that takes aRequestand returns an awaitableResponse, providing clear interface documentation.
191-191: Verify GROQ_API_KEY environment configuration.The pipeline failure indicates a missing GROQ_API_KEY environment variable. This is likely related to the new LLM integrations using Groq as a provider.
#!/bin/bash # Description: Check for GROQ API key configuration in the codebase # Expected: Find references to GROQ_API_KEY configuration and usage # Search for GROQ API key references rg -A 3 -B 3 "GROQ_API_KEY" --type py # Check if there are any default configurations or environment setup files fd -e env -e yaml -e yml | head -10src/config.py (3)
3-3: Removed Optional import in favor of native union syntax.The removal of
Optionalfrom the typing imports aligns with the project-wide adoption of Python 3.10+ native union syntax (str | None), improving consistency and readability.
143-143: Consistent type annotation modernization.The conversion from
Optional[str]tostr | Nonethroughout the settings classes provides cleaner, more readable type hints while maintaining the same semantic meaning. This is consistent with the Python 3.10+ typing standards adopted by the project.Also applies to: 156-156, 165-170
169-169: Added missing GROQ_API_KEY configuration.The addition of the
GROQ_API_KEYfield addresses the pipeline failure in main.py where the Groq LLM provider was missing API key configuration. This completes the LLM provider configuration set.src/deriver/tom/conversational.py (3)
13-17: Excellent migration to declarative LLM calls.The use of
@llm.callwith structured response models (TomInferenceOutput) provides better type safety and cleaner code compared to manual client management. The integration with tracking and Langfuse decorators maintains observability.
18-21: Function signature improvements.The renamed function (removing
get_prefix) and explicit parameter typing (str | None) align with modern Python conventions and the broader typing improvements in this PR.
41-47: Consistent decorator pattern for user representation function.The use of the same decorator pattern (
@track,@with_langfuse(),@llm.call) for the user representation function maintains consistency with the theory of mind inference function and provides the same benefits.src/deriver/tom/long_term.py (2)
3-43: Excellent refactoring to mirascope framework with structured Pydantic models!The new imports and Pydantic model definitions are well-structured and improve type safety significantly. The models provide clear schema definitions for LLM responses, making the code more maintainable and less error-prone than the previous manual parsing approach.
45-155: Well-implemented migration to mirascope declarative LLM calls!The refactored functions demonstrate excellent use of the mirascope framework:
- Proper integration of telemetry via
@trackand@with_langfuse- Clean separation of concerns with
@llm.callhandling the LLM interaction- Structured prompt templates that align with the Pydantic response models
- Elimination of manual error handling and response parsing
This approach significantly improves maintainability and type safety compared to the previous imperative client-based implementation.
src/deriver/tom/single_prompt.py (2)
13-106: Comprehensive and well-structured Pydantic model definitions!The extensive model hierarchy with enums (
InfoType,CertaintyLevel) and nested Pydantic models provides excellent type safety and clear structure for both ToM inference and user representation outputs. The field names are descriptive and the relationships between models are logical and well-organized.
108-224: Excellent implementation of mirascope-based LLM functions!Both
tom_inferenceanduser_representationfunctions demonstrate consistent and effective use of the mirascope framework:
- Proper decorator usage for tracking, langfuse integration, and LLM calls
- Well-structured prompt templates with clear XML sections for different inputs
- Appropriate provider/model selection for each function's purpose
- Clean integration with the comprehensive Pydantic response models
The migration from manual client management to this declarative approach is well-executed.
src/agent.py (5)
5-20: Great improvement in import organization!The imports have been properly cleaned up and organized to support the new mirascope-based architecture. The addition of mirascope and langfuse integrations, along with the removal of unused imports mentioned in past reviews, makes the code much cleaner.
26-53: Well-implemented dialectic functions with mirascope integration!The new
dialectic_callanddialectic_streamfunctions effectively replace the previous class-based approach:
- Proper use of mirascope decorators for tracking, langfuse integration, and LLM calls
- Consistent prompt templates between streaming and non-streaming versions
- Clean function signatures that simplify the calling interface
- Appropriate model selection (Claude 3.7 Sonnet) for the dialectic use case
56-73: Good implementation of semantic query generation with structured output!The
SemanticQueriesmodel andgenerate_semantic_queries_llmfunction demonstrate effective use of the mirascope pattern for structured output generation. The choice of Groq/Llama for this specific task appears appropriate.However, note that the pipeline failures indicate missing
GROQ_API_KEYenvironment variable, which suggests this function may be called during tests or deployment.
298-307: Excellent adaptation to structured Pydantic response models!The updated parsing logic properly handles the new structured output from the mirascope-based ToM inference, extracting
immediate_contextandtentative_inferencesfrom the Pydantic response. This is much more robust than the previous XML parsing approach.
379-409: Good implementation of backward-compatible response parsing!The parsing logic appropriately handles both the new Pydantic response models and provides fallback to XML parsing for backward compatibility. The structured extraction of
current_state,tentative_patterns,knowledge_gaps, andupdatesaligns well with the new model structure.tests/conftest.py (2)
2-241: Excellent comprehensive type annotation improvements!The extensive addition of type annotations throughout the file significantly improves:
- Code clarity and documentation
- IDE support and autocomplete functionality
- Static analysis capabilities
- Type safety in test fixtures and helper functions
The
AuthClientclass definition and updated function signatures with proper type hints are particularly well-implemented.
299-437: Outstanding refactor of test mocking for the new mirascope architecture!The replacement of the broad
mock_model_clientfixture with the granularmock_mirascope_functionsand updatedmock_agent_api_callsfixtures demonstrates excellent testing practices:
- Precise mocking of specific mirascope LLM functions rather than broad client classes
- Proper async mock handling for the new function-based approach
- Comprehensive coverage of all the refactored functions
- Well-structured mock return values that align with the new Pydantic models
This mocking strategy will provide more reliable and maintainable tests for the new architecture.
src/crud.py (5)
25-39: LGTM: Well-designed EmbeddingClient implementation.The new
EmbeddingClientclass is a clean, focused wrapper aroundAsyncOpenAIthat properly validates the API key and provides a single-responsibility interface for embedding generation. The use of@finaldecorator is appropriate to prevent inheritance of this simple wrapper.Note: The static analysis hint about "too few public methods" is a false positive here - this class has a single, well-defined responsibility and doesn't need additional methods.
91-92: Excellent type annotation improvements.The modernized union syntax (
dict[str, Any] | None) and specific generic typing (Select[tuple[Workspace]]) significantly improve type safety and IDE support. This is consistent with the broader typing modernization effort.Also applies to: 103-103
297-299: Consistent type annotation modernization.The migration from
Optional[...]to the modern union syntax (bool | None,dict[str, Any] | None) and the specific generic typing for Select statements are excellent improvements that enhance type safety and readability.Also applies to: 329-329, 341-343
554-554: Well-typed complex return types and parameter annotations.The type annotations correctly capture the complex tuple returns from SELECT statements and maintain consistency with the modern union syntax throughout. The specific typing for
Select[tuple[str, dict[str, Any], Any]]accurately reflects the SQL query results.Also applies to: 733-733, 744-744, 1000-1002
1261-1265: Comprehensive and consistent typing modernization.The systematic application of modern union syntax (
| Noneinstead ofOptional) and specific generic typing throughout the file significantly improves type safety and developer experience. The changes are consistent, well-executed, and align perfectly with the broader codebase modernization effort.Also applies to: 1350-1350, 1398-1400, 1424-1424, 1532-1534, 1564-1564
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/config.py(8 hunks)src/deriver/tom/conversational.py(1 hunks)src/deriver/tom/long_term.py(4 hunks)src/deriver/tom/single_prompt.py(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/deriver/tom/conversational.py
🧰 Additional context used
📓 Path-based instructions (1)
`src/deriver/tom/*`: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/*: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/long_term.pysrc/deriver/tom/single_prompt.py
🪛 Pylint (3.3.7)
src/deriver/tom/long_term.py
[refactor] 15-15: Too few public methods (0/2)
(R0903)
[refactor] 21-21: Too few public methods (0/2)
(R0903)
[refactor] 29-29: Too few public methods (0/2)
(R0903)
[refactor] 36-36: Too few public methods (0/2)
(R0903)
[refactor] 41-41: Too few public methods (0/2)
(R0903)
src/deriver/tom/single_prompt.py
[refactor] 27-27: Too few public methods (0/2)
(R0903)
[refactor] 33-33: Too few public methods (0/2)
(R0903)
[refactor] 38-38: Too few public methods (0/2)
(R0903)
[refactor] 43-43: Too few public methods (0/2)
(R0903)
[refactor] 47-47: Too few public methods (0/2)
(R0903)
[refactor] 53-53: Too few public methods (0/2)
(R0903)
[refactor] 61-61: Too few public methods (0/2)
(R0903)
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 72-72: Too few public methods (0/2)
(R0903)
[refactor] 78-78: Too few public methods (0/2)
(R0903)
[refactor] 84-84: Too few public methods (0/2)
(R0903)
[refactor] 88-88: Too few public methods (0/2)
(R0903)
[refactor] 94-94: Too few public methods (0/2)
(R0903)
[refactor] 100-100: Too few public methods (0/2)
(R0903)
src/config.py
[refactor] 100-100: Too many arguments (6/5)
(R0913)
[refactor] 100-100: Too many positional arguments (6/5)
(R0917)
[refactor] 153-153: Too few public methods (1/2)
(R0903)
[refactor] 162-162: Too few public methods (1/2)
(R0903)
🔇 Additional comments (11)
src/config.py (4)
3-3: Good modernization of imports.The addition of modern typing imports and mirascope Provider import aligns well with the codebase modernization.
100-100: Pyright ignore comment is appropriate.The
# pyright: ignorecomment suppresses warnings for thesettings_customise_sourcesmethod which is a Pydantic framework method with a fixed signature.
144-144: Excellent modernization of type annotations.The migration from
Optional[str]tostr | Nonefollows modern Python typing practices and improves readability.Also applies to: 157-157, 167-171
183-194: Verify the configuration changes align with system requirements.The default provider change from "groq" to "gemini" and the addition of TOM inference configuration are significant changes. Ensure these defaults work correctly in all deployment environments.
#!/bin/bash # Description: Check if gemini configuration is used consistently across the codebase # Expected: Find references to gemini configuration and verify consistency echo "=== Checking gemini provider usage ===" rg -A 2 -B 2 "gemini.*provider|provider.*gemini" --type py echo "=== Checking gemini-2.0-flash-lite model usage ===" rg -A 2 -B 2 "gemini-2\.0-flash-lite" --type py echo "=== Checking TOM_INFERENCE configuration usage ===" rg -A 2 -B 2 "TOM_INFERENCE" --type pysrc/deriver/tom/long_term.py (3)
15-44: Well-structured Pydantic models for type safety.The model definitions provide clear structure for the LLM outputs with appropriate field types. The nested models (PotentialSurprise, InformationPiece, etc.) create a logical hierarchy for complex data.
46-52: Excellent use of mirascope decorators.The combination of
@track,@with_langfuse, and@llm.calldecorators provides comprehensive telemetry and structured LLM invocation. Usingsettings.LLM.TOM_INFERENCE_PROVIDERandsettings.LLM.TOM_INFERENCE_MODELensures configuration consistency.
53-107: Well-structured prompt template with comprehensive instructions.The prompt template provides clear requirements, output format specification, and proper context formatting. The YAML-like structure in the output format section aligns well with the Pydantic model structure.
src/deriver/tom/single_prompt.py (4)
14-58: Comprehensive Pydantic model hierarchy with strong typing.The extensive model definitions with enums (
InfoType,CertaintyLevel) provide excellent type safety and structure. The nested models create a clear data hierarchy that maps well to the expected LLM outputs.
109-115: Consistent and well-configured LLM call decorators.Both functions use the same provider and model configuration from settings, ensuring consistency across the module. The decorator stack (
@track,@with_langfuse,@llm.call) provides comprehensive telemetry and structured invocation.Also applies to: 160-166
120-157: Detailed and well-structured prompt templates.The prompt templates provide comprehensive instructions with clear output format specifications that align with the Pydantic models. The XML-like section delimiters (
<conversation>,<user_representation>, etc.) help the LLM parse different input contexts correctly.Also applies to: 172-227
60-107: Excellent model design for user representation output.The
UserRepresentationOutputmodel and its nested components provide a comprehensive structure for capturing user information with proper source attribution and certainty levels. The design supports incremental updates and maintains traceability.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
src/config.py (2)
146-146: Consider using mode-specific type ignoring.The
# type: ignorecomment is quite broad. If this is for a specific type checker issue, consider being more specific about what's being ignored.If this is for mypy compatibility, consider using
# type: ignore[misc]or the specific error code being suppressed.
100-100: ```shell
#!/bin/bashDisplay first 50 lines of src/config.py to locate SettingsConfigDict import
sed -n '1,50p' src/config.py
</blockquote></details> </blockquote></details> <details> <summary>📜 Review details</summary> **Configuration used: CodeRabbit UI** **Review profile: CHILL** **Plan: Pro** <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between cc435458117c4d76e64f8d218dfe4e8c6e34014b and 7bd7f259165dd3dc6aac620428c5ac2d159d19d2. </details> <details> <summary>📒 Files selected for processing (1)</summary> * `src/config.py` (8 hunks) </details> <details> <summary>🧰 Additional context used</summary> <details> <summary>🪛 Pylint (3.3.7)</summary> <details> <summary>src/config.py</summary> [refactor] 100-100: Too many arguments (6/5) (R0913) --- [refactor] 100-100: Too many positional arguments (6/5) (R0917) --- [refactor] 153-153: Too few public methods (1/2) (R0903) --- [refactor] 162-162: Too few public methods (1/2) (R0903) </details> </details> </details> <details> <summary>🔇 Additional comments (5)</summary><blockquote> <details> <summary>src/config.py (5)</summary> `3-3`: **Good modernization of typing imports.** Removing `Optional` from the typing imports aligns with the migration to native union syntax throughout the file. --- `144-144`: **Excellent modernization of type annotations.** The migration from `Optional[str]` to `str | None` follows modern Python typing practices and improves readability. This is consistent with the broader typing improvements in the codebase. Also applies to: 157-157, 166-171 --- `192-193`: **Provider type annotation looks correct.** The use of `Provider` type for `TOM_INFERENCE_PROVIDER` is consistent with the Mirascope integration and provides better type safety than using plain strings. --- `183-194`: **Significant change in default LLM providers - verify compatibility.** The default providers have been changed from Groq/Llama models to Gemini/Anthropic models. This is a significant functional change that could affect users who rely on the default configuration. Key changes: - Query generation: `groq`/`llama3-8b-8192` → `gemini`/`gemini-2.0-flash-lite` - TOM inference: `groq`/`llama-3.3-70b-versatile` → `anthropic`/`claude-3-5-haiku-20241022` Ensure that: 1. The new default models are available and stable 2. Existing users are notified of this breaking change 3. The performance characteristics are acceptable ```shell #!/bin/bash # Description: Check if the new model names are used consistently across the codebase # Expected: Should find references to the new model names in other files echo "Checking for new model references:" rg "gemini-2.0-flash-lite|claude-3-5-haiku-20241022" --type py echo "Checking for old model references that might need updating:" rg "llama3-8b-8192|llama-3.3-70b-versatile" --type py
7-7: Verify Mirascope Provider import usage.The
Providertype is imported but I need to verify it's being used correctly in the LLM settings.#!/bin/bash # Description: Verify Provider type usage in the codebase # Expected: Should find usage in TOM_INFERENCE_PROVIDER field and other LLM settings rg -A 3 -B 1 "Provider" --type py
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
src/config.py(9 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/config.py
[refactor] 101-101: Too many arguments (6/5)
(R0913)
[refactor] 101-101: Too many positional arguments (6/5)
(R0917)
[refactor] 154-154: Too few public methods (1/2)
(R0903)
[refactor] 163-163: Too few public methods (1/2)
(R0903)
⏰ Context from checks skipped due to timeout of 90000ms (1)
- GitHub Check: test
🔇 Additional comments (5)
src/config.py (5)
2-2: LGTM: New imports support the configuration changes.The new
osimport is needed for environment variable setting, andmirascope.Providerimport supports the new ToM inference configuration.Also applies to: 8-8
4-4: LGTM: Modernized typing imports.Good modernization removing
Optionalin favor of Python 3.10+ union syntax (| None).
145-145: LGTM: Consistent type annotation modernization.Good consistent update from
Optional[str]tostr | Nonesyntax across all optional string fields.Also applies to: 158-158, 167-172
101-101: Investigate the need for widespread type checker suppression.Multiple
# pyright: ignorecomments are added to suppress type checker warnings onmodel_configassignments. This might indicate an underlying type issue that should be addressed rather than suppressed.#!/bin/bash # Description: Check if there are type issues with model_config assignments that could be fixed instead of suppressed # Expected: Find the specific type warnings that are being suppressed # Search for similar model_config patterns in the codebase to see if this is a common pattern rg -A 2 -B 2 "model_config.*SettingsConfigDict" # Check if there are any other pyright ignore comments in the codebase for comparison rg "pyright.*ignore"Also applies to: 120-120, 142-142, 155-155, 164-164, 208-208, 218-218, 232-232, 240-242
184-188: Verify the provider/model compatibility.The query generation settings are updated from groq/llama to gemini/gemini-2.0-flash-lite. Ensure this model exists and is compatible with the mirascope framework.
Does the Gemini API support the model "gemini-2.0-flash-lite" and is it available in the mirascope library?
| # Tom Inference specific | ||
| # TOM_INFERENCE_PROVIDER: Provider = "groq" | ||
| # TOM_INFERENCE_MODEL: str = "llama-3.3-70b-versatile" | ||
| TOM_INFERENCE_PROVIDER: Provider = "anthropic" | ||
| TOM_INFERENCE_MODEL: str = "claude-3-5-haiku-20241022" | ||
|
|
There was a problem hiding this comment.
Fix the Provider type annotation.
The TOM_INFERENCE_PROVIDER field uses Provider type but is assigned a string value. Based on mirascope usage patterns, this should be a string type.
- TOM_INFERENCE_PROVIDER: Provider = "anthropic"
+ TOM_INFERENCE_PROVIDER: str = "anthropic"📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| # Tom Inference specific | |
| # TOM_INFERENCE_PROVIDER: Provider = "groq" | |
| # TOM_INFERENCE_MODEL: str = "llama-3.3-70b-versatile" | |
| TOM_INFERENCE_PROVIDER: Provider = "anthropic" | |
| TOM_INFERENCE_MODEL: str = "claude-3-5-haiku-20241022" | |
| # Tom Inference specific | |
| # TOM_INFERENCE_PROVIDER: Provider = "groq" | |
| # TOM_INFERENCE_MODEL: str = "llama-3.3-70b-versatile" | |
| - TOM_INFERENCE_PROVIDER: Provider = "anthropic" | |
| + TOM_INFERENCE_PROVIDER: str = "anthropic" | |
| TOM_INFERENCE_MODEL: str = "claude-3-5-haiku-20241022" |
🤖 Prompt for AI Agents
In src/config.py around lines 190 to 195, the TOM_INFERENCE_PROVIDER variable is
annotated with the Provider type but assigned a string value. Change the type
annotation of TOM_INFERENCE_PROVIDER from Provider to str to match the assigned
string value and align with mirascope usage patterns.
VVoruganti
left a comment
There was a problem hiding this comment.
Use settings wherever there are hard coded values and avoid needing to overrwrite the environment itself for the sake of mirascope. we should be passing in the api keys directly
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (3)
src/deriver/tom/long_term.py (2)
46-52: Consistent use of settings for provider configuration.Good improvement using
settings.LLM.TOM_INFERENCE_PROVIDERandsettings.LLM.TOM_INFERENCE_MODELinstead of hardcoded values. This addresses the previous inconsistency mentioned in past reviews.
110-116: Consistent provider configuration maintained.The
extract_facts_long_termfunction now properly uses the same configuration settings asget_user_representation_long_term, resolving the previous inconsistency.src/config.py (1)
271-287: Well-structured environment variable setup.The dedicated
setup_llm_environment_variables()function properly encapsulates the environment setup logic and is called at the appropriate time. This addresses the architectural concern raised in previous reviews.
🧹 Nitpick comments (1)
src/agent.py (1)
209-218: Remove unnecessary else clause after return.The else clause is unnecessary since the if block contains a return statement.
if stream: logger.debug("Calling Dialectic with streaming") response = await dialectic_stream( final_query, user_representation, chat_history ) return response -else: - logger.debug("Calling Dialectic with non-streaming") - response = await dialectic_call(final_query, user_representation, chat_history) - return response +logger.debug("Calling Dialectic with non-streaming") +response = await dialectic_call(final_query, user_representation, chat_history) +return response
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
src/agent.py(10 hunks)src/config.py(8 hunks)src/deriver/tom/long_term.py(4 hunks)src/utils/history.py(6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- src/utils/history.py
🧰 Additional context used
📓 Path-based instructions (1)
`src/deriver/tom/*`: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/*: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/long_term.py
🪛 Pylint (3.3.7)
src/deriver/tom/long_term.py
[refactor] 15-15: Too few public methods (0/2)
(R0903)
[refactor] 21-21: Too few public methods (0/2)
(R0903)
[refactor] 29-29: Too few public methods (0/2)
(R0903)
[refactor] 36-36: Too few public methods (0/2)
(R0903)
[refactor] 41-41: Too few public methods (0/2)
(R0903)
src/agent.py
[refactor] 63-63: Too few public methods (0/2)
(R0903)
[refactor] 209-218: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
src/config.py
[refactor] 101-101: Too many arguments (6/5)
(R0913)
[refactor] 101-101: Too many positional arguments (6/5)
(R0917)
[refactor] 154-154: Too few public methods (1/2)
(R0903)
[refactor] 163-163: Too few public methods (1/2)
(R0903)
🔇 Additional comments (7)
src/deriver/tom/long_term.py (1)
15-44: Well-structured Pydantic models for typed LLM responses.The new Pydantic models provide excellent type safety and structure for the LLM responses. The models follow good practices with clear field types and logical hierarchy.
src/agent.py (4)
26-41: Excellent migration to declarative LLM calls.The new
dialectic_callfunction with mirascope decorators provides much cleaner separation of concerns compared to the previous class-based approach. The use of settings for provider configuration is consistent and maintainable.
63-65: Good use of Pydantic for structured responses.The
SemanticQueriesmodel provides type safety for the LLM response parsing, which is a significant improvement over manual JSON parsing.
272-272: Improved type annotation.Good improvement using the modern union syntax
set[str]instead of the olderSet[str]typing.
309-318: Better structured response parsing.The new approach using structured Pydantic attributes is much more robust than the previous XML parsing approach. The fallback mechanism provides good backward compatibility.
src/config.py (2)
145-171: Modern type annotations improve readability.Good migration from
Optional[str]tostr | Noneunion syntax. This is more concise and aligns with modern Python typing practices.
179-194: Proper use of Provider types from mirascope.The migration to using
Providertypes instead of raw strings provides better type safety and IDE support when working with mirascope LLM calls.
…el parameters; remove unused API keys from GitHub Actions workflow.
…claude-3-5-haiku-20241022'; maintain existing summarization provider.
… remove deprecated environment variable setup for API keys.
There was a problem hiding this comment.
Actionable comments posted: 0
🔭 Outside diff range comments (4)
src/routers/workspaces.py (1)
117-117: Update remaining Optional usage for consistency.This line still uses
Optional[str]while the rest of the file has been updated to use union syntax.Apply this diff for consistency:
- peer_id: Optional[str] = Query(None, description="Optional peer ID to filter by"), + peer_id: str | None = Query(None, description="Optional peer ID to filter by"),Also update lines 118-120 similarly:
- session_id: Optional[str] = Query( + session_id: str | None = Query(src/schemas.py (1)
250-263: Fix missing Optional import causing pipeline failure.The pipeline failure indicates that
Optionalis not defined on lines 249-250. These fields still useOptional[str]but the import was removed.Apply this diff to use union syntax:
- peer_id: Optional[str] = Field( + peer_id: str | None = Field( default=None, description="ID of the peer (optional when filtering by session only)", ) - session_id: Optional[str] = Field( + session_id: str | None = Field( default=None, description="Session ID if filtered by session" )Also update line 263:
- sessions: Optional[dict[str, "DeriverStatus"]] = Field( + sessions: dict[str, "DeriverStatus"] | None = Field(src/crud.py (2)
1679-1679: Fix undefined Optional usage.The
Optionalimport was removed but it's still being used in the function signature. This will cause a runtime error.Apply this diff to use the modern union syntax:
- peer_name: Optional[str] = None, + peer_name: str | None = None,Also update line 1680 in the same function:
- session_name: Optional[str] = None, + session_name: str | None = None,
1720-1722: Fix remaining Optional usages.Additional
Optionalusages need to be updated to use union syntax.Apply this diff to fix the remaining usages:
- peer_name: Optional[str], - session_name: Optional[str], + peer_name: str | None, + session_name: str | None,Let me verify there are no other Optional usages in the file:
#!/bin/bash # Search for any remaining Optional usages in the crud.py file rg "Optional\[" src/crud.py
♻️ Duplicate comments (6)
.github/workflows/staticanalysis.yml (1)
1-22: Add explicit permissions block to limit GITHUB_TOKEN scope.This security issue has been flagged multiple times in past reviews but remains unaddressed. By default, workflows run with full write permissions, which violates security best practices.
Add this permissions block at the top level of the workflow:
name: Static Analysis on: [push] + +permissions: + contents: read jobs:src/utils/clients.py (2)
2-2: Fix incorrect Google Generative AI import.The import
from google import genaiis incorrect and will cause a runtime error. Thegenaimodule is not available directly in theApply this diff to fix the import:
-from google import genai +import google.generativeai as genai
9-9: Fix type annotation mismatch in clients dictionary.The dictionary uses
Provideras the key type but the actual keys are string literals, creating a type mismatch.Apply this diff to fix the type annotation:
-clients: dict[Provider, AsyncAnthropic | AsyncOpenAI | genai.Client | Groq] = {} +clients: dict[str, AsyncAnthropic | AsyncOpenAI | genai.Client | Groq] = {}src/routers/messages.py (1)
314-316: Fix function call in argument defaults.Using
Body(...)in argument defaults can cause issues as the function is called at import time rather than request time.Apply this fix to move the function call inside the function:
async def get_messages( workspace_id: str = Path(..., description="ID of the workspace"), session_id: str = Path(..., description="ID of the session"), - options: schemas.MessageGet | None = Body( - None, description="Filtering options for the messages list" - ), + options: schemas.MessageGet | None = None, reverse: bool | None = Query( False, description="Whether to reverse the order of results" ), db: AsyncSession = db, ): + if options is None: + options = Body(None, description="Filtering options for the messages list")src/config.py (1)
2-2: Remove unused import.The
osmodule is imported but not used anywhere in the file, causing static analysis warnings.Apply this diff:
-import ossrc/routers/peers.py (1)
42-44: Fix function calls in default arguments to avoid potential issues.The existing comment correctly identifies this issue. Using
Body()function calls in argument defaults can cause problems and should be moved inside the function body.Also applies to: 124-126, 267-269
🧹 Nitpick comments (1)
src/agent.py (1)
213-222: Simplify conditional logic by removing unnecessary else clause.The conditional structure can be streamlined by removing the unnecessary
elseclause after thereturnstatement.if stream: logger.debug("Calling Dialectic with streaming") response = await dialectic_stream( final_query, user_representation, chat_history ) return response -else: - logger.debug("Calling Dialectic with non-streaming") - response = await dialectic_call(final_query, user_representation, chat_history) - return response + +logger.debug("Calling Dialectic with non-streaming") +response = await dialectic_call(final_query, user_representation, chat_history) +return response
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock
📒 Files selected for processing (53)
.env.template(1 hunks).github/workflows/staticanalysis.yml(1 hunks).vscode/tasks.json(1 hunks)CLAUDE.md(1 hunks)config.toml.example(1 hunks)docs/contributing/error-handling.mdx(3 hunks)migrations/utils.py(5 hunks)migrations/versions/20f89a421aff_rename_metamessage_type_to_label.py(1 hunks)migrations/versions/556a16564f50_add_user_id_and_app_id_to_tables.py(1 hunks)migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py(1 hunks)migrations/versions/a1b2c3d4e5f6_initial_schema.py(2 hunks)migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py(7 hunks)migrations/versions/c3828084f472_add_indexes_for_messages_and_.py(1 hunks)migrations/versions/d429de0e5338_adopt_peer_paradigm.py(1 hunks)pyproject.toml(4 hunks)src/agent.py(10 hunks)src/config.py(7 hunks)src/crud.py(19 hunks)src/db.py(2 hunks)src/dependencies.py(1 hunks)src/deriver/consumer.py(4 hunks)src/deriver/queue.py(4 hunks)src/deriver/tom/__init__.py(2 hunks)src/deriver/tom/conversational.py(1 hunks)src/deriver/tom/embeddings.py(4 hunks)src/deriver/tom/long_term.py(4 hunks)src/deriver/tom/single_prompt.py(3 hunks)src/exceptions.py(1 hunks)src/main.py(6 hunks)src/models.py(13 hunks)src/routers/messages.py(7 hunks)src/routers/peers.py(11 hunks)src/routers/sessions.py(15 hunks)src/routers/workspaces.py(5 hunks)src/schemas.py(6 hunks)src/security.py(6 hunks)src/utils/cache.py(0 hunks)src/utils/clients.py(1 hunks)src/utils/history.py(6 hunks)src/utils/model_client.py(0 hunks)src/utils/types.py(1 hunks)tests/conftest.py(14 hunks)tests/integration/test_enqueue.py(16 hunks)tests/routes/test_keys.py(3 hunks)tests/routes/test_messages.py(22 hunks)tests/routes/test_peers.py(26 hunks)tests/routes/test_scoped_api.py(11 hunks)tests/routes/test_sessions.py(29 hunks)tests/routes/test_validation_api.py(7 hunks)tests/routes/test_workspaces.py(16 hunks)tests/test_agent.py(1 hunks)tests/test_schema_validations.py(1 hunks)tests/utils/test_model_client.py(0 hunks)
💤 Files with no reviewable changes (3)
- src/utils/cache.py
- tests/utils/test_model_client.py
- src/utils/model_client.py
🚧 Files skipped from review as they are similar to previous changes (35)
- config.toml.example
- .env.template
- .vscode/tasks.json
- CLAUDE.md
- tests/test_schema_validations.py
- migrations/versions/66e63cf2cf77_add_indexes_to_documents_table.py
- src/dependencies.py
- src/db.py
- tests/routes/test_keys.py
- src/utils/types.py
- src/deriver/tom/embeddings.py
- src/deriver/consumer.py
- migrations/versions/c3828084f472_add_indexes_for_messages_and_.py
- tests/test_agent.py
- migrations/versions/a1b2c3d4e5f6_initial_schema.py
- src/exceptions.py
- docs/contributing/error-handling.mdx
- migrations/versions/20f89a421aff_rename_metamessage_type_to_label.py
- src/deriver/queue.py
- migrations/versions/d429de0e5338_adopt_peer_paradigm.py
- tests/routes/test_messages.py
- src/deriver/tom/init.py
- migrations/utils.py
- tests/routes/test_validation_api.py
- src/deriver/tom/conversational.py
- pyproject.toml
- src/utils/history.py
- tests/routes/test_workspaces.py
- migrations/versions/556a16564f50_add_user_id_and_app_id_to_tables.py
- tests/routes/test_scoped_api.py
- migrations/versions/b765d82110bd_change_metamessages_to_user_level_with_.py
- src/security.py
- tests/integration/test_enqueue.py
- tests/routes/test_peers.py
- tests/routes/test_sessions.py
🧰 Additional context used
📓 Path-based instructions (5)
`src/deriver/tom/*`: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/*: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/long_term.pysrc/deriver/tom/single_prompt.py
`tests/conftest.py`: Pytest fixtures should be defined in tests/conftest.py.
tests/conftest.py: Pytest fixtures should be defined in tests/conftest.py.
tests/conftest.py
`src/main.py`: Set up the FastAPI app, including middleware and global exception handlers, in src/main.py.
src/main.py: Set up the FastAPI app, including middleware and global exception handlers, in src/main.py.
src/main.py
`src/models.py`: Use explicit type hints with SQLAlchemy mapped_column annotations.
src/models.py: Use explicit type hints with SQLAlchemy mapped_column annotations.
src/models.py
`src/routers/*.py`: API endpoints should be implemented in the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own module.
src/routers/*.py: API endpoints should be implemented in the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own module.
src/routers/messages.pysrc/routers/peers.pysrc/routers/sessions.pysrc/routers/workspaces.py
🪛 Pylint (3.3.7)
src/deriver/tom/long_term.py
[refactor] 16-16: Too few public methods (0/2)
(R0903)
[refactor] 22-22: Too few public methods (0/2)
(R0903)
[refactor] 30-30: Too few public methods (0/2)
(R0903)
[refactor] 37-37: Too few public methods (0/2)
(R0903)
[refactor] 42-42: Too few public methods (0/2)
(R0903)
src/deriver/tom/single_prompt.py
[refactor] 28-28: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 39-39: Too few public methods (0/2)
(R0903)
[refactor] 44-44: Too few public methods (0/2)
(R0903)
[refactor] 48-48: Too few public methods (0/2)
(R0903)
[refactor] 54-54: Too few public methods (0/2)
(R0903)
[refactor] 62-62: Too few public methods (0/2)
(R0903)
[refactor] 67-67: Too few public methods (0/2)
(R0903)
[refactor] 73-73: Too few public methods (0/2)
(R0903)
[refactor] 79-79: Too few public methods (0/2)
(R0903)
[refactor] 85-85: Too few public methods (0/2)
(R0903)
[refactor] 89-89: Too few public methods (0/2)
(R0903)
[refactor] 95-95: Too few public methods (0/2)
(R0903)
[refactor] 101-101: Too few public methods (0/2)
(R0903)
tests/conftest.py
[refactor] 199-199: Too few public methods (0/2)
(R0903)
src/agent.py
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 213-222: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
src/config.py
[refactor] 101-101: Too many arguments (6/5)
(R0913)
[refactor] 101-101: Too many positional arguments (6/5)
(R0917)
[refactor] 154-154: Too few public methods (1/2)
(R0903)
[refactor] 163-163: Too few public methods (1/2)
(R0903)
src/crud.py
[refactor] 26-26: Too few public methods (1/2)
(R0903)
src/main.py
[error] 71-71: Using variable 'Event' before assignment
(E0601)
[error] 71-71: Using variable 'Hint' before assignment
(E0601)
src/models.py
[refactor] 100-100: Too few public methods (0/2)
(R0903)
[refactor] 122-122: Too few public methods (1/2)
(R0903)
[refactor] 157-157: Too few public methods (1/2)
(R0903)
[refactor] 191-191: Too few public methods (1/2)
(R0903)
[refactor] 256-256: Too few public methods (0/2)
(R0903)
[refactor] 293-293: Too few public methods (0/2)
(R0903)
[refactor] 340-340: Too few public methods (0/2)
(R0903)
[refactor] 353-353: Too few public methods (0/2)
(R0903)
[refactor] 379-379: Too few public methods (0/2)
(R0903)
src/routers/messages.py
[refactor] 57-57: Too many local variables (25/15)
(R0914)
[refactor] 57-57: Too many branches (14/12)
(R0912)
[refactor] 57-57: Too many statements (61/50)
(R0915)
src/schemas.py
[refactor] 25-25: Too few public methods (0/2)
(R0903)
[refactor] 29-29: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 62-62: Too few public methods (0/2)
(R0903)
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 71-71: Too few public methods (0/2)
(R0903)
[refactor] 85-85: Too few public methods (0/2)
(R0903)
[refactor] 112-112: Too few public methods (0/2)
(R0903)
[refactor] 116-116: Too few public methods (0/2)
(R0903)
[refactor] 120-120: Too few public methods (0/2)
(R0903)
[refactor] 170-170: Too few public methods (0/2)
(R0903)
[refactor] 175-175: Too few public methods (0/2)
(R0903)
[refactor] 180-180: Too few public methods (0/2)
(R0903)
[refactor] 195-195: Too few public methods (0/2)
(R0903)
[refactor] 214-214: Too few public methods (0/2)
(R0903)
[error] 231-231: Method 'validate_queries' should have "self" as first argument
(E0213)
[refactor] 219-219: Too few public methods (1/2)
(R0903)
src/utils/clients.py
[error] 2-2: No name 'genai' in module 'google'
(E0611)
🪛 GitHub Check: CodeQL
.github/workflows/staticanalysis.yml
[warning] 6-21: Workflow does not contain permissions
Actions job or workflow does not limit the permissions of the GITHUB_TOKEN. Consider setting an explicit permissions block, using the following as a minimal starting point: {{contents: read}}
🪛 GitHub Check: basedpyright
src/config.py
[warning] 2-2:
Import "os" is not accessed (reportUnusedImport)
🪛 Ruff (0.11.9)
src/config.py
2-2: os imported but unused
Remove unused import: os
(F401)
src/routers/messages.py
314-316: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/peers.py
42-44: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
124-126: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
267-269: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/sessions.py
80-82: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
src/routers/workspaces.py
56-58: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
🪛 Flake8 (7.2.0)
src/config.py
[error] 2-2: 'os' imported but unused
(F401)
🪛 GitHub Actions: Static Analysis
src/config.py
[warning] 2-2: Import "os" is not accessed (reportUnusedImport)
src/crud.py
[warning] 1679-1679: Type of parameter "peer_name" is unknown (reportUnknownParameterType)
[error] 1679-1679: "Optional" is not defined (reportUndefinedVariable)
🪛 GitHub Actions: FastAPI Tests with PostgreSQL and uv
src/schemas.py
[error] 249-250: NameError: name 'Optional' is not defined. Missing import or definition of 'Optional' in the file.
🔇 Additional comments (49)
src/routers/workspaces.py (2)
6-6: LGTM: Excellent type annotation improvements.The explicit typing of
dbparameters asAsyncSessionand the addition of the necessary import significantly improve type safety and static analysis.Also applies to: 27-27, 59-59, 84-84, 102-102
56-56: LGTM: Good migration to union syntax.The change from
Optional[schemas.WorkspaceGet]toschemas.WorkspaceGet | Nonealigns with modern Python typing practices.src/schemas.py (2)
1-1: LGTM: Good typing infrastructure improvements.The pyright ignore directive and removal of
Optionalimport in favor of union syntax align with modern Python typing practices.Also applies to: 3-3
19-20: LGTM: Excellent dictionary type specification.The explicit
dict[str, Any]type annotations provide much better type safety than generic dict types.Also applies to: 26-26, 30-31, 36-39
src/routers/sessions.py (4)
6-6: LGTM: Excellent type annotation improvements.The explicit typing of
dbparameters asAsyncSessionacross all route handlers significantly improves type safety and consistency with other router modules.Also applies to: 36-36, 83-83, 120-120, 143-143, 167-167, 201-201, 233-233, 269-269, 303-303, 325-325, 357-357, 388-388, 464-464
80-80: LGTM: Good migration to union syntax.The consistent use of
| Noneinstead ofOptionalaligns with modern Python typing practices and matches the broader codebase updates.Also applies to: 168-169, 380-383
208-217: LGTM: Good cleanup of redundant variable assignments.The removal of intermediate variable assignments and direct use of parameters in CRUD calls and logging improves code clarity and reduces unnecessary complexity.
Also applies to: 239-253, 276-289
448-448: LGTM: Appropriate pyright ignore for complex typing.The pyright ignore comment is reasonable here for the messages field, likely due to complex SQLAlchemy result typing that's difficult to satisfy statically.
src/main.py (4)
4-15: Excellent type annotation improvements!The conditional imports under
TYPE_CHECKINGand explicit type annotations for collections.abc types enhance type safety without runtime overhead. The Sentry type imports are properly guarded.
71-78: Good type safety and variable handling.The explicit type annotations for
EventandHintparameters and return typeEvent | Noneimprove type safety. Using_to ignore the unusedexc_typevariable follows Python conventions.
103-103: Good practice for unused parameters.Renaming unused parameters to
_or_requestclearly indicates they're intentionally unused, improving code readability and avoiding linter warnings.Also applies to: 157-157, 167-167
179-181: Excellent explicit typing for middleware.The explicit type annotation for
call_nextasCallable[[Request], Awaitable[Response]]provides clear documentation of the expected function signature and improves type safety.src/routers/messages.py (3)
3-3: Good type annotation modernization.Adding explicit
Anyimport andAsyncSessionimport supports the updated type annotations throughout the file.Also applies to: 8-8
28-34: Excellent type annotation improvements.The modern union syntax (
str | None,dict[str, Any]) and explicit parameter typing enhance type safety and readability.Also applies to: 57-60
272-272: Good explicit AsyncSession typing.Adding explicit
AsyncSessiontype annotations for database parameters improves type safety and consistency across the codebase.Also applies to: 320-320, 348-348, 368-368
src/models.py (5)
99-99: Excellent use of @Final decorators for data models.Adding
@finalto all ORM model classes prevents unintended inheritance, which is appropriate for data models that represent database schemas.Also applies to: 121-121, 156-156, 190-190, 255-255, 292-292, 339-339, 352-352, 378-378
101-101: Good explicit typing for table names.Adding explicit
strtype annotations for__tablename__attributes improves type safety and makes the intent clear.Also applies to: 123-123, 158-158, 192-192, 257-257, 294-294, 341-341, 354-354
108-112: Excellent dictionary type specifications.Using
dict[str, Any]for metadata and configuration fields provides precise type information for static analysis while maintaining flexibility for JSON-like data.Also applies to: 126-129, 136-136, 162-165, 201-204, 264-267, 296-298, 348-348, 383-389
244-246: Good use of @OverRide decorator.The
@overridedecorator onMessage.__repr__and proper typing of the event listener function enhance type safety and code clarity.Also applies to: 250-252
380-380: Proper Table type annotation.Explicitly typing the
__table__attribute asTableprovides clear type information for the SessionPeer association class.src/deriver/tom/long_term.py (3)
16-45: Excellent Pydantic model design for structured responses.The new models (
PotentialSurprise,UserRepresentation,InformationPiece,InformationExtraction,FactExtraction) provide clear structure for LLM responses, replacing manual JSON parsing with type-safe data models.
47-54: Great migration to declarative LLM calls.The
@track,@with_langfuse(), and@llm.calldecorators replace manual client handling with a clean, declarative approach. Using settings for provider/model configuration instead of hardcoded values improves maintainability.Also applies to: 112-119
62-109: Much improved prompt structure.The new YAML-like structured prompts with explicit field descriptions are more readable and maintainable than the previous free-text formats with embedded XML tags.
Also applies to: 121-161
src/config.py (3)
145-145: Good modernization of type annotations.Replacing
Optional[str]withstr | Noneunion syntax aligns with modern Python typing practices and improves readability.Also applies to: 158-158, 167-172
120-120: Good addition of pyright ignore comments.Adding
# pyright: ignorecomments for model_config assignments where needed helps maintain type checker compatibility while preserving functionality.Also applies to: 142-142, 155-155, 164-164, 206-206, 216-216, 230-230, 238-240
179-192: Verify Provider type consistency.The LLM provider fields are typed as
Providerbut assigned string values. Ensure thatProviderfrom mirascope is compatible with string assignment, or consider usingstrtype annotation if providers are expected to be strings.What is the Provider type in the mirascope library? Is it a string type alias or a different type that requires specific values?Also applies to: 184-185, 195-195
src/agent.py (8)
27-43: LGTM! Well-structured Mirascope integration for dialectic calls.The new
dialectic_callfunction properly uses Mirascope decorators with appropriate settings and telemetry integration. The prompt template is clear and well-formatted.
46-63: LGTM! Streaming implementation follows the same pattern.The
dialectic_streamfunction correctly mirrors the non-streaming version with thestream=Trueparameter. Good consistency in implementation.
66-88: LGTM! Clean Pydantic model and LLM function implementation.The
SemanticQueriesmodel provides proper typing, and thegenerate_semantic_queries_llmfunction uses appropriate Mirascope decorators with a clear response model specification.
276-276: LGTM! Improved type annotation.The explicit
set[str]type annotation improves code clarity and type safety.
312-322: LGTM! Well-structured Pydantic response processing.The updated response processing correctly handles the structured Pydantic object from the new Mirascope-based ToM inference, with proper attribute access and fallback logic.
341-355: LGTM! Improved error handling with proper fallback.The error handling correctly falls back to the original query and includes proper logging. Good defensive programming practice.
366-366: LGTM! Enhanced type safety and response handling.The function signature improvements with explicit type annotations and the updated response processing logic properly handle both new Mirascope response models and backwards compatibility with XML parsing.
Also applies to: 394-424
98-98: ```shell
#!/bin/bash
set -euxDisplay context around the chat endpoint in src/routers/peers.py
rg -n "router.post.*chat" -A 10 -B 10 src/routers/peers.py
</details> <details> <summary>src/deriver/tom/single_prompt.py (3)</summary> `15-108`: **LGTM! Excellent use of strongly typed models for structured AI responses.** The comprehensive set of Pydantic models with enums provides excellent type safety and structure for ToM inference outputs. The nested model hierarchy properly represents the complex response structure needed for psychological analysis. --- `110-159`: **LGTM! Well-designed ToM inference function with clear prompt structure.** The function properly uses Mirascope decorators and provides a clear, structured prompt template. The output format specification aligns well with the Pydantic models defined above. --- `162-230`: **LGTM! Comprehensive user representation function with detailed requirements.** The function includes thorough requirements and output format specification that ensures consistency with the Pydantic models. The prompt structure with XML-like tags provides clear separation of input data sections. </details> <details> <summary>src/routers/peers.py (3)</summary> `15-16`: **LGTM! Clean import update for Mirascope integration.** The import changes correctly reflect the migration from Anthropic-specific streaming to the unified Mirascope `Stream` interface. --- `42-45`: **LGTM! Excellent type annotation improvements.** The migration from `Optional[T]` to `T | None` syntax and explicit `AsyncSession` typing significantly improves type safety and code clarity throughout the router. Also applies to: 68-68, 105-105, 127-127, 171-171, 220-220, 270-270, 273-273, 309-309, 335-335 --- `192-196`: **LGTM! Proper streaming implementation for Mirascope integration.** The updated streaming logic correctly handles the new `Stream` type from Mirascope with appropriate error handling for unexpected stream types. </details> <details> <summary>tests/conftest.py (5)</summary> `2-36`: **LGTM! Comprehensive import and type annotation improvements.** The extensive type annotations and import organization significantly improve code clarity and type safety throughout the test configuration. --- `40-46`: **LGTM! Excellent type annotation coverage across all fixtures and functions.** The comprehensive type annotations for classes, functions, and fixtures provide excellent type safety and documentation. The explicit typing of generators, async sessions, and mock objects improves test reliability. Also applies to: 73-73, 94-94, 136-136, 160-160, 169-169, 211-214, 238-240, 267-269, 381-381, 400-400 --- `199-201`: **LGTM! Clean extension of TestClient for authentication testing.** The `AuthClient` class provides a clean way to track authentication state during testing. The optional `auth_type` attribute is well-designed for the parameterized authentication fixture. --- `299-357`: **LGTM! Excellent migration from broad client mocks to specific function mocks.** The new `mock_mirascope_functions` fixture correctly targets the specific Mirascope-based functions rather than the old broad client mocks. This provides more precise test control and better reflects the new architecture. The return values are appropriately structured for each function type. --- `400-437`: **LGTM! Properly updated agent API mocks for new function signatures.** The updated mocking correctly targets the new `dialectic_call` and `dialectic_stream` functions instead of the old class-based approach. The mock return values are properly structured to match the expected Mirascope response objects. </details> <details> <summary>src/crud.py (4)</summary> `4-4`: **LGTM! Import cleanup looks good.** The removal of unused `Optional` and `Tuple` imports and addition of `final` decorator is well-executed. --- `25-39`: **Excellent implementation of the new EmbeddingClient.** The class design is clean and focused with proper error handling for missing API keys. The `@final` decorator appropriately prevents inheritance for this utility class. --- `91-92`: **Excellent type annotation improvements throughout.** The migration to modern union syntax (`| None`) and specific `Select[tuple[Model]]` return types significantly improves type safety and readability. Also applies to: 103-103, 245-246, 297-299, 341-343 --- `1-1869`: **Overall excellent typing improvements with one critical fix needed.** The modernization of type annotations and introduction of the new `EmbeddingClient` significantly improves code quality and maintainability. The consistent use of union syntax and specific return types provides better type safety throughout the CRUD operations. Once the `Optional` import issue is resolved, this represents a substantial improvement to the codebase. </details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
…ng; remove unused imports and enhance function signatures for clarity.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
src/schemas.py (1)
231-231: Method signature is correct.The
validate_queriesmethod correctly usesclsas the first parameter for a@field_validatordecorated method. The past review comment flagging this appears to be incorrect.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
src/config.py(7 hunks)src/crud.py(22 hunks)src/routers/workspaces.py(6 hunks)src/schemas.py(8 hunks)tests/routes/test_queue_status.py(15 hunks)
✅ Files skipped from review due to trivial changes (1)
- tests/routes/test_queue_status.py
🧰 Additional context used
📓 Path-based instructions (1)
`src/routers/*.py`: API endpoints should be implemented in the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own module.
src/routers/*.py: API endpoints should be implemented in the src/routers/ directory, with each resource (workspaces, peers, sessions, messages, keys) having its own module.
src/routers/workspaces.py
🪛 Pylint (3.3.7)
src/schemas.py
[refactor] 25-25: Too few public methods (0/2)
(R0903)
[refactor] 29-29: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 62-62: Too few public methods (0/2)
(R0903)
[refactor] 66-66: Too few public methods (0/2)
(R0903)
[refactor] 71-71: Too few public methods (0/2)
(R0903)
[refactor] 85-85: Too few public methods (0/2)
(R0903)
[refactor] 112-112: Too few public methods (0/2)
(R0903)
[refactor] 116-116: Too few public methods (0/2)
(R0903)
[refactor] 120-120: Too few public methods (0/2)
(R0903)
[refactor] 170-170: Too few public methods (0/2)
(R0903)
[refactor] 175-175: Too few public methods (0/2)
(R0903)
[refactor] 180-180: Too few public methods (0/2)
(R0903)
[refactor] 195-195: Too few public methods (0/2)
(R0903)
[refactor] 214-214: Too few public methods (0/2)
(R0903)
[error] 231-231: Method 'validate_queries' should have "self" as first argument
(E0213)
[refactor] 219-219: Too few public methods (1/2)
(R0903)
[refactor] 249-249: Too few public methods (0/2)
(R0903)
[refactor] 256-256: Too few public methods (0/2)
(R0903)
[refactor] 265-265: Too few public methods (0/2)
(R0903)
[refactor] 278-278: Too few public methods (0/2)
(R0903)
[refactor] 285-285: Too few public methods (0/2)
(R0903)
[refactor] 290-290: Too few public methods (0/2)
(R0903)
[refactor] 297-297: Too few public methods (0/2)
(R0903)
src/config.py
[refactor] 100-100: Too many arguments (6/5)
(R0913)
[refactor] 100-100: Too many positional arguments (6/5)
(R0917)
[refactor] 153-153: Too few public methods (1/2)
(R0903)
[refactor] 162-162: Too few public methods (1/2)
(R0903)
src/crud.py
[refactor] 26-26: Too few public methods (1/2)
(R0903)
🪛 Ruff (0.11.9)
src/routers/workspaces.py
56-58: Do not perform function call Body in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
(B008)
🔇 Additional comments (12)
src/routers/workspaces.py (2)
6-6: LGTM! Type annotations improved.The explicit
AsyncSessiontyping for database parameters improves type safety and aligns with the broader typing improvements across the codebase.Also applies to: 27-27, 59-59, 84-84, 102-102, 124-124
117-118: Good modernization of type annotations.The update from
Optional[str]tostr | Nonefollows modern Python typing conventions and improves readability.src/schemas.py (3)
1-1: Good addition of pyright directive.The directive to disable warnings for unannotated class attributes is appropriate for Pydantic models where many attributes are defined through Field() annotations.
19-20: Excellent type annotation improvements.The migration from generic
dicttodict[str, Any]and fromOptional[T]toT | Nonefollows modern Python typing best practices and improves type safety.Also applies to: 26-26, 30-31, 36-39, 56-57, 63-63, 67-68, 75-78, 89-92
249-295: Well-structured new Pydantic models.The addition of
SessionCounts,QueueCounts,QueueStatusRow,PeerConfigResult,SessionPeerData, andMessageBulkDatamodels provides strong typing for queue processing and deriver status functionality. The models are well-documented and follow consistent naming conventions.src/config.py (3)
7-7: Good integration with mirascope framework.The addition of the
Providerimport supports the migration to mirascope-based LLM client management, replacing the previous custom client approach.
144-144: Excellent modernization of type annotations.The update from
Optional[str]tostr | Nonefollows Python 3.10+ best practices and improves code readability.Also applies to: 157-157, 166-171
178-178: Correct use of Provider type.The
Providertype annotation for provider configuration fields is appropriate and aligns with the mirascope framework integration. This ensures type safety for LLM provider specifications.Also applies to: 183-183, 190-190, 194-194
src/crud.py (4)
25-39: Well-implemented EmbeddingClient class.The new
EmbeddingClientprovides a clean abstraction for OpenAI embeddings with proper error handling for missing API keys. The@finaldecorator prevents subclassing, which is appropriate for this utility class.
91-92: Improved type annotations for Select statements.The explicit typing of SQLAlchemy
Selectstatements with tuple types (e.g.,Select[tuple[models.Workspace]]) improves IDE support and type safety, making it clear what models are being selected.Also applies to: 103-103, 246-246, 299-299, 343-343
1802-1836: Excellent migration to Pydantic schemas.The replacement of dictionary returns with structured Pydantic schema instances (
schemas.QueueCounts,schemas.SessionCounts,schemas.DeriverStatus) significantly improves type safety and makes the API more self-documenting.Also applies to: 1840-1841, 1845-1852
245-245: Good modernization of type annotations.The consistent update from
Optional[T]toT | Nonethroughout the codebase follows modern Python typing conventions and improves readability.Also applies to: 298-298, 342-342
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
src/utils/clients.py (1)
3-3: Fix the Google Generative AI import.The import
from google import genaiis incorrect and causes a static analysis error. This should be updated to properly import from the Google Generative AI package.Apply this diff to fix the import:
-from google import genai +import google.generativeai as genai
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/config.py(8 hunks)src/utils/clients.py(1 hunks)
🧰 Additional context used
🪛 Pylint (3.3.7)
src/utils/clients.py
[error] 3-3: No name 'genai' in module 'google'
(E0611)
src/config.py
[refactor] 101-101: Too many arguments (6/5)
(R0913)
[refactor] 101-101: Too many positional arguments (6/5)
(R0917)
[refactor] 154-154: Too few public methods (1/2)
(R0903)
[error] 179-179: Undefined variable 'Provider'
(E0602)
[error] 184-184: Undefined variable 'Provider'
(E0602)
[refactor] 163-163: Too few public methods (1/2)
(R0903)
🪛 Ruff (0.11.9)
src/config.py
179-179: Undefined name Provider
(F821)
184-184: Undefined name Provider
(F821)
🪛 GitHub Check: basedpyright
src/config.py
[failure] 184-184:
"Provider" is not defined (reportUndefinedVariable)
[failure] 179-179:
"Provider" is not defined (reportUndefinedVariable)
🪛 Flake8 (7.2.0)
src/config.py
[error] 179-179: undefined name 'Provider'
(F821)
[error] 184-184: undefined name 'Provider'
(F821)
🪛 GitHub Actions: FastAPI Tests with PostgreSQL and uv
src/config.py
[error] 1-1: ImportError: cannot import name 'settings' from partially initialized module 'src.config' due to a circular import involving 'src.utils.clients'.
🔇 Additional comments (4)
src/utils/clients.py (2)
10-12: Good type definition and dictionary structure.The
Providersunion type andclientsdictionary are well-structured. The type annotation correctly accommodates both standard providers and the custom OpenAI-compatible client.
14-36: Client initialization logic is sound.The conditional initialization based on API key availability is a good pattern. Each client is properly configured with the appropriate settings and added to the clients dictionary.
src/config.py (2)
145-145: Good modernization of type annotations.The migration from
Optional[str]tostr | Nonesyntax is a positive modernization that aligns with Python 3.10+ union syntax standards.Also applies to: 158-158, 167-172
191-195: Consistent use of Providers type.These fields correctly use the
Providerstype, which is the proper imported type for provider configuration.
…iders across multiple modules; update type annotations and improve client management for consistency.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
src/utils/clients.py (1)
2-2: Fix incorrect Google Generative AI importThe import
from google import genaiis causing static analysis errors. The correct import should be from thegoogle.generativeaipackage.Apply this fix:
-from google import genai +import google.generativeai as genai
🧹 Nitpick comments (1)
src/agent.py (1)
225-234: Consider simplifying the conditional structureThe if-else structure can be simplified by removing the unnecessary
elseclause since theifblock returns.Apply this refactor:
if stream: logger.debug("Calling Dialectic with streaming") response = await dialectic_stream( final_query, user_representation, chat_history ) return response -else: - logger.debug("Calling Dialectic with non-streaming") - response = await dialectic_call(final_query, user_representation, chat_history) - return response + +logger.debug("Calling Dialectic with non-streaming") +response = await dialectic_call(final_query, user_representation, chat_history) +return response
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
src/agent.py(10 hunks)src/config.py(8 hunks)src/deriver/tom/conversational.py(1 hunks)src/deriver/tom/long_term.py(4 hunks)src/deriver/tom/single_prompt.py(3 hunks)src/utils/clients.py(1 hunks)src/utils/history.py(6 hunks)src/utils/types.py(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- src/utils/types.py
- src/deriver/tom/conversational.py
- src/utils/history.py
🧰 Additional context used
📓 Path-based instructions (1)
`src/deriver/tom/*`: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/*: Theory of Mind implementations should be placed in src/deriver/tom/.
src/deriver/tom/long_term.pysrc/deriver/tom/single_prompt.py
🪛 Pylint (3.3.7)
src/agent.py
[refactor] 74-74: Too few public methods (0/2)
(R0903)
[refactor] 225-234: Unnecessary "else" after "return", remove the "else" and de-indent the code inside it
(R1705)
src/deriver/tom/long_term.py
[refactor] 16-16: Too few public methods (0/2)
(R0903)
[refactor] 22-22: Too few public methods (0/2)
(R0903)
[refactor] 30-30: Too few public methods (0/2)
(R0903)
[refactor] 37-37: Too few public methods (0/2)
(R0903)
[refactor] 42-42: Too few public methods (0/2)
(R0903)
src/deriver/tom/single_prompt.py
[refactor] 28-28: Too few public methods (0/2)
(R0903)
[refactor] 34-34: Too few public methods (0/2)
(R0903)
[refactor] 39-39: Too few public methods (0/2)
(R0903)
[refactor] 44-44: Too few public methods (0/2)
(R0903)
[refactor] 48-48: Too few public methods (0/2)
(R0903)
[refactor] 54-54: Too few public methods (0/2)
(R0903)
[refactor] 62-62: Too few public methods (0/2)
(R0903)
[refactor] 67-67: Too few public methods (0/2)
(R0903)
[refactor] 73-73: Too few public methods (0/2)
(R0903)
[refactor] 79-79: Too few public methods (0/2)
(R0903)
[refactor] 85-85: Too few public methods (0/2)
(R0903)
[refactor] 89-89: Too few public methods (0/2)
(R0903)
[refactor] 95-95: Too few public methods (0/2)
(R0903)
[refactor] 101-101: Too few public methods (0/2)
(R0903)
src/config.py
[refactor] 101-101: Too many arguments (6/5)
(R0913)
[refactor] 101-101: Too many positional arguments (6/5)
(R0917)
[refactor] 154-154: Too few public methods (1/2)
(R0903)
[refactor] 163-163: Too few public methods (1/2)
(R0903)
src/utils/clients.py
[error] 2-2: No name 'genai' in module 'google'
(E0611)
🔇 Additional comments (23)
src/config.py (5)
3-3: LGTM: Import optimizationGood cleanup removing unused
Optionalimport since the code now uses the modern union syntax (| None).
17-18: LGTM: Type import additionThe import of
Providersfromsrc.utils.typescorrectly resolves the previous circular import issue mentioned in past reviews by moving the type definition to a dedicated types module.
101-101: LGTM: Pyright annotationThe
# pyright: ignorecomment appropriately suppresses type checker warnings for this method signature that may have complex typing requirements.
145-145: LGTM: Modern type annotation syntaxExcellent modernization from
Optional[str]tostr | Nonesyntax, which is the preferred approach in Python 3.10+. The changes are consistent across all nullable fields.Also applies to: 158-158, 167-172
179-192: LGTM: TOM inference configurationThe addition of TOM-specific configuration fields with appropriate defaults aligns well with the mirascope framework integration. The commented alternative configuration provides good flexibility for different deployment scenarios.
src/utils/clients.py (2)
9-9: LGTM: Clean type annotation for clients dictionaryThe type annotation correctly uses
Providersas the key type and a union of client types as values. This provides good type safety for the centralized client management.
11-33: LGTM: Conditional client instantiationThe conditional client creation based on API key availability is well-structured and prevents unnecessary instantiation when credentials aren't provided. The special handling for custom OpenAI-compatible endpoints is appropriate.
src/deriver/tom/long_term.py (4)
3-10: LGTM: Modern framework integrationExcellent refactoring to use the mirascope framework with proper imports for LLM calls, Langfuse integration, and Pydantic models. This provides much better type safety and maintainability than the previous manual approach.
16-45: LGTM: Well-structured Pydantic modelsThe new data models provide clear structure for the response parsing. The
PotentialSurprise,UserRepresentation, and related models offer much better type safety than manual XML/JSON parsing.
47-58: LGTM: Proper configuration usage and decorator stackGood implementation using settings for provider/model configuration and the complete decorator stack (
@track,@with_langfuse,@llm.call). The conditional provider logic handles the custom case appropriately.
66-113: LGTM: Structured prompt templateThe prompt format is well-organized with clear requirements and output format specification. The inclusion of persistent facts enhances the context for user representation generation.
src/agent.py (7)
5-21: LGTM: Clean import structure and framework integrationGood cleanup of imports and proper integration of mirascope framework with Langfuse for telemetry. The imports are focused and necessary.
27-47: LGTM: Well-structured dialectic call functionThe
dialectic_callfunction with proper decorator stack provides clean separation of concerns. The prompt template is well-formatted and the configuration usage follows the established pattern.
74-100: LGTM: Structured semantic query generationThe refactoring to use a Pydantic
SemanticQueriesmodel and declarative LLM call is a significant improvement over manual JSON parsing. The prompt is clear and well-structured.
110-110: LGTM: Modern return type annotationGood use of the modern union syntax
llm.Stream | llm.CallResponsefor return types, improving type clarity.
325-331: LGTM: Improved response parsingThe structured parsing of the Pydantic response model is much more robust than the previous XML parsing approach. The fallback logic provides good backward compatibility.
353-367: LGTM: Robust error handlingGood error handling with fallback to the original query when LLM generation fails. The structured approach with Pydantic models provides better reliability.
378-378: LGTM: Modern type annotationGood modernization of the type annotation from
Optional[str]tostr | None.src/deriver/tom/single_prompt.py (5)
2-10: LGTM: Comprehensive framework integrationExcellent imports bringing in modern typing with enums, mirascope framework, and proper client management. This sets up a strong foundation for type-safe LLM interactions.
15-25: LGTM: Well-designed enums for type safetyThe
InfoTypeandCertaintyLevelenums provide excellent type safety and clarity for the structured responses. This is much better than using magic strings.
28-108: LGTM: Comprehensive Pydantic model hierarchyThe detailed model hierarchy with
CurrentState,TentativeInference,UserRepresentationOutput, etc. provides excellent structure for the LLM responses. This replaces manual parsing with type-safe, validated data structures.
110-163: LGTM: Well-structured tom_inference functionThe
tom_inferencefunction with proper decorator stack and clear prompt template provides excellent separation of concerns. The prompt structure is well-organized with clear requirements and output format.
166-238: LGTM: Comprehensive user_representation functionThe
user_representationfunction follows the same excellent pattern with structured prompts and clear output requirements. The XML-tagged sections provide good structure for the LLM to understand the different input contexts.
* type stuff * add action * bump python * Refactor type annotations and update tracking decorators in agent and dependencies modules. Replace ai_track with track from src.utils.types, and enhance type hints for better clarity. Update pyproject.toml to allow untyped libraries. * type everything basically * fix migration typing * type like crazy * remove usless tests * Update mocks in tests to use AsyncMock for dialectic_call and dialectic_stream, ensuring proper async behavior in test cases. Adjust mock return values for consistency and clarity. * Update src/deriver/tom/single_prompt.py Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Update src/deriver/tom/long_term.py Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Enhance CLAUDE.md documentation with additional details on core concepts, API structure, and development commands. Update command syntax for running server and tests to use 'uv run' for consistency. Improve clarity in configuration and architectural decisions sections. * Refactor type annotations in CRUD functions to accept more flexible filter types, changing from dict[str, str] to dict[str, Any]. Clean up logging in agent.py by removing unnecessary timing logs for user representation generation and query execution. * Remove unused import of ai_track from long_term.py and single_prompt.py to clean up the codebase. * pass tests * update some stuff * fix unused * ruff * make stuff work again * Add LLM_GROQ_API_KEY to GitHub Actions and format tom_inference parameters * test * test * Refactor LLM settings to use 'gemini' provider and update related model parameters; remove unused API keys from GitHub Actions workflow. * Update LLM settings to use 'anthropic' provider and change model to 'claude-3-5-haiku-20241022'; maintain existing summarization provider. * test * llm provider stuff * update * revert * Integrate client management for LLM providers across various modules; remove deprecated environment variable setup for API keys. * only if key avaialble * Refactor type hints and improve schema definitions for queue processing; remove unused imports and enhance function signatures for clarity. * fix test * model * test * Update LLM provider type annotations and enhance client management; replace Provider with Providers for better type handling in config and clients modules. * Refactor LLM provider handling to default to "openai" for custom providers across multiple modules; update type annotations and improve client management for consistency. --------- Co-authored-by: Dani Balcells <18307962+danibalcells@users.noreply.github.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Summary by CodeRabbit
New Features
Refactor
Bug Fixes
Chores