AGofficial's picture
Upload 4 files
e0fb8cc verified
// Tools definition and management
function getSeason(date) {
const month = date.getMonth(); // 0-11
if (month >= 2 && month <= 4) return 'Spring'; // Mar, Apr, May
if (month >= 5 && month <= 7) return 'Summer'; // Jun, Jul, Aug
if (month >= 8 && month <= 10) return 'Fall'; // Sep, Oct, Nov
return 'Winter'; // Dec, Jan, Feb
}
const tools = {
get_weather: {
func: (city) => {
const now = new Date();
const season = getSeason(now);
let weather, temp;
switch (season) {
case 'Spring':
weather = 'mild and rainy';
temp = '60°F';
break;
case 'Summer':
weather = 'sunny';
temp = '85°F';
break;
case 'Fall':
weather = 'cool and windy';
temp = '65°F';
break;
case 'Winter':
weather = 'cold and snowy';
temp = '30°F';
break;
}
return `The weather in ${city} is ${weather} with ${temp}. The current season is ${season}.`;
},
description: "Get the current weather for a specific city, which varies by season."
},
get_time: {
func: () => `The current time is ${new Date().toLocaleTimeString()}`,
description: "Get the current time."
},
get_date: {
func: () => {
const now = new Date();
const season = getSeason(now);
return `Today's date is ${now.toLocaleDateString()}. The current season is ${season}.`;
},
description: "Get the current date and season."
},
get_user_name: {
func: () => "User",
description: "Get the user's name."
},
calculate: {
func: (expression) => {
try {
const result = Function('"use strict"; return (' + expression + ')')();
return `${expression} = ${result}`;
} catch (e) {
return `Error calculating "${expression}": ${e.message}`;
}
},
description: "Calculate mathematical expressions (e.g., 2+2, Math.sqrt(16), etc.)"
},
generate_random: {
func: (min = 1, max = 100) => {
const minNum = parseInt(min);
const maxNum = parseInt(max);
const random = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;
return `Random number between ${minNum} and ${maxNum}: ${random}`;
},
description: "Generate a random number between min and max values."
},
encode_base64: {
func: (text) => {
try {
return `Base64 encoded: ${btoa(text)}`;
} catch (e) {
return `Error encoding: ${e.message}`;
}
},
description: "Encode text to Base64."
},
decode_base64: {
func: (base64) => {
try {
return `Decoded text: ${atob(base64)}`;
} catch (e) {
return `Error decoding: ${e.message}`;
}
},
description: "Decode Base64 to text."
},
count_words: {
func: (text) => {
const words = text.trim().split(/\s+/).filter(word => word.length > 0);
return `Word count: ${words.length} words, ${text.length} characters`;
},
description: "Count words and characters in text."
},
reverse_text: {
func: (text) => `Reversed text: ${text.split('').reverse().join('')}`,
description: "Reverse the given text."
},
generate_uuid: {
func: () => {
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0;
const v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
return `Generated UUID: ${uuid}`;
},
description: "Generate a random UUID."
},
hash_text: {
func: async (text) => {
let hash = 0;
for (let i = 0; i < text.length; i++) {
const char = text.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return `Simple hash of "${text}": ${Math.abs(hash)}`;
},
description: "Generate a simple hash of the given text."
},
format_json: {
func: (jsonString) => {
try {
const parsed = JSON.parse(jsonString);
return `Formatted JSON:\n${JSON.stringify(parsed, null, 2)}`;
} catch (e) {
return `Error parsing JSON: ${e.message}`;
}
},
description: "Format and validate JSON strings."
},
get_timestamp: {
func: () => `Current timestamp: ${Date.now()}`,
description: "Get the current Unix timestamp."
},
url_encode: {
func: (text) => `URL encoded: ${encodeURIComponent(text)}`,
description: "URL encode the given text."
},
url_decode: {
func: (text) => {
try {
return `URL decoded: ${decodeURIComponent(text)}`;
} catch (e) {
return `Error decoding URL: ${e.message}`;
}
},
description: "URL decode the given text."
},
convert_case: {
func: (text, caseType = 'upper') => {
switch (caseType.toLowerCase()) {
case 'upper':
return text.toUpperCase();
case 'lower':
return text.toLowerCase();
case 'title':
return text.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
default:
return `Invalid case type: ${caseType}. Use upper, lower, or title.`;
}
},
description: "Convert text to uppercase, lowercase, or title case."
},
get_lorem_ipsum: {
func: (paragraphs = 1) => {
const p = parseInt(paragraphs);
const lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
return Array(p).fill(lorem).join('\n\n');
},
description: "Generate Lorem Ipsum placeholder text."
},
sort_lines: {
func: (text, direction = 'asc') => {
const lines = text.split('\n');
const sorted = direction === 'desc' ? lines.sort().reverse() : lines.sort();
return sorted.join('\n');
},
description: "Sort lines of text alphabetically (asc or desc)."
},
get_crypto_price: {
func: (coin = 'Bitcoin') => {
const prices = {
'bitcoin': 68000,
'ethereum': 3500,
'dogecoin': 0.15
};
const price = prices[coin.toLowerCase()];
return price ? `Price of ${coin}: $${price}` : `${coin} not found.`;
},
description: "Get the (mock) price of a cryptocurrency (e.g., Bitcoin, Ethereum)."
},
generate_password: {
func: (length = 16) => {
const len = parseInt(length);
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()';
let password = '';
for (let i = 0; i < len; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
}
return `Generated Password: ${password}`;
},
description: "Generate a random password of a specified length."
}
};
// Tool execution functionality
function processToolCalls(responseContent, toolsObj) {
if (!responseContent.includes('```tool')) {
return null;
}
try {
const toolBlockMatch = responseContent.match(/```tool\s*([\s\S]*?)```/);
if (!toolBlockMatch) return null;
const toolBlock = toolBlockMatch[1].trim();
const toolResults = [];
const toolLines = toolBlock.split('\n').filter(line => line.trim());
for (const toolLine of toolLines) {
const match = toolLine.match(/(\w+)\(([^)]*)\)/);
if (match) {
const toolName = match[1];
const argString = match[2].replace(/['"]/g, '').trim();
const args = argString ? argString.split(',').map(arg => arg.trim()) : [];
if (toolsObj[toolName]) {
try {
if (typeof addToolExecutionMessage === 'function') {
addToolExecutionMessage(`Running tool: ${toolName}`);
}
const result = args.length > 0 ?
toolsObj[toolName].func(...args) :
toolsObj[toolName].func();
toolResults.push(`${toolName}: ${result}`);
} catch (e) {
toolResults.push(`Error in ${toolName}: ${e.message}`);
}
} else {
toolResults.push(`Error: Tool ${toolName} not found`);
}
}
}
return toolResults.length > 0 ? toolResults : null;
} catch (e) {
console.error('Error processing tool calls:', e);
return null;
}
}
// Generate tools list HTML
function generateToolsList() {
return Object.entries(tools)
.map(([name, tool]) => `<div class="tool-item"><div class="tool-name">${name}</div><div class="tool-desc">${tool.description}</div></div>`)
.join('');
}
// Export for use in other files
if (typeof module !== 'undefined' && module.exports) {
module.exports = { tools, processToolCalls, generateToolsList };
}