生成数据智能

使用 Amazon Bedrock 和 Amazon Location Service 进行地理空间生成 AI | 亚马逊网络服务

日期:

如今,地理空间工作流程通常包括加载数据、转换数据,然后生成地图、文本或图表等可视化见解。生成式人工智能可以通过自主的方式自动执行这些任务 中介代理。在这篇文章中,我们讨论如何使用基础模型 亚马逊基岩 为代理完成地理空间任务提供动力。这些代理可以使用基于位置的服务(例如可通过以下方式获得的地理编码)执行各种任务并回答问题 亚马逊定位服务。我们还分享了使用代理桥接 Amazon Bedrock 与 Amazon Location 功能的示例代码。此外,我们还讨论了构建它的设计注意事项。

Amazon Bedrock 是一项完全托管的服务,提供易于使用的 API,用于访问文本、图像和嵌入的基础模型。 Amazon Location 提供用于地图、地点和路线的 API,其中包含由 Esri、HERE、Grab 和 OpenStreetMap 等可信第三方提供的数据。如果您需要完全控制您的基础设施,您可以使用 亚马逊SageMaker JumpStart,它使您能够部署基础模型并可以访问数百个模型。

解决方案概述

在大型语言模型(LLM)领域, 代理人 是一个可以在法学硕士的帮助下自主推理和完成任务的实体。这使得法学硕士不仅可以生成文本,还可以进行对话并完成特定领域的任务。为了指导这种行为,我们采用推理模式。根据研究论文 大型语言模型是零样本推理机尽管有知识限制,法学硕士仍擅长高级推理。

我们选择了 克劳迪娅 2 作为 Amazon Bedrock 的基础模型,旨在创建能够处理地理空间任务的地理空间代理。总体概念很简单:像地理空间数据科学家一样思考。该任务涉及编写 Python 代码来读取数据、转换数据,然后在有趣的地图中将其可视化。我们使用了一种称为 计划与解决提示 为了这个。

使用计划和解决策略可以进行多步骤推理并制定高级计划作为首要任务。这对于我们的加载、转换和可视化工作流程非常有效,并且是我们的代理将使用的高级计划。这些子任务中的每一个都被发送给 Claude 2 单独解决。

我们设计了一个示例任务来创建以下价格热图 纽约的 Airbnb 房源。要规划完成任务的路径,代理需要了解数据集。代理需要知道数据集中的列以及这些列中的数据类型。我们从数据集中生成摘要,以便代理可以规划用户提供的任务,在本例中生成热图。

先决条件

部署演示有一些先决条件。您需要访问 AWS 账户 访问密钥 or AWS身份和访问管理 (我是) 角色 具有 Amazon Bedrock 和 Amazon Location 的权限。您将需要创建一个 地图,以 地点索引和一个 亚马逊位置 API 密钥 使用亚马逊位置控制台。您还需要访问安装了 Docker 的本地或虚拟环境。在我们的演示中,我们使用 亚马逊弹性计算云 运行安装了 Docker 的 Amazon Linux 的 (Amazon EC2) 实例。

阅读并总结数据

为了向代理提供有关数据集的上下文,我们提示 Claude 2 编写 Python 代码来读取数据并提供与我们的任务相关的摘要。以下是我们提供的一些提示。完整列表可在 prompts.py 项目中的文件。

Your Role: You are a geospatial data analyzer designed to analyze data schema from arbitrary geospatial datasets.
Your Task: You are provided a set of file URLs. You need to generate a Python function that meets the following: Read each file using geopandas. Each file could be CSV, shape file, or GeoJSON. Use built-in function resolved_file_url= get_data_file_url(file_url, session_id) to get downloadable URLs.

根据这些提示,Claude 2 生成了以下 Python 代码:

import geopandas as gpd
import pandas as pd
import numpy as np def analyze_geospatial_data(file_urls): dataframes = [] for file_url in file_urls: resolved_file_url = get_data_file_url(file_url, 'a5b188fe-91f7-4f92-92fe-c4030721a427', 'local') if file_url.endswith('.csv'): df = pd.read_csv(resolved_file_url) elif file_url.endswith('.shp'): df = gpd.read_file(resolved_file_url) elif file_url.endswith('.parquet'): df = pd.read_parquet(resolved_file_url) elif file_url.endswith('.geojson'): df = gpd.read_file(resolved_file_url) else: raise ValueError('Unsupported file format') df = df.sample(n=3, random_state=42) dataframes.append({ 'file_url': file_url, 'resolved_file_url': resolved_file_url, 'data_frame': df, 'column_names': list(df.columns) }) return dataframes file_urls = ['agent://airbnb_listings_price.csv']
dataframes = analyze_geospatial_data(file_urls)

agent:// 前缀告诉我们的 CLI 该文件存储在会话存储文件夹中。运行 CLI 时,它将创建一个 geospatial-agent-session-storage 文件夹来存储本地数据。代理现在可以识别上传的 Airbnb 数据及其列名称。接下来,让我们向 Claude 询问一些使用这些列生成热图的提示。我们将传入以下提示。

Your Role: You are a geospatial data analyzer designed to analyze data schema from arbitrary geospatial data sets.
Your Task: You are provided with a table with some rows data. Your task is to generate a summary that describes the data in the table following the requirements below. The first sentence should be summary of the data in the table from the aspect of the user action. If there is no geometry column in the table, the second sentence should note column names that can be used to generate a geometry column in geopandas.

克劳德2回复提示

Summary: The table contains columns for listing id, name, host id, host name, location details like neighborhood, latitude, and longitude that can be used to generate a geometry column for plotting. Price column contains listing price that can be used to generate a heatmap of listing prices.

规划解决方案

现在我们可以请克劳德二人起草一份高层计划。我们可以使用 Python 的图形库,称为 网络X 制定解决问题的步骤。

与我们上一个提示类似,我们传入一些要求来指导 Claude 2:

Your Role: You are a geospatial data scientist and an expert Python developer.
Your Task: A series of consecutive steps.
Your Reply needs to meet these requirements: Create a single NetworkX graph. No disconnected components allowed. First operations are data loading. Use geopandas for spatial data.

根据这些提示,Claude 2 生成了以下 Python 代码:

import networkx as nx
G = nx.DiGraph()
# Load the data
G.add_node("airbnb_data_url", node_type="data", data_path="agent://airbnb_listings_price.csv", description="URL for Airbnb listing price data")
G.add_node("load_data", node_type="operation", operation_type="load", description="Load the Airbnb listing price data")
G.add_edge("airbnb_data_url", "load_data")
G.add_node("airbnb_df", node_type="data", description="Pandas DataFrame containing Airbnb listing prices")
G.add_edge("load_data", "airbnb_df")
# Transform the data
G.add_node("add_geometry", node_type="operation", operation_type="transform", description="Create a geometry column using latitude and longitude")
G.add_edge("airbnb_df", "add_geometry")
G.add_node("airbnb_gdf", node_type="data", description="GeoDataFrame with geometry column added")
G.add_edge("add_geometry", "airbnb_gdf")
# Visualize the data
G.add_node("plot_heatmap", node_type="operation", operation_type="visualization", description="Generate a heatmap of listing prices")
G.add_edge("airbnb_gdf", "plot_heatmap")
G.add_node("price_heatmap", node_type="data", description="The heatmap plot showing Airbnb listing prices")
G.add_edge("plot_heatmap", "price_heatmap")

在此 NetworkX 图中,Claude 2 将流程分为三个主要部分:

  • 加载数据中 – 将 Airbnb 列表价格从给定 URL 导入到 Pandas DataFrame 中
  • 转换数据 – 根据纬度和经度坐标创建几何列
  • 可视化数据 – 生成热图来显示 Airbnb 房源的定价

这种方法可以清晰、直接地实施手头的地理空间任务。我们可以使用 GraphViz 来可视化以下工作流程。

图表

实施计划

现在克劳德 2 已经为我们提供了一个计划,是时候将其付诸实践了。对于每一步,我们都会提示 Claude 2 编写相应的代码。为了让 Claude 2 保持专注,我们为每项任务提供了高水平的要求。让我们深入研究 Claude 2 为每个阶段生成的代码。

加载数据

要将 Airbnb 列表价格数据加载到 Pandas DataFrame 中,我们创建一个提示并传入一些参数。 Operation_task 中的“加载 Airbnb 数据”引用了我们之前创建的图中的加载数据节点。

Your Role: You are a geospatial data scientist and an expert Python developer.
Operation_task: You need to generate a Python function to do: Load Airbnb data.
Your Reply needs to meet these requirements: The function definition is: load_data(airbnb_data_url='agent://airbnb_listings_price.csv'). When doing spatial joins, retain at least 1 geometry column. Point function requires importing shapely library.

根据这些提示,Claude 2 生成了以下 Python 代码:

import pandas as pd
def load_data(airbnb_data_url='agent://airbnb_listings_price.csv'): """ Load Airbnb listing price data """ file_url = get_data_file_url(airbnb_data_url, session_id, storage_mode) airbnb_df = pd.read_csv(file_url) return airbnb_df

转换数据

接下来,Claude 2 生成代码来添加 geometry 使用列到我们的 DataFrame latitudelongitude。对于这个提示,我们传入以下要求:

Your Role: You are a geospatial data scientist and an expert Python developer.
Operation_task: You need to generate a Python function to do: Add geometry column from latitude/longitude. Your Reply needs to meet these requirements: The function definition is: add_geometry(filtered_df). The function return line is: return airbnb_gdf.

根据这些提示,Claude 2 生成了以下 Python 代码:

import geopandas as gpd
from shapely.geometry import Point
def add_geometry(airbnb_df): """ Add geometry column from latitude and longitude """ airbnb_df['geometry'] = airbnb_df.apply(lambda row: Point(row['longitude'], row['latitude']), axis=1) airbnb_gdf = gpd.GeoDataFrame(airbnb_df, geometry='geometry') return airbnb_gdf

可视化数据

最后,Claude 2 使用以下方法构建了热图可视化 派德克,这是一个用于空间渲染的Python库。对于这个提示,我们传入以下要求:

Your Role: You are a geospatial data scientist and an expert Python developer.
Operation_task: You need to generate a Python function to do: Generate heatmap from price.
Your Reply needs to meet these requirements: The function definition is: generate_heatmap(airbnb_gdf). The function return line is: return airbnb_heatmap.

根据这些提示,Claude 2 生成了以下 Python 代码:

import pandas as pd
import geopandas as gpd
import pydeck as pdk def plot_heatmap(airbnb_gdf): """ Plot heatmap of listing prices """ price_heatmap = pdk.Deck( map_style=location_map_style(), initial_view_state=pdk.ViewState( latitude=airbnb_gdf['latitude'].mean(), longitude=airbnb_gdf['longitude'].mean(), zoom=11, pitch=50, ), layers=[ pdk.Layer( 'HexagonLayer', data=airbnb_gdf, get_position=['longitude', 'latitude'], radius=100, elevation_scale=4, elevation_range=[0, 1000], pickable=True, extruded=True, ), pdk.Layer( 'ScatterplotLayer', data=airbnb_gdf, get_position=['longitude', 'latitude'], get_color='[200, 30, 0, 160]', get_radius=200, ), ], ) # Save heatmap HTML price_heatmap.to_html(get_local_file_path('airbnb_heatmap.html', session_id, task_name)) return price_heatmap

当 Claude 2 返回响应时,它还包含一些有用的注释,解释每个函数如何满足所提供的要求。例如,对于热图可视化,Claude 2 指出了以下内容:

"This function generates a heatmap of Airbnb listing prices using pydeck and saves the resulting HTML locally. It fulfills the requirements specified in the prompt."

组装生成的代码

现在 Claude 2 已经创建了各个构建块,是时候将它们组合在一起了。该代理会自动将所有这些片段组装到一个 Python 文件中。该脚本按顺序调用每个函数,从而简化了整个过程。

最后一步类似于以下代码:

session_id = "a5b188fe-91f7-4f92-92fe-c4030721a427"
task_name = "1694813661_airbnb_listings_price_heatmap"
storage_mode = "local"
# Sequentially invoke the functions
airbnb_df = load_data(airbnb_data_url='agent://airbnb_listings_price.csv')
airbnb_gdf = add_geometry(airbnb_df)
price_heatmap = plot_heatmap(airbnb_gdf)

脚本完成后,我们可以看到 Claude 2 创建了一个 HTML 文件,其中包含可视化热图的代码。下图显示了亚马逊位置底图上的纽约,以及可视化 Airbnb 房源价格的热图。

热图可视化

将 Amazon Location 与 Amazon Bedrock 结合使用

尽管我们的规划和求解代理可以处理此地理空间任务,但我们需要对地址地理编码等任务采取稍微不同的方法。为此,我们可以使用一种称为 应对,我们将推理和行动与法学硕士结合起来。

在 ReAct 模式中,代理根据客户输入和 工具 供其处置。为了让这个由 Claude 2 驱动的代理具备地理编码功能,我们开发了一个地理编码工具。该工具使用 Amazon Location Places API,特别是 SearchPlaceIndexForText 方法,将地址转换为其地理坐标。

Agent: Hi! I'm Agent Smith, your conversational geospatial assistant. How can I assist you today?
You: >? Hello, can you give me the coordinates for 112 E 11th St, Austin, TX 78701?
Agent: The coordinates for 112 E 11th St, Austin, TX 78701 are longitude -97.740590981087 and latitude 30.274118017533.

在这段简短的交流中,代理会破译您对地址进行地理编码的意图,激活地理编码工具,并返回纬度和经度。

无论是绘制热图还是对地址进行地理编码,Claude 2 与 ReAct 和 Plan and Solve 等代理相结合都可以简化地理空间工作流程。

部署演示

首先,请完成以下步骤:

  1. 将以下存储库克隆到本地计算机或 EC2 实例。你可能需要运行 aws configure --profile <profilename> 并设置默认区域;该应用程序经过测试使用 us-east-1.
git clone https://github.com/aws-samples/amazon-location-geospatial-agent/

现在我们已经克隆了存储库,我们可以配置环境变量。

  1. 将目录更改为克隆的项目文件夹:
cd amazon-location-geospatial-agent

  1. 编辑 .env 使用您喜欢的文本编辑器创建文件:
  1. 添加您的地图名称、地点索引名称和 API 密钥:
API_KEY_NAME=AgentAPIKey
MAP_NAME=AgentMap
PLACE_INDEX_NAME=AgentPlaceIndex

  1. 运行以下命令来构建容器:
docker build -t agent .

  1. 运行以下命令来运行并连接到您的 Docker 容器:
docker run --rm -it -v ~/.aws:/root/.aws --entrypoint bash agent

  1. 获取 Airbnb 数据集:
apt install -y wget
wget https://data.insideairbnb.com/united-states/ny/new-york-city/2023-10-01/visualisations/listings.csv
cp listings.csv data/listings.csv

  1. 运行以下命令创建会话。我们使用会话来隔离独特的聊天环境。
SESSION_ID="3c18d48c-9c9b-488f-8229-e2e8016fa851" FILE_NAME="listings.csv" make create-session

现在您已准备好启动应用程序。

  1. 运行以下命令来启动聊天应用程序:
poetry run agent --session-id 3c18d48c-9c9b-488f-8229-e2e8016fa851 --profile <profilename>

您将收到聊天提示。

  1. 您可以首先提出以下问题:
I've uploaded the file listings.csv. Draw a heatmap of Airbnb listing price.

代理抢了 Airbnb_listings_price.csv 我们已经下载到的文件 /data 文件夹并将其解析为地理空间 DataFrame。然后它生成用于转换数据的代码以及用于可视化的代码。最后,它创建一个 HTML 文件,该文件将写入 /data 文件夹,您可以打开该文件夹以在浏览器中可视化热图。

另一个示例使用 Amazon Location Places API 对地址进行地理编码。如果我们要求代理对地址 112 E 11th St, Austin, TX 78701 进行地理编码,我们将得到如下图所示的响应。

交互示例

结论

在这篇文章中,我们简要概述了 Amazon Bedrock 和 Amazon Location,以及如何结合使用它们来分析和可视化地理空间数据。我们还介绍了 Plan-and-Solve 和 ReAct 以及如何在代理中使用它们。

我们的例子只是触及了表面。尝试下载我们的示例代码并为您的地理空间任务添加您自己的代理和工具。


关于作者

杰夫德姆斯 是一名解决方案架构师,于 2016 年加入 Amazon Web Services (AWS)。他专注于地理空间社区,并对地理信息系统 (GIS) 和技术充满热情。工作之余,Jeff 喜欢旅行、构建物联网 (IoT) 应用程序以及摆弄最新的小工具。

斯瓦加塔·普拉泰克 是一名高级软件工程师,在 Amazon Web Services (AWS) 的 Amazon Location Service 工作,专注于生成式 AI 和地理空间。

现货图片

最新情报

现货图片