AI関数ヘルパーは、OpenAIのGPTモデルのアプリケーションへの統合を簡素化する強力なnode.jsモジュールです。 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 |
outputschema :JSONスキーマまたはZODスキーマを使用して、AI関数の出力の予想構造を定義します。これにより、AIモデルがアプリケーションが期待する形式でデータを返すことが保証されます。
ツール:メインAI関数内で使用できるヘルパー関数の配列。各ツールは、 name 、 function_call 、 description 、およびparametersプロパティを備えたオブジェクトです。
BlockHijack :有効にすると、この機能により、AIモデルが関数の意図した動作をオーバーライドしようとするユーザーメッセージの指示に従うことができなくなります。
PROMPTVARS :関数の説明に置き換える変数を定義し、プロンプトエンジニアリングの柔軟性を提供できます。
画像:ビジョン対応モデルに画像入力を使用して、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|> and <|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スキーマスキーマを使用して、必要な正確なデータ構造を確実に取得します。
複雑なタスクにツールを使用する:特定の計算または外部データを必要とするタスクの場合、これらの側面を処理するカスタムツールを定義します。
エラーを優雅に処理する:トライキャッチブロックを使用し、適切なタイムアウトの設定と堅牢なエラー処理のために値を再試行することを検討します。
トークンの使用に最適化する:プロンプトの長さに注意し、トークン消費を削減するために大量の出力にminifyJSONを使用することを検討してください。
長い応答のためにストリーミングを使用する:長い応答を生成する可能性のあるタスクについては、ストリーミングオプションを使用して応答をリアルタイムで処理することを検討してください。
会話履歴を活用する:マルチターンインタラクションの場合、 historyオプションを使用して、以前の交換からコンテキストを提供します。
Q:他のAIプロバイダーと一緒にこのモジュールを使用できますか? A:現在、AI関数ヘルパーは、OpenAIのモデルを使用するように設計されています。他のプロバイダーのサポートは、将来のバージョンに追加される場合があります。
Q:予想される出力を取得していない場合、どうすればデバッグできますか? A: showDebug: trueとdebugLevel調整。これにより、API呼び出しと応答に関する詳細情報が提供されます。
Q:このモジュールは生産の使用に適していますか? A:はい。ただし、OpenAIによって設定された適切なエラー処理と尊重レートの制限が常にあることを確認してください。
Q:これを使用して大量のデータをストリーミングできますか? A:はい、 streamオプションを使用して、大きな応答を効率的に処理できます。
Q:モジュールはAPIキーを安全にどのように処理しますか? A:モジュールは、APIキーストレージまたはセキュリティを処理しません。インスタンスを作成するときにAPIキーを安全に管理および提供することはあなたの責任です。
さまざまなAIモデルで広範なテストを実施して、指定された形式を順守しながら、さまざまな複雑さのJSON出力を生成する能力を評価しました。これらのテストは、異なるAIモデルにわたるAI関数ヘルパーモジュールの汎用性と信頼性を実証するのに役立ちます。
Openaiが直接提供していないものを含む幅広いAIモデルで包括的なテストを確保するために、Litellmをプロキシとして利用しました。 Litellmは、さまざまなAIプロバイダーとローカルモデル(Ollama経由)に統一されたインターフェイスを提供する強力なツールであり、OpenAI互換のエンドポイントURLを提供します。このアプローチにより、AI関数ヘルパーと複数のAIモデルをシームレスに統合およびテストし、柔軟性と幅広い互換性を実証することができました。
| モデル | 成功率 | 平均期間 |
|---|---|---|
| 花火/llama-v3p1-405b-instruct | 100.00% | 16887.67ms |
| GROQ/LLAMA-3.1-70B-逆 | 100.00% | 2154.89ms |
| Claude-3-Haiku-20240307 | 100.00% | 3175.72ms |
| GPT-3.5-ターボ | 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 |
| Gemini-1.5-flash | 88.89% | 5150.00ms |
| Gemini-1.5-pro | 100.00% | 10066.06ms |
| gemma2:9b(ollama) | 100.00% | 13368.94ms |
このテストは、単純な計算から複雑なデータ生成と分析まで、幅広い機能をカバーしています。テストカテゴリには次のものがあります。
各テストケースとモデルのパフォーマンスの詳細な結果については、次のファイルを参照してください。
自分でテストを実行したり、それらの改善に貢献したりする場合は、githubリポジトリにテストスクリプトを見つけることができます。
これらのテストは、さまざまなAIモデルを操作し、幅広いタスクの複雑さを処理するAI関数ヘルパーの機能を示しています。また、構造化された出力を実施するモジュールの能力を紹介し、AIで生成されたコンテンツをアプリケーションに統合しやすくします。
一部のテストは「愚かに」複雑であり、AIモデルの限界をプッシュするように設計されています。これらのテストは、実用的であることを意図しているのではなく、挑戦的なシナリオを処理するAI関数ヘルパーの能力を実証することを目的としています。失敗したテストのほとんどは、AIモデルにコンテキストを増やすか、入力プロンプトを改良することで正常に完了できます。
Litellmを活用することにより、OpenaIモデルを超えてAI関数ヘルパーの互換性を拡張し、ユーザーが一貫したインターフェイスを維持しながら、さまざまなAIプロバイダーとローカルモデルを使用できるようにしました。このアプローチは、ツールの適用性を広げるだけでなく、特定のニーズと制約に最適なAIモデルを選択する柔軟性をユーザーに提供します。
貢献は大歓迎です!貢献したい場合は、リポジトリをフォークして機能ブランチを使用してください。プルリクエストは温かく大歓迎です。
AI機能ヘルパーは、MITライセンスに基づいてライセンスされているオープンソースソフトウェアです。