Created
December 12, 2025 19:49
-
-
Save JoaquinRuiz/e92bbf50be2dffd078b57febb3d961b2 to your computer and use it in GitHub Desktop.
RAG Local con Ollama y Python: Crea tu propio ChatGPT privado (Código del Tutorial de Youtube) https://youtu.be/sj1yzbXVXM0?si=xgB6NVUKMmESCQmW
This file contains hidden or 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
| import os | |
| import bs4 | |
| from langchain_community.document_loaders import WebBaseLoader | |
| from langchain_community.vectorstores import Chroma | |
| from langchain_ollama import OllamaEmbeddings | |
| from langchain_ollama import OllamaLLM | |
| from langchain_text_splitters import RecursiveCharacterTextSplitter | |
| # defino user agent para evitar bloqueos | |
| os.environ["USER_AGENT"] = "Mañobot/1.0" | |
| # 1 cargo documento | |
| loader = WebBaseLoader( | |
| web_paths=("https://es.wikipedia.org/wiki/Inteligencia_artificial",), | |
| bs_kwargs=dict(parse_only=bs4.SoupStrainer(id="bodyContent")) | |
| ) | |
| docs = loader.load() | |
| # 2 divido documento | |
| text_splitter = RecursiveCharacterTextSplitter(chunk_size = 1000, chunk_overlap = 200) | |
| splits = text_splitter.split_documents(docs) | |
| # 3 creo bd vectorial | |
| vectorstore = Chroma.from_documents( | |
| documents = splits, | |
| embedding = OllamaEmbeddings(model="llama3.1:8b") | |
| ) | |
| # 4 pregutnamos | |
| def rag_chat(question): | |
| print(f"\n Pregunta: {question}") | |
| # buscamos 3 fragmentos relevantes | |
| retriever = vectorstore.as_retriever(search_kwargs={"k": 3}) | |
| relevant_docs = retriever.invoke(question) | |
| context = "\n".join([doc.page_content for doc in relevant_docs]) | |
| prompt = f"""Eres un asistente experto. Usa SOLO el siguiente contexto para responder a la pregunta. | |
| Si no sabes la respuesta, di que no lo sabes. | |
| Contexto: {context} | |
| Pregunta: {question} | |
| Respuesta:""" | |
| # generamos respuesta con Ollama | |
| llm = OllamaLLM(model="llama3.1:8b") | |
| return llm.invoke(prompt) | |
| respuesta = rag_chat("¿Cuales son los riesgos de la Inteligencia Artificial?") | |
| print(respuesta) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank's