@damiangilgonzalez/copypasta 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -2
- package/catalog.yaml +140 -0
- package/cli/copypasta.js +4 -0
- package/cli/lib/catalog.js +131 -0
- package/cli/lib/commands.js +162 -0
- package/cli/lib/index.js +4 -0
- package/cli/lib/main.js +130 -0
- package/package.json +38 -4
- package/recipes/agents/agent-memory/RECIPE.md +75 -0
- package/recipes/agents/agent-memory/files/agentic/memory/__init__.py +25 -0
- package/recipes/agents/agent-memory/files/agentic/memory/base.py +101 -0
- package/recipes/agents/agent-memory/files/agentic/memory/factory.py +33 -0
- package/recipes/agents/agent-memory/files/agentic/memory/in_memory.py +59 -0
- package/recipes/agents/agent-memory/files/agentic/memory/models.py +66 -0
- package/recipes/agents/agent-memory/files/agentic/memory/settings.py +24 -0
- package/recipes/agents/agent-memory/files/agentic/memory/sql.py +177 -0
- package/recipes/agents/agent-memory/files/pytest.ini +5 -0
- package/recipes/agents/agent-memory/files/tests/__init__.py +0 -0
- package/recipes/agents/agent-memory/files/tests/memory_conformance.py +158 -0
- package/recipes/agents/agent-memory/files/tests/test_memory.py +74 -0
- package/recipes/agents/langchain-agent/RECIPE.md +101 -0
- package/recipes/agents/langchain-agent/files/agentic/__init__.py +10 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/__init__.py +13 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/agents.py +43 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/base_agent.py +126 -0
- package/recipes/agents/langchain-agent/files/agentic/agents/models.py +46 -0
- package/recipes/agents/langchain-agent/files/agentic/context.py +21 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/__init__.py +5 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/models.py +45 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/provider.py +78 -0
- package/recipes/agents/langchain-agent/files/agentic/llm/settings.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/middleware/language.py +28 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/__init__.py +3 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.en.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/assistant.es.yaml +15 -0
- package/recipes/agents/langchain-agent/files/agentic/prompts/loader.py +69 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/__init__.py +25 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/base_tool.py +62 -0
- package/recipes/agents/langchain-agent/files/agentic/tools/search_documents.py +42 -0
- package/recipes/agents/langchain-agent/files/pytest.ini +5 -0
- package/recipes/agents/langchain-agent/files/tests/__init__.py +0 -0
- package/recipes/agents/langchain-agent/files/tests/fakes.py +30 -0
- package/recipes/agents/langchain-agent/files/tests/test_agents.py +151 -0
- package/recipes/agents/langgraph-graph/RECIPE.md +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/conversation.py +73 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/__init__.py +17 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/builder.py +37 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/edges.py +8 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/event_processor.py +48 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/events.py +30 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/graph.py +60 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/nodes.py +63 -0
- package/recipes/agents/langgraph-graph/files/agentic/graph/state.py +31 -0
- package/recipes/agents/langgraph-graph/files/agentic/registry.py +85 -0
- package/recipes/agents/langgraph-graph/files/tests/test_graph.py +145 -0
- package/recipes/backend/.gitkeep +0 -0
- package/recipes/backend/agent-chat-api/RECIPE.md +69 -0
- package/recipes/backend/agent-chat-api/files/api/agent/guards.py +35 -0
- package/recipes/backend/agent-chat-api/files/api/agent/router.py +86 -0
- package/recipes/backend/agent-chat-api/files/api/agent/sanitize.py +22 -0
- package/recipes/backend/agent-chat-api/files/api/agent/schemas.py +26 -0
- package/recipes/backend/agent-chat-api/files/api/agent/settings.py +14 -0
- package/recipes/backend/agent-chat-api/files/api/agent/tracing.py +38 -0
- package/recipes/backend/agent-chat-api/files/api/app.py +67 -0
- package/recipes/backend/agent-chat-api/files/api/auth.py +73 -0
- package/recipes/backend/agent-chat-api/files/pytest.ini +5 -0
- package/recipes/backend/agent-chat-api/files/tests/test_agent_api.py +237 -0
- package/recipes/backend/agent-feedback/RECIPE.md +63 -0
- package/recipes/backend/agent-feedback/files/api/feedback/__init__.py +0 -0
- package/recipes/backend/agent-feedback/files/api/feedback/router.py +72 -0
- package/recipes/backend/agent-feedback/files/api/feedback/schemas.py +44 -0
- package/recipes/backend/agent-feedback/files/feedback/__init__.py +25 -0
- package/recipes/backend/agent-feedback/files/feedback/base.py +53 -0
- package/recipes/backend/agent-feedback/files/feedback/factory.py +30 -0
- package/recipes/backend/agent-feedback/files/feedback/in_memory.py +29 -0
- package/recipes/backend/agent-feedback/files/feedback/models.py +48 -0
- package/recipes/backend/agent-feedback/files/feedback/settings.py +17 -0
- package/recipes/backend/agent-feedback/files/feedback/sql.py +102 -0
- package/recipes/backend/agent-feedback/files/pytest.ini +5 -0
- package/recipes/backend/agent-feedback/files/tests/feedback_conformance.py +89 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback.py +63 -0
- package/recipes/backend/agent-feedback/files/tests/test_feedback_api.py +95 -0
- package/recipes/backend/auth-verifier/RECIPE.md +63 -0
- package/recipes/backend/auth-verifier/files/api/auth.py +73 -0
- package/recipes/backend/auth-verifier/files/auth/__init__.py +23 -0
- package/recipes/backend/auth-verifier/files/auth/factory.py +28 -0
- package/recipes/backend/auth-verifier/files/auth/jwt_verifier.py +101 -0
- package/recipes/backend/auth-verifier/files/auth/models.py +29 -0
- package/recipes/backend/auth-verifier/files/auth/settings.py +45 -0
- package/recipes/backend/auth-verifier/files/auth/supabase.py +80 -0
- package/recipes/backend/auth-verifier/files/pytest.ini +5 -0
- package/recipes/backend/auth-verifier/files/tests/__init__.py +0 -0
- package/recipes/backend/auth-verifier/files/tests/test_auth.py +229 -0
- package/recipes/backend/conversation-history/RECIPE.md +49 -0
- package/recipes/backend/conversation-history/files/api/conversations/__init__.py +0 -0
- package/recipes/backend/conversation-history/files/api/conversations/router.py +55 -0
- package/recipes/backend/conversation-history/files/api/conversations/schemas.py +57 -0
- package/recipes/backend/conversation-history/files/pytest.ini +5 -0
- package/recipes/backend/conversation-history/files/tests/test_conversations_api.py +127 -0
- package/recipes/backend/fastapi-base/RECIPE.md +57 -0
- package/recipes/backend/fastapi-base/files/api/app.py +37 -0
- package/recipes/backend/fastapi-base/files/api/base.py +54 -0
- package/recipes/backend/fastapi-base/files/api/errors.py +31 -0
- package/recipes/backend/fastapi-base/files/api/health.py +19 -0
- package/recipes/backend/fastapi-base/files/api/logging_setup.py +26 -0
- package/recipes/backend/fastapi-base/files/api/request_id.py +62 -0
- package/recipes/backend/fastapi-base/files/api/settings.py +32 -0
- package/recipes/backend/fastapi-base/files/pytest.ini +5 -0
- package/recipes/backend/fastapi-base/files/tests/__init__.py +0 -0
- package/recipes/backend/fastapi-base/files/tests/test_api_base.py +136 -0
- package/recipes/backend/observability/RECIPE.md +68 -0
- package/recipes/backend/observability/files/observability/__init__.py +34 -0
- package/recipes/backend/observability/files/observability/factory.py +73 -0
- package/recipes/backend/observability/files/observability/langfuse_tracer.py +29 -0
- package/recipes/backend/observability/files/observability/langsmith_tracer.py +23 -0
- package/recipes/backend/observability/files/observability/models.py +90 -0
- package/recipes/backend/observability/files/observability/opik_tracer.py +30 -0
- package/recipes/backend/observability/files/observability/settings.py +58 -0
- package/recipes/backend/observability/files/observability/tracer.py +142 -0
- package/recipes/backend/observability/files/observability/usage.py +61 -0
- package/recipes/backend/observability/files/pytest.ini +5 -0
- package/recipes/backend/observability/files/tests/__init__.py +0 -0
- package/recipes/backend/observability/files/tests/test_observability.py +219 -0
- package/recipes/backend/project-settings/RECIPE.md +40 -0
- package/recipes/backend/project-settings/files/.env.example +7 -0
- package/recipes/backend/project-settings/files/core/__init__.py +0 -0
- package/recipes/backend/project-settings/files/core/config.py +41 -0
- package/recipes/backend/project-settings/files/pytest.ini +3 -0
- package/recipes/backend/project-settings/files/tests/__init__.py +0 -0
- package/recipes/backend/project-settings/files/tests/test_settings.py +44 -0
- package/recipes/backend/rag-retriever/RECIPE.md +79 -0
- package/recipes/backend/rag-retriever/files/pytest.ini +5 -0
- package/recipes/backend/rag-retriever/files/rag/__init__.py +53 -0
- package/recipes/backend/rag-retriever/files/rag/base.py +106 -0
- package/recipes/backend/rag-retriever/files/rag/chunking.py +84 -0
- package/recipes/backend/rag-retriever/files/rag/document_search.py +60 -0
- package/recipes/backend/rag-retriever/files/rag/embeddings.py +91 -0
- package/recipes/backend/rag-retriever/files/rag/factory.py +82 -0
- package/recipes/backend/rag-retriever/files/rag/in_memory.py +52 -0
- package/recipes/backend/rag-retriever/files/rag/models.py +107 -0
- package/recipes/backend/rag-retriever/files/rag/pgvector.py +138 -0
- package/recipes/backend/rag-retriever/files/rag/qdrant.py +96 -0
- package/recipes/backend/rag-retriever/files/rag/settings.py +48 -0
- package/recipes/backend/rag-retriever/files/tests/__init__.py +0 -0
- package/recipes/backend/rag-retriever/files/tests/rag_conformance.py +95 -0
- package/recipes/backend/rag-retriever/files/tests/test_rag.py +270 -0
- package/recipes/backend/rate-limit-quota/RECIPE.md +77 -0
- package/recipes/backend/rate-limit-quota/files/api/agent/guards.py +62 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/__init__.py +0 -0
- package/recipes/backend/rate-limit-quota/files/api/limits/router.py +38 -0
- package/recipes/backend/rate-limit-quota/files/limits/__init__.py +43 -0
- package/recipes/backend/rate-limit-quota/files/limits/base.py +161 -0
- package/recipes/backend/rate-limit-quota/files/limits/factory.py +69 -0
- package/recipes/backend/rate-limit-quota/files/limits/in_memory.py +36 -0
- package/recipes/backend/rate-limit-quota/files/limits/models.py +108 -0
- package/recipes/backend/rate-limit-quota/files/limits/settings.py +32 -0
- package/recipes/backend/rate-limit-quota/files/limits/sql.py +94 -0
- package/recipes/backend/rate-limit-quota/files/pytest.ini +5 -0
- package/recipes/backend/rate-limit-quota/files/tests/limits_conformance.py +146 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits.py +167 -0
- package/recipes/backend/rate-limit-quota/files/tests/test_limits_api.py +100 -0
- package/recipes/backend/voice-providers/RECIPE.md +73 -0
- package/recipes/backend/voice-providers/files/api/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/api/voice/router.py +113 -0
- package/recipes/backend/voice-providers/files/pytest.ini +5 -0
- package/recipes/backend/voice-providers/files/tests/__init__.py +0 -0
- package/recipes/backend/voice-providers/files/tests/fake_openai.py +44 -0
- package/recipes/backend/voice-providers/files/tests/test_voice.py +164 -0
- package/recipes/backend/voice-providers/files/tests/test_voice_api.py +106 -0
- package/recipes/backend/voice-providers/files/tests/voice_conformance.py +80 -0
- package/recipes/backend/voice-providers/files/voice/__init__.py +29 -0
- package/recipes/backend/voice-providers/files/voice/base.py +116 -0
- package/recipes/backend/voice-providers/files/voice/factory.py +48 -0
- package/recipes/backend/voice-providers/files/voice/fake.py +51 -0
- package/recipes/backend/voice-providers/files/voice/models.py +85 -0
- package/recipes/backend/voice-providers/files/voice/openai_provider.py +116 -0
- package/recipes/backend/voice-providers/files/voice/settings.py +48 -0
- package/recipes/frontend/.gitkeep +0 -0
- package/recipes/frontend/playwright-e2e/RECIPE.md +48 -0
- package/recipes/frontend/playwright-e2e/files/.github/workflows/frontend.yml +35 -0
- package/recipes/frontend/playwright-e2e/files/e2e/helpers.ts +25 -0
- package/recipes/frontend/playwright-e2e/files/e2e/home.spec.ts +10 -0
- package/recipes/frontend/playwright-e2e/files/e2e/login.spec.ts +26 -0
- package/recipes/frontend/playwright-e2e/files/e2e/navigation.spec.ts +27 -0
- package/recipes/frontend/playwright-e2e/files/playwright.config.ts +35 -0
- package/recipes/frontend/react-agent-chat/RECIPE.md +69 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat-api.ts +27 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.css +18 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/chat.test.tsx +139 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/ChatView.tsx +22 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Composer.tsx +40 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/Markdown.tsx +20 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/components/MessageList.tsx +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/events.ts +42 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/fake-chat-api.ts +44 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/index.ts +6 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.test.ts +97 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/sse-parser.ts +85 -0
- package/recipes/frontend/react-agent-chat/files/src/features/chat/use-chat.ts +136 -0
- package/recipes/frontend/react-app-router/RECIPE.md +58 -0
- package/recipes/frontend/react-app-router/files/src/App.test.tsx +54 -0
- package/recipes/frontend/react-app-router/files/src/App.tsx +14 -0
- package/recipes/frontend/react-app-router/files/src/router/ErrorScreen.tsx +21 -0
- package/recipes/frontend/react-app-router/files/src/router/Layout.tsx +28 -0
- package/recipes/frontend/react-app-router/files/src/router/NotFoundScreen.tsx +12 -0
- package/recipes/frontend/react-app-router/files/src/router/index.ts +1 -0
- package/recipes/frontend/react-app-router/files/src/router/router.css +29 -0
- package/recipes/frontend/react-app-router/files/src/router/router.test.tsx +65 -0
- package/recipes/frontend/react-app-router/files/src/router/routes.tsx +59 -0
- package/recipes/frontend/react-app-router/files/src/screens/SettingsScreen.tsx +10 -0
- package/recipes/frontend/react-supabase-auth/RECIPE.md +77 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/LoginScreen.tsx +64 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/SignOutButton.tsx +12 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.css +33 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.test.ts +149 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/auth.ts +59 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-auth.ts +87 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/fake-gotrue.ts +85 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/index.ts +7 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/make-auth.ts +20 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-context.tsx +35 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session-store.ts +63 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/session.test.tsx +56 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/settings.ts +30 -0
- package/recipes/frontend/react-supabase-auth/files/src/auth/supabase-auth.ts +85 -0
- package/recipes/frontend/vite-react-base/RECIPE.md +69 -0
- package/recipes/frontend/vite-react-base/files/.env +6 -0
- package/recipes/frontend/vite-react-base/files/.env.fake +2 -0
- package/recipes/frontend/vite-react-base/files/index.html +12 -0
- package/recipes/frontend/vite-react-base/files/package.json +30 -0
- package/recipes/frontend/vite-react-base/files/src/App.test.tsx +49 -0
- package/recipes/frontend/vite-react-base/files/src/App.tsx +13 -0
- package/recipes/frontend/vite-react-base/files/src/api/api.ts +37 -0
- package/recipes/frontend/vite-react-base/files/src/api/fake/fake-api.ts +29 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-api.ts +16 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.test.ts +84 -0
- package/recipes/frontend/vite-react-base/files/src/api/http-client.ts +94 -0
- package/recipes/frontend/vite-react-base/files/src/api/make-api.ts +30 -0
- package/recipes/frontend/vite-react-base/files/src/api/types.ts +7 -0
- package/recipes/frontend/vite-react-base/files/src/app-context.tsx +24 -0
- package/recipes/frontend/vite-react-base/files/src/auth/token-provider.ts +27 -0
- package/recipes/frontend/vite-react-base/files/src/config.ts +18 -0
- package/recipes/frontend/vite-react-base/files/src/hooks/use-load.ts +46 -0
- package/recipes/frontend/vite-react-base/files/src/main.tsx +27 -0
- package/recipes/frontend/vite-react-base/files/src/screens/HomeScreen.tsx +28 -0
- package/recipes/frontend/vite-react-base/files/src/styles/global.css +25 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.css +33 -0
- package/recipes/frontend/vite-react-base/files/src/styles/tokens.test.ts +45 -0
- package/recipes/frontend/vite-react-base/files/src/test-setup.ts +8 -0
- package/recipes/frontend/vite-react-base/files/src/vite-env.d.ts +11 -0
- package/recipes/frontend/vite-react-base/files/tsconfig.json +18 -0
- package/recipes/frontend/vite-react-base/files/vite.config.ts +19 -0
- package/unpacked-files.json +3 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from enum import StrEnum
|
|
3
|
+
|
|
4
|
+
from langchain_core.messages import BaseMessage
|
|
5
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class MemoryBackend(StrEnum):
|
|
9
|
+
"""Where the conversation lives. Chosen in the settings (`MEMORY_BACKEND`), built by `MemoryFactory`.
|
|
10
|
+
|
|
11
|
+
IN_MEMORY: a dict of the process. Lost on restart, not shared between workers: tests and local dev.
|
|
12
|
+
SQL: the `agent_messages` table (Postgres/Supabase in production, SQLite in tests).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
IN_MEMORY = "in_memory"
|
|
16
|
+
SQL = "sql"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MemoryKey(BaseModel):
|
|
20
|
+
"""One conversation thread: the THREE ids, always.
|
|
21
|
+
|
|
22
|
+
`conversation_id` is chosen by the client, so using it alone would let tenant B read tenant A's
|
|
23
|
+
thread by guessing it. `tenant_id` and `user_id` come from the auth token, never from the body.
|
|
24
|
+
Frozen: a key that can change between `get` and `add` is a key that can be swapped.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
model_config = ConfigDict(frozen=True)
|
|
28
|
+
|
|
29
|
+
tenant_id: str = Field(min_length=1, description="Tenant. From the token.")
|
|
30
|
+
user_id: str = Field(min_length=1, description="Who asks. From the token.")
|
|
31
|
+
conversation_id: str = Field(min_length=1, description="The thread. Sent by the client.")
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def thread_id(self) -> str:
|
|
35
|
+
"""Flat id with the server namespace first (for tracing / `run_config`)."""
|
|
36
|
+
return f"{self.tenant_id}:{self.user_id}:{self.conversation_id}"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class HistoryMessage(BaseModel):
|
|
40
|
+
"""A stored message with when it was stored. What `get_history` returns (for display, not for the LLM)."""
|
|
41
|
+
|
|
42
|
+
model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)
|
|
43
|
+
|
|
44
|
+
message: BaseMessage
|
|
45
|
+
created_at: datetime
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ConversationSummary(BaseModel):
|
|
49
|
+
"""One row of the conversation list. `title` is the first human message, trimmed."""
|
|
50
|
+
|
|
51
|
+
model_config = ConfigDict(frozen=True)
|
|
52
|
+
|
|
53
|
+
conversation_id: str
|
|
54
|
+
title: str
|
|
55
|
+
created_at: datetime
|
|
56
|
+
updated_at: datetime
|
|
57
|
+
message_count: int = Field(ge=0)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
TITLE_MAX_LENGTH = 60
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def title_from(text: str, *, max_length: int = TITLE_MAX_LENGTH) -> str:
|
|
64
|
+
"""First line of the first human message, whitespace collapsed, cut with an ellipsis."""
|
|
65
|
+
flat = " ".join(str(text).split())
|
|
66
|
+
return flat if len(flat) <= max_length else flat[: max_length - 1].rstrip() + "…"
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Memory settings BLOCK, meant to be mixed into the project settings (`project-settings` recipe):
|
|
2
|
+
|
|
3
|
+
# core/config.py
|
|
4
|
+
from agentic.memory.settings import MemorySettings
|
|
5
|
+
|
|
6
|
+
class Settings(MemorySettings, BaseAppSettings): ...
|
|
7
|
+
|
|
8
|
+
Env vars: MEMORY_BACKEND (required: in_memory | sql), MEMORY_WINDOW_TURNS (default 10).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from pydantic import Field
|
|
12
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
13
|
+
|
|
14
|
+
from .models import MemoryBackend
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class MemorySettings(BaseSettings):
|
|
18
|
+
model_config = SettingsConfigDict(extra="ignore")
|
|
19
|
+
|
|
20
|
+
# No default on purpose: falling back to in-process memory "just in case" turns a config
|
|
21
|
+
# mistake into history silently lost on every restart.
|
|
22
|
+
memory_backend: MemoryBackend
|
|
23
|
+
# How many TURNS are sent back to the LLM. Everything is stored; this only bounds what is read.
|
|
24
|
+
memory_window_turns: int = Field(default=10, ge=1)
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""SQL memory (Postgres/Supabase in production, SQLite in tests) with SQLAlchemy 2.
|
|
2
|
+
|
|
3
|
+
Messages are stored whole with `message_to_dict` so `tool_calls` and `tool_call_id` survive:
|
|
4
|
+
without them the history cannot be sent back to the LLM.
|
|
5
|
+
|
|
6
|
+
The session factory is the app's (`SessionLocal`): memory shares the app database, it does not
|
|
7
|
+
open its own connection. Queries are sync and run in a thread (`asyncio.to_thread`) so they never
|
|
8
|
+
block the event loop. With an async engine, swap the `_sync` methods for async versions.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
|
|
15
|
+
from langchain_core.messages import BaseMessage, message_to_dict, messages_from_dict
|
|
16
|
+
from sqlalchemy import JSON, Column, DateTime, Integer, MetaData, String, Table, UniqueConstraint, delete, func, select
|
|
17
|
+
from sqlalchemy.orm import Session
|
|
18
|
+
|
|
19
|
+
from .base import Memory
|
|
20
|
+
from .models import ConversationSummary, HistoryMessage, MemoryKey, title_from
|
|
21
|
+
|
|
22
|
+
metadata = MetaData()
|
|
23
|
+
|
|
24
|
+
agent_messages = Table(
|
|
25
|
+
"agent_messages",
|
|
26
|
+
metadata,
|
|
27
|
+
Column("seq", Integer, primary_key=True, autoincrement=True),
|
|
28
|
+
Column("tenant_id", String, nullable=False, index=True),
|
|
29
|
+
Column("user_id", String, nullable=False),
|
|
30
|
+
Column("conversation_id", String, nullable=False, index=True),
|
|
31
|
+
Column("message_id", String, nullable=True), # NULL allowed: messages without id are always appended
|
|
32
|
+
Column("role", String, nullable=False),
|
|
33
|
+
Column("message", JSON, nullable=False),
|
|
34
|
+
Column("created_at", DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC)),
|
|
35
|
+
UniqueConstraint("tenant_id", "user_id", "conversation_id", "message_id", name="uq_agent_messages_thread_msg"),
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _aware(value: datetime) -> datetime:
|
|
40
|
+
"""SQLite drops the timezone; Postgres keeps it. Always hand back UTC-aware datetimes."""
|
|
41
|
+
return value if value.tzinfo else value.replace(tzinfo=UTC)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SqlMemory(Memory):
|
|
45
|
+
def __init__(self, session_factory: Callable[[], Session], **kwargs) -> None:
|
|
46
|
+
super().__init__(**kwargs)
|
|
47
|
+
self._session_factory = session_factory
|
|
48
|
+
|
|
49
|
+
@staticmethod
|
|
50
|
+
def _thread(query, key: MemoryKey):
|
|
51
|
+
"""The ONLY place that filters by thread: always the three ids."""
|
|
52
|
+
return query.where(
|
|
53
|
+
agent_messages.c.tenant_id == key.tenant_id,
|
|
54
|
+
agent_messages.c.user_id == key.user_id,
|
|
55
|
+
agent_messages.c.conversation_id == key.conversation_id,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
async def _fetch_recent_turns(self, key: MemoryKey, turns: int) -> list[BaseMessage]:
|
|
59
|
+
return await asyncio.to_thread(self._fetch_sync, key, turns)
|
|
60
|
+
|
|
61
|
+
def _fetch_sync(self, key: MemoryKey, turns: int) -> list[BaseMessage]:
|
|
62
|
+
with self._session_factory() as db:
|
|
63
|
+
start = db.execute(
|
|
64
|
+
self._thread(select(agent_messages.c.seq), key)
|
|
65
|
+
.where(agent_messages.c.role == "human")
|
|
66
|
+
.order_by(agent_messages.c.seq.desc())
|
|
67
|
+
.limit(1)
|
|
68
|
+
.offset(turns - 1)
|
|
69
|
+
).scalar()
|
|
70
|
+
query = self._thread(select(agent_messages.c.message), key)
|
|
71
|
+
if start is not None:
|
|
72
|
+
query = query.where(agent_messages.c.seq >= start)
|
|
73
|
+
rows = db.execute(query.order_by(agent_messages.c.seq)).scalars().all()
|
|
74
|
+
return messages_from_dict(list(rows))
|
|
75
|
+
|
|
76
|
+
async def _append(self, key: MemoryKey, messages: list[BaseMessage]) -> None:
|
|
77
|
+
await asyncio.to_thread(self._append_sync, key, messages, self._clock())
|
|
78
|
+
|
|
79
|
+
def _append_sync(self, key: MemoryKey, messages: list[BaseMessage], now: datetime) -> None:
|
|
80
|
+
ids = [m.id for m in messages if m.id]
|
|
81
|
+
with self._session_factory() as db:
|
|
82
|
+
seen = set()
|
|
83
|
+
if ids:
|
|
84
|
+
seen = set(
|
|
85
|
+
db.execute(
|
|
86
|
+
self._thread(select(agent_messages.c.message_id), key).where(
|
|
87
|
+
agent_messages.c.message_id.in_(ids)
|
|
88
|
+
)
|
|
89
|
+
).scalars()
|
|
90
|
+
)
|
|
91
|
+
rows = []
|
|
92
|
+
for message in messages:
|
|
93
|
+
if message.id and message.id in seen:
|
|
94
|
+
continue
|
|
95
|
+
if message.id:
|
|
96
|
+
seen.add(message.id)
|
|
97
|
+
rows.append(
|
|
98
|
+
{
|
|
99
|
+
"tenant_id": key.tenant_id,
|
|
100
|
+
"user_id": key.user_id,
|
|
101
|
+
"conversation_id": key.conversation_id,
|
|
102
|
+
"message_id": message.id,
|
|
103
|
+
"role": message.type,
|
|
104
|
+
"message": message_to_dict(message),
|
|
105
|
+
"created_at": now,
|
|
106
|
+
}
|
|
107
|
+
)
|
|
108
|
+
if rows:
|
|
109
|
+
db.execute(agent_messages.insert(), rows)
|
|
110
|
+
db.commit()
|
|
111
|
+
|
|
112
|
+
async def get_history(self, key: MemoryKey) -> list[HistoryMessage]:
|
|
113
|
+
return await asyncio.to_thread(self._history_sync, key)
|
|
114
|
+
|
|
115
|
+
def _history_sync(self, key: MemoryKey) -> list[HistoryMessage]:
|
|
116
|
+
with self._session_factory() as db:
|
|
117
|
+
rows = db.execute(
|
|
118
|
+
self._thread(select(agent_messages.c.message, agent_messages.c.created_at), key).order_by(
|
|
119
|
+
agent_messages.c.seq
|
|
120
|
+
)
|
|
121
|
+
).all()
|
|
122
|
+
return [
|
|
123
|
+
HistoryMessage(message=messages_from_dict([message])[0], created_at=_aware(created_at))
|
|
124
|
+
for message, created_at in rows
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
async def list_conversations(
|
|
128
|
+
self, tenant_id: str, user_id: str, *, limit: int = 50, offset: int = 0
|
|
129
|
+
) -> list[ConversationSummary]:
|
|
130
|
+
return await asyncio.to_thread(self._list_sync, tenant_id, user_id, limit, offset)
|
|
131
|
+
|
|
132
|
+
def _list_sync(self, tenant_id: str, user_id: str, limit: int, offset: int) -> list[ConversationSummary]:
|
|
133
|
+
c = agent_messages.c
|
|
134
|
+
mine = (c.tenant_id == tenant_id, c.user_id == user_id)
|
|
135
|
+
with self._session_factory() as db:
|
|
136
|
+
# One row per conversation, newest activity first (seq is monotonic, so max(seq) orders by update).
|
|
137
|
+
page = db.execute(
|
|
138
|
+
select(c.conversation_id, func.min(c.created_at), func.max(c.created_at), func.count(), func.max(c.seq))
|
|
139
|
+
.where(*mine)
|
|
140
|
+
.group_by(c.conversation_id)
|
|
141
|
+
.order_by(func.max(c.seq).desc())
|
|
142
|
+
.limit(limit)
|
|
143
|
+
.offset(offset)
|
|
144
|
+
).all()
|
|
145
|
+
if not page:
|
|
146
|
+
return []
|
|
147
|
+
# The first human message of each conversation on the page: its title.
|
|
148
|
+
first_human = (
|
|
149
|
+
select(c.conversation_id, func.min(c.seq).label("seq"))
|
|
150
|
+
.where(*mine, c.role == "human", c.conversation_id.in_([row[0] for row in page]))
|
|
151
|
+
.group_by(c.conversation_id)
|
|
152
|
+
.subquery()
|
|
153
|
+
)
|
|
154
|
+
titles = {
|
|
155
|
+
conversation_id: title_from(messages_from_dict([message])[0].text)
|
|
156
|
+
for conversation_id, message in db.execute(
|
|
157
|
+
select(c.conversation_id, c.message).join(first_human, c.seq == first_human.c.seq)
|
|
158
|
+
).all()
|
|
159
|
+
}
|
|
160
|
+
return [
|
|
161
|
+
ConversationSummary(
|
|
162
|
+
conversation_id=conversation_id,
|
|
163
|
+
title=titles.get(conversation_id, ""),
|
|
164
|
+
created_at=_aware(created_at),
|
|
165
|
+
updated_at=_aware(updated_at),
|
|
166
|
+
message_count=count,
|
|
167
|
+
)
|
|
168
|
+
for conversation_id, created_at, updated_at, count, _ in page
|
|
169
|
+
]
|
|
170
|
+
|
|
171
|
+
async def clear(self, key: MemoryKey) -> None:
|
|
172
|
+
await asyncio.to_thread(self._clear_sync, key)
|
|
173
|
+
|
|
174
|
+
def _clear_sync(self, key: MemoryKey) -> None:
|
|
175
|
+
with self._session_factory() as db:
|
|
176
|
+
db.execute(self._thread(delete(agent_messages), key))
|
|
177
|
+
db.commit()
|
|
File without changes
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Behaviour every `Memory` backend must have. A new backend = a subclass with a `memory` fixture.
|
|
2
|
+
|
|
3
|
+
class TestRedisMemory(MemoryConformance):
|
|
4
|
+
@pytest.fixture
|
|
5
|
+
def memory(self, clock): return RedisMemory(..., clock=clock)
|
|
6
|
+
|
|
7
|
+
`clock` is a `FakeClock` (starts at START): tests move time with `clock.advance(seconds)`.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from datetime import UTC, datetime, timedelta
|
|
11
|
+
|
|
12
|
+
import pytest
|
|
13
|
+
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
|
14
|
+
|
|
15
|
+
from agentic.memory import MemoryKey
|
|
16
|
+
|
|
17
|
+
KEY = MemoryKey(tenant_id="tenant-1", user_id="user-1", conversation_id="conv-1")
|
|
18
|
+
START = datetime(2026, 3, 30, 10, 0, tzinfo=UTC)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class FakeClock:
|
|
22
|
+
def __init__(self, now: datetime = START) -> None:
|
|
23
|
+
self.now = now
|
|
24
|
+
|
|
25
|
+
def __call__(self) -> datetime:
|
|
26
|
+
return self.now
|
|
27
|
+
|
|
28
|
+
def advance(self, seconds: float) -> None:
|
|
29
|
+
self.now += timedelta(seconds=seconds)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.fixture
|
|
33
|
+
def clock() -> FakeClock:
|
|
34
|
+
return FakeClock()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def turn(n: int, *, with_tool: bool = False) -> list:
|
|
38
|
+
messages = [HumanMessage(f"q{n}", id=f"h{n}")]
|
|
39
|
+
if with_tool:
|
|
40
|
+
messages += [
|
|
41
|
+
AIMessage("", id=f"call{n}", tool_calls=[{"name": "search", "args": {"q": n}, "id": f"t{n}"}]),
|
|
42
|
+
ToolMessage("ok", tool_call_id=f"t{n}", id=f"tool{n}"),
|
|
43
|
+
]
|
|
44
|
+
return messages + [AIMessage(f"a{n}", id=f"a{n}")]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def texts(messages) -> list[str]:
|
|
48
|
+
return [m.content for m in messages]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class MemoryConformance:
|
|
52
|
+
async def test_unknown_thread_is_empty(self, memory):
|
|
53
|
+
assert await memory.get_messages(KEY) == []
|
|
54
|
+
|
|
55
|
+
async def test_round_trip_keeps_order_and_tool_calls(self, memory):
|
|
56
|
+
await memory.add_messages(KEY, turn(1, with_tool=True))
|
|
57
|
+
|
|
58
|
+
got = await memory.get_messages(KEY)
|
|
59
|
+
|
|
60
|
+
assert got == turn(1, with_tool=True)
|
|
61
|
+
assert got[1].tool_calls[0]["id"] == "t1"
|
|
62
|
+
assert got[2].tool_call_id == "t1"
|
|
63
|
+
|
|
64
|
+
async def test_window_counts_turns_and_never_splits_a_tool(self, memory):
|
|
65
|
+
await memory.add_messages(KEY, turn(1))
|
|
66
|
+
await memory.add_messages(KEY, turn(2, with_tool=True))
|
|
67
|
+
await memory.add_messages(KEY, turn(3))
|
|
68
|
+
|
|
69
|
+
last_two = await memory.get_messages(KEY, turns=2)
|
|
70
|
+
|
|
71
|
+
assert texts(last_two)[0] == "q2" # starts at a human message, tool call and result together
|
|
72
|
+
assert len(last_two) == 4 + 2
|
|
73
|
+
|
|
74
|
+
async def test_default_window_comes_from_settings(self, memory):
|
|
75
|
+
for n in range(1, memory.window_turns + 3):
|
|
76
|
+
await memory.add_messages(KEY, turn(n))
|
|
77
|
+
got = await memory.get_messages(KEY)
|
|
78
|
+
assert sum(m.type == "human" for m in got) == memory.window_turns
|
|
79
|
+
|
|
80
|
+
async def test_zero_turns_is_an_error(self, memory):
|
|
81
|
+
with pytest.raises(ValueError):
|
|
82
|
+
await memory.get_messages(KEY, turns=0)
|
|
83
|
+
|
|
84
|
+
async def test_threads_are_isolated_by_tenant_and_user(self, memory):
|
|
85
|
+
await memory.add_messages(KEY, turn(1))
|
|
86
|
+
other_tenant = MemoryKey(tenant_id="tenant-2", user_id="user-1", conversation_id="conv-1")
|
|
87
|
+
other_user = MemoryKey(tenant_id="tenant-1", user_id="user-2", conversation_id="conv-1")
|
|
88
|
+
assert await memory.get_messages(other_tenant) == []
|
|
89
|
+
assert await memory.get_messages(other_user) == []
|
|
90
|
+
|
|
91
|
+
async def test_retry_with_same_ids_does_not_duplicate(self, memory):
|
|
92
|
+
await memory.add_messages(KEY, turn(1, with_tool=True))
|
|
93
|
+
await memory.add_messages(KEY, turn(1, with_tool=True))
|
|
94
|
+
|
|
95
|
+
assert len(await memory.get_messages(KEY)) == 4
|
|
96
|
+
|
|
97
|
+
async def test_messages_without_id_are_always_appended(self, memory):
|
|
98
|
+
await memory.add_messages(KEY, [HumanMessage("hola"), AIMessage("hey")])
|
|
99
|
+
await memory.add_messages(KEY, [HumanMessage("hola"), AIMessage("hey")])
|
|
100
|
+
assert texts(await memory.get_messages(KEY)) == ["hola", "hey", "hola", "hey"]
|
|
101
|
+
|
|
102
|
+
async def test_add_returns_the_answer_id(self, memory):
|
|
103
|
+
assert await memory.add_messages(KEY, turn(1, with_tool=True)) == "a1"
|
|
104
|
+
assert await memory.add_messages(KEY, [HumanMessage("x", id="hx")]) is None
|
|
105
|
+
|
|
106
|
+
async def test_clear_forgets_only_that_thread(self, memory):
|
|
107
|
+
other = MemoryKey(tenant_id="tenant-1", user_id="user-1", conversation_id="conv-2")
|
|
108
|
+
await memory.add_messages(KEY, turn(1))
|
|
109
|
+
await memory.add_messages(other, turn(1))
|
|
110
|
+
|
|
111
|
+
await memory.clear(KEY)
|
|
112
|
+
|
|
113
|
+
assert await memory.get_messages(KEY) == []
|
|
114
|
+
assert len(await memory.get_messages(other)) == 2
|
|
115
|
+
|
|
116
|
+
# --- History and conversation list (what `conversation-history` exposes) -------------------
|
|
117
|
+
|
|
118
|
+
async def test_history_is_the_whole_thread_with_timestamps(self, memory, clock):
|
|
119
|
+
await memory.add_messages(KEY, turn(1, with_tool=True))
|
|
120
|
+
clock.advance(60)
|
|
121
|
+
await memory.add_messages(KEY, turn(2))
|
|
122
|
+
|
|
123
|
+
history = await memory.get_history(KEY)
|
|
124
|
+
|
|
125
|
+
assert [h.message for h in history] == turn(1, with_tool=True) + turn(2)
|
|
126
|
+
assert [h.created_at for h in history] == [START] * 4 + [START + timedelta(seconds=60)] * 2
|
|
127
|
+
assert await memory.get_history(KEY.model_copy(update={"conversation_id": "nope"})) == []
|
|
128
|
+
|
|
129
|
+
async def test_list_is_newest_first_with_title_and_counts(self, memory, clock):
|
|
130
|
+
older = MemoryKey(tenant_id="tenant-1", user_id="user-1", conversation_id="conv-old")
|
|
131
|
+
await memory.add_messages(older, [HumanMessage(" Una pregunta muy larga " + "x" * 80, id="h0"), AIMessage("a", id="a0")])
|
|
132
|
+
clock.advance(60)
|
|
133
|
+
await memory.add_messages(KEY, turn(1, with_tool=True))
|
|
134
|
+
clock.advance(60)
|
|
135
|
+
await memory.add_messages(older, turn(9)) # activity: `older` is now the most recent
|
|
136
|
+
|
|
137
|
+
conversations = await memory.list_conversations("tenant-1", "user-1")
|
|
138
|
+
|
|
139
|
+
assert [c.conversation_id for c in conversations] == ["conv-old", "conv-1"]
|
|
140
|
+
old, new = conversations
|
|
141
|
+
assert old.title == "Una pregunta muy larga " + "x" * 36 + "…" and len(old.title) == 60
|
|
142
|
+
assert (old.created_at, old.updated_at, old.message_count) == (START, START + timedelta(seconds=120), 4)
|
|
143
|
+
assert (new.title, new.message_count) == ("q1", 4)
|
|
144
|
+
|
|
145
|
+
async def test_list_is_paginated_and_isolated_by_tenant_and_user(self, memory, clock):
|
|
146
|
+
for n in range(3):
|
|
147
|
+
await memory.add_messages(KEY.model_copy(update={"conversation_id": f"c{n}"}), turn(n))
|
|
148
|
+
clock.advance(1)
|
|
149
|
+
await memory.add_messages(MemoryKey(tenant_id="tenant-2", user_id="user-1", conversation_id="c9"), turn(9))
|
|
150
|
+
|
|
151
|
+
assert [c.conversation_id for c in await memory.list_conversations("tenant-1", "user-1", limit=2)] == ["c2", "c1"]
|
|
152
|
+
assert [c.conversation_id for c in await memory.list_conversations("tenant-1", "user-1", limit=2, offset=2)] == ["c0"]
|
|
153
|
+
assert await memory.list_conversations("tenant-1", "user-2") == []
|
|
154
|
+
|
|
155
|
+
async def test_clear_removes_it_from_the_list(self, memory):
|
|
156
|
+
await memory.add_messages(KEY, turn(1))
|
|
157
|
+
await memory.clear(KEY)
|
|
158
|
+
assert await memory.list_conversations("tenant-1", "user-1") == []
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from pydantic import ValidationError
|
|
3
|
+
from sqlalchemy import create_engine
|
|
4
|
+
from sqlalchemy.orm import sessionmaker
|
|
5
|
+
from sqlalchemy.pool import StaticPool
|
|
6
|
+
|
|
7
|
+
from agentic.memory import InMemoryMemory, MemoryBackend, MemoryFactory, MemoryKey, MemorySettings
|
|
8
|
+
from agentic.memory.sql import SqlMemory, metadata
|
|
9
|
+
|
|
10
|
+
from .memory_conformance import MemoryConformance, clock # noqa: F401 (fixture)
|
|
11
|
+
|
|
12
|
+
WINDOW = 3
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def sqlite_session_factory():
|
|
16
|
+
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
|
|
17
|
+
metadata.create_all(engine)
|
|
18
|
+
return sessionmaker(engine)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TestInMemoryMemory(MemoryConformance):
|
|
22
|
+
@pytest.fixture
|
|
23
|
+
def memory(self, clock):
|
|
24
|
+
return InMemoryMemory(window_turns=WINDOW, clock=clock)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class TestSqlMemory(MemoryConformance):
|
|
28
|
+
@pytest.fixture
|
|
29
|
+
def memory(self, clock):
|
|
30
|
+
return SqlMemory(sqlite_session_factory(), window_turns=WINDOW, clock=clock)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# --- Settings + factory: the backend is chosen in .env, not in code ---------------------------
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_backend_and_window_come_from_env(monkeypatch):
|
|
37
|
+
monkeypatch.setenv("MEMORY_BACKEND", "in_memory")
|
|
38
|
+
monkeypatch.setenv("MEMORY_WINDOW_TURNS", "4")
|
|
39
|
+
|
|
40
|
+
memory = MemoryFactory.create(MemorySettings())
|
|
41
|
+
|
|
42
|
+
assert isinstance(memory, InMemoryMemory)
|
|
43
|
+
assert memory.window_turns == 4
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_switching_to_sql_is_only_a_setting():
|
|
47
|
+
settings = MemorySettings(memory_backend="sql")
|
|
48
|
+
memory = MemoryFactory.create(settings, session_factory=sqlite_session_factory())
|
|
49
|
+
assert isinstance(memory, SqlMemory)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_backend_is_required(monkeypatch):
|
|
53
|
+
monkeypatch.delenv("MEMORY_BACKEND", raising=False)
|
|
54
|
+
with pytest.raises(ValidationError):
|
|
55
|
+
MemorySettings()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def test_unknown_backend_is_rejected():
|
|
59
|
+
with pytest.raises(ValidationError):
|
|
60
|
+
MemorySettings(memory_backend="redis")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_sql_without_session_factory_fails_loudly():
|
|
64
|
+
with pytest.raises(ValueError, match="session_factory"):
|
|
65
|
+
MemoryFactory.create(MemorySettings(memory_backend=MemoryBackend.SQL))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_key_rejects_empty_ids_and_is_frozen():
|
|
69
|
+
with pytest.raises(ValidationError):
|
|
70
|
+
MemoryKey(tenant_id="", user_id="u", conversation_id="c")
|
|
71
|
+
key = MemoryKey(tenant_id="t", user_id="u", conversation_id="c")
|
|
72
|
+
with pytest.raises(ValidationError):
|
|
73
|
+
key.tenant_id = "other"
|
|
74
|
+
assert key.thread_id == "t:u:c"
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# langchain-agent
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Cuando necesites **un agente LLM**, con o sin tools, construido con `langchain.agents.create_agent` (LangChain v1). Sirve sola o como pieza de un nodo de grafo (receta `langgraph-graph`).
|
|
6
|
+
|
|
7
|
+
No la uses para cadenas de una sola llamada sin agente (`prompt | model`). Tampoco para pipelines deterministas: para eso, un grafo sin agente.
|
|
8
|
+
|
|
9
|
+
**Usa la receta `project-settings`, pero no la trae.** Necesita que el proyecto tenga un `Settings` con `get_settings()`, ya sea el de esa receta o el que tenga ya el backend, y le añade su bloque `LLMSettings` por herencia. Sin él, los tests funcionan igual. Solo falla `get_llm_settings()`, y lo hace con un mensaje que dice qué falta.
|
|
10
|
+
|
|
11
|
+
## Qué incluye
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
agentic/
|
|
15
|
+
__init__.py regla: agentic/ no importa nada de la app (salvo get_llm_settings, perezoso)
|
|
16
|
+
context.py AgentContext (tenant, user, idioma): lo leen tools y middleware, nunca el LLM
|
|
17
|
+
llm/
|
|
18
|
+
models.py enum LLMModel(provider, model_id, reasoning_effort) + LLMProviderName
|
|
19
|
+
settings.py bloque LLMSettings(BaseSettings) para heredar en el Settings del proyecto + get_llm_settings()
|
|
20
|
+
provider.py LLMProvider.create_from_model → OpenAI | Azure OpenAI | Anthropic | Groq
|
|
21
|
+
agents/
|
|
22
|
+
base_agent.py BaseAgent: plantilla sobre create_agent
|
|
23
|
+
agents.py AssistantAgent (tools, texto) y ClassifierAgent (sin tools, structured output)
|
|
24
|
+
models.py AgentType, AgentTurn, AgentError, modelos de response_format
|
|
25
|
+
tools/
|
|
26
|
+
base_tool.py AppTool(BaseTool): fallo seguro, context_of(), emit()
|
|
27
|
+
search_documents.py tool de ejemplo con un servicio inyectado
|
|
28
|
+
__init__.py ToolSet.default(...): registro de tools
|
|
29
|
+
prompts/
|
|
30
|
+
loader.py load_prompt(name, lang): YAML versionado, caché y fallback de idioma
|
|
31
|
+
assistant.es.yaml prompt de ejemplo (uno por idioma)
|
|
32
|
+
assistant.en.yaml
|
|
33
|
+
middleware/
|
|
34
|
+
language.py build_language_middleware(): @wrap_model_call + request.override
|
|
35
|
+
tests/
|
|
36
|
+
fakes.py ScriptedChatModel, tool_call(), FakeDocumentSearch
|
|
37
|
+
test_agents.py 19 tests, sin API keys
|
|
38
|
+
pytest.ini
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Decisiones
|
|
42
|
+
|
|
43
|
+
- **`create_agent` y no `create_react_agent`**: es la API de LangChain v1 y admite `middleware`, `response_format` y `context_schema`.
|
|
44
|
+
- **Clase base con plantilla.** Una subclase solo declara lo que la distingue: `agent_type`, `response_format`, `get_prompt()` y, si los necesita, `get_tools()` y `get_middleware()`. `initialize()` construye el agente una sola vez y `process()` ejecuta un turno.
|
|
45
|
+
- **Settings por bloques.** La receta no trae settings propios del proyecto. Trae el bloque `LLMSettings` (claves, timeouts y modelo de cada agente), y el `Settings` del proyecto lo hereda: `class Settings(LLMSettings, BaseAppSettings)`. La factory lo lee sola con `get_llm_settings()`, así que nadie pasa las claves a mano. `settings=` solo se usa en tests.
|
|
46
|
+
- **Una sola línea acopla la receta al proyecto:** `PROJECT_SETTINGS = "core.config"` en `llm/settings.py`. Se importa de forma perezosa, así que copiar la receta sola nunca rompe al importar.
|
|
47
|
+
- **El modelo se elige desde fuera**, por id en el `.env` (`ASSISTANT_MODEL=gpt-4.1-mini` → `LLMModel.from_id`). `llm=` es la costura de tests.
|
|
48
|
+
- **La salida estructurada es opcional.** Con `response_format = MiModelo` el resultado llega en `AgentTurn.structured`; con `None`, en `AgentTurn.answer` como texto. Si se declara `response_format` y no llega, salta `AgentError(kind="NoStructuredResponse")`.
|
|
49
|
+
- **El agente no guarda estado.** Recibe `history` y devuelve `new_messages`; persistirlos es cosa de quien llama.
|
|
50
|
+
- **Datos de seguridad fuera del LLM.** El tenant viaja en `AgentContext` (`context=`). Las tools lo leen con `ToolRuntime` y el argumento `runtime` no aparece en el esquema que ve el LLM. Si falta el contexto, la tool falla cerrada.
|
|
51
|
+
- **Tools.** Una por archivo, sobre `AppTool`, con `name` y `description` explícitos y `args_schema` en Pydantic. Cualquier excepción llega al LLM como `SAFE_FAILURE`, sin el detalle interno.
|
|
52
|
+
- **Prompts como datos.** Van en YAML con `version`, sin Jinja ni `ChatPromptTemplate`, y el system prompt se pasa como string a `create_agent`.
|
|
53
|
+
- **Factory de LLM.** Importa los proveedores de forma perezosa (instala solo los que uses) y lanza `ValueError` ante un proveedor desconocido.
|
|
54
|
+
|
|
55
|
+
## Cómo adaptarla
|
|
56
|
+
|
|
57
|
+
1. Copia `files/` a la raíz del backend; si ya tienes `tests/` y `pytest.ini`, fusiónalos. Si `agentic/` va dentro de un paquete (`app/agentic/`), los imports relativos siguen funcionando. En los tests, cambia `from agentic...` por la ruta real.
|
|
58
|
+
2. **Settings:** si el proyecto no tiene `Settings`, copia la receta `project-settings`. Después, en tu `Settings`:
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from agentic.llm.settings import LLMSettings
|
|
62
|
+
|
|
63
|
+
class Settings(LLMSettings, BaseAppSettings): ...
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Si tu módulo de settings no es `core.config`, cambia `PROJECT_SETTINGS` en `agentic/llm/settings.py`. Añade al `.env` las variables que aparecen en el docstring de ese archivo (`OPENAI_API_KEY`, `ASSISTANT_MODEL`, …).
|
|
67
|
+
3. Sustituye `{{app_name}}` en `prompts/*.yaml`.
|
|
68
|
+
4. Ajusta `AgentContext` a tu app y deja solo los proveedores y modelos que uses en `llm/models.py`.
|
|
69
|
+
5. **Nueva tool:** copia `tools/search_documents.py`, define `Args` con `runtime: ToolRuntime[AgentContext]` e implementa `execute()`. Regístrala en `ToolSet.default`.
|
|
70
|
+
6. **Nuevo agente:** crea una subclase de `BaseAgent` en `agents/agents.py` y, si devuelve datos, añade su modelo en `agents/models.py`. Crea su `prompts/<nombre>.<lang>.yaml` y su campo `<nombre>_model` en `Settings`.
|
|
71
|
+
7. Instancia los agentes. Las claves salen solas del `.env`:
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
settings = get_llm_settings()
|
|
75
|
+
agent = AssistantAgent(LLMModel.from_id(settings.assistant_model), language="es",
|
|
76
|
+
tools=ToolSet.default(document_search=my_service))
|
|
77
|
+
turn = await agent.process("pregunta", context=AgentContext(tenant_id=..., user_id=...), history=[...])
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
`my_service` es cualquier objeto con `search(tenant_id, query, limit)`: la receta `rag-retriever` trae uno real (`DocumentSearchService`) sobre Qdrant o pgvector.
|
|
81
|
+
|
|
82
|
+
**Dependencias** (probado con langchain 1.4.9, langgraph 1.2.20 y langchain-core 1.7.7):
|
|
83
|
+
|
|
84
|
+
```
|
|
85
|
+
langchain>=1.3
|
|
86
|
+
langgraph>=1.2
|
|
87
|
+
pydantic>=2.11
|
|
88
|
+
pydantic-settings>=2.6 # para el bloque LLMSettings
|
|
89
|
+
pyyaml
|
|
90
|
+
langchain-openai>=1.1 # OpenAI y Azure OpenAI
|
|
91
|
+
langchain-anthropic>=1.1 # opcional
|
|
92
|
+
langchain-groq>=1.1 # opcional
|
|
93
|
+
pytest, pytest-asyncio # tests
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Para comprobarla: `pytest` desde la carpeta copiada.
|
|
97
|
+
|
|
98
|
+
## Origen
|
|
99
|
+
|
|
100
|
+
- Probado en producción: `BaseAgent` + `create_agent`, enum `LLMModel` + factory, `initialize()` y `process()`, `llm=` como costura de tests, `context_schema` con `extra="forbid"`, middleware `@wrap_model_call` creado por factory, prompts YAML por idioma, `response_format` como atributo de clase, `get_tools()` y `get_middleware()`, tools sobre `BaseTool` con `ToolRuntime` y `ToolSet.default()`, bloque de settings heredado por el `Settings` del proyecto y `api_key_for(provider)`.
|
|
101
|
+
- Nuevo en esta receta: proveedor Azure OpenAI.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Agentic layer of the app.
|
|
2
|
+
|
|
3
|
+
Settings: this package brings a config BLOCK (`llm/settings.py`, `LLMSettings`) that the project
|
|
4
|
+
settings inherit. It reads them through `get_llm_settings()`, the only place that knows where the
|
|
5
|
+
project settings live (`PROJECT_SETTINGS`), imported lazily.
|
|
6
|
+
|
|
7
|
+
Rule: nothing else under `agentic/` imports the app (DB, FastAPI, services).
|
|
8
|
+
Services are injected from the outside (see `registry.py`), so this package can be tested
|
|
9
|
+
on its own with fake LLMs.
|
|
10
|
+
"""
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from .agents import AssistantAgent, ClassifierAgent
|
|
2
|
+
from .base_agent import BaseAgent
|
|
3
|
+
from .models import AgentError, AgentTurn, AgentType, Classification
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"AgentError",
|
|
7
|
+
"AgentTurn",
|
|
8
|
+
"AgentType",
|
|
9
|
+
"AssistantAgent",
|
|
10
|
+
"BaseAgent",
|
|
11
|
+
"Classification",
|
|
12
|
+
"ClassifierAgent",
|
|
13
|
+
]
|