Bringing Your Own LLM or VLM¶
Every built-in psychscanner run goes through a LangChain chat model and a
LangGraph agent under the hood. But sometimes you already have your own model
to test: a raw provider SDK call, a local HuggingFace pipeline, a vision API,
a rule-based baseline, or a research prototype that isn't a LangChain chat
model at all.
The psychscanner.agents subpackage lets you wrap any callable — as long
as it turns a trial's inputs into a response — and drop it straight into the
simulation loop, bypassing the built-in LangChain/LangGraph pipeline entirely.
This notebook covers:
- The minimal contract a custom agent must satisfy
- Running a custom agent directly through
TaskRunner(noExpCardneeded) - Plugging a custom agent into a full
ScannerModelrun - Wiring in a custom VLM that handles multimodal (image) stimuli
- Exporting results to CSV, same as any other run
from pathlib import Path
from langchain_core.messages import AIMessage, HumanMessage
import psychscanner as psy
from psychscanner import CustomAgent, ScanningAgent
from psychscanner.task_runner import TaskRunner
print("PsychScanner successfully imported!")
PsychScanner successfully imported!
1. The contract¶
TaskRunner never imports LangGraph — it only ever calls:
test_agent.ai_app.invoke(input_dict, config=...) # -> dict with "inputs": [..., response]
test_agent.parser # fallback parser for trials that don't set one
ScanningAgent is a Protocol documenting exactly that. input_dict (the
per-trial state) has these keys:
| key | meaning |
|---|---|
inputs |
list of messages so far; the last one is this trial's stimulus |
system_message |
the task's system prompt |
trcode |
the trial code, e.g. "O_1" |
parser |
per-trial parser name from the task JSON, or None |
tools |
per-trial tool-name subset, or None |
CustomAgent adapts a plain Python function to this contract — no LangGraph
graph to build.
def my_llm(input_dict: dict) -> AIMessage:
"""Stand-in for any LLM call: a provider SDK, a local model, whatever."""
stim = input_dict["inputs"][-1]
text = stim.content if hasattr(stim, "content") else str(stim)
return AIMessage(content=f"[mock reply to: {text}]")
agent = CustomAgent(my_llm)
print(isinstance(agent, ScanningAgent)) # Protocol -> structural check
print(agent.ai_app is agent) # CustomAgent wraps itself as its own ai_app
True True
Try it directly through TaskRunner¶
No ExpCard or ScannerModel needed to sanity-check a custom agent — just
hand it to TaskRunner with a couple of trials.
tasktrials = {
"trials": [
{"trcode": "t1", "stimulus": HumanMessage(content="Rate your mood 1-5."),
"tasktype": "x", "parser": None, "fb": False},
{"trcode": "t2", "stimulus": HumanMessage(content="Rate your energy 1-5."),
"tasktype": "x", "parser": None, "fb": False},
]
}
runner = TaskRunner(
scanning_agent=agent,
trace_cfg={"trial": "tut-", "task": "tut-task"},
system_message="You are a participant in a psychology study.",
tasktrials=tasktrials,
chain_type="item",
hmsg="stimulus",
)
results = runner.execute()
for r in results:
print(r["trcode"], "->", r["pred_resp"].content)
----<>---- task running
t1 -> [mock reply to: Rate your mood 1-5.] t2 -> [mock reply to: Rate your energy 1-5.]
2. Plugging a custom agent into ScannerModel¶
For a full simulation run — task JSON, session tunnel, .psyscan output —
build an ExpCard as usual, then pass the custom agent to
scanner.run(custom_agent=...). It bypasses AgentConfig's LangChain model
entirely, so the card's model/family fields don't matter here (the
default mock-llm is fine — no API key required for this notebook).
RUN_DIR = Path.cwd() / "_custom_agent_tutorial_run"
card_in = psy.ExpCardInit()
card_in.proj_dir = RUN_DIR
card_in.projectname = "custom_agent_demo"
card_in.tunnel_status = "0"
card_in.task_file = Path.cwd() / "tasks" / "example_survey.json"
card_in.cogtype = "no"
card_in.parser = "0"
card_in.chain_type = "task"
card_in.memory = "SingleTurn"
expcard = psy.ExpCard(card_in)
----<PROJECT AND DATA ROOT DIRECTORY>----
Project root dir: /Users/saurabhext/Documents/PSYCHSCANNER/psychscanner/examples/_custom_agent_tutorial_run
Simulation data root dir: /Users/saurabhext/Documents/PSYCHSCANNER/psychscanner/examples/_custom_agent_tutorial_run/custom_agent_demo/example_survey/mock-llm_mock-chat-model_SingleTurn
----<>----
def rule_based_rater(input_dict: dict) -> AIMessage:
"""A simple non-LLM baseline: rate Openness items high, Conscientiousness low."""
rating = 5 if input_dict["trcode"].startswith("O") else 2
return AIMessage(content=str(rating))
rater_agent = CustomAgent(rule_based_rater)
scanner = psy.ScannerModel(expcard=expcard)
scan_results = scanner.run(custom_agent=rater_agent)
for trial in scan_results[0]:
print(trial["trcode"], "->", trial["pred_resp"].content)
--<chat model>-- metadata={'lc_versions': {'langchain-core': '1.4.8', 'langchain': '1.3.11'}} output_version=None model_name='mock-chat-model' repeat_buffer_length=10
2026-07-05 23:58:49.964 | CRITICAL | psychscanner.session_tunnel.session_tunnel:create_tunnel:152 - BEGIN
TOTAL RUNS: 1 RESUME IDX: None
----<>---- task running
0it [00:00, ?it/s]
6it [00:00, 33916.20it/s]
2026-07-05 23:58:49.973 | INFO | psychscanner.session_tunnel.session_tunnel:scan_checkpoint:184 - scan-checkpoint
----<scanned runs>---- i = 0
2026-07-05 23:58:49.975 | CRITICAL | psychscanner.session_tunnel.session_tunnel:end_checkpoint:163 - END
O_1 -> 5 O_2 -> 5 O_3 -> 5 C_1 -> 2 C_2 -> 2 C_3 -> 2
3. Wiring in a custom VLM¶
Multimodal stimuli (see the psychscanner.datasets.prompts.multimodal
helpers — image_block, audio_block, file_block) arrive in inputs as a
HumanMessage whose .content is a list of content blocks. A custom VLM
function just inspects those blocks and calls whatever vision model it
wants — a hosted API, a local model, anything.
import base64
from psychscanner.datasets.prompts.multimodal import image_block
# A tiny 1x1 PNG, just to exercise a real image_block() call end to end.
png_bytes = base64.b16decode(
"89504E470D0A1A0A0000000D49484452000000010000000108020000009077"
"53DE0000000C4944415478DA6360000002000155A1F6B50000000049454E44AE426082"
)
pixel_path = RUN_DIR / "pixel.png"
pixel_path.parent.mkdir(parents=True, exist_ok=True)
pixel_path.write_bytes(png_bytes)
def my_vlm(input_dict: dict) -> AIMessage:
stim = input_dict["inputs"][-1]
blocks = stim.content if isinstance(stim.content, list) else [stim.content]
n_images = sum(1 for b in blocks if isinstance(b, dict) and b.get("type") == "image")
return AIMessage(content=f"[VLM] saw {n_images} image block(s), trial={input_dict['trcode']}")
vlm_agent = CustomAgent(my_vlm)
vlm_tasktrials = {
"trials": [
{
"trcode": "img_1",
"stimulus": HumanMessage(content=[
image_block(pixel_path),
{"type": "text", "text": "Describe this image."},
]),
"tasktype": "x", "parser": None, "fb": False,
},
]
}
vlm_runner = TaskRunner(
scanning_agent=vlm_agent,
trace_cfg={"trial": "tut-vlm-", "task": "tut-vlm-task"},
system_message="You are a vision model rating psychological stimuli.",
tasktrials=vlm_tasktrials,
chain_type="item",
hmsg="stimulus",
)
vlm_results = vlm_runner.execute()
for r in vlm_results:
print(r["trcode"], "->", r["pred_resp"].content)
----<>---- task running
img_1 -> [VLM] saw 1 image block(s), trial=img_1
4. Exporting results¶
A ScannerModel run driven by a custom agent exports to CSV exactly like any
other run.
from psychscanner import to_csv
df = to_csv(scanner, path=RUN_DIR / "custom_agent_demo.csv")
df.select(["trcode", "pred_resp_raw"])
Saved 6 rows → /Users/saurabhext/Documents/PSYCHSCANNER/psychscanner/examples/_custom_agent_tutorial_run/custom_agent_demo.csv
| trcode | pred_resp_raw |
|---|---|
| str | str |
| "O_1" | "5" |
| "O_2" | "5" |
| "O_3" | "5" |
| "C_1" | "2" |
| "C_2" | "2" |
| "C_3" | "2" |
Recap¶
- A scanning agent only needs
.ai_app.invoke(input_dict, config=None) -> dictand a.parserattribute — seepsychscanner.agents.ScanningAgent. CustomAgent(call_fn, parser=...)adapts any plain function to that contract, so no LangGraph knowledge is required to bring your own model.- Pass it to
TaskRunner(scanning_agent=...)directly, or toScannerModel.run(custom_agent=...)for a full simulation (task JSON, session tunnel, CSV export — everything else stays the same). - The
parserattribute is only used as a fallback for trials that don't set their own parser in the task JSON — a custom agent is free to return whateverAIMessagecontent it wants; it owns its own parsing/tool logic.
Further reading¶
Advanced applications of wrapping arbitrary models/agents behind a common contract:
- "AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation Framework" (Wu et al., 2023) — a broader framework for the same idea shown here: any callable (LLM, VLM, rule-based function) can be wrapped behind one uniform agent interface.
- "Toolformer: Language Models Can Teach Themselves to Use Tools" (Schick et al., 2023) — a custom-agent contract taken further, where the wrapped model decides for itself which underlying tool/API to call.