-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtools.cpp
More file actions
287 lines (251 loc) · 9.34 KB
/
tools.cpp
File metadata and controls
287 lines (251 loc) · 9.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Copyright (c) 2025 Elias Bachaalany
// SPDX-License-Identifier: MIT
/// @file tools.cpp
/// @brief Custom tools example demonstrating tool registration and invocation
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <copilot/copilot.hpp>
#include <ctime>
#include <iostream>
#include <mutex>
#include <sstream>
#include <string>
// Define custom tool handlers
/// Calculate tool - performs basic arithmetic
copilot::ToolResultObject calculate_handler(const copilot::ToolInvocation& invocation)
{
copilot::ToolResultObject result;
try
{
auto& args = invocation.arguments.value();
std::string operation = args["operation"].get<std::string>();
double a = args["a"].get<double>();
double b = args["b"].get<double>();
double answer;
if (operation == "add")
{
answer = a + b;
}
else if (operation == "subtract")
{
answer = a - b;
}
else if (operation == "multiply")
{
answer = a * b;
}
else if (operation == "divide")
{
if (b == 0)
{
result.result_type = copilot::ToolResultType::Failure;
result.error = "Division by zero";
result.text_result_for_llm = "Error: Cannot divide by zero";
return result;
}
answer = a / b;
}
else if (operation == "power")
{
answer = std::pow(a, b);
}
else
{
result.result_type = copilot::ToolResultType::Failure;
result.error = "Unknown operation: " + operation;
result.text_result_for_llm = "Error: Unknown operation '" + operation + "'";
return result;
}
std::ostringstream oss;
std::string op_symbol = (operation == "power") ? "^" : operation;
oss << a << " " << op_symbol << " " << b << " = " << answer;
result.text_result_for_llm = oss.str();
}
catch (const std::exception& e)
{
result.result_type = copilot::ToolResultType::Failure;
result.error = e.what();
result.text_result_for_llm = std::string("Error: ") + e.what();
}
return result;
}
/// Get current time tool
copilot::ToolResultObject get_time_handler(const copilot::ToolInvocation& invocation)
{
copilot::ToolResultObject result;
try
{
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
std::string time_str = std::ctime(&time_t);
// Remove trailing newline
if (!time_str.empty() && time_str.back() == '\n')
time_str.pop_back();
std::string timezone = "local";
if (invocation.arguments.has_value() && invocation.arguments->contains("timezone"))
timezone = (*invocation.arguments)["timezone"].get<std::string>();
std::ostringstream oss;
oss << "Current time (" << timezone << "): " << time_str;
result.text_result_for_llm = oss.str();
}
catch (const std::exception& e)
{
result.result_type = copilot::ToolResultType::Failure;
result.error = e.what();
result.text_result_for_llm = std::string("Error: ") + e.what();
}
return result;
}
/// Echo tool - simple echo for testing
copilot::ToolResultObject echo_handler(const copilot::ToolInvocation& invocation)
{
copilot::ToolResultObject result;
std::string message = "Hello from echo tool!";
if (invocation.arguments.has_value() && invocation.arguments->contains("message"))
message = (*invocation.arguments)["message"].get<std::string>();
result.text_result_for_llm = "Echo: " + message;
return result;
}
int main()
{
try
{
// Create client
copilot::ClientOptions options;
options.log_level = copilot::LogLevel::Info;
copilot::Client client(options);
std::cout << "Starting Copilot client...\n";
client.start().get();
// Define custom tools BEFORE creating the session
// (tools are sent to the server during session creation)
// Calculator tool
copilot::Tool calc_tool;
calc_tool.name = "calculate";
calc_tool.description =
"Perform basic arithmetic operations (add, subtract, multiply, divide, power)";
calc_tool.parameters_schema = copilot::json{
{"type", "object"},
{"properties",
{{"operation",
{{"type", "string"},
{"enum", {"add", "subtract", "multiply", "divide", "power"}},
{"description", "The arithmetic operation to perform"}}},
{"a", {{"type", "number"}, {"description", "First operand"}}},
{"b", {{"type", "number"}, {"description", "Second operand"}}}}},
{"required", {"operation", "a", "b"}}
};
calc_tool.handler = calculate_handler;
// Time tool
copilot::Tool time_tool;
time_tool.name = "get_current_time";
time_tool.description = "Get the current date and time";
time_tool.parameters_schema = copilot::json{
{"type", "object"},
{"properties",
{{"timezone",
{{"type", "string"}, {"description", "Timezone (optional, defaults to local)"}}}}}
};
time_tool.handler = get_time_handler;
// Echo tool
copilot::Tool echo_tool;
echo_tool.name = "echo";
echo_tool.description = "Echo back a message";
echo_tool.parameters_schema = copilot::json{
{"type", "object"},
{"properties", {{"message", {{"type", "string"}, {"description", "Message to echo"}}}}}
};
echo_tool.handler = echo_handler;
// Create session with custom tools
copilot::SessionConfig session_config;
session_config.tools = {calc_tool, time_tool, echo_tool};
auto session = client.create_session(session_config).get();
std::cout << "Session created: " << session->session_id() << "\n";
std::cout << "Registered 3 custom tools: calculate, get_current_time, echo\n\n";
// Synchronization
std::mutex mtx;
std::condition_variable cv;
std::atomic<bool> idle{false};
// Subscribe to events
auto subscription = session->on(
[&](const copilot::SessionEvent& event)
{
if (auto* msg = event.try_as<copilot::AssistantMessageData>())
{
std::cout << "\nAssistant: " << msg->content << "\n";
}
else if (auto* tool_start = event.try_as<copilot::ToolExecutionStartData>())
{
std::cout << "\n[Tool: " << tool_start->tool_name << "] Starting...\n";
if (tool_start->arguments)
std::cout << " Args: " << tool_start->arguments->dump() << "\n";
}
else if (auto* tool_complete = event.try_as<copilot::ToolExecutionCompleteData>())
{
std::cout << "[Tool: " << tool_complete->tool_call_id << "] ";
if (tool_complete->success)
{
std::cout << "Success\n";
if (tool_complete->result)
std::cout << " Result: " << tool_complete->result->content << "\n";
}
else
{
std::cout << "Failed\n";
if (tool_complete->error)
std::cout << " Error: " << tool_complete->error->message << "\n";
}
}
else if (auto* error = event.try_as<copilot::SessionErrorData>())
{
std::cerr << "Error: " << error->message << "\n";
}
else if (event.type == copilot::SessionEventType::SessionIdle)
{
std::lock_guard<std::mutex> lock(mtx);
idle = true;
cv.notify_one();
}
}
);
// Interactive loop
std::cout << "Try asking questions that require calculations or time!\n";
std::cout << "Examples:\n";
std::cout << " - What is 42 * 17?\n";
std::cout << " - What time is it?\n";
std::cout << " - Calculate 2^10\n";
std::cout << "\nType 'quit' to exit.\n\n> ";
std::string line;
while (std::getline(std::cin, line))
{
if (line == "quit" || line == "exit")
break;
if (line.empty())
{
std::cout << "> ";
continue;
}
idle = false;
copilot::MessageOptions msg_opts;
msg_opts.prompt = line;
session->send(msg_opts).get();
// Wait for idle
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [&idle]() { return idle.load(); });
}
std::cout << "\n> ";
}
// Cleanup
std::cout << "\nCleaning up...\n";
session->destroy().get();
client.stop().get();
return 0;
}
catch (const std::exception& e)
{
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
}