Examples for integrating Cortex with popular frameworks, AI tools, and automation platforms.
Retrieving knowledge from Cortex?
The recommended first call for "ask the Cortex" / "find something in the Cortex" is a streaming Deep Research query: POST /api/ask/stream (SSE) with use_agentic: true — see Ask AI. The non-streaming POST /api/ask shown in some examples below is for platforms that cannot consume SSE (Slack slash commands, n8n HTTP nodes); it serves quick chat answers only, is bounded by a ~28s server deadline, and rejects use_agentic: true.
AI Coding Agents (Cortex Skills)
The fastest way to integrate is to let your AI agent do it. Cortex Skills (source) serves curated, always-current SKILL.md files over plain HTTP — one per subsystem — so agents work from ground truth instead of stale training data:
Code
https://cortexskills.org/SKILL.md # index: how to build on Cortexhttps://cortexskills.org/upload/SKILL.md # document ingestionhttps://cortexskills.org/search/SKILL.md # hybrid searchhttps://cortexskills.org/ask/SKILL.md # RAG Q&A + streaminghttps://cortexskills.org/cortex/SKILL.md # use Cortex as agent long-term memoryhttps://cortexskills.org/hermes/SKILL.md # long-term memory for Hermes agents (recommended)https://cortexskills.org/openclaw/SKILL.md # the same memory skill on OpenClawhttps://cortexskills.org/mcp/SKILL.md # MCP server setup (Claude, Cursor, ...)https://cortexskills.org/llms.txt # machine-readable skill listing
Example prompt:
Fetch https://cortexskills.org/upload/SKILL.md and use it to write a Python script that batch-uploads a folder of PDFs to my Cortex instance.
Official TypeScript SDK
For JavaScript/TypeScript, skip the hand-rolled fetch wrappers below — the official SDK owns the whole integration surface (unified ask with depth, SSE streaming that correctly handles the late memory frame, conversation threads, upload-and-wait, collections, webhooks, typed errors) and works against current and older Cortex versions alike:
Code
npm install @mocaos/cortex-client
Code
import { CortexClient } from "@mocaos/cortex-client";const cortex = new CortexClient({ baseUrl: process.env.CORTEX_API_URL!, apiKey: process.env.CORTEX_API_KEY!,});const quick = await cortex.ask("What did we decide about the auth rewrite?");const deep = await cortex.deepResearch("Compare every approach we tried", { onContent: (token) => process.stdout.write(token),});const thread = cortex.thread("research-session"); // multi-turn memoryawait thread.ask("How does authentication work?");await thread.ask("Expand on the caching part"); // follow-ups work
from langchain.schema import BaseRetriever, Documentfrom typing import Listimport requestsclass CortexRetriever(BaseRetriever): """LangChain retriever that uses Cortex for search.""" base_url: str api_key: str collection_id: str = "default" k: int = 5 class Config: arbitrary_types_allowed = True def _get_relevant_documents(self, query: str) -> List[Document]: """Retrieve relevant documents from Cortex.""" response = requests.post( f"{self.base_url}/api/search", headers={"X-API-Key": self.api_key}, json={ "query": query, "limit": self.k, "collection_id": self.collection_id } ) response.raise_for_status() results = response.json()["results"] return [ Document( page_content=r["content"], metadata={ "source": r["document_title"], "doc_id": r["document_id"], "score": r["score"] } ) for r in results ]# Usage with LangChainfrom langchain.chains import RetrievalQAfrom langchain.chat_models import ChatOpenAIretriever = CortexRetriever( base_url="http://localhost:8000", api_key="your-key", collection_id="research", k=5)llm = ChatOpenAI(model="gpt-4o-mini")qa_chain = RetrievalQA.from_chain_type( llm=llm, retriever=retriever, return_source_documents=True)result = qa_chain({"query": "What are the key findings?"})print(result["result"])
LangChain Tool
Code
from langchain.tools import Toolimport requestsdef cortex_search(query: str) -> str: """Search the Cortex knowledge base.""" response = requests.post( "http://localhost:8000/api/search", headers={"X-API-Key": "your-key"}, json={"query": query, "limit": 5} ) results = response.json()["results"] return "\n\n".join([ f"**{r['document_title']}**: {r['content'][:500]}" for r in results ])cortex_tool = Tool( name="Cortex Search", func=cortex_search, description="Search the company knowledge base for information about products, processes, and documentation.")# Use with an agentfrom langchain.agents import initialize_agent, AgentTypefrom langchain.chat_models import ChatOpenAIagent = initialize_agent( tools=[cortex_tool], llm=ChatOpenAI(model="gpt-4o-mini"), agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION)response = agent.run("What does our documentation say about authentication?")
Slack Bot Integration
Code
from slack_bolt import Appfrom slack_bolt.adapter.socket_mode import SocketModeHandlerimport requestsimport osapp = App(token=os.environ["SLACK_BOT_TOKEN"])CORTEX_URL = os.environ["CORTEX_API_URL"]CORTEX_KEY = os.environ["CORTEX_API_KEY"]@app.command("/ask")def handle_ask(ack, respond, command): """Handle /ask slash command.""" ack() question = command["text"] if not question: respond("Please provide a question: `/ask What is X?`") return respond(f"Looking up: _{question}_...") try: response = requests.post( f"{CORTEX_URL}/api/ask", headers={"X-API-Key": CORTEX_KEY}, json={"question": question} ) response.raise_for_status() data = response.json() answer = data["answer"] sources = data.get("sources", []) # Format response blocks = [ { "type": "section", "text": {"type": "mrkdwn", "text": f"*Answer:*\n{answer}"} } ] if sources: source_text = "\n".join([ f"• {s['document_title']}" for s in sources[:3] ]) blocks.append({ "type": "context", "elements": [ {"type": "mrkdwn", "text": f"*Sources:*\n{source_text}"} ] }) respond(blocks=blocks) except Exception as e: respond(f"Error: {str(e)}")@app.command("/search")def handle_search(ack, respond, command): """Handle /search slash command.""" ack() query = command["text"] if not query: respond("Please provide a search query: `/search topic`") return try: response = requests.post( f"{CORTEX_URL}/api/search", headers={"X-API-Key": CORTEX_KEY}, json={"query": query, "limit": 5} ) response.raise_for_status() results = response.json()["results"] if not results: respond("No results found.") return blocks = [ { "type": "section", "text": {"type": "mrkdwn", "text": f"*Search results for:* _{query}_"} } ] for r in results: blocks.append({ "type": "section", "text": { "type": "mrkdwn", "text": f"*{r['document_title']}*\n{r['content'][:200]}..." } }) respond(blocks=blocks) except Exception as e: respond(f"Error: {str(e)}")if __name__ == "__main__": handler = SocketModeHandler( app, os.environ["SLACK_APP_TOKEN"] ) handler.start()