Skip to content

Core Modules

This section contains documentation for the core modules of DeepCritical.

Agents

DeepCritical Agents - Pydantic AI-based agent system for research workflows.

This module provides a comprehensive agent system following Pydantic AI patterns, integrating with existing tools and state machines for bioinformatics, search, and RAG workflows.

Classes:

Name Description
AgentDependencies

Dependencies for agent execution.

AgentResult

Result from agent execution.

AgentStatus

Agent execution status.

AgentType

Types of agents in the DeepCritical system.

BaseAgent

Base class for all DeepCritical agents following Pydantic AI patterns.

BioinformaticsAgent

Agent for bioinformatics data fusion and reasoning.

DeepAgentFilesystemAgent

DeepAgent filesystem agent integrated with DeepResearch.

DeepAgentGeneralAgent

DeepAgent general-purpose agent integrated with DeepResearch.

DeepAgentOrchestrationAgent

DeepAgent orchestration agent integrated with DeepResearch.

DeepAgentPlanningAgent

DeepAgent planning agent integrated with DeepResearch.

DeepAgentResearchAgent

DeepAgent research agent integrated with DeepResearch.

DeepSearchAgent

Agent for deep search operations with iterative refinement.

EvaluatorAgent

Agent for evaluating research results and quality.

ExecutionHistory

History of agent executions.

ExecutorAgent

Agent for executing research workflows.

MultiAgentOrchestrator

Orchestrator for coordinating multiple agents in complex workflows.

ParserAgent

Agent for parsing and understanding research questions.

PlannerAgent

Agent for planning research workflows.

RAGAgent

Agent for RAG (Retrieval-Augmented Generation) operations.

SearchAgent

Agent for web search operations.

Functions:

Name Description
create_agent

Create an agent of the specified type.

create_orchestrator

Create a multi-agent orchestrator.

Attributes

__all__ module-attribute

__all__ = [
    "AgentDependencies",
    "AgentResult",
    "AgentStatus",
    "AgentType",
    "BaseAgent",
    "BioinformaticsAgent",
    "DeepAgentFilesystemAgent",
    "DeepAgentGeneralAgent",
    "DeepAgentOrchestrationAgent",
    "DeepAgentPlanningAgent",
    "DeepAgentResearchAgent",
    "DeepSearchAgent",
    "EvaluatorAgent",
    "ExecutionHistory",
    "ExecutorAgent",
    "MultiAgentOrchestrator",
    "ParserAgent",
    "PlannerAgent",
    "RAGAgent",
    "SearchAgent",
    "create_agent",
    "create_orchestrator",
]

Classes

AgentDependencies dataclass

AgentDependencies(
    config: dict[str, Any] = dict(),
    tools: list[str] = list(),
    other_agents: list[str] = list(),
    data_sources: list[str] = list(),
)

Dependencies for agent execution.

Attributes:

Name Type Description
config dict[str, Any]
data_sources list[str]
other_agents list[str]
tools list[str]

Attributes

config class-attribute instance-attribute

config: dict[str, Any] = field(default_factory=dict)

data_sources class-attribute instance-attribute

data_sources: list[str] = field(default_factory=list)

other_agents class-attribute instance-attribute

other_agents: list[str] = field(default_factory=list)

tools class-attribute instance-attribute

tools: list[str] = field(default_factory=list)

Functions

AgentResult dataclass

AgentResult(
    success: bool,
    data: dict[str, Any] = dict(),
    metadata: dict[str, Any] = dict(),
    error: str | None = None,
    execution_time: float = 0.0,
    agent_type: AgentType = EXECUTOR,
)

Result from agent execution.

Attributes:

Name Type Description
agent_type AgentType
data dict[str, Any]
error str | None
execution_time float
metadata dict[str, Any]
success bool

Attributes

agent_type class-attribute instance-attribute

agent_type: AgentType = EXECUTOR

data class-attribute instance-attribute

data: dict[str, Any] = field(default_factory=dict)

error class-attribute instance-attribute

error: str | None = None

execution_time class-attribute instance-attribute

execution_time: float = 0.0

metadata class-attribute instance-attribute

metadata: dict[str, Any] = field(default_factory=dict)

success instance-attribute

success: bool

Functions

AgentStatus

Bases: str, Enum

Agent execution status.

Attributes:

Name Type Description
COMPLETED
FAILED
IDLE
RETRYING
RUNNING

Attributes

COMPLETED class-attribute instance-attribute

COMPLETED = 'completed'

FAILED class-attribute instance-attribute

FAILED = 'failed'

IDLE class-attribute instance-attribute

IDLE = 'idle'

RETRYING class-attribute instance-attribute

RETRYING = 'retrying'

RUNNING class-attribute instance-attribute

RUNNING = 'running'

AgentType

Bases: str, Enum

Types of agents in the DeepCritical system.

Attributes:

Name Type Description
BIOINFORMATICS
DEEPSEARCH
DEEP_AGENT_FILESYSTEM
DEEP_AGENT_GENERAL
DEEP_AGENT_ORCHESTRATION
DEEP_AGENT_PLANNING
DEEP_AGENT_RESEARCH
EVALUATOR
EXECUTOR
ORCHESTRATOR
PARSER
PLANNER
RAG
SEARCH

Attributes

BIOINFORMATICS class-attribute instance-attribute

BIOINFORMATICS = 'bioinformatics'

DEEPSEARCH class-attribute instance-attribute

DEEPSEARCH = 'deepsearch'

DEEP_AGENT_FILESYSTEM class-attribute instance-attribute

DEEP_AGENT_FILESYSTEM = 'deep_agent_filesystem'

DEEP_AGENT_GENERAL class-attribute instance-attribute

DEEP_AGENT_GENERAL = 'deep_agent_general'

DEEP_AGENT_ORCHESTRATION class-attribute instance-attribute

DEEP_AGENT_ORCHESTRATION = 'deep_agent_orchestration'

DEEP_AGENT_PLANNING class-attribute instance-attribute

DEEP_AGENT_PLANNING = 'deep_agent_planning'

DEEP_AGENT_RESEARCH class-attribute instance-attribute

DEEP_AGENT_RESEARCH = 'deep_agent_research'

EVALUATOR class-attribute instance-attribute

EVALUATOR = 'evaluator'

EXECUTOR class-attribute instance-attribute

EXECUTOR = 'executor'

ORCHESTRATOR class-attribute instance-attribute

ORCHESTRATOR = 'orchestrator'

PARSER class-attribute instance-attribute

PARSER = 'parser'

PLANNER class-attribute instance-attribute

PLANNER = 'planner'

RAG class-attribute instance-attribute

RAG = 'rag'

SEARCH class-attribute instance-attribute

SEARCH = 'search'

BaseAgent

BaseAgent(
    agent_type: AgentType,
    model_name: str = "anthropic:claude-sonnet-4-0",
    dependencies: AgentDependencies | None = None,
    system_prompt: str | None = None,
    instructions: str | None = None,
)

Bases: ABC

Base class for all DeepCritical agents following Pydantic AI patterns.

This abstract base class provides the foundation for all agent implementations in DeepCritical, integrating Pydantic AI agents with the existing tool ecosystem and state management systems.

Attributes:

Name Type Description
agent_type AgentType

The type of agent (search, rag, bioinformatics, etc.)

model_name str

The AI model to use for this agent

_agent Agent

The underlying Pydantic AI agent instance

_prompts AgentPrompts

Agent-specific prompt templates

Examples:

Creating a custom agent:

class MyCustomAgent(BaseAgent):
    def __init__(self):
        super().__init__(AgentType.CUSTOM, "anthropic:claude-sonnet-4-0")

    async def execute(
        self, input_data: str, deps: AgentDependencies
    ) -> AgentResult:
        result = await self._agent.run(input_data, deps=deps)
        return AgentResult(success=True, data=result.data)

Methods:

Name Description
execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def __init__(
    self,
    agent_type: AgentType,
    model_name: str = "anthropic:claude-sonnet-4-0",
    dependencies: AgentDependencies | None = None,
    system_prompt: str | None = None,
    instructions: str | None = None,
):
    self.agent_type = agent_type
    self.model_name = model_name
    self.dependencies = dependencies or AgentDependencies()
    self.status = AgentStatus.IDLE
    self.history = ExecutionHistory()
    self._agent: Agent | None = None

    # Initialize Pydantic AI agent
    self._initialize_agent(system_prompt, instructions)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

BioinformaticsAgent

BioinformaticsAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

Agent for bioinformatics data fusion and reasoning.

Methods:

Name Description
execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

fuse_data

Fuse bioinformatics data from multiple sources.

perform_reasoning

Perform reasoning on fused bioinformatics data.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.BIOINFORMATICS, model_name, **kwargs)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

fuse_data async

fuse_data(
    fusion_request: DataFusionRequest,
) -> FusedDataset

Fuse bioinformatics data from multiple sources.

Source code in DeepResearch/agents.py
async def fuse_data(self, fusion_request: DataFusionRequest) -> FusedDataset:
    """Fuse bioinformatics data from multiple sources."""
    result = await self.execute(fusion_request.model_dump())

    if result.success and "fused_dataset" in result.data:
        return FusedDataset(**result.data["fused_dataset"])
    return FusedDataset(
        dataset_id="error",
        name="Error Dataset",
        description="Failed to fuse data",
        source_databases=[],
    )

perform_reasoning async

perform_reasoning(
    task: ReasoningTask, dataset: FusedDataset
) -> dict[str, Any]

Perform reasoning on fused bioinformatics data.

Source code in DeepResearch/agents.py
async def perform_reasoning(
    self, task: ReasoningTask, dataset: FusedDataset
) -> dict[str, Any]:
    """Perform reasoning on fused bioinformatics data."""
    reasoning_params = {"task": task.model_dump(), "dataset": dataset.model_dump()}

    result = await self.execute(reasoning_params)
    return result.data if result.success else {"error": result.error}

DeepAgentFilesystemAgent

DeepAgentFilesystemAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

DeepAgent filesystem agent integrated with DeepResearch.

Methods:

Name Description
execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

manage_files

Manage filesystem operations.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.DEEP_AGENT_FILESYSTEM, model_name, **kwargs)
    self._deep_agent = None
    self._initialize_deep_agent()

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

manage_files async

manage_files(
    operation: str, context: DeepAgentState | None = None
) -> AgentExecutionResult

Manage filesystem operations.

Source code in DeepResearch/agents.py
async def manage_files(
    self, operation: str, context: DeepAgentState | None = None
) -> AgentExecutionResult:
    """Manage filesystem operations."""
    if self._deep_agent:
        return await self._deep_agent.manage_files(operation, context)
    # Fallback to standard agent execution
    result = await self.execute({"operation": operation, "context": context})
    return AgentExecutionResult(
        success=result.success,
        result=result.data,
        error=result.error,
        execution_time=result.execution_time,
        tools_used=["standard_filesystem"],
    )

DeepAgentGeneralAgent

DeepAgentGeneralAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

DeepAgent general-purpose agent integrated with DeepResearch.

Methods:

Name Description
execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

handle_general_task

Handle general-purpose tasks.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.DEEP_AGENT_GENERAL, model_name, **kwargs)
    self._deep_agent = None
    self._initialize_deep_agent()

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

handle_general_task async

handle_general_task(
    task_description: str,
    context: DeepAgentState | None = None,
) -> AgentExecutionResult

Handle general-purpose tasks.

Source code in DeepResearch/agents.py
async def handle_general_task(
    self, task_description: str, context: DeepAgentState | None = None
) -> AgentExecutionResult:
    """Handle general-purpose tasks."""
    if self._deep_agent:
        return await self._deep_agent.execute(task_description, context)
    # Fallback to standard agent execution
    result = await self.execute({"task": task_description, "context": context})
    return AgentExecutionResult(
        success=result.success,
        result=result.data,
        error=result.error,
        execution_time=result.execution_time,
        tools_used=["standard_general"],
    )

DeepAgentOrchestrationAgent

DeepAgentOrchestrationAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

DeepAgent orchestration agent integrated with DeepResearch.

Methods:

Name Description
execute

Execute the agent with input data.

execute_parallel_tasks

Execute multiple tasks in parallel.

execute_sync

Synchronous execution wrapper.

orchestrate_tasks

Orchestrate multiple tasks across agents.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.DEEP_AGENT_ORCHESTRATION, model_name, **kwargs)
    self._deep_agent = None
    self._orchestrator = None
    self._initialize_deep_agent()

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_parallel_tasks async

execute_parallel_tasks(
    tasks: list[dict[str, Any]],
    context: DeepAgentState | None = None,
) -> list[AgentExecutionResult]

Execute multiple tasks in parallel.

Source code in DeepResearch/agents.py
async def execute_parallel_tasks(
    self, tasks: list[dict[str, Any]], context: DeepAgentState | None = None
) -> list[AgentExecutionResult]:
    """Execute multiple tasks in parallel."""
    if self._orchestrator:
        return await self._orchestrator.execute_parallel(tasks, context)
    # Fallback to sequential execution
    results = []
    for task in tasks:
        result = await self.orchestrate_tasks(task.get("description", ""), context)
        results.append(result)
    return results

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

orchestrate_tasks async

orchestrate_tasks(
    task_description: str,
    context: DeepAgentState | None = None,
) -> AgentExecutionResult

Orchestrate multiple tasks across agents.

Source code in DeepResearch/agents.py
async def orchestrate_tasks(
    self, task_description: str, context: DeepAgentState | None = None
) -> AgentExecutionResult:
    """Orchestrate multiple tasks across agents."""
    if self._deep_agent:
        return await self._deep_agent.orchestrate_tasks(task_description, context)
    # Fallback to standard agent execution
    result = await self.execute({"task": task_description, "context": context})
    return AgentExecutionResult(
        success=result.success,
        result=result.data,
        error=result.error,
        execution_time=result.execution_time,
        tools_used=["standard_orchestration"],
    )

DeepAgentPlanningAgent

DeepAgentPlanningAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

DeepAgent planning agent integrated with DeepResearch.

Methods:

Name Description
create_plan

Create a detailed execution plan.

execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.DEEP_AGENT_PLANNING, model_name, **kwargs)
    self._deep_agent = None
    self._initialize_deep_agent()

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

create_plan async

create_plan(
    task_description: str,
    context: DeepAgentState | None = None,
) -> AgentExecutionResult

Create a detailed execution plan.

Source code in DeepResearch/agents.py
async def create_plan(
    self, task_description: str, context: DeepAgentState | None = None
) -> AgentExecutionResult:
    """Create a detailed execution plan."""
    if self._deep_agent:
        return await self._deep_agent.create_plan(task_description, context)
    # Fallback to standard agent execution
    result = await self.execute({"task": task_description, "context": context})
    return AgentExecutionResult(
        success=result.success,
        result=result.data,
        error=result.error,
        execution_time=result.execution_time,
        tools_used=["standard_planning"],
    )

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

DeepAgentResearchAgent

DeepAgentResearchAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

DeepAgent research agent integrated with DeepResearch.

Methods:

Name Description
conduct_research

Conduct comprehensive research.

execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.DEEP_AGENT_RESEARCH, model_name, **kwargs)
    self._deep_agent = None
    self._initialize_deep_agent()

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

conduct_research async

conduct_research(
    research_query: str,
    context: DeepAgentState | None = None,
) -> AgentExecutionResult

Conduct comprehensive research.

Source code in DeepResearch/agents.py
async def conduct_research(
    self, research_query: str, context: DeepAgentState | None = None
) -> AgentExecutionResult:
    """Conduct comprehensive research."""
    if self._deep_agent:
        return await self._deep_agent.conduct_research(research_query, context)
    # Fallback to standard agent execution
    result = await self.execute({"query": research_query, "context": context})
    return AgentExecutionResult(
        success=result.success,
        result=result.data,
        error=result.error,
        execution_time=result.execution_time,
        tools_used=["standard_research"],
    )

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

DeepSearchAgent

DeepSearchAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

Agent for deep search operations with iterative refinement.

Methods:

Name Description
deep_search

Perform deep search with iterative refinement.

execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.DEEPSEARCH, model_name, **kwargs)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

deep_search(
    question: str, max_steps: int = 20
) -> dict[str, Any]

Perform deep search with iterative refinement.

Source code in DeepResearch/agents.py
async def deep_search(self, question: str, max_steps: int = 20) -> dict[str, Any]:
    """Perform deep search with iterative refinement."""
    search_params = {"question": question, "max_steps": max_steps}

    result = await self.execute(search_params)
    return result.data if result.success else {"error": result.error}

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

EvaluatorAgent

EvaluatorAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

Agent for evaluating research results and quality.

Methods:

Name Description
evaluate

Evaluate research results.

execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.EVALUATOR, model_name, **kwargs)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

evaluate async

evaluate(question: str, answer: str) -> dict[str, Any]

Evaluate research results.

Source code in DeepResearch/agents.py
async def evaluate(self, question: str, answer: str) -> dict[str, Any]:
    """Evaluate research results."""
    eval_params = {"question": question, "answer": answer}

    result = await self.execute(eval_params)
    return result.data if result.success else {"error": result.error}

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

ExecutionHistory dataclass

ExecutionHistory(items: list[dict[str, Any]] = list())

History of agent executions.

Methods:

Name Description
record

Record an execution result.

Attributes:

Name Type Description
items list[dict[str, Any]]

Attributes

items class-attribute instance-attribute

items: list[dict[str, Any]] = field(default_factory=list)

Functions

record

record(
    agent_type: AgentType, result: AgentResult, **kwargs
)

Record an execution result.

Source code in DeepResearch/src/datatypes/agents.py
def record(self, agent_type: AgentType, result: AgentResult, **kwargs):
    """Record an execution result."""
    self.items.append(
        {
            "timestamp": time.time(),
            "agent_type": agent_type.value,
            "success": result.success,
            "execution_time": result.execution_time,
            "error": result.error,
            **kwargs,
        }
    )

ExecutorAgent

ExecutorAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    retries: int = 2,
    **kwargs,
)

Bases: BaseAgent

Agent for executing research workflows.

Methods:

Name Description
execute

Execute the agent with input data.

execute_plan

Execute a research plan.

execute_sync

Synchronous execution wrapper.

run_plan

Legacy synchronous run_plan method.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
retries
status
Source code in DeepResearch/agents.py
def __init__(
    self,
    model_name: str = "anthropic:claude-sonnet-4-0",
    retries: int = 2,
    **kwargs,
):
    self.retries = retries
    super().__init__(AgentType.EXECUTOR, model_name, **kwargs)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

retries instance-attribute

retries = retries

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_plan async

execute_plan(
    plan: list[dict[str, Any]], history: ExecutionHistory
) -> dict[str, Any]

Execute a research plan.

Source code in DeepResearch/agents.py
async def execute_plan(
    self, plan: list[dict[str, Any]], history: ExecutionHistory
) -> dict[str, Any]:
    """Execute a research plan."""
    bag: dict[str, Any] = {}

    for step in plan:
        tool_name = step["tool"]
        params = self._materialize_params(step.get("params", {}), bag)

        attempt = 0
        result: ExecutionResult | None = None

        while attempt <= self.retries:
            try:
                runner = registry.make(tool_name)
                result = runner.run(params)
                history.record(
                    agent_type=AgentType.EXECUTOR,
                    result=AgentResult(
                        success=result.success,
                        data=result.data,
                        error=result.error,
                        agent_type=AgentType.EXECUTOR,
                    ),
                    tool=tool_name,
                    params=params,
                )

                if result.success:
                    for k, v in result.data.items():
                        bag[f"{tool_name}.{k}"] = v
                        bag[k] = v  # convenience aliasing
                    break

            except Exception as e:
                result = ExecutionResult(success=False, error=str(e))

            attempt += 1

            # Adaptive parameter adjustment
            if not result.success and attempt <= self.retries:
                params = self._adjust_parameters(params, bag)

        if not result or not result.success:
            break

    return bag

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

run_plan

run_plan(
    plan: list[dict[str, Any]], history: ExecutionHistory
) -> dict[str, Any]

Legacy synchronous run_plan method.

Source code in DeepResearch/agents.py
def run_plan(
    self, plan: list[dict[str, Any]], history: ExecutionHistory
) -> dict[str, Any]:
    """Legacy synchronous run_plan method."""
    return asyncio.run(self.execute_plan(plan, history))

MultiAgentOrchestrator

MultiAgentOrchestrator(config: dict[str, Any])

Orchestrator for coordinating multiple agents in complex workflows.

Methods:

Name Description
execute_workflow

Execute a complete research workflow.

Attributes:

Name Type Description
agents dict[AgentType, BaseAgent]
config
history
Source code in DeepResearch/agents.py
def __init__(self, config: dict[str, Any]):
    self.config = config
    self.agents: dict[AgentType, BaseAgent] = {}
    self.history = ExecutionHistory()
    self._initialize_agents()

Attributes

agents instance-attribute

agents: dict[AgentType, BaseAgent] = {}

config instance-attribute

config = config

history instance-attribute

history = ExecutionHistory()

Functions

execute_workflow async

execute_workflow(
    question: str, workflow_type: str = "research"
) -> dict[str, Any]

Execute a complete research workflow.

Source code in DeepResearch/agents.py
async def execute_workflow(
    self, question: str, workflow_type: str = "research"
) -> dict[str, Any]:
    """Execute a complete research workflow."""
    start_time = time.time()

    try:
        # Step 1: Parse the question
        parser = self.agents[AgentType.PARSER]
        parsed = await parser.parse_question(question)

        # Step 2: Create execution plan
        planner = self.agents[AgentType.PLANNER]
        plan = await planner.create_plan(parsed)

        # Step 3: Execute based on workflow type
        if workflow_type == "bioinformatics":
            result = await self._execute_bioinformatics_workflow(
                question, parsed, plan
            )
        elif workflow_type == "deepsearch":
            result = await self._execute_deepsearch_workflow(question, parsed, plan)
        elif workflow_type == "rag":
            result = await self._execute_rag_workflow(question, parsed, plan)
        elif workflow_type == "deep_agent":
            result = await self._execute_deep_agent_workflow(question, parsed, plan)
        else:
            result = await self._execute_standard_workflow(question, parsed, plan)

        # Step 4: Evaluate results
        evaluator = self.agents[AgentType.EVALUATOR]
        evaluation = await evaluator.evaluate(question, result.get("answer", ""))

        execution_time = time.time() - start_time

    except Exception as e:
        execution_time = time.time() - start_time
        return {
            "question": question,
            "workflow_type": workflow_type,
            "error": str(e),
            "execution_time": execution_time,
            "success": False,
        }
    else:
        return {
            "question": question,
            "workflow_type": workflow_type,
            "parsed_question": parsed,
            "execution_plan": plan,
            "result": result,
            "evaluation": evaluation,
            "execution_time": execution_time,
            "success": True,
        }

ParserAgent

ParserAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

Agent for parsing and understanding research questions.

Methods:

Name Description
execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

parse

Legacy synchronous parse method.

parse_question

Parse a research question.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.PARSER, model_name, **kwargs)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

parse

parse(question: str) -> dict[str, Any]

Legacy synchronous parse method.

Source code in DeepResearch/agents.py
def parse(self, question: str) -> dict[str, Any]:
    """Legacy synchronous parse method."""
    result = self.execute_sync(question)
    return (
        result.data if result.success else {"intent": "research", "query": question}
    )

parse_question async

parse_question(question: str) -> dict[str, Any]

Parse a research question.

Source code in DeepResearch/agents.py
async def parse_question(self, question: str) -> dict[str, Any]:
    """Parse a research question."""
    result = await self.execute(question)
    if result.success:
        return result.data
    return {"intent": "research", "query": question, "error": result.error}

PlannerAgent

PlannerAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

Agent for planning research workflows.

Methods:

Name Description
create_plan

Create an execution plan from parsed question.

execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

plan

Legacy synchronous plan method.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.PLANNER, model_name, **kwargs)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

create_plan async

create_plan(
    parsed_question: dict[str, Any],
) -> list[dict[str, Any]]

Create an execution plan from parsed question.

Source code in DeepResearch/agents.py
async def create_plan(
    self, parsed_question: dict[str, Any]
) -> list[dict[str, Any]]:
    """Create an execution plan from parsed question."""
    result = await self.execute(parsed_question)
    if result.success and "steps" in result.data:
        return result.data["steps"]
    # Fallback to default plan
    return self._get_default_plan(parsed_question.get("query", ""))

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

plan

plan(parsed: dict[str, Any]) -> list[dict[str, Any]]

Legacy synchronous plan method.

Source code in DeepResearch/agents.py
def plan(self, parsed: dict[str, Any]) -> list[dict[str, Any]]:
    """Legacy synchronous plan method."""
    result = self.execute_sync(parsed)
    if result.success and "steps" in result.data:
        return result.data["steps"]
    return self._get_default_plan(parsed.get("query", ""))

RAGAgent

RAGAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

Agent for RAG (Retrieval-Augmented Generation) operations.

Methods:

Name Description
execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

query

Perform RAG query.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.RAG, model_name, **kwargs)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

query async

query(rag_query: RAGQuery) -> RAGResponse

Perform RAG query.

Source code in DeepResearch/agents.py
async def query(self, rag_query: RAGQuery) -> RAGResponse:
    """Perform RAG query."""
    result = await self.execute(rag_query.model_dump())

    if result.success:
        return RAGResponse(**result.data)
    return RAGResponse(
        query=rag_query.text,
        retrieved_documents=[],
        generated_answer="",
        context="",
        processing_time=0.0,
        metadata={"error": result.error},
    )

SearchAgent

SearchAgent(
    model_name: str = "anthropic:claude-sonnet-4-0",
    **kwargs,
)

Bases: BaseAgent

Agent for web search operations.

Methods:

Name Description
execute

Execute the agent with input data.

execute_sync

Synchronous execution wrapper.

search

Perform web search.

Attributes:

Name Type Description
agent_type
dependencies
history
model_name
status
Source code in DeepResearch/agents.py
def __init__(self, model_name: str = "anthropic:claude-sonnet-4-0", **kwargs):
    super().__init__(AgentType.SEARCH, model_name, **kwargs)

Attributes

agent_type instance-attribute

agent_type = agent_type

dependencies instance-attribute

dependencies = dependencies or AgentDependencies()

history instance-attribute

history = ExecutionHistory()

model_name instance-attribute

model_name = model_name

status instance-attribute

status = IDLE

Functions

execute async

execute(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Execute the agent with input data.

This is the main entry point for executing an agent. It handles initialization, execution, and result processing while tracking execution metrics and errors.

Parameters:

Name Type Description Default
input_data Any

The input data to process. Can be a string, dict, or any structured data appropriate for the agent type.

required
deps AgentDependencies | None

Optional agent dependencies. If not provided, uses the agent's default dependencies.

None

Returns:

Name Type Description
AgentResult AgentResult

The execution result containing success status, processed data, execution metrics, and any errors.

Raises:

Type Description
RuntimeError

If the agent is not properly initialized.

Examples:

Basic execution:

agent = SearchAgent()
deps = AgentDependencies.from_config(config)
result = await agent.execute("machine learning", deps)

if result.success:
    print(f"Results: {result.data}")
else:
    print(f"Error: {result.error}")

With custom dependencies:

custom_deps = AgentDependencies(
    model_name="openai:gpt-4",
    api_keys={"openai": "your-key"},
    config={"temperature": 0.8}
)
result = await agent.execute("research query", custom_deps)
Source code in DeepResearch/agents.py
async def execute(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """
    Execute the agent with input data.

    This is the main entry point for executing an agent. It handles
    initialization, execution, and result processing while tracking
    execution metrics and errors.

    Args:
        input_data: The input data to process. Can be a string, dict,
                   or any structured data appropriate for the agent type.
        deps: Optional agent dependencies. If not provided, uses
             the agent's default dependencies.

    Returns:
        AgentResult: The execution result containing success status,
                   processed data, execution metrics, and any errors.

    Raises:
        RuntimeError: If the agent is not properly initialized.

    Examples:
        Basic execution:

        ```python
        agent = SearchAgent()
        deps = AgentDependencies.from_config(config)
        result = await agent.execute("machine learning", deps)

        if result.success:
            print(f"Results: {result.data}")
        else:
            print(f"Error: {result.error}")
        ```

        With custom dependencies:

        ```python
        custom_deps = AgentDependencies(
            model_name="openai:gpt-4",
            api_keys={"openai": "your-key"},
            config={"temperature": 0.8}
        )
        result = await agent.execute("research query", custom_deps)
        ```
    """
    start_time = time.time()
    self.status = AgentStatus.RUNNING

    try:
        if not self._agent:
            return AgentResult(
                success=False,
                error="Agent not properly initialized",
                agent_type=self.agent_type,
            )

        # Use provided deps or default
        execution_deps = deps or self.dependencies

        # Execute with Pydantic AI
        result = await self._agent.run(input_data, deps=execution_deps)

        execution_time = time.time() - start_time

        agent_result = AgentResult(
            success=True,
            data=self._process_result(result),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

    except Exception as e:
        execution_time = time.time() - start_time
        agent_result = AgentResult(
            success=False,
            error=str(e),
            execution_time=execution_time,
            agent_type=self.agent_type,
        )

        self.status = AgentStatus.FAILED
        self.history.record(self.agent_type, agent_result)
        return agent_result
    else:
        self.status = AgentStatus.COMPLETED
        self.history.record(self.agent_type, agent_result)
        return agent_result

execute_sync

execute_sync(
    input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult

Synchronous execution wrapper.

Source code in DeepResearch/agents.py
def execute_sync(
    self, input_data: Any, deps: AgentDependencies | None = None
) -> AgentResult:
    """Synchronous execution wrapper."""
    return asyncio.run(self.execute(input_data, deps))

search async

search(
    query: str,
    search_type: str = "search",
    num_results: int = 10,
) -> dict[str, Any]

Perform web search.

Source code in DeepResearch/agents.py
async def search(
    self, query: str, search_type: str = "search", num_results: int = 10
) -> dict[str, Any]:
    """Perform web search."""
    search_params = {
        "query": query,
        "search_type": search_type,
        "num_results": num_results,
    }

    result = await self.execute(search_params)
    return result.data if result.success else {"error": result.error}

Functions

create_agent

create_agent(agent_type: AgentType, **kwargs) -> BaseAgent

Create an agent of the specified type.

Source code in DeepResearch/agents.py
def create_agent(agent_type: AgentType, **kwargs) -> BaseAgent:
    """Create an agent of the specified type."""
    agent_classes = {
        AgentType.PARSER: ParserAgent,
        AgentType.PLANNER: PlannerAgent,
        AgentType.EXECUTOR: ExecutorAgent,
        AgentType.SEARCH: SearchAgent,
        AgentType.RAG: RAGAgent,
        AgentType.BIOINFORMATICS: BioinformaticsAgent,
        AgentType.DEEPSEARCH: DeepSearchAgent,
        AgentType.EVALUATOR: EvaluatorAgent,
        # DeepAgent types
        AgentType.DEEP_AGENT_PLANNING: DeepAgentPlanningAgent,
        AgentType.DEEP_AGENT_FILESYSTEM: DeepAgentFilesystemAgent,
        AgentType.DEEP_AGENT_RESEARCH: DeepAgentResearchAgent,
        AgentType.DEEP_AGENT_ORCHESTRATION: DeepAgentOrchestrationAgent,
        AgentType.DEEP_AGENT_GENERAL: DeepAgentGeneralAgent,
    }

    agent_class = agent_classes.get(agent_type)
    if not agent_class:
        msg = f"Unknown agent type: {agent_type}"
        raise ValueError(msg)

    return agent_class(**kwargs)

create_orchestrator

create_orchestrator(
    config: dict[str, Any],
) -> MultiAgentOrchestrator

Create a multi-agent orchestrator.

Source code in DeepResearch/agents.py
def create_orchestrator(config: dict[str, Any]) -> MultiAgentOrchestrator:
    """Create a multi-agent orchestrator."""
    return MultiAgentOrchestrator(config)

Main Application

Classes:

Name Description
Analyze
BioinformaticsFuse
BioinformaticsParse
DSAnalyze
DSExecute
DSPlan
DSSynthesize
EnhancedREACTWorkflow
EvaluateChallenge
Plan

Planning node for research workflow.

PrepareChallenge
PrimaryREACTWorkflow
PrimeEvaluate
PrimeExecute
PrimeParse
PrimePlan
RAGExecute
RAGParse
ResearchState

State object for the research workflow.

RunChallenge
Search
Synthesize

Functions:

Name Description
main
run_graph

Attributes:

Name Type Description
research_graph

Attributes

research_graph module-attribute

research_graph = Graph(
    nodes=(
        Plan,
        Search,
        Analyze,
        Synthesize,
        PrimaryREACTWorkflow,
        EnhancedREACTWorkflow,
    ),
    state_type=ResearchState,
)

Classes

Analyze dataclass

Analyze()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> Synthesize
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> Synthesize:
    history = ctx.state.execution_results.get("history")
    n = len(history.items) if history else 0
    ctx.state.notes.append(f"Analysis: executed {n} steps")
    return Synthesize()

BioinformaticsFuse dataclass

BioinformaticsFuse()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> Annotated[End[str], Edge(label="done")]
Source code in DeepResearch/app.py
async def run(
    self, ctx: GraphRunContext[ResearchState]
) -> Annotated[End[str], Edge(label="done")]:
    # The bioinformatics workflow is already complete, just return the result
    if ctx.state.answers:
        return End(ctx.state.answers[-1])
    return End("Bioinformatics analysis completed.")

BioinformaticsParse dataclass

BioinformaticsParse()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> BioinformaticsFuse
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> BioinformaticsFuse:
    # Import here to avoid circular imports
    from .src.statemachines.bioinformatics_workflow import (
        run_bioinformatics_workflow,
    )

    question = ctx.state.question
    cfg = ctx.state.config

    ctx.state.notes.append("Starting bioinformatics workflow")

    # Run the complete bioinformatics workflow
    try:
        cfg_dict = cfg.to_container() if hasattr(cfg, "to_container") else {}
        final_answer = run_bioinformatics_workflow(question, cfg_dict)
        ctx.state.answers.append(final_answer)
        ctx.state.notes.append("Bioinformatics workflow completed successfully")
    except Exception as e:
        error_msg = f"Bioinformatics workflow failed: {e!s}"
        ctx.state.notes.append(error_msg)
        ctx.state.answers.append(f"Error: {error_msg}")

    return BioinformaticsFuse()

DSAnalyze dataclass

DSAnalyze()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> DSSynthesize
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> DSSynthesize:
    history = ctx.state.execution_results.get("history")
    n = len(history.items) if history else 0
    ctx.state.notes.append(f"DeepSearch analysis: {n} steps")
    return DSSynthesize()

DSExecute dataclass

DSExecute()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> DSAnalyze
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> DSAnalyze:
    history = ExecutionHistory()
    plan = getattr(ctx.state, "full_plan", []) or []
    retries = int(getattr(ctx.state.config, "retries", 2))
    exec_agent = ExecutorAgent(retries=retries)
    bag = exec_agent.run_plan(plan, history)
    ctx.state.execution_results["history"] = history
    ctx.state.execution_results["bag"] = bag
    ctx.state.notes.append("DeepSearch executed plan")
    return DSAnalyze()

DSPlan dataclass

DSPlan()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> DSExecute
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> DSExecute:
    # Orchestrate plan selection based on enabled subflows
    flows_cfg = getattr(ctx.state.config, "flows", {})
    orchestrator = Orchestrator()
    active = orchestrator.build_plan(ctx.state.question, flows_cfg)
    ctx.state.active_subgraphs["deepsearch"] = active
    # Default deepsearch-style plan
    parser = ParserAgent()
    parsed = parser.parse(ctx.state.question)
    planner = PlannerAgent()
    plan = planner.plan(parsed)
    # Prefer Pydantic web_search + summarize + finalize
    ctx.state.full_plan = plan
    ctx.state.plan = [f"{s['tool']}" for s in plan]
    ctx.state.notes.append(f"DeepSearch planned: {ctx.state.plan}")
    return DSExecute()

DSSynthesize dataclass

DSSynthesize()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> Annotated[End[str], Edge(label="done")]
Source code in DeepResearch/app.py
async def run(
    self, ctx: GraphRunContext[ResearchState]
) -> Annotated[End[str], Edge(label="done")]:
    bag = ctx.state.execution_results.get("bag") or {}
    final = (
        bag.get("final")
        or bag.get("finalize.final")
        or bag.get("summarize.summary")
    )
    if not final:
        final = "No result."
    answer = f"Q: {ctx.state.question}\n{final}"
    ctx.state.answers.append(answer)
    return End(answer)

EnhancedREACTWorkflow dataclass

EnhancedREACTWorkflow()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Execute the enhanced REACT workflow with nested loops and subgraphs.

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> Annotated[End[str], Edge(label="done")]

Execute the enhanced REACT workflow with nested loops and subgraphs.

Source code in DeepResearch/app.py
async def run(
    self, ctx: GraphRunContext[ResearchState]
) -> Annotated[End[str], Edge(label="done")]:
    """Execute the enhanced REACT workflow with nested loops and subgraphs."""
    cfg = ctx.state.config
    app_mode = ctx.state.current_mode

    try:
        # Create app configuration from Hydra config
        app_config = self._create_app_configuration(cfg, app_mode)
        ctx.state.app_configuration = app_config

        # Create agent orchestrator
        agent_orchestrator = AgentOrchestrator(app_config.primary_orchestrator)
        ctx.state.agent_orchestrator = agent_orchestrator

        # Execute orchestration based on mode
        if app_mode == AppMode.SINGLE_REACT:
            result = await self._execute_single_react(ctx, agent_orchestrator)
        elif app_mode == AppMode.MULTI_LEVEL_REACT:
            result = await self._execute_multi_level_react(ctx, agent_orchestrator)
        elif app_mode == AppMode.NESTED_ORCHESTRATION:
            result = await self._execute_nested_orchestration(
                ctx, agent_orchestrator
            )
        elif app_mode == AppMode.LOSS_DRIVEN:
            result = await self._execute_loss_driven(ctx, agent_orchestrator)
        else:
            result = await self._execute_custom_mode(ctx, agent_orchestrator)

        # Process results
        if result.success:
            final_answer = self._generate_enhanced_output(
                ctx.state.question, result, app_config, agent_orchestrator
            )

            ctx.state.answers.append(final_answer)
            ctx.state.notes.append(
                f"Enhanced REACT workflow ({app_mode.value if app_mode else 'unknown'}) completed successfully"
            )

            return End(final_answer)
        error_msg = f"Enhanced REACT workflow failed: {result.break_reason or 'Unknown error'}"
        ctx.state.notes.append(error_msg)
        return End(f"Error: {error_msg}")

    except Exception as e:
        error_msg = f"Enhanced REACT workflow orchestration failed: {e!s}"
        ctx.state.notes.append(error_msg)
        return End(f"Error: {error_msg}")

EvaluateChallenge dataclass

EvaluateChallenge()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> Synthesize
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> Synthesize:
    ctx.state.notes.append(
        "Evaluate: participant cross-assessment, expert review, pilot AI (placeholder)"
    )
    return Synthesize()

Plan dataclass

Plan()

Bases: BaseNode[ResearchState]

Planning node for research workflow.

This node analyzes the research question and determines the appropriate workflow path based on configuration flags and question characteristics. Routes to different execution paths including search, REACT workflows, or challenge mode.

Methods:

Name Description
run

Functions

run async

Source code in DeepResearch/app.py
async def run(
    self, ctx: GraphRunContext[ResearchState]
) -> (
    Search
    | PrimaryREACTWorkflow
    | EnhancedREACTWorkflow
    | PrepareChallenge
    | PrimeParse
    | BioinformaticsParse
    | RAGParse
    | DSPlan
):
    cfg = ctx.state.config

    # Check for enhanced REACT architecture modes
    app_mode_cfg = getattr(cfg, "app_mode", None)
    if app_mode_cfg:
        ctx.state.current_mode = AppMode(app_mode_cfg)
        ctx.state.notes.append(f"Enhanced REACT architecture mode: {app_mode_cfg}")
        return EnhancedREACTWorkflow()

    # Check if primary REACT workflow orchestration is enabled
    orchestration_cfg = getattr(cfg, "workflow_orchestration", None)
    if getattr(orchestration_cfg or {}, "enabled", False):
        ctx.state.notes.append("Primary REACT workflow orchestration enabled")
        return PrimaryREACTWorkflow()

    # Switch to challenge flow if enabled
    if (
        hasattr(cfg, "challenge")
        and cfg.challenge
        and getattr(cfg.challenge, "enabled", False)
    ):
        ctx.state.notes.append("Challenge mode enabled")
        return PrepareChallenge()

    # Route to PRIME flow if enabled
    prime_cfg = getattr(getattr(cfg, "flows", {}), "prime", None)
    if getattr(prime_cfg or {}, "enabled", False):
        ctx.state.notes.append("PRIME flow enabled")
        return PrimeParse()

    # Route to Bioinformatics flow if enabled
    bioinformatics_cfg = getattr(getattr(cfg, "flows", {}), "bioinformatics", None)
    if getattr(bioinformatics_cfg or {}, "enabled", False):
        ctx.state.notes.append("Bioinformatics flow enabled")
        return BioinformaticsParse()

    # Route to RAG flow if enabled
    rag_cfg = getattr(getattr(cfg, "flows", {}), "rag", None)
    if getattr(rag_cfg or {}, "enabled", False):
        ctx.state.notes.append("RAG flow enabled")
        return RAGParse()

    # Route to DeepSearch flow if enabled
    deepsearch_cfg = getattr(getattr(cfg, "flows", {}), "deepsearch", None)
    node_example_cfg = getattr(getattr(cfg, "flows", {}), "node_example", None)
    jina_ai_cfg = getattr(getattr(cfg, "flows", {}), "jina_ai", None)
    if any(
        [
            getattr(deepsearch_cfg or {}, "enabled", False),
            getattr(node_example_cfg or {}, "enabled", False),
            getattr(jina_ai_cfg or {}, "enabled", False),
        ]
    ):
        ctx.state.notes.append("DeepSearch flow enabled")
        return DSPlan()

    # Default flow
    parser = ParserAgent()
    planner = PlannerAgent()
    parsed = parser.parse(ctx.state.question)
    plan = planner.plan(parsed)
    ctx.state.full_plan = plan
    ctx.state.plan = [f"{s['tool']}" for s in plan]
    ctx.state.notes.append(f"Planned steps: {ctx.state.plan}")
    return Search()

PrepareChallenge dataclass

PrepareChallenge()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> RunChallenge
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> RunChallenge:
    ch = getattr(ctx.state.config, "challenge", None) if ctx.state.config else None
    if ch:
        ctx.state.notes.append(f"Prepare: {ch.name} in {ch.domain}")
    else:
        ctx.state.notes.append("Prepare: Challenge configuration not found")
    return RunChallenge()

PrimaryREACTWorkflow dataclass

PrimaryREACTWorkflow()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Execute the primary REACT workflow with orchestration.

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> Annotated[End[str], Edge(label="done")]

Execute the primary REACT workflow with orchestration.

Source code in DeepResearch/app.py
async def run(
    self, ctx: GraphRunContext[ResearchState]
) -> Annotated[End[str], Edge(label="done")]:
    """Execute the primary REACT workflow with orchestration."""
    cfg = ctx.state.config
    orchestration_cfg = getattr(cfg, "workflow_orchestration", {})

    try:
        # Initialize orchestration configuration
        orchestration_config = self._create_orchestration_config(orchestration_cfg)
        ctx.state.orchestration_config = orchestration_config

        # Create primary workflow orchestrator
        orchestrator = PrimaryWorkflowOrchestrator(orchestration_config)
        ctx.state.orchestration_state = orchestrator.state

        # Execute primary workflow
        if cfg is None:
            from omegaconf import DictConfig

            cfg = DictConfig({})
        result = await orchestrator.execute_primary_workflow(
            ctx.state.question, cfg
        )

        # Process results
        if result["success"]:
            # Extract spawned workflows
            ctx.state.spawned_workflows = list(
                orchestrator.state.active_executions
            ) + [
                exec.execution_id
                for exec in orchestrator.state.completed_executions
            ]

            # Extract multi-agent results
            ctx.state.multi_agent_results = result.get("result", {})

            # Generate comprehensive output
            final_answer = self._generate_comprehensive_output(
                ctx.state.question, result, orchestrator.state
            )

            ctx.state.answers.append(final_answer)
            ctx.state.notes.append(
                "Primary REACT workflow orchestration completed successfully"
            )

            return End(final_answer)
        error_msg = (
            f"Primary REACT workflow failed: {result.get('error', 'Unknown error')}"
        )
        ctx.state.notes.append(error_msg)
        return End(f"Error: {error_msg}")

    except Exception as e:
        error_msg = f"Primary REACT workflow orchestration failed: {e!s}"
        ctx.state.notes.append(error_msg)
        return End(f"Error: {error_msg}")

PrimeEvaluate dataclass

PrimeEvaluate()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> Annotated[End[str], Edge(label="done")]
Source code in DeepResearch/app.py
async def run(
    self, ctx: GraphRunContext[ResearchState]
) -> Annotated[End[str], Edge(label="done")]:
    # Evaluate results and generate final answer
    results = ctx.state.execution_results
    problem = ctx.state.structured_problem

    if results["success"]:
        # Extract key results from data bag
        data_bag = results.get("data_bag", {})
        summary = self._extract_summary(data_bag, problem)
        answer = f"PRIME Analysis Complete\n\nQ: {ctx.state.question}\n\n{summary}"
    else:
        # Handle failure case
        history = results.get("history", PrimeExecutionHistory())
        failed_steps = [item.step_name for item in history.get_failed_steps()]
        answer = f"PRIME Analysis Incomplete\n\nQ: {ctx.state.question}\n\nFailed steps: {failed_steps}\n\nPlease review the execution history for details."

    ctx.state.answers.append(answer)
    return End(answer)

PrimeExecute dataclass

PrimeExecute()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> PrimeEvaluate
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> PrimeEvaluate:
    # Execute workflow using PRIME Tool Executor
    cfg = ctx.state.config
    prime_cfg = getattr(getattr(cfg, "flows", {}), "prime", {})

    # Initialize tool registry with PRIME tools
    registry = ToolRegistry()
    registry.enable_mock_mode()  # Use mock tools for development

    # Create execution context
    history = PrimeExecutionHistory()
    if ctx.state.workflow_dag is None:
        from .src.datatypes.execution import WorkflowDAG

        ctx.state.workflow_dag = WorkflowDAG(
            steps=[], dependencies={}, execution_order=[]
        )
    context = ExecutionContext(
        workflow=ctx.state.workflow_dag,
        history=history,
        manual_confirmation=getattr(prime_cfg, "manual_confirmation", False),
        adaptive_replanning=getattr(prime_cfg, "adaptive_replanning", True),
    )

    # Execute workflow
    executor = ToolExecutor(registry)
    results = executor.execute_workflow(context)

    ctx.state.execution_results = results
    ctx.state.notes.append(f"PRIME executed: {results['success']} success")
    return PrimeEvaluate()

PrimeParse dataclass

PrimeParse()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> PrimePlan
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> PrimePlan:
    # Parse the query using PRIME Query Parser
    parser = QueryParser()
    structured_problem = parser.parse(ctx.state.question)
    ctx.state.structured_problem = structured_problem
    ctx.state.notes.append(
        f"PRIME parsed: {structured_problem.intent.value} in {structured_problem.domain}"
    )
    return PrimePlan()

PrimePlan dataclass

PrimePlan()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> PrimeExecute
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> PrimeExecute:
    # Generate workflow using PRIME Plan Generator
    planner = PlanGenerator()
    if ctx.state.structured_problem is None:
        # Create a simple structured problem from the question
        from .src.agents.prime_parser import ScientificIntent, StructuredProblem

        ctx.state.structured_problem = StructuredProblem(
            intent=ScientificIntent.CLASSIFICATION,
            input_data={"description": ctx.state.question},
            output_requirements={"answer": "comprehensive_response"},
            constraints=[],
            success_criteria=["complete_answer"],
            domain="general",
            complexity="simple",
        )
    workflow_dag = planner.plan(ctx.state.structured_problem)
    ctx.state.workflow_dag = workflow_dag
    ctx.state.notes.append(f"PRIME planned: {len(workflow_dag.steps)} steps")
    return PrimeExecute()

RAGExecute dataclass

RAGExecute()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> Annotated[End[str], Edge(label="done")]
Source code in DeepResearch/app.py
async def run(
    self, ctx: GraphRunContext[ResearchState]
) -> Annotated[End[str], Edge(label="done")]:
    # The RAG workflow is already complete, just return the result
    if ctx.state.answers:
        return End(ctx.state.answers[-1])
    return End("RAG analysis completed.")

RAGParse dataclass

RAGParse()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> RAGExecute
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> RAGExecute:
    # Import here to avoid circular imports
    from .src.statemachines.rag_workflow import run_rag_workflow

    question = ctx.state.question
    cfg = ctx.state.config

    ctx.state.notes.append("Starting RAG workflow")

    # Run the complete RAG workflow
    try:
        cfg_non_null = cfg or DictConfig({})
        final_answer = run_rag_workflow(question, cfg_non_null)
        ctx.state.answers.append(final_answer)
        ctx.state.notes.append("RAG workflow completed successfully")
    except Exception as e:
        error_msg = f"RAG workflow failed: {e!s}"
        ctx.state.notes.append(error_msg)
        ctx.state.answers.append(f"Error: {error_msg}")

    return RAGExecute()

ResearchState dataclass

ResearchState(
    question: str,
    plan: list[str] | None = list(),
    full_plan: list[dict[str, Any]] | None = list(),
    notes: list[str] = list(),
    answers: list[str] = list(),
    structured_problem: StructuredProblem | None = None,
    workflow_dag: WorkflowDAG | None = None,
    execution_results: dict[str, Any] = dict(),
    config: DictConfig | None = None,
    orchestration_config: WorkflowOrchestrationConfig
    | None = None,
    orchestration_state: OrchestrationState | None = None,
    spawned_workflows: list[str] = list(),
    multi_agent_results: dict[str, Any] = dict(),
    hypothesis_datasets: list[HypothesisDataset] = list(),
    testing_environments: list[
        HypothesisTestingEnvironment
    ] = list(),
    reasoning_results: list[ReasoningResult] = list(),
    judge_evaluations: dict[str, Any] = dict(),
    app_configuration: AppConfiguration | None = None,
    agent_orchestrator: AgentOrchestrator | None = None,
    nested_loops: dict[str, Any] = dict(),
    active_subgraphs: dict[str, Any] = dict(),
    break_conditions_met: list[str] = list(),
    loss_function_values: dict[str, float] = dict(),
    current_mode: AppMode | None = None,
)

State object for the research workflow.

This dataclass maintains the state of a research workflow execution, containing the original question, planning results, intermediate notes, and final answers.

Attributes:

Name Type Description
question str

The original research question being answered.

plan list[str] | None

High-level plan steps (optional).

full_plan list[dict[str, Any]] | None

Detailed execution plan with parameters.

notes list[str]

Intermediate notes and observations.

answers list[str]

Final answers and results.

structured_problem StructuredProblem | None

PRIME-specific structured problem representation.

workflow_dag WorkflowDAG | None

PRIME workflow DAG for execution.

execution_results dict[str, Any]

Results from tool execution.

config DictConfig | None

Global configuration object.

Attributes

active_subgraphs class-attribute instance-attribute

active_subgraphs: dict[str, Any] = field(
    default_factory=dict
)

agent_orchestrator class-attribute instance-attribute

agent_orchestrator: AgentOrchestrator | None = None

answers class-attribute instance-attribute

answers: list[str] = field(default_factory=list)

app_configuration class-attribute instance-attribute

app_configuration: AppConfiguration | None = None

break_conditions_met class-attribute instance-attribute

break_conditions_met: list[str] = field(
    default_factory=list
)

config class-attribute instance-attribute

config: DictConfig | None = None

current_mode class-attribute instance-attribute

current_mode: AppMode | None = None

execution_results class-attribute instance-attribute

execution_results: dict[str, Any] = field(
    default_factory=dict
)

full_plan class-attribute instance-attribute

full_plan: list[dict[str, Any]] | None = field(
    default_factory=list
)

hypothesis_datasets class-attribute instance-attribute

hypothesis_datasets: list[HypothesisDataset] = field(
    default_factory=list
)

judge_evaluations class-attribute instance-attribute

judge_evaluations: dict[str, Any] = field(
    default_factory=dict
)

loss_function_values class-attribute instance-attribute

loss_function_values: dict[str, float] = field(
    default_factory=dict
)

multi_agent_results class-attribute instance-attribute

multi_agent_results: dict[str, Any] = field(
    default_factory=dict
)

nested_loops class-attribute instance-attribute

nested_loops: dict[str, Any] = field(default_factory=dict)

notes class-attribute instance-attribute

notes: list[str] = field(default_factory=list)

orchestration_config class-attribute instance-attribute

orchestration_config: WorkflowOrchestrationConfig | None = (
    None
)

orchestration_state class-attribute instance-attribute

orchestration_state: OrchestrationState | None = None

plan class-attribute instance-attribute

plan: list[str] | None = field(default_factory=list)

question instance-attribute

question: str

reasoning_results class-attribute instance-attribute

reasoning_results: list[ReasoningResult] = field(
    default_factory=list
)

spawned_workflows class-attribute instance-attribute

spawned_workflows: list[str] = field(default_factory=list)

structured_problem class-attribute instance-attribute

structured_problem: StructuredProblem | None = None

testing_environments class-attribute instance-attribute

testing_environments: list[HypothesisTestingEnvironment] = (
    field(default_factory=list)
)

workflow_dag class-attribute instance-attribute

workflow_dag: WorkflowDAG | None = None

Functions

RunChallenge dataclass

RunChallenge()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> EvaluateChallenge
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> EvaluateChallenge:
    ctx.state.notes.append(
        "Run: release material, collect methods/answers (placeholder)"
    )
    return EvaluateChallenge()

Search dataclass

Search()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(ctx: GraphRunContext[ResearchState]) -> Analyze
Source code in DeepResearch/app.py
async def run(self, ctx: GraphRunContext[ResearchState]) -> Analyze:
    history = ExecutionHistory()
    plan = getattr(ctx.state, "full_plan", []) or []
    retries = int(getattr(ctx.state.config, "retries", 2))
    exec_agent = ExecutorAgent(retries=retries)
    bag = exec_agent.run_plan(plan, history)
    ctx.state.execution_results["history"] = history
    ctx.state.execution_results["bag"] = bag
    ctx.state.notes.append("Executed plan with tool runners")
    return Analyze()

Synthesize dataclass

Synthesize()

Bases: BaseNode[ResearchState]

Methods:

Name Description
run

Functions

run async

run(
    ctx: GraphRunContext[ResearchState],
) -> Annotated[End[str], Edge(label="done")]
Source code in DeepResearch/app.py
async def run(
    self, ctx: GraphRunContext[ResearchState]
) -> Annotated[End[str], Edge(label="done")]:
    bag = ctx.state.execution_results.get("bag") or {}
    final = (
        bag.get("final")
        or bag.get("finalize.final")
        or bag.get("references.answer_with_refs")
        or bag.get("summarize.summary")
    )
    if not final:
        final = "No summary available."
    answer = f"Q: {ctx.state.question}\n{final}"
    ctx.state.answers.append(answer)
    return End(answer)

Functions

main

main(cfg: DictConfig) -> None
Source code in DeepResearch/app.py
@hydra.main(version_base=None, config_path="../configs", config_name="config")
def main(cfg: DictConfig) -> None:
    question = cfg.get("question", "What is deep research?")
    run_graph(question, cfg)

run_graph

run_graph(question: str, cfg: DictConfig) -> str
Source code in DeepResearch/app.py
def run_graph(question: str, cfg: DictConfig) -> str:
    state = ResearchState(question=question, config=cfg)
    # Include all nodes in runtime graph - instantiate them
    nodes = (
        Plan(),
        Search(),
        Analyze(),
        Synthesize(),
        PrepareChallenge(),
        RunChallenge(),
        EvaluateChallenge(),
        DSPlan(),
        DSExecute(),
        DSAnalyze(),
        DSSynthesize(),
        PrimeParse(),
        PrimePlan(),
        PrimeExecute(),
        PrimeEvaluate(),
        BioinformaticsParse(),
        BioinformaticsFuse(),
        RAGParse(),
        RAGExecute(),
        PrimaryREACTWorkflow(),
        EnhancedREACTWorkflow(),
    )
    g = Graph(nodes=nodes)
    # Run the graph starting from Plan node
    loop = asyncio.new_event_loop()
    try:
        asyncio.set_event_loop(loop)
        result = loop.run_until_complete(g.run(Plan(), state=state, deps=None))  # type: ignore
    finally:
        loop.close()
        asyncio.set_event_loop(None)
    return (result.output or "") if hasattr(result, "output") else ""

Models

Custom Pydantic AI model implementations for DeepCritical.

This module provides Pydantic AI model wrappers for: - vLLM (production-grade local LLM inference) - llama.cpp (lightweight local inference) - OpenAI-compatible servers (generic wrapper)

Usage
from pydantic_ai import Agent
from DeepResearch.src.models import VLLMModel, LlamaCppModel

# vLLM
vllm_model = VLLMModel.from_vllm(
    base_url="http://localhost:8000/v1",
    model_name="meta-llama/Llama-3-8B"
)
agent = Agent(vllm_model)

# llama.cpp
llamacpp_model = LlamaCppModel.from_llamacpp(
    base_url="http://localhost:8080/v1",
    model_name="llama-3-8b.gguf"
)
agent = Agent(llamacpp_model)

Modules:

Name Description
openai_compatible_model

Pydantic AI model wrapper for OpenAI-compatible servers.

Classes:

Name Description
OpenAICompatibleModel

Pydantic AI model for OpenAI-compatible servers.

Attributes:

Name Type Description
LlamaCppModel

Alias for OpenAICompatibleModel when using llama.cpp.

VLLMModel

Alias for OpenAICompatibleModel when using vLLM.

Attributes

LlamaCppModel module-attribute

LlamaCppModel = OpenAICompatibleModel

Alias for OpenAICompatibleModel when using llama.cpp.

VLLMModel module-attribute

Alias for OpenAICompatibleModel when using vLLM.

__all__ module-attribute

__all__ = [
    "LlamaCppModel",
    "OpenAICompatibleModel",
    "VLLMModel",
]

Classes

OpenAICompatibleModel

Bases: OpenAIChatModel

Pydantic AI model for OpenAI-compatible servers.

This is a thin wrapper around Pydantic AI's OpenAIChatModel that makes it easy to connect to local or custom OpenAI-compatible servers.

Supports: - vLLM with OpenAI-compatible API - llama.cpp server in OpenAI mode - Text Generation Inference (TGI) - Any custom OpenAI-compatible endpoint

Methods:

Name Description
from_config

Create a model from Hydra configuration.

from_custom

Create a model for any custom OpenAI-compatible server.

from_llamacpp

Create a model for a llama.cpp server.

from_tgi

Create a model for a Text Generation Inference (TGI) server.

from_vllm

Create a model for a vLLM server.

Functions

from_config classmethod

from_config(
    config: DictConfig | dict | LLMModelConfig,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel

Create a model from Hydra configuration.

Parameters:

Name Type Description Default
config DictConfig | dict | LLMModelConfig

Hydra configuration (DictConfig), dict, or LLMModelConfig with model settings.

required
model_name str | None

Override model name from config.

None
base_url str | None

Override base URL from config.

None
api_key str | None

Override API key from config.

None
**kwargs Any

Additional arguments passed to the model.

{}

Returns:

Type Description
OpenAICompatibleModel

Configured OpenAICompatibleModel instance.

Source code in DeepResearch/src/models/openai_compatible_model.py
@classmethod
def from_config(
    cls,
    config: DictConfig | dict | LLMModelConfig,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel:
    """Create a model from Hydra configuration.

    Args:
        config: Hydra configuration (DictConfig), dict, or LLMModelConfig with model settings.
        model_name: Override model name from config.
        base_url: Override base URL from config.
        api_key: Override API key from config.
        **kwargs: Additional arguments passed to the model.

    Returns:
        Configured OpenAICompatibleModel instance.
    """
    # If already a validated LLMModelConfig, use it
    if isinstance(config, LLMModelConfig):
        validated_config = config
    else:
        # Convert DictConfig to dict if needed
        if isinstance(config, DictConfig):
            config_dict = OmegaConf.to_container(config, resolve=True)
            if not isinstance(config_dict, dict):
                msg = f"Expected dict after OmegaConf.to_container, got {type(config_dict)}"
                raise ValueError(msg)
            config = config_dict
        elif not isinstance(config, dict):
            msg = f"Expected dict or DictConfig, got {type(config)}"
            raise ValueError(msg)

        # Build config dict with fallbacks for validation
        provider_value = config.get("provider", "custom")
        model_name_value = (
            model_name
            or config.get("model_name")
            or config.get("model", {}).get("name", "gpt-3.5-turbo")
        )
        base_url_value = (
            base_url or config.get("base_url") or os.getenv("LLM_BASE_URL", "")
        )
        timeout_value = config.get("timeout", 60.0) or 60.0
        max_retries_value = config.get("max_retries", 3) or 3
        retry_delay_value = config.get("retry_delay", 1.0) or 1.0

        config_dict = {
            "provider": (
                LLMProvider(provider_value)
                if provider_value
                else LLMProvider.CUSTOM
            ),
            "model_name": (
                str(model_name_value) if model_name_value else "gpt-3.5-turbo"
            ),
            "base_url": str(base_url_value) if base_url_value else "",
            "api_key": api_key or config.get("api_key") or os.getenv("LLM_API_KEY"),
            "timeout": float(timeout_value),
            "max_retries": int(max_retries_value),
            "retry_delay": float(retry_delay_value),
        }

        # Validate using Pydantic model
        try:
            validated_config = LLMModelConfig(**config_dict)  # type: ignore
        except Exception as e:
            msg = f"Invalid LLM model configuration: {e}"
            raise ValueError(msg)

    # Apply direct parameter overrides
    final_model_name = model_name or validated_config.model_name
    final_base_url = base_url or validated_config.base_url
    final_api_key = api_key or validated_config.api_key or "EMPTY"

    # Extract and validate generation settings from config
    settings = kwargs.pop("settings", {})

    if isinstance(config, (dict, DictConfig)) and not isinstance(
        config, LLMModelConfig
    ):
        if isinstance(config, DictConfig):
            config_dict = OmegaConf.to_container(config, resolve=True)
            if not isinstance(config_dict, dict):
                msg = f"Expected dict after OmegaConf.to_container, got {type(config_dict)}"
                raise ValueError(msg)
            config = config_dict
        elif not isinstance(config, dict):
            msg = f"Expected dict or DictConfig, got {type(config)}"
            raise ValueError(msg)

        generation_config_dict = config.get("generation", {})

        # Validate generation parameters that are present in config
        if generation_config_dict:
            try:
                # Validate only the parameters present in the config
                validated_gen_config = GenerationConfig(**generation_config_dict)
                # Only include parameters that were in the original config
                for key in generation_config_dict:
                    if hasattr(validated_gen_config, key):
                        settings[key] = getattr(validated_gen_config, key)
            except Exception as e:
                msg = f"Invalid generation configuration: {e}"
                raise ValueError(msg)

    provider = OllamaProvider(
        base_url=final_base_url,
        api_key=final_api_key,
    )

    return cls(
        final_model_name, provider=provider, settings=settings or None, **kwargs
    )

from_custom classmethod

from_custom(
    config: DictConfig | dict | None = None,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel

Create a model for any custom OpenAI-compatible server.

Parameters:

Name Type Description Default
config DictConfig | dict | None

Optional Hydra configuration with custom server settings.

None
model_name str | None

Model name (overrides config if provided).

None
base_url str | None

Server URL (overrides config if provided).

None
api_key str | None

API key (overrides config if provided).

None
**kwargs Any

Additional arguments passed to the model.

{}

Returns:

Type Description
OpenAICompatibleModel

Configured OpenAICompatibleModel instance.

Source code in DeepResearch/src/models/openai_compatible_model.py
@classmethod
def from_custom(
    cls,
    config: DictConfig | dict | None = None,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel:
    """Create a model for any custom OpenAI-compatible server.

    Args:
        config: Optional Hydra configuration with custom server settings.
        model_name: Model name (overrides config if provided).
        base_url: Server URL (overrides config if provided).
        api_key: API key (overrides config if provided).
        **kwargs: Additional arguments passed to the model.

    Returns:
        Configured OpenAICompatibleModel instance.
    """
    if config is not None:
        return cls.from_config(config, model_name, base_url, api_key, **kwargs)

    # Fallback for direct parameter usage
    if not base_url:
        msg = "base_url is required when not using config"
        raise ValueError(msg)
    if not model_name:
        msg = "model_name is required when not using config"
        raise ValueError(msg)

    provider = OllamaProvider(
        base_url=base_url,
        api_key=api_key or "EMPTY",
    )
    return cls(model_name, provider=provider, **kwargs)

from_llamacpp classmethod

from_llamacpp(
    config: DictConfig | dict | None = None,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel

Create a model for a llama.cpp server.

Parameters:

Name Type Description Default
config DictConfig | dict | None

Optional Hydra configuration with llama.cpp settings.

None
model_name str | None

Model name (overrides config if provided).

None
base_url str | None

llama.cpp server URL (overrides config if provided).

None
api_key str | None

API key (overrides config if provided).

None
**kwargs Any

Additional arguments passed to the model.

{}

Returns:

Type Description
OpenAICompatibleModel

Configured OpenAICompatibleModel instance.

Source code in DeepResearch/src/models/openai_compatible_model.py
@classmethod
def from_llamacpp(
    cls,
    config: DictConfig | dict | None = None,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel:
    """Create a model for a llama.cpp server.

    Args:
        config: Optional Hydra configuration with llama.cpp settings.
        model_name: Model name (overrides config if provided).
        base_url: llama.cpp server URL (overrides config if provided).
        api_key: API key (overrides config if provided).
        **kwargs: Additional arguments passed to the model.

    Returns:
        Configured OpenAICompatibleModel instance.
    """
    if config is not None:
        # Use default llama model name if not specified
        if model_name is None and "model_name" not in config:
            model_name = "llama"
        return cls.from_config(config, model_name, base_url, api_key, **kwargs)

    # Fallback for direct parameter usage
    if not base_url:
        msg = "base_url is required when not using config"
        raise ValueError(msg)

    provider = OllamaProvider(
        base_url=base_url,
        api_key=api_key or "sk-no-key-required",
    )
    return cls(model_name or "llama", provider=provider, **kwargs)

from_tgi classmethod

from_tgi(
    config: DictConfig | dict | None = None,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel

Create a model for a Text Generation Inference (TGI) server.

Parameters:

Name Type Description Default
config DictConfig | dict | None

Optional Hydra configuration with TGI settings.

None
model_name str | None

Model name (overrides config if provided).

None
base_url str | None

TGI server URL (overrides config if provided).

None
api_key str | None

API key (overrides config if provided).

None
**kwargs Any

Additional arguments passed to the model.

{}

Returns:

Type Description
OpenAICompatibleModel

Configured OpenAICompatibleModel instance.

Source code in DeepResearch/src/models/openai_compatible_model.py
@classmethod
def from_tgi(
    cls,
    config: DictConfig | dict | None = None,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel:
    """Create a model for a Text Generation Inference (TGI) server.

    Args:
        config: Optional Hydra configuration with TGI settings.
        model_name: Model name (overrides config if provided).
        base_url: TGI server URL (overrides config if provided).
        api_key: API key (overrides config if provided).
        **kwargs: Additional arguments passed to the model.

    Returns:
        Configured OpenAICompatibleModel instance.
    """
    if config is not None:
        return cls.from_config(config, model_name, base_url, api_key, **kwargs)

    # Fallback for direct parameter usage
    if not base_url:
        msg = "base_url is required when not using config"
        raise ValueError(msg)
    if not model_name:
        msg = "model_name is required when not using config"
        raise ValueError(msg)

    provider = OllamaProvider(
        base_url=base_url,
        api_key=api_key or "EMPTY",
    )
    return cls(model_name, provider=provider, **kwargs)

from_vllm classmethod

from_vllm(
    config: DictConfig | dict | None = None,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel

Create a model for a vLLM server.

Parameters:

Name Type Description Default
config DictConfig | dict | None

Optional Hydra configuration with vLLM settings.

None
model_name str | None

Model name (overrides config if provided).

None
base_url str | None

vLLM server URL (overrides config if provided).

None
api_key str | None

API key (overrides config if provided).

None
**kwargs Any

Additional arguments passed to the model.

{}

Returns:

Type Description
OpenAICompatibleModel

Configured OpenAICompatibleModel instance.

Source code in DeepResearch/src/models/openai_compatible_model.py
@classmethod
def from_vllm(
    cls,
    config: DictConfig | dict | None = None,
    model_name: str | None = None,
    base_url: str | None = None,
    api_key: str | None = None,
    **kwargs: Any,
) -> OpenAICompatibleModel:
    """Create a model for a vLLM server.

    Args:
        config: Optional Hydra configuration with vLLM settings.
        model_name: Model name (overrides config if provided).
        base_url: vLLM server URL (overrides config if provided).
        api_key: API key (overrides config if provided).
        **kwargs: Additional arguments passed to the model.

    Returns:
        Configured OpenAICompatibleModel instance.
    """
    if config is not None:
        return cls.from_config(config, model_name, base_url, api_key, **kwargs)

    # Fallback for direct parameter usage
    if not base_url:
        msg = "base_url is required when not using config"
        raise ValueError(msg)
    if not model_name:
        msg = "model_name is required when not using config"
        raise ValueError(msg)

    provider = OllamaProvider(
        base_url=base_url,
        api_key=api_key or "EMPTY",
    )
    return cls(model_name, provider=provider, **kwargs)