Create and manage agents (Deprecated)

This documentation is deprecated. Please use the new workflow documentation instead.

Alfa agents are the core building blocks of your AI-powered workflow. In this guide, we’ll walk through the complete lifecycle of an agent using our API - from creation to retrieving results.

Creating your first agent

Creating an agent is simple - you just need to provide a clear prompt that describes what you want the agent to do.

1import requests
2
3BASE_URL = "https://alfa.boosted.ai/client"
4API_KEY = "YOUR_API_KEY_HERE"
5
6headers = {"x-api-key": API_KEY, "Content-Type": "application/json"}
7
8def create_agent(prompt):
9 """Create a new agent with the specified prompt."""
10 url = f"{BASE_URL}/agent/create-agent"
11 payload = {"prompt": prompt}
12
13 response = requests.post(url, headers=headers, json=payload)
14
15 if response.status_code == 201:
16 data = response.json()
17 agent_id = data.get("agent_id")
18 print(f"Success! Agent created with ID: {agent_id}")
19 return agent_id
20 else:
21 print(f"Error: {response.status_code}, {response.text}")
22 return None
23
24# Create an agent to analyze Tesla's stock performance
25agent_id = create_agent("What was TSLA's close price on Feb 1, 2023 and how does it compare to recent performance?")

For complex analyses, you can include placeholders like {doc} in your prompt to reference custom documents. See our Custom Documents guide for details.

Example: Creating an agent for comprehensive price target analysis

1

Define your analysis needs

Determine what specific market data you want to analyze

2

Formulate your prompt

Create a clear prompt that specifies exactly what you need:

1comprehensive_prompt = """
2Show a line graph of Target Price Consensus Mean over the past year for Apple. Then show current
3Target Price Consensus High and Target Price Consensus Low in a table. Finally, in a new section,
4get all news developments for the target company, then get the articles associated with those developments.
5Pass the articles to the text to table tool and extract all the analysts that have given ratings and their
6price targets, using the columns research firm, price target, date, and buy/sell recommendation.
7"""
3

Create the agent

1# Create price target analysis agent
2analysis_agent_id = create_agent(comprehensive_prompt)
3
4print(f"Your price target analysis agent is being created with ID: {analysis_agent_id}")

Monitoring agent status

After creating an agent, it will start processing your request in the background. You can check its status to know when it’s done.

1import time
2
3def get_agent_status(agent_id):
4 """Check if an agent has completed its processing."""
5 url = f"{BASE_URL}/agent/status?agent_id={agent_id}"
6
7 response = requests.get(url, headers=headers)
8
9 if response.status_code == 200:
10 data = response.json()
11 status = data.get("status")
12 print(f"Agent status: {status}")
13 return status
14 else:
15 print(f"Error: {response.status_code}, {response.text}")
16 return None
17
18# Poll until the agent is done
19status = ""
20while status != "COMPLETE":
21 status = get_agent_status(agent_id)
22 if status in ["ERROR", "CANCELLED", "NO_RESULTS_FOUND"]:
23 print(f"Agent encountered an issue: {status}")
24 break
25 if status != "COMPLETE":
26 print("Agent still working... waiting 10 seconds")
27 time.sleep(10)

The agent can be in one of the following states:

  • NOT_STARTED: The agent has been created but hasn’t begun processing
  • RUNNING: The agent is actively working on your request
  • COMPLETE: The agent has finished successfully
  • ERROR: The agent encountered an error during processing
  • CANCELLED: The processing was stopped before completion
  • NO_RESULTS_FOUND: The agent completed but couldn’t find relevant results

Retrieving agent output

Once your agent has completed its work, you can retrieve the output.

1def get_agent_output(agent_id):
2 """Retrieve the results from a completed agent."""
3 url = f"{BASE_URL}/get-agent-output/{agent_id}"
4
5 response = requests.get(url, headers=headers)
6
7 if response.status_code == 200:
8 return response.json()
9 else:
10 print(f"Error: {response.status_code}, {response.text}")
11 return None
12
13# Get the agent's findings
14output = get_agent_output(agent_id)
15
16# Process the outputs
17if output and "outputs" in output:
18 for item in output["outputs"]:
19 output_type = item["output"]["output_type"]
20
21 if output_type == "text":
22 print("Text output:", item["output"]["val"])
23 elif output_type == "table":
24 print("Table output with columns:", [col["name"] for col in item["output"]["columns"]])
25 elif output_type == "graph":
26 print(f"Graph output: {item['output']['title']} ({item['output']['graph']['graph_type']} graph)")

Agent outputs can be of different types:

  • text: Plain text analysis and explanations
  • table: Structured data in tabular format
  • graph: Visual representation of data as a line, bar, or pie chart

Example: Processing different output types

1

Get the agent output

First, fetch the agent’s completed analysis

2

Process by output type

Handle different output formats appropriately:

1# Get the comprehensive analysis results
2results = get_agent_output(agent_id)
3
4if results and "outputs" in results:
5 for i, item in enumerate(results["outputs"]):
6 output_data = item["output"]
7 output_type = output_data["output_type"]
8
9 print(f"\n--- Output {i+1} ({output_type}) ---")
10
11 if output_type == "text":
12 # Save the text analysis to a file
13 with open(f"analysis_{i+1}.txt", "w") as f:
14 f.write(output_data["val"])
15 print(f"Text analysis saved to analysis_{i+1}.txt")
16
17 elif output_type == "table":
18 # Export the table to CSV
19 import csv
20
21 columns = [col["name"] for col in output_data["columns"]]
22 with open(f"table_{i+1}.csv", "w", newline="") as f:
23 writer = csv.writer(f)
24 writer.writerow(columns)
25 writer.writerows(output_data["rows"])
26 print(f"Table data exported to table_{i+1}.csv")
27
28 elif output_type == "graph":
29 # Just print info about the graph (in a real app, you might render it)
30 graph_type = output_data["graph"]["graph_type"]
31 title = output_data["title"]
32 print(f"Graph: {title} ({graph_type})")

Managing your agents

Getting a specific agent

To retrieve basic details about a specific agent:

1def get_agent(agent_id):
2 """Get metadata for a specific agent."""
3 url = f"{BASE_URL}/agent/get-agent/{agent_id}"
4
5 response = requests.get(url, headers=headers)
6
7 if response.status_code == 200:
8 data = response.json()
9 print(f"Agent Name: {data.get('agent_name')}")
10 print(f"Created: {data.get('created_at')}")
11 print(f"Description: {data.get('agent_description')}")
12 return data
13 else:
14 print(f"Error: {response.status_code}, {response.text}")
15 return None
16
17# Get details for a specific agent
18agent_details = get_agent(agent_id)

Example: Finding an agent by ID

1

Retrieve agent details

Get information about a specific agent you’ve created:

1# Look up an agent by its ID
2agent_id = "ff39b720-8179-4e7d-9f4c-b5e9a35fb8d2"
3agent_info = get_agent(agent_id)
4
5if agent_info:
6 print(f"\nAgent: {agent_info['agent_name']}")
7 print(f"Created: {agent_info['created_at']}")
8 print(f"Description: {agent_info.get('agent_description', 'No description')}")
9else:
10 print("Agent not found or access denied")

Viewing all your agents

To get a list of all agents you’ve created and their basic details:

1def get_all_agents():
2 """List all available agents."""
3 url = f"{BASE_URL}/agent/get-all-agents"
4
5 response = requests.get(url, headers=headers)
6
7 if response.status_code == 200:
8 data = response.json()
9 return data.get("agents", [])
10 else:
11 print(f"Error: {response.status_code}, {response.text}")
12 return []
13
14# Display all your agents
15agents = get_all_agents()
16for agent in agents:
17 print(f"ID: {agent['agent_id']}")
18 print(f"Name: {agent['agent_name']}")
19 print(f"Created: {agent['created_at']}")
20 print("---")

Example: Finding agents by pattern matching

1

Get all agents

First, retrieve the list of all your agents

2

Filter by criteria

Search for agents that match certain patterns:

1# Get all available agents
2all_agents = get_all_agents()
3
4# Filter agents by name pattern
5earnings_agents = [a for a in all_agents if "earnings" in a["agent_name"].lower()]
6recent_agents = [a for a in all_agents if a["created_at"] > "2023-10-01"]
7
8# Display filtered results
9print(f"\nFound {len(earnings_agents)} earnings-related agents:")
10for agent in earnings_agents:
11 print(f"- {agent['agent_name']} (ID: {agent['agent_id']})")
12
13print(f"\nFound {len(recent_agents)} agents created since October 2023:")
14for agent in recent_agents:
15 print(f"- {agent['agent_name']} (created: {agent['created_at']})")

Next steps

Now that you understand how to create and manage agents, you can:

For production systems, always implement proper error handling and consider using exponential backoff for status polling to avoid rate limiting.