Welcome to CSI 4106!

CSI 4106 - Fall 2026

Marcel Turcotte

Version: Sep 11, 2026 12:09

Preamble

Message of the day (MOTD)

Joëlle Pineau — an AI leader from Ottawa

Cohere raises US$500-million, hires former Meta AI expert Joelle Pineau, Joe Castaldo, The Globe and Mail, 2025-08-14.

Learning objectives

  • Clarify the proposition
  • Discuss the syllabus
  • Articulate the expectations
  • Explore the various definitions of “artificial intelligence”

Proposition

Course overview

Calendar description

The roots and scope of Artificial Intelligence. Knowledge and knowledge representation. Search, informed search, adversarial search. Deduction and reasoning. Uncertainty in Artificial Intelligence. Introduction to Natural Language Processing. Elements of planning. Basics of Machine Learning.

Aims: Deep learning early

To the larger community of computer science and information technology, AI is usually identified by the techniques grown from it, which at different periods may include theorem proving, heuristic search, game playing, expert systems, neural networks, Bayesian networks, data mining, agents, and recently, deep learning.

  • Deep learning is so dominant that I have chosen to structure everything around it

What does this mean?

Good Old-Fashioned AI (GOFAI) relied on hand-crafted knowledge engineering, but it has been largely displaced by machine learning due to the increased availability of data, computing resources, and new algorithms.

Deep learning has significantly impacted various domains, including natural language processing, robotics, and computer vision.

However, deep learning has current limitations, particularly in reasoning, where symbolic AI excels and could potentially offer valuable insights.

But also

  • In A Brief History of Intelligence (Bennett 2023), Max Bennett discusses significant milestones in the evolution of human intelligence and draws parallels to advancements in artificial intelligence (AI).
  • Learning itself represents one of the earliest and most extensively understood milestones in the evolution of intelligence.

Aims: Applied

Many software developers worry that large language models will make human coders obsolete. We doubt that AI will replace coders, but we believe that coders who use AI will replace those who don’t.

  • Whenever possible, concepts will be introduced with code.

Aims: Applied

Richard Feynman

What I cannot build. I do not understand.

Course Philosophy and Expectations

  • Theory to Practice
  • The Necessity of Code and Mathematics
    • Note: data visualization code is exempt from examinations.
  • Active Engagement
  • The Value of Inquiry

Web sites

Beta testers

This will be my third iteration of this content. Your help identifying what works and what doesn’t will be most appreciated.

Warnings

CSI 4106 is an introductory course on artificial intelligence, offering a brief overview of various topics within this broad field. Each topic covered could be explored in much greater depth through one or more graduate-level courses. The primary objective of CSI 4106 is to provide students with a foundational understanding of the core areas that constitute artificial intelligence.

Overlaps with other courses are inevitable, but I will do my best to keep it at a minimum.

This is not a course on the impact of AI on society, including ethics, fairness, trust and safety.

Setting the Stage: AI, Deep Learning, and Diverging Views on Intelligence.

AI, ML, DL

Influential Approaches

  • Symbolic AI: represents knowledge using explicit symbols and structures, manipulated through rules, inference, or search.
  • Connectionist AI: represents knowledge through patterns of activity and connection weights in networks of computational units.

Symbolic systems in mathematics

  • Algebra
    • \(x + 3 = 7\), here \(x\) represents a quantity, \(x\) is a symbol.
  • Calculus
    • Symbolic differentiation of \(x^2\) into \(2x\), \(x\) is a symbol.
  • Logic
    • We might use \(P\) to mean “It is raining” and \(Q\) mean “The ground is wet.” \(P\) and \(Q\) are symbols.

Towers of Hanoi

(for your information only)

Symbolic AI (Planning)

The Towers of Hanoi is a puzzle that consists of three pegs and a number of disks of different sizes. The puzzle starts with all the disks stacked in decreasing size on one peg, and the goal is to move the entire stack to another peg, following these rules:

  1. Only one disk can be moved at a time.
  2. A disk can only be placed on top of a larger disk or on an empty peg.
Action Move(X,Y,Z):
    Preconditions = {Clear(X), On(X,Y), Clear(Z), Smaller(X,Z)};
    Effects = {-On(X,Y), Clear(Y), On(X,Z), -Clear(Z)};

D1, D2, D3, P1, P2, P3 are symbols, where D1, D2, and D3 are disks, and P1, P2, and P3 are pegs.

On(D1, D2), On(D2, D3), On(D3, P1),
Clear(D1), Clear(P2), Clear(P3),
Smaller(D1, D2), Smaller(D1, D3), Smaller(D2, D3),
Smaller(D1, P1), Smaller(D1, P2), Smaller(D1, P3),
Smaller(D2, P1), Smaller(D2, P2), Smaller(D2, P3),
Smaller(D3, P1), Smaller(D3, P2), Smaller(D3, P3).
On(D1, D2), On(D2, D3), On(D3, P3).
Move(D1, D2, P3)
Move(D2, D3, P2)
Move(D1, P3, D2)
Move(D3, P1, P3)
Move(D1, D2, P1)
Move(D2, P2, D3)
Move(D1, P1, D2)

Symbolic AI (Kinship)

Given a few facts about who is parent of whom (symbols) and a handful of Horn-clause rules, infer new relations (e.g., ancestor, siblings, grandparent) by logical deduction.

father(F,C) :- male(F), parent(F,C).
mother(M,C) :- female(M), parent(M,C).

sibling(X,Y) :- parent(P,X), parent(P,Y), X \= Y.

grandparent(G,C) :- parent(G,P), parent(P,C).

ancestor(A,D) :- parent(A,D).
ancestor(A,D) :- parent(A,X), ancestor(X,D).
% facts/symbols

male(alan).  female(brenda).
male(chris). female(dina).
male(eli).   female(fiona).

parent(alan, chris).
parent(brenda, chris).
parent(chris, dina).
parent(dina, eli).
parent(dina, fiona).
?- grandparent(G, dina).
% Expected: G = alan ; G = brenda.

?- ancestor(A, fiona).
% Expected: A = dina ; A = alan ; A = brenda ; A = chris ;

?- sibling(eli, fiona).
% Expected: true.

Symbolic AI (Prerequisites)

Given course prerequisites and a student’s completed set, infer which courses they can take next. This shows symbolic constraint reasoning.

all_prereqs_met(Student, Course) :-
    \+ (prereq(Course, P), \+ completed(Student, P)).

can_take(Student, Course) :-
    all_prereqs_met(Student, Course),
    \+ completed(Student, Course).
% --- Course graph (facts, symbols) ---

prereq(csi2120, csi2110).
prereq(csi2110, iti1121).
prereq(csi2110, mat1338).
prereq(iti1121, iti1120).
% --- Student record (facts, symbols) ---

completed(alex, iti1121).
completed(alex, iti1120).
completed(alex, mat1338).
?- can_take(alex, csi2110).
% true

?- can_take(alex, csi2120).
% false

?- can_take(alex, iti1121).
% false

?- all_prereqs_met(alex, csi2110).
% true

Symbolic AI: historical perspective

  • “Their founding tenet held that knowledge can be represented by a set of rules, and computer programs can use logic to manipulate that knowledge.” (Strickland 2021)
  • “Researchers developing symbolic AI set out to explicitly teach computers about the world.” (Strickland 2021)
  • “(\(\ldots\)) a physical symbol system has the necessary and sufficient means for general intelligent action.”
    (Newell and Herbert A. Simon 1976b)

Symbolic AI

  • What do you think made symbolic AI difficult in practice?

Connectionist

Artificial neural networks (ANNs) are computational models loosely inspired by biological neural systems. They consist of interconnected computational units with weighted connections.

During training, their parameters, including connection weights, are adjusted to improve performance on a specified objective.

Knowledge is encoded in the network’s parameters and patterns of activity, rather than primarily as explicit facts and rules.

Connectionist

Definig AI

Survey

Perceptions and Attitudes Toward Artificial Intelligence.

Why defining AI?

  • Enhancing Clarity and Communication: Establishing a mutual understanding of evaluation criteria, benchmarking tests, and milestones.

  • Addressing Ethical, Social, and Legal Implications: Enabling policymakers to develop regulations that minimize AI-related risks.

An operational definition

To the larger community of computer science and information technology, AI is usually identified by the techniques grown from it, which at different periods may include theorem proving, heuristic search, game playing, expert systems, neural networks, Bayesian networks, data mining, agents, and recently, deep learning.

Context

  • Significant hype.
  • Several leading companies, including DeepMind and OpenAI, are primarily focused on the development of artificial general intelligence (AGI).
  • Should AGI become a reality, its implications could profoundly impact various aspects of our lives, including education, employment, economic structures, and scientific advancements.

4 days ago

Question

User: The man and the goat want to enjoy a picnic near a river, but there’s a wolf. What to do with the zucchini?

ChatGPT 5: You’ve got the classic river‐crossing (wolf–goat–cabbage ⇒ here, zucchini).

Boat carries you + one item. Unsafe pairings: wolf with goat; goat with zucchini.

Minimal plan:

  1. Take goat over.
  2. Return alone.
  3. Take wolf over.
  4. Bring goat back.
  5. Take zucchini over.
  6. Return alone.
  7. Take goat over.

Conclusion: keep the zucchini never alone with the goat; ferry it on step 5.

Attribution: Andriy Burkov, published on LinkedIn August 2025.

Question

User: Surgeon but child, hopsital, it have a no, why it so?

ChatGPT 5: You’re pointing to the classic riddle:

Car crash → injured child → surgeon says “I can’t operate—this is my child.”

Resolution: the surgeon is the child’s mother (or another parent in a non-heteronormative family).

The “paradox” arises from implicit gender assumptions about surgeons.

Attribution: Andriy Burkov, published on LinkedIn 3 weeks ago.

The complex nature of intelligence

  • “Artificial” pertains to the creation of entities or phenomena that mimic natural processes using technology or synthetic materials, a definition broadly recognized and accepted.

  • Therefore, defining “artificial intelligence” fundamentally requires us to first clarify what we mean by “intelligence.” Surprisingly, “[d]espite a long history of research and debate, there is still no standard definition of intelligence.” (Legg and Hutter 2007)

How do you define intelligence?

  • What are the characteristics you associate with intelligence?

  • Intelligence is a very general mental capability that, among other things, involves the ability to reason, plan, solve problems, think abstractly, comprehend complex ideas, learn quickly and learn from experience.”

    • Originally published in the Wall Street Journal in 1994, the content was reprinted in 1997: (Gottfredson 1997)

Thinking, acting, humanly, rationally

Russell and Norvig considers two axes: thinking vs behaviour, human vs rationality.

Thinking Acting
Human-like thinking humanly (simulation) acting humanly (Turing test)
Rationality thinking rationally (logic) acting rationally (agent)

Rationality

Rationality involves the evaluation of choices to achieve a goal or to find the optimal solution to a problem. Simon (1972, p. 161) defined rationality as “a style of behavior that is appropriate to the achievement of given goals, within the limits imposed by given conditions and constraints.”

Cognitive Taxonomy

Cognitive Taxonomy (continued)

  • Perception:
    • The ability to extract and process sensory information from the environment.
  • Generation:
    • The ability to produce outputs such as speech, text, motor movements, and computer control actions.
  • Attention:
    • The ability to focus cognitive resources on specific aspects of perceptual stimuli, thoughts, or task demands.

Cognitive Taxonomy (continued)

  • Learning:
    • The ability to acquire new knowledge, skills, or understanding through experience, study, or instruction.
  • Memory:
    • The ability to store and retrieve information over time.
  • Reasoning:
    • The ability to draw valid conclusions and make inferences by applying logical principles.

Cognitive Taxonomy (continued)

  • Metacognition:
    • The knowledge a system has about its own cognitive processes and its ability to monitor and control those processes.
  • Executive functions:
    • Abilities that facilitate goal-directed behavior. Includes planning, inhibition, and cognitive flexibility.

Cognitive Taxonomy (continued)

  • Problem solving:
    • The ability to find effective solutions to domain-specific problems.
  • Social cognition:
    • The ability to process and interpret social information and to respond appropriately in social situations.

Narrow vs General AI

OpenAI GPT-6 Astra

Artificial General Intelligence (AGI)

Artificial general intelligence (AGI) refers to a form of artificial intelligence (AI) that either equals or exceeds human proficiency across a diverse array of cognitive functions.

AlphaFold (1, 2, & 3)

I repeat, there is nothing wrong with narrow AI.

  • «Two papers in this week’s issue dramatically expand our structural understanding of proteins. Researchers at DeepMind, Google’s London-based sister company, present the latest version of their AlphaFold neural network.»

    • Jumper et al. (2021)

AI effect/paradox

(\(\ldots\)) as soon as a computer system is built to solve a problem successfully, the problem is no longer “only solvable by the human mind,” so does not need intelligence anymore. Consequently, “AI is whatever hasn’t been done yet” (Hofstadter, 1979; Schank, 1991), which is known as “the AI Effect(McCorduck 2004).

Impact

Economy

McKinsey research estimates that gen AI could add to the economy between $2.6 trillion and $4.4 trillion annually while increasing the impact of all artificial intelligence by 15 to 40 percent.

In fact, it seems possible that within the next three years, anything not connected to AI will be considered obsolete or ineffective.

Subfields of AI

  1. Machine Learning: Credit card fraud detection
  2. Deep Learning: Image and facial recognition
  3. Natural Language Processing: Virtual assistants like Siri or Alexa
  4. Computer Vision: Autonomous vehicles
  5. Robotics: Industrial automation in manufacturing
  6. Expert Systems: Medical diagnosis support
  7. Speech Recognition: Voice-to-text transcription services
  8. Planning and Decision Making: Supply chain optimization
  9. Reinforcement Learning: Game AI in complex strategy games
  10. Knowledge Representation: Semantic web technologies for information retrieval

Our Final Invention

AI expert Kai-Fu Lee predicts that its impact will be “more than anything in the history of mankind.”

Questions

  • Can the concept of intelligence be considered independently of the entities that express it? This is the problem of embodiment.

  • Can a machine exhibit human-level intelligence?

  • Is it possible to dissociate the following concepts from that of intelligence?

    • Agency.
    • Sentience.
    • Consciousness.
    • Emotions.
    • Language.
    • Mind.
  • Can an AI suffer?

Deepen the Reflection

Rouleau, N. & Levin, M. (2024). Discussions of machine versus living intelligence need more clarity. Nature Machine Intelligence, 6(12), 1424–1426.

Prologue

Summary

  • Discussed the syllabus
  • Distinguish the concept of artificial intelligence from the concept of machine learning
  • Distinguish symbolic AI from connectionist AI
  • Explored the various definitions of “artificial intelligence”

Next lecture

  • Introduction to machine learning

References

Bennett, Max S. 2023. A Brief History of Intelligence: Evolution, AI, and the Five Breakthroughs That Made Our Brains. First edition. Mariner Books.
Burnell, Ryan, Yumeya Yamamori, Orhan Firat, et al. 2026. “Measuring Progress Toward AGI: A Cognitive Framework.” arXiv, ahead of print. https://doi.org/10.48550/arxiv.2605.28405.
Domingos, Pedro. 2018. The Master Algorithm: How the Quest for the Ultimate Learning Machine Will Remake Our World. Basic Books, Inc.
Dreyfus, Hubert L. 1972. What Computers Can’t Do: The Limits of Artificial Intelligence. Harper & Row.
Feigenbaum, Edward A. 1977. “The Art of Artificial Intelligence: Themes and Case Studies of Knowledge Engineering.” Proceedings of the 5th International Joint Conference on Artificial Intelligence 2: 1014–29.
Gottfredson, Linda S. 1997. “Mainstream Science on Intelligence: An Editorial with 52 Signatories, History, and Bibliography.” Intelligence 24 (1): 13–23. https://doi.org/10.1016/s0160-2896(97)90011-8.
Harnad, Stevan. 1990. “The Symbol Grounding Problem.” Physica D: Nonlinear Phenomena 42 (1-3): 335–46.
Jumper, John, Richard Evans, Alexander Pritzel, et al. 2021. Highly accurate protein structure prediction with AlphaFold.” Nature, 1–11. https://doi.org/10.1038/s41586-021-03819-2.
Legg, Shane, and Marcus Hutter. 2007. A Collection of Definitions of Intelligence.” Advances in Artificial General Intelligence: Concepts, Architectures and Algorithms: (NLD), 17–24. https://doi.org/10.5555/1565455.1565458.
Lenat, Douglas B, and Ramanathan V Guha. 1989. Building Large Knowledge-Based Systems: Representation and Inference in the Cyc Project. Addison-Wesley.
Lighthill, James. 1973. Artificial Intelligence: A General Survey. Science Research Council.
McCarthy, John, and Patrick J Hayes. 1969. “Some Philosophical Problems from the Standpoint of Artificial Intelligence.” In Machine Intelligence 4, edited by Bernard Meltzer and Donald Michie. Edinburgh University Press.
McCorduck, Pamela. 2004. Machines Who Think, A Personal Inquiry into the History and Prospects of Artificial Intelligence. Taylor & Francis Group, LLC. https://doi.org/10.1201/9780429258985.
Mohammed, Anne-Marie, Sandra Sookram, and George Saridakis. 2019. “Rationality.” In Encyclopedia of Law and Economics, edited by Alain Marciano and Giovanni Battista Ramello. Springer New York. https://doi.org/10.1007/978-1-4614-7753-2_404.
Newell, Allen, and Herbert A Simon. 1976a. “Computer Science as Empirical Inquiry: Symbols and Search.” Communications of the ACM 19 (3): 113–26.
Newell, Allen, and Herbert A. Simon. 1976b. “Computer Science as Empirical Inquiry: Symbols and Search.” Commun. ACM (New York, NY, USA) 19 (3): 113–26. https://doi.org/10.1145/360018.360022.
Nilsson, Nils J. 2005. “Human-Level Artificial Intelligence? Be Serious!” AI Mag. 26 (4): 68–75. https://doi.org/10.1609/AIMAG.V26I4.1850.
Pearl, Judea. 1988. Probabilistic Reasoning in Intelligent Systems: Networks of Plausible Inference. Morgan Kaufmann.
Russell, Stuart, and Peter Norvig. 2020. Artificial Intelligence: A Modern Approach. 4th ed. Pearson. http://aima.cs.berkeley.edu/.
Savage, Neil. 2024. “Beyond Turing: Testing LLMs for Intelligence.” Commun. ACM (New York, NY, USA), ahead of print, June. https://doi.org/10.1145/3673427.
Strickland, Eliza. 2021. “The Turbulent Past and Uncertain Future of AI: Is There a Way Out of AI’s Boom-and-Bust Cycle?” IEEE Spectrum 58 (10): 26–31. https://doi.org/10.1109/MSPEC.2021.9563956.
Wang, Pei. 2019. On Defining Artificial Intelligence.” Journal of Artificial General Intelligence 10 (2): 1–37. https://doi.org/10.2478/jagi-2019-0002.

Appendix: On Defining Artificial Intelligence

Wang (2019)

An agent and its interaction with the environment are specified as a tuple: \[ \langle P,S,A \rangle \] where

  • \(P\) represents a sequence of input signals, \(P = \langle p_0,\ldots,p_t \rangle\)
  • \(S\) represents a sequence of internal states, \(S = \langle s_0,\ldots,s_t \rangle\)
  • \(A\) represents a sequence of actions, \(A = \langle a_0,\ldots,a_t \rangle\)

For a sequence of moments, \(0,\ldots,t\).

Human (H) vs Computer (C)

AI is conceived as computer systems that are similar to the human mind in a certain sense, though a computer and a human mind cannot be identical in all aspects.

\[ \langle P^H,S^H,A^H \rangle \approx \langle P^C,S^C,A^C \rangle \]

Wang (2019) proposes 5 perspectives: Structure-AI, Behavior-AI, Capability-AI, Function-AI, and Principle-AI.

1. Structure-AI

(brain modelling, cognitive science)

I call this type of definition “Structure-AI,” since it requires an AI system to go through isomorphic states or structure changes as the brain does when they are given similar input, which will produce similar output, so the three components of the two are pairwise similar to each other:

\[ P^H \approx P^C, S^H \approx S^C, A^H \approx A^C \]

2. Behaviour-AI

(Turing Test)

One way to acknowledge a human-like mind without demanding a human-like brain is to associate intelligence to the external behaviors of the agent. After all, if an agent behaves like a human, it should be considered as intelligent, no matter whether it looks like a human, either inside or outside.

\[ P^H \approx P^C, A^H \approx A^C \]

3. Capability-AI (Employment Test)

In the agent framework, it means that \(C\) is similar to \(H\) in the sense that there are moments \(i\) and \(j\) that:

\[ p_i^C \approx p_j^H, a_i^C \approx a_j^H \]

the action (solution) the computer produces for a percept (problem) is similar to the action produced by a human to a similar percept (\(\ldots\)) In this way, the intelligence of a system is identified by a set of problems it can solve, while whether they are solved in the “human way” does not matter.

Capability-AI (contd)

“I suggest we replace the Turing test by something I will call the ‘employment test.’ To pass the employment test, AI programs must be able to perform the jobs ordinarily performed by humans. Progress toward human-level AI could then be measured by the fraction of these jobs that can be acceptably performed by machines”

4. Function-AI

In the agent framework, this “Function-AI” perspective takes \(C\) to be similar to \(H\) in the sense that there are moments \(i\) and \(j\) that:

\[ a_i^C \approx f^C(p_i^C), a_j^H \approx f^H(p_j^H), f^C \approx f^H \]

Here the function can correspond to searching, reasoning, learning, etc., and since the focus is on the functions (i.e., input-output mappings), the concrete input and output values of the two agents do not have to be similar to each other.

5. Principle-AI (rationality, logicist)

As in any field, there are researchers in AI trying to find fundamental principles that can uniformly explain the relevant phenomena. Here the idea comes from the usage of intelligence as a form of rationality (\(\ldots\)) that can make the best-possible decision in various situations, according to the experience or history of the system.

\[ A^C = F^C(P^C), A^H = F^H(P^H), F^C \approx F^H \]

The above \(F\) is often not formally specified, but described informally as a certain “principle,” which is not merely about a single type of problem and its solution, but about the agent’s life-long history in various situations, when dealing with various types of problems.

Code of the day

#!/usr/bin/env python3
# -*- Mode: Python -*-
# ai_lecture-01.py
# Author          : Marcel Turcotte & ChatGPT 5
# Created On      : Tue Feb 13 16:29:41 2024
# Last Modified By: Marcel Turcotte
# Last Modified On: Sun Sep  6 09:58:08 EDT 2026

# The initial version of this script was developed in 2024. 
# In 2025, ChatGPT was used to revise the code to align with the 
# latest API version, expand the comments to improve its instructional value, 
# and enhance its suitability as a teaching example. In 2026, the script was 
# further updated using Codex ChatGPT 5.6 Sol. 
# Attempts to use Codex ChatGPT 6 Astra Light were disappointing.

"""Generate bilingual narration and speech for the first lecture.

The script uses the OpenAI API to write an English narration, translate it
into Canadian French, and synthesize both versions as audio files.

Required:
    python -m pip install openai

OPENAI_API_KEY can be exported by the shell or injected by a secret manager:
    export OPENAI_API_KEY="your_api_key_here"
    python ai_lecture-01-v04.py --voice marin

With a 1Password environment file containing a secret reference:
    op run --env-file="$HOME/.env" -- python ai_lecture-01-v04.py --voice marin

Optional .env support:
    python -m pip install python-dotenv

Keep API keys private and exclude .env files from version control.
When presenting the recordings, disclose that the voices are AI-generated.
"""

from __future__ import annotations

import argparse
import os
import sys
from pathlib import Path
from typing import Optional

from openai import (
    APIConnectionError,
    APITimeoutError,
    AuthenticationError,
    OpenAI,
    OpenAIError,
    RateLimitError,
)

try:
    from dotenv import load_dotenv
except ImportError:
    load_dotenv = None


TEXT_MODEL = "gpt-4o"
SPEECH_MODEL = "gpt-4o-mini-tts"

WELCOME_SENTENCE = 'Welcome to CSI 4106, "Introduction to Artificial Intelligence"!'

# Quoted verbatim from the official uOttawa calendar.
OFFICIAL_CALENDAR_DESCRIPTION = (
    "The roots and scope of Artificial Intelligence. Knowledge and knowledge "
    "representation. Search, informed search, adversarial search. Deduction and "
    "reasoning. Uncertainty in Artificial Intelligence. Introduction to Natural "
    "Language Processing. Elements of planning. Basics of Machine Learning."
)

TEACHING_APPROACH = (
    "The calendar description establishes the broad scope of the course rather than its "
    "teaching order. This offering uses a modernized, machine-learning-first structure and "
    "introduces deep learning as early as the necessary foundations allow. Deep learning "
    "is central to contemporary AI, so studying it early connects the course with "
    "technologies that attract students' attention. It also provides a framework for "
    "introducing and defining central AI ideas. We will examine cases in which deep "
    "learning has displaced or changed the role of earlier approaches, as well as cases "
    "in which its limitations make earlier, purpose-built methods valuable. A further "
    "motivation is to treat learning as an early and extensively studied milestone in the "
    "development of intelligence. This foundation will later help us compare learning-based "
    "and search-based approaches when studying Monte Carlo Tree Search."
)

LEARNING_OUTCOMES = (
    "Explain the fundamental concepts of Artificial Intelligence (AI)",
    "Apply problem-solving strategies using AI techniques",
    "Critically analyze and compare different AI approaches",
    "Demonstrate independent learning and exploration",
)

PRELIMINARY_COURSE_OUTLINE = (
    "Defining AI",
    "Introduction to machine learning",
    "Linear regression",
    "Training",
    "Logistic regression",
    "Evaluation",
    "Hyperparameter tuning",
    "Machine learning engineering",
    "Introduction to artificial neural networks",
    "Backpropagation",
    "Softmax, cross-entropy, and regularization",
    "Convolutional neural networks",
    "Introduction to search",
    "Informed search",
    "Local search",
    "Population-based metaheuristics",
    "Adversarial search",
    "Monte Carlo Tree Search",
)


# -------------------------------------------------------
# Setup
# -------------------------------------------------------

def prepare_api_key() -> bool:
    """Load an optional .env file and check for an API key."""
    if not os.getenv("OPENAI_API_KEY") and load_dotenv is not None:
        load_dotenv(override=False)

    api_key = os.getenv("OPENAI_API_KEY", "")

    if api_key.startswith("op://"):
        print(
            "OPENAI_API_KEY is an unresolved 1Password reference. Run:\n"
            f'  op run --env-file="$HOME/.env" -- python {Path(__file__).name}',
            file=sys.stderr,
        )
        return False

    if not api_key:
        print(
            "No OpenAI API key was found. You can:\n"
            "  • export OPENAI_API_KEY=\"your_api_key_here\"\n"
            "  • use a secret manager to inject OPENAI_API_KEY\n"
            "  • install python-dotenv and store the key in a local .env file\n\n"
            "An exported key or a secret manager does not require python-dotenv.",
            file=sys.stderr,
        )
        return False

    return True


# -------------------------------------------------------
# Prompt builders
# -------------------------------------------------------

def build_course_context() -> str:
    """Organize the source material while keeping its roles unambiguous."""
    outcomes = "\n".join(f"- {outcome}" for outcome in LEARNING_OUTCOMES)
    outline = "\n".join(
        f"{number}. {topic}"
        for number, topic in enumerate(PRELIMINARY_COURSE_OUTLINE, start=1)
    )

    return f'''REQUIRED OPENING SENTENCE:
{WELCOME_SENTENCE}

OFFICIAL UOTTAWA CALENDAR DESCRIPTION:
{OFFICIAL_CALENDAR_DESCRIPTION}

INSTRUCTOR'S DESIGN FOR THIS OFFERING:
{TEACHING_APPROACH}

LEARNING OUTCOMES:
Upon completion of the course, students will be able to:
{outcomes}

PRELIMINARY AND AMBITIOUS COURSE OUTLINE:
{outline}'''


def build_instructions_en(tone: Optional[str]) -> str:
    """Build instructions for the English narration."""
    instructions = (
        "Write a natural spoken welcome of 180 to 240 words for the first lecture of an "
        "undergraduate AI course at the bilingual University of Ottawa. Begin with the "
        "required opening sentence exactly as supplied. Clearly identify the calendar "
        "paragraph as the official uOttawa course description, then explain that this "
        "offering uses a modernized, machine-learning-first structure and reaches deep "
        "learning as early as its foundations permit. Do not present the calendar "
        "description as the teaching sequence or the preliminary outline as official "
        "calendar text. Explain both reasons for teaching deep learning early: its "
        "importance to current AI and its use as a framework for discussing other AI "
        "ideas. Contrast cases where deep learning has changed earlier approaches with "
        "cases where its limitations make specialized methods valuable. State all four "
        "learning outcomes naturally, preserving their action verbs. Describe the "
        "preliminary and ambitious sequence as an arc from machine-learning foundations "
        "through neural networks and then search, ending with Monte Carlo Tree Search; do "
        "not recite all eighteen topics. Do not imply that deep learning is a prerequisite "
        "for Monte Carlo Tree Search. The students have varied backgrounds, languages, and "
        "prior exposure to AI. Be welcoming, inclusive, clear, and encouraging. Use plain "
        "language and short sentences. Return only the narration."
    )
    if tone:
        instructions += f" Writing style: {tone}"
    return instructions


def build_instructions_fr() -> str:
    """Build instructions for the Canadian French translation."""
    return (
        "Translate the supplied English narration into natural Canadian French. "
        "The University of Ottawa is bilingual, and CSI 4506 is the French-language "
        "course corresponding to CSI 4106. Replace 'CSI4106' or 'CSI 4106' with "
        "'CSI 4506'. Translate the course title as 'Introduction à l’intelligence "
        "artificielle'. Preserve the distinction between the official calendar description "
        "and the way this offering is organized, along with all other ideas and the "
        "welcoming tone. Return only the translation."
    )


def build_speech_instructions(language: str, tone: Optional[str]) -> str:
    """Build language-specific delivery instructions."""
    if language == "en":
        instructions = (
            "Speak as a welcoming university instructor. Use natural Canadian English, "
            "a conversational tone, and a measured pace. Pause briefly between the main "
            "ideas. Pronounce 'CSI 4106' as 'C S I four one zero six'."
        )
    else:
        instructions = (
            "Parlez comme une personne qui accueille sa classe à l’université. Utilisez "
            "un français canadien naturel, un ton chaleureux et un débit mesuré. Faites "
            "une courte pause entre les idées principales. Prononcez « CSI 4506 » comme "
            "« cé esse i, quatre cinq zéro six »."
        )

    if tone:
        instructions += f" Additional delivery instruction: {tone}"
    return instructions


# -------------------------------------------------------
# OpenAI utilities
# -------------------------------------------------------

def generate_text(client: OpenAI, source: str, instructions: str) -> str:
    """Generate text with the Responses API."""
    response = client.responses.create(
        model=TEXT_MODEL,
        instructions=instructions,
        input=source,
        temperature=0.2,
        max_output_tokens=800,
    )
    return (response.output_text or "").strip()


def synthesize_speech(
    client: OpenAI,
    text: str,
    output_path: Path,
    *,
    voice: str,
    instructions: str,
    response_format: str,
) -> None:
    """Stream synthesized speech to an audio file."""
    with client.audio.speech.with_streaming_response.create(
        model=SPEECH_MODEL,
        voice=voice,
        input=text,
        instructions=instructions,
        response_format=response_format,
    ) as response:
        response.stream_to_file(output_path)


# -------------------------------------------------------
# Script logic
# -------------------------------------------------------

def main(audio_format: str, voice: str, tone: Optional[str]) -> int:
    """Generate English and French narrations and audio files."""
    if not prepare_api_key():
        return 1

    course_context = build_course_context()

    try:
        client = OpenAI()

        narration_en = generate_text(
            client, course_context, build_instructions_en(tone)
        )
        if not narration_en:
            print("The text model returned an empty English narration.", file=sys.stderr)
            return 1

        narration_fr = generate_text(
            client, narration_en, build_instructions_fr()
        )
        if not narration_fr:
            print("The text model returned an empty French translation.", file=sys.stderr)
            return 1

        narrations = (
            ("en", narration_en),
            ("fr", narration_fr),
        )

        for language, narration in narrations:
            output_path = Path(
                f"01_tts_course_intro-{language}-{voice}.{audio_format}"
            )
            synthesize_speech(
                client,
                narration,
                output_path,
                voice=voice,
                instructions=build_speech_instructions(language, tone),
                response_format=audio_format,
            )
            print(f"[OK] {language.upper()} audio → {output_path}")

    except AuthenticationError:
        print(
            "OpenAI rejected the API key. Check OPENAI_API_KEY or the secret manager.",
            file=sys.stderr,
        )
        return 1
    except (APIConnectionError, APITimeoutError) as error:
        print(f"Could not reach the OpenAI API: {error}", file=sys.stderr)
        return 1
    except RateLimitError:
        print(
            "The request was rate-limited. Check the account's limits and API credit.",
            file=sys.stderr,
        )
        return 1
    except OpenAIError as error:
        print(f"OpenAI API error: {error}", file=sys.stderr)
        return 1
    except OSError as error:
        print(f"Could not write an audio file: {error}", file=sys.stderr)
        return 1

    print("Reminder: disclose that the narration uses AI-generated voices.")
    return 0


# -------------------------------------------------------
# Command-line interface
# -------------------------------------------------------

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Generate bilingual first-lecture narration and speech."
    )
    parser.add_argument(
        "--format",
        default="mp3",
        choices=("mp3", "wav", "aac", "flac", "opus", "pcm"),
        help="Audio output format (default: mp3).",
    )
    parser.add_argument(
        "--voice",
        default="marin",
        help="Speech voice (default: marin). Try cedar or nova.",
    )
    parser.add_argument(
        "--tone",
        default=None,
        help=(
            "Optional writing and delivery instruction, for example: "
            "'Sound warm, calm, and optimistic.'"
        ),
    )
    args = parser.parse_args()

    raise SystemExit(main(args.format, args.voice, args.tone))

Marcel Turcotte

[email protected]

School of Electrical Engineering and Computer Science (EECS)

University of Ottawa