-
Notifications
You must be signed in to change notification settings - Fork 20
Description
tooluse-config.yaml
utility_agents:
- agent_class: ToolUseAgent
agent_name: "Tool Use Agent"
agent_description: "An agent that performs function calling using provided tools."
config:
wait_time: 120
enable_interpreter: true
builtin_tools:
- "calculate_expression"
custom_tools:
- |
{
"type": "function",
"function": {
"name": "generate_password",
"description": "Generate a random password of specified length.",
"parameters": {
"type": "object",
"properties": {
"length": {
"type": "integer",
"description": "Length of the password to generate. Default is 12.",
"default": 12
}
},
"required": []
}
}
}
- |
{
"type": "function",
"function": {
"name": "convert_temperature",
"description": "Convert temperature between Celsius and Fahrenheit.",
"parameters": {
"type": "object",
"properties": {
"value": {
"type": "float",
"description": "The temperature value to convert."
},
"to_scale": {
"type": "string",
"description": "The scale to convert the temperature to ('Celsius' or 'Fahrenheit').",
"enum": ["Celsius", "Fahrenheit"],
"default": "Celsius"
}
},
"required": ["value"]
}
}
}
tooluse.py
import random
import string
import os
import asyncio
from dotenv import load_dotenv
from air import login, DistillerClient
import logging
import uuid
Set up logging
logger = logging.getLogger(name)
logging.basicConfig(
level=logging.DEBUG, # Show debug logs and above
format='%(asctime)s | %(levelname)-8s | %(name)s:%(funcName)s:%(lineno)d - %(message)s',
)
load_dotenv() # This loads your ACCOUNT and API_KEY from your local '.env' file
auth = login(
account=str(os.getenv("ACCOUNT")),
api_key=str(os.getenv("API_KEY")),
)
distiller_client = DistillerClient()
async def convert_temperature(value: float, to_scale: str = "Celsius") -> str:
"""
Convert temperature between Celsius and Fahrenheit.
Args:
value (float): The temperature value to convert.
to_scale (str): The scale to convert to ('Celsius' or 'Fahrenheit').
Returns:
float: The converted temperature value.
"""
logger.debug(f"Converting {value} to {to_scale}")
if to_scale == "Celsius":
converted = (value - 32) * 5.0 / 9.0
elif to_scale == "Fahrenheit":
converted = (value * 9.0 / 5.0) + 32
else:
raise ValueError("Invalid to_scale. Must be 'Celsius' or 'Fahrenheit'.")
return f"{converted:.2f}"
async def generate_password(length: int = 12) -> str:
"""
Generate a random password of specified length.
Args:
length (int, optional): The total length of the password to generate.
Must be at least 4 to include one of each required character type.
Defaults to 12.
Returns:
str: A randomly generated password string.
"""
logger.debug(f"Generating password with length:{length} chars")
if length < 4:
raise ValueError("Password length should be at least 4 characters.")
password_chars = [
random.choice(string.ascii_uppercase),
random.choice(string.ascii_lowercase),
random.choice(string.digits),
random.choice(string.punctuation),
]
if length > 4:
all_chars = string.ascii_letters + string.digits + string.punctuation
password_chars.extend(random.choice(all_chars) for _ in range(length - 4))
random.shuffle(password_chars)
password = "".join(password_chars)
return password
async def tool_use_demo():
distiller_client = DistillerClient()
# Create project from YAML config
distiller_client.create_project(
config_path="tooluse-config.yaml",
project="tooluse_example"
)
executor_dict = {
"generate_password": generate_password,
"convert_temperature": convert_temperature,
}
session_id = str(uuid.uuid4())
logger.debug(f"Session ID: {session_id}")
# Important: Connect properly before using
await distiller_client.connect(
project="tooluse_example",
uuid=session_id,
executor_dict=executor_dict
)
logger.debug("connected to tool use demo...")
queries = [
"Convert 100 Fahrenheit to Celsius.",
"Generate a safe password with 23 chars.",
]
try:
for query in queries:
responses = await distiller_client.query(query=query)
print(f"----\nQuery: {query}")
async for response in responses:
print(f"Response: {response['content']}")
except Exception as e:
logger.error(f"An error occurred: {e}")
finally:
await distiller_client.close()
logger.info("Completed test...")
async def tool_use_demo1():
# Initialize the DistillerClient
distiller_client = DistillerClient()
# Register a new project with your configuration
distiller_client.create_project(config_path="tooluse-config.yaml", project="example")
# Map custom agent names to their corresponding functions
executor_dict = {
"generate_password": generate_password,
"convert_temperature": convert_temperature,
}
async with distiller_client(
project="example",
uuid="test_user",
executor_dict=executor_dict,
) as dc:
# List of queries to process
queries = [
"Covert 100 Fahrenheit to Celsius.",
"Generate a safe password with 23 chars.",
]
for query in queries:
# Send the query and print responses
responses = await dc.query(query=query)
print(f"----\nQuery: {query}")
async for response in responses:
print(f"Response: {response['content']}")
if name == "main":
asyncio.run(tool_use_demo())
error
(venv) ➜ DistClient pip install "git+https://github.com/Accenture/airefinery-sdk.git@main"
(venv) ➜ DistClient python tooluse.py
Registering project 'tooluse_example' for account 'faad96ef-7482-4d24-8667-adc02663bf82'
Project tooluse_example - version 1 has been created for faad96ef-7482-4d24-8667-adc02663bf82.
Query: Convert 100 Fahrenheit to Celsius.
Receive loop error: received 1011 (internal error) Internal Server Error; then sent 1011 (internal error) Internal Server Error
Ping monitor: No PING received in the last interval. Closing connection.
Query: Generate a safe password with 23 chars.
2025-06-16 12:56:18.134 | ERROR | main:tool_use_demo:105 - An error occurred: Project cannot be None. You should call connect first.
2025-06-16 12:56:18.134 | INFO | main:tool_use_demo:108 - Completed test...