Skip to content

Commit

Permalink
[Docs] Prepare docs for refactoring (#678)
Browse files Browse the repository at this point in the history
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Lingyi Zhang <[email protected]>
Co-authored-by: Jo Stichbury <[email protected]>
  • Loading branch information
4 people authored Sep 20, 2024
1 parent f1e68ae commit bb6a99f
Show file tree
Hide file tree
Showing 27 changed files with 560 additions and 258 deletions.
2 changes: 2 additions & 0 deletions .vale/styles/Microsoft/ignore.txt
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,5 @@ virginica
Hugging Face
dash_ag_grid
dash_data_table
Langchain
Langchain's
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<!--
A new scriv changelog fragment.
Uncomment the section that is right (remove the HTML comment wrapper).
-->

### Highlights ✨

- VizroAI now allows **any** `langchain` model with structured output capabilities to be used, not just `ChatOpenAI` ([#646](https://github.com/mckinsey/vizro/pull/646))
- VizroAI now has a more flexible output when choosing `VizroAI.plot(...,return_elements=True)`. See documentation for all new options. ([#646](https://github.com/mckinsey/vizro/pull/646))

### Removed

- Removed the automatic display of chart explanation and insights in Jupyter. ([#646](https://github.com/mckinsey/vizro/pull/646))

<!--
### Added
- A bullet item for the Added category with a link to the relevant PR at the end of your entry, e.g. Enable feature XXX ([#1](https://github.com/mckinsey/vizro/pull/1))
-->

### Changed

- Changed the return type of `VizroAI.plot(...,return_elements=True)` from `PlotOutputs` dataclass to a pydantic model with more flexible methods. See documentation for more into ([#646](https://github.com/mckinsey/vizro/pull/646))

### Deprecated

- Removed argument `explain` from VizroAI.plot(). Use `return_elements=True` instead. ([#646](https://github.com/mckinsey/vizro/pull/646))

<!--
### Fixed
- A bullet item for the Fixed category with a link to the relevant PR at the end of your entry, e.g. Enable feature XXX ([#1](https://github.com/mckinsey/vizro/pull/1))
-->
<!--
### Security
- A bullet item for the Security category with a link to the relevant PR at the end of your entry, e.g. Enable feature XXX ([#1](https://github.com/mckinsey/vizro/pull/1))
-->
Binary file modified vizro-ai/docs/assets/tutorials/chart/GermanExample.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added vizro-ai/docs/assets/user_guides/VizroAIVizro.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file removed vizro-ai/docs/assets/user_guides/vizro-ai-chart.gif
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion vizro-ai/docs/pages/explanation/safeguard.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Safeguard dynamic code execution in Vizro-AI

Vizro-AI uses the `exec()` statement in Python to run generated code from large language models (LLMs) for
self-debugging and automatic visual rendering in methods such as `vizro_ai._get_chart_code()` and `vizro_ai.plot()`.
self-debugging and automatic visual rendering in methods such as `.get_fig_object()` and `VizroAI.plot()`.
One of the primary concerns is the potential for malicious code to access or change critical system resources or data.

## Understand `exec()`
Expand Down
69 changes: 57 additions & 12 deletions vizro-ai/docs/pages/tutorials/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ To learn how to customize the `VizroAI` class, check out the guide on [how to cu
Finally, we call the `plot()` method with our English language instruction, to generate the visualization:

```python
vizro_ai.plot(df, "create a line graph for GDP per capita since 1950 for each continent. Mark the x axis as Year, y axis as GDP Per Cap and don't include a title")
vizro_ai.plot(
df,
"""create a line graph for GDP per capita since 1950 for
each continent. Mark the x axis as Year, y axis as GDP Per Cap
and don't include a title. Make sure to take average over continent.""",
)
```

!!! warning "Help! The LLM request was unauthorized"
Expand All @@ -82,18 +87,22 @@ vizro_ai.plot(df, "create a line graph for GDP per capita since 1950 for each co

And that's it! By passing the prepared data and written visualization request, Vizro-AI takes care of the processing. It generates the necessary code for data manipulation and chart creation, and returns the chart by executing the generated code.

!!! example "Vizro AI Syntax"
!!! example "Vizro-AI Syntax"

=== "Code for the cell"
```py
from vizro_ai import VizroAI
import vizro.plotly.express as px
from vizro_ai import VizroAI

df = px.data.gapminder()

vizro_ai = VizroAI()
fig = vizro_ai.plot(df, "create a line graph for GDP per capita since 1950 for each continent. Mark the x axis as Year, y axis as GDP Per Cap and don't include a title", explain=True)
fig.show()
vizro_ai = VizroAI(model="gpt-4-turbo")
fig = vizro_ai.plot(
df,
"""create a line graph for GDP per capita since 1950 for each continent.
Mark the x axis as Year, y axis as GDP Per Cap and don't include a title.
Make sure to take average over continent.""",
)
```
=== "Result"
[![LineGraph]][LineGraph]
Expand All @@ -102,7 +111,7 @@ And that's it! By passing the prepared data and written visualization request, V

The chart created is interactive: you can hover over the data for more information.

Passing `explain=True` to the `plot()` method returns the code to create the chart, along with a set of insights to explain the rendered chart in detail. You can then use the code within a Vizro dashboard as illustrated in the [Vizro documentation](https://vizro.readthedocs.io/en/stable/pages/tutorials/explore-components/#22-add-further-components). For the line graph above, the code returned is as follows:
Passing `return_elements=True` to the `plot()` method returns an object, which includes the code along with a set of insights to explain the rendered chart in detail. You can then use the code within a Vizro dashboard as illustrated in the [Vizro documentation](https://vizro.readthedocs.io/en/stable/pages/tutorials/explore-components/#22-add-further-components). For the line graph above, the code returned may be as follows:

!!! example "Returned by Vizro-AI"

Expand All @@ -123,17 +132,53 @@ Passing `explain=True` to the `plot()` method returns the code to create the cha
### 4. Get an explanation with your chart
<!-- vale on -->

Let's create another example to illustrate the code and insights returned when passing `explain=True` as a parameter to `plot()`:
Let's create another example to illustrate the code and insights returned when passing `return_elements=True` as a parameter to `plot()`:

!!! example "Specify `explain=True`"
!!! example "Specify `return_elements=True`"

=== "Code for the cell"
```py
fig = vizro_ai.plot(df, "show me the geo distribution of life expectancy", explain=True)
fig.show()
res = vizro_ai.plot(df, "show me the geo distribution of life expectancy", return_elements=True)
print(res.code)
print(res.chart_insights)
print(res.code_explanation)
```
=== "Result"
[![GeoDistribution]][GeoDistribution]
Code
```py
import plotly.express as px


def custom_chart(data_frame):
fig = px.choropleth(
data_frame,
locations="iso_alpha",
color="lifeExp",
hover_name="country",
color_continuous_scale=px.colors.sequential.Plasma,
labels={"lifeExp": "Life Expectancy"},
)
fig.update_layout(
title="Global Life Expectancy Distribution",
geo=dict(showframe=False, showcoastlines=True),
)
return fig
```
Chart insights
```
This choropleth map visualizes the global distribution of life expectancy across
different countries. It highlights variations and trends in life expectancy,
providing a clear visual representation of geographical disparities.
```
Code explanation
```
- Import Plotly Express.
- Create a choropleth map using the `px.choropleth` function.
- Set the `locations` parameter to the ISO alpha codes from the data.
- Color the map based on life expectancy values.
- Use a continuous color scale to represent different life expectancies.
- Update layout to enhance map readability and aesthetics.
```

[GeoDistribution]: ../../assets/tutorials/chart/GeoDistribution.png

Expand Down
95 changes: 52 additions & 43 deletions vizro-ai/docs/pages/user-guides/add-generated-chart-usecase.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This guide explains the different ways in which you can add a chart generated by

1. Create a chart with Vizro-AI that you would like to visualize in a dashboard.

In this example, we aim to create a chart that illustrates the population development of each continent over time. To gain deeper insights and access the underlying code responsible for generating the chart, include `explain=True` in the `plot()` method. Let's execute the provided code and examine the outcome.
In this example, we aim to create a chart that illustrates the population development of each continent over time. To gain deeper insights and access the underlying code responsible for generating the chart, include `return_elements=True` in the `plot()` method. Let's execute the provided code and examine the outcome.

!!! example "Vizro-AI chart"

Expand All @@ -20,38 +20,44 @@ This guide explains the different ways in which you can add a chart generated by
load_dotenv()

df = px.data.gapminder()
vizro_ai = VizroAI(model="gpt-4-0613")

fig = vizro_ai.plot(df,
"""Plot a bubble chart to show the changes in life expectancy
and GDP per capita for each country over time.
Color the bubbles by continent.
Add animation on yearly basis, and do not use facets.
Put the legend on top""", explain=True)
fig.show()
vizro_ai = VizroAI(model="gpt-4o")

result = vizro_ai.plot(df,
"""Plot a bubble chart to show the changes in life expectancy
and GDP per capita for each country over time.
Color the bubbles by continent.
Add animation on yearly basis, and do not use facets.
Put the legend on top""", return_elements=True)

print(f"Insight:\n{result.chart_insights}\n" )
print(f"Code explanation:\n{result.code_explanation}\n\nCode:\n{result.code_vizro}\n" )
result.get_fig_object(df).show()
```
=== "Result"
[![VizroAIChart]][VizroAIChart]

[VizroAIChart]: ../../assets/user_guides/vizro-ai-chart.gif
[VizroAIChart]: ../../assets/user_guides/vizro-ai-chart.png

2. Insert the resulting chart into a dashboard.

Once you are satisfied with the chart, you can add it to a [Vizro](https://github.com/mckinsey/vizro/tree/main/vizro-core) dashboard. In the explanation section from the result of the example above, you'll find the code snippet used to generate the chart.
Once you are satisfied with the chart, you can add it to a [Vizro](https://github.com/mckinsey/vizro/tree/main/vizro-core) dashboard.

```py
@capture('graph')
def custom_chart(data_frame=pd.DataFrame()):
# Create a bubble chart
fig = px.scatter(data_frame, x='gdpPercap', y='lifeExp', animation_frame='year', animation_group='country',
size='pop', color='continent', hover_name='country', log_x=True, size_max=60,
range_y=[20,90],
labels={'gdpPercap':'GDP per Capita', 'lifeExp':'Life Expectancy', 'year':'Year', 'continent':'Continent', 'pop':'Population'},
title='Life Expectancy v. Per Capita GDP, 1952-2007',
height=400)
# Put the legend on top
fig.update_layout(legend=dict(y=1, yanchor='top', x=0.5, xanchor='center'))
# Return the plot
@capture("graph")
def custom_chart(data_frame):
fig = px.scatter(
data_frame,
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
animation_frame="year",
hover_name="country",
size_max=60,
)
fig.update_layout(
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
)
return fig
```

Expand All @@ -60,26 +66,29 @@ This object must then be passed to the `figure` argument of the Vizro [Graph](ht

!!! example "Vizro-AI chart within vizro dashboard"
=== "Code for the cell"
```py
```py hl_lines="8-23 31"
from vizro import Vizro
import vizro.models as vm
from vizro.models.types import capture
import pandas as pd
import vizro.plotly.express as px


@capture('graph')
def custom_chart(data_frame=pd.DataFrame()):
# Create a bubble chart
fig = px.scatter(data_frame, x='gdpPercap', y='lifeExp', animation_frame='year', animation_group='country',
size='pop', color='continent', hover_name='country', log_x=True, size_max=60,
range_y=[20,90],
labels={'gdpPercap':'GDP per Capita', 'lifeExp':'Life Expectancy', 'year':'Year', 'continent':'Continent', 'pop':'Population'},
title='Life Expectancy v. Per Capita GDP, 1952-2007',
height=400)
# Put the legend on top
fig.update_layout(legend=dict(y=1, yanchor='top', x=0.5, xanchor='center'))
# Return the plot
@capture("graph")
def custom_chart(data_frame):
fig = px.scatter(
data_frame,
x="gdpPercap",
y="lifeExp",
size="pop",
color="continent",
animation_frame="year",
hover_name="country",
size_max=60,
)
fig.update_layout(
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
)
return fig


Expand All @@ -98,12 +107,12 @@ This object must then be passed to the `figure` argument of the Vizro [Graph](ht
vm.Filter(column='country'),
vm.Filter(column='continent')])

Vizro().build(vm.Dashboard(pages=[page])).run(port=8000)
Vizro().build(vm.Dashboard(pages=[page])).run(port=8090)
```
=== "Result"
[![VizroDashboard]][VizroDashboard]

[VizroDashboard]: ../../assets/user_guides/chart_into_dashboard_large.gif
[VizroDashboard]: ../../assets/user_guides/chart_into_dashboard_large.png


## Use Vizro-AI dynamically to return a `fig` object
Expand All @@ -117,7 +126,7 @@ Executing the code below yields the identical dashboard as the example above.

!!! example "Use Vizro-AI fig directly in vizro dashboard"
=== "Code for the cell"
```py
```py hl_lines="13-18 23"
from vizro import Vizro
import vizro.models as vm
import pandas as pd
Expand All @@ -128,7 +137,7 @@ Executing the code below yields the identical dashboard as the example above.
from dotenv import load_dotenv
load_dotenv()
df = px.data.gapminder()
vizro_ai = VizroAI(model="gpt-4-0613")
vizro_ai = VizroAI(model="gpt-4o")

fig = vizro_ai.plot(df,
"""Plot a bubble chart to show the changes in life expectancy
Expand All @@ -150,9 +159,9 @@ Executing the code below yields the identical dashboard as the example above.
vm.Filter(column='country'),
vm.Filter(column='continent')])

Vizro().build(vm.Dashboard(pages=[page])).run(port=8000)
Vizro().build(vm.Dashboard(pages=[page])).run(port=8090)
```
=== "Result"
[![VizroDashboard2]][VizroDashboard2]

[VizroDashboard2]: ../../assets/user_guides/chart_into_dashboard_2.gif
[VizroDashboard2]: ../../assets/user_guides/chart_into_dashboard_large.png
Loading

0 comments on commit bb6a99f

Please sign in to comment.