Skip to main content

defog

A comprehensive Python toolkit for AI-powered data operations - from natural language SQL queries to multi-agent orchestration.

Features

  • 🤖 Cross-provider LLM operations - Unified interface for OpenAI, Anthropic, Gemini, Grok (xAI), and Together AI
  • 📊 SQL Agent - Convert natural language to SQL with automatic table filtering for large databases
  • 🔍 Data extraction - Extract structured data from PDFs, images, HTML, text documents, and even images embedded in HTML
  • 🛠️ Advanced AI tools - Code interpreter, web search, YouTube transcription, document citations
  • 🎭 Agent orchestration - Hierarchical task delegation and multi-agent coordination
  • 💾 Memory management - Automatic conversation compactification for long contexts

Installation

pip install --upgrade defog

Quick Start

1. LLM Chat (Cross-Provider)

from defog.llm.utils import chat_async
from defog.llm.llm_providers import LLMProvider

# Works with any provider
response = await chat_async(
    provider=LLMProvider.ANTHROPIC,  # or OPENAI, GEMINI
    model="claude-sonnet-4-20250514",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.content)

OpenAI GPT‑5: Responses API controls

from defog.llm.utils import chat_async
from defog.llm.llm_providers import LLMProvider

response = await chat_async(
    provider=LLMProvider.OPENAI,
    model="gpt-5.1",
    messages=[
        {"role": "system", "content": "You are concise and helpful."},
        {"role": "user", "content": "Summarize the benefits of unit tests."},
    ],
    # Optional Responses API controls for GPT‑5.1
    reasoning_effort="none",   # none | low | medium | high
    verbosity="low",              # low | medium | high
)
print(response.content)

2. Natural Language to SQL

from defog.llm.sql import sql_answer_tool
from defog.llm.llm_providers import LLMProvider

# Ask questions in natural language
result = await sql_answer_tool(
    question="What are the top 10 customers by total sales?",
    db_type="postgres",
    db_creds={
        "host": "localhost",
        "database": "mydb",
        "user": "postgres",
        "password": "password",
        "port": 5432
    },
    model="claude-sonnet-4-20250514",
    provider=LLMProvider.ANTHROPIC
)

print(f"SQL: {result['query']}")
print(f"Results: {result['results']}")

3. Extract Data from PDFs

from defog.llm import extract_pdf_data

# Extract structured data from any PDF
data = await extract_pdf_data(
    pdf_url="https://example.com/financial_report.pdf",
    focus_areas=["revenue", "financial metrics"]
)

for datapoint_name, extracted_data in data["data"].items():
    print(f"{datapoint_name}: {extracted_data}")

4. Code Interpreter

from defog.llm.code_interp import code_interpreter_tool
from defog.llm.llm_providers import LLMProvider

# Execute Python code with AI assistance
result = await code_interpreter_tool(
    question="Analyze this data and create a visualization",
    csv_string="name,sales\nAlice,100\nBob,150",
    model="gpt-4o",
    provider=LLMProvider.OPENAI
)

print(result["code"])    # Generated Python code
print(result["output"])  # Execution results

5. Using MCP Servers with chat_async

from defog.llm.utils import chat_async
from defog.llm.llm_providers import LLMProvider

# Use MCP servers for dynamic tool integration
# Works with both local and remote MCP servers
response = await chat_async(
    provider=LLMProvider.OPENAI,
    model="gpt-4.1",
    mcp_servers=["http://localhost:8000/mcp"],  # Can be local or remote
    messages=[
        {"role": "user", "content": "How many users are in the first table?"}
    ]
)

# MCP tools are automatically converted to Python functions
# and made available to the LLM
print(response.content)

6. Anthropic Server-Side Tools and Programmatic Tool Calling

chat_async exposes Anthropic's first-party server-side tools (web_search, web_fetch, code_execution, advisor) and the new programmatic tool calling flow, where Claude writes Python in the code execution sandbox that calls your local tools as await my_tool(...) — keeping intermediate results in the sandbox so they never re-enter the model context.

from pydantic import BaseModel
from defog.llm.utils import chat_async


# Server-side web_search
response = await chat_async(
    provider="anthropic",
    model="claude-opus-4-6",
    messages=[{"role": "user", "content": "What's the latest defog-python release?"}],
    server_tools=["web_search"],
)
print(response.content)
print(response.server_tool_outputs)   # raw web_search_tool_result blocks
print(response.server_tool_usage)     # {"web_search_requests": 1, ...}


# Programmatic tool calling: Claude calls your tool from inside code execution
class QueryArgs(BaseModel):
    sql: str

async def query_database(input: QueryArgs) -> list:
    """Run a SQL query and return rows as JSON."""
    return [{"customer": "Acme", "revenue": 50_000}]

response = await chat_async(
    provider="anthropic",
    model="claude-opus-4-6",
    messages=[{"role": "user", "content": "Who is the top customer by revenue?"}],
    tools=[query_database],
    server_tools=["code_execution"],
    programmatic_tool_calling=True,
)
print(response.content)
print(response.container_id)   # reuse via `container_id=` on a follow-up call


# Task budgets: advisory token cap across the full agentic loop
# (Claude Opus 4.7 only). Accepts an int (expands to {"type": "tokens",
# "total": N}) or the full dict with optional "remaining" for loops that
# compact history between requests. Minimum 20,000 tokens.
response = await chat_async(
    provider="anthropic",
    model="claude-opus-4-7",
    messages=[{"role": "user", "content": "Audit this repo for security issues."}],
    tools=[...],
    task_budget=64000,
)

See docs/llm/anthropic-server-tools.md for the full reference, including version overrides for Bedrock/Vertex, container reuse, and the LLMResponse shape additions.

Documentation

📚 Full Documentation - Comprehensive guides and API reference

Quick Links

Environment Variables

# API Keys
export OPENAI_API_KEY="your-openai-key"
export ANTHROPIC_API_KEY="your-anthropic-key"
export GEMINI_API_KEY="your-gemini-key"

Advanced Use Cases

For advanced features like:

  • Memory compactification for long conversations
  • YouTube video transcription and summarization
  • Multi-agent orchestration with shared context
  • Database schema auto-documentation
  • Model Context Protocol (MCP) support

See the full documentation.

Development

Testing and formatting

  1. Run tests: python -m pytest tests
  2. Format code: ruff format
  3. Update documentation when adding features

Using our MCP Server

  1. Run defog serve once to complete your setup, and defog db to update your database credentials
  2. Add to your MCP Client
    • Claude Code: claude mcp add defog -- python3 -m defog.mcp_server. Or if you do not want to install the defog package globally or set up environment variables, run claude mcp add dfg -- uv run --directory FULL_PATH_TO_VENV_DIRECTORY --env-file .env -m defog.mcp_server
    • Claude Desktop: add the config below
    {
        "mcpServers": {
            "defog": {
                "command": "python3",
                "args": ["-m", "defog.mcp_server"],
                "env": {
                    "OPENAI_API_KEY": "YOUR_OPENAI_KEY",
                    "ANTHROPIC_API_KEY": "YOUR_ANTHROPIC_KEY",
                    "GEMINI_API_KEY": "YOUR_GEMINI_KEY",
                    "DB_TYPE": "YOUR_DB_TYPE",
                    "DB_HOST": "YOUR_DB_HOST",
                    "DB_PORT": "YOUR_DB_PORT",
                    "DB_USER": "YOUR_DB_USER",
                    "DB_PASSWORD": "YOUR_DB_PASSWORD",
                    "DB_NAME": "YOUR_DB_NAME"
                }
            }
        }
        }
    

Available MCP Tools and Resources

The Defog MCP server provides the following capabilities:

Tools (actions the AI can perform):

  • text_to_sql_tool - Execute natural language queries against your database
  • list_database_schema - List all tables and their schemas
  • youtube_video_summary - Get transcript/summary of YouTube videos (requires Gemini API key)
  • extract_pdf_data - Extract structured data from PDFs
  • extract_html_data - Extract structured data from HTML pages
  • extract_text_data - Extract structured data from text files

Resources (read-only data the AI can access):

  • schema://tables - Get list of all tables in the database
  • schema://table/{table_name} - Get detailed schema for a specific table
  • stats://table/{table_name} - Get statistics and metadata for a table (row count, column statistics)
  • sample://table/{table_name} - Get sample data (10 rows) from a table

License

MIT License - see LICENSE file for details.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

defog-1.6.14.tar.gz (324.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

defog-1.6.14-py3-none-any.whl (252.3 kB view details)

Uploaded Python 3

File details

Details for the file defog-1.6.14.tar.gz.

File metadata

  • Download URL: defog-1.6.14.tar.gz
  • Upload date:
  • Size: 324.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for defog-1.6.14.tar.gz
Algorithm Hash digest
SHA256 61947cd2b22f7decb987c4225bf813829bb45a7fc272b0b36566f0c85fd602f8
MD5 c70981d744db3db475e044d7c9543b40
BLAKE2b-256 4757d6bff33ff773cacf9bb0da5378fd9d777775a3c2215d553534aa42653caf

See more details on using hashes here.

File details

Details for the file defog-1.6.14-py3-none-any.whl.

File metadata

  • Download URL: defog-1.6.14-py3-none-any.whl
  • Upload date:
  • Size: 252.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for defog-1.6.14-py3-none-any.whl
Algorithm Hash digest
SHA256 625c09daaa987e5452233ccecc412caeecb0dd217fc551e40f83ef05740136a5
MD5 1859d9a365603d9f7d285a6616824a45
BLAKE2b-256 b33a7a1a06f0e8eadc00bb1068d3edb2027fc0912ac44721bcefb69a3bbc5fd9

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.6.14 This release

2 files

1.6.13

2 files

1.6.12

2 files

1.6.11

2 files

1.6.10

1 file

1.6.9

2 files

1.6.8

2 files

1.6.7

1 file

1.6.6

2 files

1.6.5

2 files

1.6.4

2 files

1.6.3

2 files

1.6.2

1 file

1.6.1

1 file

1.6.0

1 file

1.5.12

1 file

1.5.11

1 file

1.5.10

1 file

1.5.9

1 file

1.5.8

2 files

1.5.7

2 files

1.5.6

2 files

1.5.5

2 files

1.5.4

2 files

1.5.3

1 file

1.5.2

2 files

1.5.1

2 files

1.5.0

2 files

1.4.49

2 files

1.4.48

2 files

1.4.47

2 files

1.4.46

2 files

1.4.45

2 files

1.4.44

2 files

1.4.43

1 file

1.4.42

1 file

1.4.41

2 files

1.4.40

1 file

1.4.39

1 file

1.4.38

1 file

1.4.37

1 file

1.4.36

1 file

1.4.35

1 file

1.4.34

1 file

1.4.33

1 file

1.4.32

1 file

1.4.31

1 file

1.4.30

1 file

1.4.29

1 file

1.4.28

1 file

1.4.27

1 file

1.4.26

1 file

1.4.25

1 file

1.4.24

1 file

1.4.23

1 file

1.4.22

1 file

1.4.21

1 file

1.4.20

1 file

1.4.19

1 file

1.4.18

1 file

1.4.17

1 file

1.4.16

1 file

1.4.15

1 file

1.4.14

1 file

1.4.13

1 file

1.4.12

1 file

1.4.11

1 file

1.4.10

1 file

1.4.9

1 file

1.4.8

1 file

1.4.7

1 file

1.4.6

1 file

1.4.5

1 file

1.4.4

1 file

1.4.3

1 file

1.4.2

1 file

1.4.1

1 file

1.4.0

1 file

1.3.10

1 file

1.3.9

1 file

1.3.8

1 file

1.3.7

1 file

1.3.6

1 file

1.3.5

1 file

1.3.4

1 file

1.3.3

1 file

1.3.2

1 file

1.3.1

1 file

1.3.0

1 file

1.2.17

1 file

1.2.16

1 file

1.2.15

1 file

1.2.14

1 file

1.2.13

1 file

1.2.12

1 file

1.2.11

1 file

1.2.10

1 file

1.2.9

1 file

1.2.8

1 file

1.2.7

1 file

1.2.6

1 file

1.2.5

1 file

1.2.4

1 file

1.2.3

1 file

1.2.2

1 file

1.2.1

1 file

1.2.0

1 file

1.1.16

1 file

1.1.15

1 file

1.1.14

1 file

1.1.13

1 file

1.1.12

1 file

1.1.11

1 file

1.1.10

1 file

1.1.9

1 file

1.1.8

1 file

1.1.7

1 file

1.1.6

1 file

1.1.5

1 file

1.1.4

1 file

1.1.3

1 file

1.1.2

1 file

1.1.1

1 file

1.1.0

1 file

1.0.2

1 file

1.0.1

1 file

1.0.0

1 file

0.72.4

1 file

0.72.3

1 file

0.72.2

1 file

0.72.1

1 file

0.72.0

1 file

0.71.0

1 file

0.70.1

1 file

0.70.0

1 file

0.69.7

1 file

0.69.6

1 file

0.69.5

1 file

0.69.4

1 file

0.69.3

1 file

0.69.2

1 file

0.69.1

1 file

0.69.0

1 file

0.68.4

1 file

0.68.3

1 file

0.68.2

1 file

0.68.1

1 file

0.68.0

1 file

0.67.15

1 file

0.67.14

1 file

0.67.13

1 file

0.67.12

1 file

0.67.11

1 file

0.67.10

1 file

0.67.9

1 file

0.67.8

1 file

0.67.7

1 file

0.67.6

1 file

0.67.5

1 file

0.67.4

1 file

0.67.3

1 file

0.67.2

1 file

0.67.1

1 file

0.67.0

1 file

0.66.1

1 file

0.66.0

1 file

0.65.24

1 file

0.65.23

1 file

0.65.22

1 file

0.65.21

1 file

0.65.20

1 file

0.65.19

1 file

0.65.18

1 file

0.65.17

1 file

0.65.16

1 file

0.65.15

1 file

0.65.14

1 file

0.65.13

1 file

0.65.12

1 file

0.65.11

1 file

0.65.10

1 file

0.65.9

1 file

0.65.8

1 file

0.65.7

1 file

0.65.6

1 file

0.65.5

1 file

0.65.4

1 file

0.65.3

1 file

0.65.2

1 file

0.65.1

1 file

0.65.0

1 file

0.64.2

1 file

0.64.1

1 file

0.64.0

1 file

0.63.8

1 file

0.63.7

1 file

0.63.6

1 file

0.63.5

1 file

0.63.4

1 file

0.63.3

1 file

0.63.2

2 files

0.63.1

2 files

0.63.0

2 files

0.62.7

1 file

0.62.6

1 file

0.62.5

1 file

0.62.4

1 file

0.62.3

1 file

0.62.2

1 file

0.62.1

1 file

0.62.0

1 file

0.61.0

1 file

0.60.0

2 files

0.59.0

1 file

0.58.0

1 file

0.57.1

1 file

0.57.0

1 file

0.56.4

1 file

0.56.3

1 file

0.56.2

1 file

0.56.0

1 file

0.55.1

1 file

0.55.0

1 file

0.54.6

1 file

0.54.5

1 file

0.54.3

1 file

0.54.2

1 file

0.54.0

1 file

0.53.1

1 file

0.53.0

1 file

0.52.2

1 file

0.52.0

1 file

0.51.0

1 file

0.50.0

1 file

0.49.0

1 file

0.48.3

1 file

0.48.2

1 file

0.48.1

1 file

0.48.0

1 file

0.47.7

1 file

0.47.6

1 file

0.47.5

2 files

0.47.4

2 files

0.47.3

1 file

0.47.2

1 file

0.47

1 file

0.46.3

1 file

0.46.2

2 files

0.46.1

1 file

0.46

1 file

0.45

1 file

0.44.1

1 file

0.44.0

1 file

0.43.0

1 file

0.42.2

1 file

0.42.1

1 file

0.42.0

1 file

0.41.1

2 files

0.41.0

1 file

0.40.2

2 files

0.40.1

2 files

0.40.0

2 files

0.39.0

1 file

0.38.0

1 file

0.37.0

1 file

0.36.0

1 file

0.35.0

1 file

0.34.0

1 file

0.33.0

1 file

0.32.0

1 file

0.31.0

1 file

0.30.0

1 file

0.29.0

1 file

0.28.0

1 file

0.27.0

1 file

0.26.0

2 files

0.25.0

2 files

0.24.0

1 file

0.23.0

1 file

0.22.0

1 file

0.21.0

1 file

0.20.0

1 file

0.19.0

1 file

0.18.0

1 file

0.17.0

1 file

0.16.0

1 file

0.15.0

1 file

0.14.0

1 file

0.13.0

1 file

0.12.0

1 file

0.11.0

1 file

0.10.0

1 file

0.9.2

1 file

0.9.1

1 file

0.9.0

1 file

0.8.0

1 file

0.7.0

1 file

0.6.1

1 file

0.6

1 file

0.5.3

1 file

0.5.2

1 file

0.5.1

1 file

0.5.0

1 file

0.4.0

1 file

0.3.0

1 file

0.2.0

1 file

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page