Agents 0.0.2
Edge AI Agents SDK
Loading...
Searching...
No Matches
simple_agent.cpp

Simple Agent Example.

Simple Agent Example

Version
0.1
Date
2025-07-20
#include <agents-cpp/agent_context.h>
#include <agents-cpp/agents/autonomous_agent.h>
#include <agents-cpp/config_loader.h>
#include <agents-cpp/coroutine_utils.h>
#include <agents-cpp/llm_interface.h>
#include <agents-cpp/logger.h>
#include <agents-cpp/tools/tool_registry.h>
#include <agents-cpp/types.h>
#include <iostream>
#include <chrono>
#include <string>
#include <thread>
using namespace agents;
// Simple callback to print agent steps
void stepCallback(const AutonomousAgent::Step& step) {
Logger::info("Step: {}", step.description);
Logger::info("Status: {}", step.status);
if (step.success) {
Logger::info("Result: {}", step.result.dump(2));
} else {
Logger::error("Failed!");
}
Logger::info("--------------------------------------");
}
// Simple callback for human-in-the-loop
bool humanApproval(const String& message, const JsonObject& context) {
Logger::info("\n{}", message);
Logger::info("Context: {}", context.dump(2));
Logger::info("Approve this step? (y/n): ");
char response;
std::cin >> response;
return (response == 'y' || response == 'Y');
}
// Main agent task
Task<int> runAgentApp(int argc, char* argv[]) {
// Initialize the logger
// Get API key from .env, environment, or command line
String api_key;
auto& config = ConfigLoader::getInstance();
// Try to get API key from config or environment
api_key = config.get("OPENAI_API_KEY", "");
// If not found, check command line
if (api_key.empty() && argc > 1) {
api_key = argv[1];
}
// Still not found, show error and exit
if (api_key.empty()) {
Logger::error("API key not found. Please:");
Logger::error("1. Create a .env file with OPENAI_API_KEY=your_key, or");
Logger::error("2. Set the OPENAI_API_KEY environment variable, or");
Logger::error("3. Provide an API key as a command line argument");
co_return 1;
}
// Create the context
auto context = std::make_shared<AgentContext>();
// Configure the LLM
auto llm = createLLM("openai", api_key, "gpt-4o");
// Configure LLM options
LLMOptions options;
options.temperature = (0.7);
llm->setOptions(options);
context->setLLM(llm);
// Register some tools
context->registerTool(tools::createWebSearchTool());
context->registerTool(tools::createWikipediaTool());
// Create the agent
AutonomousAgent agent(context);
// Configure the agent
agent.setSystemPrompt(
"You are a research assistant that helps users find information and answer questions. "
"Use the tools available to you to gather information and provide comprehensive answers. "
"When searching for information, try multiple queries if necessary."
);
// Set the planning strategy
agent.setPlanningStrategy(AutonomousAgent::PlanningStrategy::REACT);
// Set up options
AutonomousAgent::Options agent_options;
agent_options.max_iterations = 15;
agent_options.human_feedback_enabled = true;
agent_options.human_in_the_loop = humanApproval;
agent.setOptions(agent_options);
// Set up callbacks
agent.setStepCallback(stepCallback);
agent.setStatusCallback([](const String& status) {
Logger::info("Agent status: {}", status);
});
// Initialize the agent
agent.init();
// Get user input
Logger::info("Enter a question or task for the agent (or 'exit' to quit):");
String user_input;
while (true) {
Logger::info("> ");
std::getline(std::cin, user_input);
if (user_input == "exit") {
break;
}
if (user_input.empty()) {
continue;
}
try {
// Run the agent with coroutines
JsonObject result = co_await agent.run(user_input);
// Display the final result
Logger::info("\nFinal Result:\n{}", result["answer"].get<String>());
} catch (const std::exception& e) {
Logger::error("Error: {}", e.what());
}
}
co_return 0;
}
// Entry point
int main(int argc, char* argv[]) {
// Use blockingWait to execute the coroutine
return blockingWait(runAgentApp(argc, argv));
}
static ConfigLoader & getInstance()
Get the singleton instance of ConfigLoader.
static void error(fmt::format_string< Args... > fmt, Args &&... args)
Log a message at error level.
Definition logger.h:124
static void init(Level level=Level::INFO)
Initialize the logger.
static void info(fmt::format_string< Args... > fmt, Args &&... args)
Log a message at info level.
Definition logger.h:104
An agent that operates autonomously to complete a task.
Definition autonomous_agent.h:28
@ REACT
Reasoning and acting.
Definition autonomous_agent.h:75
@ INFO
Info logging level.
Definition logger.h:40
Provide a future-based fallback for Task.
Definition coroutine_utils.h:115
std::shared_ptr< Tool > createWikipediaTool()
Creates a tool for retrieving information from Wikipedia.
std::shared_ptr< Tool > createWebSearchTool()
Creates a tool for performing web searches.
Framework Namespace.
Definition agent.h:18
Options for LLM API calls.
Definition llm_interface.h:25
double temperature
The temperature of the LLM.
Definition llm_interface.h:29
Agent execution options.
Definition agent.h:61
bool human_feedback_enabled
Whether human feedback is enabled.
Definition agent.h:75
int max_iterations
The maximum number of iterations.
Definition agent.h:65
std::function< bool(const String &, const JsonObject &)> human_in_the_loop
The human in the loop function.
Definition agent.h:80
Step in the agent's execution.
Definition autonomous_agent.h:33
JsonObject result
The result of the step.
Definition autonomous_agent.h:45
bool success
Whether the step was successful.
Definition autonomous_agent.h:49
String description
The description of the step.
Definition autonomous_agent.h:37
String status
The status of the step.
Definition autonomous_agent.h:41