#!/usr/bin/env python3
# dummy harness code snippet
# illustrating tool definition and execution
def get_weather(city: str, moon: bool = False) -> str:
"""Dummy function defining a tool.
Would return the current weather for a
city, e.g., as obtained from a weather API.
"""
myString = f"The weather in {city} is sunny."
if moon:
myString += f" Rising moon."
return myString
# tool description (OpenAI-style) sent to the LLM,
# together with chat history
# :: nested dictionaries
WT_properties = { "city": { "type": "string",
"description": "The city to check."},
"moon": { "type": "boolean",
"description": "If true, returns also the moon phase.",
"default": False },
}
#
WT_parameters = { "type" : "object",
"properties": WT_properties,
"required" : ["city"]
}
#
WT_function = { "name" : "get_weather",
"description": "Get the current weather for a city.",
"parameters" : WT_parameters
}
#
weather_tool = { "type" : 'function', # function wrapper not
"function": WT_function # needed for Anthropic
}
# dictionary of all tools,
# used by the harness
ALL_TOOLS = {"get_weather": get_weather
}
if __name__ == '__main__':
# say, the LLM asks the harness to execute a tool,
# the LLM would then return a JSON string containing
tool_name = "get_weather"
arguments = {"city": "Berlin",
"moon": True}
# arguments = {"city": "Berlin"}
# tool execution by the harness
# ** unpacks a dictionary into keyword arguments
result = ALL_TOOLS[tool_name](**arguments)
print(result)
curl console command
curl -X POST https://jsonplaceholder.typicode.com/posts \
-H "Content-Type: application/json" \
-d '{"title": "My Test Post",
"body": "This is a test body sent via POST.",
"userId": 1}'
{
"id" : "chatcmpl-...",
"object" : "chat.completion",
"choices": [
{
"index" : 0,
"message": {
"role" : "assistant",
"content" : null,
"tool_calls": [
{
"id" : "call_abc123",
"type": "function",
"function": {
"name" : "get_weather",
"arguments": "{\"city\": \"Paris\", \"moon\": true}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
"usage": {...}
}
agent_tools.py
#!/usr/bin/env python3
# Minimal weather agent: an LLM that can call a tool.
import json
import requests
from agent_tools import ALL_TOOLS, weather_tool # ALL_TOOLS: {"name": function}
API_URL = "https://api.groq.com/openai/v1/chat/completions"
API_KEY = '-- to be added --'
MODEL = "openai/gpt-oss-120b"
def ask_llm(messages, tools=None):
"""Send the chat history (and optionally tool definitions)
to the LLM, return the LLM's reply message."""
payload = {"model": MODEL, "messages": messages}
if tools:
payload["tools"] = tools
headers = {"Authorization": f"Bearer {API_KEY}"}
resp = requests.post(API_URL, headers=headers, json=payload)
resp.raise_for_status() # stop with an error if the request failed
return resp.json()["choices"][0]["message"]
# ------------------------
# 1. Starting conversation: system prompt and user question
# ------------------------
messages = [
{"role": "system", "content": "Use the provided tools to answer weather queries. "},
{"role": "user", "content": "Is it raining in Berlin?"},
]
# ------------------------
# 2. First call: the LLM sees question and tool description
# ------------------------
reply = ask_llm(messages, tools=[weather_tool])
messages.append(reply)
# 3. If the LLM asked for tool calls, run them and add the results to the history
for call in reply.get("tool_calls") or []:
name = call["function"]["name"]
args = json.loads(call["function"]["arguments"]) # arguments arrive as a JSON string
result = ALL_TOOLS[name](**args) # the actual tool execution
messages.append({"role": "tool",
"tool_call_id": call["id"],
"content": result})
# ------------------------
# 4. Second call: the LLM sees the tool results and writes the final answer
# :: if no tool was called, the LLM answers directly in step 2
# ------------------------
if reply.get("tool_calls"):
reply = ask_llm(messages)
print("User:\n", messages[1]["content"])
print("LLM :\n", reply["content"])
# ------------------------
# 5. Dump chat history
# ------------------------
with open("chat_history.json", "w", encoding="utf-8") as f:
json.dump(messages, f, indent=2, ensure_ascii=False)
curl --request GET \
--url https://litellm.s.studiumdigitale.uni-frankfurt.de/v1/models \
--header 'x-litellm-api-key: API_KEY'
#!/usr/bin/env python3
# Minimal file agent: an LLM that can list, read, write and append files
# inside a sandbox folder called 'workspace'.
import json
import requests
from pathlib import Path
API_URL = "https://api.groq.com/openai/v1/chat/completions"
API_KEY = ''
MODEL = "openai/gpt-oss-120b"
WORKSPACE = (Path(__file__).parent / "workspace").resolve()
WORKSPACE.mkdir(exist_ok=True)
# ---------------------------
# 1. Tools: ordinary Python functions that work inside the workspace
# (errors are simply raised; the agent loop reports them to the LLM)
# ---------------------------
def safe_path(path: str) -> Path:
"""Turn a relative path into an absolute one, but never leave the workspace."""
full = (WORKSPACE / path.lstrip("/")).resolve()
if not full.is_relative_to(WORKSPACE): # blocks tricks like '../../secret'
raise PermissionError("Access denied")
return full
def list_files(path: str = "") -> str:
items = sorted(safe_path(path).rglob("*"))
lines = [f"{'[DIR] ' if p.is_dir() else '[FILE]'} {p.relative_to(WORKSPACE)}" for p in items]
return "\n".join(lines) or "(empty)"
def read_file(path: str) -> str:
return safe_path(path).read_text(encoding="utf-8")
def write_file(path: str, content: str) -> str:
file = safe_path(path)
file.parent.mkdir(parents=True, exist_ok=True)
file.write_text(content, encoding="utf-8")
return f"Wrote file: {path}"
def append_file(path: str, content: str) -> str:
file = safe_path(path)
file.parent.mkdir(parents=True, exist_ok=True)
with open(file, "a", encoding="utf-8") as f:
f.write(content)
return f"Appended to file: {path}"
# ---------------------------
# 2. Tool descriptions: this is what the LLM sees (a JSON schema per tool).
# Each description is built step by step from small dictionaries.
# ---------------------------
# --- list_files ---
LF_properties = { "path": { "type" : "string",
"description": "Optional subdirectory; empty means workspace root."}
}
LF_parameters = { "type" : "object",
"properties": LF_properties
}
LF_function = { "name" : "list_files",
"description": "List all files and directories in the workspace.",
"parameters" : LF_parameters
}
list_files_tool = { "type" : "function",
"function": LF_function
}
# --- read_file ---
RF_properties = { "path": { "type" : "string",
"description": "Path of the file."}
}
RF_parameters = { "type" : "object",
"properties": RF_properties,
"required" : ["path"]
}
RF_function = { "name" : "read_file",
"description": "Read the contents of a text file.",
"parameters" : RF_parameters
}
read_file_tool = { "type" : "function",
"function": RF_function
}
# --- write_file ---
WF_properties = { "path" : { "type" : "string",
"description": "Path of the file."},
"content": { "type" : "string",
"description": "Content to write."}
}
WF_parameters = { "type" : "object",
"properties": WF_properties,
"required" : ["path", "content"]
}
WF_function = { "name" : "write_file",
"description": "Write content to a file (creates or overwrites it).",
"parameters" : WF_parameters
}
write_file_tool = { "type" : "function",
"function": WF_function
}
# --- append_file ---
AF_properties = { "path" : { "type" : "string",
"description": "Path of the file."},
"content": { "type" : "string",
"description": "Content to append."}
}
AF_parameters = { "type" : "object",
"properties": AF_properties,
"required" : ["path", "content"]
}
AF_function = { "name" : "append_file",
"description": "Append content to a file (creates it if missing).",
"parameters" : AF_parameters
}
append_file_tool = { "type" : "function",
"function": AF_function
}
# list of all tool descriptions, sent to the LLM
TOOL_DEFS = [list_files_tool, read_file_tool, write_file_tool, append_file_tool]
# name (string sent by the LLM) -> Python function
TOOL_FUNCS = {f.__name__: f for f in (list_files, read_file, write_file, append_file)}
# ---------------------------
# 3. Talking to the LLM
# ---------------------------
def ask_llm(messages):
payload = {"model": MODEL, "messages": messages, "tools": TOOL_DEFS}
headers = {"Authorization": f"Bearer {API_KEY}"}
resp = requests.post(API_URL, headers=headers, json=payload, timeout=60)
resp.raise_for_status()
return resp.json()["choices"][0]["message"]
# ---------------------------
# 4. The agent loop: repeat until the LLM stops asking for tools
# ---------------------------
def run_agent(messages):
while True:
reply = ask_llm(messages)
messages.append(reply)
tool_calls = reply.get("tool_calls")
if not tool_calls: # no tool wanted -> this is the final answer
return reply["content"] or ""
for call in tool_calls:
name = call["function"]["name"]
args = json.loads(call["function"]["arguments"])
print(f" [tool] {name}({args})")
try:
result = TOOL_FUNCS[name](**args) # run the tool
except Exception as e: # tell the LLM what went wrong
result = f"ERROR: {e}"
messages.append({"role": "tool",
"tool_call_id": call["id"],
"content": result})
# ---------------------------
# 5. Chat with the agent; the history is dumped to JSON when we quit
# ---------------------------
messages = [{"role": "system",
"content": "You are a file assistant. Use the tools for ALL file operations, "
"never invent file contents, and read a file before modifying it. "
"All paths are relative to the workspace root."}]
print(f"File agent, workspace: {WORKSPACE}\nType 'exit' to quit.\n")
while True:
try:
user_input = input("> ").strip()
except (EOFError, KeyboardInterrupt):
break
if user_input.lower() in ("exit", "quit"):
break
if not user_input:
continue
messages.append({"role": "user", "content": user_input})
try:
print("\n" + run_agent(messages) + "\n")
except requests.exceptions.RequestException as e:
print(f"\nAPI error: {e}\n")
with open("chat_history.json", "w", encoding="utf-8") as f:
json.dump(messages, f, indent=2, ensure_ascii=False)
print("Bye!")