Package: chat2plot
📈 Chat2Plot - interactive & safe text-to-visualization with LLMThis library uses LLMs to generate:VisualizationHigh-level chart specifications in json (You can choose between a simple or vega-lite format)Explanationfrom natural language requests for given data.Chat2Plot does not generate executable code or SQL from the LLM,
so you can safely generate visualizations.demo:https://chat2plot-sample.streamlit.app/Quick Startpipinstallchat2plotimportosimportpandasaspdfromchat2plotimportchat2plot# 1. Set api-keyos.environ["OPENAI_API_KEY"]="..."df=pd.read_csv(...)# 2. Pass a dataframe to drawc2p=chat2plot(df)# 3. Make a question about the dataresult=c2p("average target over countries")result.figure.show()# draw a plotprint(result.config)# get a config (json / dataclass)print(result.explanation)# see the explanation generated by LLM# you can make follow-up request to refine the chartresult=c2p("change to horizontal-bar chart")result.figure.show()Why Chat2Plot?Inside Chat2Plot, LLM does not generate Python code,
but generates plot specifications in json.The declarative visualization specification in json is transformed into actual charts in
Chat2Plot using plotly or altair, but users can also use json directly in their own applications.This design limits the visualization expression compared to Python code generation
(such as ChatGPT's Code Interpreter Plugin), but has the following practical advantages:SecureMore secure execution, as LLM does not directly generate code.Language-independentDeclarative data structures are language-agnostic, making it easy to plot in non-Python environments.InteractiveDeclarative data can be modified by the user to improve plots through collaborative work between the user and LLM.By default, chat2plot usesfunction calling API.ExamplesCustom language modelsgpt-3.5-turbo-0613is used by default, but you can use other language models.importpandasaspdfromlangchain.chat_modelsimportAzureChatOpenAIfromchat2plotimportchat2plotplot=chat2plot(pd.DataFrame(),chat=AzureChatOpenAI())ret=plot.query("<your query>")Vega-lite formatimportpandasaspdfromchat2plotimportchat2plotplot=chat2plot(pd.DataFrame(),schema_definition="vega")ret=plot.query("<your query>")assertisinstance(ret.config,dict)# vega-lite formatprint(ret.config)Custom chart definitionimportpydanticimportpandasaspdfromchat2plotimportchat2plotclassCustomChartConfig(pydantic.BaseModel):chart_type:strx_axis_name:stry_axis_name:stry_axis_aggregate:strplot=chat2plot(pd.DataFrame(),schema_definition=CustomChartConfig)ret=plot.query("<your query>")# chat2plot treats the data type you pass as a chart settingassertisinstance(ret.config,CustomChartConfig)Specifying output languageYou can specify in which language the chart explanations should be output.
If not specified, it will return as much as possible in the same language as the user's question,
but this option is often useful if you always want output in a specific language.importpandasaspdfromchat2plotimportchat2plotplot=chat2plot(pd.DataFrame(),language="Chinese")ret=plot.query("<your query>")print(ret.explanation)# explanationPrivacy preservingWhendescription_strategy="dtypes"is specified, chat2plot will not send the data
content (but just column names) to LLM.importpandasaspdfromlangchain.chat_modelsimportAzureChatOpenAIfromchat2plotimportchat2plotplot=chat2plot(pd.DataFrame(),description_strategy="dtypes")ret=plot.query("<your query>")APIAChat2Plotinstance can be created using thechat2plotfunction.defchat2plot(df:pd.DataFrame,schema_definition:Literal["simple","vega"]|Type[pydantic.BaseModel]="simple",chat:BaseChatModel|None=None,function_call:bool|Literal["auto"]="auto",language:str|None=None,description_strategy:str="head",custom_deserializer:ModelDeserializer|None=None,verbose:bool=False,)->Chat2PlotBase:df- Data source for visualization.schema_definition(optional) - Type of json format.vega- A vega-lite compliant formatsimple- chat2plot's built-in format, parsed aschat2plot.PlotConfigIf you want chat2plot to generate chart definitions according to your own defined schema,
you can pass any type that extends pydantic.BaseModel instead of these two options.chat(optional) - The chat instance for interaction with LLMs.
If omitted,ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo-0613")will be used.function_call(optional) - Specifies whether to use thefunction calling API.
If omitted, it is automatically determined based on the underlying model type.language(optional) - Language of explanations. If not specified, it will be automatically inferred from user prompts.description_strategy(optional) - Type of how the information in the dataset is embedded in the prompt.head- senddf.head(5)to LLMs.dtypes- senddf.dtypesto LLMs. This can be used when you do not want to send contents ofdfto LLMs.custom_deserializer(optional) - Specifies a custom deserializer to convert json returned from the LLM into a chart configuration.verbose(optional) - IfTrue, chat2plot will output logs.Once an instance is created, a graph generation request can be made
by callingquerymethod, or simply passing the same arguments to the instance (__call__).defquery(self,q:str,config_only:bool=False,show_plot:bool=False)->Plot:q- A query string.config_only- IfTrue, skip generating figure.show_plot- IfTrue, showing the generated figure is also performed inside chat2plot.The default behavior isconfig_only=Falseandshow_plot=False,
i.e. Chat2Plot generates a figure as well as configuration, but does not draw it.Thequerymethod returnsPlotobject, and this has the following properties:@dataclass(frozen=True)classPlot:figure:alt.Chart|Figure|Noneconfig:PlotConfig|dict[str,Any]|Noneresponse_type:ResponseTypeexplanation:strconversation_history:list[langchain.schema.BaseMessage]|Nonefigure- The generated figure (chart).config- The chart specification. Returns dict forvegamode andPlotConfigforsimplemode.response_type- The result code of the response.explanation- Reason for the chart setup, generated by LLMs.conversation_history- Full history of conversation (including retry prompt).