AI for Social Science Research · Fall 2026
2026-09-16
Fill out this survey for the Sociology of AI minicourse (see also the course canvas page).
Next week’s presentation (9/23): Simulating Subjects & Interactions, Survey Experiments, by Woojung & YJ
Chat Interface: A conversational web/app interface. Easy to use (no coding). Handles multimodal input easily. Less flexible & difficult to scale for some research purposes.

API: A programming interface to send requests and receive responses. More control over model parameters and easier to integrate into research pipeline. Requires writing, running, and maintaining code.

CLI (Command Line Interface): A terminal-based interface. Uses command-line commands. Used to be better than chat interface for agentic workflow, but chat interfaces have caught up.


In the TextEdit file, put your API key:
Save, close, and verify the filename from your CLI:
Then confirm .env is ignored by git — the course repo’s .gitignore already lists it:
import os
from dotenv import load_dotenv, find_dotenv
# Load your API key to the programming enviornment
env_path = find_dotenv(usecwd=True)
loaded = load_dotenv(env_path) if env_path else False
# Import API packaeg
from openai import OpenAI
client = OpenAI()
# Define the model you use
MODEL = "gpt-5.4-mini-2026-03-17"
# Try the model: you can change the model parameters such as max token returned, temperature, etc.
r = client.chat.completions.create(
model=MODEL,
# You can set system & user prompts, you can also sent chat record as messages
messages=[{"role": "user", "content": "Explain what is an API in one sentence: "}],
max_completion_tokens=30,
temperature=0,
)
# Print the text generated from the model
print(r.choices[0].message.content)def annotate_corpus(tweets, prompt=PROMPT, temperature=0):
"""
This function: (1) builds the prompt using the tweet, (2) sends every prompt to the model, one at a time,
(3) returns a list of raw replies.
"""
replies = []
for tw in tweets:
tweet = tw.replace("#SemST", "").strip()
r = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt + tweet}],
max_tokens=200,
temperature=temperature,
)
replies.append(r.choices[0].message.content)
if len(replies) % 25 == 0:
print(f" {len(replies)}/{len(tweets)} done")
return replies
# The tweets are saved in the dataframe `lab_df` in the variable `Tweet`.
# Apply above function on every tweet in `lab_df` and save all response in the list: raw_zs
raw_zs = annotate_corpus(lab_df["Tweet"].tolist())
print(f"\n{len(raw_zs)} replies received. First one:\n{raw_zs[0]}"){Trump, None} to a python tuple object with two elements: ('Donald Trump', 'NONE'). We later convert the tuple list to dataframe variables.TARG_MAP = {"trump": "Donald Trump", "clinton": "Hillary Clinton"}
STANCE_MAP = {"favor": "FAVOR", "against": "AGAINST", "none": "NONE"}
def parse(reply):
"""Extract (target, stance) from a model reply. Returns (None, None) on failure."""
m = re.search(r"\{\s*([A-Za-z']+)\s*,\s*([A-Za-z]+)\s*\}", reply)
if not m:
return None, None
target = TARG_MAP.get(m.group(1).lower().replace("'", ""))
stance = STANCE_MAP.get(m.group(2).lower())
return target, stance
parsed = [parse(r) for r in raw_zs]
n_bad = sum(1 for _, s in parsed if s is None)
print(f"unparseable / invalid replies: {n_bad} / {len(parsed)}")Same pipeline runs on images, audio, and video
Evaluation tells us how well the model performs the classification task compared to the “ground truth.” You should understand:

Source: Scikit-Learn
Two common workflows, both cheaper than the conventional pipeline:
Process 1 — no fine-tuning (today’s lab):
Process 2 — with fine-tuning:
Key differences from conventional ML
| pred = positive | pred = negative | |
|---|---|---|
| true positive | true positive (TP) | false negative (FN) |
| true negative | false positive (FP) | true negative (TN) |
Accuracy is misleading on imbalanced data
If only 15% of tweets are AGAINST-Trump, an annotator that flags nothing still gets 85% accuracy. It found zero real AGAINST tweets.
You need class-specific metrics to see this.
Recall matters more when a false negative is expensive, i.e. when missing the reality is dangerous or fatal: telling a patient that they don’t have aggresive cancer when they actually do, failing to detect weapon in baggage check, auto-drive car sensor fails to detect pedestrain, …
Precision matters more when a false positive is expensive, i.e. when acting on a false alarm causes severe damage: innocent person being wrongfully accused of a crime, spam filter that filter important emails, AI/plagiarism detection flags a student paper that didn’t use AI/plagiarize, …
F1 when you want a measure that considers both recall and precision
Traditional classifiers output a score (a probability), not a label. You choose a threshold to turn the score into a decision.


Source: Google ML Crash Course
An LLM by default outputs a label, not a score, but there are ways to reintroduce a score if you want ROC/AUC:
logprobs=True on the API call. Ask for the probability of each candidate label token. Most principled — this is the model’s probability distribution.{"stance": "AGAINST", "confidence": 85}. Easy to add to the prompt, but empirically poorly calibrated — unclear how well the scores are calibrated.temperature=1, take the fraction of the positive class (costs 10× more).Motivation:
Intuition: Borrow information in the comparison between expert labeling and LLM labeling.
What DSL does:
model = "felm").sample_prob = "...".Open the lab page: Lab 3: LLM Annotation via API
AI for Social Science Research · Week 3