Skip to content

How to Write Your First AI Program in Python with Ollama

Building Your First AI Program in Python: A Step-by-Step Guide

In this tutorial, you will learn how to create a Python program that communicates with a local AI model (Ollama) to ask a question and receive an intelligent response. To get started, you should first complete the Free AI Development Setup: Install Python, VS Code & Ollama Tools guide if you haven't already. We will break down the code line by line so you understand each component.

Step 1: Import the Necessary Libraries

The first three lines of your program are critical for enabling communication with the AI model.

  • from openai import OpenAI: This imports the OpenAI library, which acts as a telephone line allowing Python to talk to the AI model (Ollama). Without this, there is no communication.
  • from dotenv import load_dotenv: This imports the load_dotenv function, which reads configuration values (like API keys and model names) from a separate .env file. This is a best practice to keep sensitive settings out of your main code.
  • import os: The OS library gives Python access to the operating system, enabling it to read environment variables and run commands.

Step 2: Load Environment Variables

load_dotenv()

This single line loads all values from your .env file (base URL, API key, model name) into your Python program. For a deeper dive into this step, see How to Configure AI Model Settings for Your First Python Program. After this, your program knows where to connect and what model to use.

Step 3: Create a Client to Connect to the AI Model

client = OpenAI(base_url=os.getenv("BASE_URL"), api_key=os.getenv("API_KEY"))

This creates a client object that establishes a connection to the Ollama AI model. Think of it as dialing a phone number, now Python knows exactly where to send your questions.

Step 4: Send a Question to the AI Model

response = client.chat.completions.create(
    model=os.getenv("MODEL_NAME"),
    messages=[
        {"role": "user", "content": "What is artificial intelligence?"}
    ]
)
  • The function client.chat.completions.create() sends your question to the AI.
  • Arguments:
    • model: Specifies which AI model to use (e.g., "llama3").
    • messages: A list containing a dictionary with:
      • "role": Identifies who is speaking (here, "user").
      • "content": The actual question text.
  • The AI processes the question and stores the complete response in the response variable.

Step 5: Display the Answer

print(response.choices[0].message.content)

The AI returns a large response object with extra information. To extract just the answer, navigate to response.choices[0].message.content. This is where the generated text lives.

How to Run Your Program

  1. Save your file (e.g., hello_ai.py).
  2. Open a terminal in VS Code.
  3. Run the command: python hello_ai.py.

If everything is configured correctly, you will see the AI's answer, like a definition of artificial intelligence.

Congratulations!

You have just built your first AI-powered application. Your Python program successfully communicated with a local AI model and received an intelligent response. This simple pattern is the foundation of every AI assistant you will build in this course.

Key Takeaways

  • The OpenAI library enables Python-AI communication.
  • Use dotenv to securely manage configuration.
  • The client object connects your program to the model.
  • Questions are sent in a structured format with role and content.
  • The answer is extracted from response.choices[0].message.content.

Common Pitfalls to Avoid

This foundational program will be the basis for all future AI projects. Practice by changing the question and seeing how the model responds. Happy coding!

Keep this summary

Save it to LunaNotes and it becomes a real note in your library — editable, searchable, and ready to turn into flashcards or a diagram. Free to start.

Save to LunaNotes

Or summarise for another video.

32K+ people have turned 65K+ videos into notes

“Very useful tool. I'm using it for the last couple weeks and I'm loving it so far. Makes learning on YouTube a great experience.”
Bhai Chrome Web Store review

This summary and transcript were automatically generated using AI with the Free YouTube transcript summary tool by LunaNotes.

Related summaries

Install Python, VS Code, and Ollama for AI Agent Development

Install Python, VS Code, and Ollama for AI Agent Development

This video provides a step-by-step guide to setting up your development environment for building AI agents. Learn how to install Python, download and configure Visual Studio Code, and set up Ollama with large language models.

Install Ollama and Run Qwen3 4B Locally – AI Model Setup Guide

Install Ollama and Run Qwen3 4B Locally – AI Model Setup Guide

Learn how to install the Ollama AI framework on your computer, download the lightweight Qwen3 4B model, and run it locally via terminal. This step-by-step tutorial lets you chat with an open-source LLM right on your own laptop—no cloud or GPU required.

Free AI Development Setup: Install Python, VS Code & Ollama Tools

Free AI Development Setup: Install Python, VS Code & Ollama Tools

Learn how to set up a complete local AI development environment using three free tools. This guide covers Python installation, Visual Studio Code setup, and Ollama for running AI models on your own computer — no GPU or cloud costs required.

How to Configure AI Model Settings for Your First Python Program

How to Configure AI Model Settings for Your First Python Program

Learn to set up a configuration file (.env) for your AI program, including base URL, API key, and model name. This tutorial shows how to configure Ollama locally so your Python code can communicate with an AI model without hardcoding settings.

How AI Models Work: Cloud vs. Local (Free Ollama Setup)

How AI Models Work: Cloud vs. Local (Free Ollama Setup)

Discover how an AI assistant processes questions like 'What is machine learning?' in four simple steps. Learn the difference between cloud-based AI models and free local alternatives like Ollama, perfect for hands-on learning without API costs.

Found this summary useful?

Take it with you. One click puts it in your own LunaNotes library.

Save to LunaNotes

Start taking better notes today with LunaNotes