Skip to content

Instantly share code, notes, and snippets.

@rbitr
Created November 6, 2025 13:28
Show Gist options
  • Select an option

  • Save rbitr/bfbc43b806ac62a5230555582d63d4f7 to your computer and use it in GitHub Desktop.

Select an option

Save rbitr/bfbc43b806ac62a5230555582d63d4f7 to your computer and use it in GitHub Desktop.
command line chat with claude
#! /Users/andrew/miniconda3/envs/py312/bin/python
import anthropic
from datetime import datetime
from hashlib import sha256
import sys
import os
import hashlib
import json
def chat(prompt, system="You are a helpful assistant", messages=None, prefill="", temp=1):
if messages is None:
messages = []
client = anthropic.Anthropic()
messages.append(
{
"role": "user",
"content": [
{
"type": "text",
"text": prompt
}
]
}
)
if prefill:
messages.append(
{
"role": "assistant",
"content": [
{
"type": "text",
"text": prefill
}
]
}
)
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=16384,
temperature=temp,
system=system,
messages=messages
)
resp = message.content[0].text
messages.append(
{
"role": "assistant",
"content": [
{
"type": "text",
"text": resp
}
]
}
)
return resp
if __name__ == "__main__":
cachedir = "/Users/andrew/.chat/"
if len(sys.argv) > 2:
cache_id = sys.argv[2]
with open(cachedir+cache_id) as f:
messages = json.load(f)
else:
cache_id = hashlib.sha256(bytes(str(datetime.now()),encoding="utf-8")).hexdigest()
messages = []
result = chat(sys.argv[1], messages=messages)
print(result)
with open(cachedir+cache_id, "w") as f:
f.write(json.dumps(messages))
print(cache_id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment