我正在做一個小組專案(非學術),前端作業的人已經停止回應。截止日期快到了,我有點擔心。專案的其余部分已完成,僅此一部分。誰能告訴我如何在 Dart 中重寫這個 Python 代碼或創建一個 Python API?它應該可以讓用戶輸入一條訊息,該訊息被發送到 GPT-3 API 并附加到generative_conversation字串中。然后將回傳的回應輸出到螢屏上。謝謝您的幫助。
顫振前端:
import 'package:flutter/material.dart';
import 'messageModel.dart';
class homepage extends StatefulWidget {
const homepage({Key? key}) : super(key: key);
@override
State<homepage> createState() => _homepageState();
}
class _homepageState extends State<homepage> {
ScrollController _scrollController = ScrollController();
List<ChatMessage> messages = [];
final myController = TextEditingController();
void clearText() {
myController.clear();
}
@override
void initState() {
_scrollController = ScrollController();
super.initState();
}
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
toolbarHeight: 100,
elevation: 0,
automaticallyImplyLeading: false,
backgroundColor: Color.fromARGB(255, 62, 238, 176),
flexibleSpace: SafeArea(
child: Container(
padding: EdgeInsets.only(right: 16),
child: Row(
children: <Widget>[
SizedBox(
width: 10,
),
CircleAvatar(
backgroundImage: NetworkImage(
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQtutzqepv7vSde5mQLzT00fWEbynYBq70VaQ&usqp=CAU"),
maxRadius: 40,
),
SizedBox(
width: 15,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"Carl Rogers",
style: TextStyle(
fontSize: 32, fontWeight: FontWeight.w600),
),
SizedBox(
height: 6,
),
],
),
),
],
),
),
)),
body: Stack(
children: <Widget>[
Container(
height: 600,
child: SingleChildScrollView(
child: ListView.builder(
controller: _scrollController,
itemCount: messages.length,
shrinkWrap: true,
padding: EdgeInsets.only(top: 10, bottom: 10),
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.only(
left: 14, right: 14, top: 10, bottom: 10),
child: Align(
alignment: (messages[index].messageType == "receiver"
? Alignment.topLeft
: Alignment.topRight),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: (messages[index].messageType == "receiver"
? Colors.grey.shade200
: Color.fromARGB(255, 93, 232, 183)),
),
padding: EdgeInsets.all(16),
child: Text(
messages[index].messageContent,
style: TextStyle(fontSize: 15),
),
),
),
);
},
),
),
),
Align(
alignment: Alignment.bottomLeft,
child: Container(
padding: EdgeInsets.only(left: 10, bottom: 10, top: 10),
height: 60,
width: double.infinity,
color: Colors.white,
child: Row(
children: <Widget>[
SizedBox(
width: 15,
),
Expanded(
child: TextField(
controller: myController,
decoration: InputDecoration(
hintText: "Write message...",
hintStyle: TextStyle(color: Colors.black54),
border: InputBorder.none),
),
),
SizedBox(
width: 15,
),
FloatingActionButton(
onPressed: () {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: Duration(milliseconds: 300),
curve: Curves.easeOut);
messages.add(ChatMessage(
messageContent: myController.text,
messageType: "sender"));
clearText();
setState(() {});
},
child: Icon(
Icons.send,
color: Colors.white,
size: 18,
),
backgroundColor: Color.fromARGB(255, 62, 238, 176),
elevation: 0,
),
],
),
),
),
],
),
),
);
}
}
Python:
def startSession():
global generative_conversation
activeSession = True
display_text = "Hello, nice to see you today."
print(display_text)
while(activeSession):
response = openai.Completion.create(
model = "text-davinci-002",
prompt = generative_conversation,
max_tokens = 100,
temperature = 0.8,
stop = "P:",
)
display_text = response["choices"][0]["text"]
user_input = input(f'\n{display_text}\n')
generative_conversation = generative_conversation[len(user_input):] f'P:{user_input}\n{display_text}T:'
if(user_input == "Quit" or user_input == "Q"):
activeSession = False
startSession()
uj5u.com熱心網友回復:
所以,我知道你想通過向它發送一些東西來接受 openAi 回應。這將帶來您想要的資訊。
要使用它,您應該添加“http”包。您可以通過在終端中撰寫來做到這一點:
flutter pub add http
不要忘記實作 URL 和您的 API_KEY。
import 'package:http/http.dart';
import 'dart:convert';
Future<String> getCompletionOpenAi(String userInput) async {
final client = Client();
//TODO: implement your API_KEY
final String apiKey = 'YOUR_API_KEY';
//TODO: implement your URL
final String url = 'YOUR_URL';
Map decodedResponse = {};
String displayText = '';
final Map<String, dynamic> bodyRequest = {
'model' : 'text-davinci-002',
'prompt' : userInput,
'max_tokens' : 100,
'temperature' : 0.8,
'stop' : 'P:',
};
Response response =
await client.post(
Uri.parse(url),
headers: {
'Content-Type': 'application/json',
'Authorization':'Bearer $apiKey',
},
body: jsonEncode(bodyRequest),
);
decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
displayText = decodedResponse['choices'][0]['text'];
return displayText;
}
呼入按鈕時:
onPressed() async {
String valueReturned = await getCompletionOpenAi(userInput);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/493174.html
上一篇:如何修復“無法讀取未定義的屬性(讀取'front_default')”?
下一篇:將暮光之城資料匯入谷歌表格
