Open In App

Creating ChatGPT Clone in Python

Last Updated : 18 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are learning how to develop a chat application with multiple nodes and an answering bot made with OpenAI’s text-davinci-003 [ChatGPT API ] model engine using Flet in Python.

What is Flet?

Without using Flutter directly, programmers can create real-time web, mobile, and desktop apps using the Flet Python library. While creating apps with Flutter, developers must understand the Dart programming language, but by using the Flet module and simple Python code, we can create apps that function similarly to those created with Flutter.

Main Features of Flet :

  • Powered By Flutter: Your app will look fantastic and function on any platform because Flet UI is made with Flutter. Flet streamlines the Flutter strategy by incorporating smaller “widgets” into ready-to-use “controls” with an imperative programming language.
  • Architecture: With Flet you just write a monolith stateful app in Python only and get a multi-user, real-time Single-Page Application.
  • Ability to deliver the app to any device: We can deploy Flet app as a web app and run it in the browser. The package can also be installed on Windows,macOS and Linux. It can also be installed on Mobile.

Required Modules :

For this tutorial, we will be using the Flet module and openai module [ChatGPT] of python. To install it using pip, run the following command in the terminal.

pip install flet
pip install openai

Source Code :

Python3




import flet as ft
  
  
class Message():
    def __init__(self, user_name: str, text: str, message_type: str):
        self.user_name = user_name
        self.text = text
        self.message_type = message_type
  
  
class ChatMessage(ft.Row):
    def __init__(self, message: Message):
        super().__init__()
        self.vertical_alignment = "start"
        self.controls = [
            ft.CircleAvatar(
                content=ft.Text(self.get_initials(message.user_name)),
                color=ft.colors.WHITE,
                bgcolor=self.get_avatar_color(message.user_name),
            ),
            ft.Column(
                [
                    ft.Text(message.user_name, weight="bold"),
                    ft.Text(message.text, selectable=True),
                ],
                tight=True,
                spacing=5,
            ),
        ]
  
    def get_initials(self, user_name: str):
        return user_name[:1].capitalize()
  
    def get_avatar_color(self, user_name: str):
        colors_lookup = [
            ft.colors.AMBER,
            ft.colors.BLUE,
            ft.colors.BROWN,
            ft.colors.CYAN,
            ft.colors.GREEN,
            ft.colors.INDIGO,
            ft.colors.LIME,
            ft.colors.ORANGE,
            ft.colors.PINK,
            ft.colors.PURPLE,
            ft.colors.RED,
            ft.colors.TEAL,
            ft.colors.YELLOW,
        ]
        return colors_lookup[hash(user_name) % len(colors_lookup)]
  
  
def main(page: ft.Page):
    page.horizontal_alignment = "stretch"
    page.title = "ChatGPT - Flet"
  
    def join_chat_click(e):
        if not join_user_name.value:
            join_user_name.error_text = "Name cannot be blank!"
            join_user_name.update()
        else:
            page.session.set("user_name", join_user_name.value)
            page.dialog.open = False
            new_message.prefix = ft.Text(f"{join_user_name.value}: ")
            page.pubsub.send_all(Message(user_name=join_user_name.value,
                                         text=
            f"{join_user_name.value}+has joined the chat.", message_type="login_message"))
            page.update()
  
    def send_message_click(e):
        if new_message.value != "":
            page.pubsub.send_all(Message(page.session.get(
                "user_name"), new_message.value, message_type="chat_message"))
            temp = new_message.value
            new_message.value = ""
            new_message.focus()
            res = chatgpt(temp)
            if len(res) > 220# adjust the maximum length as needed
                res = '\n'.join([res[i:i+220]
                                 for i in range(0, len(res), 220)])
            page.pubsub.send_all(
                Message("ChatGPT", res, message_type="chat_message"))
            page.update()
  
    def chatgpt(message):
        import openai
  
        # Set up the OpenAI API client
        openai.api_key = "YOUR API"
  
        # Set up the model and prompt
        model_engine = "text-davinci-003"
        prompt = message
        # Generate a response
        completion = openai.Completion.create(
            engine=model_engine,
            prompt=prompt,
            max_tokens=1024,
            n=1,
            stop=None,
            temperature=0.5,
        )
  
        response = completion.choices[0].text.strip()
        if response.startswith('\n'):
            response = response[1:]
        return response
  
    def on_message(message: Message):
        if message.message_type == "chat_message":
            m = ChatMessage(message)
        elif message.message_type == "login_message":
            m = ft.Text(message.text, italic=True,
                        color=ft.colors.BLACK45, size=12)
        chat.controls.append(m)
        page.update()
  
    page.pubsub.subscribe(on_message)
  
    # A dialog asking for a user display name
    join_user_name = ft.TextField(
        label="Enter your name to join the chat",
        autofocus=True,
        on_submit=join_chat_click,
    )
    page.dialog = ft.AlertDialog(
        open=True,
        modal=True,
        title=ft.Text("Welcome!"),
        content=ft.Column([join_user_name], width=300, height=70, tight=True),
        actions=[ft.ElevatedButton(
            text="Join chat", on_click=join_chat_click)],
        actions_alignment="end",
    )
  
    # Chat messages
    chat = ft.ListView(
        expand=True,
        spacing=10,
        auto_scroll=True,
    )
  
    # A new message entry form
    new_message = ft.TextField(
        hint_text="Write a message...",
        autofocus=True,
        shift_enter=True,
        min_lines=1,
        max_lines=5,
        filled=True,
        expand=True,
        on_submit=send_message_click,
    )
  
    # Add everything to the page
    page.add(
        ft.Container(
            content=chat,
            border=ft.border.all(1, ft.colors.OUTLINE),
            border_radius=5,
            padding=10,
            expand=True,
        ),
        ft.Row(
            [
                new_message,
                ft.IconButton(
                    icon=ft.icons.SEND_ROUNDED,
                    tooltip="Send message",
                    on_click=send_message_click,
                ),
            ]
        ),
    )
  
  
# to run the flet application as a web application on the browser
ft.app(target=main, port=9000, view=ft.WEB_BROWSER)
# to run the flet application as a desktop application
ft.app(target=main) 


Code Explanation :

The Message class defines the structure of a message, and the ChatMessage class creates a graphical representation of a message that can be displayed in the chat. The main function defines the overall structure of the chat application, including the chat window, the new message entry form, and the functionality for sending messages and receiving responses from OpenAI’s GPT-3 language model.

The chat application uses the flet library to create a graphical user interface, including text fields, buttons, and icons. The ft.app function starts a web server and renders the chat application in a web browser.

Note:

Add your own OpenAI Secret key from (https://platform.openai.com/account/api-keys) on line 88 of the code above.

To run the Flet application on the browser add this piece of code to the bottom of the code :

ft.app(port=any-port-number,target=main,view=ft.WEB_BROWSER)

To run the Flet application as a desktop application add this piece of code to the bottom of the code :

ft.app(target=main)

Output :

Chat Application Joining Option

ChatGPT Response Application using Flet in Python

To learn more about Chat GPT, you can refer to:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads