Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials AI ChatGPT & Large Language Models
AI Intermediate FREE

ChatGPT & Large Language Models

Lesson 2 of 17 Intermediate Interactive

Large Language Models (LLMs) like GPT-4 are trained on massive text data to understand and generate language.

Syntax

AI
from openai import OpenAI

client = OpenAI(api_key="your-key")
response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
Simple Text Generation
PYTHON
import random

# Simple markov chain text generator
def build_chain(text):
    words = text.split()
    chain = {}
    for i in range(len(words) - 1):
        key = words[i]
        if key not in chain:
            chain[key] = []
        chain[key].append(words[i + 1])
    return chain

def generate(chain, length=20):
    word = random.choice(list(chain.keys()))
    result = [word]
    for _ in range(length - 1):
        if word in chain:
            word = random.choice(chain[word])
            result.append(word)
    return " ".join(result)

text = "the cat sat on the mat the dog ran in the park"
chain = build_chain(text)
print(generate(chain))

Practice

1
Exercise

Practice this concept.

Answer
Write the code as shown above.

Quick Quiz

1

What did you learn?

This covers the basics.

Interview Questions

It is a fundamental AI feature.