{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Tutorial from https://www.datacamp.com/tutorial/knowledge-graph-rag" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Chunk 1:\n", "Sarah is an employee at prismaticAI, a leading technology company based in Westside Valley. She has been working there for the past three years as a software engineer.\n", "\n", "Chunk 2:\n", "Michael is also an employee at prismaticAI, where he works as a data scientist. He joined the company two years ago after completing his graduate studies.\n", "\n", "Chunk 3:\n", "prismaticAI is a well-known technology company that specializes in developing cutting-edge software solutions and artificial intelligence applications. The company has a diverse workforce of talented\n", "\n", "Chunk 4:\n", "of talented individuals from various backgrounds.\n", "\n", "Chunk 5:\n", "Both Sarah and Michael are highly skilled professionals who contribute significantly to prismaticAI's success. They work closely with their respective teams to develop innovative products and\n", "\n", "Chunk 6:\n", "products and services that meet the evolving needs of the company's clients.\n" ] } ], "source": [ "from langchain.schema import Document\n", "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", "\n", "# Your raw text\n", "text = \"\"\"Sarah is an employee at prismaticAI, a leading technology company based in Westside Valley. She has been working there for the past three years as a software engineer.\n", "Michael is also an employee at prismaticAI, where he works as a data scientist. He joined the company two years ago after completing his graduate studies.\n", "prismaticAI is a well-known technology company that specializes in developing cutting-edge software solutions and artificial intelligence applications. The company has a diverse workforce of talented individuals from various backgrounds.\n", "Both Sarah and Michael are highly skilled professionals who contribute significantly to prismaticAI's success. They work closely with their respective teams to develop innovative products and services that meet the evolving needs of the company's clients.\"\"\"\n", "\n", "# Wrap in a Document object\n", "documents = [Document(page_content=text)]\n", "\n", "# Split\n", "text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20)\n", "texts = text_splitter.split_documents(documents)\n", "\n", "# Show result\n", "for i, t in enumerate(texts):\n", " print(f\"\\nChunk {i+1}:\\n{t.page_content}\")\n" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/leandratejedor/miniforge3/envs/agents-py11/lib/python3.11/site-packages/langchain_openai/chat_models/base.py:1660: UserWarning: Cannot use method='json_schema' with model gpt-3.5-turbo since it doesn't support OpenAI's Structured Output API. You can see supported models here: https://platform.openai.com/docs/guides/structured-outputs#supported-models. To fix this warning, set `method='function_calling'. Overriding to method='function_calling'.\n", " warnings.warn(\n" ] } ], "source": [ "from langchain_openai import ChatOpenAI\n", "from langchain_experimental.graph_transformers import LLMGraphTransformer\n", "\n", "import os\n", "from dotenv import load_dotenv\n", "load_dotenv()\n", "\n", "\n", "# Initialize LLM\n", "llm = ChatOpenAI(temperature=0)\n", "\n", "# Extract Knowledge Graph\n", "llm_transformer = LLMGraphTransformer(llm=llm)\n", "graph_documents = llm_transformer.convert_to_graph_documents(texts)" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "LLM Response: content='Hello! Yes, I am functioning properly. How can I assist you today?' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 14, 'total_tokens': 31, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'id': 'chatcmpl-BMkHf9pV37IhPnp53mgu9Aqa2yRmm', 'finish_reason': 'stop', 'logprobs': None} id='run-1b031a01-d933-457f-bfe7-2e05110e9dbf-0' usage_metadata={'input_tokens': 14, 'output_tokens': 17, 'total_tokens': 31, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n", "Test successful! Your LLM is running correctly.\n" ] } ], "source": [ "try:\n", " response = llm.invoke(\"Hello, are you working properly?\")\n", " print(\"LLM Response:\", response)\n", " print(\"Test successful! Your LLM is running correctly.\")\n", "except Exception as e:\n", " print(\"Error connecting to LLM:\", e)\n", " print(\"Check your API key and network connection.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from langchain_community.graphs import Neo4jGraph\n", "\n", "# Store Knowledge Graph in Neo4j\n", "graph_store = Neo4jGraph(refresh_schema=False)\n", "#graph_store.add_graph_documents(graph_documents)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "graph_store.refresh_schema()\n" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [], "source": [ "from langchain.chains import GraphCypherQAChain\n", "from langchain.prompts import PromptTemplate\n", "\n", "\n", "qa_template = \"\"\"\n", "Based on the context: {context}\n", "Answer the question: {question}\n", "\"\"\"\n", "qa_prompt = PromptTemplate(template=qa_template, input_variables=[\"context\", \"question\"])\n", "\n", "chain = GraphCypherQAChain.from_llm(\n", " graph=graph_store,\n", " cypher_llm=llm,\n", " qa_llm=llm,\n", " qa_prompt=qa_prompt,\n", " #cypher_prompt=CYPHER_GENERATION_PROMPT,\n", " verbose=True,\n", " return_intermediate_steps=True,\n", " allow_dangerous_requests=True\n", ")" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\u001b[1m> Entering new GraphCypherQAChain chain...\u001b[0m\n", "Generated Cypher:\n", "\u001b[32;1m\u001b[1;3mMATCH (p1:Person {id: \"Michael\"})-[:EMPLOYEE]->(o:Organization)<-[:EMPLOYEE]-(p2:Person {id: \"Sarah\"})\n", "RETURN o\u001b[0m\n", "Full Context:\n", "\u001b[32;1m\u001b[1;3m[]\u001b[0m\n", "\n", "\u001b[1m> Finished chain.\u001b[0m\n", "It is not possible to determine if Michael works for the same company as Sarah without more information.\n" ] } ], "source": [ "response = chain.invoke({\"query\": \"Does Michael work for the same company as Sarah?\"})\n", "print(response['result'])\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "agents-py11", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.12" } }, "nbformat": 4, "nbformat_minor": 2 }