首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在颤振应用程序中编写这段Python代码?

如何在颤振应用程序中编写这段Python代码?
EN

Stack Overflow用户
提问于 2022-06-19 02:41:17
回答 1查看 129关注 0票数 0

我正在做一个小组项目(非学术性的),前端工作的人已经停止了回应。截止日期快到了,我有点担心。项目的其余部分已经完成--这只是其中的一部分。有人能告诉我如何用Dart重写这个Python代码或创建Python吗?它的工作方式应该是用户输入一条消息,该消息被发送到GPT-3API并附加到generative_conversation字符串中。然后将返回的响应输出到屏幕上。谢谢你的帮助。

颤振前端:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-19 04:39:47

因此,我知道您想通过向它发送一些东西来获取openAi响应。这会带来你想要的信息。

要使用它,您应该添加'http‘包。你可以在终端上写:

flutter pub add http

不要忘记实现URL和您的API_KEY。

代码语言:javascript
复制
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;
}

当呼叫按钮:

代码语言:javascript
复制
onPressed() async {
    String valueReturned = await getCompletionOpenAi(userInput);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72673943

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档