Flutter Google Vertex AI集成插件vertex_ai的使用
Flutter Google Vertex AI集成插件vertex_ai的使用
Vertex AI API Client
这是一个非官方的Dart客户端,用于Google的 Vertex AI API。
功能
- Generative AI
- 文本模型
- 聊天模型
- 文本嵌入模型
- Matching Engine
- 创建和管理索引和索引端点
- 查询索引
Generative AI
Generative AI (也称为genai
) 支持在Vertex AI上使用Google的大规模生成AI模型,以便在你的AI驱动的应用程序中使用。
认证
VertexAIGenAIClient
使用 googleapis_auth
包进行认证。你需要提供一个 AuthClient
实例。
final serviceAccountCredentials = ServiceAccountCredentials.fromJson(
json.decode(serviceAccountJson),
);
final authClient = await clientViaServiceAccount(
serviceAccountCredentials,
[VertexAIGenAIClient.cloudPlatformScope],
);
final vertexAi = VertexAIGenAIClient(
authHttpClient: authClient,
project: 'your-project-id',
);
服务账号需要以下权限:
aiplatform.endpoints.predict
OAuth2范围为:
https://www.googleapis.com/auth/cloud-platform
文本模型
文本模型可用于分类、摘要和实体提取等语言任务。
final res = await vertexAi.text.predict(
prompt: 'What is the purpose of life?',
);
聊天模型
聊天模型支持多轮对话,模型会根据之前的对话内容生成新的回复。
final res = await vertexAi.chat.predict(
context: 'I want you to act as a Socrat.',
messages: const [
VertexAIChatModelMessage(
author: 'USER',
content: 'Is justice neccessary in a society?',
),
],
);
文本嵌入
文本嵌入API可以为输入文本生成向量嵌入,适用于语义搜索、推荐、分类和异常检测等任务。
final res = await vertexAi.textEmbeddings.predict(
content: [
const VertexAITextEmbeddingsModelContent(
taskType: VertexAITextEmbeddingsModelTaskType.retrievalDocument,
title: 'The Paradox of Wisdom',
content: 'The only true wisdom is in knowing you know nothing',
),
],
);
Matching Engine
Vertex AI Matching Engine 提供了高扩展性、低延迟的向量数据库,常用于语义相似项匹配。
认证
VertexAIMatchingEngineClient
使用 googleapis_auth
包进行认证。你需要提供一个 AuthClient
实例。
final serviceAccountCredentials = ServiceAccountCredentials.fromJson(
json.decode(serviceAccountJson),
);
final authClient = await clientViaServiceAccount(
serviceAccountCredentials,
[VertexAIMatchingEngineClient.cloudPlatformScope],
);
final vertexAi = VertexAIMatchingEngineClient(
authHttpClient: authClient,
project: 'your-project-id',
location: 'europe-west1',
);
服务账号需要以下权限:
aiplatform.indexes.create
aiplatform.indexes.get
aiplatform.indexes.list
aiplatform.indexes.update
aiplatform.indexes.delete
aiplatform.indexEndpoints.create
aiplatform.indexEndpoints.get
aiplatform.indexEndpoints.list
aiplatform.indexEndpoints.update
aiplatform.indexEndpoints.delete
aiplatform.indexEndpoints.deploy
aiplatform.indexEndpoints.undeploy
OAuth2范围为:
https://www.googleapis.com/auth/cloud-platform
创建索引
- 生成嵌入并保存到文件。
- 创建Cloud Storage存储桶并上传嵌入文件。
- 创建索引:
final operation = await matchingEngine.indexes.create(
displayName: 'test-index',
description: 'This is a test index',
metadata: const VertexAINearestNeighborSearch(
contentsDeltaUri: 'gs://bucket-name/path-to-index-dir',
config: VertexAINearestNeighborSearchConfig(
dimensions: 768,
algorithmConfig: VertexAITreeAhAlgorithmConfig(),
),
),
);
检查操作状态:
final operation = await matchingEngine.indexes.operations.get(
name: operation.name,
);
print(operation.done);
获取索引信息
final index = await matchingEngine.indexes.get(id: '5086059315115065344');
列出所有索引:
final indexes = await matchingEngine.indexes.list();
更新索引
final res = await matchingEngine.indexes.update(
id: '5086059315115065344',
metadata: const VertexAIIndexRequestMetadata(
contentsDeltaUri: 'gs://bucket-name/path-to-index-dir',
isCompleteOverwrite: true,
),
);
创建索引端点
final operation = await matchingEngine.indexEndpoints.create(
displayName: 'test-index-endpoint',
description: 'This is a test index endpoint',
publicEndpointEnabled: true,
);
检查操作状态:
final operation = await matchingEngine.indexEndpoints.operations.get(
name: operation.name,
);
print(operation.done);
部署索引到索引端点
final operation = await matchingEngine.indexEndpoints.deployIndex(
indexId: '5086059315115065344',
indexEndpointId: '8572232454792807200',
deployedIndexId: 'deployment1',
deployedIndexDisplayName: 'test-deployed-index',
);
启用自动缩放:
final operation = await matchingEngine.indexEndpoints.deployIndex(
indexId: '5086059315115065344',
indexEndpointId: '8572232454792807200',
deployedIndexId: 'deployment1',
deployedIndexDisplayName: 'test-deployed-index',
automaticResources: const VertexAIAutomaticResources(
minReplicaCount: 2,
maxReplicaCount: 10,
),
);
获取索引端点信息
final ie = await matchingEngine.indexEndpoints.get(id: '8572232454792807200');
列出所有索引端点:
final indexEndpoints = await matchingEngine.indexEndpoints.list();
修改索引端点
final operation = await matchingEngine.indexEndpoints.mutateDeployedIndex(
indexEndpointId: '8572232454792807200',
deployedIndexId: 'deployment1',
automaticResources: const VertexAIAutomaticResources(
minReplicaCount: 2,
maxReplicaCount: 20,
),
);
从索引端点取消部署索引
final operation = await matchingEngine.indexEndpoints.undeployIndex(
indexEndpointId: '8572232454792807200',
deployedIndexId: 'deployment1',
);
删除索引端点
final operation = await matchingEngine.indexEndpoints.delete(
id: '8572232454792807200',
);
删除索引
final operation = await matchingEngine.indexes.delete(
id: '5086059315115065344',
);
使用索引端点查询索引
final machineEngineQuery = VertexAIMatchingEngineClient(
authHttpClient: authClient,
project: Platform.environment['VERTEX_AI_PROJECT_ID']!,
rootUrl:
'https://1451028333.europe-west1-706285145444.vdb.vertexai.goog/',
);
final res = await machineEngineQuery.indexEndpoints.findNeighbors(
indexEndpointId: '8572232454792807200',
deployedIndexId: 'deployment1',
queries: const [
VertexAIFindNeighborsRequestQuery(
datapoint: VertexAIIndexDatapoint(
datapointId: 'your-datapoint-id',
featureVector: [-0.0024800552055239677, 0.011974085122346878, ...],
),
neighborCount: 3,
),
],
);
示例代码
// ignore_for_file: avoid_print
import 'dart:convert';
import 'dart:io';
import 'package:googleapis_auth/auth_io.dart';
import 'package:vertex_ai/vertex_ai.dart';
void main() async {
final vertexAi = VertexAIGenAIClient(
httpClient: await _getAuthHttpClient(),
project: _getProjectId(),
);
final res = await vertexAi.text.predict(
prompt: 'List the numbers from 1 to 9 in order '
'without any spaces or commas.',
);
print(res);
}
Future<AuthClient> _getAuthHttpClient() async {
final serviceAccountCredentials = ServiceAccountCredentials.fromJson(
json.decode(Platform.environment['VERTEX_AI_SERVICE_ACCOUNT']!),
);
return clientViaServiceAccount(
serviceAccountCredentials,
[VertexAIGenAIClient.cloudPlatformScope],
);
}
String _getProjectId() {
return Platform.environment['VERTEX_AI_PROJECT_ID']!;
}
以上是关于如何在Flutter项目中集成和使用vertex_ai
插件与Google Vertex AI交互的详细说明。希望这些信息能帮助你更好地理解和使用该插件。
更多关于Flutter Google Vertex AI集成插件vertex_ai的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter Google Vertex AI集成插件vertex_ai的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter应用中集成并使用vertex_ai
插件的示例代码。假设你已经有一个Flutter项目,并且已经配置好了Google Cloud环境以及Vertex AI服务。
首先,确保你已经在pubspec.yaml
文件中添加了vertex_ai
插件的依赖(注意:vertex_ai
是一个假设的插件名称,实际中可能需要使用相关的HTTP客户端库与Vertex AI API进行交互,因为官方可能没有直接提供Flutter插件。这里我们假设有一个类似的插件):
dependencies:
flutter:
sdk: flutter
vertex_ai: ^x.y.z # 替换为实际的版本号
然后,运行flutter pub get
来获取依赖。
接下来,我们编写Flutter代码来调用Vertex AI API。由于Flutter本身不直接支持Google Cloud服务的原生客户端库,我们通常会通过HTTP请求与Vertex AI的REST API进行交互。这里假设vertex_ai
插件封装了这些HTTP请求。
import 'package:flutter/material.dart';
import 'package:vertex_ai/vertex_ai.dart'; // 假设这是封装好的插件
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Vertex AI Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: VertexAIDemo(),
);
}
}
class VertexAIDemo extends StatefulWidget {
@override
_VertexAIDemoState createState() => _VertexAIDemoState();
}
class _VertexAIDemoState extends State<VertexAIDemo> {
String responseText = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Vertex AI Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Response from Vertex AI:',
),
SizedBox(height: 20),
Text(
responseText,
style: TextStyle(fontSize: 18),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
setState(() {
responseText = 'Loading...';
});
// 假设VertexAIClient是插件中提供的客户端类
final client = VertexAIClient();
// 调用Vertex AI API的示例方法,这里需要根据实际的API文档来编写
final response = await client.predict(
instanceId: 'your-instance-id', // 替换为你的Vertex AI实例ID
endpointId: 'your-endpoint-id', // 替换为你的Vertex AI端点ID
payload: {
// 替换为你的预测请求负载,根据API文档构造
'instances': [
{'your_input_field': 'your_input_value'},
],
},
);
// 更新UI显示API响应
setState(() {
responseText = response.toString(); // 这里可能需要根据实际响应结构来格式化显示
});
},
child: Text('Predict'),
),
],
),
),
);
}
}
注意:
VertexAIClient
和它的方法(如predict
)是假设存在的,实际中你需要使用HTTP客户端(如http
或dio
包)来发送请求到Vertex AI的REST API。- 你需要替换代码中的
'your-instance-id'
和'your-endpoint-id'
为你实际的Vertex AI实例和端点ID。 - 预测请求的负载(
payload
)也需要根据Vertex AI模型的输入要求来构造。
实际项目中,你可能还需要处理认证(如使用Google Cloud的Service Account凭证),这通常涉及到在HTTP请求中添加认证头。由于Flutter中没有官方的Google Cloud客户端库,你可能需要手动管理这些认证细节。