
tl;dr
I built codesherpa, a code interpreter plugin for ChatGPT. ChatGPT writes the code, and a small FastAPI server running on your machine executes it and sends back the result.
- The code is on GitHub
- It works with ChatGPT’s “Develop your own plugin” option, so you need plugin developer access to use it as a plugin.
Intro
On March 23, 2023, OpenAI announced ChatGPT plugins. Third party plugins from Expedia, Instacart, Wolfram and others, plus two plugins OpenAI built themselves: a web browser and something called Code Interpreter. Access was a limited alpha with a waitlist, both for people who wanted to use plugins and for developers who wanted to build them. I put my name down as a developer.
Code Interpreter was the one that got my attention.
I didn’t have access to it. I’d been paying for ChatGPT since January1, and still no Code Interpreter. Meanwhile I kept seeing posts and screenshots from the people who did.
So, I wanted Code Interpreter, I didn’t have Code Interpreter, and OpenAI had just told everyone how to build plugins.
How Plugins Work
A ChatGPT plugin is surprisingly straight-forward. It’s an HTTP API plus two files:
- A manifest at
/.well-known/ai-plugin.json. It has a name, a logo, an auth type, a link to your API spec, and adescription_for_modelfield, which is basically a prompt telling the model what your plugin does and when to use it. - An OpenAPI spec describing your endpoints.
ChatGPT reads both, and when a conversation calls for it, the model decides to call one of your endpoints with JSON it wrote itself. Your API responds, and the model reads the response and continues.
So the code interpreteer is just a repl:
- Model writes code
- Something runs the code
- The output goes back to the model
- profit???
The model already does step 1 pretty well. I just needed to build step 2: an endpoint that takes code and returns what it printed.
By early May I was off the developer waitlist, which unlocked “Develop your own plugin” button in the plugin store thing. And you can point it it to localhost.
Version 0: A FastAPI repl
The first version was one file, main.py. Two endpoints: /repl to execute python, and /command to run shell commands. Python’s standard library has a code module that gives you an interactive console, the same thing behind the >>> prompt, so I used that:
main.py
class CodeExecutionRequest(BaseModel):
code: List[str]
persistent_console = code.InteractiveConsole()
def execute_code_in_repl(code_list: List[str]) -> str:
output = io.StringIO()
try:
with redirect_stdout(output), redirect_stderr(output):
for code_line in code_list:
persistent_console.push(code_line)
result = output.getvalue()
except Exception as e:
result = str(e)
return result
The console lives as long as the server, and so the state willpersist between each request. Define df in one message, then use it three messages later.
The List[str] part did not work so great. InteractiveConsole.push() behaves exactly like you typing at a >>> prompt, one line at a time. And at the prompt, a block like a for loop isn’t finished until you enter a blank line. The model doesn’t know that, so it sends perfectly valid python like:
{
"code": [
"for i in range(3):",
" print(i)",
"print('done')"
]
}
and gets back:
File "<console>", line 3
print('done')
^^^^^
SyntaxError: invalid syntax
My description_for_model had to teach the model to send code as an array of escaped strings, with an escaped JSON example inside the description. ’twas fugly. Later I tried splitting lines on ; so the model could cram more onto one line, which of course breaks the moment there’s a semicolon inside a str, etc.
the model also didn’t call the plugin every time (very frustrating!). Sometimes it would just answer without running anything, so it was basically unpredictable at first, though it seems to have improved since.
Still, it worked well enough for a first demo - which was basically me ripping off OpenAI’s Code Interpreter demo to see if I could primitively recreate it. here it is (i admit i didn’t check the outputs very closely..)
May 6, 2023. Note the little “LOCALHOST” badge.
Detour: Should This Run in the Cloud?
tl;dr: no! it shouldnt.
I wasted a bit of time following this hair-brained idea that I would actually try to publish this plugin to the store, which means I’d need to run an RCE service, VMs, all that. Suffice to say I was not interested in recreating the full code interpreter experience myself. There’s a /server dir, and some other grave sites of this failed expedition.
Local Only
So codesherpa just stays local. That’s it. That’s all it is.
For plugins in development on localhost, the API calls are made from the ChatGPT page in your browser. That’s why the server has to allow CORS from https://chat.openai.com:
localserver/main.py
PORT = 3333
origins = [
f"http://localhost:{PORT}",
"http://localhost:3002",
"http://localhost:3001",
"http://localhost:3000",
"https://chat.openai.com",
"https://chat.openai.com/?model=gpt-4-plugins",
]
(yeah, that last one is a URL with a query string in a list of origins. It does nothing. I’m leaving it in as a monument, because yeah.)
When the model makes a plot, codesherpa saves it to static/images/, which FastAPI serves as static files. The model then embeds it in its answer with a regular markdown image pointing at http://localhost:3333/static/images/plot.png. That image loads in your browser, from your machine. Uploaded files work the same way: there’s a small /upload page that saves files to static/uploads/, and the model knows to look there.

It’s your python env. if you need a package, just pip install it via the /command endpoint.
ASTs
In late May I switched the request from a lines list to just a single string, and refactored the code execution into these executor classes, one per language, because why not add C++ and Rust while I’m at it? I’m not proficient in either, but maybe chatgpt is. The first Python executor wrote the code to script.py and ran it in a subprocess. That fixed the indentation problem i was having, and htne it broke state, since every request was a brand new process.
If you exec() a string, df.head() gets evaluated and the result is thrown out. If you eval() it, you get the value, but eval() only accepts a single expression, not statements like import or x = 5. You need to know, for each statement, which kind it is. luckily some very smart people invented/discovered the abstract syntax tree (AST).
Python’s ast module parses the source into a tree of nodes without running anything. Lets take a typical snippet ChatGPT might send:
import pandas as pd
df = pd.read_csv('static/uploads/music.csv')
df.head()
ast.dump(ast.parse(code), indent=2) gives you:
Module(
body=[
Import(
names=[
alias(name='pandas', asname='pd')]),
Assign(
targets=[
Name(id='df', ctx=Store())],
value=Call(
func=Attribute(
value=Name(id='pd', ctx=Load()),
attr='read_csv',
ctx=Load()),
args=[
Constant(value='static/uploads/music.csv')],
keywords=[])),
Expr(
value=Call(
func=Attribute(
value=Name(id='df', ctx=Load()),
attr='head',
ctx=Load()),
args=[],
keywords=[]))],
type_ignores=[])
here’s the executor w/a quick explanation.
executors/executor.py
class PythonExecutor(Executor):
locals = {}
def execute(self, code: str) -> str:
logger.info("Executing Python code: {}", code)
output = io.StringIO()
# Parse the code into an AST.
tree = ast.parse(code, mode="exec")
try:
# Redirect standard output to our StringIO instance.
with redirect_stdout(output):
for node in tree.body:
# Compile and execute each node.
exec(
compile(
ast.Module(body=[node], type_ignores=[]), "<ast>", "exec"
),
None,
PythonExecutor.locals,
)
# If the node is an expression, print its result.
if isinstance(node, ast.Expr):
eval_result = eval(
compile(ast.Expression(body=node.value), "<ast>", "eval"),
None,
PythonExecutor.locals,
)
if eval_result is not None:
print(eval_result)
except Exception as e:
logger.error("Error executing Python code: {}", e)
return str(e)
# Retrieve the output and return it.
return output.getvalue()
Step by step:
ast.parse(code, mode="exec")parses the whole block, so theforloop indentation thing isn’t a problem anymore.- Each top-level statement gets wrapped in its own little
ast.Moduleand handed tocompile(). You can passcompile()an AST instead of a string, which i did not know. So good on you, Python. exec()runs it against a dict that lives on the class, so stuff sticks around between requests. That dictionary i guess is sort of the session (right?). Anyway….- If the statement is just an expression (an
Expr), it also getseval()’d and the result printed, like the REPL does.Nonegets skipped so you don’t seeNoneafter everyplt.show(). redirect_stdoutgrabs whatever got printed, and that’s what goes back to ChatGPT.- Errors go back as just the message, e.g.
name 'df' is not defined.
Running it statement by statement also means that if statement 4 of 6 blows up, statements 1 through 3 already happened and whatever they defined is still sitting there, so the model can see the error and just send the fix without redoing all the slow stuff like importing a csv or whatever.
Demo of the Demo
By far my favorite part of this whole endeavor was recreating the openai demo. First, plot 1/sin(x), then zoom in, then add a tangent line. Sped up 2x:
Next, the music.csv dataset from CORGIS. I uploaded it and asked for some analysis. Sped up 1.5x:
And one just for fun, from a bit earlier: a vector field on a sphere, saved as an animated GIF and embedded right back into the chat (I did not check this for accuracy, to be clear!).
Teaching ChatGPT to Use It
The other half of a plugin, besides the code that actually runs, is the so-called “prompt engineering” (I’ve never liked that term) in description_for_model. Mine started as one enormous run-on paragraph with escaped JSON examples, instructions to pip.main(['install', ...]) things, and a reminder to always use /static/images for plots. Every token of it gets read by the model, so I wanted it smaller.
In June I let FastAPI do more of the work. FastAPI already generates an OpenAPI spec from the route definitions and Pydantic models, so instead of hand-maintaining an openapi.yaml, the plugin now serves FastAPI’s own spec at /.well-known/openapi.json. Request examples live on the Pydantic models, so they end up in the spec too:
models/api.py
class CodeExecutionRequest(BaseModel):
language: str = Field(..., example="python")
code: str = Field(..., example="print('Hello, World!')")
The server URL gets patched in at startup:
@app.on_event("startup")
def startup_event():
openapi_schema = app.openapi()
openapi_schema["servers"] = [
{
"url": "http://localhost:3333",
"description": "Local server",
}
]
app.openapi_schema = openapi_schema
With the “how to call me” part handled by the spec, the description only has to cover “when and why”:
utils/plugin.py (trimmed)
description_for_model = textwrap.dedent(f"""
A plugin for interactive code execution, file management, and shell command execution.
`/repl` endpoint
- Execute Python code interactively for general programming, tasks, data analysis, visualizations, and more.
- Pre-installed packages: matplotlib, seaborn, pandas, numpy, scipy, openpyxl.If you need to install additional packages, use the `pip install` command.
- When a user asks for visualization, save the plot to `static/images/` directory, and embed it in the response using `http://localhost:{PORT}/static/images/` URL.
`/command` endpoint
- Run terminal commands and interact with the filesystem, run scripts, and more.
File management
- Provide 'Upload file' link for users: http://localhost:{PORT}/upload
- Access user-uploaded files in `static/uploads/`
""")
Standalone Mode: Function Calling
On June 13, OpenAI added function calling to the API (gpt-3.5-turbo-0613 and gpt-4-0613). You describe functions with JSON Schema, and the model can respond with a function name and JSON arguments instead of text.
Which meant codesherpa didn’t strictly need plugin access anymore. The function names are just FastAPI’s auto-generated operation IDs:
frontend/src/constants/const.ts (trimmed)
export const FUNCTIONS: Array<any> = [
{
"name": "repl_repl_post",
"description": "Exexute code. Note: This endpoint current supports a REPL-like environment for Python only. ...",
"parameters": {
"type": "object",
"properties": {
"language": { "type": "string", "example": "python" },
"code": { "type": "string", "example": "print('Hello, World!')" }
},
"required": ["language", "code"]
}
},
{
"name": "command_endpoint_command_post",
...
}
];
(Yes, “Exexute”. lol)
So in July I built a Next.js chat UI. It streams the response, and when the model asks for a function call, the UI looks up the path for that operation ID in the OpenAPI spec, POSTs the arguments to the local codesherpa server, adds the result to the conversation as a function message, and lets the model continue. If the model makes up a function name (it does), the UI adds an assistant message apologizing for using the wrong function and sends the conversation back so it tries again. This is crude. but i guess it kind of works, though again, its very primitive. You bring your own OpenAI API key.
It’s experimental, and it’s buggy. Function call rendering is inconsistent, there’s only one conversation at a time, and you can’t edit previous messages. But it’s a fun loop.
Finally in early July, OpenAI announced Code Interpreter would roll out to all Plus users over the next week. So now I have the real thing.
It’s very good. More polished than I expected. You just give it your stuff, and let it rip, so to speak.
I don’t plan on maintaining codesherpa. It was a stopgap until I got the real thing, and now I have the real thing. A special thanks to anyone who tried it out and/or contributed!