@jhm1909/ag-kit 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/.agent/ARCHITECTURE.md +189 -0
- package/.agent/known-registries.json +181 -0
- package/.agent/mcp_config.json +19 -0
- package/.agent/rules/clean-code.md +107 -0
- package/.agent/rules/documents.md +177 -0
- package/.agent/rules/git-workflow.md +68 -0
- package/.agent/rules/nano-banana.md +46 -0
- package/.agent/rules/research.md +35 -0
- package/.agent/rules/skill-loading.md +100 -0
- package/.agent/rules/skill-suggestion.md +47 -0
- package/.agent/rules/testing.md +52 -0
- package/.agent/rules/workflow-advisor.md +108 -0
- package/.agent/rules/workflow-skill-convention.md +127 -0
- package/.agent/skills/ai-engineer/SKILL.md +824 -0
- package/.agent/skills/ai-engineer/references/agentic-patterns.md +329 -0
- package/.agent/skills/ai-engineer/references/evaluation.md +493 -0
- package/.agent/skills/ai-engineer/references/llm.md +490 -0
- package/.agent/skills/ai-engineer/references/rag-advanced.md +444 -0
- package/.agent/skills/ai-engineer/references/serving-optimization.md +531 -0
- package/.agent/skills/ai-engineer/vector-db/README.md +137 -0
- package/.agent/skills/app-builder/SKILL.md +75 -0
- package/.agent/skills/app-builder/agent-coordination.md +71 -0
- package/.agent/skills/app-builder/feature-building.md +53 -0
- package/.agent/skills/app-builder/project-detection.md +34 -0
- package/.agent/skills/app-builder/scaffolding.md +118 -0
- package/.agent/skills/app-builder/tech-stack.md +41 -0
- package/.agent/skills/app-builder/templates/SKILL.md +39 -0
- package/.agent/skills/app-builder/templates/astro-static/TEMPLATE.md +76 -0
- package/.agent/skills/app-builder/templates/chrome-extension/TEMPLATE.md +92 -0
- package/.agent/skills/app-builder/templates/cli-tool/TEMPLATE.md +88 -0
- package/.agent/skills/app-builder/templates/electron-desktop/TEMPLATE.md +88 -0
- package/.agent/skills/app-builder/templates/express-api/TEMPLATE.md +83 -0
- package/.agent/skills/app-builder/templates/flutter-app/TEMPLATE.md +90 -0
- package/.agent/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +90 -0
- package/.agent/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +122 -0
- package/.agent/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +122 -0
- package/.agent/skills/app-builder/templates/nextjs-static/TEMPLATE.md +169 -0
- package/.agent/skills/app-builder/templates/nuxt-app/TEMPLATE.md +134 -0
- package/.agent/skills/app-builder/templates/python-fastapi/TEMPLATE.md +83 -0
- package/.agent/skills/app-builder/templates/react-native-app/TEMPLATE.md +119 -0
- package/.agent/skills/backend-developer/SKILL.md +763 -0
- package/.agent/skills/backend-developer/references/general-patterns.md +65 -0
- package/.agent/skills/backend-developer/references/go-echo.md +68 -0
- package/.agent/skills/backend-developer/references/go-gin.md +76 -0
- package/.agent/skills/backend-developer/references/java-springboot.md +83 -0
- package/.agent/skills/backend-developer/references/node-express.md +64 -0
- package/.agent/skills/backend-developer/references/node-nestjs.md +69 -0
- package/.agent/skills/backend-developer/references/python-django.md +67 -0
- package/.agent/skills/backend-developer/references/python-fastapi.md +80 -0
- package/.agent/skills/blockchain-engineer/SKILL.md +975 -0
- package/.agent/skills/blockchain-engineer/references/deployment.md +28 -0
- package/.agent/skills/blockchain-engineer/references/evm.md +14 -0
- package/.agent/skills/blockchain-engineer/references/mechanisms.md +32 -0
- package/.agent/skills/blockchain-engineer/references/solidity.md +32 -0
- package/.agent/skills/business-analysis/SKILL.md +85 -0
- package/.agent/skills/business-analysis/references/best-practices/diagrams.md +141 -0
- package/.agent/skills/business-analysis/references/domains/ai-agent.md +94 -0
- package/.agent/skills/business-analysis/references/domains/blockchain-dapp.md +86 -0
- package/.agent/skills/business-analysis/references/domains/ecommerce.md +77 -0
- package/.agent/skills/business-analysis/references/domains/education.md +42 -0
- package/.agent/skills/business-analysis/references/domains/fintech.md +44 -0
- package/.agent/skills/business-analysis/references/domains/fnb.md +82 -0
- package/.agent/skills/business-analysis/references/domains/healthtech.md +44 -0
- package/.agent/skills/business-analysis/references/domains/internal-tools.md +38 -0
- package/.agent/skills/business-analysis/references/domains/marketplace.md +52 -0
- package/.agent/skills/business-analysis/references/domains/saas.md +36 -0
- package/.agent/skills/business-analysis/references/workflows/collaboration.md +41 -0
- package/.agent/skills/business-analysis/scripts/verify_mermaid.py +86 -0
- package/.agent/skills/business-analysis/templates/brd.md +46 -0
- package/.agent/skills/business-analysis/templates/change-request.md +41 -0
- package/.agent/skills/business-analysis/templates/prd-functional.md +38 -0
- package/.agent/skills/business-analysis/templates/use-case.md +40 -0
- package/.agent/skills/business-analysis/templates/user-story-detailed.md +36 -0
- package/.agent/skills/code-review/SKILL.md +113 -0
- package/.agent/skills/code-review/references/code-review-reception.md +209 -0
- package/.agent/skills/code-review/references/differential_review.md +59 -0
- package/.agent/skills/code-review/references/requesting-code-review.md +105 -0
- package/.agent/skills/code-review/references/spec_compliance.md +43 -0
- package/.agent/skills/code-review/references/verification-before-completion.md +139 -0
- package/.agent/skills/context-engineering/SKILL.md +68 -0
- package/.agent/skills/context-engineering/references/context-compression.md +84 -0
- package/.agent/skills/context-engineering/references/context-degradation.md +93 -0
- package/.agent/skills/context-engineering/references/context-fundamentals.md +75 -0
- package/.agent/skills/context-engineering/references/context-optimization.md +82 -0
- package/.agent/skills/context-engineering/references/evaluation.md +89 -0
- package/.agent/skills/context-engineering/references/memory-systems.md +88 -0
- package/.agent/skills/context-engineering/references/multi-agent-patterns.md +90 -0
- package/.agent/skills/context-engineering/references/project-development.md +97 -0
- package/.agent/skills/context-engineering/references/tool-design.md +86 -0
- package/.agent/skills/debugging/SKILL.md +60 -0
- package/.agent/skills/debugging/references/defense-in-depth.md +130 -0
- package/.agent/skills/debugging/references/root-cause-tracing.md +177 -0
- package/.agent/skills/debugging/references/systematic-debugging.md +295 -0
- package/.agent/skills/debugging/references/verification-before-completion.md +142 -0
- package/.agent/skills/designer/SKILL.md +159 -0
- package/.agent/skills/designer/concepts/apple-glass.md +48 -0
- package/.agent/skills/designer/concepts/aurora-gradients.md +26 -0
- package/.agent/skills/designer/concepts/bento-grids.md +14 -0
- package/.agent/skills/designer/concepts/claymorphism.md +27 -0
- package/.agent/skills/designer/concepts/neo-brutalism.md +32 -0
- package/.agent/skills/designer/data/app-interface.csv +31 -0
- package/.agent/skills/designer/data/charts.csv +26 -0
- package/.agent/skills/designer/data/colors.csv +162 -0
- package/.agent/skills/designer/data/design.csv +1776 -0
- package/.agent/skills/designer/data/icons.csv +106 -0
- package/.agent/skills/designer/data/landing.csv +35 -0
- package/.agent/skills/designer/data/products.csv +162 -0
- package/.agent/skills/designer/data/react-performance.csv +45 -0
- package/.agent/skills/designer/data/styles.csv +85 -0
- package/.agent/skills/designer/data/typography.csv +74 -0
- package/.agent/skills/designer/data/ui-reasoning.csv +162 -0
- package/.agent/skills/designer/data/ux-guidelines.csv +100 -0
- package/.agent/skills/designer/references/accessibility.md +172 -0
- package/.agent/skills/designer/references/branding.md +88 -0
- package/.agent/skills/designer/references/color-theory.md +139 -0
- package/.agent/skills/designer/references/creation.md +118 -0
- package/.agent/skills/designer/references/design-systems.md +219 -0
- package/.agent/skills/designer/references/frontend_design_aesthetics.md +57 -0
- package/.agent/skills/designer/references/layout.md +200 -0
- package/.agent/skills/designer/references/motion.md +92 -0
- package/.agent/skills/designer/references/review.md +100 -0
- package/.agent/skills/designer/references/trends.md +209 -0
- package/.agent/skills/designer/references/typography.md +190 -0
- package/.agent/skills/designer/scripts/remove_background.py +135 -0
- package/.agent/skills/designer/scripts/ui-search/__pycache__/core.cpython-314.pyc +0 -0
- package/.agent/skills/designer/scripts/ui-search/__pycache__/design_system.cpython-314.pyc +0 -0
- package/.agent/skills/designer/scripts/ui-search/core.py +217 -0
- package/.agent/skills/designer/scripts/ui-search/design_system.py +1067 -0
- package/.agent/skills/designer/scripts/ui-search/search.py +114 -0
- package/.agent/skills/designer/templates/design-motion-spec.md +30 -0
- package/.agent/skills/devops-engineer/SKILL.md +90 -0
- package/.agent/skills/devops-engineer/docker-compose/README.md +47 -0
- package/.agent/skills/devops-engineer/references/ci-cd-pipelines.md +76 -0
- package/.agent/skills/devops-engineer/references/cloud-providers.md +57 -0
- package/.agent/skills/devops-engineer/references/codebase-normalization.md +104 -0
- package/.agent/skills/devops-engineer/references/container-orchestration.md +69 -0
- package/.agent/skills/devops-engineer/references/iac-tools.md +63 -0
- package/.agent/skills/devops-engineer/references/observability-security.md +45 -0
- package/.agent/skills/devops-engineer/references/vercel-supabase.md +17 -0
- package/.agent/skills/devops-engineer/templates/release-notes.md +8 -0
- package/.agent/skills/frontend-developer/SKILL.md +125 -0
- package/.agent/skills/frontend-developer/react-nextjs/README.md +90 -0
- package/.agent/skills/frontend-developer/references/angular.md +52 -0
- package/.agent/skills/frontend-developer/references/composition_patterns.md +60 -0
- package/.agent/skills/frontend-developer/references/core-performance.md +68 -0
- package/.agent/skills/frontend-developer/references/modern-signals.md +43 -0
- package/.agent/skills/frontend-developer/references/react_performance_rules.md +55 -0
- package/.agent/skills/frontend-developer/references/vue-nuxt.md +55 -0
- package/.agent/skills/frontend-developer/scripts/validate_compliance.py +65 -0
- package/.agent/skills/frontend-developer/threejs/README.md +89 -0
- package/.agent/skills/frontend-developer/threejs/animation.md +552 -0
- package/.agent/skills/frontend-developer/threejs/fundamentals.md +488 -0
- package/.agent/skills/frontend-developer/threejs/geometry.md +548 -0
- package/.agent/skills/frontend-developer/threejs/interaction.md +660 -0
- package/.agent/skills/frontend-developer/threejs/lighting.md +481 -0
- package/.agent/skills/frontend-developer/threejs/loaders.md +623 -0
- package/.agent/skills/frontend-developer/threejs/materials.md +520 -0
- package/.agent/skills/frontend-developer/threejs/postprocessing.md +602 -0
- package/.agent/skills/frontend-developer/threejs/router.json +181 -0
- package/.agent/skills/frontend-developer/threejs/shaders.md +642 -0
- package/.agent/skills/frontend-developer/threejs/textures.md +628 -0
- package/.agent/skills/game-development/2d-games/SKILL.md +119 -0
- package/.agent/skills/game-development/3d-games/SKILL.md +135 -0
- package/.agent/skills/game-development/SKILL.md +167 -0
- package/.agent/skills/game-development/game-art/SKILL.md +185 -0
- package/.agent/skills/game-development/game-audio/SKILL.md +190 -0
- package/.agent/skills/game-development/game-design/SKILL.md +129 -0
- package/.agent/skills/game-development/mobile-games/SKILL.md +108 -0
- package/.agent/skills/game-development/multiplayer/SKILL.md +132 -0
- package/.agent/skills/game-development/pc-games/SKILL.md +144 -0
- package/.agent/skills/game-development/vr-ar/SKILL.md +123 -0
- package/.agent/skills/game-development/web-games/SKILL.md +150 -0
- package/.agent/skills/lead-architect/SKILL.md +85 -0
- package/.agent/skills/lead-architect/references/application-architecture.md +70 -0
- package/.agent/skills/lead-architect/references/infrastructure.md +51 -0
- package/.agent/skills/lead-architect/references/process.md +42 -0
- package/.agent/skills/lead-architect/references/system-architecture.md +62 -0
- package/.agent/skills/lead-architect/references/web-fullstack.md +82 -0
- package/.agent/skills/lead-architect/templates/adr.md +62 -0
- package/.agent/skills/lead-architect/templates/rfc.md +46 -0
- package/.agent/skills/lead-architect/templates/sdd.md +62 -0
- package/.agent/skills/lead-architect/templates/technical-spec.md +61 -0
- package/.agent/skills/marketer/SKILL.md +66 -0
- package/.agent/skills/marketer/remotion-best-practices/SKILL.md +58 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/3d.md +86 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/animations.md +29 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/assets/charts-bar-chart.tsx +173 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/assets/text-animations-typewriter.tsx +100 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/assets/text-animations-word-highlight.tsx +108 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/assets.md +78 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/audio.md +172 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/calculate-metadata.md +104 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/can-decode.md +75 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/charts.md +58 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/compositions.md +146 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/display-captions.md +126 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/extract-frames.md +229 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/fonts.md +152 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/get-audio-duration.md +58 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/get-video-dimensions.md +68 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/get-video-duration.md +58 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/gifs.md +138 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/images.md +130 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/import-srt-captions.md +67 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/lottie.md +68 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/measuring-dom-nodes.md +35 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/measuring-text.md +143 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/sequencing.md +106 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/tailwind.md +11 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/text-animations.md +20 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/timing.md +179 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/transcribe-captions.md +19 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/transitions.md +122 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/trimming.md +53 -0
- package/.agent/skills/marketer/remotion-best-practices/rules/videos.md +171 -0
- package/.agent/skills/mcp-builder/SKILL.md +76 -0
- package/.agent/skills/mcp-builder/references/evaluation.md +602 -0
- package/.agent/skills/mcp-builder/references/mcp_best_practices.md +249 -0
- package/.agent/skills/mcp-builder/references/node_mcp_server.md +970 -0
- package/.agent/skills/mcp-builder/references/python_mcp_server.md +719 -0
- package/.agent/skills/mobile-developer/SKILL.md +83 -0
- package/.agent/skills/mobile-developer/api-routes/SKILL.md +389 -0
- package/.agent/skills/mobile-developer/building-ui/SKILL.md +335 -0
- package/.agent/skills/mobile-developer/building-ui/references/animations.md +220 -0
- package/.agent/skills/mobile-developer/building-ui/references/controls.md +270 -0
- package/.agent/skills/mobile-developer/building-ui/references/form-sheet.md +227 -0
- package/.agent/skills/mobile-developer/building-ui/references/gradients.md +106 -0
- package/.agent/skills/mobile-developer/building-ui/references/icons.md +213 -0
- package/.agent/skills/mobile-developer/building-ui/references/media.md +198 -0
- package/.agent/skills/mobile-developer/building-ui/references/route-structure.md +229 -0
- package/.agent/skills/mobile-developer/building-ui/references/search.md +248 -0
- package/.agent/skills/mobile-developer/building-ui/references/storage.md +121 -0
- package/.agent/skills/mobile-developer/building-ui/references/tabs.md +368 -0
- package/.agent/skills/mobile-developer/building-ui/references/visual-effects.md +197 -0
- package/.agent/skills/mobile-developer/building-ui/references/webgpu-three.md +605 -0
- package/.agent/skills/mobile-developer/cicd-workflows/SKILL.md +107 -0
- package/.agent/skills/mobile-developer/cicd-workflows/scripts/fetch.js +109 -0
- package/.agent/skills/mobile-developer/cicd-workflows/scripts/package.json +11 -0
- package/.agent/skills/mobile-developer/cicd-workflows/scripts/validate.js +84 -0
- package/.agent/skills/mobile-developer/data-fetching/SKILL.md +508 -0
- package/.agent/skills/mobile-developer/deployment/SKILL.md +207 -0
- package/.agent/skills/mobile-developer/deployment/references/app-store-metadata.md +479 -0
- package/.agent/skills/mobile-developer/deployment/references/ios-app-store.md +355 -0
- package/.agent/skills/mobile-developer/deployment/references/play-store.md +246 -0
- package/.agent/skills/mobile-developer/deployment/references/testflight.md +58 -0
- package/.agent/skills/mobile-developer/deployment/references/workflows.md +200 -0
- package/.agent/skills/mobile-developer/dev-client/SKILL.md +181 -0
- package/.agent/skills/mobile-developer/tailwind-setup/SKILL.md +501 -0
- package/.agent/skills/mobile-developer/upgrading-expo/SKILL.md +116 -0
- package/.agent/skills/mobile-developer/upgrading-expo/references/new-architecture.md +79 -0
- package/.agent/skills/mobile-developer/upgrading-expo/references/react-19.md +79 -0
- package/.agent/skills/mobile-developer/upgrading-expo/references/react-compiler.md +59 -0
- package/.agent/skills/mobile-developer/use-dom/SKILL.md +434 -0
- package/.agent/skills/modern-python/SKILL.md +122 -0
- package/.agent/skills/project-manager/SKILL.md +110 -0
- package/.agent/skills/project-manager/references/ba-collaboration.md +62 -0
- package/.agent/skills/project-manager/references/discovery_process.md +52 -0
- package/.agent/skills/project-manager/references/jobs_to_be_done.md +51 -0
- package/.agent/skills/project-manager/references/prd_development.md +52 -0
- package/.agent/skills/project-manager/references/rules-guide.md +55 -0
- package/.agent/skills/project-manager/references/skill-creation.md +98 -0
- package/.agent/skills/project-manager/references/strategic-frameworks.md +62 -0
- package/.agent/skills/project-manager/references/task-decomposition.md +194 -0
- package/.agent/skills/project-manager/references/workflows-guide.md +44 -0
- package/.agent/skills/project-manager/router.json +160 -0
- package/.agent/skills/project-manager/scripts/compare_skill.py +177 -0
- package/.agent/skills/project-manager/scripts/encoding_utils.py +36 -0
- package/.agent/skills/project-manager/scripts/init_skill.py +190 -0
- package/.agent/skills/project-manager/scripts/quick_validate.py +123 -0
- package/.agent/skills/project-manager/templates/pm-strategy-one-pager.md +6 -0
- package/.agent/skills/project-manager/templates/prd-strategic.md +38 -0
- package/.agent/skills/project-manager/templates/skill-questionnaire.md +118 -0
- package/.agent/skills/project-manager/templates/user-story-simple.md +14 -0
- package/.agent/skills/prompt-engineer/SKILL.md +319 -0
- package/.agent/skills/prompt-engineer/skill-creator/README.md +47 -0
- package/.agent/skills/qa-tester/SKILL.md +142 -0
- package/.agent/skills/qa-tester/assets/README.md +8 -0
- package/.agent/skills/qa-tester/references/accessibility_testing.md +35 -0
- package/.agent/skills/qa-tester/references/agent_browser.md +38 -0
- package/.agent/skills/qa-tester/references/automation/api_testing.md +23 -0
- package/.agent/skills/qa-tester/references/automation/best_practices.md +14 -0
- package/.agent/skills/qa-tester/references/automation/jest_vitest.md +26 -0
- package/.agent/skills/qa-tester/references/automation/playwright.md +30 -0
- package/.agent/skills/qa-tester/references/e2e_testing.md +46 -0
- package/.agent/skills/qa-tester/references/integration_testing.md +39 -0
- package/.agent/skills/qa-tester/references/performance_testing.md +44 -0
- package/.agent/skills/qa-tester/references/property_based_testing.md +44 -0
- package/.agent/skills/qa-tester/references/security_audit.md +53 -0
- package/.agent/skills/qa-tester/references/security_testing.md +30 -0
- package/.agent/skills/qa-tester/references/sharp_edges.md +49 -0
- package/.agent/skills/qa-tester/references/static_analysis.md +52 -0
- package/.agent/skills/qa-tester/references/supply_chain_audit.md +54 -0
- package/.agent/skills/qa-tester/references/test_case_standards.md +96 -0
- package/.agent/skills/qa-tester/references/test_report_template.md +32 -0
- package/.agent/skills/qa-tester/references/unit_testing.md +50 -0
- package/.agent/skills/qa-tester/references/visual_testing.md +32 -0
- package/.agent/skills/qa-tester/templates/uat-plan.md +34 -0
- package/.agent/skills/research-first/SKILL.md +118 -0
- package/.agent/skills-manifest.json +264 -0
- package/.agent/workflows/absorb.md +176 -0
- package/.agent/workflows/bootstrap.md +91 -0
- package/.agent/workflows/brainstorm.md +168 -0
- package/.agent/workflows/break-tasks.md +77 -0
- package/.agent/workflows/commit.md +349 -0
- package/.agent/workflows/custom-behavior.md +64 -0
- package/.agent/workflows/debug.md +65 -0
- package/.agent/workflows/development.md +49 -0
- package/.agent/workflows/documentation.md +221 -0
- package/.agent/workflows/gen-tests.md +53 -0
- package/.agent/workflows/guide.md +196 -0
- package/.agent/workflows/implement-feature.md +182 -0
- package/.agent/workflows/install-skill.md +193 -0
- package/.agent/workflows/qa.md +54 -0
- package/.agent/workflows/ui-ux-design.md +108 -0
- package/LICENSE +21 -0
- package/README.md +258 -0
- package/cli/index.js +345 -0
- package/cli/migrate-skills.js +113 -0
- package/cli/verify.js +291 -0
- package/package.json +49 -0
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
# Serving & Optimization
|
|
2
|
+
|
|
3
|
+
Production deployment patterns for LLM applications.
|
|
4
|
+
|
|
5
|
+
## 1. Deployment Architectures
|
|
6
|
+
|
|
7
|
+
### Synchronous API
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from fastapi import FastAPI, HTTPException
|
|
11
|
+
from pydantic import BaseModel
|
|
12
|
+
|
|
13
|
+
app = FastAPI()
|
|
14
|
+
|
|
15
|
+
class QueryRequest(BaseModel):
|
|
16
|
+
query: str
|
|
17
|
+
context: str = None
|
|
18
|
+
max_tokens: int = 500
|
|
19
|
+
|
|
20
|
+
@app.post("/api/v1/complete")
|
|
21
|
+
async def complete(request: QueryRequest):
|
|
22
|
+
try:
|
|
23
|
+
response = await llm.complete(
|
|
24
|
+
request.query,
|
|
25
|
+
max_tokens=request.max_tokens,
|
|
26
|
+
timeout=30
|
|
27
|
+
)
|
|
28
|
+
return {"response": response}
|
|
29
|
+
except TimeoutError:
|
|
30
|
+
raise HTTPException(status_code=504, detail="LLM timeout")
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Asynchronous Queue
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from celery import Celery
|
|
37
|
+
from redis import Redis
|
|
38
|
+
|
|
39
|
+
app = Celery('llm_tasks', broker='redis://localhost:6379')
|
|
40
|
+
|
|
41
|
+
@app.task(bind=True, max_retries=3)
|
|
42
|
+
def async_complete(self, query: str, webhook_url: str):
|
|
43
|
+
try:
|
|
44
|
+
response = llm.complete(query)
|
|
45
|
+
|
|
46
|
+
# Send result via webhook
|
|
47
|
+
requests.post(webhook_url, json={
|
|
48
|
+
"status": "complete",
|
|
49
|
+
"response": response
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
except Exception as exc:
|
|
53
|
+
self.retry(exc=exc, countdown=60)
|
|
54
|
+
|
|
55
|
+
# Usage
|
|
56
|
+
task = async_complete.delay(
|
|
57
|
+
query="Summarize this document...",
|
|
58
|
+
webhook_url="https://example.com/webhook"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
return {"task_id": task.id, "status": "pending"}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Streaming
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from fastapi import StreamingResponse
|
|
68
|
+
|
|
69
|
+
@app.post("/api/v1/stream")
|
|
70
|
+
async def stream_completion(request: QueryRequest):
|
|
71
|
+
async def generate():
|
|
72
|
+
stream = await llm.complete_stream(request.query)
|
|
73
|
+
async for chunk in stream:
|
|
74
|
+
yield f"data: {json.dumps({'token': chunk})}\n\n"
|
|
75
|
+
yield "data: [DONE]\n\n"
|
|
76
|
+
|
|
77
|
+
return StreamingResponse(
|
|
78
|
+
generate(),
|
|
79
|
+
media_type="text/event-stream"
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## 2. Caching Strategies
|
|
84
|
+
|
|
85
|
+
### Exact Match Cache
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
import hashlib
|
|
89
|
+
from redis import Redis
|
|
90
|
+
|
|
91
|
+
redis = Redis(host='localhost', port=6379, db=0)
|
|
92
|
+
|
|
93
|
+
def cache_key(prompt: str, model: str, **params) -> str:
|
|
94
|
+
"""Generate deterministic cache key"""
|
|
95
|
+
key_data = f"{model}:{prompt}:{sorted(params.items())}"
|
|
96
|
+
return hashlib.sha256(key_data.encode()).hexdigest()
|
|
97
|
+
|
|
98
|
+
async def cached_complete(prompt: str, model: str = "gpt-4", **kwargs):
|
|
99
|
+
key = cache_key(prompt, model, **kwargs)
|
|
100
|
+
|
|
101
|
+
# Check cache
|
|
102
|
+
cached = redis.get(key)
|
|
103
|
+
if cached:
|
|
104
|
+
return json.loads(cached)
|
|
105
|
+
|
|
106
|
+
# Generate
|
|
107
|
+
response = await llm.complete(prompt, model=model, **kwargs)
|
|
108
|
+
|
|
109
|
+
# Cache with TTL
|
|
110
|
+
redis.setex(
|
|
111
|
+
key,
|
|
112
|
+
timedelta(hours=24),
|
|
113
|
+
json.dumps(response)
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
return response
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Semantic Cache
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
class SemanticCache:
|
|
123
|
+
"""Cache based on semantic similarity"""
|
|
124
|
+
|
|
125
|
+
def __init__(self, threshold: float = 0.95):
|
|
126
|
+
self.vector_db = VectorDB()
|
|
127
|
+
self.threshold = threshold
|
|
128
|
+
|
|
129
|
+
async def get(self, query: str) -> str | None:
|
|
130
|
+
query_emb = embed(query)
|
|
131
|
+
|
|
132
|
+
# Find similar cached queries
|
|
133
|
+
results = self.vector_db.search(query_emb, top_k=1)
|
|
134
|
+
|
|
135
|
+
if results and cosine_similarity(query_emb, results[0].embedding) > self.threshold:
|
|
136
|
+
return results[0].response
|
|
137
|
+
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
async def set(self, query: str, response: str):
|
|
141
|
+
self.vector_db.upsert({
|
|
142
|
+
"embedding": embed(query),
|
|
143
|
+
"query": query,
|
|
144
|
+
"response": response
|
|
145
|
+
})
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## 3. Batching
|
|
149
|
+
|
|
150
|
+
### Dynamic Batching
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
class DynamicBatcher:
|
|
154
|
+
"""Batch requests to improve throughput"""
|
|
155
|
+
|
|
156
|
+
def __init__(self, max_batch_size: int = 8, max_wait_ms: int = 50):
|
|
157
|
+
self.max_batch_size = max_batch_size
|
|
158
|
+
self.max_wait_ms = max_wait_ms
|
|
159
|
+
self.queue = asyncio.Queue()
|
|
160
|
+
self.results = {}
|
|
161
|
+
|
|
162
|
+
async def submit(self, prompt: str) -> str:
|
|
163
|
+
request_id = str(uuid.uuid4())
|
|
164
|
+
future = asyncio.Future()
|
|
165
|
+
|
|
166
|
+
await self.queue.put({
|
|
167
|
+
"id": request_id,
|
|
168
|
+
"prompt": prompt,
|
|
169
|
+
"future": future
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
return await future
|
|
173
|
+
|
|
174
|
+
async def process_batches(self):
|
|
175
|
+
while True:
|
|
176
|
+
batch = []
|
|
177
|
+
deadline = asyncio.get_event_loop().time() + (self.max_wait_ms / 1000)
|
|
178
|
+
|
|
179
|
+
# Collect batch
|
|
180
|
+
while len(batch) < self.max_batch_size:
|
|
181
|
+
timeout = deadline - asyncio.get_event_loop().time()
|
|
182
|
+
if timeout <= 0:
|
|
183
|
+
break
|
|
184
|
+
|
|
185
|
+
try:
|
|
186
|
+
item = await asyncio.wait_for(
|
|
187
|
+
self.queue.get(),
|
|
188
|
+
timeout=max(0, timeout)
|
|
189
|
+
)
|
|
190
|
+
batch.append(item)
|
|
191
|
+
except asyncio.TimeoutError:
|
|
192
|
+
break
|
|
193
|
+
|
|
194
|
+
if batch:
|
|
195
|
+
await self._process_batch(batch)
|
|
196
|
+
|
|
197
|
+
async def _process_batch(self, batch: list):
|
|
198
|
+
"""Process a batch of requests"""
|
|
199
|
+
prompts = [item["prompt"] for item in batch]
|
|
200
|
+
|
|
201
|
+
# Single batched API call
|
|
202
|
+
responses = await llm.batch_complete(prompts)
|
|
203
|
+
|
|
204
|
+
# Fulfill futures
|
|
205
|
+
for item, response in zip(batch, responses):
|
|
206
|
+
item["future"].set_result(response)
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## 4. Load Balancing
|
|
210
|
+
|
|
211
|
+
### Multi-Provider Failover
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
class ResilientLLM:
|
|
215
|
+
"""Route across multiple providers with failover"""
|
|
216
|
+
|
|
217
|
+
PROVIDERS = [
|
|
218
|
+
{"name": "openai", "model": "gpt-4", "priority": 1},
|
|
219
|
+
{"name": "anthropic", "model": "claude-3-opus", "priority": 2},
|
|
220
|
+
{"name": "together", "model": "llama-3-70b", "priority": 3}
|
|
221
|
+
]
|
|
222
|
+
|
|
223
|
+
def __init__(self):
|
|
224
|
+
self.health = {p["name"]: True for p in self.PROVIDERS}
|
|
225
|
+
|
|
226
|
+
async def complete(self, prompt: str, timeout: float = 30) -> str:
|
|
227
|
+
for provider in sorted(self.PROVIDERS, key=lambda p: p["priority"]):
|
|
228
|
+
if not self.health[provider["name"]]:
|
|
229
|
+
continue
|
|
230
|
+
|
|
231
|
+
try:
|
|
232
|
+
response = await self._call_provider(
|
|
233
|
+
provider,
|
|
234
|
+
prompt,
|
|
235
|
+
timeout=timeout
|
|
236
|
+
)
|
|
237
|
+
self.health[provider["name"]] = True
|
|
238
|
+
return response
|
|
239
|
+
|
|
240
|
+
except Exception as e:
|
|
241
|
+
logger.warning(f"{provider['name']} failed: {e}")
|
|
242
|
+
self.health[provider["name"]] = False
|
|
243
|
+
continue
|
|
244
|
+
|
|
245
|
+
raise AllProvidersFailed("All LLM providers unavailable")
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
## 5. Rate Limiting
|
|
249
|
+
|
|
250
|
+
### Token Bucket
|
|
251
|
+
|
|
252
|
+
```python
|
|
253
|
+
import time
|
|
254
|
+
from threading import Lock
|
|
255
|
+
|
|
256
|
+
class TokenBucket:
|
|
257
|
+
def __init__(self, rate: float, capacity: int):
|
|
258
|
+
"""
|
|
259
|
+
rate: tokens per second
|
|
260
|
+
capacity: maximum burst
|
|
261
|
+
"""
|
|
262
|
+
self.rate = rate
|
|
263
|
+
self.capacity = capacity
|
|
264
|
+
self.tokens = capacity
|
|
265
|
+
self.last_update = time.time()
|
|
266
|
+
self.lock = Lock()
|
|
267
|
+
|
|
268
|
+
def consume(self, tokens: int = 1) -> bool:
|
|
269
|
+
with self.lock:
|
|
270
|
+
now = time.time()
|
|
271
|
+
elapsed = now - self.last_update
|
|
272
|
+
self.tokens = min(
|
|
273
|
+
self.capacity,
|
|
274
|
+
self.tokens + elapsed * self.rate
|
|
275
|
+
)
|
|
276
|
+
self.last_update = now
|
|
277
|
+
|
|
278
|
+
if self.tokens >= tokens:
|
|
279
|
+
self.tokens -= tokens
|
|
280
|
+
return True
|
|
281
|
+
return False
|
|
282
|
+
|
|
283
|
+
# Per-user rate limiting
|
|
284
|
+
USER_BUCKETS = {}
|
|
285
|
+
|
|
286
|
+
def get_user_bucket(user_id: str) -> TokenBucket:
|
|
287
|
+
if user_id not in USER_BUCKETS:
|
|
288
|
+
USER_BUCKETS[user_id] = TokenBucket(rate=1, capacity=10)
|
|
289
|
+
return USER_BUCKETS[user_id]
|
|
290
|
+
|
|
291
|
+
@app.post("/api/complete")
|
|
292
|
+
async def rate_limited_complete(request: Request):
|
|
293
|
+
bucket = get_user_bucket(request.user_id)
|
|
294
|
+
|
|
295
|
+
if not bucket.consume():
|
|
296
|
+
raise HTTPException(
|
|
297
|
+
status_code=429,
|
|
298
|
+
detail="Rate limit exceeded"
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
return await llm.complete(request.query)
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
## 6. Cost Monitoring
|
|
305
|
+
|
|
306
|
+
### Real-time Cost Tracking
|
|
307
|
+
|
|
308
|
+
```python
|
|
309
|
+
class CostTracker:
|
|
310
|
+
PRICING = {
|
|
311
|
+
"gpt-4": {"input": 0.03, "output": 0.06}, # per 1k tokens
|
|
312
|
+
"gpt-3.5-turbo": {"input": 0.0015, "output": 0.002},
|
|
313
|
+
"claude-3-opus": {"input": 0.015, "output": 0.075}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
def __init__(self):
|
|
317
|
+
self.daily_costs = defaultdict(float)
|
|
318
|
+
self.requests = []
|
|
319
|
+
|
|
320
|
+
def log_request(
|
|
321
|
+
self,
|
|
322
|
+
model: str,
|
|
323
|
+
input_tokens: int,
|
|
324
|
+
output_tokens: int,
|
|
325
|
+
user_id: str = None
|
|
326
|
+
):
|
|
327
|
+
pricing = self.PRICING[model]
|
|
328
|
+
cost = (
|
|
329
|
+
input_tokens * pricing["input"] +
|
|
330
|
+
output_tokens * pricing["output"]
|
|
331
|
+
) / 1000
|
|
332
|
+
|
|
333
|
+
today = datetime.now().date()
|
|
334
|
+
self.daily_costs[today] += cost
|
|
335
|
+
|
|
336
|
+
self.requests.append({
|
|
337
|
+
"timestamp": datetime.now(),
|
|
338
|
+
"model": model,
|
|
339
|
+
"cost": cost,
|
|
340
|
+
"user_id": user_id
|
|
341
|
+
})
|
|
342
|
+
|
|
343
|
+
# Alert if approaching budget
|
|
344
|
+
if self.daily_costs[today] > DAILY_BUDGET * 0.8:
|
|
345
|
+
alert(f"Daily cost at 80%: ${self.daily_costs[today]:.2f}")
|
|
346
|
+
|
|
347
|
+
def get_user_costs(self, user_id: str, days: int = 30) -> float:
|
|
348
|
+
cutoff = datetime.now() - timedelta(days=days)
|
|
349
|
+
return sum(
|
|
350
|
+
r["cost"] for r in self.requests
|
|
351
|
+
if r["user_id"] == user_id and r["timestamp"] > cutoff
|
|
352
|
+
)
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
## 7. Performance Optimization
|
|
356
|
+
|
|
357
|
+
### Connection Pooling
|
|
358
|
+
|
|
359
|
+
```python
|
|
360
|
+
from aiohttp import ClientSession, TCPConnector
|
|
361
|
+
|
|
362
|
+
# Reuse connections
|
|
363
|
+
connector = TCPConnector(limit=100, limit_per_host=20)
|
|
364
|
+
session = ClientSession(connector=connector)
|
|
365
|
+
|
|
366
|
+
async def optimized_call(prompt: str):
|
|
367
|
+
async with session.post(
|
|
368
|
+
API_URL,
|
|
369
|
+
json={"prompt": prompt},
|
|
370
|
+
headers={"Authorization": f"Bearer {API_KEY}"}
|
|
371
|
+
) as response:
|
|
372
|
+
return await response.json()
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
### Pre-warming
|
|
376
|
+
|
|
377
|
+
```python
|
|
378
|
+
async def prewarm_models():
|
|
379
|
+
"""Send warmup requests to reduce cold start latency"""
|
|
380
|
+
warmup_prompts = [
|
|
381
|
+
"Hello",
|
|
382
|
+
"What is the weather?",
|
|
383
|
+
"Summarize this"
|
|
384
|
+
]
|
|
385
|
+
|
|
386
|
+
await asyncio.gather(*[
|
|
387
|
+
llm.complete(p, priority="low")
|
|
388
|
+
for p in warmup_prompts
|
|
389
|
+
])
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
### Model Distillation
|
|
393
|
+
|
|
394
|
+
```python
|
|
395
|
+
# Use small model for simple tasks
|
|
396
|
+
# Large model only when needed
|
|
397
|
+
|
|
398
|
+
def route_by_complexity(query: str) -> str:
|
|
399
|
+
classification = classifier.predict(query)
|
|
400
|
+
|
|
401
|
+
if classification == "simple":
|
|
402
|
+
return "gpt-3.5-turbo"
|
|
403
|
+
elif classification == "medium":
|
|
404
|
+
return "claude-3-sonnet"
|
|
405
|
+
else:
|
|
406
|
+
return "gpt-4"
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
## 8. Monitoring
|
|
410
|
+
|
|
411
|
+
### Key Metrics
|
|
412
|
+
|
|
413
|
+
```python
|
|
414
|
+
from prometheus_client import Counter, Histogram, Gauge
|
|
415
|
+
|
|
416
|
+
# Request metrics
|
|
417
|
+
request_count = Counter(
|
|
418
|
+
'llm_requests_total',
|
|
419
|
+
'Total requests',
|
|
420
|
+
['model', 'status']
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
request_duration = Histogram(
|
|
424
|
+
'llm_request_duration_seconds',
|
|
425
|
+
'Request latency',
|
|
426
|
+
['model']
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
tokens_used = Counter(
|
|
430
|
+
'llm_tokens_total',
|
|
431
|
+
'Total tokens',
|
|
432
|
+
['model', 'type'] # input/output
|
|
433
|
+
)
|
|
434
|
+
|
|
435
|
+
cache_hit_rate = Gauge(
|
|
436
|
+
'llm_cache_hit_rate',
|
|
437
|
+
'Cache hit percentage'
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
# Usage tracking
|
|
441
|
+
@app.middleware("http")
|
|
442
|
+
async def track_metrics(request, call_next):
|
|
443
|
+
start = time.time()
|
|
444
|
+
|
|
445
|
+
response = await call_next(request)
|
|
446
|
+
|
|
447
|
+
duration = time.time() - start
|
|
448
|
+
request_duration.labels(model="gpt-4").observe(duration)
|
|
449
|
+
|
|
450
|
+
return response
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
## 9. Scaling Strategies
|
|
454
|
+
|
|
455
|
+
### Horizontal Scaling
|
|
456
|
+
|
|
457
|
+
```yaml
|
|
458
|
+
# docker-compose.yml
|
|
459
|
+
version: '3'
|
|
460
|
+
services:
|
|
461
|
+
api:
|
|
462
|
+
build: .
|
|
463
|
+
deploy:
|
|
464
|
+
replicas: 3
|
|
465
|
+
environment:
|
|
466
|
+
- REDIS_URL=redis://redis:6379
|
|
467
|
+
|
|
468
|
+
worker:
|
|
469
|
+
build: .
|
|
470
|
+
command: celery -A tasks worker --concurrency=4
|
|
471
|
+
deploy:
|
|
472
|
+
replicas: 2
|
|
473
|
+
|
|
474
|
+
redis:
|
|
475
|
+
image: redis:alpine
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
### Auto-scaling
|
|
479
|
+
|
|
480
|
+
```yaml
|
|
481
|
+
# kubernetes hpa
|
|
482
|
+
apiVersion: autoscaling/v2
|
|
483
|
+
kind: HorizontalPodAutoscaler
|
|
484
|
+
metadata:
|
|
485
|
+
name: llm-api
|
|
486
|
+
spec:
|
|
487
|
+
scaleTargetRef:
|
|
488
|
+
apiVersion: apps/v1
|
|
489
|
+
kind: Deployment
|
|
490
|
+
name: llm-api
|
|
491
|
+
minReplicas: 2
|
|
492
|
+
maxReplicas: 10
|
|
493
|
+
metrics:
|
|
494
|
+
- type: Resource
|
|
495
|
+
resource:
|
|
496
|
+
name: cpu
|
|
497
|
+
target:
|
|
498
|
+
type: Utilization
|
|
499
|
+
averageUtilization: 70
|
|
500
|
+
- type: Pods
|
|
501
|
+
pods:
|
|
502
|
+
metric:
|
|
503
|
+
name: llm_requests_per_second
|
|
504
|
+
target:
|
|
505
|
+
type: AverageValue
|
|
506
|
+
averageValue: "100"
|
|
507
|
+
```
|
|
508
|
+
|
|
509
|
+
## 10. Deployment Checklist
|
|
510
|
+
|
|
511
|
+
### Pre-deployment
|
|
512
|
+
- [ ] Load testing completed
|
|
513
|
+
- [ ] Failover tested
|
|
514
|
+
- [ ] Rate limits configured
|
|
515
|
+
- [ ] Monitoring dashboards ready
|
|
516
|
+
- [ ] Alerting rules set up
|
|
517
|
+
- [ ] Rollback plan documented
|
|
518
|
+
|
|
519
|
+
### Security
|
|
520
|
+
- [ ] API authentication enabled
|
|
521
|
+
- [ ] Input validation implemented
|
|
522
|
+
- [ ] Output filtering configured
|
|
523
|
+
- [ ] Audit logging enabled
|
|
524
|
+
- [ ] Secrets management in place
|
|
525
|
+
|
|
526
|
+
### Operations
|
|
527
|
+
- [ ] Health checks implemented
|
|
528
|
+
- [ ] Graceful shutdown handled
|
|
529
|
+
- [ ] Log aggregation configured
|
|
530
|
+
- [ ] Cost tracking enabled
|
|
531
|
+
- [ ] Documentation updated
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# Vector Databases
|
|
2
|
+
|
|
3
|
+
Vector databases for RAG, semantic search, and embeddings storage.
|
|
4
|
+
|
|
5
|
+
## When to Use
|
|
6
|
+
|
|
7
|
+
Use this capability when:
|
|
8
|
+
- Building RAG (Retrieval Augmented Generation) systems
|
|
9
|
+
- Implementing semantic search
|
|
10
|
+
- Storing and querying embeddings
|
|
11
|
+
- Building recommendation engines
|
|
12
|
+
|
|
13
|
+
## Providers
|
|
14
|
+
|
|
15
|
+
| Provider | Best For | Integration |
|
|
16
|
+
|:---------|:---------|:------------|
|
|
17
|
+
| **Pinecone** | Managed, high-scale | REST API, SDK |
|
|
18
|
+
| **Chroma** | Open source, local dev | Embedded, no server |
|
|
19
|
+
| **Weaviate** | GraphQL interface | GraphQL + vector |
|
|
20
|
+
| **pgvector** | Postgres integration | SQL extensions |
|
|
21
|
+
| **Qdrant** | Rust-based, fast | gRPC/HTTP |
|
|
22
|
+
|
|
23
|
+
## Quick Start (Chroma)
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
import chromadb
|
|
27
|
+
|
|
28
|
+
# In-memory (dev)
|
|
29
|
+
client = chromadb.Client()
|
|
30
|
+
|
|
31
|
+
# Or persistent
|
|
32
|
+
client = chromadb.PersistentClient(path="./chroma_db")
|
|
33
|
+
|
|
34
|
+
# Create collection
|
|
35
|
+
collection = client.create_collection("documents")
|
|
36
|
+
|
|
37
|
+
# Add documents
|
|
38
|
+
collection.add(
|
|
39
|
+
documents=["doc1 content", "doc2 content"],
|
|
40
|
+
metadatas=[{"source": "web"}, {"source": "pdf"}],
|
|
41
|
+
ids=["id1", "id2"]
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# Query
|
|
45
|
+
results = collection.query(
|
|
46
|
+
query_texts=["search query"],
|
|
47
|
+
n_results=5
|
|
48
|
+
)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Quick Start (Pinecone)
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from pinecone import Pinecone
|
|
55
|
+
|
|
56
|
+
pc = Pinecone(api_key="your-api-key")
|
|
57
|
+
index = pc.Index("my-index")
|
|
58
|
+
|
|
59
|
+
# Upsert vectors
|
|
60
|
+
index.upsert(vectors=[
|
|
61
|
+
{
|
|
62
|
+
"id": "vec1",
|
|
63
|
+
"values": [0.1, 0.2, 0.3, ...], # embedding
|
|
64
|
+
"metadata": {"text": "original text"}
|
|
65
|
+
}
|
|
66
|
+
])
|
|
67
|
+
|
|
68
|
+
# Query
|
|
69
|
+
results = index.query(
|
|
70
|
+
vector=[0.1, 0.2, 0.3, ...],
|
|
71
|
+
top_k=5,
|
|
72
|
+
include_metadata=True
|
|
73
|
+
)
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## RAG Pipeline Integration
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# 1. Generate embeddings
|
|
80
|
+
from openai import OpenAI
|
|
81
|
+
client = OpenAI()
|
|
82
|
+
|
|
83
|
+
def get_embedding(text):
|
|
84
|
+
response = client.embeddings.create(
|
|
85
|
+
model="text-embedding-3-small",
|
|
86
|
+
input=text
|
|
87
|
+
)
|
|
88
|
+
return response.data[0].embedding
|
|
89
|
+
|
|
90
|
+
# 2. Store in vector DB
|
|
91
|
+
def store_document(doc_id, text, metadata):
|
|
92
|
+
embedding = get_embedding(text)
|
|
93
|
+
collection.add(
|
|
94
|
+
ids=[doc_id],
|
|
95
|
+
embeddings=[embedding],
|
|
96
|
+
documents=[text],
|
|
97
|
+
metadatas=[metadata]
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
# 3. Retrieve for RAG
|
|
101
|
+
def retrieve_context(query, top_k=5):
|
|
102
|
+
query_embedding = get_embedding(query)
|
|
103
|
+
results = collection.query(
|
|
104
|
+
query_embeddings=[query_embedding],
|
|
105
|
+
n_results=top_k
|
|
106
|
+
)
|
|
107
|
+
return results['documents'][0]
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Hybrid Search
|
|
111
|
+
|
|
112
|
+
Combine vector + keyword search for better results:
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
# Sparse (BM25) + Dense (embeddings)
|
|
116
|
+
def hybrid_search(query, alpha=0.5):
|
|
117
|
+
# Get keyword results
|
|
118
|
+
keyword_results = bm25_search(query)
|
|
119
|
+
|
|
120
|
+
# Get vector results
|
|
121
|
+
vector_results = vector_search(query)
|
|
122
|
+
|
|
123
|
+
# Combine with reciprocal rank fusion
|
|
124
|
+
return reciprocal_rank_fusion(
|
|
125
|
+
keyword_results,
|
|
126
|
+
vector_results,
|
|
127
|
+
k=60
|
|
128
|
+
)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Best Practices
|
|
132
|
+
|
|
133
|
+
- **Dimension matching** — Ensure embedding model matches DB dimensions
|
|
134
|
+
- **Batch operations** — Upsert in batches (100-1000) for efficiency
|
|
135
|
+
- **Metadata filtering** — Use metadata filters to narrow search space
|
|
136
|
+
- **Index tuning** — Adjust index type based on recall vs speed needs
|
|
137
|
+
- **Monitoring** — Track query latency and recall metrics
|