ChatGPT很强,最近正好在做IM项目,提出来一个ChatPage页面改改,也很nice,基本上和微信差不多了,表情,更多,语音,没有用到,就单纯的想接入一下看一下效果。
于是,就想了想实现,页面有了,去翻了翻仓库,发现一个 chat_gpt_sdk,可以自行搜索,就去openAI官网搞了一个key,万事俱备。(得科学上网)
late OpenAI openAI;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const Duration(milliseconds: 100), vsync: this);
animation = Tween(begin: 0.0, end: 300.0).animate(controller)
..addListener(() {
setState(() {});
});
openAI = OpenAI.instance.build(
token: "这个就是我搞的token",
baseOption: HttpSetup(receiveTimeout: 6000),
isLogger: true);
}
然后就是监听返回的文字,弄了一个简单Model,区分自己还是机器人
class MessageGPT {
final bool isSelf;
final String text;
MessageGPT(this.isSelf, this.text);
}
List<MessageGPT> message = [];
void _listener(String word) async {
final request =
CompleteText(prompt: word, maxTokens: 200, model: kTranslateModelV3);
openAI.onCompleteText(request: request).asStream().listen((res) {
print("ChatGPT回答:${res?.choices.last.text}");
message.insert(0, MessageGPT(false, res?.choices.last.text.trim() ?? ""));
setState(() {});
});
}
// 消息列表气泡的代码
Widget getItme(bool isSelef, String text) {
return Container(
margin: EdgeInsets.only(bottom: 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment:
isSelef ? MainAxisAlignment.end : MainAxisAlignment.start,
children: [
if (!isSelef)
Container(
margin: EdgeInsets.only(right: 10),
child: ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Container(
width: 40,
height: 40,
child: Image.network(
"https://img2.baidu.com/it/u=2421090168,324781765&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500")),
),
),
WechatBubble(
direction: !isSelef
? WechatBubbleDirection.left
: WechatBubbleDirection.right,
color: Colors.white,
child: Text("${text}",
style: TextStyle(color: Colors.black, fontSize: 14)),
),
if (isSelef)
Container(
margin: EdgeInsets.only(left: 10),
child: ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Container(
width: 40,
height: 40,
child: Image.network(
"https://img2.baidu.com/it/u=2421090168,324781765&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500")),
),
),
],
),
);
}
接下来监听 TextField --- onEditingComplete 更新UI上去