TypeAI ist ein Toolkit zum Erstellen von AI-fähigen Apps mithilfe von TypeScript, mit dem die Dinge so einfach aussehen, dass es wie magisch erscheint. Noch wichtiger ist, dass das Aufbau mit LLMs wie gewöhnlicher Code mit geringem Impedanz -Missverhältnis "sich" anfühlt.
Ein Beispiel:
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!' )
Geben Sie einfach Ihre Typen und Funktionssignaturen an, wie Sie es natürlich tun würden, und typeai erzeugt die entsprechende Implementierung, die Ihre Typdeklarationen respektiert. Kein Laden separater Schema -Dateien, kein schnelles Engineering und kein manuelles Schreiben von JSON -Schema -Darstellungen Ihrer Funktionen.
Folgen Sie mir auf Twitter:
DeepKit ist erforderlich, um Laufzeit -Informationen zu Ihren Funktionen und Typen bereitzustellen.
npm install @typeai/core @deepkit/core
HINWEIS: Die automatische Extraktion von JSDOC @Description-Tags erfordert vorerst diese Forked NPM-Paket-Builds @Deepkit/Typ und @Deepkit/Typ-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
}
HINWEIS: Einige Laufzeiten wie tsx
werden nicht mit Deepkit funktionieren. Weitere Informationen finden Sie in Gotchas.
Zur Ausführungszeit
export OPENAI_API_KEY= ' ... ' # currently required for core functionality
export BING_API_KEY= ' ... ' # if using predefined SearchWeb Tool function
Typeai macht das Verbinden Ihrer Funktionen und Typen mit AI -APIs wie OpenAIs Chat Completion -Endpunkten Leichtgewicht, indem Sie den Laufzeittyp -Reflexion im TypeScript -Code verwenden, um das JSON -Schema zu generieren, das von der Funktionsaufruf -Funktion von OpenAI erforderlich ist, sowie die Funktionsweise der Funktion und die Erstellung der Lieferung an die LLM.
Typai bietet derzeit zwei Hauptfunktionsbereiche:
Um eine mit AI unterstützte Funktion zu erstellen, schreiben Sie eine Stubfunktion und geben Sie sie an toAIFunction()
weiter, wodurch eine mit AI-unterstützte Funktion mit dem gewünschten Verhalten erzeugt wird.
/** @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!' )
Funktionen mit komplexen Eingangs- und Ausgabe -Typ -Typ -Typen funktionieren ebenfalls. Hier ist ein interessanteres Beispiel:
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' )
Eine KI -Toolfunktion ist eine Funktion, die einem LLM für ihre eigene Verwendung zur Generierung von Antworten zur Verfügung gestellt wird.
Angenommen, Sie haben eine Funktion und möchten die Funktionen für die OpenAI -LLM für die Verwendung ihrer Funktionsaufruffunktion bereitstellen.
Sehen:
TypeAI bietet drei Funktionen, mit denen Ihre Funktionen und Modelle GPT-3,5/4 ausgesetzt werden und die resultierenden Funktionsanfragen von GPT-3/4, transparent:
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 >
Sie können so verwendet werden:
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!
*/
Aufgrund der Art und Weise, wie Deepkit die Typ-Kompilier-Transformation injiziert, funktionieren einige Laufzeiten möglicherweise nicht. Diese sind wissen, dass sie nicht funktionieren:
tsx
TypeAI verwendet die von @deepkit/type
bereitgestellten Informationen zum Rennzeitstyp von TypeAI.
Dies führt zu einer Codierungserfahrung, die sich "nativ" anfühlt.
Beispiel
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 ) } ` )
HINWEIS: Die OpenAI -Abschluss -API mag keine Leerfunktionsantworten.
Siehe Lizenz.TXT