@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,42 @@
|
|
|
1
|
+
"""Example tool. Copy this file to add a tool, then register it in `tools/__init__.py`."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Protocol
|
|
4
|
+
|
|
5
|
+
from langchain.tools import ToolRuntime
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
7
|
+
|
|
8
|
+
from ..context import AgentContext
|
|
9
|
+
from .base_tool import AppTool
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DocumentSearch(Protocol):
|
|
13
|
+
"""What the tool needs from the app. The real service is injected; tests pass a fake."""
|
|
14
|
+
|
|
15
|
+
async def search(self, tenant_id: str, query: str, limit: int) -> list[dict[str, Any]]: ...
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SearchDocumentsArgs(BaseModel):
|
|
19
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
20
|
+
|
|
21
|
+
query: str = Field(description="What to look for, rewritten as a short search query.")
|
|
22
|
+
limit: int = Field(default=5, ge=1, le=20, description="Maximum number of documents to return.")
|
|
23
|
+
runtime: ToolRuntime[AgentContext] # injected, hidden from the LLM
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SearchDocumentsTool(AppTool):
|
|
27
|
+
name: str = "search_documents"
|
|
28
|
+
description: str = (
|
|
29
|
+
"Search the user's documents. Use it whenever the answer depends on them. "
|
|
30
|
+
"Returns one line per document: '<title>: <snippet>', or 'No results.'"
|
|
31
|
+
)
|
|
32
|
+
args_schema: type[BaseModel] = SearchDocumentsArgs
|
|
33
|
+
|
|
34
|
+
service: Any = Field(exclude=True) # DocumentSearch
|
|
35
|
+
|
|
36
|
+
async def execute(self, runtime: ToolRuntime, *, query: str, limit: int = 5) -> str:
|
|
37
|
+
context = self.context_of(runtime) # tenant comes from the context, never from the LLM
|
|
38
|
+
self.emit(runtime, {"tool": self.name, "status": "searching", "query": query})
|
|
39
|
+
hits = await self.service.search(context.tenant_id, query, limit)
|
|
40
|
+
if not hits:
|
|
41
|
+
return "No results."
|
|
42
|
+
return "\n".join(f"{hit['title']}: {hit['snippet']}" for hit in hits)
|
|
File without changes
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Test doubles: a scripted chat model and a fake document service. No API keys needed."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
|
|
6
|
+
from langchain_core.messages import AIMessage
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ScriptedChatModel(FakeMessagesListChatModel):
|
|
10
|
+
"""Returns the given AIMessages in order. `bind_tools` is a no-op so it works inside create_agent."""
|
|
11
|
+
|
|
12
|
+
def bind_tools(self, tools: Any, **kwargs: Any) -> "ScriptedChatModel":
|
|
13
|
+
return self
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def tool_call(name: str, args: dict[str, Any], call_id: str = "call_1") -> AIMessage:
|
|
17
|
+
return AIMessage("", tool_calls=[{"name": name, "args": args, "id": call_id}])
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FakeDocumentSearch:
|
|
21
|
+
def __init__(self, hits: list[dict[str, Any]] | None = None, error: Exception | None = None) -> None:
|
|
22
|
+
self.hits = hits or []
|
|
23
|
+
self.error = error
|
|
24
|
+
self.calls: list[tuple[str, str, int]] = []
|
|
25
|
+
|
|
26
|
+
async def search(self, tenant_id: str, query: str, limit: int) -> list[dict[str, Any]]:
|
|
27
|
+
self.calls.append((tenant_id, query, limit))
|
|
28
|
+
if self.error:
|
|
29
|
+
raise self.error
|
|
30
|
+
return self.hits
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
|
3
|
+
|
|
4
|
+
from agentic.agents import AgentError, AssistantAgent, ClassifierAgent, Classification
|
|
5
|
+
from agentic.context import AgentContext
|
|
6
|
+
from agentic.llm import LLMModel, LLMProvider, LLMSettings
|
|
7
|
+
from agentic.llm import settings as llm_settings
|
|
8
|
+
from agentic.prompts import load_prompt
|
|
9
|
+
from agentic.tools import AppTool, ToolSet
|
|
10
|
+
|
|
11
|
+
from .fakes import FakeDocumentSearch, ScriptedChatModel, tool_call
|
|
12
|
+
|
|
13
|
+
CONTEXT = AgentContext(tenant_id="tenant-1", user_id="user-1", language="es")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def test_assistant_uses_tool_with_tenant_from_context():
|
|
17
|
+
service = FakeDocumentSearch(hits=[{"title": "Guía", "snippet": "texto"}])
|
|
18
|
+
llm = ScriptedChatModel(
|
|
19
|
+
responses=[tool_call("search_documents", {"query": "vacaciones"}), AIMessage("Según la Guía...")]
|
|
20
|
+
)
|
|
21
|
+
agent = AssistantAgent(llm=llm, tools=ToolSet.default(document_search=service))
|
|
22
|
+
|
|
23
|
+
turn = await agent.process("¿Cuántos días de vacaciones?", context=CONTEXT)
|
|
24
|
+
|
|
25
|
+
assert turn.answer == "Según la Guía..."
|
|
26
|
+
assert turn.structured is None
|
|
27
|
+
assert service.calls == [("tenant-1", "vacaciones", 5)]
|
|
28
|
+
tool_messages = [m for m in turn.new_messages if isinstance(m, ToolMessage)]
|
|
29
|
+
assert tool_messages[0].content == "Guía: texto"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
async def test_new_messages_exclude_history():
|
|
33
|
+
llm = ScriptedChatModel(responses=[AIMessage("hola de nuevo")])
|
|
34
|
+
agent = AssistantAgent(llm=llm, tools=[])
|
|
35
|
+
history = [HumanMessage("hola"), AIMessage("hola")]
|
|
36
|
+
|
|
37
|
+
turn = await agent.process("¿sigues ahí?", context=CONTEXT, history=history)
|
|
38
|
+
|
|
39
|
+
assert [type(m) for m in turn.new_messages] == [HumanMessage, AIMessage]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_llm_never_sees_runtime_argument():
|
|
43
|
+
tool = ToolSet.default(document_search=FakeDocumentSearch())[0]
|
|
44
|
+
assert set(tool.tool_call_schema.model_json_schema()["properties"]) == {"query", "limit"}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def test_tool_failure_returns_safe_message():
|
|
48
|
+
service = FakeDocumentSearch(error=RuntimeError("password=secret"))
|
|
49
|
+
llm = ScriptedChatModel(responses=[tool_call("search_documents", {"query": "x"}), AIMessage("fin")])
|
|
50
|
+
agent = AssistantAgent(llm=llm, tools=ToolSet.default(document_search=service))
|
|
51
|
+
|
|
52
|
+
turn = await agent.process("x", context=CONTEXT)
|
|
53
|
+
|
|
54
|
+
tool_message = next(m for m in turn.new_messages if isinstance(m, ToolMessage))
|
|
55
|
+
assert tool_message.content == AppTool.SAFE_FAILURE
|
|
56
|
+
assert "secret" not in tool_message.content
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
async def test_classifier_returns_structured_answer():
|
|
60
|
+
args = {"category": "billing", "needs_search": False, "confidence": 0.9}
|
|
61
|
+
llm = ScriptedChatModel(responses=[tool_call("Classification", args)])
|
|
62
|
+
agent = ClassifierAgent(llm=llm)
|
|
63
|
+
|
|
64
|
+
turn = await agent.process("¿Por qué me cobrasteis dos veces?", context=CONTEXT)
|
|
65
|
+
|
|
66
|
+
assert turn.structured == Classification(**args)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_missing_structured_answer_raises():
|
|
70
|
+
# create_agent keeps asking the model until it calls the structured-output tool, so a run
|
|
71
|
+
# that ends without it means a limit cut it short: the agent must not return a half answer.
|
|
72
|
+
agent = ClassifierAgent(llm=ScriptedChatModel(responses=[AIMessage("x")]))
|
|
73
|
+
|
|
74
|
+
with pytest.raises(AgentError) as error:
|
|
75
|
+
agent._to_turn({"messages": [HumanMessage("x"), AIMessage("no sé")]}, history_len=0)
|
|
76
|
+
assert error.value.kind == "NoStructuredResponse"
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
async def test_initialize_is_idempotent():
|
|
80
|
+
agent = AssistantAgent(llm=ScriptedChatModel(responses=[AIMessage("a")]), tools=[])
|
|
81
|
+
await agent.initialize()
|
|
82
|
+
first = agent.agent
|
|
83
|
+
await agent.initialize()
|
|
84
|
+
assert agent.agent is first
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def test_agent_requires_model_and_settings_or_llm():
|
|
88
|
+
with pytest.raises(ValueError):
|
|
89
|
+
AssistantAgent(tools=[])
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_prompt_falls_back_to_default_language():
|
|
93
|
+
assert load_prompt("assistant", "fr").language == "es"
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def test_prompt_rejects_path_traversal():
|
|
97
|
+
with pytest.raises(ValueError):
|
|
98
|
+
load_prompt("../secrets")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@pytest.mark.parametrize(
|
|
102
|
+
"model, settings",
|
|
103
|
+
[
|
|
104
|
+
(LLMModel.GPT_4_1_MINI, LLMSettings(_env_file=None, openai_api_key="k")),
|
|
105
|
+
(LLMModel.CLAUDE_HAIKU_5_5, LLMSettings(_env_file=None, anthropic_api_key="k")),
|
|
106
|
+
(LLMModel.LLAMA_3_3_70B, LLMSettings(_env_file=None, groq_api_key="k")),
|
|
107
|
+
(
|
|
108
|
+
LLMModel.AZURE_GPT_4_1,
|
|
109
|
+
LLMSettings(
|
|
110
|
+
_env_file=None,
|
|
111
|
+
azure_openai_api_key="k",
|
|
112
|
+
azure_openai_endpoint="https://example.openai.azure.com",
|
|
113
|
+
azure_openai_api_version="2024-10-21",
|
|
114
|
+
),
|
|
115
|
+
),
|
|
116
|
+
],
|
|
117
|
+
)
|
|
118
|
+
def test_factory_builds_every_provider(model, settings):
|
|
119
|
+
llm = LLMProvider.create_from_model(model, settings, temperature=0)
|
|
120
|
+
assert llm is not None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def test_factory_fails_without_key():
|
|
124
|
+
with pytest.raises(ValueError):
|
|
125
|
+
LLMProvider.create_from_model(LLMModel.GPT_4_1, LLMSettings(_env_file=None, openai_api_key=None))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_model_from_id():
|
|
129
|
+
assert LLMModel.from_id("gpt-4.1-nano") is LLMModel.GPT_4_1_NANO
|
|
130
|
+
with pytest.raises(ValueError):
|
|
131
|
+
LLMModel.from_id("nope")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_llm_settings_block_reads_env(monkeypatch):
|
|
135
|
+
monkeypatch.setenv("OPENAI_API_KEY", "from-env")
|
|
136
|
+
monkeypatch.setenv("ASSISTANT_MODEL", "gpt-4.1-nano")
|
|
137
|
+
settings = LLMSettings()
|
|
138
|
+
assert settings.openai_api_key.get_secret_value() == "from-env"
|
|
139
|
+
assert LLMModel.from_id(settings.assistant_model) is LLMModel.GPT_4_1_NANO
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def test_factory_uses_project_settings_when_none_passed(monkeypatch):
|
|
143
|
+
monkeypatch.setattr(llm_settings, "get_llm_settings", lambda: LLMSettings(_env_file=None, openai_api_key="k"))
|
|
144
|
+
monkeypatch.setattr("agentic.llm.provider.get_llm_settings", llm_settings.get_llm_settings)
|
|
145
|
+
assert LLMProvider.create_from_model(LLMModel.GPT_4_1_MINI) is not None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def test_missing_project_settings_gives_clear_error(monkeypatch):
|
|
149
|
+
monkeypatch.setattr(llm_settings, "PROJECT_SETTINGS", "no_such_module.config")
|
|
150
|
+
with pytest.raises(RuntimeError, match="project-settings"):
|
|
151
|
+
llm_settings.get_llm_settings()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# langgraph-graph
|
|
2
|
+
|
|
3
|
+
## Cuándo usarla
|
|
4
|
+
|
|
5
|
+
Cuando el flujo tenga **pasos fijos** alrededor de uno o varios agentes: clasificar o enrutar, rechazar, llamar al agente, postprocesar. Es el caso habitual de un chat con router y un agente con tools, expuesto como JSON y como SSE.
|
|
6
|
+
|
|
7
|
+
**Requiere las recetas `langchain-agent` y `agent-memory`**, copiadas en el mismo `agentic/`.
|
|
8
|
+
|
|
9
|
+
## Qué incluye
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
agentic/
|
|
13
|
+
graph/
|
|
14
|
+
state.py GraphState (Pydantic): contrato de datos entre nodos
|
|
15
|
+
nodes.py RouterNode, AgentNode, RejectNode: @staticmethod async invoke(state, runtime)
|
|
16
|
+
edges.py route_after_router(state) -> nombre del nodo
|
|
17
|
+
builder.py build_graph() con la topología y compile_graph(), compilado una vez sin checkpointer
|
|
18
|
+
graph.py ainvoke_graph() (JSON) · astream_graph() (SSE) · run_config() (observabilidad)
|
|
19
|
+
event_processor.py astream_events v2 → SSEEvent; guarda el estado final
|
|
20
|
+
events.py SSEEvent y EventType (token, tool_start, tool_end, routing, error, done)
|
|
21
|
+
conversation.py answer_question() y stream_answer(): un turno completo (memoria → grafo → memoria) → TurnResult
|
|
22
|
+
registry.py frontera de cableado: construye y cachea los agentes
|
|
23
|
+
conversation.py answer_question() y stream_answer(): memoria → grafo → persistencia
|
|
24
|
+
tests/
|
|
25
|
+
test_graph.py 7 tests: enrutado, fail-open, memoria, streaming, errores
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Topología de ejemplo:
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
START → router_node ─┬→ agent_node ──→ END
|
|
32
|
+
└→ reject_node ─→ END
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Decisiones
|
|
36
|
+
|
|
37
|
+
- **El grafo coordina y el agente vive dentro de un nodo.** `AgentNode` llama a `agent.process(...)`. Nunca se añade el agente como subgrafo, no hay supervisor y el bucle de tools ocurre dentro del agente.
|
|
38
|
+
- **State en Pydantic** con `Field(description=...)`. Los nodos devuelven un dict solo con las claves que escriben. Solo hace falta un reducer (`Annotated[list, operator.add]`) en claves que escriben varias ramas paralelas.
|
|
39
|
+
- **Nodos como clases** con `@staticmethod async invoke(state, runtime)`. Sus nombres son constantes y la topología solo existe en `build_graph()`.
|
|
40
|
+
- **Dependencias desde `registry`.** Los nodos no construyen agentes. Las claves y los modelos los lee el registry de `get_llm_settings()` (los settings del proyecto, receta `project-settings`), y la app solo inyecta servicios con `registry.configure(...)` en el `lifespan` y los tests a `registry.override(...)`. Los agentes se cachean por idioma, con `asyncio.Lock` y doble comprobación.
|
|
41
|
+
- **Contexto tipado.** `context_schema=AgentContext`, pasado como `context=` y leído con `runtime.context`. El tenant no va en el state.
|
|
42
|
+
- **Sin checkpointer, con memoria propia** (receta `agent-memory`). `conversation.py` lee la ventana, ejecuta el grafo y guarda los mensajes nuevos antes de responder.
|
|
43
|
+
- **Un grafo, dos modos.** `ainvoke` para JSON y `astream_events(v2)` con `EventProcessor` para SSE. Los tokens solo salen del nodo del agente, así que la salida estructurada del router no llega al usuario. Los eventos propios se emiten con `adispatch_custom_event`.
|
|
44
|
+
- **Errores.** El router falla abierto (si cae, la pregunta pasa al agente). En streaming, un error se convierte en el evento `error` con un `error_id` y sin el detalle, que solo va a los logs.
|
|
45
|
+
- **Observabilidad** por callbacks en el `config` del run (Langfuse, Opik o LangSmith), nunca dentro de los nodos. `answer_question` y `stream_answer` aceptan `config=`; sin él usan `run_config(thread_id)`. La receta `observability` construye ese `config` por turno.
|
|
46
|
+
|
|
47
|
+
## Cómo adaptarla
|
|
48
|
+
|
|
49
|
+
1. Copia primero la receta `langchain-agent` y luego `files/` de esta en el mismo sitio.
|
|
50
|
+
2. **Tu topología:** añade campos a `GraphState`, nodos a `nodes.py` (con su constante), condiciones a `edges.py` y conéctalo todo en `build_graph()`.
|
|
51
|
+
3. Cambia `ALLOWED_CATEGORIES` y `REJECT_TEXT` en `nodes.py`, o elimina el router si no lo necesitas.
|
|
52
|
+
4. **Modelos de cada agente:** `ASSISTANT_MODEL` y `CLASSIFIER_MODEL` en el `.env`, del bloque `LLMSettings` (receta `langchain-agent`).
|
|
53
|
+
5. **Memoria:** sigue el RECIPE.md de `agent-memory`. El backend se elige con `MEMORY_BACKEND` en el `.env`.
|
|
54
|
+
6. **FastAPI:** la receta `agent-chat-api` trae los endpoints (`POST /agent/chat` y `POST /agent/stream`), la auth, los guards y `create_app`. Si no la usas, el mínimo es: en el `lifespan`, `registry.configure(document_search=...)`, `compile_graph()` y `app.state.memory = MemoryFactory.create(...)`; en el endpoint, `MemoryKey` y `AgentContext` con `tenant_id` y `user_id` **del token, nunca del body**, y `answer_question(...)` o `EventSourceResponse(e.to_sse() async for e in stream_answer(...))`.
|
|
55
|
+
|
|
56
|
+
**Dependencias** (además de las de `langchain-agent` y `agent-memory`): `sse-starlette` para el streaming.
|
|
57
|
+
|
|
58
|
+
Para comprobarla: `pytest` con las dos recetas copiadas.
|
|
59
|
+
|
|
60
|
+
## Origen
|
|
61
|
+
|
|
62
|
+
- Probado en producción: router → agente | rechazo, State Pydantic, `context_schema`, nodos como clases con `@staticmethod invoke`, `build_graph()` compartido entre invoke y stream, `EventProcessor`, `registry` con caché, errores saneados con `request_id`, fan-out y join para ramas paralelas y reducers solo donde hay concurrencia.
|
|
63
|
+
- Nuevo en esta receta: nada; combina patrones ya existentes.
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""One conversation turn: read memory -> run graph -> persist -> answer.
|
|
2
|
+
|
|
3
|
+
This is what the API calls. Memory is persisted BEFORE answering (or before `done` when
|
|
4
|
+
streaming), so a reload right after the answer already sees it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import AsyncIterator
|
|
9
|
+
|
|
10
|
+
from langchain_core.runnables import RunnableConfig
|
|
11
|
+
from pydantic import BaseModel, ConfigDict
|
|
12
|
+
|
|
13
|
+
from .context import AgentContext
|
|
14
|
+
from .graph import EventProcessor, EventType, SSEEvent, ainvoke_graph, astream_graph, run_config
|
|
15
|
+
from .memory import Memory, MemoryKey
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TurnResult(BaseModel):
|
|
21
|
+
"""What a turn gives back to the API. `message_id` is the persisted answer (None if nothing
|
|
22
|
+
was stored): the id the client can vote on."""
|
|
23
|
+
|
|
24
|
+
model_config = ConfigDict(frozen=True)
|
|
25
|
+
|
|
26
|
+
answer: str
|
|
27
|
+
conversation_id: str
|
|
28
|
+
message_id: str | None = None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def answer_question(
|
|
32
|
+
question: str,
|
|
33
|
+
*,
|
|
34
|
+
key: MemoryKey,
|
|
35
|
+
context: AgentContext,
|
|
36
|
+
memory: Memory,
|
|
37
|
+
config: RunnableConfig | None = None,
|
|
38
|
+
) -> TurnResult:
|
|
39
|
+
"""`config=None` -> `run_config(key.thread_id)`. Pass one to add observability callbacks."""
|
|
40
|
+
history = await memory.get_messages(key)
|
|
41
|
+
state = await ainvoke_graph(
|
|
42
|
+
question, context=context, history=history, config=config or run_config(key.thread_id)
|
|
43
|
+
)
|
|
44
|
+
message_id = await memory.add_messages(key, state.new_messages)
|
|
45
|
+
return TurnResult(answer=state.answer or "", conversation_id=key.conversation_id, message_id=message_id)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def stream_answer(
|
|
49
|
+
question: str,
|
|
50
|
+
*,
|
|
51
|
+
key: MemoryKey,
|
|
52
|
+
context: AgentContext,
|
|
53
|
+
memory: Memory,
|
|
54
|
+
config: RunnableConfig | None = None,
|
|
55
|
+
) -> AsyncIterator[SSEEvent]:
|
|
56
|
+
"""Events of the graph, then `done` with the same fields as `TurnResult`."""
|
|
57
|
+
history = await memory.get_messages(key)
|
|
58
|
+
processor = EventProcessor()
|
|
59
|
+
async for event in astream_graph(
|
|
60
|
+
question, context=context, history=history, config=config or run_config(key.thread_id), processor=processor
|
|
61
|
+
):
|
|
62
|
+
yield event
|
|
63
|
+
if event.type is EventType.ERROR:
|
|
64
|
+
return
|
|
65
|
+
|
|
66
|
+
final = processor.final_state
|
|
67
|
+
message_id = await memory.add_messages(key, final.new_messages) if final is not None else None
|
|
68
|
+
result = TurnResult(
|
|
69
|
+
answer=final.answer or "" if final is not None else "",
|
|
70
|
+
conversation_id=key.conversation_id,
|
|
71
|
+
message_id=message_id,
|
|
72
|
+
)
|
|
73
|
+
yield SSEEvent(type=EventType.DONE, data=result.model_dump())
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .builder import build_graph, compile_graph
|
|
2
|
+
from .event_processor import EventProcessor
|
|
3
|
+
from .events import EventType, SSEEvent
|
|
4
|
+
from .graph import ainvoke_graph, astream_graph, run_config
|
|
5
|
+
from .state import GraphState
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"EventProcessor",
|
|
9
|
+
"EventType",
|
|
10
|
+
"GraphState",
|
|
11
|
+
"SSEEvent",
|
|
12
|
+
"ainvoke_graph",
|
|
13
|
+
"astream_graph",
|
|
14
|
+
"build_graph",
|
|
15
|
+
"compile_graph",
|
|
16
|
+
"run_config",
|
|
17
|
+
]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""The ONLY place with the topology. Shared by invoke and stream modes.
|
|
2
|
+
|
|
3
|
+
START -> router_node -> (agent_node | reject_node) -> END
|
|
4
|
+
|
|
5
|
+
Compiled once per process, without a checkpointer (memory lives in `agentic/memory`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from langgraph.graph import END, START, StateGraph
|
|
9
|
+
from langgraph.graph.state import CompiledStateGraph
|
|
10
|
+
|
|
11
|
+
from ..context import AgentContext
|
|
12
|
+
from .edges import route_after_router
|
|
13
|
+
from .nodes import AGENT_NODE, REJECT_NODE, ROUTER_NODE, AgentNode, RejectNode, RouterNode
|
|
14
|
+
from .state import GraphState
|
|
15
|
+
|
|
16
|
+
_compiled: CompiledStateGraph | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def build_graph() -> StateGraph:
|
|
20
|
+
builder = StateGraph(GraphState, context_schema=AgentContext)
|
|
21
|
+
|
|
22
|
+
builder.add_node(ROUTER_NODE, RouterNode.invoke)
|
|
23
|
+
builder.add_node(AGENT_NODE, AgentNode.invoke)
|
|
24
|
+
builder.add_node(REJECT_NODE, RejectNode.invoke)
|
|
25
|
+
|
|
26
|
+
builder.add_edge(START, ROUTER_NODE)
|
|
27
|
+
builder.add_conditional_edges(ROUTER_NODE, route_after_router, [AGENT_NODE, REJECT_NODE])
|
|
28
|
+
builder.add_edge(AGENT_NODE, END)
|
|
29
|
+
builder.add_edge(REJECT_NODE, END)
|
|
30
|
+
return builder
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def compile_graph() -> CompiledStateGraph:
|
|
34
|
+
global _compiled
|
|
35
|
+
if _compiled is None:
|
|
36
|
+
_compiled = build_graph().compile()
|
|
37
|
+
return _compiled
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Conditional edges: pure functions of the state that return the next node's name."""
|
|
2
|
+
|
|
3
|
+
from .nodes import AGENT_NODE, REJECT_NODE
|
|
4
|
+
from .state import GraphState
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def route_after_router(state: GraphState) -> str:
|
|
8
|
+
return REJECT_NODE if state.blocked else AGENT_NODE
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Translate raw `astream_events(version="v2")` events into `SSEEvent`s. Pure: no I/O.
|
|
2
|
+
|
|
3
|
+
- Tokens: only from the chat model of the answering agent (`AGENT_NODE`), so the router's
|
|
4
|
+
structured output never leaks to the user.
|
|
5
|
+
- Tools: start/end with the tool name only (no args/outputs: they may hold private data).
|
|
6
|
+
- Custom events (`adispatch_custom_event`) pass through by name.
|
|
7
|
+
- The final state is the output of the root run (`on_chain_end` without parents).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .events import EventType, SSEEvent
|
|
13
|
+
from .nodes import AGENT_NODE
|
|
14
|
+
from .state import GraphState
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class EventProcessor:
|
|
18
|
+
def __init__(self) -> None:
|
|
19
|
+
self.final_state: GraphState | None = None
|
|
20
|
+
|
|
21
|
+
def process(self, raw: dict[str, Any]) -> list[SSEEvent]:
|
|
22
|
+
kind = raw.get("event")
|
|
23
|
+
metadata = raw.get("metadata") or {}
|
|
24
|
+
in_agent = str(metadata.get("checkpoint_ns", "")).startswith(AGENT_NODE) or (
|
|
25
|
+
metadata.get("langgraph_node") == AGENT_NODE
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
if kind == "on_chat_model_stream" and in_agent:
|
|
29
|
+
text = getattr(raw["data"].get("chunk"), "text", "")
|
|
30
|
+
text = str(text) if text else ""
|
|
31
|
+
return [SSEEvent(type=EventType.TOKEN, data={"text": text})] if text else []
|
|
32
|
+
|
|
33
|
+
if kind == "on_tool_start":
|
|
34
|
+
return [SSEEvent(type=EventType.TOOL_START, data={"tool": raw.get("name")})]
|
|
35
|
+
|
|
36
|
+
if kind == "on_tool_end":
|
|
37
|
+
return [SSEEvent(type=EventType.TOOL_END, data={"tool": raw.get("name")})]
|
|
38
|
+
|
|
39
|
+
if kind == "on_custom_event":
|
|
40
|
+
if raw.get("name") == EventType.ROUTING.value:
|
|
41
|
+
return [SSEEvent(type=EventType.ROUTING, data=dict(raw.get("data") or {}))]
|
|
42
|
+
return []
|
|
43
|
+
|
|
44
|
+
if kind == "on_chain_end" and not raw.get("parent_ids"):
|
|
45
|
+
output = raw["data"].get("output")
|
|
46
|
+
if output is not None:
|
|
47
|
+
self.final_state = output if isinstance(output, GraphState) else GraphState.model_validate(output)
|
|
48
|
+
return []
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Events sent to the client over SSE. The frontend contract: change it with care."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class EventType(str, Enum):
|
|
11
|
+
TOKEN = "token"
|
|
12
|
+
TOOL_START = "tool_start"
|
|
13
|
+
TOOL_END = "tool_end"
|
|
14
|
+
ROUTING = "routing"
|
|
15
|
+
ERROR = "error"
|
|
16
|
+
DONE = "done"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SSEEvent(BaseModel):
|
|
20
|
+
model_config = ConfigDict(frozen=True)
|
|
21
|
+
|
|
22
|
+
type: EventType
|
|
23
|
+
data: dict[str, Any] = Field(default_factory=dict)
|
|
24
|
+
|
|
25
|
+
def to_sse(self) -> dict[str, str]:
|
|
26
|
+
"""Shape expected by `sse_starlette.EventSourceResponse`."""
|
|
27
|
+
return {"event": self.type.value, "data": json.dumps(self.data, ensure_ascii=False)}
|
|
28
|
+
|
|
29
|
+
def as_dict(self) -> dict[str, Any]:
|
|
30
|
+
return {"type": self.type.value, **self.data}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Entry points of the graph: one turn as JSON (`ainvoke_graph`) or as SSE events (`astream_graph`)."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import uuid
|
|
5
|
+
from collections.abc import AsyncIterator, Sequence
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from langchain_core.messages import BaseMessage
|
|
9
|
+
from langchain_core.runnables import RunnableConfig
|
|
10
|
+
|
|
11
|
+
from ..context import AgentContext
|
|
12
|
+
from .builder import compile_graph
|
|
13
|
+
from .event_processor import EventProcessor
|
|
14
|
+
from .events import EventType, SSEEvent
|
|
15
|
+
from .state import GraphState
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def run_config(thread_id: str, callbacks: Sequence[Any] = ()) -> RunnableConfig:
|
|
21
|
+
"""Observability goes here (Langfuse/Opik/LangSmith callbacks + metadata), never in the core."""
|
|
22
|
+
return {"callbacks": list(callbacks), "metadata": {"thread_id": thread_id}}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
async def ainvoke_graph(
|
|
26
|
+
question: str,
|
|
27
|
+
*,
|
|
28
|
+
context: AgentContext,
|
|
29
|
+
history: Sequence[BaseMessage] = (),
|
|
30
|
+
config: RunnableConfig | None = None,
|
|
31
|
+
) -> GraphState:
|
|
32
|
+
graph = compile_graph()
|
|
33
|
+
result = await graph.ainvoke(
|
|
34
|
+
GraphState(question=question, history=list(history)), context=context, config=config
|
|
35
|
+
)
|
|
36
|
+
return GraphState.model_validate(result)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def astream_graph(
|
|
40
|
+
question: str,
|
|
41
|
+
*,
|
|
42
|
+
context: AgentContext,
|
|
43
|
+
history: Sequence[BaseMessage] = (),
|
|
44
|
+
config: RunnableConfig | None = None,
|
|
45
|
+
processor: EventProcessor | None = None,
|
|
46
|
+
) -> AsyncIterator[SSEEvent]:
|
|
47
|
+
"""Yields events; the final state is left in `processor.final_state`. Errors -> one `error` event
|
|
48
|
+
with a correlation id (details only in the logs)."""
|
|
49
|
+
graph = compile_graph()
|
|
50
|
+
processor = processor or EventProcessor()
|
|
51
|
+
try:
|
|
52
|
+
async for raw in graph.astream_events(
|
|
53
|
+
GraphState(question=question, history=list(history)), context=context, config=config, version="v2"
|
|
54
|
+
):
|
|
55
|
+
for event in processor.process(raw):
|
|
56
|
+
yield event
|
|
57
|
+
except Exception:
|
|
58
|
+
error_id = uuid.uuid4().hex[:12]
|
|
59
|
+
logger.exception("Graph stream failed (error_id=%s)", error_id)
|
|
60
|
+
yield SSEEvent(type=EventType.ERROR, data={"error_id": error_id})
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Graph nodes: one class per node with `@staticmethod async invoke(state, runtime) -> dict`.
|
|
2
|
+
|
|
3
|
+
- The node name is a module constant; the topology uses only the constants.
|
|
4
|
+
- `runtime.context` is the `AgentContext` (tenant, user, language).
|
|
5
|
+
- Agents come from `registry`, never built inside a node.
|
|
6
|
+
- A node returns only the keys it writes.
|
|
7
|
+
- Auxiliary nodes fail OPEN (the router falls through to the agent); security never does.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from langchain_core.callbacks import adispatch_custom_event
|
|
14
|
+
from langchain_core.messages import AIMessage, HumanMessage
|
|
15
|
+
from langgraph.runtime import Runtime
|
|
16
|
+
|
|
17
|
+
from ..context import AgentContext
|
|
18
|
+
from ..registry import registry
|
|
19
|
+
from .state import GraphState
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
ROUTER_NODE = "router_node"
|
|
24
|
+
AGENT_NODE = "agent_node"
|
|
25
|
+
REJECT_NODE = "reject_node"
|
|
26
|
+
|
|
27
|
+
ALLOWED_CATEGORIES = {"billing", "technical"}
|
|
28
|
+
|
|
29
|
+
REJECT_TEXT = {
|
|
30
|
+
"es": "Solo puedo ayudarte con temas de facturación o soporte técnico.",
|
|
31
|
+
"en": "I can only help with billing or technical support.",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RouterNode:
|
|
36
|
+
@staticmethod
|
|
37
|
+
async def invoke(state: GraphState, runtime: Runtime[AgentContext]) -> dict[str, Any]:
|
|
38
|
+
try:
|
|
39
|
+
classifier = await registry.get_classifier()
|
|
40
|
+
turn = await classifier.process(state.question, context=runtime.context, history=state.history)
|
|
41
|
+
classification = turn.structured
|
|
42
|
+
except Exception:
|
|
43
|
+
logger.exception("Router failed; letting the question through")
|
|
44
|
+
return {"classification": None, "blocked": False}
|
|
45
|
+
|
|
46
|
+
blocked = classification.category not in ALLOWED_CATEGORIES
|
|
47
|
+
await adispatch_custom_event("routing", {"category": classification.category, "blocked": blocked})
|
|
48
|
+
return {"classification": classification, "blocked": blocked}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class AgentNode:
|
|
52
|
+
@staticmethod
|
|
53
|
+
async def invoke(state: GraphState, runtime: Runtime[AgentContext]) -> dict[str, Any]:
|
|
54
|
+
agent = await registry.get_assistant(runtime.context.language)
|
|
55
|
+
turn = await agent.process(state.question, context=runtime.context, history=state.history)
|
|
56
|
+
return {"answer": turn.answer, "new_messages": turn.new_messages}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class RejectNode:
|
|
60
|
+
@staticmethod
|
|
61
|
+
async def invoke(state: GraphState, runtime: Runtime[AgentContext]) -> dict[str, Any]:
|
|
62
|
+
text = REJECT_TEXT.get(runtime.context.language, REJECT_TEXT["es"])
|
|
63
|
+
return {"answer": text, "new_messages": [HumanMessage(state.question), AIMessage(text)]}
|