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許可證許可的開源軟件。