How To Implement ChatGPT In Flutter

Introduction

In this article, we will learn about how to implement ChatGPT in flutter development. ChatGPT is an AI language model developed by OpenAI. It uses deep learning techniques to generate human-like text based on the input it receives. ChatGPT can be used for a variety of tasks such as chatbots, question answering, language translation, etc. 

 

Prerequisites

  • Having the latest version of Android Studio
  • Having Installed Flutter and Dart in Android Studio
  • Having Basic knowledge of Flutter Development

Let's Start With Android Studio  

Step 1

Open Android Studio and click on the New Flutter Project button

 

Step 2

Click on the Next Button 

 

Step 3

Edit the project name, android language, iOS language, and platform, and click on Create button

 

Step 4

Generate API key

Open the below URL and register yourself in openAI Platform and click on create new secret key button

URL -  https://platform.openai.com/account/api-keys

   

Please save your API KEY. It will be used further.

Step 5.

We are going to implement ChatGPT using the following URL

API URL - https://api.openai.com/v1/completions

API Request

curl https://api.openai.com/v1/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}'

API Response

{
    "id": "cmpl-GERzeJQ4lvqPk8SkZu4XMIuR",
    "object": "text_completion",
    "created": 1586839808,
    "model": "text-davinci:003",
    "choices": [{
        "text": "\n\nThis is indeed a test",
        "index": 0,
        "logprobs": null,
        "finish_reason": "length"
    }],
    "usage": {
        "prompt_tokens": 5,
        "completion_tokens": 7,
        "total_tokens": 12
    }
}

Step 6

Go to pubspec.yaml file in the flutter project and add the following dependency in the dependencies section. Please specially take care of indentation in pubspec.ymal file.

# Added chatGPT SDK using this link - https://pub.dev/packages/chat_gpt_sdk
chat_gpt_sdk: ^1.0.2+3

# Added http package for Api Calls using this link - https://pub.dev/packages/http
http: ^0.13.5

# Added velocity package to make Flutter development easier and more joyful by using this link - 
# https://pub.dev/packages/velocity_x
velocity_x: ^3.6.0

Step 7

 After adding the dependency please make sure to click on the pub get button.

 

Step 7

Go to AndroidManifest.xml and added the below permissions

 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Step 8

Go to main.dart in the lib folder and replace the existing code with the following code

import 'package:chatgptexample/chat_srceen.dart';
import 'package:flutter/material.dart';

// Entry Point
void main() {
    runApp(const MyApp());
}
class MyApp extends StatelessWidget {
    const MyApp({
        Key ? key
    }): super(key: key);
    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            // Disable debug banner
            debugShowCheckedModeBanner: false,
            // set title name
            title: 'ChatGPT App',
            // select theme
            theme: ThemeData(primarySwatch: Colors.green, ),
            // Here we are calling a Screen named ChatScreen
            home: ChatScreen(), );
    }
}

Step 9

Create a new file named chat_srceen.dart and add the below code 

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:velocity_x/velocity_x.dart';
import 'chatmessage.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class ChatScreen extends StatefulWidget {
    const ChatScreen({
        Key ? key
    }): super(key: key);
    @override
    State < ChatScreen > createState() => _ChatScreenState();
}
class _ChatScreenState extends State < ChatScreen > {
    // To get text from textfield I have create controller.
    final TextEditingController _controller = TextEditingController();
    // Create a list
    final List < ChatMessage > _message = [];
    // Api key - Please generate YOUR_API_KEY from here
    // https://platform.openai.com/account/api-keys
    // Replace with Your API-KEY
    String apiKey = "Your API-KEY";
    Future < void > _sendMessage() async {
        // Create Create ChatMessage Class object and pass the user input
        ChatMessage message = ChatMessage(text: _controller.text, sender: "user");
        // Refresh the page
        setState(() {
            _message.insert(0, message);
        });
        // clear the user input from text-field
        _controller.clear();
        // Call the generateText method and store result into response
        final response = await generateText(message.text);
        // Create Create ChatMessage Class object and pass the bot output
        ChatMessage botMessage = ChatMessage(text: response.toString(), sender: "bot");
        // Refresh the page
        setState(() {
            _message.insert(0, botMessage);
        });
    }
    Future < String > generateText(String prompt) async {
        // Here we have to create body based on the document
        try {
            Map < String, dynamic > requestBody = {
                "model": "text-davinci-003",
                "prompt": prompt,
                "temperature": 0,
                "max_tokens": 100,
            };
            // Post Api Url
            var url = Uri.parse('https://api.openai.com/v1/completions');
            //  use post method of http and pass url,headers and body according to documents
            var response = await http.post(url, headers: {
                "Content-Type": "application/json",
                "Authorization": "Bearer $apiKey"
            }, body: json.encode(requestBody)); // post call
            // Checked we get the response or not
            // if status code is 200 then Api Call is Successfully Executed
            if (response.statusCode == 200) {
                var responseJson = json.decode(response.body);
                return responseJson["choices"][0]["text"];
            } else {
                return "Failed to generate text: ${response.body}";
            }
        } catch (e) {
            return "Failed to generate text: $e";
        }
    }
    //  This method is used for making bottom user input text-field and and send icon part
    Widget _buidTextComposer() {
        return Row(children: [
            Expanded(child: TextField(controller: _controller, decoration: InputDecoration.collapsed(hintText: "Send a message"), ), ),
            IconButton(onPressed: () {
                _sendMessage();
            }, icon: Icon(Icons.send))
        ], ).px12();
    }
    @override
    Widget build(BuildContext context) {
        return Scaffold(
            // App bar
            appBar: AppBar(centerTitle: true, title: Text("ChatGPT App"), ),
            // body
            body: SafeArea(child: Column(children: [
                Flexible(child: ListView.builder(padding: Vx.m8, reverse: true, itemBuilder: (context, index) {
                    return _message[index];
                }, itemCount: _message.length, )),
                Divider(height: 1, ),
                Container(decoration: BoxDecoration(), child: _buidTextComposer(), )
            ], ), ), );
    }
}

Step 10

Create a new file named chatmessage.dart and add the below code 

import 'package:flutter/material.dart';
import 'package:velocity_x/velocity_x.dart';

class ChatMessage extends StatelessWidget {
    const ChatMessage({
        Key ? key,
        required this.text,
        required this.sender
    }): super(key: key);
    // Use for User Input and chatbot output
    final String text;
    // Use for check sender is user or bot
    final String sender;
    @override
    Widget build(BuildContext context) {
        return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(sender).text.subtitle1(context).make().box.color(sender == 'user' ? Vx.red200 : Vx.green200).p16.rounded.alignCenter.makeCentered(),
            Expanded(child: text.trim().text.bodyText1(context).make().px8())
        ], ).py8();
    }
}

Output

  

Conclusion

In this article, we have seen how to implement ChatGPT in the flutter application. Thanks for reading and hope you like it. If you have any suggestions or queries on this article, please share your thoughts. you can read my other articles by clicking here.

Happy learning, friends!