Typeai es un conjunto de herramientas para construir aplicaciones habilitadas para AI que usan un escritor de mecanografiado que hace que las cosas se vean tan simples que parece magia. Más importante aún, hace que la construcción con LLM "se sienta" como el código ordinario con desajuste de baja impedancia.
Un ejemplo:
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!' )
Simplemente especifique sus firmas de tipos y funciones como lo haría naturalmente, y TypEAI generará la implementación adecuada con respecto a sus declaraciones de tipo. Sin cargar archivos de esquema separados, sin ingeniería rápida y sin escribir manualmente representaciones de esquema JSON de sus funciones.
Sígueme en Twitter:
Se requiere DeepKit para proporcionar información de tipo de ejecución sobre sus funciones y tipos.
npm install @typeai/core @deepkit/core
Nota: Por ahora, la extracción automática de las etiquetas JSDOC @description requiere que estos paquetes NPM bifurcados compilan @Deepkit/type y @profundo/tipo-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
}
Nota: Algunos tiempos de ejecución, como tsx
, no funcionarán con DeepKit. Vea Gotchas para obtener más información.
En el momento de la ejecución
export OPENAI_API_KEY= ' ... ' # currently required for core functionality
export BING_API_KEY= ' ... ' # if using predefined SearchWeb Tool function
Typeai hace que la conexión de sus funciones y tipos a AI AI API, como los puntos finales de finalización de chat de OpenAi, sean livianos utilizando la reflexión del tipo de tiempo de ejecución en el código TypeScript para generar el esquema JSON requerido por la función de llamadas de funciones de OpenAI y al manejar el envío de funciones y la entrega de resultados a la LLM.
Typeai actualmente proporciona dos áreas principales de funcionalidad:
Para crear una función respaldada por IA, escriba una función de stub y pase a toAIFunction()
, que generará una función respaldada por IA con el comportamiento deseado.
/** @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!' )
Las funciones con tipos complejos de tipos de mecanografía de entrada y salida también funcionan. Aquí hay un ejemplo más interesante:
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' )
Una función de herramienta AI es una función proporcionada a un LLM para su propio uso en la generación de respuestas.
Digamos que tiene una función y desea proporcionar su funcionalidad a OpenAI's LLM para su uso con su función de llamadas de funciones .
Ver:
Typeai proporciona tres funciones que hacen que exponga sus funciones y modelos a GPT-3.5/4, y manejen las solicitudes de llamadas de función resultante de GPT-3/4, transparente:
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 >
Se pueden usar así:
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!
*/
Debido a la forma en que DeepKit inyecta su transformación de compilador tipo, al parchear TSC, algunos tiempos de ejecución pueden no funcionar. Estos se sabe que no funcionan:
tsx
Typeai usa la información de tipo de ejecución de TypeScript proporcionada por @deepkit/type
a:
Esto da como resultado una experiencia de codificación que se siente "nativa".
Ejemplo
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 ) } ` )
Nota: A la API de finalización de OpenAI no le gustan las respuestas de la función vacía.
Ver licencia.txt