Upload 2 files
Browse files- GPT_RAG.py +200 -0
- RAG_Datos.json +0 -0
GPT_RAG.py
ADDED
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -*- coding: utf-8 -*-
|
2 |
+
"""nomic_embedding_rag.ipynb
|
3 |
+
|
4 |
+
Automatically generated by Colab.
|
5 |
+
|
6 |
+
Original file is located at
|
7 |
+
https://colab.research.google.com/drive/1vAQoZx_07yU0nVCkFxJQkcVeymgNpzFF
|
8 |
+
"""
|
9 |
+
|
10 |
+
!pip install nomic
|
11 |
+
!pip install --upgrade langchain
|
12 |
+
|
13 |
+
! nomic login
|
14 |
+
|
15 |
+
! nomic login nk-bqukmTuFJHW8tgXzXXBw1qDL062-pth-ACecKP7CkXs
|
16 |
+
|
17 |
+
! pip install -U langchain-nomic langchain_community tiktoken langchain-openai chromadb langchain
|
18 |
+
|
19 |
+
# Optional: LangSmith API keys
|
20 |
+
import os
|
21 |
+
|
22 |
+
os.environ["LANGCHAIN_TRACING_V2"] = "true"
|
23 |
+
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
|
24 |
+
os.environ["LANGCHAIN_API_KEY"] = "api_key"
|
25 |
+
|
26 |
+
"""## Document Loading
|
27 |
+
|
28 |
+
Let's test 3 interesting blog posts.
|
29 |
+
"""
|
30 |
+
|
31 |
+
import json
|
32 |
+
from langchain_community.document_loaders import JSONLoader
|
33 |
+
from langchain.docstore.document import Document
|
34 |
+
|
35 |
+
# Define el JSONLoader para cargar y procesar cada mensaje del JSON
|
36 |
+
class JSONLoader:
|
37 |
+
def __init__(self, message):
|
38 |
+
self.message = message
|
39 |
+
|
40 |
+
def load(self):
|
41 |
+
# Crear una instancia de Document con el contenido y metadata adecuada
|
42 |
+
return Document(
|
43 |
+
page_content=self.message['content'],
|
44 |
+
metadata={
|
45 |
+
'role': self.message['role'],
|
46 |
+
'conversation_id': self.message['conversation_id'],
|
47 |
+
'message_id': self.message['message_id']
|
48 |
+
}
|
49 |
+
)
|
50 |
+
|
51 |
+
# Cargar el archivo JSON
|
52 |
+
file_path = 'RAG_Datos.json' # Asegúrate de que esta ruta sea correcta
|
53 |
+
|
54 |
+
with open(file_path, 'r') as file:
|
55 |
+
data = json.load(file)
|
56 |
+
|
57 |
+
# Procesar los mensajes y crear los documentos
|
58 |
+
docs_list = []
|
59 |
+
for conversation in data:
|
60 |
+
for message in conversation['messages']:
|
61 |
+
docs_list.append(JSONLoader(message).load())
|
62 |
+
|
63 |
+
# Verificar el contenido (opcional)
|
64 |
+
for doc in docs_list:
|
65 |
+
print(doc.page_content, doc.metadata)
|
66 |
+
|
67 |
+
"""from langchain_community.document_loaders import WebBaseLoader
|
68 |
+
|
69 |
+
urls = [
|
70 |
+
"https://lilianweng.github.io/posts/2023-06-23-agent/",
|
71 |
+
"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/",
|
72 |
+
"https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/",
|
73 |
+
]"""
|
74 |
+
|
75 |
+
"""docs = [WebBaseLoader(url).load() for url in urls]""
|
76 |
+
|
77 |
+
"""docs_list = [item for sublist in docs for item in sublist]
|
78 |
+
|
79 |
+
## Splitting
|
80 |
+
|
81 |
+
Long context retrieval,
|
82 |
+
Chunck_size -> tamaño de cada texto
|
83 |
+
"""
|
84 |
+
|
85 |
+
# Ahora puedes usar docs_list con text_splitter
|
86 |
+
from langchain.text_splitter import CharacterTextSplitter
|
87 |
+
|
88 |
+
text_splitter = CharacterTextSplitter(
|
89 |
+
chunk_size=7500, chunk_overlap=100
|
90 |
+
)
|
91 |
+
doc_splits = text_splitter.split_documents(docs_list)
|
92 |
+
|
93 |
+
# Verificar el contenido de los splits (opcional)
|
94 |
+
for split in doc_splits:
|
95 |
+
print(split.page_content, split.metadata)
|
96 |
+
|
97 |
+
import tiktoken
|
98 |
+
|
99 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
100 |
+
encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
|
101 |
+
for d in doc_splits:
|
102 |
+
print("The document is %s tokens" % len(encoding.encode(d.page_content)))
|
103 |
+
|
104 |
+
"""## Index
|
105 |
+
|
106 |
+
Nomic embeddings [here](https://docs.nomic.ai/reference/endpoints/nomic-embed-text).
|
107 |
+
"""
|
108 |
+
|
109 |
+
import os
|
110 |
+
|
111 |
+
from langchain_community.vectorstores import Chroma
|
112 |
+
from langchain_core.output_parsers import StrOutputParser
|
113 |
+
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
|
114 |
+
from langchain_nomic import NomicEmbeddings
|
115 |
+
from langchain_nomic.embeddings import NomicEmbeddings
|
116 |
+
|
117 |
+
# Add to vectorDB
|
118 |
+
vectorstore = Chroma.from_documents(
|
119 |
+
documents=doc_splits,
|
120 |
+
collection_name="rag-chroma",
|
121 |
+
embedding=NomicEmbeddings(model="nomic-embed-text-v1"),
|
122 |
+
)
|
123 |
+
retriever = vectorstore.as_retriever()
|
124 |
+
|
125 |
+
"""## RAG Chain
|
126 |
+
|
127 |
+
We can use the
|
128 |
+
"""
|
129 |
+
|
130 |
+
import os
|
131 |
+
from sklearn.metrics import precision_score, recall_score, f1_score
|
132 |
+
from nltk.translate.bleu_score import corpus_bleu
|
133 |
+
from langchain_core.prompts import ChatPromptTemplate
|
134 |
+
from langchain_openai import ChatOpenAI
|
135 |
+
from langchain.chains import LLMChain
|
136 |
+
|
137 |
+
# Configurar la clave de API como variable de entorno
|
138 |
+
os.environ['OPENAI_API_KEY'] = 'sk-proj-OaIQbNSKP2uATHxcaUxhT3BlbkFJi2HSSi4zSHSOw9UjtUWn'
|
139 |
+
|
140 |
+
# Prompt
|
141 |
+
template = """Answer the question based only on the following context:
|
142 |
+
{context}
|
143 |
+
|
144 |
+
Question: {question}
|
145 |
+
"""
|
146 |
+
prompt = ChatPromptTemplate.from_template(template)
|
147 |
+
|
148 |
+
# LLM API
|
149 |
+
model = ChatOpenAI(temperature=0, model="gpt-4-1106-preview")
|
150 |
+
|
151 |
+
# Placeholder para `retriever`
|
152 |
+
class DummyRetriever:
|
153 |
+
def __call__(self, *args, **kwargs):
|
154 |
+
return {"context": "This is a test context"}
|
155 |
+
|
156 |
+
retriever = DummyRetriever()
|
157 |
+
|
158 |
+
# Crear una cadena LLM
|
159 |
+
llm_chain = LLMChain(
|
160 |
+
prompt=prompt,
|
161 |
+
llm=model,
|
162 |
+
)
|
163 |
+
|
164 |
+
# Datos de prueba
|
165 |
+
test_data = [
|
166 |
+
{"context": "Write a Python function to sum all prime numbers up to 1000.", "question": "How to write a function to sum all prime numbers up to 1000?", "expected_answer": "def sum_primes(limit):\n def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n return sum(x for x in range(limit) if is_prime(x))\n\nprint(sum_primes(1000))"},
|
167 |
+
{"context": "Write a Python function to calculate the factorial of a number.", "question": "How to write a function to calculate the factorial of a number?", "expected_answer": "def factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\n\nprint(factorial(5))"},
|
168 |
+
{"context": "Write a Python function to check if a number is palindrome.", "question": "How to write a function to check if a number is palindrome?", "expected_answer": "def is_palindrome(n):\n return str(n) == str(n)[::-1]\n\nprint(is_palindrome(121))"},
|
169 |
+
{"context": "Write a Python function to generate Fibonacci sequence up to n.", "question": "How to write a function to generate Fibonacci sequence up to n?", "expected_answer": "def fibonacci(n):\n fib_sequence = [0, 1]\n while len(fib_sequence) < n:\n fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])\n return fib_sequence\n\nprint(fibonacci(10))"},
|
170 |
+
{"context": "Write a Python function to find the greatest common divisor (GCD) of two numbers.", "question": "How to write a function to find the greatest common divisor (GCD) of two numbers?", "expected_answer": "def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\nprint(gcd(48, 18))"},
|
171 |
+
{"context": "Write a Python function to check if a string is an anagram of another string.", "question": "How to write a function to check if a string is an anagram of another string?", "expected_answer": "def is_anagram(str1, str2):\n return sorted(str1) == sorted(str2)\n\nprint(is_anagram('listen', 'silent'))"},
|
172 |
+
{"context": "Write a Python function to find the maximum element in a list.", "question": "How to write a function to find the maximum element in a list?", "expected_answer": "def find_max(lst):\n return max(lst)\n\nprint(find_max([3, 5, 7, 2, 8]))"},
|
173 |
+
{"context": "Write a Python function to reverse a string.", "question": "How to write a function to reverse a string?", "expected_answer": "def reverse_string(s):\n return s[::-1]\n\nprint(reverse_string('hello'))"},
|
174 |
+
{"context": "Write a Python function to merge two sorted lists.", "question": "How to write a function to merge two sorted lists?", "expected_answer": "def merge_sorted_lists(lst1, lst2):\n return sorted(lst1 + lst2)\n\nprint(merge_sorted_lists([1, 3, 5], [2, 4, 6]))"},
|
175 |
+
{"context": "Write a Python function to remove duplicates from a list.", "question": "How to write a function to remove duplicates from a list?", "expected_answer": "def remove_duplicates(lst):\n return list(set(lst))\n\nprint(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))"},
|
176 |
+
]
|
177 |
+
|
178 |
+
# Evaluar la precisión, recall y F1-score de la recuperación
|
179 |
+
retrieved_contexts = [retriever()["context"] for _ in test_data]
|
180 |
+
expected_contexts = [item["context"] for item in test_data]
|
181 |
+
precision = precision_score(expected_contexts, retrieved_contexts, average='macro', zero_division=1)
|
182 |
+
recall = recall_score(expected_contexts, retrieved_contexts, average='macro', zero_division=1)
|
183 |
+
f1 = f1_score(expected_contexts, retrieved_contexts, average='macro')
|
184 |
+
|
185 |
+
print(f"Retrieval Precision: {precision}")
|
186 |
+
print(f"Retrieval Recall: {recall}")
|
187 |
+
print(f"Retrieval F1 Score: {f1}")
|
188 |
+
|
189 |
+
# Evaluar la generación de respuestas
|
190 |
+
generated_answers = []
|
191 |
+
for item in test_data:
|
192 |
+
output = llm_chain.run({"context": item["context"], "question": item["question"]})
|
193 |
+
generated_answers.append(output)
|
194 |
+
|
195 |
+
# BLEU Score
|
196 |
+
reference_answers = [[item["expected_answer"].split()] for item in test_data]
|
197 |
+
generated_answers_tokens = [answer.split() for answer in generated_answers]
|
198 |
+
bleu_score = corpus_bleu(reference_answers, generated_answers_tokens)
|
199 |
+
|
200 |
+
print(f"BLEU Score: {bleu_score}")
|
RAG_Datos.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|