Typeaiは、TypeScriptを使用してAI対応アプリを構築するためのツールキットであり、物事が非常にシンプルに見えるため、魔法のように見える。さらに重要なことは、LLMSを使用した構築により、インピーダンスの不一致が低い通常のコードのように「感じる」ことです。
例:
import { toAIFunction } from '@typeai/core'
/** @description Given `text`, returns a number between 1 (positive) and -1 (negative) indicating its sentiment score. */
function sentimentSpec ( text : string ) : number | void { }
const sentiment = toAIFunction ( sentimentSpec )
const score = await sentiment ( 'That was surprisingly easy!' )
当然のようにタイプと関数の署名を指定するだけで、Typeaiはタイプ宣言を尊重する適切な実装を生成します。個別のスキーマファイル、迅速なエンジニアリングはありませんし、機能のJSONスキーマ表現を手動で書き込むこともありません。
Twitterでフォローしてください:
deepkitは、機能とタイプに関するランタイムタイプ情報を提供するために必要です。
npm install @typeai/core @deepkit/core
注:今のところ、JSDOC @descriptionタグを自動抽出するには、これらのフォークされたNPMパッケージが @deepkit/typeおよび @deepkit/type-compilerをビルドする必要があります
npm install @deepkit/type@npm:@jefflaporte/[email protected]
npm install --save-dev @deepkit/type-compiler@npm:@jefflaporte/[email protected]
# Bash
./node_modules/.bin/deepkit-type-install
# PowerShell
pwsh ./node_modules/.bin/deepkit-type-install.ps1
tsconfig.json
// tsconfig.json
{
"compilerOptions" : {
// ...
// Note: DeepKit says that experimentalDecorators is not necessary when using @deepkit/type,
// but I have found that deepkit's typeOf() does not always work with TypeScript > 4.9
// without experimentalDecorators set.
"experimentalDecorators" : true
} ,
"reflection" : true
}
注: tsx
などのいくつかのランタイムは、DeepKitで動作しません。詳細については、Gotchasをご覧ください。
実行時に
export OPENAI_API_KEY= ' ... ' # currently required for core functionality
export BING_API_KEY= ' ... ' # if using predefined SearchWeb Tool function
Typeaiは、OpenAIのチャット完了エンドポイントのような機能とタイプをAI APIに接続して、TypeScriptコードのランタイムタイプリフレクションを使用して、OpenAIの関数呼び出し機能に必要なJSONスキーマを生成し、関数ディスパッチと結果配信をLLMに処理します。
Typeaiは現在、機能の2つの主要な領域を提供しています。
AIバックされた関数を作成するには、スタブ関数を書き込み、それをtoAIFunction()
に渡します。
/** @description Given `text`, returns a number between 1 (positive) and -1 (negative) indicating its sentiment score. */
function sentimentSpec ( text : string ) : number | void { }
const sentiment = toAIFunction ( sentimentSpec )
const score = await sentiment ( 'That was surprisingly easy!' )
複雑な入力および出力タイプスクリプトタイプを使用した関数も機能します。これがより興味深い例です:
type Patient = {
name : string
age : number
isSmoker : boolean
}
type Diagnosis = {
condition : string
diagnosisDate : Date
stage ?: string
type ?: string
histology ?: string
complications ?: string
}
type Treatment = {
name : string
startDate : Date
endDate ?: Date
}
type Medication = Treatment & {
dose ?: string
}
type BloodTest = {
name : string
result : string
testDate : Date
}
type PatientData = {
patient : Patient
diagnoses : Diagnosis [ ]
treatments : Treatment | Medication [ ]
bloodTests : BloodTest [ ]
}
/** @description Returns a PatientData record generate from the content of doctorsNotes notes. */
function generateElectronicHealthRecordSpec ( input : string ) : PatientData | void { }
const generateElectronicHealthRecord = toAIFunction ( generateElectronicHealthRecordSpec , {
model : 'gpt-4' ,
} )
enum AppRouteEnum {
USER_PROFILE = '/user-profile' ,
SEARCH = '/search' ,
NOTIFICATIONS = '/notifications' ,
SETTINGS = '/settings' ,
HELP = '/help' ,
SUPPORT_CHAT = '/support-chat' ,
DOCS = '/docs' ,
PROJECTS = '/projects' ,
WORKSPACES = '/workspaces' ,
}
const AppRoute = toAIClassifier ( AppRouteEnum )
const appRouteRes = await AppRoute ( 'I need to talk to somebody about billing' )
AIツール関数は、回答を生成する際に独自の使用のためにLLMに提供される関数です。
関数があり、機能呼び出し機能で使用するためにOpenaiのLLMに機能を提供したいとします。
見る:
Typeaiは、関数とモデルをGPT-3.5/4に公開し、GPT-3/4からの結果の関数呼び出し要求を処理する3つの関数を提供します。
static ToolFunction . from < R > (
fn : ( ... args : any [ ] ) => R ,
options ?: ToolFunctionFromOptions
) : ToolFunction
static ToolFunction . modelSubmissionToolFor < T > (
cb : ( arg : T ) => Promise < void >
) : ToolFunction
function handleToolUse (
openAIClient : OpenAIApi ,
originalRequest : CreateChatCompletionRequest ,
responseData : CreateChatCompletionResponse ,
options ?: {
model ?: string ,
registry ?: SchemaRegistry ,
handle ?: 'single' | 'multiple'
} ,
) : Promise < CreateChatCompletionResponse | undefined >
これらは次のように使用できます:
import {
OpenAIApi ,
Configuration ,
CreateChatCompletionRequest ,
ChatCompletionRequestMessage ,
ChatCompletionRequestMessageRoleEnum ,
} from 'openai'
import { ToolFunction , handleToolUse } from '@typeai/core'
import { getCurrentWeather } from 'yourModule'
// Init OpenAI client
const configuration = new Configuration ( { apiKey : process . env . OPENAI_API_KEY } )
const openai = new OpenAIApi ( configuration )
// Generate JSON Schema for function and dependent types
const getCurrentWeatherTool = ToolFunction . from ( getCurrentWeather )
// Run a chat completion sequence
const messages : ChatCompletionRequestMessage [ ] = [
{
role : ChatCompletionRequestMessageRoleEnum . User ,
content : "What's the weather like in Boston? Say it like a weather reporter." ,
} ,
]
const request : CreateChatCompletionRequest = {
model : 'gpt-3.5-turbo' ,
messages ,
functions : [ getCurrentWeatherTool . schema ] ,
stream : false ,
max_tokens : 1000 ,
}
const { data : response } = await openai . createChatCompletion ( request )
// Transparently handle any LLM calls to your function.
// handleToolUse() returns OpenAI's final response after
// any/all function calls have been completed
const responseData = await handleToolUse ( openai , request , response )
const result = responseData ?. choices [ 0 ] . message
/*
Good afternoon, Boston! This is your weather reporter bringing you the latest
updates. Currently, we're experiencing a pleasant temperature of 82 degrees Celsius. The sky is a mix of sunshine and clouds, making for a beautiful day. However, there is a 25% chance of precipitation, so you might want to keep an umbrella handy. Additionally, the atmospheric pressure is at 25 mmHg. Overall, it's a great day to get outside and enjoy the city. Stay safe and have a wonderful time!
*/
DeepKitの挿入方法により、TSCにパッチを適用することにより、いくつかのランタイムが機能しない可能性があります。これらは機能しないことを知っています:
tsx
Typeaiは@deepkit/type
によって提供されるタイプスクリプトランタイムタイプ情報を使用します。
これにより、「ネイティブ」を感じるコーディングエクスペリエンスが発生します。
例
import { ToolFunction , handleToolUse } from '@typeai/core'
// Your type definitions
// ...
// Your function definitions dependent on your types
// ...
// eg:
const getCurrentWeather = function getCurrentWeather (
location : string ,
unit : TemperatureUnit = 'fahrenheit' ,
options ?: WeatherOptions ,
) : WeatherInfo {
const weatherInfo : WeatherInfo = {
location : location ,
temperature : 82 ,
unit : unit ,
precipitationPct : options ?. flags ?. includePrecipitation ? 25 : undefined ,
pressureMmHg : options ?. flags ?. includePressure ? 25 : undefined ,
forecast : [ 'sunny' , 'cloudy' ] ,
}
return weatherInfo
}
// Register your function and type info
const getCurrentWeatherTool = ToolFunction . from ( getCurrentWeather )
// Run a completion series
const messages : ChatCompletionRequestMessage [ ] = [
{
role : ChatCompletionRequestMessageRoleEnum . User ,
content : "What's the weather like in Boston? Say it like a weather reporter." ,
} ,
]
const request : CreateChatCompletionRequest = {
model : 'gpt-3.5-turbo-0613' ,
messages ,
functions : [ getCurrentWeatherTool . schema ] ,
stream : false ,
max_tokens : 1000 ,
}
const { data : response } = await openai . createChatCompletion ( request )
const responseData = await handleToolUse ( openai , request , response )
const result = responseData ?. choices [ 0 ] . message
console . log ( `LLM final result: ${ JSON . stringify ( result , null , 2 ) } ` )
注:OpenAI完了APIは、ボイド関数応答が好きではありません。
license.txtを参照してください