Tool Calling

ARK Platform Example / Tool Calling

  • Copy
    
    import requests
    import json
    
    ark_api_key = "API_KEY"
    ark_url = "https://api.ark-labs.cloud/api/v1/chat/completions"
    
    HEADERS = {
        "Authorization": f"Bearer {ark_api_key}",
        "Content-Type": "application/json",
    }
    
    # define the tool (function)
    tools = [
        {
            "type": "function",
            "function": {
                "name": "read_sensor",
                "description": "Reads the value of a sensor.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "sensor_name": {
                            "type": "string",
                            "description": "Name of the sensor: temperature, humidity, or pressure",
                        }
                    },
                    "required": ["sensor_name"],
                },
            },
        }
    ]
    
    # system prompt guiding the assistant to use tool calling
    system_message = {
        "role": "system",
        "content": (
            "You are a helpful assistant with function calling ability. Use your knowledge first. Only call a function when "
            "it is listed and defined and it can return information that is required to answer user's request, otherwise "
            "do not use tools. Never call functions from outside the given list. Never mention tools in your responses "
            "unless you've used them. It's very important to respond *only* with JSON when calling a tool! "
            "Also, do not use escape codes, just plain UTF-8."
        ),
    }
    
    # user prompt that will trigger a tool call
    user_message = {
        "role": "user",
        "content": "What's the current temperature?",
    }
    
    payload = {
        "model": "gpt-4o",
        "temperature": 0,
        "messages": [
            system_message,
            user_message
        ],
        "tools": tools
    }
    
    response = requests.post(ark_url, headers=HEADERS, json=payload)
    
    if response.status_code == 200:
        result = response.json()
        print("Tool call result:")
        print(json.dumps(result["choices"][0]["message"], indent=2, ensure_ascii=False))
    else:
        print(f"Request failed with status {response.status_code}: {response.text}")