Help

Overview Admin Chat UI Design Curated Answers Search Settings Conversational Intelligence Data Sync Upload Documents Human Handoff Admin Console Authorisation Contact Support

Writing Your First Function

Airgentic Help

Coming Soon — This feature is currently in development and not yet available. This guide is a preview of what's coming.

This tutorial walks you through creating a complete AirScript function from scratch. By the end, you'll have a working get_weather function that calls a public API and returns the current weather to the user.


What You'll Build

A function that:
1. Receives a location from the user (e.g. "London", "Tokyo")
2. Calls the free wttr.in weather API
3. Parses the JSON response
4. Returns a weather summary to the agent


Step 1: Create a New Function

  1. Navigate to Agents, Prompts & Functions → Functions
  2. Click Add Function
  3. Enter a name: get_weather

You'll see two editor panels: the Function Definition (JSON) on the right, and the AirScript Code on the left.


Step 2: Define the Function Schema

The function definition tells the AI when to call your function and what arguments to extract from the conversation.

For our get_weather function, we need to define two parameters:
- location (required) — the city or place to get weather for
- unit (optional) — whether to return temperature in celsius or fahrenheit

Replace the default JSON with:

{
    "type": "function",
    "name": "get_weather",
    "description": "Get the current weather for a location. Call this when the user asks about the weather.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city or location to get the weather for (e.g. 'London', 'New York', 'Tokyo')."
            },
            "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "Temperature unit to use in the response. Use 'celsius' unless the user explicitly asks for fahrenheit."
            }
        },
        "required": ["location"],
        "additionalProperties": false
    },
    "strict": true
}

Key attributes:
- type — must always be "function"
- name — must match your function name exactly
- description — helps the AI decide when to call this function (be specific)
- parameters — defines what the AI should extract from the conversation
- required — lists parameters the AI must provide (optional ones like unit can be omitted)
- strict — when true, ensures the AI strictly follows your schema

For more details on function schemas, see the OpenAI Function Calling Guide.


Step 3: Write the AirScript Code

Now write the code that runs when the AI calls your function. Replace the default code with:

async def run(air):
    """Look up the current weather for a location using the wttr.in API."""

    # Read the location and preferred temperature unit from the LLM-extracted arguments.
    # Unit defaults to celsius unless the user asked for fahrenheit.
    location = air.args.get("location", "")
    unit = air.args.get("unit", "celsius").lower()

    if not location:
        # Tell the LLM no location was provided so it can ask the user
        air.reply_to_llm("No location was provided.")
        return

    # Show a "please wait" message to the user while the API call runs
    air.send_interim_message_to_user()

    # Build the wttr.in API URL — j1 format returns structured JSON
    url = f"https://wttr.in/{location}?format=j1"

    # Make the HTTP GET request; air.http_get returns the response body as a
    # string, or None if the request failed
    response = await air.http_get(url)

    if not response:
        air.reply_to_llm(f"Sorry, I couldn't retrieve the weather for {location}.")
        return

    try:
        # Parse the JSON response body (json module is available without importing)
        data = json.loads(response)
    except (ValueError, TypeError):
        air.reply_to_llm(f"Sorry, I received an unexpected response when looking up the weather for {location}.")
        return

    # Extract the current conditions from the API response
    current = data.get("current_condition", [{}])[0]
    temp_c = current.get("temp_C", "?")
    temp_f = current.get("temp_F", "?")
    feels_like_c = current.get("FeelsLikeC", "?")
    humidity = current.get("humidity", "?")
    description = current.get("weatherDesc", [{}])[0].get("value", "Unknown")
    wind_kmph = current.get("windspeedKmph", "?")

    # Format temperature values based on the requested unit
    if unit == "fahrenheit":
        temp = f"{temp_f}°F"
        feels_like = f"{current.get('FeelsLikeF', '?')}°F"
    else:
        temp = f"{temp_c}°C"
        feels_like = f"{feels_like_c}°C"

    # Build a plain-text summary to hand back to the LLM
    summary = (
        f"Weather in {location}: {description}, "
        f"{temp}, "
        f"feels like {feels_like}, "
        f"humidity {humidity}%, "
        f"wind {wind_kmph} km/h."
    )

    # Pass the summary to the LLM so it can relay it to the user
    air.reply_to_llm(summary)

Step 4: Understanding the Code

Let's break down the key parts:

Reading Arguments

location = air.args.get("location", "")
unit = air.args.get("unit", "celsius").lower()

The air.args dictionary contains the arguments the AI extracted from the conversation based on your schema. Always use .get() with a default value to handle missing optional parameters.

Validation

if not location:
    air.reply_to_llm("No location was provided.")
    return

If required data is missing, use air.reply_to_llm() to tell the AI what went wrong. The AI will then ask the user for the missing information.

Showing Progress

air.send_interim_message_to_user()

For operations that take time (API calls, searches), show a "Please wait..." message so the user knows something is happening.

Making HTTP Requests

response = await air.http_get(url)

Use await air.http_get() to fetch data from external APIs. It returns the response body as a string, or None if the request failed. Remember to use await — this is an async operation.

Parsing JSON

data = json.loads(response)

The json module is available without importing. Use json.loads() to parse JSON strings into Python dictionaries.

Returning Results

air.reply_to_llm(summary)

Use air.reply_to_llm() to send your result back to the AI. The AI will use this information to formulate its response to the user.


Step 5: Save and Test

  1. Click Save to save your function
  2. Add the function to an agent (in the agent's configuration)
  3. Test by asking your agent: "What's the weather in London?"

The agent should call your function, fetch the weather data, and respond with the current conditions.


Common Patterns

Error Handling

Always handle potential errors gracefully:

if not response:
    air.reply_to_llm("Sorry, the weather service is unavailable.")
    return

try:
    data = json.loads(response)
except (ValueError, TypeError):
    air.reply_to_llm("Sorry, I received an invalid response.")
    return

Optional Parameters with Defaults

unit = air.args.get("unit", "celsius")  # Default to celsius
limit = air.args.get("limit", 10)        # Default to 10 results

Conditional Logic

if unit == "fahrenheit":
    temp = f"{temp_f}°F"
else:
    temp = f"{temp_c}°C"

Next Steps


← Back to Functions overview

You have unsaved changes