Visualizzazione post con etichetta Gemma2. Mostra tutti i post
Visualizzazione post con etichetta Gemma2. Mostra tutti i post

martedì 17 settembre 2024

RAG con Ollama Gemma2 e LangChain

Aggiornamento:

Per poter avere le risposte in italiano (al posto dell'inglese di default) basta modificare il context template

 <|context|>
You are an AI assistant that follows instruction extremely well.
Please be truthful and give direct answers
Answer in italian
</s>

questa la risposta alla domanda "Descrivimi il monopoly"

Monopoly è un gioco da tavolo di strategia e fortuna.

I giocatori comprano, vendono e scambiano proprietà immobiliari sul tabellone, cercando di accumulare il maggior patrimonio possibile.  

Si lanciano i dadi per muoversi sul tabellone, acquistando le caselle che incontrano. Alcune caselle comportano pagamenti o attività specifiche, come andare in prigione o pagare tasse.  

Il gioco prosegue finché tutti tranne uno dei giocatori sono falliti a causa del debito. Il vincitore è il giocatore che rimane con denaro e proprietà alla fine.

Per la cronaca il Pdf delle istruzioni di Monopoly era in inglese 

=========================================  

 Seguendo un po' la moda del momento volevo provare a fare una applicazione RAG (Retrieval Augmented Generation) partendo dal modello  Gemma2 di Google e dandogli in pasto dei Pdf personali per il retraining. Per questa prova ho sentito le indicazioni contenute in questo notebook

Prima cosa: per usare Gemma2 la macchina deve avere almeno 9 Gb di ram liberi (giusto per la cronaca per usare il modello LLama 70b sono necessari almeno 40 Gb di ram liberi..diciamo che non se ne parla nemmeno)


Secondo: per installare i modelli la cosa piu' comodo e' utilizzare Ollama

Terzo : molti esempi si basano su API esterne come https://jina.ai/, OpenAI, ma in questo caso ci sono pacchetti gratuiti e poi si deve pagare il servizio. Cercavo di mettere in piedi una soluzione offline svincolata da servizi cloud di terze parti

Si scaricano quindi il modello ed un text encoder (in questo caso Nomic-Embed-Text)

ollama pull gemma2 
ollama pull nomic-embed-text

Si installa poi i pacchetti delle librerie (meglio in un venv)

pip install langchain chromadb langchain_community pypdf

ChromaDb e' il database in cui vengono salvati i vectorstore per garantire la persistenza dell'apprendimento. E' in pratica un Db orientato all'AI basato su sqlite; una alternativa con un vero server e' Milvus

I file PDF devono essere inseriti nel folder ./Pdf


# -*- coding: utf-8 -*-

from langchain_community.document_loaders import PyPDFDirectoryLoader
from langchain.text_splitter import CharacterTextSplitter,RecursiveCharacterTextSplitter
from langchain_community.embeddings import OllamaEmbeddings
from langchain.vectorstores import Chroma
from langchain_community.llms import Ollama
from langchain.chains import RetrievalQA, LLMChain

import pathlib
import textwrap
from IPython.display import display
from IPython.display import Markdown



def to_markdown(text):
text = text.replace('•', ' *')
return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))


loader = PyPDFDirectoryLoader("./Pdf")
docs = loader.load()

text_splitter = RecursiveCharacterTextSplitter(chunk_size=300, chunk_overlap=50)
chunks = text_splitter.split_documents(docs)


embeddings = OllamaEmbeddings(model="nomic-embed-text")



vectorstore = Chroma.from_documents(chunks, embeddings)



query = "who is at risk of heart disease"
search = vectorstore.similarity_search(query)

to_markdown(search[0].page_content)

"""## Retriever"""

retriever = vectorstore.as_retriever(
search_kwargs={'k': 5}
)

retriever.get_relevant_documents(query)

"""## Large Language Model - Open Source

## RAG Chain
"""

from langchain_community.llms import Ollama
llm = Ollama(model="gemma2")

from langchain.schema.runnable import RunnablePassthrough
from langchain.schema.output_parser import StrOutputParser
from langchain.prompts import ChatPromptTemplate

template = """
<|context|>
You are an AI assistant that follows instruction extremely well.
Please be truthful and give direct answers
</s>
<|user|>
{query}
</s>
<|assistant|>
"""

prompt = ChatPromptTemplate.from_template(template)

rag_chain = (
{"context": retriever, "query": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)

response = rag_chain.invoke("why should I care about my heart health")

to_markdown(response)

import sys

while True:
user_input = input(f"Input Prompt: ")
if user_input == 'exit':
print('Exiting')
sys.exit()
if user_input == '':
continue
result = rag_chain.invoke(user_input)
print("Answer: ",result)



Ho inserito due Pdf (regole di Monopoly e Ticket to Ride), questo un esempio di interazione

===========================================

Input Prompt: give me the rules of Monopoly
Answer:  ##  Monopoly Rules (Simplified):

**Goal:** Be the last player standing with money! Drive your opponents into bankruptcy by buying properties, building houses and hotels, and charging rent.

**Gameplay:**

1. **Roll Dice & Move:** Players roll two dice and move their piece around the board clockwise.
2. **Land on Property?**
    * **Unowned:** You can buy it for the listed price.
    * **Owned:** Pay rent to the owner based on the property's value and any buildings.
3. **Chance & Community Chest:** Draw a card and follow its instructions. These can be good or bad!
4. **Go To Jail:**  Land on "Go To Jail," draw a "Go To Jail" card, or roll doubles three times in a row. While in jail, you can't collect rent or move until you pay a fine, use a "Get Out of Jail Free" card, or roll doubles.
5. **Build Houses & Hotels:** Once you own all properties in a color group, you can start building houses and hotels. These increase rent significantly!
6. **Bankruptcy:** If you can't afford to pay your debts, you're bankrupt and out of the game.

**Key Elements:**

* **Properties:** Divided into color groups, each with different rent values.
* **Railroads & Utilities:** Pay rent based on dice rolls.
* **Taxes:**  Pay a set amount when landing on specific spaces.
* **Free Parking:** A safe space where you can collect any "Free Parking" money (rules vary).


**Variations:**

Many variations of Monopoly exist, with different rules and themes. Be sure to clarify the specific rules being used before starting a game!

Let me know if you'd like more detail on any specific aspect of the rules!

===========================================

Adesso rendiamo le cose piu' difficili...domanda in italiano e richiesta di trovare le differenze tra i due giochi. La domanda viene correttamente interpretata anche se in italiano ed in effetti la risposta fa una sintesi delle differenze tra i due giochi

===========================================

Answer:  Here are the key differences between Monopoly and Ticket to Ride:

**Monopoly:**

* **Goal:** Become the richest player by buying properties, developing them, and charging rent to other players.
* **Gameplay:**  Players roll dice, move around a board, buy properties, build houses and hotels, and collect rent from opponents who land on their spaces.
* **Emphasis:**  Strategic property acquisition, negotiation, and bankrupting opponents.

**Ticket to Ride:**

* **Goal:** Score the most points by claiming railway routes connecting cities across a map.
* **Gameplay:** Players draw colored train cards and use them to claim routes. Longer routes earn more points, and completing destination tickets (secret routes) awards bonus points.
* **Emphasis:** Route building, strategic card management, and fulfilling destination goals.


**In short:** Monopoly is about accumulating wealth and bankrupting opponents, while Ticket to Ride is about building railway networks and strategically claiming routes. 


RAG con Ollama Mistral e LangChain

Una altra prova usando questo repository https://github.com/CallumJMac/lessons Il folder di riferimento e'  lessons/1. RAG/examples/pixe...