Metadata-Version: 2.4
Name: dhrishti
Version: 0.0.5
Summary: live variable inspection & manipulation for python runtimes
Project-URL: Repository, https://github.com/vedicreader/dhrishti
Project-URL: Documentation, https://vedicreader.github.io/dhrishti/
Author-email: Karthik <karthik.rajgopal@hotmail.com>
License: Apache-2.0
License-File: LICENSE
Keywords: nbdev
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Requires-Python: >=3.11
Requires-Dist: fastcore>=2.1.4
Requires-Dist: ipython>=9.15.0
Requires-Dist: numpy>=2.4.6
Requires-Dist: pandas>=3.0.3
Requires-Dist: python-fasthtml>=0.14.9
Requires-Dist: safepyrun>=0.2.5
Requires-Dist: textual>=8.2.8
Description-Content-Type: text/markdown

# dhrishti


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

dhrishti gives you a live window into a running Python namespace. Point it at a kernel, a script, or a plain dict and it renders every variable as a tree you can expand, page through, and edit while the code keeps running. It sits in a browser tab or a terminal pane and updates as your program does, the way `htop` tracks processes.

The same window opens onto AI agents. An agent works your live namespace through a sandboxed overlay: it reads your variables and creates its own, you watch what it builds, and you promote the results worth keeping.

## See it live

[`serve()`](https://vedicreader.github.io/dhrishti/serving.html#serve) opens a live panel in the browser for any process; inside Jupyter, [`inspector()`](https://vedicreader.github.io/dhrishti/serving.html#inspector) drops the same panel into the notebook as an inline iframe. The tree refreshes as your variables change, an exec bar runs code against the namespace, and clicking a value edits it in place.

``` python
from dhrishti.serving import serve, inspector
# server, url = serve()   # background inspector for a script or process -> its URL
inspector()             # or, inside Jupyter, the same panel inline
```

<script>
document.body.addEventListener('htmx:configRequest', (event) => {
    if(event.detail.path.includes('://')) return;
    htmx.config.selfRequestsOnly=false;
    event.detail.path = `${location.protocol}//${location.hostname}:8000${event.detail.path}`;
});
</script>

<a href="http://localhost:8000/" target="_blank">Open in new tab</a>

<iframe src="http://localhost:8000/" style="width: 100%; height: 520px; border: none;" onload="" allow="accelerometer; autoplay; camera; clipboard-read; clipboard-write; display-capture; encrypted-media; fullscreen; gamepad; geolocation; gyroscope; hid; identity-credentials-get; idle-detection; magnetometer; microphone; midi; payment; picture-in-picture; publickey-credentials-get; screen-wake-lock; serial; usb; web-share; xr-spatial-tracking"></iframe> 

![The inspector](images/inspector.png)

A terminal client mirrors the same server, for when you live in a shell. You can also run a script straight under an inspector:

``` sh
dhristi-serve train.py   # run a script under a live inspector
dhrishti-tui             # attach a terminal client to a running server
```

![The terminal client](images/tui.png)

When an agent is driving the session the panel does more than show variables: it shows the ones the agent has created, next to yours, and the full transcript of its run, saved as a notebook you can read top to bottom and replay.

## Install

``` sh
pip install dhrishti
```

Or straight from source:

``` sh
pip install git+https://github.com/vedicreader/dhrishti.git
```

## What it shows

Everything starts from a namespace, a dict of names to values. [`snapshot`](https://vedicreader.github.io/dhrishti/core.html#snapshot) turns one into inspector rows: a name, a type, a short value, and a shape.

``` python
import pandas as pd
from dhrishti.core import snapshot, expand, grid_page
hello='hi'
ns = dict(x=42, names=['ada','turing','hopper'], df=pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]}))
for v in snapshot(ns): print(f'{v.name} = {v.value}  ({v.type})')
```

    df = DataFrame [3×2]  (DataFrame)
    names = ['ada', 'turing', 'hopper']  (list)
    x = 42  (int)

Containers expand one level at a time, so a million-row frame costs nothing until you open it. A DataFrame expands into its metadata and columns; anything backed by numpy or pandas can also be paged as a grid.

``` python
for v in expand(ns, ('df',)): print(f'{v.name}: {v.value}')
```

    shape: (3, 2)
    size: 6
    dtypes: Series [2] object
    a: Series [3] int64
    b: Series [3] int64

``` python
grid_page(ns, ('df',))['cells']
```

    [['1', '4'], ['2', '5'], ['3', '6']]

## Handing your namespace to an agent

This is where it pays off. Start a server with the agent surface on, and a tool-calling model can work the same namespace you are watching. Below drives it with [rishi](https://github.com/vedicreader/rishi), whose `Chat` runs an on-device model, so no API keys are involved. The full walkthrough lives on the [agent page](https://vedicreader.github.io/dhrishti/agent.html).

``` python
from dhrishti.serving import serve, agent_session, AGENT_POLICY
from dhrishti.agent import agent_tools, run_coro, AgentSession

df = pd.DataFrame({'x': range(5), 'y': list('abcde')})   # your live data
server, url = serve(agent='restricted'); print(url)                  # inspector + agent surface
sess = agent_session()                                   # the shared, sandboxed session
```

<script>
document.body.addEventListener('htmx:configRequest', (event) => {
    if(event.detail.path.includes('://')) return;
    htmx.config.selfRequestsOnly=false;
    event.detail.path = `${location.protocol}//${location.hostname}:8000${event.detail.path}`;
});
</script>

    http://127.0.0.1:8000

`agent_tools(sess)` hands the model two functions, `list_vars` and `run_python`, both bound to the session. `conversation_logger(sess)` mirrors every turn into a transcript notebook. Wire them into a `Chat` and ask for some work:

``` python
from fastcore.docments import docstring
sp = f'You are a Python assistant. you have a persistent session defined by {docstring(AgentSession)} Use builtins where possible. import only once. dont run same code again. check globals check if a module before using it. numpy and pandas are always be avilable. Call list_vars before writing code. tools available: {docstring(agent_tools)}'; sp
```

    'You are a Python assistant. you have a persistent session defined by Sandboxed Python session over a shared owner namespace. You can read and access any owner variable freely; your writes land in your own layer and never touch the owner. Mutating or deleting owner variables is blocked. copy to a new name first (e.g. `df2 = df.copy()`, `lst2 = lst[:]`). Check available variables before writing code. Use builtins where possible. import only once. dont run same code again. check globals check if a module before using it. numpy and pandas are always be avilable. Call list_vars before writing code. tools available: Tools for a tool-calling agent over an AgentSession. `list_vars` shows what is available; call it first. `run_python` executes code in the session.'

``` python
from rishi import *
from litert_lm import set_min_log_severity, Backend
from dhrishti.agent import conversation_logger
from fastcore.docments import docstring
set_min_log_severity(5)

chat = Chat(model_id=gemma4_e4b, sp=sp, tools=agent_tools(sess), cbs=[conversation_logger(sess)], backend=Backend.GPU(),
            approve=hitl_policy({'list_vars':'approved', 'run_python':'approved'}))
chat('Scale the numeric columns of df to 0..1 as a new frame df_norm.')
```

    /Users/71293/code/personal/orgs/dhrishti/.venv/lib/python3.13/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
      from .autonotebook import tqdm as notebook_tqdm

The numeric columns of `df` have been successfully scaled to the range of 0 to 1, and the resulting DataFrame is stored in `df_norm`. The output shows the first few rows of `df_norm`, confirming the scaling has been applied to the numeric columns (`x` and `y` in the example output).

Now, the agent_session will have `df_norm` created.

``` python
sess.layer['df_norm']
```

<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }
&#10;    .dataframe tbody tr th {
        vertical-align: top;
    }
&#10;    .dataframe thead th {
        text-align: right;
    }
</style>

|     | x    | y   |
|-----|------|-----|
| 0   | 0.00 | a   |
| 1   | 0.25 | b   |
| 2   | 0.50 | c   |
| 3   | 0.75 | d   |
| 4   | 1.00 | e   |

</div>

`df_norm` is an agent variable. `df` is not modified.

``` python
list(sess.layer), list(df.columns)   # df_norm is the agent's; df keeps its original columns
```

    (['np', 'numeric_cols', 'df_norm', 'col', 'min_val', 'max_val'], ['x', 'y'])

You can see the variables modified live in the webui and the tui. you can even edit variables inline

![The live client](images/inspector-live.png)

You can see the whole transcript of a session as it’s stored as a notebook in `sess.log_path`

``` python
from fastcore.nbio import read_nb
from IPython.display import display, Markdown
def show(cells):
    for c in cells: display(Markdown(f"```python\n{c['source']}\n```" if c['cell_type'] == 'code' else c['source']))
show(read_nb(sess.log_path)['cells'])
```

**user**

Scale the numeric columns of df to 0..1 as a new frame df_norm.

``` python
# error: ModuleNotFoundError: No module named 'sklearn'
from sklearn.preprocessing import MinMaxScaler
import pandas as pd

# Identify numeric columns
numeric_cols = df.select_dtypes(include=['number']).columns

# Initialize the scaler
scaler = MinMaxScaler()

# Fit and transform the numeric data
# We need to reshape the data for the scaler (it expects a 2D array)
df_norm_numeric = scaler.fit_transform(df[numeric_cols])

# Create a new DataFrame with the scaled numeric data
df_norm_numeric = pd.DataFrame(df_norm_numeric, columns=numeric_cols, index=df.index)

# Combine the scaled numeric columns with any non-numeric columns from the original df
# Assuming all columns in df are numeric based on the initial inspection, 
# but this handles mixed types robustly.
df_norm = df.copy()
df_norm[numeric_cols] = df_norm_numeric

print("df_norm created successfully.")
print(df_norm.head())
```

``` python
import numpy as np

# Identify numeric columns
numeric_cols = df.select_dtypes(include=np.number).columns

# Create a copy of the original DataFrame to store the normalized values
df_norm = df.copy()

# Apply Min-Max scaling to each numeric column
for col in numeric_cols:
    min_val = df[col].min()
    max_val = df[col].max()
    
    # Handle the case where max_val == min_val to avoid division by zero
    if max_val - min_val == 0:
        df_norm[col] = 0.0  # Or 1.0, or keep original, but 0.0 is standard for constant features
    else:
        df_norm[col] = (df[col] - min_val) / (max_val - min_val)

print("df_norm created successfully using manual Min-Max scaling.")
print(df_norm.head())
```

**assistant**

The numeric columns of `df` have been successfully scaled to the range of 0 to 1, and the resulting DataFrame is stored in `df_norm`. The output shows the first few rows of `df_norm`, confirming the scaling has been applied to the numeric columns (`x` and `y` in the example output).

## What the agent can’t do

The session is sandboxed. The agent reads anything and binds its own names, but the moment it tries to change something you own, or reach for the filesystem or shell, the cell is refused and the reason comes back in place of a result.

``` python
print(sess.run("df['z'] = 0").error)   # mutating what you own is refused
print(sess.run("import shutil; shutil.rmtree('/nope')").error) # filesystem escapes are refused
list(df.columns)    # your df is exactly as it was
```

    blocked: cannot modify owner variable 'df' in place; bind your result to a new name instead
    blocked: 'shutil.rmtree' is a shell/filesystem escape and is not allowed in the agent session; use your own shell tool

    ['x', 'y']

## Promote what you want to keep

A [`Client`](https://vedicreader.github.io/dhrishti/tui.html#client) connects to the running server over HTTP. It can read the agent’s overlay and, with the owner token it picks up automatically, promote a variable the agent built into your own namespace.

``` python
from dhrishti.tui import Client

async def adopt():
    cli = Client(url)
    names = (await cli.agent_rows())['agent_names']   # what the agent has built
    res = await cli.promote(('df_norm',))             # adopt it into your namespace
    await cli.aclose()
    return names, res
run_coro(adopt())
```

    (['col', 'df_norm', 'max_val', 'min_val', 'np', 'numeric_cols'],
     {'ok': True, 'error': None})

``` python
'df_norm' in globals()   # now it is yours, and shows up in your own inspector
```

    True

## Learn more

The [documentation](https://vedicreader.github.io/dhrishti/) covers the inspection core, the serving layer, and the agent overlay in full.

dhrishti is built with [nbdev](https://nbdev.fast.ai): edit the notebooks under `nbs/`, then `nbdev_prepare` to compile the library, run tests, and rebuild the docs.
