Function calling for Cohere

This commit is contained in:
Cohee
2024-05-25 17:09:47 +03:00
parent dc8530049f
commit fa6fc45e6f
5 changed files with 127 additions and 31 deletions

View File

@ -451,6 +451,76 @@ function convertTextCompletionPrompt(messages) {
return messageStrings.join('\n') + '\nassistant:';
}
/**
* Convert OpenAI Chat Completion tools to the format used by Cohere.
* @param {object[]} tools OpenAI Chat Completion tool definitions
*/
function convertCohereTools(tools) {
if (!Array.isArray(tools) || tools.length === 0) {
return [];
}
const jsonSchemaToPythonTypes = {
'string': 'str',
'number': 'float',
'integer': 'int',
'boolean': 'bool',
'array': 'list',
'object': 'dict',
};
const cohereTools = [];
for (const tool of tools) {
if (tool?.type !== 'function') {
console.log(`Unsupported tool type: ${tool.type}`);
continue;
}
const name = tool?.function?.name;
const description = tool?.function?.description;
const properties = tool?.function?.parameters?.properties;
const required = tool?.function?.parameters?.required;
const parameters = {};
if (!name) {
console.log('Tool name is missing');
continue;
}
if (!description) {
console.log('Tool description is missing');
}
if (!properties || typeof properties !== 'object') {
console.log(`No properties found for tool: ${tool?.function?.name}`);
continue;
}
for (const property in properties) {
const parameterDefinition = properties[property];
const description = parameterDefinition.description || (parameterDefinition.enum ? JSON.stringify(parameterDefinition.enum) : '');
const type = jsonSchemaToPythonTypes[parameterDefinition.type] || 'str';
const isRequired = Array.isArray(required) && required.includes(property);
parameters[property] = {
description: description,
type: type,
required: isRequired,
};
}
const cohereTool = {
name: tool.function.name,
description: tool.function.description,
parameter_definitions: parameters,
};
cohereTools.push(cohereTool);
}
return cohereTools;
}
module.exports = {
convertClaudePrompt,
convertClaudeMessages,
@ -458,4 +528,5 @@ module.exports = {
convertTextCompletionPrompt,
convertCohereMessages,
convertMistralMessages,
convertCohereTools,
};