Develop your own AI conversational robot with 35 lines of Python code

Although the API currently provided by OpenAI cannot develop applications that continue conversations on the same topic like ChatGPT (you can look forward to the soon-to-be-released ChatGPT API, but it will be charged), based on a piece of knowledge and a text editing requirement, such as continuing to write , or a single text requirement such as a writing outline, using the current Open AI Text Completion class API and the Steamlit library, you can easily develop a conversational web application. And because the API is used for access, there is no restriction on access IP during normal use, and there is no congestion or queuing.

Old rules, OpenAI website: openai.com. Registration and login require Google access and overseas mobile phone number verification (there are many tutorials, which can be directly searched on the platform).

Streamlit

Streamlit is an open source framework ideal for machine learning and data science. Developers use it to create interactive applications for data visualization and data analysis without writing large amounts of HTML, CSS, or JavaScript code. Streamlit builds applications with Python, making it easy for data scientists and software engineers to use existing skills to create interactive web for data exploration and data analysis. This article uses Streamlit to develop this AI conversational web page.

There are two ways to use Streamlit, one is in their own cloud platform, and the other is installed locally on your own computer or server. For the first option, you need to register an account on the Streamlit platform and link your own GitHub. I won’t introduce it here. Here we mainly introduce the second method, because it is more free to use.

OpenAI API

To use the API, you need to obtain an OpenAI API key. You need to visit and register an OpenAI account. There are many specific methods on CSDN and I will not repeat them here.

What we have today The interface to be used is in Text completion.

Once we have an account, we can find the API Key in our account, as shown below. Note that when creating an API Key, be sure to copy it immediately, because after you close the dialog box after creating it, you will no longer be able to see the complete Key.

With the API key in hand, we can create a Streamlit Python script.

Create Python script

First, install the necessary libraries:

$ pip install streamlit
$ pip install streamlit_chat
$ pip install openai
$ pip install python-detenv

The specific code implementation is very easy. First, import the required libraries and add the API Key just copied to openai.api_key.

import openai
import streamlit as st
from streamlit_chat import message
import os
from dotenv import load_dotenv
openai.api_key = 'Your API_KEY'
Then define the generate_response() function:
def generate_response(prompt):
    completion=openai.Completion.create(
        engine='text-davinci-003',
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.6,
    )
    message=completion.choices[0].text
    return message

Generate OpenAI’s text completion model response from GPT-3 by passing user dialogue commands (Prompt) as parameters. We have also specified the model text-davinci-003’ here. Of course, you can also use other models, but Davinci’s training data is currently relatively new.

You can also set a word limit (max_tokens) for Prompt.

There is also a temperature variable that is very relevant, as it essentially defines the level of AI creativity, and it can be set between 0 and 1. 0 produces robust output, while 1 is highly creative.

The following code demonstrates how to use streamlit, including a third-party library streamlit_chat, to build a conversational web interface, which creates past (the text input by the user in the input box) and generated (the API reply after calling generate_response() text) list, used to save and display historical conversation records. The code is very simple and clear at a glance:

st.title("AI Chatbot from Yeyu Lab")
#storing the chat
if 'generated' not in st.session_state:
    st.session_state['generated'] = []
if 'past' not in st.session_state:
    st.session_state['past'] = []
user_input=st.text_input("You:",key='input')
if user_input:
    output=generate_response(user_input)
    #store the output
    st.session_state['past'].append(user_input)
    st.session_state['generated'].append(output)
if st.session_state['generated']:
    for i in range(len(st.session_state['generated'])-1, -1, -1):
        message(st.session_state["generated"][i], key=str(i))
        message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')

The above is all the code. Combine it and save it as demo.py. There are less than 40 lines in total. Next, you only need to enter the command line in the file directory:

python -m streamlit run demo.py

You will see the following print, and a web page with a smooth interface will be opened locally:

You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8502
  Network URL: http://xxx.xxx.xxx.xxx(my IP):8502

Well, try talking to him. You can say hello to him, gain knowledge, ask him to provide a writing outline, ask him to continue your article, or summarize a paragraph of text for you.

Until the ChatGPT API is released, this is probably the easiest way to use the GPT-3 model. The last thing that needs to be mentioned is that regarding the use of Streamlit, we must know that if we need to make a large-scale application with strong interactivity and security, we should still consider using web frameworks such as Django for development.

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.

1. Python learning routes in all directions

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Python essential development tools

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

img

6. Interview Guide

Resume template

If there is any infringement, please contact us for deletion