Generative AI
LLMs
AI technology
OpenAI
Written by:
Building an AI application can be challenging without prior experience. In this article, we will explore the OpenAI API for chat completions, the most common parameters, how to get an OpenAI API key, and we will write the necessary code to build a command line chat application. This can be the perfect first AI application and the entry point to build awesome things. Let's start!
Before we dive into coding, we need to set up our environment. Follow these steps:
Install Python: Make sure you have Python installed on your machine. You can download it from python.org.
Install the OpenAI SDK: Open your terminal and run the following command to install the OpenAI SDK:
1pip install openai
Get Your OpenAI API Key:
Set Your API Key as an Environment Variable:
1export OPENAI_API_KEY="your_api_key_here"
1set OPENAI_API_KEY="your_api_key_here"
Now that we have our environment set up, let's create a simple command line chatbot. We will create a Python file named chatbot.py
.
chatbot.py
1import os 2import openai 3 4# Load your API key from an environment variable 5openai.api_key = os.getenv("OPENAI_API_KEY") 6 7# Initialize conversation history 8conversation_history = [] 9 10def get_chat_response(user_input): 11 # Append user input to conversation history 12 conversation_history.append({"role": "user", "content": user_input}) 13 14 response = openai.ChatCompletion.create( 15 model="gpt-4o-mini", 16 messages=[ 17 {"role": "system", "content": "You are a helpful assistant."}, 18 ] + conversation_history, # Include conversation history 19 temperature=0.7, # Controls randomness of the output 20 max_tokens=150, # Limits the response length 21 n=1, # Number of responses to generate 22 stop=None # You can specify stop sequences here 23 ) 24 25 # Get the assistant's response 26 assistant_response = response.choices[0].message['content'] 27 28 # Append assistant response to conversation history 29 conversation_history.append({"role": "assistant", "content": assistant_response}) 30 31 return assistant_response 32 33def main(): 34 print("Welcome to the Chatbot! Type 'exit' to quit.") 35 while True: 36 user_input = input("You: ") 37 if user_input.lower() == 'exit': 38 break 39 response = get_chat_response(user_input) 40 print(f"Chatbot: {response}") 41 42if __name__ == "__main__": 43 main()
os
for environment variables and openai
for accessing the OpenAI API.conversation_history
to keep track of the dialogue.get_chat_response
: This function takes user input, appends it to the conversation history, sends it to the OpenAI API, and returns the chatbot's response.
model
: Specifies which model to use (e.g., gpt-4o-mini
).messages
: An array of message objects that includes the system message and the conversation history.temperature
: Controls the randomness of the output (0.0 for deterministic, 1.0 for more random).max_tokens
: Limits the number of tokens in the response.n
: Number of responses to generate.stop
: Optional parameter to specify stop sequences.main
function runs a loop that takes user input and prints the chatbot's response until the user types 'exit'.To run your chatbot, open your terminal and execute the following command:
1python chatbot.py
You should see a welcome message, and you can start chatting with your AI assistant!
Congratulations! You've just built your first AI application using Python and the OpenAI API. This simple command line chatbot can be expanded with more features, such as saving conversation history, integrating with web applications, or even adding voice capabilities.
Feel free to explore the OpenAI API documentation for more advanced features and parameters. The possibilities are endless!