AI功能助手是一个强大的节点。JS模块,简化了OpenAI的GPT模型在您的应用程序中的集成。它提供了一种结构化的方式来与AI模型进行交互,从而确保一致和格式的响应。
使用NPM安装AI功能助手:
npm install ai-function-helper这是一个简单的示例,可以让您入门:
const { createAiFunctionInstance } = require ( 'ai-function-helper' ) ;
// Create an instance with your OpenAI API key
const aiFunction = createAiFunctionInstance ( 'your_api_key_here' ) ;
// Define your function
const options = {
functionName : 'generate_haiku' ,
model : 'gpt-3.5-turbo' ,
args : { topic : 'spring' } ,
description : 'Generate a haiku about the given topic.' ,
outputSchema : {
type : "object" ,
properties : {
haiku : { type : "string" }
} ,
required : [ "haiku" ]
}
} ;
// Call the function
aiFunction ( options )
. then ( result => console . log ( result . haiku ) )
. catch ( error => console . error ( error ) ) ; 要使用AI功能助手,您首先需要使用OpenAI API密钥创建一个实例:
const { createAiFunctionInstance } = require ( 'ai-function-helper' ) ;
const aiFunction = createAiFunctionInstance ( 'your_api_key_here' ) ;您也可以使用自定义端点URL:
const aiFunction = createAiFunctionInstance ( 'your_api_key_here' , 'https://api.openai.com/v1' ) ;另外,您可以使用现有的OpenAI实例:
const OpenAI = require ( 'openai' ) ;
const openai = new OpenAI ( { apiKey : 'your_api_key_here' } ) ;
const aiFunction = createAiFunctionInstance ( openai ) ;有一个实例后,您可以通过提供选项来调用AI函数:
const result = await aiFunction ( {
functionName : 'example_function' ,
model : 'gpt-4o' ,
args : { param1 : 'value1' , param2 : 'value2' } ,
description : 'This is an example function.' ,
outputSchema : {
type : "object" ,
properties : {
result : { type : "string" }
} ,
required : [ "result" ]
}
} ) ; aiFunction将选项对象带有以下属性:
| 选项 | 类型 | 描述 | 默认 |
|---|---|---|---|
functionName | 细绳 | AI功能的名称 | 'custom_function' |
args | 对象/字符串 | 该功能的论点 | - |
description | 细绳 | 函数目的的描述 | - |
outputSchema | 目的 | 预期返回类型(JSON模式或ZOD模式) | - |
strictReturn | 布尔 | 执行严格的返回类型验证 | true |
showDebug | 布尔 | 将调试信息打印到控制台 | false |
debugLevel | 数字 | 调试信息级别(0-2) | 0 |
temperature | 数字 | AI模型的采样温度 | 0.6 |
frequency_penalty | 数字 | AI模型的频率罚款 | 0 |
presence_penalty | 数字 | AI模型的存在处罚 | 0 |
model | 细绳 | 使用的AI模型 | 'gpt-4o-mini' |
max_tokens | 数字 | 生成的最大令牌数 | 1000 |
top_p | 数字 | AI模型的最高P值 | null |
blockHijack | 布尔 | 防止提示劫持 | false |
blockHijackThrowError | 布尔 | 在劫持尝试上丢下错误 | false |
tools | 大批 | 助手功能在主要功能中使用 | [] |
stream | 布尔 | 启用响应流 | false |
streamCallback | 功能 | 流式响应的回调 | null |
promptVars | 目的 | 在提示中使用的变量 | {} |
images | 字符串/数组 | 视觉模型的图像URL | null |
imageQuality | 细绳 | 视觉模型的图像质量 | 'low' |
minifyJSON | 布尔 | 缩小JSON输出 | false |
history | 大批 | 上下文的对话历史 | [] |
forceJsonMode | 布尔 | 非json模型的力量JSON模式 | false |
timeout | 数字 | API呼叫的超时(以毫秒为单位) | 120000 |
maxRetries | 数字 | API呼叫的最大检索次数 | 0 |
includeThinking | 布尔 | 在调试输出中包括AI的思维过程 | false |
OUTUPTSCHEMA :使用JSON模式或ZOD模式定义AI函数输出的预期结构。这样可以确保AI模型以您的应用程序期望的格式返回数据。
工具:可以在主AI函数中使用的辅助功能数组。每个工具都是具有name , function_call , description和parameters属性的对象。
Blockhijack :启用后,此功能可防止AI模型以下在用户消息中尝试覆盖该功能的预期行为的说明。
提示值:允许您定义将在功能描述中替换的变量,从而在及时工程中提供了更灵活的。
图像:启用图像输入用于具有视觉能力的模型,扩展AI可以执行的任务类型。
包括:设置为true时,此选项将AI的思维过程包括在调试输出中,从而洞悉AI如何得出其结论。这对于复杂的解决问题的任务和调试特别有用。
includeThinking选项使您可以在生成最终输出之前捕获AI的思维过程。此功能提供了几个好处:
提高了响应质量:通过“思考”在响应之前,AI可以组织其思想并提供更连贯和结构良好的答案。
透明度:您可以看到AI响应背后的推理,这对于调试和了解AI如何得出其结论很有用。
调试援助:当微调提示或故障排除意外输出时,思维过程可能是无价的。
启用后,AI的思维过程包含在调试输出中,但作为最终结果的一部分未返回。这是使用它的方法:
const options = {
functionName : 'complex_calculation' ,
args : { expression : '15*87 + ( 129/ (48*0.5) ) +12' } ,
description : 'Perform a complex mathematical calculation and show the steps.' ,
outputSchema : {
type : "object" ,
properties : {
result : { type : "number" }
} ,
required : [ "result" ]
} ,
includeThinking : true ,
showDebug : true // Set this to true to see the thinking process in the console
} ;
const result = await aiFunction ( options ) ;在调试输出中,您会看到<|start_of_thinking|>和<|end_of_thinking|>标签中包含的思维过程。例如:
--- Thinking Process ---
To solve the expression '15*87 + ( 129/ (48*0.5) ) +12', I'll break it down into steps:
1. First, let's solve the parentheses:
(48*0.5) = 24
2. Now we can simplify the division:
129 / 24 = 5.375
3. Let's calculate 15*87:
15*87 = 1305
4. Now we have simplified the expression to:
1305 + 5.375 + 12
5. Let's add these numbers:
1305 + 5.375 = 1310.375
1310.375 + 12 = 1322.375
Therefore, the final result is 1322.375.
--- Parsed JSON Output ---
{
"result": 1322.375
}
请注意,思维过程仅在调试输出中可见,不会影响返回结果的结构或内容。此功能对于理解AI的推理可以带来更好的迅速工程和更准确的结果的复杂任务特别有用。
在此示例中,我们可以看到AI如何将复杂的计算分解为可管理的步骤,从而更容易验证结果并了解解决问题的方法。思维过程中的这种细节水平对于调试,教育或得出结论的步骤与最终答案本身一样重要时可能特别有价值。
使流媒体能够实时处理响应:
const options = {
// ... other options ...
stream : true ,
streamCallback : ( chunk ) => {
console . log ( 'Received chunk:' , chunk ) ;
}
} ;流媒体功能使您可以实时处理AI响应,这对于长期运行的任务或想向用户提供即时反馈时可能特别有用。这是如何使用streamCallback使用stream选项的示例:
const { createAiFunctionInstance } = require ( 'ai-function-helper' ) ;
const aiFunction = createAiFunctionInstance ( 'your_api_key_here' ) ;
async function generateStory ( ) {
let story = '' ;
const options = {
functionName : 'generate_story' ,
model : 'gpt-4o' ,
args : {
theme : 'space exploration' ,
length : 'short'
} ,
description : 'Generate a short story about space exploration.' ,
// We don't use 'outputSchema' to return a text instead of a JSON
stream : true ,
streamCallback : ( chunk ) => {
const content = chunk . choices [ 0 ] ?. delta ?. content ;
if ( content ) {
story += content ;
console . log ( 'Received chunk:' , content ) ;
// You can update your UI here with the new content
}
}
} ;
try {
const result = await aiFunction ( options ) ;
// The result here will be the complete response
console . log ( 'Final story:' , story ) ;
return story ;
} catch ( error ) {
console . error ( 'Error generating story:' , error ) ;
}
}
generateStory ( ) ;在此示例中:
stream: true 。streamCallback函数,该功能会在响应到达时接收响应的部分。这种方法使您可以实时处理AI的响应,这可能是有益的:
请记住,在使用流时,由aiFunction返回的最终结果将是完整的响应,因此您仍然可以在需要时使用它。
定义用于在主要AI函数中使用的助手功能:
const options = {
// ... other options ...
tools : [
{
name : "generate_password" ,
function_call : ( { length = 5 , passwordCount = 1 } ) => {
// Password generation logic here
} ,
description : "Generate a random password" ,
parameters : {
type : "object" ,
properties : {
length : { type : "integer" } ,
passwordCount : { type : "integer" }
}
}
}
]
} ;启用防止提示劫持的保护:
const options = {
// ... other options ...
blockHijack : true ,
blockHijackThrowError : true // Optional: throw error instead of returning a message
} ;对于具有视觉能力的模型,您可以包括图像输入:
const options = {
// ... other options ...
images : 'https://example.com/image.jpg' ,
// Or
images : [ 'https://example.com/image1.jpg' , 'https://example.com/image2.jpg' ] ,
imageQuality : 'high'
} ;提供以前交互的上下文:
const options = {
// ... other options ...
history : [
{ role : "user" , content : "What's the weather like?" } ,
{ role : "assistant" , content : "I'm sorry, but I don't have access to real-time weather information. Is there anything else I can help you with?" }
]
} ; 以下是一些引人入胜的示例,展示了aiFunction模块的多功能性和功能:
const options = {
functionName : 'generate_quiz' ,
model : 'gpt-4o' ,
args : { topic : 'space exploration' , difficulty : 'medium' , num_questions : 2 } ,
description : 'Generate a quiz with multiple-choice questions on the given topic.' ,
outputSchema : {
type : "array" ,
items : {
type : "object" ,
properties : {
question : { type : "string" } ,
options : {
type : "array" ,
items : { type : "string" } ,
minItems : 4 ,
maxItems : 4
} ,
correct_answer : { type : "string" }
} ,
required : [ "question" , "options" , "correct_answer" ]
}
}
} ;
const quiz = await aiFunction ( options ) ;
console . log ( JSON . stringify ( quiz , null , 2 ) ) ;预期输出:
[
{
"question" : " Which space agency launched the first artificial satellite, Sputnik 1? " ,
"options" : [
" NASA " ,
" Soviet Union " ,
" European Space Agency " ,
" China National Space Administration "
],
"correct_answer" : " Soviet Union "
},
{
"question" : " What year did the Apollo 11 mission successfully land humans on the Moon? " ,
"options" : [
" 1967 " ,
" 1969 " ,
" 1971 " ,
" 1973 "
],
"correct_answer" : " 1969 "
}
] const { z } = require ( 'zod' ) ;
const options = {
functionName : 'create_recipe' ,
model : 'gpt-4o' ,
args : { cuisine : 'Italian' , main_ingredient : 'pasta' , dietary_restriction : 'vegetarian' } ,
description : 'Create a recipe based on the given cuisine, main ingredient, and dietary restriction.' ,
outputSchema : z . object ( {
name : z . string ( ) ,
ingredients : z . array ( z . string ( ) ) ,
instructions : z . array ( z . string ( ) ) ,
prep_time : z . string ( ) ,
cook_time : z . string ( ) ,
servings : z . number ( ) . int ( )
} )
} ;
const recipe = await aiFunction ( options ) ;
console . log ( JSON . stringify ( recipe , null , 2 ) ) ;预期输出:
{
"name" : " Vegetarian Pasta Primavera " ,
"ingredients" : [
" 12 oz penne pasta " ,
" 2 cups mixed vegetables (bell peppers, zucchini, carrots) " ,
" 1/4 cup olive oil " ,
" 3 cloves garlic, minced " ,
" 1/2 cup grated Parmesan cheese " ,
" 1/4 cup fresh basil, chopped " ,
" Salt and pepper to taste "
],
"instructions" : [
" Cook pasta according to package instructions. Reserve 1/2 cup pasta water. " ,
" In a large skillet, heat olive oil over medium heat. Add minced garlic and sauté for 1 minute. " ,
" Add mixed vegetables to the skillet and cook for 5-7 minutes until tender-crisp. " ,
" Drain pasta and add it to the skillet with vegetables. Toss to combine. " ,
" Add Parmesan cheese, basil, and pasta water as needed to create a light sauce. " ,
" Season with salt and pepper to taste. Serve hot. "
],
"prep_time" : " 15 minutes " ,
"cook_time" : " 20 minutes " ,
"servings" : 4
} const options = {
functionName : 'analyze_reviews' ,
model : 'gpt-4o' ,
args : {
reviews : [
"The product exceeded my expectations. Great value for money!" ,
"Disappointed with the quality. Wouldn't recommend." ,
"Average product, nothing special but does the job."
]
} ,
description : 'Analyze the sentiment of customer reviews and categorize them.' ,
outputSchema : {
type : "array" ,
items : {
type : "object" ,
properties : {
review : { type : "string" } ,
sentiment : { type : "string" , enum : [ "positive" , "neutral" , "negative" ] } ,
score : { type : "number" , minimum : 0 , maximum : 1 }
} ,
required : [ "review" , "sentiment" , "score" ]
}
}
} ;
const sentiment_analysis = await aiFunction ( options ) ;
console . log ( JSON . stringify ( sentiment_analysis , null , 2 ) ) ;预期输出:
[
{
"review" : " The product exceeded my expectations. Great value for money! " ,
"sentiment" : " positive " ,
"score" : 0.9
},
{
"review" : " Disappointed with the quality. Wouldn't recommend. " ,
"sentiment" : " negative " ,
"score" : 0.2
},
{
"review" : " Average product, nothing special but does the job. " ,
"sentiment" : " neutral " ,
"score" : 0.5
}
] const { z } = require ( 'zod' ) ;
const options = {
functionName : 'create_travel_itinerary' ,
model : 'gpt-4o' ,
args : { destination : 'Tokyo' , duration : 3 , interests : [ 'technology' , 'culture' , 'food' ] } ,
description : 'Create a daily travel itinerary for the specified destination and duration, considering the traveler's interests.' ,
outputSchema : z . object ( {
destination : z . string ( ) ,
duration : z . number ( ) . int ( ) ,
daily_plans : z . array ( z . object ( {
day : z . number ( ) . int ( ) ,
activities : z . array ( z . object ( {
time : z . string ( ) ,
activity : z . string ( ) ,
description : z . string ( )
} ) )
} ) )
} )
} ;
const itinerary = await aiFunction ( options ) ;
console . log ( JSON . stringify ( itinerary , null , 2 ) ) ;预期输出:
{
"destination" : " Tokyo " ,
"duration" : 3 ,
"daily_plans" : [
{
"day" : 1 ,
"activities" : [
{
"time" : " 09:00 " ,
"activity" : " Visit Akihabara " ,
"description" : " Explore the technology and electronics district, known for its gadgets and anime culture. "
},
{
"time" : " 13:00 " ,
"activity" : " Lunch at a Robot Restaurant " ,
"description" : " Experience a unique dining experience with robot performances. "
},
{
"time" : " 15:00 " ,
"activity" : " Tour the Miraikan Science Museum " ,
"description" : " Discover cutting-edge technology and scientific innovations at this interactive museum. "
}
]
},
{
"day" : 2 ,
"activities" : [
{
"time" : " 10:00 " ,
"activity" : " Visit Senso-ji Temple " ,
"description" : " Explore Tokyo's oldest Buddhist temple and experience traditional Japanese culture. "
},
{
"time" : " 14:00 " ,
"activity" : " Tea Ceremony in Hamarikyu Gardens " ,
"description" : " Participate in a traditional Japanese tea ceremony in a beautiful garden setting. "
},
{
"time" : " 18:00 " ,
"activity" : " Dinner at Tsukiji Outer Market " ,
"description" : " Enjoy fresh sushi and local delicacies at the world-famous fish market area. "
}
]
},
{
"day" : 3 ,
"activities" : [
{
"time" : " 09:00 " ,
"activity" : " Visit teamLab Borderless " ,
"description" : " Immerse yourself in a digital art museum that blends technology and creativity. "
},
{
"time" : " 13:00 " ,
"activity" : " Ramen Tour in Shinjuku " ,
"description" : " Sample various styles of ramen at some of Tokyo's best ramen shops. "
},
{
"time" : " 16:00 " ,
"activity" : " Shopping in Ginza " ,
"description" : " Explore high-end technology stores and experience Japanese retail innovation. "
}
]
}
]
} const options = {
functionName : 'analyze_stock' ,
model : 'gpt-4o' ,
args : { symbol : 'AAPL' , timeframe : '1 year' } ,
description : 'Analyze the stock performance and provide insights based on the given symbol and timeframe.' ,
outputSchema : {
type : "object" ,
properties : {
symbol : { type : "string" } ,
currentPrice : { type : "number" } ,
yearlyPerformance : { type : "number" } ,
technicalIndicators : {
type : "object" ,
properties : {
RSI : { type : "number" } ,
MACD : {
type : "object" ,
properties : {
value : { type : "number" } ,
signal : { type : "number" } ,
histogram : { type : "number" }
} ,
required : [ "value" , "signal" , "histogram" ]
}
} ,
required : [ "RSI" , "MACD" ]
} ,
recommendation : { type : "string" , enum : [ "Buy" , "Hold" , "Sell" ] }
} ,
required : [ "symbol" , "currentPrice" , "yearlyPerformance" , "technicalIndicators" , "recommendation" ]
}
} ;
const stockAnalysis = await aiFunction ( options ) ;
console . log ( JSON . stringify ( stockAnalysis , null , 2 ) ) ;预期输出:
{
"symbol" : " AAPL " ,
"currentPrice" : 178.25 ,
"yearlyPerformance" : 0.35 ,
"technicalIndicators" : {
"RSI" : 62.5 ,
"MACD" : {
"value" : 2.1 ,
"signal" : 1.8 ,
"histogram" : 0.3
}
},
"recommendation" : " Buy "
}这些示例演示了如何将AI功能助手用于从内容生成到数据分析的各种任务。每个示例都包括一个详细的outputSchema模式(在JSON模式和ZOD格式之间交替),以确保AI模型的结构和验证的输出。
使用特定的函数名称:选择清晰和描述性函数名称来帮助AI了解上下文。
提供详细的描述:您在描述中提供的上下文越多,AI可以理解和执行任务越好。
定义精确的返回模式:使用详细的outputSchema模式来确保您获得所需的确切数据结构。
利用工具进行复杂的任务:对于需要特定计算或外部数据的任务,请定义自定义工具来处理这些方面。
优雅地处理错误:使用try-catch块,并考虑设置适当的超时和重试值以进行鲁棒错误处理。
优化令牌用法:请注意提示的长度,并考虑使用minifyJSON进行大量输出以减少令牌消耗。
使用流进行长响应:对于可能会生成较长响应的任务,请考虑使用流选项实时处理响应。
利用对话历史记录:对于多转交互,请使用history选项来提供以前交流的上下文。
问:我可以将此模块与其他AI提供商一起使用吗?答:目前,AI功能助手旨在与OpenAI的模型一起使用。对其他提供商的支持可能会在以后的版本中添加。
问:如果我没有获得预期的输出,该如何调试?答:通过设置showDebug: true并调整debugLevel 。这将提供有关API调用和响应的更多信息。
问:该模块适合生产使用吗?答:是的,但始终确保您有适当的错误处理和尊重OpenAI设定的率限制。
问:我可以将其用于流量大量数据吗?答:是的,您可以使用stream选项有效地处理大型响应。
问:模块如何安全地处理API键?答:该模块不处理API键存储或安全性。创建实例时,您有责任安全管理和提供API密钥。
我们已经对各种AI模型进行了广泛的测试,以评估它们在遵守指定格式的同时产生不同复杂性的JSON输出的能力。这些测试有助于证明在不同的AI模型上AI功能助手模块的多功能性和可靠性。
为了确保对广泛的AI模型进行全面测试,包括OpenAI未直接提供的AI模型,我们将Litellm作为代理。 Litellm是一种强大的工具,可为各种AI提供商和本地型号(通过Ollama)提供统一的接口,并提供与OpenAI兼容的端点URL。这种方法使我们能够与我们的AI功能助手无缝集成和测试多个AI模型,从而证明了其灵活性和广泛的兼容性。
| 模型 | 成功率 | 平均持续时间 |
|---|---|---|
| 烟花/骆驼-V3P1-405B教学 | 100.00% | 16887.67ms |
| GROQ/LLAMA-3.1-70B反相 | 100.00% | 2154.89ms |
| Claude-3-Haiku-20240307 | 100.00% | 3175.72ms |
| GPT-3.5-Turbo | 88.89% | 3398.67ms |
| GPT-4O-Mini | 100.00% | 5699.72ms |
| GPT-4O | 100.00% | 5673.00ms |
| Claude-3-5-Sonnet-20240620 | 100.00% | 5940.50ms |
| 双子座1.5闪烁 | 88.89% | 5150.00ms |
| 双子座1.5-Pro | 100.00% | 10066.06ms |
| gemma2:9b(ollama) | 100.00% | 13368.94ms |
这些测试涵盖了广泛的功能,从简单的计算到复杂的数据生成和分析。一些测试类别包括:
有关每个测试用例和模型性能的详细结果,请参阅以下文件:
如果您想自己运行测试或改进测试,可以在我们的GitHub存储库中找到测试脚本:
这些测试证明了AI功能助手与各种AI模型一起工作并处理各种任务复杂性的能力。他们还展示了该模块执行结构化输出的能力,从而更容易将AI生成的内容集成到您的应用程序中。
一些测试是“愚蠢的”复杂的,旨在突破AI模型的限制。这些测试并不是实用的,而是要证明AI功能助手处理具有挑战性方案的能力。大多数失败的测试可以通过为AI模型提供更多上下文或完善输入提示来成功完成。
通过利用Litellm,我们将AI功能助手的兼容性扩展到OpenAI模型之外,使用户可以与各种AI提供商和本地型号一起工作,同时保持一致的界面。这种方法不仅扩大了我们的工具的适用性,而且还可以为用户提供更大的灵活性,以选择最适合其特定需求和约束的AI模型。
欢迎捐款!如果您想做出贡献,请提供存储库并使用功能分支。拉力请求非常欢迎。
AI功能助手是根据MIT许可证许可的开源软件。