import json
from openai import OpenAI
client = OpenAI(
base_url="https://kymaapi.com/v1",
api_key="ky-your-api-key"
)
tools = [{"type": "function", "function": {
"name": "run_python", "description": "Execute Python code and return the output",
"parameters": {"type": "object", "properties": {
"code": {"type": "string"}}, "required": ["code"]}}}]
def run_python(code: str) -> str:
import subprocess
r = subprocess.run(["python3", "-c", code], capture_output=True, text=True, timeout=10)
return r.stdout or r.stderr
messages = [
{"role": "system", "content": "You are a coding assistant. Use run_python to test your code."},
{"role": "user", "content": "Write a function to find all prime numbers up to 50."}
]
while True:
response = client.chat.completions.create(
model="qwen-3-coder", messages=messages, tools=tools, temperature=0)
msg = response.choices[0].message
messages.append(msg)
if response.choices[0].finish_reason != "tool_calls":
print(msg.content); break
for call in msg.tool_calls:
result = run_python(json.loads(call.function.arguments)["code"])
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})