Flutter ChatGPT API集成插件flutter_chatgpt_api的使用
Flutter ChatGPT API集成插件flutter_chatgpt_api的使用
安装
dependencies:
flutter_chatgpt_api: ^1.0.0
使用示例代码
import 'package:flutter_chatgpt_api/flutter_chatgpt_api.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter ChatGPT API Example by justecdev',
home: ChatPage(),
debugShowCheckedModeBanner: false,
);
}
}
class ChatPage extends StatefulWidget {
const ChatPage({Key? key}) : super(key: key);
@override
State<ChatPage> createState() => _ChatPageState();
}
class _ChatPageState extends State<ChatPage> {
final _textController = TextEditingController();
final _scrollController = ScrollController();
final List<ChatMessage> _messages = [];
late ChatGPTApi _api;
String? _parentMessageId;
String? _conversationId;
late bool isLoading;
@override
void initState() {
super.initState();
_api = ChatGPTApi(
sessionToken: SESSION_TOKEN,
clearanceToken: CLEARANCE_TOKEN,
);
isLoading = false;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 100,
title: const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
'Flutter ChatGPT API Example @coskuncay',
maxLines: 22,
textAlign: TextAlign.center,
),
),
backgroundColor: botBackgroundColor,
),
backgroundColor: backgroundColor,
body: SafeArea(
child: Column(
children: [
Expanded(
child: _buildList(),
),
Visibility(
visible: isLoading,
child: const Padding(
padding: EdgeInsets.all(8.0),
child: CircularProgressIndicator(
color: Colors.white,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
_buildInput(),
_buildSubmit(),
],
),
),
],
),
),
);
}
Widget _buildSubmit() {
return Visibility(
visible: !isLoading,
child: Container(
color: botBackgroundColor,
child: IconButton(
icon: const Icon(
Icons.send_rounded,
color: Color.fromRGBO(142, 142, 160, 1),
),
onPressed: () async {
setState(() {
_messages.add(
ChatMessage(
text: _textController.text,
chatMessageType: ChatMessageType.user,
),
);
isLoading = true;
});
var input = _textController.text;
_textController.clear();
Future.delayed(const Duration(milliseconds: 50))
.then((_) => _scrollDown());
var newMessage = await _api.sendMessage(
input,
conversationId: _conversationId,
parentMessageId: _parentMessageId,
);
setState(() {
_conversationId = newMessage.conversationId;
_parentMessageId = newMessage.messageId;
isLoading = false;
_messages.add(
ChatMessage(
text: newMessage.message,
chatMessageType: ChatMessageType.bot,
),
);
});
_textController.clear();
Future.delayed(const Duration(milliseconds: 50))
.then((_) => _scrollDown());
},
),
),
);
}
Expanded _buildInput() {
return Expanded(
child: TextField(
textCapitalization: TextCapitalization.sentences,
style: const TextStyle(color: Colors.white),
controller: _textController,
decoration: const InputDecoration(
fillColor: botBackgroundColor,
filled: true,
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
),
),
);
}
ListView _buildList() {
return ListView.builder(
controller: _scrollController,
itemCount: _messages.length,
itemBuilder: (context, index) {
var message = _messages[index];
return ChatMessageWidget(
text: message.text,
chatMessageType: message.chatMessageType,
);
},
);
}
void _scrollDown() {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 300),
curve: Curves.easeOut,
);
}
}
class ChatMessageWidget extends StatelessWidget {
const ChatMessageWidget(
{super.key, required this.text, required this.chatMessageType});
final String text;
final ChatMessageType chatMessageType;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
padding: const EdgeInsets.all(16),
color: chatMessageType == ChatMessageType.bot
? botBackgroundColor
: backgroundColor,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
chatMessageType == ChatMessageType.bot
? Container(
margin: const EdgeInsets.only(right: 16.0),
child: CircleAvatar(
backgroundColor: const Color.fromRGBO(16, 163, 127, 1),
child: Image.asset(
'assets/bot.png',
color: Colors.white,
scale: 1.5,
),
),
)
: Container(
margin: const EdgeInsets.only(right: 16.0),
child: const CircleAvatar(
child: Icon(
Icons.person,
),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
padding: const EdgeInsets.all(8.0),
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
child: Text(
text,
style: Theme.of(context)
.textTheme
.bodyLarge
?.copyWith(color: Colors.white),
),
),
],
),
),
],
),
);
}
}
Session Token 获取
- 访问 ahttps://chat.openai.com/chat 并登录或注册。
- 打开开发者工具。
- 打开
Application
>Cookies
(Storage
>Cookies
在 Firefox 上)。
- 创建这些文件并添加您的会话令牌以运行测试和示例:
test/session_token.dart
example/lib/session_token.dart
示例内容如下:
const SESSION_TOKEN = 'my session token from https://chat.openai.com/chat';
更多关于Flutter ChatGPT API集成插件flutter_chatgpt_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter ChatGPT API集成插件flutter_chatgpt_api的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何在Flutter项目中集成和使用flutter_chatgpt_api
插件的示例代码。这个插件允许你通过ChatGPT API在Flutter应用中实现聊天功能。
1. 添加依赖
首先,你需要在你的pubspec.yaml
文件中添加flutter_chatgpt_api
依赖:
dependencies:
flutter:
sdk: flutter
flutter_chatgpt_api: ^最新版本号 # 替换为最新版本号
2. 导入包
在你的Dart文件中导入该包:
import 'package:flutter_chatgpt_api/flutter_chatgpt_api.dart';
3. 配置API密钥
你需要一个ChatGPT的API密钥,可以在OpenAI官网申请。然后,你可以将这个密钥保存在你的Flutter项目中的某个安全位置(例如,使用.env
文件或直接在代码中,但注意不要在公开的代码中硬编码密钥)。
// 假设你在.env文件中存储了API密钥
String apiKey = DotEnv().env['OPENAI_API_KEY']!;
4. 初始化ChatGPT客户端
创建一个ChatGPT客户端实例:
final chatGptClient = ChatGptClient(apiKey: apiKey);
5. 发送请求并处理响应
使用ChatGPT客户端发送请求并处理响应:
import 'package:flutter/material.dart';
import 'package:flutter_chatgpt_api/flutter_chatgpt_api.dart';
import 'package:dotenv/dotenv.dart';
void main() {
loadDotenv(); // 加载.env文件
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ChatScreen(),
);
}
}
class ChatScreen extends StatefulWidget {
@override
_ChatScreenState createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
final TextEditingController _controller = TextEditingController();
String _response = '';
final chatGptClient = ChatGptClient(apiKey: DotEnv().env['OPENAI_API_KEY']!);
void _sendMessage() async {
if (_controller.text.isEmpty) return;
try {
final response = await chatGptClient.sendMessage(
model: "gpt-3.5-turbo", // 你可以根据需要选择不同的模型
prompt: _controller.text,
);
setState(() {
_response = response.data!.choices!.first!.text;
_controller.clear();
});
} catch (e) {
print(e);
setState(() {
_response = 'Error: ${e.message}';
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chat with ChatGPT'),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: _controller,
maxLines: 5,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Your Message',
),
),
SizedBox(height: 16),
Text(
_response,
style: TextStyle(fontSize: 18),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _sendMessage,
tooltip: 'Send',
child: Icon(Icons.send),
),
);
}
}
注意事项
- API配额和费用:ChatGPT API调用可能会产生费用,并受到配额限制。请确保你了解并管理这些配额和费用。
- 错误处理:在生产环境中,请确保添加适当的错误处理和用户反馈机制。
- 安全性:不要在客户端代码中硬编码API密钥。使用环境变量或后端服务来管理敏感信息。
这个示例代码展示了如何在Flutter应用中集成ChatGPT API,并允许用户发送消息和接收ChatGPT的响应。你可以根据需要对UI和功能进行进一步的自定义和扩展。