Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions .github/workflows/agents.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
name: Agent examples

on:
push:
branches: [main]
paths: ["agents/**", ".github/workflows/agents.yml", "sample.pdf"]
pull_request:
paths: ["agents/**", ".github/workflows/agents.yml", "sample.pdf"]
schedule:
# Weekly: these examples sit on fast-moving frameworks and unpinned upper bounds.
- cron: "30 6 * * 1"

permissions:
contents: read

jobs:
python:
name: ${{ matrix.example }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- { example: openai-agents-sdk, script: agent.py, expect: "Tool result received" }
- { example: crewai, script: crew.py, expect: "requires your own model key" }
- { example: langgraph, script: graph.py, expect: "Tool result:" }
- { example: semantic-kernel, script: plugin.py, expect: "pages containing 'multi-page': [1]" }
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install
working-directory: agents/${{ matrix.example }}
run: pip install -r requirements.txt
- name: Run against sample.pdf, no model key
working-directory: agents/${{ matrix.example }}
env:
CREWAI_DISABLE_TELEMETRY: "true"
OTEL_SDK_DISABLED: "true"
run: |
set -o pipefail
python ${{ matrix.script }} | tee out.txt
grep -qF "${{ matrix.expect }}" out.txt
grep -q "Sample Document" out.txt

typescript:
name: ${{ matrix.example }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
example: [vercel-ai-sdk, mastra]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- uses: actions/setup-node@v4
with:
node-version: "22"
- name: Install pdfluent-mcp
run: pip install pdfluent-mcp
- name: Install
working-directory: agents/${{ matrix.example }}
run: npm ci
- name: Type check
working-directory: agents/${{ matrix.example }}
run: npx tsc --noEmit --module nodenext --moduleResolution nodenext --target es2022 --skipLibCheck --strict agent.ts
- name: Run against sample.pdf, no model key
working-directory: agents/${{ matrix.example }}
run: |
set -o pipefail
npx tsx agent.ts | tee out.txt
grep -q "get_metadata" out.txt
grep -q "Sample Document" out.txt
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/rust/target/
*.pdf
!rust/examples/fixtures/
/agents/*/node_modules/
__pycache__/
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ cargo run --example text_extraction -- ../sample.pdf
| [`redact_text`](rust/examples/redact_text.rs) | Search-based redaction: find patterns and permanently remove them | Rust | `cargo run --example redact_text -- in.pdf out.pdf PATTERN` |
| [`wasm/index.html`](wasm/index.html) | Open a PDF and extract its text entirely in the browser via `@pdfluent/sdk-wasm`, no server, no upload | JavaScript (WASM) | Serve the repo root (`python3 -m http.server`), open `/wasm/` |

### Agent frameworks

Read a PDF from OpenAI Agents SDK, Vercel AI SDK, Mastra, CrewAI, LangGraph and Semantic Kernel. See [`agents/`](agents/README.md).

### How-to guide programs

The `howto_*` examples are the programs from the how-to guides on pdfluent.com, byte for byte; each guide page links here and embeds the video in which the same code is typed and run. Each one reads the input file named in its source, from the directory you run it in.
Expand Down
14 changes: 14 additions & 0 deletions agents/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Agent framework examples

Each folder reads a local PDF with PDFluent inside one agent framework. Every script runs against the bundled `../sample.pdf` and does as much as it can without a model: it starts the tool source, lists the tools and calls them directly. Where the framework allows a local stand-in model, the agent loop runs on that; otherwise the script says "requires your own model key" and stops before the model call. No script reads a key from anywhere except the environment variable it names.

| Folder | Framework | PDFluent route | Agent loop without a key |
|---|---|---|---|
| [`openai-agents-sdk`](openai-agents-sdk) | OpenAI Agents SDK | `pdfluent-mcp` stdio server | local stub model |
| [`vercel-ai-sdk`](vercel-ai-sdk) | Vercel AI SDK (TypeScript) | `pdfluent-mcp` through `@ai-sdk/mcp` | mock model |
| [`mastra`](mastra) | Mastra (TypeScript) | `pdfluent-mcp` through `@mastra/mcp` | stops before the model call |
| [`crewai`](crewai) | CrewAI | tool over the `pdfluent` package | stops before the model call |
| [`langgraph`](langgraph) | LangGraph | `langchain-pdfluent` loader | local stub chat model |
| [`semantic-kernel`](semantic-kernel) | Semantic Kernel (Python) | plugin over the `pdfluent` package | stops before the model call |

CI runs every script on each pull request and weekly (`.github/workflows/agents.yml`).
34 changes: 34 additions & 0 deletions agents/crewai/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# CrewAI with PDFluent

A CrewAI `BaseTool` (`pdf_to_markdown`) that wraps the `pdfluent` Python package. The script calls the tool directly, then builds an `Agent`, a `Task` and a `Crew` around it.

## Run

```bash
git clone https://github.com/pdfluent/examples
cd examples/agents/crewai
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python crew.py
```

The script reads `../../sample.pdf` unless you pass another path as the first argument. The PDFluent MCP server only reads and writes inside the folder of that file.

## Model

`crew.kickoff()` requires your own model key: set `OPENAI_API_KEY`, or set `CREWAI_MODEL` to another provider's model name together with that provider's key. Without a key the script stops before the model call.

## Output

Recorded on 2026-11-16 (macOS, no model key set). The extracted markdown of the sample PDF is printed in between; it is left out here.

```text
--- tool called directly ---
This is a small public sample PDF used by the PDFluent examples. It contains plain text so text-extraction demos have something to find. Generated for
--- crew built: 1 agent, 1 task, ['pdf_to_markdown']
--- crew.kickoff() skipped: requires your own model key (OPENAI_API_KEY, or CREWAI_MODEL for another provider) ---
```

## Licence

This example is MIT. It uses `pdfluent` and `pdfluent-mcp`, which are released under AGPL-3.0 or a commercial licence; see the [PDFluent licence page](https://pdfluent.com/license).
61 changes: 61 additions & 0 deletions agents/crewai/crew.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""CrewAI tool that wraps the pdfluent Python package.

The tool is plain CrewAI: a BaseTool whose _run calls pdfluent. The script calls
the tool directly (no model needed), builds the crew, and runs it only when a
model key is set.
"""

import os
import sys
from pathlib import Path

import pdfluent
from crewai import Agent, Crew, Task
from crewai.tools import BaseTool
from pydantic import BaseModel, Field

pdf = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).parents[2] / "sample.pdf").resolve()


class PdfInput(BaseModel):
path: str = Field(description="Path of a local PDF file")


class PdfMarkdownTool(BaseTool):
name: str = "pdf_to_markdown"
description: str = "Read a local PDF and return it as markdown, in reading order."
args_schema: type[BaseModel] = PdfInput

def _run(self, path: str) -> str:
doc = pdfluent.open(path)
try:
return doc.extract_markdown()
finally:
doc.close()


tool = PdfMarkdownTool()

print("--- tool called directly ---")
print(tool.run(path=str(pdf))[:600])

reader = Agent(
role="PDF reader",
goal="Answer questions about a PDF from its extracted markdown",
backstory="You only use the pdf_to_markdown tool and never guess.",
tools=[tool],
llm=os.environ.get("CREWAI_MODEL", "gpt-4o-mini"),
allow_delegation=False,
)
task = Task(
description=f"List the headings of {pdf} and say how many pages it has.",
expected_output="A short bullet list.",
agent=reader,
)
crew = Crew(agents=[reader], tasks=[task])
print("--- crew built:", len(crew.agents), "agent,", len(crew.tasks), "task,", [t.name for t in reader.tools])

if os.environ.get("OPENAI_API_KEY"):
print(crew.kickoff())
else:
print("--- crew.kickoff() skipped: requires your own model key (OPENAI_API_KEY, or CREWAI_MODEL for another provider) ---")
2 changes: 2 additions & 0 deletions agents/crewai/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
crewai>=1.15
pdfluent>=1.4
33 changes: 33 additions & 0 deletions agents/langgraph/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# LangGraph with PDFluent

A LangChain tool that loads a PDF with `langchain-pdfluent` (`PDFluentLoader`, one `Document` per heading, paragraph, list item or table, with `page` and `bbox` metadata), wired into a LangGraph agent built with `langchain.agents.create_agent`.

## Run

```bash
git clone https://github.com/pdfluent/examples
cd examples/agents/langgraph
python3 -m venv .venv && . .venv/bin/activate
pip install -r requirements.txt
python graph.py
```

The script reads `../../sample.pdf` unless you pass another path as the first argument. The PDFluent MCP server only reads and writes inside the folder of that file.

## Model

With `OPENAI_API_KEY` set (and `langchain-openai` installed) the agent uses `gpt-4o-mini`. Without a key a local stub chat model issues one `read_pdf` call and echoes the result, so the graph, the tool node and the loader all run for real. The stub has no language ability.

## Output

Recorded on 2026-11-16 (macOS, no model key set). The extracted markdown of the sample PDF is printed in between; it is left out here.

```text
--- model: local stub (no OPENAI_API_KEY set; a real run requires your own model key) ---
human: 'What is in /path/to/examples/sample.pdf?'
ai: '' tool_calls=['read_pdf']
```

## Licence

This example is MIT. It uses `pdfluent` and `pdfluent-mcp`, which are released under AGPL-3.0 or a commercial licence; see the [PDFluent licence page](https://pdfluent.com/license).
62 changes: 62 additions & 0 deletions agents/langgraph/graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""LangGraph agent whose tool loads a PDF with langchain-pdfluent.

The loader turns the PDF into one LangChain Document per block (heading,
paragraph, list item or table) with page and bounding box in the metadata.
Without a model key the graph runs on a local stub model that issues one tool
call, so the graph, the tool node and the loader all run for real.
"""

import os
import sys
from pathlib import Path

from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.tools import tool
from langchain_pdfluent import PDFluentLoader
from langchain.agents import create_agent # builds a LangGraph graph

pdf = Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).parents[2] / "sample.pdf").resolve()


@tool
def read_pdf(path: str) -> str:
"""Read a local PDF and return its blocks, one per line, with kind and page (0-based)."""
docs = PDFluentLoader(path).load()
return "\n".join(f"[{d.metadata['kind']} p{d.metadata['page']}] {d.page_content}" for d in docs)


class StubChatModel(BaseChatModel):
"""Calls read_pdf once, then answers with what the tool returned. No language ability."""

path: str

@property
def _llm_type(self) -> str:
return "stub"

def bind_tools(self, tools, **kwargs):
return self

def _generate(self, messages, stop=None, run_manager=None, **kwargs):
if messages[-1].type == "tool":
msg = AIMessage(content="Tool result: " + messages[-1].content)
else:
msg = AIMessage(content="", tool_calls=[{"name": "read_pdf", "args": {"path": self.path}, "id": "call_1"}])
return ChatResult(generations=[ChatGeneration(message=msg)])


if os.environ.get("OPENAI_API_KEY"):
from langchain_openai import ChatOpenAI # pip install langchain-openai

model = ChatOpenAI(model="gpt-4o-mini")
print("--- model: OpenAI ---")
else:
model = StubChatModel(path=str(pdf))
print("--- model: local stub (no OPENAI_API_KEY set; a real run requires your own model key) ---")

agent = create_agent(model, [read_pdf])
result = agent.invoke({"messages": [("user", f"What is in {pdf}?")]})
for m in result["messages"]:
print(f"{m.type}: {str(m.content)[:400]!r}" + (f" tool_calls={[c['name'] for c in m.tool_calls]}" if getattr(m, "tool_calls", None) else ""))
5 changes: 5 additions & 0 deletions agents/langgraph/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
langchain>=1.0
langgraph>=1.2
langchain-pdfluent>=0.2
# only for a real model:
# langchain-openai
36 changes: 36 additions & 0 deletions agents/mastra/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Mastra with PDFluent

Starts `pdfluent-mcp` through Mastra's `MCPClient`, lists the tools (prefixed with the server name, for example `pdfluent_extract_markdown`), calls two of them directly and builds an `Agent` with them.

## Run

```bash
git clone https://github.com/pdfluent/examples
cd examples/agents/mastra
python3 -m pip install pdfluent-mcp # puts `pdfluent-mcp` on PATH
npm install
npx tsx agent.ts
```

The script reads `../../sample.pdf` unless you pass another path as the first argument. The PDFluent MCP server only reads and writes inside the folder of that file.

## Model

The `agent.generate()` call needs a model, so it requires your own model key (`OPENAI_API_KEY`). Without one the script builds the agent and stops before the model call; everything up to that point runs against the real server.

## Output

Recorded on 2026-11-16 (macOS, no model key set). The extracted markdown of the sample PDF is printed in between; it is left out here.

```text
tools: pdfluent_extract_markdown, pdfluent_extract_text, pdfluent_extract_tables, pdfluent_extract_blocks, pdfluent_get_metadata, pdfluent_search, pdf
--- pdfluent_get_metadata ---
{"result":{"path":"/path/to/examples/sample.pdf","bytes":2172,"pages":2,"title":"untitled","author":"anonymous","subject":"unspecified","created":"D:2
--- pdfluent_extract_markdown ---
--- agent built with 9 tools ---
--- agent.generate() skipped: requires your own model key (OPENAI_API_KEY) ---
```

## Licence

This example is MIT. It uses `pdfluent` and `pdfluent-mcp`, which are released under AGPL-3.0 or a commercial licence; see the [PDFluent licence page](https://pdfluent.com/license).
Loading
Loading