-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool-integration.ts
More file actions
245 lines (205 loc) · 9.21 KB
/
Copy pathtool-integration.ts
File metadata and controls
245 lines (205 loc) · 9.21 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
/**
* Tool Integration Example
*
* Demonstrates how to configure and use tools with the Harmony Protocol,
* including custom functions, browser tools, and Python execution.
*/
import {
Message,
Conversation,
Role,
Channel,
loadHarmonyEncoding,
createSystemContent,
createToolDescription,
createToolNamespace,
createBrowserToolNamespace,
createPythonToolNamespace,
createCommonFunctionTools,
createToolCalls,
ReasoningEffort
} from '../src/index.js';
async function main(): Promise<void> {
console.log('🛠️ Harmony Protocol - Tool Integration Example');
console.log('===============================================');
try {
// Step 1: Create custom function tools
console.log('\n🔧 Step 1: Creating custom function tools');
const calculatorTool = createToolDescription(
'calculate',
'Performs mathematical calculations',
{
type: 'object',
properties: {
expression: { type: 'string', description: 'Mathematical expression to evaluate' },
precision: { type: 'number', description: 'Number of decimal places' }
},
required: ['expression']
}
);
const weatherTool = createToolDescription(
'get_weather',
'Gets current weather for a location',
{
type: 'object',
properties: {
location: { type: 'string', description: 'City name or coordinates' },
units: { type: 'string', enum: ['celsius', 'fahrenheit'], description: 'Temperature units' }
},
required: ['location']
}
);
const customFunctionNamespace = createToolNamespace(
'functions',
'Custom mathematical and utility functions',
[calculatorTool, weatherTool]
);
console.log('✓ Created custom function tools:');
console.log(` - ${calculatorTool.name}: ${calculatorTool.description}`);
console.log(` - ${weatherTool.name}: ${weatherTool.description}`);
// Step 2: Create system content with multiple tool namespaces
console.log('\n📋 Step 2: Configuring system with multiple tool types');
const systemContent = createSystemContent()
.withIdentity('Advanced Assistant with Tool Access')
.withRequiredChannels(['analysis', 'final'])
.withReasoningEffort(ReasoningEffort.HIGH)
.withBrowserTool()
.withPythonTool()
.withTools(customFunctionNamespace)
.withCommonFunctionTools()
.build();
const systemMessage = Message.system(systemContent);
console.log('✓ Created system message with:');
console.log(' - Browser tools enabled');
console.log(' - Python execution enabled');
console.log(' - Custom function namespace');
console.log(' - Common utility functions');
// Step 3: Create a conversation with tool usage
console.log('\n💬 Step 3: Creating conversation with tool requests');
const conversation = new Conversation([
systemMessage,
Message.user('I need to solve a complex calculation: (15 + 25) * 0.75, and then search for information about the mathematical constant pi. Can you help?'),
]);
console.log('✓ Created conversation requesting calculation and web search');
// Step 4: Demonstrate encoding with tools
console.log('\n🎨 Step 4: Encoding conversation with tool support');
const encoding = loadHarmonyEncoding('o200k_base');
const tokens = encoding.renderConversationForCompletion(conversation, Role.ASSISTANT);
console.log(`✓ Encoded conversation to ${tokens.length} tokens`);
// Decode to show the formatted system content
const decodedText = encoding.decode(tokens);
console.log('\n📄 Formatted system content (excerpt):');
const lines = decodedText.split('\n');
const systemContentLines = lines.slice(0, 20); // Show first 20 lines
systemContentLines.forEach((line, i) => {
console.log(` ${i + 1}: ${line}`);
});
if (lines.length > 20) {
console.log(` ... and ${lines.length - 20} more lines`);
}
// Step 5: Simulate assistant response with tool calls
console.log('\n🤖 Step 5: Simulating assistant response with tool calls');
const toolCalls = createToolCalls()
.addCalculation('calc_1', '(15 + 25) * 0.75')
.addSearch('search_1', 'mathematical constant pi definition history', 5)
.build();
// Create assistant messages demonstrating tool usage workflow
const analysisMessage = Message.assistant(
'I need to solve this calculation and search for information about pi. Let me break this down:'
).withChannel(Channel.ANALYSIS);
// Simulate tool call message (this would typically be generated by the model)
const toolCallMessage = Message.assistant(
JSON.stringify({ tool_calls: toolCalls })
).withChannel(Channel.FINAL);
// Simulate tool results
const calculationResult = Message.tool(
JSON.stringify({ result: 30, expression: '(15 + 25) * 0.75 = 30' }),
'calc_1'
);
const searchResult = Message.tool(
JSON.stringify({
results: [
{ title: 'Pi - Wikipedia', snippet: 'Pi is a mathematical constant that is the ratio of a circle\'s circumference to its diameter.' },
{ title: 'History of Pi', snippet: 'The ancient civilizations knew pi as early as 2000 BC...' }
]
}),
'search_1'
);
const finalResponse = Message.assistant(
'Perfect! The calculation (15 + 25) * 0.75 equals 30. And I found comprehensive information about pi - it\'s the famous mathematical constant representing the ratio of a circle\'s circumference to its diameter, approximately 3.14159. The concept has been known since ancient civilizations around 2000 BC.'
).withChannel(Channel.FINAL);
// Add all messages to conversation
conversation
.addMessage(analysisMessage)
.addMessage(toolCallMessage)
.addMessage(calculationResult)
.addMessage(searchResult)
.addMessage(finalResponse);
console.log(`✓ Extended conversation with ${conversation.length()} messages including tool calls and results`);
// Step 6: Parse and analyze the complete conversation
console.log('\n📊 Step 6: Analyzing complete conversation with tools');
const stats = conversation.getStats();
console.log('✓ Conversation statistics:');
console.log(` Total messages: ${stats.totalMessages}`);
console.log(` Assistant messages: ${stats.messagesByRole[Role.ASSISTANT]}`);
console.log(` Tool messages: ${stats.messagesByRole[Role.TOOL]}`);
console.log(` Analysis channel: ${stats.messagesByChannel[Channel.ANALYSIS]}`);
console.log(` Final channel: ${stats.messagesByChannel[Channel.FINAL]}`);
// Step 7: Demonstrate tool validation
console.log('\n✅ Step 7: Tool validation');
const browserNamespace = createBrowserToolNamespace();
const pythonNamespace = createPythonToolNamespace();
console.log('✓ Available tool namespaces:');
console.log(` Browser tools: ${browserNamespace.tools.length} tools`);
browserNamespace.tools.forEach(tool => {
console.log(` - ${tool.name}: ${tool.description}`);
});
console.log(` Python tools: ${pythonNamespace.tools.length} tools`);
pythonNamespace.tools.forEach(tool => {
console.log(` - ${tool.name}: ${tool.description}`);
});
// Step 8: Advanced tool configuration example
console.log('\n🔬 Step 8: Advanced tool configuration');
const advancedTools = [
createToolDescription('database_query', 'Execute SQL queries on the database', {
type: 'object',
properties: {
query: { type: 'string', description: 'SQL query to execute' },
timeout: { type: 'number', description: 'Query timeout in seconds', default: 30 }
},
required: ['query']
}),
createToolDescription('send_email', 'Send an email message', {
type: 'object',
properties: {
to: { type: 'string', format: 'email', description: 'Recipient email address' },
subject: { type: 'string', description: 'Email subject' },
body: { type: 'string', description: 'Email body content' },
priority: { type: 'string', enum: ['low', 'normal', 'high'], default: 'normal' }
},
required: ['to', 'subject', 'body']
})
];
const advancedNamespace = createToolNamespace(
'enterprise',
'Enterprise integration tools',
advancedTools
);
console.log('✓ Created advanced tool namespace with:');
advancedNamespace.tools.forEach(tool => {
console.log(` - ${tool.name}: ${tool.description}`);
});
console.log('\n🎉 Tool integration example completed successfully!');
console.log('\n💡 Best practices for tool integration:');
console.log(' 1. Group related tools into logical namespaces');
console.log(' 2. Provide comprehensive parameter schemas with descriptions');
console.log(' 3. Use analysis channel for tool planning and commentary channel for explanations');
console.log(' 4. Handle tool errors gracefully in your application');
console.log(' 5. Validate tool calls before execution');
console.log(' 6. Log tool usage for debugging and analytics');
} catch (error) {
console.error('❌ Tool integration example failed:', error);
}
}
// Run the example
main().catch(console.error);