> ## Documentation Index
> Fetch the complete documentation index at: https://www.minitap.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Class

> Central class for mobile automation

The `Agent` class is the primary entry point for the mobile-use SDK, responsible for managing device interaction and executing tasks.

## Import

```python theme={null}
from minitap.mobile_use.sdk import Agent
```

## Constructor

```python theme={null}
Agent(config: AgentConfig | None = None)
```

### Parameters

<ParamField path="config" type="AgentConfig" optional>
  Custom agent configuration. If not provided, default configuration is used.
</ParamField>

### Example

```python theme={null}
from minitap.mobile_use.sdk import Agent
from minitap.mobile_use.sdk.builders import Builders
from minitap.mobile_use.sdk.types import AgentProfile

# With default configuration
agent = Agent()

# With custom configuration
profile = AgentProfile(name="default", from_file="llm-config.defaults.jsonc")
config = Builders.AgentConfig.with_default_profile(profile).build()
agent = Agent(config=config)
```

## Methods

### init

Initialize the agent by connecting to a device and starting required servers.

```python theme={null}
async def init(
    self,
    api_key: str | None = None,
    server_restart_attempts: int = 3,
    retry_count: int = 5,
    retry_wait_seconds: int = 5,
) -> bool
```

#### Parameters

<ParamField path="api_key" type="str" optional>
  Minitap API key for Platform features (Platform tasks, cloud mobiles). Can also be set via `MINITAP_API_KEY` environment variable.
</ParamField>

<ParamField path="server_restart_attempts" type="int" default={3}>
  Maximum number of attempts to start servers if they fail
</ParamField>

<ParamField path="retry_count" type="int" default={5}>
  Number of retries for API calls
</ParamField>

<ParamField path="retry_wait_seconds" type="int" default={5}>
  Seconds to wait between retries
</ParamField>

#### Returns

<ResponseField name="success" type="bool">
  `True` if initialization succeeded, `False` otherwise
</ResponseField>

#### Example

```python theme={null}
import asyncio

async def main():
    agent = Agent()

    # Initialize without API key (local mode only)
    if not await agent.init():
        print("Failed to initialize agent")
        exit(1)

    print("Agent initialized successfully")

asyncio.run(main())
```

#### Example with API Key

```python theme={null}
import asyncio

async def main():
    agent = Agent()

    # Initialize with API key for Platform features
    if not await agent.init(api_key="your-minitap-api-key"):
        print("Failed to initialize agent")
        exit(1)

    print("Agent initialized successfully with Platform support")

asyncio.run(main())
```

<Warning>
  Always check the return value of `init()` before running tasks. Note that `init()` is now an async method and must be awaited.
</Warning>

***

### run\_task

Execute a mobile automation task asynchronously.

```python theme={null}
async def run_task(
    self,
    *,
    goal: str | None = None,
    output: type[TOutput] | str | None = None,
    profile: str | AgentProfile | None = None,
    name: str | None = None,
    request: TaskRequest[TOutput] | PlatformTaskRequest[TOutput] | None = None,
) -> str | dict | TOutput | None
```

#### Parameters

<ParamField path="goal" type="str" optional>
  Natural language description of what to accomplish
</ParamField>

<ParamField path="output" type="type[TOutput] | str" optional>
  Type of output:

  * Pydantic model class for structured output
  * String description for output format
</ParamField>

<ParamField path="profile" type="str | AgentProfile" optional>
  Agent profile to use (name or instance)
</ParamField>

<ParamField path="name" type="str" optional>
  Optional name for the task (for logging/debugging)
</ParamField>

<ParamField path="request" type="TaskRequest[TOutput] | PlatformTaskRequest[TOutput]" optional>
  Pre-built TaskRequest or PlatformTaskRequest (alternative to individual parameters)
</ParamField>

#### Returns

<ResponseField name="result" type="str | dict | TOutput | None">
  Task result:

  * `str`: Simple text output
  * `dict`: Unstructured dictionary
  * `TOutput`: Instance of specified Pydantic model
  * `None`: Task failed or no output
</ResponseField>

#### Examples

<CodeGroup>
  ```python Simple Task theme={null}
  result = await agent.run_task(
      goal="Open calculator and compute 5 * 7"
  )
  print(result)  # String output
  ```

  ```python Structured Output theme={null}
  from pydantic import BaseModel, Field

  class CalculationResult(BaseModel):
      expression: str
      result: float

  result = await agent.run_task(
      goal="Calculate 123 * 456 in calculator app",
      output=CalculationResult
  )

  print(f"{result.expression} = {result.result}")
  ```

  ```python With Profile theme={null}
  result = await agent.run_task(
      goal="Analyze this complex interface",
      profile="detail_oriented",
      name="ui_analysis"
  )
  ```

  ```python Using TaskRequest theme={null}
  task = (
      agent.new_task("Check notifications")
      .with_max_steps(300)
      .with_trace_recording(True)
      .build()
  )

  result = await agent.run_task(request=task)
  ```

  ```python Using PlatformTaskRequest theme={null}
  from minitap.mobile_use.sdk.types import PlatformTaskRequest

  result = await agent.run_task(
      request=PlatformTaskRequest(task="check-notifications")
  )
  ```
</CodeGroup>

<Note>
  For platform tasks, the **Locked App Package** is configured on the platform task itself, not in `PlatformTaskRequest`. For local tasks using `TaskRequest`, use `.with_locked_app_package()` in the builder.
</Note>

***

### new\_task

Create a new task request builder for fluent task configuration.

```python theme={null}
def new_task(self, goal: str) -> TaskRequestBuilder[None]
```

#### Parameters

<ParamField path="goal" type="str" required>
  Natural language description of what to accomplish
</ParamField>

#### Returns

<ResponseField name="builder" type="TaskRequestBuilder[None]">
  TaskRequestBuilder instance for fluent configuration
</ResponseField>

#### Example

```python theme={null}
from pathlib import Path

task = (
    agent.new_task("Open Gmail and count unread emails")
    .with_name("email_count")
    .with_max_steps(400)
    .with_trace_recording(enabled=True, path=Path("/tmp/traces"))
    .build()
)

result = await agent.run_task(request=task)
```

***

### clean

Clean up resources, stop servers, and reset the agent state.

```python theme={null}
async def clean(self, force: bool = False) -> None
```

#### Parameters

<ParamField path="force" type="bool" default={false}>
  Set to `True` to clean zombie/pre-existing mobile-use servers
</ParamField>

#### Example

```python theme={null}
import asyncio

async def main():
    agent = Agent()

    try:
        await agent.init()
        await agent.run_task(goal="Some task")
    finally:
        await agent.clean()  # Always clean up

asyncio.run(main())
```

<Tip>
  Use `force=True` if you have zombie servers from previous runs:

  ```python theme={null}
  await agent.clean(force=True)  # Kill any existing servers
  await agent.init()              # Start fresh
  ```
</Tip>

<Warning>
  Note that `clean()` is now an async method and must be awaited.
</Warning>

***

### install\_apk

Install an APK on the connected Android device.

```python theme={null}
async def install_apk(self, apk_path: str | Path) -> None
```

This method works with both local devices and cloud mobiles:

* **For local devices**: Uses ADB to install the APK directly
* **For cloud mobiles**: Installs it on the cloud mobile via the API

#### Parameters

<ParamField path="apk_path" type="str | Path" required>
  Path to the local APK file to install
</ParamField>

#### Raises

* `FileNotFoundError`: If the APK file does not exist
* `AgentNotInitializedError`: If the agent is not initialized (local mode)
* `AgentError`: If the device is not an Android device or ADB client is not initialized
* `CloudMobileServiceUninitializedError`: If cloud mobile service is not initialized (cloud mode)
* `AgentTaskRequestError`: If cloud mobile ID is not configured (cloud mode)

<Warning>
  APK installation is only supported on Android devices. Attempting to install an APK on an iOS device will raise an `AgentError`.
</Warning>

<Warning>
  For cloud mobiles, the APK must be **x86\_64 compatible**.
</Warning>

<Tip>
  For cloud mobiles, the `install_apk` method automatically starts the cloud mobile if it's not already running, so you don't need to manually start it before installing.
</Tip>

***

### get\_screenshot

Capture a screenshot from the mobile device.

```python theme={null}
async def get_screenshot(self) -> Image.Image
```

This method works with both local devices and cloud mobiles:

* **For local devices**: Uses ADB (Android) or xcrun (iOS) to capture screenshots directly
* **For cloud mobiles**: Retrieves screenshots from the cloud mobile via the Platform API

#### Returns

<ResponseField name="screenshot" type="Image.Image">
  Screenshot as a PIL Image object
</ResponseField>

#### Raises

* `AgentNotInitializedError`: If the agent is not initialized
* `CloudMobileServiceUninitializedError`: If using cloud mobile without proper initialization
* `Exception`: If screenshot capture fails

#### Example

```python theme={null}
import asyncio
from minitap.mobile_use.sdk import Agent

async def main():
    agent = Agent()

    try:
        await agent.init()

        # Capture a screenshot
        screenshot = await agent.get_screenshot()

        # Save the screenshot
        screenshot.save("device_screenshot.png")
        print("Screenshot saved!")

    finally:
        await agent.clean()

asyncio.run(main())
```

#### Example with Cloud Mobile

```python theme={null}
import asyncio
from minitap.mobile_use.sdk import Agent
from minitap.mobile_use.sdk.builders import Builders

async def main():
    # Configure for cloud mobile
    config = Builders.AgentConfig.for_cloud_mobile("my-cloud-device").build()
    agent = Agent(config=config)

    try:
        await agent.init(api_key="your-minitap-api-key")

        # Capture screenshot from cloud mobile
        screenshot = await agent.get_screenshot()
        screenshot.save("cloud_device_screenshot.png")

    finally:
        await agent.clean()

asyncio.run(main())
```

<Tip>
  Use `get_screenshot()` for debugging, monitoring, or extracting visual data from your mobile device during automation workflows.
</Tip>

## Complete Example

```python theme={null}
import asyncio
from pydantic import BaseModel, Field
from minitap.mobile_use.sdk import Agent
from minitap.mobile_use.sdk.types import AgentProfile
from minitap.mobile_use.sdk.builders import Builders

class WeatherInfo(BaseModel):
    temperature: float = Field(..., description="Temperature in Celsius")
    condition: str = Field(..., description="Weather condition")

async def main():
    # Configure agent
    profile = AgentProfile(name="default", from_file="llm-config.defaults.jsonc")
    config = Builders.AgentConfig.with_default_profile(profile).build()
    agent = Agent(config=config)

    try:
        # Initialize
        if not await agent.init():
            print("Failed to initialize")
            return

        # Run task with structured output
        weather = await agent.run_task(
            goal="Open weather app and check current temperature",
            output=WeatherInfo,
            name="weather_check"
        )

        if weather:
            print(f"Temperature: {weather.temperature}°C")
            print(f"Condition: {weather.condition}")

    except Exception as e:
        print(f"Error: {e}")
    finally:
        await agent.clean()

if __name__ == "__main__":
    asyncio.run(main())
```

## Exception Handling

The Agent may raise the following exceptions:

* `AgentNotInitializedError`: Agent methods called before initialization
* `DeviceNotFoundError`: No device found or device disconnected
* `AgentProfileNotFoundError`: Specified profile not found
* `ServerStartupError`: Failed to start required servers
* `ExecutableNotFoundError`: Required executable (adb, idb, xcrun) not found
* `AgentTaskRequestError`: Invalid task request configuration
* `PlatformServiceUninitializedError`: Platform service not initialized (missing API key)
* `CloudMobileServiceUninitializedError`: Cloud mobile service not initialized (missing API key or cloud mobile not configured)
* `AgentInvalidApiKeyError`: Invalid Minitap API key

See [Exceptions](/docs/mobile-use-sdk/sdk-reference/exceptions) for details.

## Next Steps

<CardGroup cols={2}>
  <Card title="Task Request Builder" icon="list-check" href="/docs/mobile-use-sdk/sdk-reference/task-request-builder">
    Configure tasks with the builder pattern
  </Card>

  <Card title="Agent Config Builder" icon="gear" href="/docs/mobile-use-sdk/sdk-reference/agent-config-builder">
    Configure agent behavior
  </Card>
</CardGroup>
