Flutter集成GPT插件gpt的使用
Flutter集成GPT插件gpt的使用
在本教程中,我们将演示如何在Flutter项目中集成GPT插件。我们将通过一系列步骤来展示如何创建一个简单的Flutter应用,该应用能够利用GPT插件生成文本。
特性
使用此工具可以:
- 创建GPT请求的批处理。将一组数据应用于提示并记录响应。
- 创建实验以查看不同配置参数和提示如何影响性能和输出。
- 使用DALL-E创建图像。
- 通过模拟服务器进行快速原型设计的ChatGPT插件。
- 使用ChatGPT插件发现ChatGPT插件。
准备工作
创建OpenAI API密钥
你需要创建一个OpenAI API密钥。如果你有账户,可以在以下链接创建一个密钥:
https://platform.openai.com/account/api-keys
不要与他人共享你的API密钥,也不要将其暴露在浏览器或其他客户端代码中。如果有人使用你的密钥,你将承担所有费用。不要将密钥提交到任何公共仓库。
创建一个包含API密钥的文件(下面的密钥不是真实的)。例如,我们命名文件为api_key
并添加密钥。
sk-gKtTxOumv4orO6cfWlh0ZK
安装此工具
确保已经安装了Dart。请按照以下链接中的说明操作:
https://dart.dev/get-dart
安装完成后,可以使用以下命令安装gpt程序:
dart pub global activate gpt
使用方法
以下是支持的用例:
- 生成ChatGPT插件
- 生成图像项目
- 生成批处理项目
- 生成提示项目
- 生成链项目
- 添加报告插件
创建项目
运行生成项目的命令:
air genp
首先需要选择项目类型:
? Project Archetype ›
❯ Prompt
Chain
Batch
Image
ChatGPT Plugin
输入项目名称和版本号:
✔ Project Archetype · Prompt
✔ Project Name: · myproject
✔ Project Version: · 1.0
根据项目需求,可能需要输入API密钥。可以选择跳过、使用现有密钥文件或创建新的密钥文件。
? Import Key ›
❯ Skip
Use Existing OpenAI API Key File
Create New OpenAI API Key File
接下来,输入API密钥:
✔ Import Key · Create New OpenAI API Key File
? API Key: › sk-gKtTxOumv4orO6cfWlh0ZK
示例代码
以下是几个示例项目的详细信息:
ChatGPT插件
用于快速原型设计的ChatGPT插件项目。该项目基于快速启动项目:
https://github.com/openai/plugins-quickstart
项目文件如下:
---
projectName: plugin-quickstart
projectVersion: '1.0'
projectType: plugin
defaultConfig:
properties:
port: 5003
nameForHuman: TODO Plugin (no auth)
nameForModel: todo
descriptionForHuman: Plugin for managing a TODO list, you can add, remove and view your TODOs.
mockedRequests:
- path: "/todos/global"
method: get
mockedResponse: todos-global.json
- path: "/todos/user"
method: get
mockedResponse: todos-global.json
pluginServers:
- serverId: todo-mike
flavor: mike
# mocked requests
mockedRequests:
- path: "/todos/mike"
method: get
mockedResponse: todos.json # returns the content of this file
# Adds a different user for testing
- serverId: todo-kaleb
flavor: kaleb
mockedRequests:
- path: "/todos/kaleb"
method: get
mockedResponse: todos.json
properties:
showHttpHeaders: true # Show http headers in logs
启动模拟插件服务器:
air plugin
或者启动特定服务器:
air plugin --serverId todo-mike
更多关于创建和使用ChatGPT插件的信息,请参阅:
https://github.com/sisbell/stackwire-gpt/wiki/ChatGPT-Plugin
图像生成
如果你选择了创建图像项目,会被要求输入描述。不用担心,可以在生成项目后修改它。
? Image Description: › A goldfish with big eyes
项目文件如下:
projectName: image-2
projectVersion: 2.0
apiKeyFile: api_key
blocks:
- blockId: image-block-1
pluginName: ImageGptPlugin
executions:
#First Image
- id: img-1
sizes:
- 256
- 256
- 1024
prompt: image.prompt
properties:
imageDescription: A goldfish with big eyes
你的提示文件如下:
Generate a picture of a ${imageDescription}
更多关于图像生成的信息,请参阅:
https://github.com/sisbell/stackwire-gpt/wiki/Images
批处理项目
以下是询问执行批处理次数的问题。如果你选择5次,它将运行所有批处理调用5次。
? Number of Times to Run The Block: › 5
项目文件如下:
---
projectName: mybatch
projectVersion: 1.0
apiKeyFile: api_key
blocks:
- blockId: batch-1
pluginName: BatchGptPlugin
blockRuns: 5
configuration:
requestParams:
model: gpt-3.5-turbo
temperature: 0.7
top_p: 1
max_tokens: 500
executions:
- id: batch-1
dataFile: batch-data.json
prompt: batch.prompt
提示文件如下:
Write me a paragraph about the world I live in
World: ```${my_world}```
batch-data.json
文件如下:
{
"my_world" : [
"Hello World, I live in a magical place with magical creatures",
"Hello World, I live in a futuristic Utopia",
"Hello World, I live in a futuristic Dystopia"
]
}
更多关于批处理的信息,请参阅:
https://github.com/sisbell/stackwire-gpt/wiki/Batches
提示项目
以下是询问执行提示请求次数的问题。如果你选择5次,它将运行所有提示请求5次。
? Number of Times to Run The Block: › 5
接下来选择输出格式。你想要直接的文本响应还是JSON格式?
? Response Format ›
JSON
❯ TEXT
如果选择JSON,会被问是否启用修复JSON响应功能。这将尝试解析AI助手可能添加的任何多余文本。
? Attempt to FIX JSON Responses? (y/n) › no
项目文件如下:
---
projectName: prompt-1
projectVersion: 1.0
apiKeyFile: api_key
blocks:
- blockId: single-1
pluginName: ExperimentGptPlugin
blockRuns: 5
configuration:
requestParams:
model: gpt-3.5-turbo
temperature: 1.2
top_p: 1
max_tokens: 500
executions:
- id: exp-1
responseFormat: json
fixJson: false
promptChain:
- prompt-json.prompt
properties:
character: Commander in Starfleet
mainCharacterName: ''
- blockId: report-1
pluginName: ReportingGptPlugin
executions:
- id: report-1
blockIds:
- single-1
更多关于提示的信息,请参阅:
https://github.com/sisbell/stackwire-gpt/wiki/Prompts
链项目
选择“链”项目模板,然后按选项进行操作。
? Number of Times to Run The Block: › 1
? Attempt to FIX JSON Responses? (y/n) › yes
? Number of Times to Run The Prompt Chain: › 2
生成的 project.yaml
文件如下:
---
projectName: "chain-project"
projectVersion: "1.0"
apiKeyFile: "api_key"
blocks:
# Block demonstrates the use of importing properties
- blockId: chain-1
pluginName: ExperimentGptPlugin
blockRuns: 1 # Number of Stories
configuration:
requestParams:
model: gpt-3.5-turbo
temperature: 1.2
top_p: 1
max_tokens: 500
executions:
- id: exp-1-import
chainRuns: 2 # Number of times to run the promptChain
promptChain:
- story.prompt
- user-action.prompt # Simulates user input
excludesMessageHistory:
- user-action.prompt
fixJson: true
responseFormat: json
# Import properties from a properties file
import:
propertiesFile: properties.json # predefined values
properties:
planet: 1 # Earth
action: 3 # Lands on the planet
- blockId: report-1
pluginName: ReportingGptPlugin
executions:
- id: report-1
blockIds:
- chain-1
更多关于链的信息,请参阅:
https://github.com/sisbell/stackwire-gpt/wiki/Chains
添加报告插件
为了生成HTML报告,作为最后一个块添加ReportingGptPlugin
。在blockIds
下添加任何你想加入报告的先前块ID。
---
projectName: experiment-reporting
projectVersion: '1.7'
apiKeyFile: "../../api_key"
blocks:
- blockId: chain-1
pluginName: ExperimentGptPlugin
blockRuns: 1
...
# Generate HTML Report
- blockId: report-1
pluginName: ReportingGptPlugin
executions:
- id: report-execution
blockIds:
- chain-1
示例报告
报告将显示配置块执行的整个聊天内容。
更多关于报告的信息,请参阅:
https://github.com/sisbell/stackwire-gpt/wiki/Reporting
命令帮助
air --help
A command line tool for running GPT commands
Usage: air <command> [arguments]
Global options:
-h, --help Print this usage information.
Available commands:
clean Cleans project's output directory
count Returns the number of OpenApiCalls that would be made
genp Generates a new project
plugin Runs local version of ChatGPT Plugin
run Runs a project's blocks
Run "air help <command>" for more information about a command.
其他命令
清理项目
要清理项目,请运行以下命令:
air clean
这会删除项目的output
目录。
计算项目中的OpenAI调用次数
运行OpenAI调用可能会很昂贵,如果你配置错误的话。要确定项目将创建多少个OpenAI调用,请运行以下命令:
air count
或者对于特定块的计数:
air count -b myblockId
它将输出:
Project: product-summary-2.8
Total OpenAPI Calls would be 12
干运行
如果你想在实际产生OpenAI费用之前了解项目的行为,请使用干运行标志:
air run --dryRun
Executing Block
Running Project: image-generation-2.3
BlockId: image-1, PluginName: ImageGptPlugin
----------
Starting Block Run: 1
Starting execution: 1 - Requires 1 calls to OpenAI
POST to https://api.openai.com/v1/images/generations
{"prompt":"Generate a picture of a Unicorn with a gold horn and wings","n":1,"size":"256x256","response_format":"url"}
Finished execution: 1
Starting execution: 2 - Requires 2 calls to OpenAI
POST to https://api.openai.com/v1/images/generations
{"prompt":"Generate a picture of a fish with giant eyes","n":1,"size":"256x256","response_format":"b64_json"}
POST to https://api.openai.com/v1/images/generations
{"prompt":"Generate a picture of a fish with giant eyes","n":1,"size":"512x512","response_format":"b64_json"}
Finished execution: 2
--------
Finished running project: 0 seconds
更多关于Flutter集成GPT插件gpt的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter集成GPT插件gpt的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中集成GPT(如OpenAI的GPT-3或GPT-4)可以通过调用OpenAI的API来实现。虽然Flutter没有官方的GPT插件,但你可以使用http
或dio
等包来发送HTTP请求到OpenAI的API,从而实现与GPT的交互。
以下是一个简单的步骤指南,展示如何在Flutter中集成GPT:
1. 安装依赖
首先,你需要在pubspec.yaml
文件中添加http
或dio
依赖:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3 # 或者使用 dio: ^4.0.0
然后运行 flutter pub get
来安装依赖。
2. 获取OpenAI API密钥
你需要从OpenAI的官方网站获取API密钥。访问 OpenAI API 并创建一个账户,然后生成API密钥。
3. 创建API请求
接下来,你可以创建一个函数来发送请求到OpenAI的API。以下是一个使用http
包的示例:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class GPTService {
final String apiKey = 'your_openai_api_key'; // 替换为你的API密钥
final String apiUrl = 'https://api.openai.com/v1/completions';
Future<String> getGPTResponse(String prompt) async {
final response = await http.post(
Uri.parse(apiUrl),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer $apiKey',
},
body: jsonEncode({
'model': 'text-davinci-003', // 你可以选择其他模型
'prompt': prompt,
'max_tokens': 150,
'temperature': 0.7,
}),
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
return data['choices'][0]['text'].trim();
} else {
throw Exception('Failed to load response: ${response.body}');
}
}
}
4. 在UI中使用GPT服务
你可以在Flutter的UI中调用这个服务来获取GPT的响应并显示给用户:
import 'package:flutter/material.dart';
import 'gpt_service.dart'; // 导入你创建的GPT服务
class ChatScreen extends StatefulWidget {
[@override](/user/override)
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _controller = TextEditingController();
String _response = '';
final GPTService _gptService = GPTService();
void _sendMessage() async {
final prompt = _controller.text;
if (prompt.isEmpty) return;
try {
final response = await _gptService.getGPTResponse(prompt);
setState(() {
_response = response;
});
} catch (e) {
setState(() {
_response = 'Error: $e';
});
}
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('GPT Chat'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
TextField(
controller: _controller,
decoration: InputDecoration(
hintText: 'Enter your message',
),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: _sendMessage,
child: Text('Send'),
),
SizedBox(height: 20),
Text('Response: $_response'),
],
),
),
);
}
}
void main() {
runApp(MaterialApp(
home: ChatScreen(),
));
}