# Get started with the Lumi™ AI Workspace

## Overview

The Lumi AI Workspace enables the development and deployment of custom web applications by leveraging cloud APIs from the Delfi digital platform and Lumi data and AI platform. This guide offers a straightforward, step-by-step walkthrough to help you build and preview your first web application using SLB APIs within the AI Workspace. To illustrate the process, we’ve used the OSDU Search API in a sample Dash web app.

While this tutorial is based on the Dash-Python framework, you can also use alternatives like Shiny, Bokeh, or even create a traditional HTML web application using JavaScript and CSS.

## Prerequisites

* The Lumi Data Science subscription is required to access the AI Workspace.
* The Dataiku code environment is required with the following packages. You might need a Data Science Admin subscription to create or modify the code environment to get the following mandatory packages installed. See "Step 3: Set up code environment" for more information.


```
dash==3.0.4
dash-bootstrap-components==2.0.3
Flask==3.0.3
```

## Step 1: Launch the AI Workspace

1. Launch the Data Science app from the **My Subscriptions** section of [Digital Home](https://delfi.slb.com/).
![Launch_subscriptions](/assets/digital_home_launch.430cbf71a080e765d8d97a078e6940e3686a4402c18d6c27ed93437497a00c2e.3e37ecb4.png)
2. Launch the AI Workspace by clicking **AI Workspace** as shown below.

![Launch](/assets/launch_ai_workspace.ce6abd3d560261588251880dabedb3859d5af15e83384652a70438dc1ae5cd66.3e37ecb4.png)


#### AI Workspace description and features

The AI Workspace has four main tabs that display projects in the workspace. Each project is displayed as a card.

**My Projects**: Displays all of the projects created by the logged-in user. From this tab, you can create new projects or import existing templates.

**Shared**: Displays the shared projects that you have permission to access.

**All**: Displays all projects that you have permission to access.

**Favorites**: Displays the projects that you have tagged as a favorite by clicking on a card.

For more details on AI Workspace features, refer to the [SLB Help documentation on the AI Workspace](https://help.digital.slb.com/content/1023/help/AI_Workspace_interface_tour_1C6F0B7F-0BC3-487C-9078-2E000ADB7BB1). Note, you must be onboarded to a Digital Home account to access SLB Help documentation.

## Step 2: Create a project

A  project is a container in Dataiku for all your work on a particular activity. Each project has a single flow that shows the pipeline of datasets and recipes associated with the project.
To create a project in the AI Workspace:

1. From the **AI Workspace** tab in the Data Science application, click **New Project**.
The **New Project** dialog box opens.
![Create_new_project](/assets/create_new_project.44b76f16c390e5e05d3de954545d1f5c44527409148a7245b758f516f7f7214c.3e37ecb4.png)
2. Type the project **Name**. Do not use special characters in the name, except for an underscore.
The **Project Key** is added automatically when you enter the project name.
3. Select the **Status** and **Type**.
4. (Optional) Enter one or more **Domain** tags as needed.
5. Search for and select users in your organization as **Readers** or **Contributors**.
6. Enter a **Description** for the project.
7. Click **Create**.


The project is added to the **My Projects** area in the AI Workspace. You can edit a project's details by clicking **Edit** on a project card.

## Step 3: Set up the code environment

1. Click your project's name in the **My Project** area of the AI Workspace to launch the project page.
2. Click the grid icon on the top-right of the page, as shown in the image below, and click **Administration**. The Administration page opens where you can create or modify code environments that can be used to run the webapp. You can only access **Administration** if you have a Data Science Admin subscription.


![launch_administration](/assets/administration_launch.54700e472eb9b0fc8d42d819e467691280f77ca7219922fabae0f8fb77d43bc1.3e37ecb4.png)

1. Click the **Code Envs** tab to view available environments. You can filter the existing environments to show the ones that you would like to modify, or you can create a new Python environment as shown below:


![New_python_Env](/assets/new_env.af663bef7e009313136e58a565f933dd60c2511646b6b49ad147c827a7ad7f93.3e37ecb4.png)

1. If you are planning to create a new environment, the image below shows the settings to select when creating a code environment to run the provided webapp code.
![Create_code_env](/assets/code_env_creation.ed74a7e2325ea331b17187dc99a1c059921da4b5a0e1811125e0c57e0748cba8.3e37ecb4.png)
2. Ensure the following dependencies are installed. To install dependecies, navigate to **Packages to install** as shown in image below.
3. Copy the provided dependency list below and paste it into the space provided for **Requested packages**.
4. Click **Save and Update** to update your code environment with the required dependencies.


![Install dependencies](/assets/install_dependencies.6db0536e14aae17e9bd630bcff0bd29c294c509780af79ecd6983cb38d023725.3e37ecb4.png)

**Packages required**

```
dash==3.0.4
dash-bootstrap-components==2.0.3
Flask==3.0.3
```

## Step 4: Create an empty Dash Webapp

1. Navigate back to the AI Workspace and click your project's name in the **My Project** area to launch the Project page in Dataiku.
2. Click the **</>** icon in the toolbar and select **Webapp**.
![Create_webapp](/assets/create_webapp.53cbc1f9bfadcee332182c08697704ab88added6a00b1172bc4f9267e823cb7d.3e37ecb4.png)
3. Click **CREATE YOUR FIRST WEBAPP** and select **Code Webapp**.
![First_webapp](/assets/create_first_webapp.e147436a4ceb0edaf74b41c2e4e72ced0c0768344d444635fd96496232645cf2.3e37ecb4.png)
4. Click **Dash** to develop your webapp.
![Dash_webapp](/assets/dash_webapp_select.0526bf068989133ab8e4f2f32eedb59954a6d9899625358983ef2c4bea44ff0d.3e37ecb4.png)
5. Select **An empty Dash app**.
6. Type the **Webapp name** in the space privided and click **CREATE**.
![Create_Dash_webapp](/assets/empty_dash_webapp.facd4b3c3cadea0f5bd3c67348770cf0b3746768a13bca06f7b62d32785bf4ed.3e37ecb4.png)
This creates an empty Dash webapp in the AI Workspace project where you can start coding.
![empty_webapp](/assets/empty_webapp.99fc9a019f0c25c29e2ea99d26be55e90759eb077bdda4af29e8b8729cbb3082.3e37ecb4.png)


The empty webapp has the following tabs:

**Preview**: Click to view the Webapp while you code.

**Python**: Click to show the code.

**Log**: Click to show the server log for the webapp.

**Settings**: Click to configure the back-end settings for the webapp server.

## Step 5: Back-end settings

Each webapp requires a code environment with prerequisite packages and the right back-end settings to run without errors. You must specify the code environment containing the Dash packages to run the provided code snippets in this tutorial.

a) Go to **Settings**, change the value of **Code env** to **Select an environment**, and change the value of the **Environment** to the code environment with the prerequisite packages installed. [Refer to the Prerequisites](#pre-requisites).

b) Change the **Container** to **None-Use backend to execute**.

![set_code_env](/assets/set_code_env.399dde9cb765e81a963ef9f9f2d86e6275036fd1c572d0b8abbead404edaa911.3e37ecb4.png)

c) Click **Save** at the top-right corner of the page.

## Step 6: Develop

## 6.1. Import dependencies

The tabs in the AI Workspace webapp are highlighted in the image below.

![empty_webapp](/assets/empty_webapp.99fc9a019f0c25c29e2ea99d26be55e90759eb077bdda4af29e8b8729cbb3082.3e37ecb4.png)

a)  Navigate to the **Python** tab in the web app and replace the existing dependency imports with the ones provided in the code snippet. This will ensure that the required dependencies for the web app being developed in this guide are properly imported.
Your prewritten code snippet for importing dependencies should look like following highlighted snippet.

Prewritten dependency imports:
![Import Depenency](/assets/replace_dependency.3e00bb39eb174fe865b41d72aca57e85a1947fa14f319f18e3ed7db7e84437e2.3e37ecb4.png)

Replace the highlighted line above of the prewritten code with the following snippet:

```python
import dataiku
from global_de_utils import getAppKey, getSauthToken

import dash
from dash import html
from dash import dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input
from dash.dependencies import Output
from dash.dependencies import State
from dash.exceptions import PreventUpdate

import requests
import xml.etree.ElementTree as ET
```

b)  Click **Save** from the top-right corner of the page.

c)  Check the **Log** tab for any errors. If the **Log** tab shows "Backend is not running," click **Start Backend**.

d)  If the **Log** tab indicates that any dependencies are missing, contact your Data Science application admin to update the code environment with the missing dependencies. Refer to Step 3 above for more information.

## 6.2. Define app layout

Copy and use the following code snippet on the **Python** tab to replace the app.layout defined in the prewritten code. Click **Save** to generate the UI elements as shown in the image below.

![Webapp_preview](/assets/webapp-preview.61e85aff7040b7080f89b832e0c896075964d2edcd2e5fe4ff8c3104c0bb0ba4.3e37ecb4.png)
Copy and Paste the following code snippet:

```python
# Define App layout using stylesheet
app.config.external_stylesheets = [dbc.themes.BOOTSTRAP]

Login_layout = html.Div([
   dbc.Card(
           dbc.CardBody([
               html.Div([
                   html.H2("My First AI Workspace Webapp"),
               ], style={'textAlign': 'center'}) 
           ])
           ),
   html.Br(),
   dbc.Row([
       dbc.Col(dbc.Button("Get Token", id="login_button", color="primary", n_clicks=0), width=2, className="d-grid col-2 gap-2"),
   ], className="mb-3",),
   html.Br(),
   html.Br(),
   html.P(id="login_output"),
   
   dbc.Row([
   dbc.Col(dbc.Button("Show logged in User", id="ShowUser_button", color="primary", n_clicks=0), width=2, className="d-grid col-2 gap-2"),
   ], className="mb-3",),
   html.Br(),
   html.Br(),
   html.P(id="ShowUser_output"),
   
   dcc.Input(id='input-text', type='text', placeholder='Enter Kind to search'),
   html.Br(),
   html.Br(),
   dbc.Button('Search', id='submit-button', color="primary", n_clicks=0),
   html.Div(id='response-output')

])

# build your Dash app
app.layout = html.Div([
   Login_layout
], className="container-fluid mt-3")
```

## 6.3. Write callback functions

There are three controls in the webapp UI: **Get Token** button, **Show logged in user** button, and **Search**.

To write callbacks for these:

1. **Get Token button - Callback**


The AI Workspace provides built-in functions to get an SLB Authenticator token and appkey that can be used to call any SLB platform APIs. The following code snippet is a simple function that can be used to generate the token.

a. Append the following code to define the callback for the **Get Token** button.

b. Click **Save** and test the **Get Token** button in the **Preview** tab. It should return the SLB Authenticator token.

**Note**: You must be logged into the Data Science Application for the getSauthToken() function to get the token successfully.

Code snippet:

```python
# 'Get Token' button-function and callback 
@app.callback(
   Output("login_output", "children"),
   Input('login_button', 'n_clicks'),
   prevent_initial_call = True
)
def on_login_button_click(n_clicks):
   stoken, info = getSauthToken()
   return f"Your Access Token is  {stoken}"
```

1. **Show Logged in user button - Callback**
a. Append the following code to define the callback for the **Show logged in user** button.
b. Click **Save** and test the **Show logged in user** button in the **Preview** tab. It should return your login email.


Code snippet:

```python
# show logged in user- function and callback
@app.callback(
   Output("ShowUser_output","children"),
   Input('ShowUser_button', 'n_clicks'),
   prevent_initial_call = True
)
def on_show_user_button_click(n_clicks):
   from flask import request
   #return 'test'
   request_headers = dict(request.headers)
   auth_info_brower = dataiku.api_client().get_auth_info_from_browser_headers(request_headers)
   return  auth_info_brower["authIdentifier"]
```

1. **Search function - Callback**
a. Append the following code snippet to define the callback for the **Search** button.
b. Replace the "server" in the API endpoint url definition and add the Data Partition ID in the header.
c. Click **Save**.
2. **Add your "server" url and "Data Partition ID"**
You can get the URL and data partition information from Digital Home.
a. Navigate to [Digital Home](https://delfi.slb.com/home) and click the profile icon. You will see a **Copy** icon as shown in screenshot below.
b. Click the **Copy** icon and paste the copied text to a notepad.
c. You can use the "DeploymentURL" and "DataPartitionID" to replace "server" and "Add-Data-Partition-Here" respectively in the code below.


![Digital_Home_profile](/assets/get_deployment-url.7908ad944fa8828400ebe5e16b776354bf184fd0edc72770739cb14782bc88fc.3e37ecb4.png)

![update_code](/assets/update_code.9e69a8d6114e2f42d00bced1e7811bb3003414d14f48d8448b3a01998abebebc.3e37ecb4.png)

Code snippet:

```python
# Search Function definition and Callback
@app.callback(
   Output('response-output', 'children'),
   Input('submit-button', 'n_clicks'),
   Input('input-text', 'value')
)
  
def call_api(n_clicks, value):
   if n_clicks > 0:
       #get stoken
       from global_de_utils import getAppKey, getSauthToken
       stoken, info = getSauthToken()
       appkey = getAppKey()
       if info:
           print(f"Error retrieving sauth token : {info}")
           

       # API endpoint
       url = "https://<Server>/api/search/v2/query"

       # Headers
       headers = {
           "Authorization": 'Bearer ' + stoken,
           'data-partition-id': '<Add-Data-Partition-Here>',
           "Content-Type": "application/json"
       }

       # Payload
       payload = {"kind": value, "limit":5}

       # Make the API request
       response = requests.post(url, headers=headers, json=payload)
       

       # Check response status
       if response.status_code == 200:
           return f"API Response: {response.json()}"
       else:
           return f"Error: {response.status_code} - {response.text}"
```

The final webapp preview would like the image below. After the backend starts, you can test all three functions in the **Preview** tab.

* The **Get Token** button returns the SLB Authenticator token that can be used to call an API from within an AI Workspace webapp.
* The **show logged in User** button shows the logged-in user in the webapp.
* The **search** box takes the OSDU data "Kind," such as osdu:wks:master-data--Wellbore:1.0.0, as input and returns the first 5 search results. The search limit in the API is set to 5, but you can modify it as needed.


**Final Webapp Preview**

![final_webapp](/assets/final_webapp.b5071b43231d46b78d7953e08d4194d1981af3ce6a5d1d8c21b366bc16725917.3e37ecb4.png)

## Conclusion

You were able to create a Dash WebApp in the AI Workspace that uses the provided SLB utility to get a token and call the "OSDU Search API." This can be extended to build custom applications using any of the SLB offered APIs for varied domain use cases.

## Recommended further reading

- [SLB Help documentation on AI Workspace](https://help.digital.slb.com/content/1023/help/AI_Workspace_interface_tour_1C6F0B7F-0BC3-487C-9078-2E000ADB7BB1)
- [More Tutorials on webapp development for the AI Workpspace](https://developer.dataiku.com/latest/tutorials/webapps/index.html)