AI Tools & Resources

Interactive Code Playground — AI Tutorial Examples

· 4 min read

Interactive Code Playground — AI Tutorial Examples

Try the code examples from our AI tutorials directly in your browser. Each example is editable and runnable via linked Colab notebooks or local setup instructions.

Available Examples

🤖 Example 1: Basic AI Chatbot

Build a conversational chatbot with memory and streaming responses. Uses LangChain + OpenAI/Ollama.

from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
from langchain_core.chat_history import InMemoryChatMessageHistory

llm = ChatOpenAI(model="gpt-4o-mini", streaming=True)
history = InMemoryChatMessageHistory()
history.add_message(SystemMessage(content="You are a helpful assistant."))

def chat(text):
    history.add_message(HumanMessage(content=text))
    response = ""
    for chunk in llm.stream(history.messages):
        print(chunk.content or "", end="")
        response += chunk.content or ""
    history.add_message(AIMessage(content=response))
    return response

chat("Hello! What can you help me with?")

Open in Colab →

🧠 Example 2: RAG Pipeline

Retrieve relevant documents and feed them to an LLM for grounded responses.

from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

# Build vector store
embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_texts(
    ["Document 1 content...", "Document 2 content..."],
    embeddings
)
retriever = vectorstore.as_retriever()

# RAG chain
prompt = ChatPromptTemplate.from_template(
    "Answer based on context:n{context}nnQuestion: {question}"
)
llm = ChatOpenAI(model="gpt-4o-mini")

def format_docs(docs):
    return "nn".join(d.page_content for d in docs)

rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt | llm
)

result = rag_chain.invoke("What is the main topic?")
print(result.content)

Open in Colab →

🎯 Example 3: LoRA Fine-Tuning Loop

The core training loop for fine-tuning a model with LoRA adapters.

from unsloth import FastLanguageModel
from trl import SFTTrainer
from transformers import TrainingArguments
import torch

# Load model
model, tokenizer = FastLanguageModel.from_pretrained(
    "unsloth/Llama-3.2-1B-Instruct",
    max_seq_length=2048,
    load_in_4bit=True,
)

# Apply LoRA
model = FastLanguageModel.get_peft_model(
    model, r=16,
    target_modules=["q_proj","k_proj","v_proj","o_proj",
                    "gate_proj","up_proj","down_proj"],
)

# Train
trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=dataset["train"],
    dataset_text_field="text",
    max_seq_length=2048,
    args=TrainingArguments(
        per_device_train_batch_size=2,
        gradient_accumulation_steps=4,
        num_train_epochs=3,
        learning_rate=2e-4,
        output_dir="outputs",
        optim="adamw_8bit",
    ),
)
trainer.train()

# Save
model.save_pretrained_merged("my_finetuned_model", 
                              tokenizer, save_method="merged_16bit")
print("Training complete! Model saved.")

Open in Colab →

📊 Example 4: Evaluating Model Output

Simple evaluation harness for measuring response quality.

from langchain.evaluation import load_evaluator
from langchain_openai import ChatOpenAI

evaluator = load_evaluator(
    "criteria",
    criteria="conciseness",
    llm=ChatOpenAI(model="gpt-4o-mini")
)

prediction = "The capital of France, which is a country in Western Europe, is Paris."
reference = "Paris"

result = evaluator.evaluate_strings(
    prediction=prediction,
    reference=reference,
)
print(f"Score: {result['score']}")
print(f"Reasoning: {result['reasoning']}")

Open in Colab →

Running Locally

To run these examples on your own machine:

git clone https://github.com/datagate-ch/ai-tutorials.git
cd ai-tutorials
pip install -r requirements.txt
# Copy .env.example and fill in your API keys
cp .env.example .env
# Run any example
python examples/01_basic_chatbot.py

Tips

Related tutorials: Build Your First AI Chatbot · Fine-Tune an LLM on Custom Data

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert