Home > Mobile >  How do I write this Python code inside a Flutter application?
How do I write this Python code inside a Flutter application?

Time:06-19

I'm doing a group project (non-academic) and the person working on the front-end has stopped responding. The deadline is getting close and I'm getting a little worried. The rest of the project is done it's just this one part. Could anyone tell me how to re-write this Python code in Dart or create a Python API? It should work such that the user enters a message, that message is sent to the GPT-3 API and appended to the generative_conversation string. The returned response is then outputted onto the screen. Thanks for the help.

Flutter front-end:

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()

CodePudding user response:

So, I get that you want to take the openAi response by sending something to it. This will bring the info you want.

To use it, you should add 'http' package. You can do it by writing in terminal:

flutter pub add http


Do not forget to implement the URL and your 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: bodyRequest,
      );
    
    decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
    
    displayText = decodedResponse['choices'][0]['text'];
    
    return displayText;
}
  • Related