Self-paced

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Search from all Lessons


LoginGet Started
← Back to How to's
Edit on Github

How to Make Your First AI Application

Written by:

Programador frente a una laptop

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!

Step 1: Setting Up Your Environment

Before we dive into coding, we need to set up our environment. Follow these steps:

  1. Install Python: Make sure you have Python installed on your machine. You can download it from python.org.

  2. Install the OpenAI SDK: Open your terminal and run the following command to install the OpenAI SDK:

    1pip install openai
  3. Get Your OpenAI API Key:

    • Go to the OpenAI API dashboard.
    • Sign up or log in to your account.
    • Create a new API key and store it securely.
  4. Set Your API Key as an Environment Variable:

    • On Unix systems, you can do this by running:
      1export OPENAI_API_KEY="your_api_key_here"
    • On Windows, you can set it in the command prompt:
      1set OPENAI_API_KEY="your_api_key_here"

Step 2: Creating Your Chatbot Application

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.

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

Explanation of the Code

  • Importing Libraries: We import the necessary libraries, including os for environment variables and openai for accessing the OpenAI API.
  • Setting the API Key: We load the API key from the environment variable.
  • Conversation History: We initialize an empty list conversation_history to keep track of the dialogue.
  • Function 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.
    • Parameters:
      • 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 Loop: The main function runs a loop that takes user input and prints the chatbot's response until the user types 'exit'.

Step 3: Running Your Chatbot

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!

Conclusion

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!