前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >构建数据可视化代理(Plotly)

构建数据可视化代理(Plotly)

作者头像
云云众生s
发布于 2024-05-30 05:07:07
发布于 2024-05-30 05:07:07
19100
代码可运行
举报
文章被收录于专栏:云云众生s云云众生s
运行总次数:0
代码可运行

Plotly 是我最喜欢的数据可视化库。在广泛撰写有关使用 Plotly 创建高级可视化的文章后,我产生了好奇:我能否通过仅提供 dataframe 和自然语言指令来教语言模型构建我喜欢的可视化?本项目就是尝试此想法的成果,我很高兴与你分享结果。

译自 Building an Agent for Data Visualization (Plotly),作者 Arslan Shahid。

为什么构建代理?

如果你曾尝试过 ChatGPTLLM,你就会知道它们可以为几乎任何语言或包生成代码。但是,仅依赖 LLM 存在局限性。以下是通过构建代理我旨在解决的一些关键问题:

  1. 描述你的数据:LLM 本质上不知道你的数据集的具体信息,例如列名称和行详细信息。手动提供此信息可能很麻烦,尤其是在数据集变大时。如果没有此上下文,LLM 可能会产生幻觉或发明列名称,从而导致数据可视化中的错误。
  2. 样式和偏好:数据可视化是一种艺术形式,每个人都有独特的审美偏好,这些偏好因图表类型和信息而异。为每个可视化持续向 LLM 提供详细说明很乏味。配备了样式信息的代理可以简化此过程,确保一致且个性化的视觉输出。
  3. 代理推理:ReAct 代理具有“推理”和执行任务的能力,从而产生更准确的响应和更少的幻觉。这种高级提示工程技术已被证明可以产生更强大、更可靠的结果。你可以在此 论文 中阅读有关 ReAct 代理的更多信息。

构建代理可以缓解这些问题,为数据可视化和其他任务提供更高效、更定制的方法。

下面你可以看到当我告诉 Llama3:70B(我为最终代理使用的 LLM)构建可视化时的基线。

作者图片——用70B 模型询问 Groq,它为数据创建的假名,下面可以看到可视化

作者图片 — 当我修复Llama3制作的一些错误时,可视化看起来是这样。不是一个好的输出

设计

要构建此应用程序,我们需要为 LLM 代理配备两个工具,以便帮助它生成更好的数据可视化。一个工具提供有关数据集的信息,另一个工具包含有关样式的信息。

Llama-index 允许将任何查询引擎用作代理工具。由于这两个工具都涉及信息检索,因此查询引擎工具适合我们的需求。

dataframe 索引

此工具的目的是分析 dataframe 并将其内容信息存储到索引中。要编制索引的数据包括列名称、数据类型以及值的最小、最大和平均范围。这有助于代理了解他们正在处理的变量类型。

在此示例中,使用了 layoff.fyi 中的数据。但是,该工具可以与任何 dataframe 一起使用。

预处理

预处理至关重要,并且因数据集而异。建议将数据转换为适当的类型(例如,将数字字符串转换为整数或浮点数)并删除空值。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#Optional pre-processing
import pandas as pd
import numpy as np


df = pd.read_csv('WARN Notices California_Omer Arain - Sheet1.csv')

#Changes date like column into datetime 
df['Received Date'] = [pd.to_datetime(x) for x in df['Received Date']]
df['Effective Date'] = [pd.to_datetime(x) for x in df['Effective Date']]
#Converts numbers stored as strings into ints
df['Number of Workers'] = [int(str(x).replace(',','')) if str(x)!='nan' else np.nan for x in df['Number of Workers']]
# Replacing NULL values
df = df.replace(np.nan,0)

将数据集信息存储到索引

以下是如何实现 DataFrame 索引

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from llama_index.core.readers.json import JSONReader
from llama_index.core import VectorStoreIndex
import json

# Function that stores the max,min & mean for numerical values
def return_vals(df,c):
    if isinstance(df[c].iloc[0], (int, float, complex)):
        return [max(df[c]), min(df[c]), np.mean(df[c])]
# For datetime we need to store that information as string
    elif(isinstance(df[c].iloc[0],datetime.datetime)):
        return [str(max(df[c])), str(min(df[c])), str(np.mean(df[c]))]
    else:
# For categorical variables you can store the top 10 most frequent items and their frequency
        return list(df[c].value_counts()[:10])

# declare a dictionary 
dict_ = {}
for c in df.columns:
# storing the column name, data type and content
  dict_[c] = {'column_name':c,'type':str(type(df[c].iloc[0])), 'variable_information':return_vals(df,c)}
# After looping storing the information as a json dump that can be loaded 
# into a llama-index Document

# Writing the information into dataframe.json 

with open("dataframe.json", "w") as fp:
    json.dump(dict_ ,fp) 


reader = JSONReader()
# Load data from JSON file
documents = reader.load_data(input_file='dataframe.json')

# Creating an Index
dataframe_index =  VectorStoreIndex.from_documents(documents)

样式索引

样式工具作为文档存储,其中包含有关如何使用 plotly 样式不同图表自然语言说明。我鼓励你尝试给出的不同说明。以下是有关如何构建折线图和条形图的说明!

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from llama_index.core import Document
from llama_index.core import VectorStoreIndex

styling_instructions =[Document(text="""
  Dont ignore any of these instructions.
        For a line chart always use plotly_white template, reduce x axes & y axes line to 0.2 & x & y grid width to 1. 
        Always give a title and make bold using html tag axis label and try to use multiple colors if more than one line
        Annotate the min and max of the line
        Display numbers in thousand(K) or Million(M) if larger than 1000/100000 
        Show percentages in 2 decimal points with '%' sign
        """
        )
        , Document(text="""
        Dont ignore any of these instructions.
        For a bar chart always use plotly_white template, reduce x axes & y axes line to 0.2 & x & y grid width to 1. 
        Always give a title and make bold using html tag axis label and try to use multiple colors if more than one line
        Always display numbers in thousand(K) or Million(M) if larger than 1000/100000. Add annotations x values
        Annotate the values on the y variable
        If variable is a percentage show in 2 decimal points with '%' sign.
        """)


       # You should fill in instructions for other charts and play around with these instructions
       , Document(text=
          """ General chart instructions
        Do not ignore any of these instructions
         always use plotly_white template, reduce x & y axes line to 0.2 & x & y grid width to 1. 
        Always give a title and make bold using html tag axis label 
        Always display numbers in thousand(K) or Million(M) if larger than 1000/100000. Add annotations x values
        If variable is a percentage show in 2 decimal points with '%'""")
         ]
# Creating an Index
style_index =  VectorStoreIndex.from_documents(styling_instructions)

构建代理

创建的索引需要基于代理作为工具。Llama-Index 具有可从索引构建查询引擎并将其用作工具的功能。

图片作者 — 解释 Agent 的工作原理

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#All imports for this section
from llama_index.core.agent import ReActAgent
from llama_index.core.tools import QueryEngineTool
from llama_index.core.tools import  ToolMetadata
from llama_index.llms.groq import Groq


# Build query engines over your indexes
# It makes sense to only retrieve one document per query 
# However, you may play around with this if you need multiple charts
# Or have two or more dataframes with similar column names
dataframe_engine = dataframe_index.as_query_engine(similarity_top_k=1)
styling_engine = style_index.as_query_engine(similarity_top_k=1)

# Builds the tools
query_engine_tools = [
    QueryEngineTool(
        query_engine=dataframe_engine,
# Provides the description which helps the agent decide which tool to use 
        metadata=ToolMetadata(
            name="dataframe_index",
            description="Provides information about the data in the data frame. Only use column names in this tool",
        ),
\
    ),
    QueryEngineTool(
# Play around with the description to see if it leads to better results
        query_engine=styling_engine,
        metadata=ToolMetadata(
            name="Styling",
            description="Provides instructions on how to style your Plotly plots"
            "Use a detailed plain text question as input to the tool.",
        ),
    ),
]

# I used open-source models via Groq but you can use OpenAI/Google/Mistral models as well
llm = Groq(model="llama3-70b-8192", api_key="<your_api_key>")

# initialize ReAct agent
agent = ReActAgent.from_tools(query_engine_tools, llm=llm, verbose=True)

调整 Agent 提示

Llama-Index 和其他编排包具有默认提示,这些提示可能不适用于你的特定用例。在反复试验时我发现,稍微调整提示有助于防止出现幻觉。

作者图片——这是 ReAct Agent 的默认提示语

图片来自作者——调整提示,以黄色突出显示所做的更改

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from llama_index.core import PromptTemplate

new_prompt_txt= """You are designed to help with building data visualizations in Plotly. You may do all sorts of analyses and actions using Python

## Tools

You have access to a wide variety of tools. You are responsible for using the tools in any sequence you deem appropriate to complete the task at hand.
This may require breaking the task into subtasks and using different tools to complete each subtask.

You have access to the following tools, use these tools to find information about the data and styling:
{tool_desc}


## Output Format

Please answer in the same language as the question and use the following format:

\`\`\`
Thought: The current language of the user is: (user's language). I need to use a tool to help me answer the question.
Action: tool name (one of {tool_names}) if using a tool.
Action Input: the input to the tool, in a JSON format representing the kwargs (e.g. {{"input": "hello world", "num_beams": 5}})
\`\`\`

Please ALWAYS start with a Thought.

Please use a valid JSON format for the Action Input. Do NOT do this {{'input': 'hello world', 'num_beams': 5}}.

If this format is used, the user will respond in the following format:

\`\`\`
Observation: tool response
\`\`\`

You should keep repeating the above format till you have enough information to answer the question without using any more tools. At that point, you MUST respond in the one of the following two formats:

\`\`\`
Thought: I can answer without using any more tools. I'll use the user's language to answer
Answer: [your answer here (In the same language as the user's question)]
\`\`\`

\`\`\`
Thought: I cannot answer the question with the provided tools.
Answer: [your answer here (In the same language as the user's question)]
\`\`\`

## Current Conversation

Below is the current conversation consisting of interleaving human and assistant messages."""

# Adding the prompt text into PromptTemplate object
new_prompt = PromptTemplate(new_prompt_txt)

# Updating the prompt
agent.update_prompts({'agent_worker:system_prompt':new_prompt})

可视化

现在进入有趣的部分,在第一部分中,我展示了 Llama 3 如何响应我构建可视化的请求。现在让我们向代理提出类似的请求。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
response = agent.chat("Give Plotly code for a line chart for Number of Workers get information from the dataframe about the correct column names and make sure to style the plot properly and also give a title")

作者图片 — 你可以了解代理如何分解请求,并在最后用 Python 代码做出响应(你可以直接生成输出解析器,或复制并运行)

作者图片 — 通过运行以下代码创建的图表,注释、标签/标题、轴格式完全按照样式化信息进行。并且不会构成数据,因为它已经包含了关于 dataframe 的信息。

不断围绕样式指令和代理提示进行调整可以产生更好的回复。该项目还有很长的路要走!然而,它可以帮助你节省时间并提供更好的可视化代码。

后续步骤

该项目的下一阶段涉及优化提示和处理常见的故障用例。最终目标是制作一套代理工具,可以帮助我(作为数据科学家)在工作时节省时间。如果您喜欢这个概念,请在 Medium 上关注我。

感谢您的阅读!

相关文章:

  1. LangChain:2023 年最流行的 Web 框架,这要归功于 AI
  2. 低代码生成式AI:让AI更容易的新解决方案
  3. 人工智能代理需要Code Interpreter的4个原因
  4. LLM 如何转变企业应用
  5. 当云遇见智能:推理AI即服务
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-05-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
使用Llama index构建多代理 RAG
检索增强生成(RAG)已成为增强大型语言模型(LLM)能力的一种强大技术。通过从知识来源中检索相关信息并将其纳入提示,RAG为LLM提供了有用的上下文,以产生基于事实的输出。
deephub
2023/10/31
1.2K0
使用Llama index构建多代理 RAG
LlamaIndex 应用完整指南
LlamaIndex 是一个强大的框架,专门用于构建基于LLM的数据应用。它的主要目标是帮助开发者创建能够与私有数据交互的LLM应用。
@小森
2025/03/05
3280
LlamaIndex 应用完整指南
「翻译」使用 Llama-index 实现的 Agentic RAG-Router Query Engine
你是否也厌倦了我在博文中经常提到的老式 RAG(Retrieval Augmented Generation | 检索增强生成) 系统?反正我是对此感到厌倦了。但我们可以做一些有趣的事情,让它更上一层楼。接下来就跟我一起将 agents 概念引入传统的 RAG 工作流,重新构建自己的 Agentic RAG 系统吧。
Ryoma
2024/06/14
5840
「翻译」使用 Llama-index 实现的 Agentic RAG-Router Query Engine
使用Llama-3生成PowerPoint
在企业界,幻灯片无处不在,它通常被用作传达想法和成就的一种方式。过去 4 年,我一直在为大型跨国公司工作,制作幻灯片是大多数人每周都会做的事情。
云云众生s
2024/04/30
6250
使用Llama-3生成PowerPoint
PhiData 一款开发AI搜索、agents智能体和工作流应用的AI框架
在人工智能领域,构建一个能够理解并响应用户需求的智能助手是一项挑战性的任务。PhiData作为一个开源框架,为开发者提供了构建具有长期记忆、丰富知识和强大工具的AI助手的可能性。本文将介绍PhiData的核心优势、应用示例以及如何使用PhiData来构建自己的AI助手。
JadePeng
2024/05/25
2.9K0
PhiData 一款开发AI搜索、agents智能体和工作流应用的AI框架
通过4个任务比较LangChain和LlamaIndex
我们在本地使用大模型的时候,尤其是构建RAG应用的时候,一般会有2个成熟的框架可以使用
deephub
2024/01/29
2K0
通过4个任务比较LangChain和LlamaIndex
抽象推理链CoA能否增强RAG应用对用户问题的理解?
自从在《蚂蚁开源新RAG框架KAG,可达91%准确率》中提到蚂蚁集团使用 CoA 来推理问题后,我就一直心痒难耐,想亲自试试这种 CoA(Chain of Actions)在问题理解和工具调用中的实际表现。好多文章在说明高级RAG时候,我们应该尝试查询重写,扩展,分解。但实际写下来并不好用,那么CoA能否用来做用户问题理解呢?
AgenticAI
2025/03/18
810
抽象推理链CoA能否增强RAG应用对用户问题的理解?
DeepSeek从云端模型部署到应用开发-03-实战指南:从部署到RAG Agent
Ollama理论上不刚需显存,只需要有足够的内存(RAM),基础版环境刚好卡到门槛,但是为了优化使用体验,建议通过V100 16GB启动项目,而且每日运行项目就送8算力点!!!
用户2225445
2025/03/15
1180
DeepSeek从云端模型部署到应用开发-03-实战指南:从部署到RAG Agent
整合LlamaIndex与LangChain构建高级的查询处理系统
构建大型语言模型应用程序可能会颇具挑战,尤其是当我们在不同的框架(如Langchain和LlamaIndex)之间进行选择时。LlamaIndex在智能搜索和数据检索方面的性能令人瞩目,而LangChain则作为一个更加通用的应用程序框架,提供了更好的与各种平台的兼容性。
deephub
2024/05/22
3980
整合LlamaIndex与LangChain构建高级的查询处理系统
可视化FAISS矢量空间并调整RAG参数提高结果精度
随着开源大型语言模型的性能不断提高,编写和分析代码、推荐、文本摘要和问答(QA)对的性能都有了很大的提高。但是当涉及到QA时,LLM通常会在未训练数据的相关的问题上有所欠缺,很多内部文件都保存在公司内部,以确保合规性、商业秘密或隐私。当查询这些文件时,会使得LLM产生幻觉,产生不相关、捏造或不一致的内容。
deephub
2024/03/01
4580
可视化FAISS矢量空间并调整RAG参数提高结果精度
👾打开 RAG 对接大模型的黑盒 —— 9 大隐藏问题
前一段时间,各个大模型在争斗:谁能携带更长、更大的上下文 Prompt,比如 Kimi 说 200 万字,阿里通义千问又说自己能达 1000 万字;大家都知道 Prompt 很重要,但是 RAG 和 长的上下文文本携带 是两个不同的技术方向。
掘金安东尼
2024/04/04
4510
👾打开 RAG 对接大模型的黑盒 —— 9  大隐藏问题
使用UMAP降维可视化RAG嵌入
大型语言模型(LLMs)如 GPT-4 已经展示了出色的文本理解和生成能力。但它们在处理领域特定信息方面面临挑战,比如当查询超出训练数据范围时,它们会产生错误的答案。LLMs 的推理过程也缺乏透明度,使用户难以理解达成结论的方式。
deephub
2024/02/21
3350
使用UMAP降维可视化RAG嵌入
如何评估 RAG 应用的质量?最典型的方法论和评估工具都在这里了
随着 LLM(Large Language Model)的应用逐渐普及,人们对 RAG(Retrieval Augmented Generation)场景的关注也越来越多。然而,如何定量评估 RAG 应用的质量一直以来都是一个前沿课题。
Zilliz RDS
2024/01/04
6.1K0
如何评估 RAG 应用的质量?最典型的方法论和评估工具都在这里了
ReACT介绍与llama_index ReActAgent实践
Agent是大模型的重要应用方向,而ReACT是学术界提出的重要方法,本文介绍ReACT论文,然后通过llama_index ReActAgent来分析ReACT的执行过程。
JadePeng
2024/03/14
8480
ReACT介绍与llama_index ReActAgent实践
LLMLingua:集成LlamaIndex,对提示进行压缩,提供大语言模型的高效推理
大型语言模型(llm)的出现刺激了多个领域的创新。但是在思维链(CoT)提示和情境学习(ICL)等策略的驱动下,提示的复杂性不断增加,这给计算带来了挑战。这些冗长的提示需要大量的资源来进行推理,因此需要高效的解决方案,本文将介绍LLMLingua与专有的LlamaIndex的进行集成执行高效推理。
deephub
2023/11/27
8090
LLMLingua:集成LlamaIndex,对提示进行压缩,提供大语言模型的高效推理
AI大模型全栈工程师课程笔记 - LangChain
LangChain 也是面向LLM的开发框架SDK,有 python 和 js 版的 https://python.langchain.com/docs/get_started
Michael阿明
2023/12/21
1.5K0
AI大模型全栈工程师课程笔记 - LangChain
LLM的测试工具:LaVague平替成国内大模型
LaVague 通过LLM将自然语言转换Selenium的代码引擎,用户或其他人工智能轻松实现自动化。 LaVague通过Llama Index实现了自然语言到python的selenium代码的编写能力,例子中提供了在线调用huggingface的LLM以及本地LLM两种方式,在线调用huggingface的Nous-Hermes-2-Mixtral-8x7B-DPO模型和BAAI/bge-small-en-v1.5的embedding模型实现了上面代码生成,但是要试用huggingface的api必须是pro付费会员,而且访问起来也不方便。 本地大模型的方式需要将模型现在到本地,并且在本地的显里面,那么开发笔记本就需要一个顶级配置的显卡,笔者也没办法解决。 想要尝鲜,怎么办?
Criss@陈磊
2024/03/20
6220
LLM的测试工具:LaVague平替成国内大模型
使用 LlamaIndex 和 Llama 2-Chat 构建知识驱动的对话应用程序
从大量文本中解锁准确且富有洞察力的答案是大型语言模型 (LLM) 所实现的一项令人兴奋的功能。在构建 LLM 应用程序时,通常需要连接和查询外部数据源以为模型提供相关上下文。一种流行的方法是使用检索增强生成(RAG)来创建问答系统,该系统可以理解复杂的信息并对查询提供自然的响应。 RAG 允许模型利用庞大的知识库,并为聊天机器人和企业搜索助手等应用程序提供类似人类的对话。
Maynor
2024/05/26
3690
使用 LlamaIndex 和 Llama 2-Chat 构建知识驱动的对话应用程序
如何从文档创建 RAG 评估数据集
通过上传 PDF 文件并将其存储在矢量数据库中,我们可以通过矢量相似性搜索检索这些知识,然后将检索到的文本作为附加上下文插入到 LLM 提示中。
致Great
2025/01/03
4870
如何从文档创建 RAG 评估数据集
如何通过 LlamaIndex 将数据导入 Elasticsearch
本文将介绍如何使用 LlamaIndex 将数据索引到 Elasticsearch 中,以实现 FAQ 搜索引擎。Elasticsearch 将作为我们的向量数据库,支持向量搜索,而 RAG(检索增强生成)将丰富搜索上下文,提供更准确的响应。
点火三周
2025/03/05
1180
如何通过 LlamaIndex 将数据导入 Elasticsearch
推荐阅读
相关推荐
使用Llama index构建多代理 RAG
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档