Created
April 23, 2023 10:40
-
-
Save AlexGoiaDev/1593ce6d1932368a56f419a0ab7c67d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// authenticates you with the API standard library | |
// type `await lib.` to display API autocomplete | |
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN}); | |
const { encode, decode } = require('gpt-3-encoder'); | |
const { search } = context.params; | |
const data = require('../data/data.json'); | |
/* CONVIERTE EL TEXTO A VECTOR */ | |
const toEmbeddings = async (text) => { | |
return lib.openai.playground[ | |
'@0.2.1' | |
].embeddings.create({ | |
model: `text-embedding-ada-002`, | |
input: [`${text}`], | |
}); | |
} | |
/* GUARDAR EN BASE DE DATOS VECTORIAL */ | |
const saveVectorData = async (data) => { | |
const { id, content } = data; | |
console.log('Voy a guardar...') | |
// Convertimos el contenido a vector antes de guardarlo | |
const embeddingResponse = await toEmbeddings(data.content); | |
const objectToSave = { | |
id: id + '', | |
metadata: { | |
content, | |
}, | |
values: embeddingResponse.data[0].embedding | |
} | |
return lib.pinecone.index['@0.0.3'].vectors.upsert({ | |
namespace: `my-data`, | |
vectors: [ | |
objectToSave | |
] | |
}); | |
} | |
/* BUSCAR CONTENIDO POR SIMILITUD DE COSENO */ | |
const searchVectorData = async (embedding) => { | |
return lib.pinecone.index['@0.0.3'].query({ | |
namespace: `my-data`, | |
vector: embedding, | |
topK: 4, | |
includeMetadata: true, | |
includeValues: true | |
}); | |
} | |
/* Guardamos la información dividida por tamaño de tokne */ | |
/* | |
for(let infoPart of data) { | |
await saveVectorData(infoPart); | |
} | |
*/ | |
console.log(`Search: ${search}`); | |
/* 1. CONVERTIMOS LA BÚSQUEDA EN EMBEDDINGS/VECTORES */ | |
const searchEmbeddingsRes = await toEmbeddings(search); | |
const searchEmbedding = searchEmbeddingsRes.data[0].embedding; | |
console.log(`Search embeddings: ${searchEmbedding}`); | |
/* 2. BUSCAMOS EN LA BASE DE DATOS VECTORIAL - SIMILITUD DE COSENO */ | |
const results = await searchVectorData(searchEmbedding); | |
/* 3. Sacamos el contenido en formato texto de los resultados más parecidos */ | |
const CONTENIDO = results.matches.map(match => match.metadata.content).join('. '); | |
const ND = 'Lo siento, pero no lo sé'; | |
const res = await lib.openai.playground['@0.2.1'].chat.completions.create({ | |
model: `gpt-3.5-turbo`, | |
messages: [ | |
{ | |
role: `system`, | |
content: ` | |
Eres una IA FAQ, a partir de ahora vas a limitarte a contestar preguntas sobre este contenido: ${CONTENIDO}. | |
NO DES MÁS INFORMACIÓN Y NO SUPONAGAS NADA. No contestes con Respuesta: o según el contenido. | |
Habla como si tú sugieres . | |
Como FAQ debes dar repuestas cortas y precisas y dar la respuesta en en lenguaje sencillo y cercano. | |
Cuando no sepas la respuesta o tengas dudas contesta con la siguiente frase "${ND}"" | |
`, | |
}, | |
{ | |
role: `user`, | |
content: search, | |
}, | |
], | |
max_tokens: 2000, | |
temperature: 0.5, | |
top_p: 1, | |
n: 1, | |
presence_penalty: 0, | |
frequency_penalty: 0, | |
}); | |
// endpoints are executed as functions, click [> Run] below to test | |
return { | |
message: res.choices[0].message.content, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment