How to experiment without draining your wallet?

#machine-learning#llm#experimentation

Run stateful and one-shot LLM experiments using Codex and Claude Code subscriptions.

How to experiment without draining your wallet?

Hey, how’s everything going? Today I decided to write about something different than what I usually do. I wanted to teach you something I just figured out. How to use your codex or claude subscription as your API endpoint so that you can skip the pay-per-token catch when you experiment.

As a researcher who’s running different experiments, LLM judges and benchmarks using LLM models, I find the cost of running frontier models as opus or astra is quite expensive and I usually retreat to using opensource models which are 马马虎虎(not so great).

Table comparing input and output token prices for OpenAI and Anthropic models

Illustration of a stressed researcher and a machine funneling money into a sack

So, I’ve been trying to see if there is a way which I can utilize my subscription for the job, in a way that doesn’t contaminate my experiments. This method not only saves you from the shower trap of Pay-per-api costs, but also gives you additional perks as Tibo’s blessing.

Illustration of a robed figure distributing glowing tokens to a crowd of developers

So lets get into it.

1. Install codex & claude code CLI

Terminal window
npm install -g @anthropic-ai/claude-code @openai/codex
# sign in to claude
claude
/login # type login and proceed with the auth
# now lets sign in to codex
codex login
codex -p "OK"
codex exec --skip-git-repo-check "OK"
# done

2. Running experiments using Claude

We utilize Claude cli print mode of “-p” tag to give it a prompt and returns us output. We can use –output-format JSON which also return us the session ID with the JSON and we utilize that to create persistence if we need to make the experiment stateful, or use –no-session-persistence to make it one shot call.

Let me summarize everything we’ll be using in single table.

Flag What it does
--system-prompt "..." Replaces Claude Code’s built-in coding instructions with yours
--tools "" No tools at all: the model cannot run commands or read files
--setting-sources "" Ignores your personal settings: no hooks, plugins, or CLAUDE.md files
--strict-mcp-config No MCP servers
--disable-slash-commands No skills or slash commands
--no-session-persistence Saves nothing (only for one-shot calls)
--model accepts short names such as haiku, sonnet, opus, or a full model id

Enough talking, here is a small example

"""Talk to Claude through your Claude Code login.
Chat() - a stateful conversation: each send() continues the same chat.
ask() - a stateless call: a new private chat that is not saved.
python claude_chat.py "What is the capital of France?"
"""
import json
import shutil
import subprocess
import sys
import tempfile
CLAUDE = shutil.which("claude") # on Windows `claude` is a wrapper script; this finds it
# No tools, no MCP servers, and none of your own settings, hooks, plugins or CLAUDE.md.
CLEAN = ["--tools", "", "--setting-sources", "", "--strict-mcp-config", "--disable-slash-commands"]
class Chat:
def __init__(self, system="You are a helpful assistant.", model="sonnet", save=True):
self.system, self.model, self.save = system, model, save
self.session = None # Claude's session id, set by the first reply
# Claude stores sessions per working directory, so a chat keeps one empty folder.
self.folder = tempfile.mkdtemp(prefix="claude-chat-")
def send(self, prompt):
args = [CLAUDE, "-p", "--model", self.model, "--output-format", "json",
"--system-prompt", self.system, *CLEAN]
if self.session:
args += ["--resume", self.session] # continue the same conversation
if not self.save:
args += ["--no-session-persistence"] # write nothing to disk
out = subprocess.run(args, input=prompt, capture_output=True, text=True,
encoding="utf-8", cwd=self.folder)
reply = json.loads(out.stdout)
if reply["is_error"]:
raise RuntimeError(reply.get("api_error_status") or reply["result"])
self.session = reply["session_id"]
return reply["result"]
def ask(prompt, system="You are a helpful assistant.", model="sonnet"):
"""One prompt, one answer, nothing remembered or saved."""
return Chat(system, model, save=False).send(prompt)
if __name__ == "__main__":
print(ask(" ".join(sys.argv[1:]) or "What is the capital of France?"))

Now lets try both

from claude_chat import Chat, ask
chat = Chat(model="haiku")
chat.send("My favourite colour is teal. Reply OK.")
print(chat.send("What is my favourite colour?")) # -> Teal
print(ask("What is my favourite colour? If you don't know, say UNKNOWN.")) # -> UNKNOWN

Running experiments using Codex

Here we utilize codex app-server mode which runs your call as background process accepting your JSON and replies you JSON back. Lets see some what psuedo code of this.

  1. initialize
  2. thread/start - If we want to do stateful conversation, and we send our prompts as baseInstructions replacing Codex coding instructions and models, we can use ephemeral: true if we don’t want to write the thread to our disk.
  3. turn/start - we use this to send a message starting codex stream event which’ll be stateless and gives us back agentMessage and return us turn/completed finishing the turn.
  4. close - since we’re managing our thread make sure to close the thread.

Lets see it with small example

"""Talk to Codex models through your Codex (ChatGPT) login.
Chat() - a stateful conversation: each send() continues the same thread.
ask() - a stateless call: a new thread that is not saved, closed after one answer.
python codex_chat.py "What is the capital of France?"
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
CODEX = shutil.which("codex")
# Turn off tools and extras so Codex acts as a plain assistant.
OFF = ["apps", "plugins", "hooks", "shell_tool", "unified_exec", "multi_agent", "image_generation",
"view_image", "browser_use", "computer_use", "memories", "skill_search", "goals"]
CONFIG = {"web_search": "disabled", "include_environment_context": False,
"project_doc_max_bytes": 0, "features": {name: False for name in OFF}}
class Chat:
def __init__(self, system="You are a helpful assistant.", model="gpt-6.1-sol", save=True):
# Keep CODEX_HOME (where the login lives); drop other inherited CODEX_* variables.
env = {k: v for k, v in os.environ.items()
if not k.upper().startswith("CODEX_") or k.upper() == "CODEX_HOME"}
folder = tempfile.mkdtemp(prefix="codex-chat-")
self.process = subprocess.Popen([CODEX, "app-server", "--listen", "stdio://"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, env=env, cwd=folder,
encoding="utf-8")
self.count = 0
self.request("initialize", {"clientInfo": {"name": "cli-llm", "version": "1"},
"capabilities": {"experimentalApi": True}})
self.notify("initialized")
started = self.request("thread/start", {
"model": model, "ephemeral": not save, "cwd": folder,
"baseInstructions": system, "developerInstructions": "",
"approvalPolicy": "never", "sandbox": "read-only", "config": CONFIG})
self.thread = started["thread"]["id"]
def notify(self, method, params=None):
message = {"method": method, **({"params": params} if params else {})}
self.process.stdin.write(json.dumps(message) + "\n")
self.process.stdin.flush()
def request(self, method, params):
self.count += 1
self.process.stdin.write(json.dumps({"id": self.count, "method": method, "params": params}) + "\n")
self.process.stdin.flush()
for line in self.process.stdout:
message = json.loads(line)
if message.get("id") == self.count and "method" not in message:
if "error" in message:
raise RuntimeError(message["error"])
return message["result"]
raise RuntimeError("Codex closed the connection")
def send(self, prompt):
self.request("turn/start", {"threadId": self.thread,
"input": [{"type": "text", "text": prompt, "text_elements": []}]})
answer = ""
for line in self.process.stdout:
message = json.loads(line)
method = message.get("method")
if method == "item/completed" and message["params"]["item"].get("type") == "agentMessage":
answer = message["params"]["item"]["text"]
elif method == "turn/completed":
turn = message["params"]["turn"]
if turn.get("status") != "completed":
raise RuntimeError(turn.get("error")) # for example a usage limit
return answer
elif "id" in message and method: # Codex asks for permission or input: refuse
self.process.stdin.write(json.dumps(
{"id": message["id"], "error": {"code": -32601, "message": "Unavailable"}}) + "\n")
self.process.stdin.flush()
raise RuntimeError("Codex closed the connection")
def close(self):
self.process.kill()
def ask(prompt, system="You are a helpful assistant.", model="gpt-6.1-sol"):
"""One prompt, one answer, nothing remembered or saved."""
chat = Chat(system, model, save=False)
try:
return chat.send(prompt)
finally:
chat.close()
if __name__ == "__main__":
print(ask(" ".join(sys.argv[1:]) or "What is the capital of France?"))

Lets try it

from codex_chat import Chat
chat = Chat()
chat.send("My favourite colour is teal. Reply OK.")
print(chat.send("What is my favourite colour?")) # -> Teal
chat.close() # always close: the conversation lives in a running process

If you enabled Chat(save=True) it will save the thread to ~/.codex/sessions/ which you later can use for analysis.

We’ll now we’re done, happy experiment 😂

© 2026 Yeabsira Tesfaye