paint-brush
100 días de IA, día 18: Desarrollo de un RAG utilizando el kernel semántico de Microsoftpor@sindamnataraj
1,042 lecturas
1,042 lecturas

100 días de IA, día 18: Desarrollo de un RAG utilizando el kernel semántico de Microsoft

por Nataraj5m2024/04/05
Read on Terminal Reader

Demasiado Largo; Para Leer

En esta publicación analizamos la creación de un RAG utilizando el kernel semántico de Microsoft.
featured image - 100 días de IA, día 18: Desarrollo de un RAG utilizando el kernel semántico de Microsoft
Nataraj HackerNoon profile picture

¡Hola a todos! soy nataraj Y , al igual que usted, me han fascinado los recientes avances de la inteligencia artificial. Al darme cuenta de que necesitaba estar al tanto de todos los avances que ocurrían, decidí embarcarme en un viaje personal de aprendizaje, así 100 días de IA ¡nació! Con esta serie, aprenderé sobre los LLM y compartiré ideas, experimentos, opiniones, tendencias y aprendizajes a través de las publicaciones de mi blog. Puedes seguir el viaje en HackerNoon aquí o mi sitio web personal aquí . En el artículo de hoy, veremos cómo desarrollar un RAG utilizando el kernel semántico de Microsoft.

La recuperación de generación aumentada (RAG) es una de las aplicaciones más comunes que se desarrollan utilizando diferentes LLM. Anteriormente hemos explorado cómo desarrollar un RAG usando langchain . En esta publicación crearemos un RAG utilizando el kernel semántico de Microsoft .


Para seguir adelante, necesitará la API Open AI.

Paso 1: Inicializar el kernel semántico

El primer paso es inicializar el kernel semántico y decirle que queremos usar la finalización del chat de Open AI y el modelo de incrustación de Open AI que luego usaremos para crear incrustaciones. También le diremos al kernel que queremos utilizar un almacén de memoria que en nuestro caso será Chroma DB. Tenga en cuenta que también le estamos indicando al Kernel que este almacén de memoria debe ser persistente.


 kernel = sk.Kernel() kernel.add_text_completion_service("openai", OpenAIChatCompletion("gpt-4",api_key)) kernel.add_text_embedding_generation_service("openai-embedding", OpenAITextEmbedding("text-embedding-ada-002", api_key)) # chrome db kernel.register_memory_store(memory_store=ChromaMemoryStore(persist_directory='mymemories2')) print("Made two new services attached to the kernel and made a Chroma memory store that's persistent.")

Paso 2: crear incrustaciones

En este ejemplo, estamos creando un RAG que puede responder preguntas sobre un análisis FODA que creamos para un negocio de pizza. Entonces, para hacer eso, tomamos el análisis FODA, obtenemos las incrustaciones para ellos y almacenamos las incrustaciones correspondientes en una colección llamada "FODA" en el almacén de datos persistente que creamos en el último paso.


 strength_questions = ["What unique recipes or ingredients does the pizza shop use?","What are the skills and experience of the staff?","Does the pizza shop have a strong reputation in the local area?","Are there any unique features of the shop or its location that attract customers?", "Does the pizza shop have a strong reputation in the local area?", "Are there any unique features of the shop or its location that attract customers?"] weakness_questions = ["What are the operational challenges of the pizza shop? (eg, slow service, high staff turnover)","Are there financial constraints that limit growth or improvements?","Are there any gaps in the product offering?","Are there customer complaints or negative reviews that need to be addressed?"] opportunities_questions = ["Is there potential for new products or services (eg, catering, delivery)?","Are there under-served customer segments or market areas?","Can new technologies or systems enhance the business operations?","Are there partnerships or local events that can be leveraged for marketing?"] threats_questions = ["Who are the major competitors and what are they offering?","Are there potential negative impacts due to changes in the local area (eg, construction, closure of nearby businesses)?","Are there economic or industry trends that could impact the business negatively (eg, increased ingredient costs)?","Is there any risk due to changes in regulations or legislation (eg, health and safety, employment)?"] strengths = [ "Unique garlic pizza recipe that wins top awards","Owner trained in Sicily at some of the best pizzerias","Strong local reputation","Prime location on university campus" ] weaknesses = [ "High staff turnover","Floods in the area damaged the seating areas that are in need of repair","Absence of popular calzones from menu","Negative reviews from younger demographic for lack of hip ingredients" ] opportunities = [ "Untapped catering potential","Growing local tech startup community","Unexplored online presence and order capabilities","Upcoming annual food fair" ] threats = [ "Competition from cheaper pizza businesses nearby","There's nearby street construction that will impact foot traffic","Rising cost of cheese will increase the cost of pizzas","No immediate local regulatory changes but it's election season" ] print("✅ SWOT analysis for the pizza shop is resident in native memory") memoryCollectionName = "SWOT" # lets put these in memory / vector store async def run_storeinmemory_async(): for i in range(len(strengths)): await kernel.memory.save_information_async(memoryCollectionName, id=f"strength-{i}", text=f"Internal business strength (S in SWOT) that makes customers happy and satisfied Q&A: Q: {strength_questions[i]} A: {strengths[i]}") for i in range(len(weaknesses)): await kernel.memory.save_information_async(memoryCollectionName, id=f"weakness-{i}", text=f"Internal business weakness (W in SWOT) that makes customers unhappy and dissatisfied Q&A: Q: {weakness_questions[i]} A: {weaknesses[i]}") for i in range(len(opportunities)): await kernel.memory.save_information_async(memoryCollectionName, id=f"opportunity-{i}", text=f"External opportunity (O in SWOT) for the business to gain entirely new customers Q&A: Q: {opportunities_questions[i]} A: {opportunities[i]}") for i in range(len(threats)): await kernel.memory.save_information_async(memoryCollectionName, id=f"threat-{i}", text=f"External threat (T in SWOT) to the business that impacts its survival Q&A: Q: {threats_questions[i]} A: {threats[i]}") asyncio.run(run_storeinmemory_async()) print("😶‍🌫️ Embeddings for SWOT have been generated and stored in vector db")

Paso 3 – Haz tu pregunta

Ahora que tenemos la incorporación de nuestros datos almacenados en Chrome Vector Store, podemos hacer preguntas relacionadas con el negocio de la pizza y obtener una respuesta.


 #ask questions on swot potential_question = "What are the easiest ways to make more money?" counter = 0 async def run_askquestions_async(): memories = await kernel.memory.search_async(memoryCollectionName, potential_question, limit=5, min_relevance_score=0.5) display(f"### ❓ Potential question: {potential_question}") for memory in memories: if counter == 0: related_memory = memory.text counter += 1 print(f" > 🧲 Similarity result {counter}:\n >> ID: {memory.id}\n Text: {memory.text} Relevance: {memory.relevance}\n") asyncio.run(run_askquestions_async())


Esta es una versión muy simplificada de cómo se puede crear un RAG utilizando Semantic Kernel. La opción de marco más popular para construir en este momento usando LLM es langchain y anteriormente hemos visto cómo construir un RAG usando langchain. Aunque Langchain es más popular a medida que vemos más y más empresas que crean herramientas, habrá herramientas más sofisticadas y descubrí que Semantic Kernel tiene algunas características especiales que lo hacen destacar.


Eso es todo por el día 18 de 100 días de IA.


Escribo un boletín llamado Above Average donde hablo sobre los conocimientos de segundo orden detrás de todo lo que está sucediendo en la gran tecnología. Si estás en tecnología y no quieres ser promedio, suscríbete .


Sígueme en Twitter , LinkedIn o HackerNoon para obtener las últimas actualizaciones sobre 100 días de IA o agrega esta página a tus favoritos . Si está en tecnología, es posible que le interese unirse a mi comunidad de profesionales de la tecnología aquí .