Skip to main content
This page focuses on a single pattern: wiring Morphik retrieval tools into your own agent loop.

Build a Retrieval Agent with Morphik Tools

Use Morphik’s retrieval APIs as function-calling tools when you want a lightweight agent loop you fully control. The example below uses OpenAI’s Responses API, list_documents for discovery, and retrieve_chunks (with ColPali image URLs) for grounded answers.
Prerequisites: pip install morphik openai, set MORPHIK_URI and OPENAI_API_KEY, and update the metadata fields in SYSTEM_INSTRUCTIONS to match your corpus.
Giving the LLM direct access to retrieval tools lets it decide when to explore vs. fetch, narrow scope with filters, and request only the needed pages. This example exposes two tools, but you can add more (e.g., page-range or download helpers) from the API reference to expand the agent’s toolkit while keeping guardrails tight. You can use any major LLM with tool-calling support (OpenAI, Anthropic, Gemini, etc.); we show OpenAI for familiarity and will add provider-specific snippets soon—the core loop remains the same. Imports used in the snippets below:

1) System prompt

Use this to govern the agent’s behavior, metadata awareness, and citation discipline; it is the primary control surface for how the loop plans and answers.

2) Tool schemas (OpenAI Responses API)

Expose only the tools you want the model to call. The schema format may differ slightly by provider, but the tool list and arguments stay consistent.

3) Tool implementations (Morphik Python SDK)

These Python functions bridge the LLM’s tool calls to Morphik APIs and normalize outputs (metadata, previews, image URLs) for reuse in the loop.

4) Agent runner (OpenAI Responses loop)

Handles the model call, executes tool invocations, and re-feeds results until the model returns a final answer. Swap the client/model for any tool-calling LLM and keep the structure.

5) Optional CLI entry point

Run it with your own question:
To extend this loop, add more Morphik tools (e.g., page-range retrieval or download helpers) from the API reference into TOOLS and implement matching handlers in the runner. This retrieval agent pattern shows how to keep full control over tool usage while grounding responses with Morphik. The agent’s ability to plan, execute tools, and remember context makes it ideal for sophisticated business intelligence and research workflows.