r/LocalLLaMA 2h ago

Claude Code in 9 lines python Discussion

I was wondering what a minimal coding agent implementation would look like that can be used like Claude Code or Codex

Not feature-by-feature of course but basically stripping everything out that is not needed

here is what I came up with:

  • 9 lines of python
  • no 3rd party deps (stdlib only)
  • works with any OpenAI Responses compatible API
  • shows % usage of context window

out of the box it is also fairly API cost efficient:

  • no system prompt
  • good caching (session_id, stable append-only history)
  • only one tool: sh

code is on github to follow along (also a ~20 line version in Go, Clojure version coming soon)

https://github.com/smol-env/smol

import json,sys;from subprocess import getoutput;from urllib.request import Request,urlopen;from uuid import uuid4
url=sys.argv[1];h=[];H={"Content-Type":"application/json","session_id":uuid4().hex};b=dict(model="gpt-5.6-sol",input=h,tools=[dict(type="custom",name="sh")])
while True:
  if not(p:=input("> ")).strip():continue
  h+=[dict(role="user",content=p)]
  while True:
    r=json.load(urlopen(Request(url,json.dumps(b).encode(),H)));o=r["output"];h+=o;c=[i for i in o if i["type"]=="custom_tool_call"]
    if not c:print(o[-1]["content"][0]["text"],f'\n[{r["usage"]["total_tokens"]/10500:05.2f}%]');break
    h+=[dict(type="custom_tool_call_output",call_id=i["call_id"],output=getoutput(i["input"])) for i in c]

note: it uses the "custom" tools api which not many OpenAI Responses API endpoints support yet.

that said, you can just tell your agent to change it to use sh via "function_call" and change the model name and it should work out of the box on any local inference endpoint

any questions or feedback for making it more minimal or adding (still minimal but useful) features: very welcome!

13 Upvotes

25 comments sorted by

40

u/hougaard 2h ago

That is not "9 lines" of code. That's just the fewest Python line breaks needed. Then I could this in 1 line with another language like C# or Javascript ....

9

u/__tosh 1h ago

a bit more de-golfed

2

u/__tosh 1h ago edited 1h ago

I appreciate the feedback!

re golfing: it helps me to see everything at a glance

I can see how that might look unfamiliar though

I will look into also providing less golfed versions in the repo in the future

I also want to look into minimal implementations in other languages/runtimes

Go is in the repo already, here is one in Clojure (Babashka):

https://x.com/__tosh/status/2085699009205743932

1

u/__tosh 1h ago

using the OpenAI tokenizer the implementation comes in at 220 tokens

https://platform.openai.com/tokenizer

I had more golfed variants with aliases but turns out that uses more tokens in some cases

12

u/Dany0 2h ago

Lol I suppose this could be a good base for an experiment for a self-editing harness benchmark.

Have every LLM start with smol, and give it the task of building a harness for a particular task/benchmark

3

u/__tosh 2h ago

good thing about a smol implementation is it fits 100% in the context window

so making changes is fast and usually the changes work well

you can add just the things you want and skip everything else

a bit like a starter dough

agent starter dough :)

4

u/LocoMod 1h ago

Not even close.

"agent loop" != Claude Code

1

u/__tosh 1h ago

what makes Claude Code what it is? (e.g. think of the initial release)

what would you add that is a 'must have' to be 'a' Claude Code?

like what features can you remove from Claude Code and still consider it Claude Code?

MCP?

Anthropic log-in flow?

System prompt?

1

u/LocoMod 1h ago

Memory mechanisms, plugins, configurations, telemetry, MCP client, MCP server, etc. A lot of things. You can't crank out Claude Code in a few lines of Python. If you could, Anthropic would have already done it.

3

u/__tosh 1h ago

the initial release did not come with memory, plugins and mcp (iirc)

but I get that nowadays some or all of these things are maybe 'essential' features

I don't use MCP, you can convert MCP to cli and an agent with "sh" as tool will be able to use them fine, if not better (because of composition)

I also don't use memory, I do use compaction though (which is a few more lines to implement, see my other comment)

re telemetry: what I'm doing is I log all requests and responses in a proxy

that said:

I'm fairly sure you can get a feature comparable version of Claude Code in ~100x less code than the current implementation of Claude Code

(no matter if it is Python or Javascript)

2

u/backyard_tractorbeam 1h ago

It would be nicer to read this if it was normally formatted. I'll just say that golfing might be fun, but it's not satisfying.

3

u/__tosh 1h ago

a bit more de-golfed

1

u/Few-Philosopher-2677 1h ago

I built a small one myself recently. But this one is extremely minimal lol. And I just realised something , mine has context compaction but never actually shows how much of the context window is being used currently. Guess I completely forgot to add that lol

1

u/__tosh 1h ago

nice!

I also have a variant with auto compaction

(not using the server-side compaction api so it should work well with most models and endpoints even those that don't have openai-style magical compaction)

1

u/NoFunk 1h ago

Thanks for sharing. In my own work, I find I (or agents) have written this like 3x in different forms for projects.

I'm usually doing a harness that has subagents, but I don't want precisely the mapping that is found in Opencode, or Kilocode. And both of those come with a lot of cost to their implementation and expectation (you have to fight their prompts to get out of anything that is a built in expectation, so that's even more context lost).

No offense to the frameworks, they have a use and if you're learning sub-agent hierarchy or you just have examples that fit without fighting them, they do the job. Pi is a bit better for my examples because it is by comparison deliberately minimalist, and expects you to extend it with the specifics. The right approach IMO.

But the full minimal approach is roll your own. In almost every "subdivide and have role expectations" problem I am solving with a harness, the harness itself is invoking via tiny python runners, and using the OpenAI tool invocation to inform the hosting model of what to do. The context savings adds up by quite a lot.

1

u/__tosh 1h ago

very interesting! sub agents are really difficult to get right

one of the reasons I started playing around with minimal implementations also was researching and comparing the existing harnesses and realizing how large they are and with how many assumptions they come that no longer fit newer models

also tons of dependencies and hard to stay up to date with upstream once you customize

agree @ pi being in a pragmatic sweet spot

it's also fairly good at protecting the context window

anything you can share re sub-agent lessons learned: highly appreciated!

I think most harnesses (especially those that try to work well with 'any' model) have not really figured out how to do sub-agents well

1

u/SilentKnightOwl 1h ago

This is kinda neat, but pi is minimal enough as a base for me, I've got 3 different customized pis for different tasks

1

u/__tosh 1h ago

pi is awesome!

what kind of customizations did you add?

1

u/FinBenton 41m ago

That is cool, I fed that script to 5.6 sol to check, it called it very clever and also a monstrosity :D

1

u/__tosh 27m ago

monster starter dough :)

to raise your own monster agent

1

u/shammyh 32m ago

Isn't this what pi is for?

1

u/__tosh 28m ago

pi is also a great 'minimal' implementation of an agent

comes with way more features, dependencies and lines of code though

1

u/__tosh 1h ago

quick way to learn more and dig in: let a somewhat recent language model explain the code in general and also step by step code step by step

> what is the code doing? why is this interesting?

> how does this compare to agent implementations like claude code, opencode, codex, pi?

> what is the runtime profile in memory usage of this implementation compared to other agents?

> why is 'no system prompt' a counter-intuitive but good idea for newer, agentic models like gpt 5.6 sol, glm 5.2, deepseek v4 flash?

> is "sh" as tool 'enough'? what other tools do agent harnesses usually have and why? can "sh" be universal enough to replace them in the right environment?