diff --git a/app/ai/page.tsx b/app/ai/page.tsx index de034af..39d06a4 100644 --- a/app/ai/page.tsx +++ b/app/ai/page.tsx @@ -1,15 +1,10 @@ -import Image from "next/image"; +import type { ReactNode } from "react"; import Link from "next/link"; import CommandSnippet from "../components/CommandSnippet"; +import { SampleCard } from "../components/SampleCard"; import TelemetryNote from "../components/TelemetryNote"; +import { samples } from "../data/samples"; import { getMetadata } from "../services/metadataService"; -import { - documentdbGitHubForks, - documentdbGitHubStars, - documentdbTscMembers, - documentdbTscOrganizations, -} from "../services/projectStats"; -import { withBasePath } from "../services/sitePath"; export const metadata = getMetadata({ title: "DocumentDB for AI - Vector Search, RAG, and Embeddings", @@ -27,47 +22,61 @@ export const metadata = getMetadata({ ], }); +const agentKitUrl = "https://github.com/Azure/documentdb-agent-kit"; +const vectorSearchReference = "/docs/reference/operators/aggregation/$vectorsearch/"; + const quickRunCommand = `docker run -dt --pull always --name documentdb \\ -p 127.0.0.1:10260:10260 \\ -e USERNAME=admin \\ -e PASSWORD=password \\ ghcr.io/documentdb/documentdb/documentdb-local:latest`; -const connectCommand = `mongosh "mongodb://admin:password@localhost:10260/?tls=true&tlsAllowInvalidCertificates=true"`; +const modelCommand = `ollama pull nomic-embed-text +pip install pymongo ollama`; -const createIndexCommand = `// Real embeddings are longer: set dimensions to your model's size, such as 1536. -db.documents.insertMany([ - { title: "Vector indexes", category: "technical", embedding: [0.10, -0.02, 0.30] }, - { title: "Release notes", category: "news", embedding: [0.90, 0.40, -0.10] } -]); +const storeCode = `import ollama +from pymongo import MongoClient -db.runCommand({ - createIndexes: "documents", - indexes: [{ - key: { embedding: "cosmosSearch" }, - name: "vector_idx", - cosmosSearchOptions: { - kind: "vector-hnsw", - similarity: "COS", - dimensions: 3 - } - }] -}); +client = MongoClient("mongodb://admin:password@localhost:10260/?tls=true&tlsAllowInvalidCertificates=true") +db = client.demo -// $vectorSearch filters need an index on each filtered field. -db.documents.createIndex({ category: 1 });`; +def embed(text): + return ollama.embed(model="nomic-embed-text", input=text)["embeddings"][0] -const vectorSearchCommand = `db.documents.aggregate([ - { - $vectorSearch: { - queryVector: [0.12, -0.04, 0.31], - path: "embedding", - limit: 10, - numCandidates: 100, - filter: { category: "technical" } - } - } -]);`; +notes = [ + "DocumentDB is an open-source document database built on PostgreSQL.", + "Our office is closed on public holidays.", + "Keep each text chunk next to its embedding so retrieval returns the source.", +] +db.notes.insert_many([{"text": t, "embedding": embed(t)} for t in notes]) + +db.command({ + "createIndexes": "notes", + "indexes": [{ + "key": {"embedding": "cosmosSearch"}, + "name": "vector_idx", + "cosmosSearchOptions": { + "kind": "vector-hnsw", + "similarity": "COS", + "dimensions": 768, # nomic-embed-text output size + }, + }], +})`; + +const searchCode = `question = "Which database runs on Postgres?" +results = db.notes.aggregate([ + {"$vectorSearch": {"queryVector": embed(question), "path": "embedding", "limit": 2}}, + {"$project": {"_id": 0, "text": 1, "score": {"$meta": "searchScore"}}}, +]) +for note in results: + print(f"{note['score']:.2f} {note['text']}")`; + +const documentExample = `{ + _id: "handbook-chunk-42", + text: "Keep each chunk next to its embedding...", + source: "handbook.pdf", + embedding: [0.0213, -0.0871, 0.0456, /* ...768 numbers */] +}`; const heroBadges = [ "Start locally in minutes", @@ -106,35 +115,37 @@ const beforeAfter = [ const quickStartSteps = [ { step: "01", - title: "Run locally with Docker", - description: - "One command to start DocumentDB on port 10260 with local credentials.", + title: "Run DocumentDB", + description: "One command starts DocumentDB on port 10260 with local credentials.", label: "Docker", code: quickRunCommand, }, { step: "02", - title: "Connect with mongosh", + title: "Get an embedding model", description: - "Connect with mongosh, pymongo, the Node.js driver, or another standard Mongo client.", + "Ollama runs an open embedding model on your machine, so your text never leaves it. Any model works; size the index to its output.", label: "Shell", - code: connectCommand, + code: modelCommand, + link: { label: "Download Ollama", href: "https://ollama.com/download" }, }, { step: "03", - title: "Create a vector index", + title: "Store text with its embedding", description: - "Add sample documents, a native HNSW vector index with cosine similarity, and an index on the field you filter by.", - label: "Index", - code: createIndexCommand, + "Embed each note, store it next to its text, and add an HNSW vector index with cosine similarity.", + label: "Python: store", + code: storeCode, + link: { label: "createIndexes reference", href: "/docs/reference/commands/indexing/createIndexes/" }, }, { step: "04", - title: "Query by meaning", + title: "Ask a question", description: - "Retrieve semantically similar results with vector search and optional metadata filters.", - label: "Vector search", - code: vectorSearchCommand, + "Add this to the same script. It embeds the question and returns the closest notes with their similarity scores.", + label: "Python: search", + code: searchCode, + link: { label: "$vectorSearch reference", href: vectorSearchReference }, }, ]; @@ -148,6 +159,7 @@ const useCases = [ "Pre-filter by category, source, or recency before retrieval", "Return source text alongside similarity scores", ], + sampleId: "hotel-agent-ts", }, { badge: "Search", @@ -158,6 +170,7 @@ const useCases = [ "Choose cosine, L2, or inner product for your domain", "Mix vector results with metadata filters in one query", ], + sampleId: "content-semantic-search-py", }, { badge: "Agents", @@ -168,57 +181,48 @@ const useCases = [ "Persist tool outputs, plans, and dialogue turns naturally", "Recall relevant history without scanning entire threads", ], + sampleId: "personal-memory-mcp-ts", }, { badge: "Graph + AI", title: "Knowledge navigation", description: - "Find the best vector matches, then traverse related entities with `$graphLookup` in one query pipeline.", + "Find the best vector matches, then traverse related entities with $graphLookup in one query pipeline.", points: [ "Recursive traversal with depth control", "Useful when retrieval also needs relationship traversal", ], + reference: { label: "$graphLookup reference", href: "/docs/reference/operators/aggregation/$graphlookup/" }, }, ]; -const credibilityPoints = [ - { - value: documentdbGitHubStars, - label: "GitHub stars", - }, - { - value: documentdbGitHubForks, - label: "Forks", - }, - { - value: documentdbTscMembers, - label: "TSC members", - detail: `across ${documentdbTscOrganizations} organizations`, - }, -]; +// The gallery is compiled from its registry at build time, so new vector search samples show up here on their own +const aiSamples = samples.filter((sample) => sample.tags.includes("Vector Search")); +const aiFrameworks = ["LlamaIndex", "Ollama", "OpenAI", "MCP"].filter((tag) => + aiSamples.some((sample) => sample.tags.includes(tag)), +); -const contributorLogos = [ - { - name: "Microsoft", - src: "/images/AzureLogo.png", - }, - { - name: "Amazon", - src: "/images/AWS%20Logo.png", - }, - { - name: "Rippling", - src: "/images/Rippling%20Logo%20no%20background.png", - }, - { - name: "YugabyteDB", - src: "/images/YugabyteLogo.png", - }, - { - name: "AB InBev", - src: "/images/AB%20InBev%20transparent%20logo.png", - }, -]; +function useCaseLink(useCase: (typeof useCases)[number]) { + if (useCase.reference) return useCase.reference; + const sample = samples.find((candidate) => candidate.id === useCase.sampleId); + return sample ? { label: `Sample: ${sample.title.split(":")[0]}`, href: sample.githubUrl } : null; +} + +// Site paths go through Link so preview deployments keep their base path +function TextLink({ href, className, children }: { href: string; className: string; children: ReactNode }) { + if (href.startsWith("/")) { + return ( + + {children} + + ); + } + return ( + + {children} + + ); +} function SectionIntro({ eyebrow, @@ -242,6 +246,8 @@ function SectionIntro({ ); } +const textLinkClass = "font-semibold text-violet-300 transition-colors hover:text-violet-200"; + export default function AIPage() { return (
@@ -263,18 +269,18 @@ export default function AIPage() { keep documents plus embeddings together — no extra sync layer needed.

- - Start with Docker - - + - Explore AI/ML Samples - + See AI samples +
{heroBadges.map((badge) => ( @@ -291,24 +297,24 @@ export default function AIPage() {
- Quick start + One document - Vector search in minutes + No second database

- Start locally with one Docker command + Your text, its metadata, and its embedding live together

-

- Spin up DocumentDB with Docker, then follow the four-step quick - start below to connect with mongosh, create a vector index, and - run your first vector search. -

-
- - +
+
+                {documentExample}
+              
+

+ A single $vectorSearch stage finds the + nearest embeddings and returns the documents they belong to. +

@@ -373,12 +379,15 @@ export default function AIPage() {

-
+
{quickStartSteps.map((item) => ( @@ -400,14 +409,16 @@ export default function AIPage() { {item.code === quickRunCommand && }
+ {item.link ? ( + + {item.link.label} + + ) : null} ))}
- + Follow the full Docker quick start
- {useCases.map((item) => ( -
- - {item.badge} - -

{item.title}

-

{item.description}

-
    - {item.points.map((point) => ( -
  • - - {point} -
  • - ))} -
-
- ))} + {useCases.map((item) => { + const link = useCaseLink(item); + return ( +
+ + {item.badge} + +

{item.title}

+

{item.description}

+
    + {item.points.map((point) => ( +
  • + + {point} +
  • + ))} +
+ {link ? ( + + {link.label} + + ) : null} +
+ ); + })}
-
+
-
- {credibilityPoints.map((item) => ( -
-

{item.value}

-

- {item.label} -

- {"detail" in item && item.detail && ( -

{item.detail}

- )} -
+ {aiFrameworks.length > 0 ? ( +
+ Built with + {aiFrameworks.map((framework) => ( + + {framework} + + ))} +
+ ) : null} +
+ {aiSamples.map((sample) => ( + ))}
-
- {contributorLogos.map((logo) => ( -
- {logo.name} + + Browse all samples + +
+
+ +
+
+
+
+
+

+ For coding agents +

+ + Public preview +
- ))} +

+ Teach your coding agent DocumentDB +

+

+ Agent-Kit gives Claude Code, Cursor, Codex, Gemini CLI, and GitHub Copilot skills + for data modeling, indexing, and vector search, an MCP server, and read-only + diagnostics for a local DocumentDB container. +

+
+ + Get Agent-Kit on GitHub +
@@ -501,7 +541,7 @@ export default function AIPage() { Ready to try it?

- Go from zero to vector search in four commands. Open source, self-hosted, MIT-licensed. + Go from zero to vector search in four steps. Open source, self-hosted, MIT-licensed.

}) { +type NavLink = { label: string; href: string; section?: string }; +type NavGroup = { label: string; items: NavLink[] }; +type NavIconLink = NavLink & { icon: string }; + +const links: (NavLink | NavGroup)[] = nav.links; +const iconLinks: NavIconLink[] = nav.icons; + +const desktopLinkClass = + "flex items-center gap-1 font-medium text-gray-300 transition-colors duration-200 hover:text-blue-400 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-blue-400"; +const dropdownLinkClass = + "flex items-center justify-between gap-3 rounded-md px-3 py-2 text-sm font-medium text-gray-300 transition-colors duration-200 hover:bg-neutral-800 hover:text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-400"; +const mobileLinkClass = + "flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium text-gray-300 transition-colors duration-200 hover:bg-neutral-800 hover:text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-400"; + +function isExternal(href: string) { + return /^https?:\/\//.test(href); +} + +function groupId(label: string) { + return `nav-${label.toLowerCase()}`; +} + +function NavAnchor({ + link, + className, + onClick, + children, +}: { + link: NavLink; + className: string; + onClick?: () => void; + children: ReactNode; +}) { + if (isExternal(link.href)) { + return ( + + {children} + + ); + } + + // Jekyll builds these sections, so they are not Next.js routes + if (link.section) { + return ( + + {children} + + ); + } + + return ( + + {children} + + ); +} + +function BrandIcon({ name }: { name: string }) { if (name === "github") { return ( - + {item.label} - - ); - - if (item.kind === "link") { + if (name === "discord") { return ( - - {content} - + ); } + return null; +} + +function ExternalIcon() { return ( - - {content} - + ); } export default function Navbar() { const [isMenuOpen, setIsMenuOpen] = useState(false); + const [openGroup, setOpenGroup] = useState(null); + const desktopNav = useRef(null); const closeMenu = () => setIsMenuOpen(false); + const closeGroup = () => setOpenGroup(null); + + useEffect(() => { + if (!openGroup) return; + // Safari never focuses a clicked button, so blur alone cannot close the panel + const closeOnOutsidePointer = (event: PointerEvent) => { + if (!desktopNav.current?.contains(event.target as Node)) setOpenGroup(null); + }; + const closeOnEscape = (event: KeyboardEvent) => { + if (event.key !== "Escape") return; + setOpenGroup(null); + document.getElementById(`${groupId(openGroup)}-button`)?.focus(); + }; + document.addEventListener("pointerdown", closeOnOutsidePointer); + document.addEventListener("keydown", closeOnEscape); + return () => { + document.removeEventListener("pointerdown", closeOnOutsidePointer); + document.removeEventListener("keydown", closeOnEscape); + }; + }, [openGroup]); return (