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

# Guide: Executing Your First Tool

> Learn how to discover, execute, and retrieve results from UBIK's powerful asynchronous tools.

This guide demonstrates how to leverage UBIK's tools to perform complex tasks. You will learn how to list available tools, execute one with the required inputs, and then poll for the execution results.

<Steps>
  <Step title="Discover Available Tools">
    First, let's see what tools are available. We can get a list of all tools accessible to us by making a `GET` request to the `/tools` endpoint.

    <CodeGroup title="GET /tools">
      ```bash cURL theme={null}
      curl -X GET "https://app.ubik-agent.com/api/v1/tools" \
           -H "X-API-KEY: YOUR_API_KEY"
      ```

      ```python Python theme={null}
      import requests

      api_key = "YOUR_API_KEY"
      headers = {"X-API-KEY": api_key}

      response = requests.get("https://app.ubik-agent.com/api/v1/tools", headers=headers)

      if response.status_code == 200:
          tools = response.json()
          print(tools['items'])
      else:
          print(f"Error: {response.status_code}", response.text)
      ```

      ```javascript JavaScript theme={null}
      const apiKey = "YOUR_API_KEY";
      const url = "https://app.ubik-agent.com/api/v1/tools";

      fetch(url, {
        method: 'GET',
        headers: { 'X-API-KEY': apiKey }
      })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error: ${response.status}`);
        }
        return response.json();
      })
      .then(data => console.log(data.items))
      .catch(error => console.error('Error:', error));
      ```
    </CodeGroup>

    The response will be a paginated list of tools. For this guide, let's assume we want to use a tool named **"Financial Data Extractor"**. Find it in the list and copy its `id`.
  </Step>

  <Step title="Execute the Tool">
    Now, we'll start the tool by making a `POST` request to the `/tools/{tool_id}/execute` endpoint. You'll need the `id` from the previous step. In the request body, we'll provide the `inputs` that the tool requires.

    <CodeGroup title="POST /tools/{tool_id}/execute">
      ```bash cURL theme={null}
      curl -X POST "https://app.ubik-agent.com/api/v1/tools/YOUR_TOOL_ID/execute" \
           -H "X-API-KEY: YOUR_API_KEY" \
           -H "Content-Type: application/json" \
           -d '{
                "inputs": {
                  "document_id": "YOUR_DOCUMENT_ID",
                  "data_points": ["revenue", "net_income", "ebitda"]
                }
              }'
      ```

      ```python Python theme={null}
      import requests

      api_key = "YOUR_API_KEY"
      tool_id = "YOUR_TOOL_ID"

      headers = {
          "X-API-KEY": api_key,
          "Content-Type": "application/json"
      }
      payload = {
          "inputs": {
              "document_id": "YOUR_DOCUMENT_ID",
              "data_points": ["revenue", "net_income", "ebitda"]
          }
      }

      response = requests.post(
          f"https://app.ubik-agent.com/api/v1/tools/{tool_id}/execute",
          headers=headers,
          json=payload
      )

      if response.status_code == 202: # Accepted
          execution_info = response.json()
          print(execution_info)
          # Save the execution_id to check the status later
      else:
          print(f"Error: {response.status_code}", response.text)
      ```

      ```javascript JavaScript theme={null}
      const apiKey = "YOUR_API_KEY";
      const toolId = "YOUR_TOOL_ID";
      const url = `https://app.ubik-agent.com/api/v1/tools/${toolId}/execute`;

      const payload = {
        inputs: {
          document_id: "YOUR_DOCUMENT_ID",
          data_points: ["revenue", "net_income", "ebitda"]
        }
      };

      fetch(url, {
        method: 'POST',
        headers: {
          'X-API-KEY': apiKey,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      })
      .then(response => {
        if (response.status !== 202) { // Accepted
          throw new Error(`HTTP error: ${response.status}`);
        }
        return response.json();
      })
      .then(executionInfo => {
        console.log(executionInfo);
        // Save the execution_id to check the status later
      })
      .catch(error => console.error('Error:', error));
      ```
    </CodeGroup>

    The API will respond with a `202 Accepted` status, indicating that the task has been received. The response body contains an `execution_id` and a `details_url`. We will use this URL to get the final result.

    <Tip>
      **User Isolation**: If you are executing tools on behalf of your end-users, you can isolate their data by passing the `X-End-User-ID` header.

      `curl -H "X-End-User-ID: user_123" ...`

      For more details on data isolation and multi-tenancy, see the [Authentication & Security Guide](/en/guides/authentication).
    </Tip>
  </Step>

  <Step title="Poll for Results">
    Since the tool runs asynchronously, we need to poll the `details_url` to check for the final result. You'll want to check this endpoint periodically until the `status` changes to `completed` or `failed`.

    <CodeGroup title="GET /tool-executions/{execution_id}">
      ```bash cURL theme={null}
      curl -X GET "https://app.ubik-agent.com/api/v1/tool-executions/YOUR_EXECUTION_ID" \
           -H "X-API-KEY: YOUR_API_KEY"
      ```

      ```python Python theme={null}
      import requests
      import time

      api_key = "YOUR_API_KEY"
      execution_id = "YOUR_EXECUTION_ID"

      headers = {"X-API-KEY": api_key}
      url = f"https://app.ubik-agent.com/api/v1/tool-executions/{execution_id}"

      while True:
          response = requests.get(url, headers=headers)
          if response.status_code == 200:
              result = response.json()
              print(f"Current status: {result['status']}")
              if result['status'] in ['completed', 'failed']:
                  print("Final Result:", result)
                  break
          else:
              print(f"Error polling: {response.status_code}", response.text)
              break
          time.sleep(5) # Wait for 5 seconds before polling again
      ```

      ```javascript JavaScript theme={null}
      const apiKey = "YOUR_API_KEY";
      const executionId = "YOUR_EXECUTION_ID";
      const url = `https://app.ubik-agent.com/api/v1/tool-executions/${executionId}`;

      const pollResult = async () => {
        try {
          const response = await fetch(url, {
            headers: { 'X-API-KEY': apiKey }
          });

          if (!response.ok) {
            throw new Error(`HTTP error: ${response.status}`);
          }

          const result = await response.json();
          console.log(`Current status: ${result.status}`);

          if (result.status === 'completed' || result.status === 'failed') {
            console.log('Final Result:', result);
            // Stop polling
          } else {
            setTimeout(pollResult, 5000); // Poll again in 5 seconds
          }
        } catch (error) {
          console.error('Polling error:', error);
        }
      };

      pollResult();
      ```
    </CodeGroup>

    Once the status is `completed`, the `outputs` field will contain the data extracted by the tool.

    <Tip>
      For a more responsive, real-time experience, you can stream events instead of polling. Check out our guide on [Getting Real-Time Results with SSE](/en/guides/streaming-results).
    </Tip>
  </Step>
</Steps>

You now know how to discover and execute powerful, pre-built tools to automate complex workflows with the UBIK API.
