Agent Runs
Last updated
Last updated
With Agent Runs, you can create agents from any prompt you build in Prompt Studio and then run each agent as an API. This feature is particularly useful because it allows you to build and deploy agents directly from your application without needing direct access to an AI model or requiring the adoption of additional frameworks and APIs.
Agent Runs are equipped with all the default Toolhouse tools. You can optionally specify a bundle to further tailor the functionality of your agent.
Agent tokens are free
All Agents Runs use a premium LLM model. For a limited time, LLM tokens are free, meaning you will need to worry about cost per token. Your account will only be charged for Toolhouse Execs.
Make sure you have your API Key ready. You can see or create an API key in the API Keys page.
Head over to Prompt Studio and create a chat. If you're looking for inspiration, you can use this prompt.
Click the Share button, then copy the Chat ID.
Create an Agent Run using the Agent Runs API:
import requests
import json
def send_request(toolhouse_api_key, chat_id):
url = "https://api.toolhouse.ai/v1/agent-runs"
headers = {
"Authorization": f"Bearer {toolhouse_api_key}",
"Content-Type": "application/json"
}
# Set the JSON payload
payload = {
"chat_id": chat_id
}
# Send the POST request
response = requests.post(url, headers=headers, json=payload)
return response
# Example usage
if __name__ == "__main__":
toolhouse_api_key = "YOUR_TOOLHOUSE_API_KEY"
chat_id = "YOUR_CHAT_ID"
response = send_request(toolhouse_api_key, chat_id)
# Check if the request was successful
if response.status_code == 200:
print("Request successful. Response:")
print(response.json())
else:
print("Request failed with status code", response.status_code)
async function createAgentRun(toolhouseApiKey, chatId) {
try {
const url = 'https://api.toolhouse.ai/v1/agent-runs';
const headers = {
'Authorization': `Bearer ${toolhouseApiKey}`,
'Content-Type': 'application/json',
};
const body = JSON.stringify({
'chat_id': chatId,
});
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: body,
});
if (response.ok) {
const data = await response.json();
console.log(data);
} else {
console.error('Failed to retrieve data:', response.status, response.statusText);
}
} catch (error) {
console.error('An error occurred:', error);
}
}
// Example usage
const toolhouseApiKey = 'YOUR_TOOLHOUSE_API_KEY';
const chatId = 'your_chat_id';
await createAgentRun(toolhouseApiKey, chatId);
curl "https://api.toolhouse.ai/v1/agent-runs" \
-H "Authorization: Bearer $YOUR_TOOLHOUSE_API_KEY" \
--json '{
"chat_id": "your_chat_id"
}'
Your Agent Run will be queued for execution:
{
"data": {
"id": "bcb7e865-9e6c-xxxx-xxxx-c0110fdf5c2e",
"user_id": "665618fbdeadd84260aa",
"status": "queued",
"results": [],
"created_at": "2025-01-15T01:46:23.568338",
"updated_at": "2025-01-15T01:46:23.568338",
"bundle": "default",
"toolhouse_id": "default"
}
}
Use the Get Agent Runs endpoint to retrive the status of a run.
import requests
YOUR_RUN_ID = "your_run_id_here" # replace with your actual run ID
url = f"https://api.toolhouse.ai/v1/agent-runs/{YOUR_RUN_ID}"
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
print(response.json())
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")
async function getAgentRun(toolhouseApiKey, runId) {
try {
const url = `https://api.toolhouse.ai/v1/agent-runs/${runId}`;
const headers = {
'Authorization': `Bearer ${toolhouseApiKey}`,
'Content-Type': 'application/json',
};
const response = await fetch(url, { headers });
if (response.ok) {
const data = await response.json();
console.log(data);
} else {
console.error('Failed to retrieve data:', response.status, response.statusText);
}
} catch (error) {
console.error('An error occurred:', error);
}
}
// Example usage
const toolhouseApiKey = 'YOUR_TOOLHOUSE_API_KEY';
const chatId = 'your_chat_id';
await getAgentRuns(toolhouseApiKey, chatId);
curl "https://api.toolhouse.ai/v1/agent-runs/$YOUR_RUN_ID"
You will see the run status and its results. The run status will be one of these values:
queued
The Agent Run is being scheduled and will be executed shortly.
in_progress
The agent is currently running and its results are being generated
completed
The Agent Run completed successfully. You will be able to see the results of the run in the results
field of the API response.
failed
The Agent Run completed with one or more errors. You will be able to see the errors in the results
field of the API response.
This is what a response will look like:
{
"data": {
"id": "bcb7e865-9e6c-xxxx-xxxx-c0110fdf5c2e",
"chat_id": "a3a26d33-6f4d-4490-a56f-e17f867ba451",
"status": "queued",
"results": [],
"created_at": "2025-01-15T01:46:23.568338",
"updated_at": "2025-01-15T01:46:59.270078",
"bundle": "default",
"toolhouse_id": "default"
}
}
{
"data": {
"id": "bcb7e865-9e6c-xxxx-xxxx-c0110fdf5c2e",
"chat_id": "a3a26d33-6f4d-4490-a56f-e17f867ba451",
"status": "in_progress",
"results": [],
"created_at": "2025-01-15T01:46:23.568338",
"updated_at": "2025-01-15T01:46:59.270078",
"bundle": "default",
"toolhouse_id": "default"
}
}
{
"data": {
"id": "bcb7e865-9e6c-xxxx-xxxx-c0110fdf5c2e",
"chat_id": "a3a26d33-6f4d-4490-a56f-e17f867ba451",
"status": "completed",
"results": [
{
"role": "user",
"content": "Generate a random pet fact and send it to me via email. Here's how to generate a pet fact: \n\n1. Look into memory for past pet facts I already know about. Ensure you avoid mentioning these facts, so I can always get new pet facts. It's okay if I don't have previous pet facts.\n2. Prepare a few sentences about this pet fact. Make it fun and insightful!\n3. Get my email address from memory and send an email with the pet fact. Format it nicely with HTML and CSS so it looks super cute. If you can't find my email in memory, ask me for one.\n4. Store my email and the pet fact you generated in memory."
},
{
"role": "assistant",
"content": [
{
"text": "I'll help you generate and send a random pet fact! Let me follow your steps:\n\n1. First, let me check memory for any past pet facts and your email address:",
"type": "text"
},
{
"args": {},
"type": "tool-call",
"toolName": "memory_fetch",
"toolCallId": "toolu_01L1KXeHYNKhSxqAtLMDdC57"
}
]
},
{
"role": "tool",
"content": [
{
"type": "tool-result",
"result": "<memory created_at=\"2024-12-10 02:52:59\">\n Email: daniele@toolhouse.ai\nMeal preferences: vegetarian\n </memory><memory created_at=\"2024-12-10 03:18:12\">\n Email: daniele@toolhouse.ai\nMeal preferences: vegetarian\n </memory><memory created_at=\"2024-12-10 19:18:08\">\n Daily Meal Plan for December 10, 2024:\n\n**Breakfast:** \n- **Vegetarian Avocado Toast** \n *Ingredients:* \n - 1 slice of whole grain bread \n - 1 ripe avocado \n - Salt, to taste \n - Pepper, to taste \n - Optional: cherry tomatoes, radishes, or lemon juice \n \n *Instructions:* \n 1. Toast the bread until golden brown. \n 2. Mash the avocado in a bowl and season with salt and pepper. \n 3. Spread the mashed avocado over the toasted bread. \n 4. Top with cherry tomatoes, radishes, or a squeeze of lemon if desired. \n \n\n**Lunch:** \n- **Chickpea Salad** \n *Ingredients:* \n - 1 can chickpeas, rinsed and drained \n - 1 cucumber, chopped \n - 1 bell pepper, chopped \n - 1/4 red onion, chopped \n - 2 tablespoons olive oil \n - Juice of 1 lemon \n - Salt and pepper, to taste \n - Fresh parsley, chopped \n \n *Instructions:* \n 1. In a large bowl, combine chickpeas, cucumber, bell pepper, and red onion. \n 2. In a small bowl, whisk together olive oil, lemon juice, salt, and pepper. \n 3. Pour the dressing over the salad and toss to combine. \n 4. Garnish with fresh parsley. \n \n\n**Dinner:** \n- **Vegetarian Stir-Fry** \n *Ingredients:* \n - 1 cup broccoli florets \n - 1 cup bell peppers, sliced \n - 1 cup carrots, sliced \n - 1 cup tofu, cubed \n - 2 tablespoons soy sauce \n - 1 tablespoon sesame oil \n - 2 cloves garlic, minced \n - Cooked rice or quinoa, to serve \n \n *Instructions:* \n 1. Heat sesame oil in a large pan over medium heat. \n 2. Add garlic and tofu, and stir-fry until golden. \n 3. Add broccoli, bell peppers, and carrots. Stir-fry until veggies are tender. \n 4. Add soy sauce and stir to combine. \n 5. Serve hot on a bed of rice or quinoa.\n </memory><memory created_at=\"2024-12-10 19:21:53\">\n Daily Meal Plan for December 10, 2024:\n\n**Breakfast:** \n- **Vegetarian Avocado Toast** \n *Ingredients:* \n - 1 slice of whole grain bread \n - 1 ripe avocado \n - Salt, to taste \n - Pepper, to taste \n - Optional: cherry tomatoes, radishes, or lemon juice \n \n *Instructions:* \n 1. Toast the bread until golden brown. \n 2. Mash the avocado in a bowl and season with salt and pepper. \n 3. Spread the mashed avocado over the toasted bread. \n 4. Top with cherry tomatoes, radishes, or a squeeze of lemon if desired. \n \n\n**Lunch:** \n- **Chickpea Salad** \n *Ingredients:* \n - 1 can chickpeas, rinsed and drained \n - 1 cucumber, chopped \n - 1 bell pepper, chopped \n - 1/4 red onion, chopped \n - 2 tablespoons olive oil \n - Juice of 1 lemon \n - Salt and pepper, to taste \n - Fresh parsley, chopped \n \n *Instructions:* \n 1. In a large bowl, combine chickpeas, cucumber, bell pepper, and red onion. \n 2. In a small bowl, whisk together olive oil, lemon juice, salt, and pepper. \n 3. Pour the dressing over the salad and toss to combine. \n 4. Garnish with fresh parsley. \n \n\n**Dinner:** \n- **Vegetarian Stir-Fry** \n *Ingredients:* \n - 1 cup broccoli florets \n - 1 cup bell peppers, sliced \n - 1 cup carrots, sliced \n - 1 cup tofu, cubed \n - 2 tablespoons soy sauce \n - 1 tablespoon sesame oil \n - 2 cloves garlic, minced \n - Cooked rice or quinoa, to serve \n \n *Instructions:* \n 1. Heat sesame oil in a large pan over medium heat. \n 2. Add garlic and tofu, and stir-fry until golden. \n 3. Add broccoli, bell peppers, and carrots. Stir-fry until veggies are tender. \n 4. Add soy sauce and stir to combine. \n 5. Serve hot on a bed of rice or quinoa.\n </memory><memory created_at=\"2024-12-12 06:06:24\">\n Email: daniele@toolhouse.ai\nMeal preference: vegetarian\n </memory><memory created_at=\"2024-12-12 16:09:41\">\n Email: daniele@toolhouse.ai\nMeal preferences: vegetarian or vegan\n </memory><memory created_at=\"2024-12-13 17:14:42\">\n Email: orlando@toolhouse.ai\nNews Preferences: Artificial Intelligence and Robotics\n </memory><memory created_at=\"2024-12-13 22:12:07\">\n Email: hello@toolhouse.ai\nMeal Preferences: Keto, high performance for weightlifting\n </memory><memory created_at=\"2024-12-13 22:26:26\">\n Email: hello@toolhouse.ai\nMeal preference: Ketogenic\n </memory><memory created_at=\"2024-12-14 01:27:48\">\n Email: daniele@toolhouse.ai\nMeal Preferences: vegetarian\n </memory><memory created_at=\"2024-12-14 01:31:43\">\n User's email: hello@toolhouse.ai\n </memory><memory created_at=\"2024-12-14 01:31:45\">\n User's valid X account: @toolhouseai\n </memory><memory created_at=\"2025-01-14 23:52:21\">\n Pet fact shared on December 14, 2023: Capybara fact - World's largest rodent weighing up to 140 pounds. Known for their friendly nature and being called \"nature's ottoman\".\n </memory><memory created_at=\"2025-01-14 23:53:26\">\n Pet fact about capybaras (world's largest rodent) shared with simone@toolhouse.ai\n </memory>",
"toolName": "memory_fetch",
"toolCallId": "toolu_01L1KXeHYNKhSxqAtLMDdC57"
}
]
},
{
"role": "assistant",
"content": [
{
"text": "I see your email is hello@toolhouse.ai, and I found one previous pet fact about capybaras. Let me search for an interesting new pet fact:",
"type": "text"
},
{
"args": {
"query": "interesting unique pet facts animals",
"num_results": 3
},
"type": "tool-call",
"toolName": "web_search",
"toolCallId": "toolu_01SGidsQaEsE5jTj2cM8Stxx"
}
]
},
{
"role": "tool",
"content": [
{
"type": "tool-result",
"result": "Position: 1\nTitle: Fun Facts\nLink: https://animalmedical.org/fun-facts\nSnippet: Animal Facts · Fleas can jump 350 times its body length. · Hummingbirds are the only birds that can fly backwards. · Crocodiles cannot stick their tongue out.\nSource: animalmedical.org\n\nPosition: 2\nTitle: Pet Fun Facts | Interesting Facts & Trivia on Dogs, Cats & ...\nLink: https://www.petinsurance.com/healthzone/ownership-adoption/pet-ownership/pet-owner-topics/fun-facts-about-pets/\nSnippet: Fun Facts About Birds and Exotic Pets. 68parrot. To survive, every bird must eat at least half its own weight in food each day. A bird's heart beats ...\nSource: Nationwide Pet Insurance",
"toolName": "web_search",
"toolCallId": "toolu_01SGidsQaEsE5jTj2cM8Stxx"
}
]
},
{
"role": "assistant",
"content": [
{
"text": "I'll create a fascinating pet fact about birds! Let me send this via email with a nice format:",
"type": "text"
},
{
"args": {
"to": "hello@toolhouse.ai",
"content": "<!DOCTYPE html>\n<html>\n<body style=\"font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f5f5f5;\">\n <div style=\"background-color: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);\">\n <h1 style=\"color: #2c3e50; text-align: center;\">🐦 Amazing Bird Fact of the Day! 🐦</h1>\n \n <div style=\"border-left: 4px solid #3498db; padding-left: 15px; margin: 20px 0;\">\n <p style=\"font-size: 16px; line-height: 1.6; color: #34495e;\">\n Did you know that a bird's heart is truly remarkable? Birds must maintain an incredibly active metabolism to survive, and their hearts work extra hard to support this. In fact, every bird needs to eat at least half its own weight in food each day just to keep up with their energy needs!\n </p>\n <p style=\"font-size: 16px; line-height: 1.6; color: #34495e;\">\n This is because birds have extremely fast-beating hearts and high metabolic rates to support their flying abilities and maintain their body temperature. Their hearts can beat several hundred times per minute during normal activity, and even faster during flight!\n </p>\n </div>\n \n <p style=\"font-size: 12px; color: #7f8c8d; text-align: center; margin-top: 20px;\">\n Brought to you by your friendly AI assistant, powered by Toolhouse 🌟\n </p>\n </div>\n</body>\n</html>",
"subject": "🐦 Your Daily Pet Fact: Amazing Bird Hearts!"
},
"type": "tool-call",
"toolName": "send_email",
"toolCallId": "toolu_01BKc5XUnZWwN31u5677QhQS"
}
]
},
{
"role": "tool",
"content": [
{
"type": "tool-result",
"result": "The mail has been sent.",
"toolName": "send_email",
"toolCallId": "toolu_01BKc5XUnZWwN31u5677QhQS"
}
]
},
{
"role": "assistant",
"content": [
{
"text": "Now, let me store this fact and your email in memory:",
"type": "text"
},
{
"args": {
"memory": "Pet fact shared: Birds must eat at least half their body weight in food daily to maintain their high metabolism and heart rate. Email sent to: hello@toolhouse.ai"
},
"type": "tool-call",
"toolName": "memory_store",
"toolCallId": "toolu_01Q1oxPbry5eTgwsTv1uBwUx"
}
]
},
{
"role": "tool",
"content": [
{
"type": "tool-result",
"result": "User memory has been stored",
"toolName": "memory_store",
"toolCallId": "toolu_01Q1oxPbry5eTgwsTv1uBwUx"
}
]
},
{
"role": "assistant",
"content": [
{
"text": "I've completed all the steps:\n1. Checked memory for past pet facts (found one about capybaras)\n2. Generated a new fact about birds' amazing metabolism and heart rates\n3. Sent the email to your address (hello@toolhouse.ai) with a nicely formatted HTML design\n4. Stored the new fact and your email in memory\n\nThe email has been sent to your inbox! Let me know if you'd like another pet fact or if there's anything else I can help you with! 🐦",
"type": "text"
}
]
}
],
"created_at": "2025-01-15T01:46:23.568338",
"updated_at": "2025-01-15T01:46:59.270078",
"bundle": "default",
"toolhouse_id": "default"
}
}
{
"data": {
"id": "bcb7e865-9e6c-xxxx-xxxx-c0110fdf5c2e",
"chat_id": "a3a26d33-6f4d-4490-a56f-e17f867ba451",
"status": "completed",
"results": [
{
"error": "You ran out of Toolhouse Execs. Please top up your balance at https://app.toolohuse.ai/billing."
},
],
"created_at": "2025-01-15T01:46:23.568338",
"updated_at": "2025-01-15T01:46:59.270078",
"bundle": "default",
"toolhouse_id": "default"
}
}
If an Agent Run completed successfully, you can add further messages to it. This will cause the Agent Run to be queued and start again. The Agent Run will keep its context and chat history.
import requests
import json
def send_request(toolhouse_api_key, run_id):
url = f"https://api.toolhouse.ai/v1/agent-runs/{run_id}"
headers = {
"Authorization": f"Bearer {toolhouse_api_key}",
"Content-Type": "application/json"
}
payload = {
"message": "Perfect, thank you!"
}
response = requests.put(url, headers=headers, json=payload)
return response
# Example usage
if __name__ == "__main__":
toolhouse_api_key = "YOUR_TOOLHOUSE_API_KEY"
run_id = "YOUR_RUN_ID"
response = send_request(toolhouse_api_key, run_id)
# Check if the request was successful
if response.status_code == 200:
print("Request successful. Response:")
print(response.json())
else:
print("Request failed with status code", response.status_code)
async function continueAgentRun(toolhouseApiKey, runId) {
try {
const url = 'https://api.toolhouse.ai/v1/agent-runs/${runId}';
const headers = {
'Authorization': `Bearer ${toolhouseApiKey}`,
'Content-Type': 'application/json',
};
const body = JSON.stringify({
'message': 'Perfect, thank you!',
});
const response = await fetch(url, {
method: 'PUT',
headers: headers,
body: body,
});
if (response.ok) {
const data = await response.json();
console.log(data);
} else {
console.error('Failed to retrieve data:', response.status, response.statusText);
}
} catch (error) {
console.error('An error occurred:', error);
}
}
// Example usage
const toolhouseApiKey = 'YOUR_TOOLHOUSE_API_KEY';
const runId = 'your_run_id';
await continueAgentRun(toolhouseApiKey, runId);
curl -XPUT "https://api.toolhouse.ai/v1/agent-runs/$YOUR_RUN_ID" \
-H "Authorization: Bearer $YOUR_TOOLHOUSE_API_KEY" \
--json '{
"message": "Perfect, thank you!"
}'