O Typeai é um kit de ferramentas para criar aplicativos habilitados para AIs usando o TypeScript que faz com que as coisas pareçam tão simples que parece mágica. Mais importante, faz com que a construção com o LLMS "pareça" como código comum com incompatibilidade de baixa impedância.
Um exemplo:
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!' )
Basta especificar seus tipos e assinaturas de funções como você faria naturalmente, e o TypeAI gerará a implementação apropriada em relação às suas declarações de tipo. Sem carregar arquivos de esquema separados, sem engenharia imediata e sem escrever manualmente representações de esquema JSON de suas funções.
Siga -me no Twitter:
O DeepKit é necessário para fornecer informações do tipo de tempo de execução sobre suas funções e tipos.
npm install @typeai/core @deepkit/core
Nota: Por enquanto, a extração automática de tags JSDOC @Description requer esses pacote NPM bifurres @Deepkit/Type e @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
}
Nota: Alguns tempos de execução, como tsx
, não funcionam com o DeepKit. Veja Gotchas para mais informações.
No momento da execução
export OPENAI_API_KEY= ' ... ' # currently required for core functionality
export BING_API_KEY= ' ... ' # if using predefined SearchWeb Tool function
O TypeAI torna a conexão de suas funções e tipos a APIs de IA, como os pontos de extremidade de conclusão do Chat do OpenAI, leves usando o tipo de tempo de execução, reflexão sobre o código do TypeScript para gerar o esquema JSON exigido pelo recurso de chamada de função do OpenAI e, ao lidar com a expedição de funções e entrega de resultados ao LLM.
Atualmente, o TypeAI fornece duas áreas principais de funcionalidade:
Para criar uma função apoiada pela IA, escreva uma função de stub e passe-a para toAIFunction()
, que gerará uma função apoiada pela IA com o comportamento desejado.
/** @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!' )
As funções com tipos complexos de entrada e saída de saída também funcionam. Aqui está um exemplo mais interessante:
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' )
Uma função de ferramenta de IA é uma função fornecida a um LLM para seu próprio uso na geração de respostas.
Digamos que você tenha uma função e deseja fornecer sua funcionalidade ao LLM do OpenAI para uso com o recurso de chamada de função .
Ver:
O TypeAI fornece três funções que tornam a exposição de suas funções e modelos ao GPT-3.5/4, e lidando com as solicitações de chamada de função resultante do 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 >
Eles podem ser usados assim:
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!
*/
Devido à maneira como o Deepkit injeta sua transformação de compilador de tipo, corrigindo o TSC, alguns tempos de execução podem não funcionar. Estes são conhecidos para não funcionar:
tsx
Typeai usa o TypeScript Runttime Type Informações fornecidas por @deepkit/type
para:
Isso resulta em uma experiência de codificação que parece "nativa".
Exemplo
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 API de conclusão do OpenAI não gosta de respostas à função vazia.
Veja License.txt