|
| 1 | +import os |
| 2 | +import logging |
| 3 | +import ollama |
| 4 | +import numpy as np |
| 5 | +from openai import AsyncOpenAI |
| 6 | +from nano_graphrag import GraphRAG, QueryParam |
| 7 | +from nano_graphrag import GraphRAG, QueryParam |
| 8 | +from nano_graphrag.base import BaseKVStorage |
| 9 | +from nano_graphrag._utils import compute_args_hash, wrap_embedding_func_with_attrs |
| 10 | + |
| 11 | +logging.basicConfig(level=logging.WARNING) |
| 12 | +logging.getLogger("nano-graphrag").setLevel(logging.INFO) |
| 13 | + |
| 14 | +# Assumed llm model settings |
| 15 | +LLM_BASE_URL = "https://your.api.url" |
| 16 | +LLM_API_KEY = "your_api_key" |
| 17 | +MODEL = "your_model_name" |
| 18 | + |
| 19 | +# Assumed embedding model settings |
| 20 | +EMBEDDING_MODEL = "nomic-embed-text" |
| 21 | +EMBEDDING_MODEL_DIM = 768 |
| 22 | +EMBEDDING_MODEL_MAX_TOKENS = 8192 |
| 23 | + |
| 24 | + |
| 25 | +async def llm_model_if_cache( |
| 26 | + prompt, system_prompt=None, history_messages=[], **kwargs |
| 27 | +) -> str: |
| 28 | + openai_async_client = AsyncOpenAI( |
| 29 | + api_key=LLM_API_KEY, base_url=LLM_BASE_URL |
| 30 | + ) |
| 31 | + messages = [] |
| 32 | + if system_prompt: |
| 33 | + messages.append({"role": "system", "content": system_prompt}) |
| 34 | + |
| 35 | + # Get the cached response if having------------------- |
| 36 | + hashing_kv: BaseKVStorage = kwargs.pop("hashing_kv", None) |
| 37 | + messages.extend(history_messages) |
| 38 | + messages.append({"role": "user", "content": prompt}) |
| 39 | + if hashing_kv is not None: |
| 40 | + args_hash = compute_args_hash(MODEL, messages) |
| 41 | + if_cache_return = await hashing_kv.get_by_id(args_hash) |
| 42 | + if if_cache_return is not None: |
| 43 | + return if_cache_return["return"] |
| 44 | + # ----------------------------------------------------- |
| 45 | + |
| 46 | + response = await openai_async_client.chat.completions.create( |
| 47 | + model=MODEL, messages=messages, **kwargs |
| 48 | + ) |
| 49 | + |
| 50 | + # Cache the response if having------------------- |
| 51 | + if hashing_kv is not None: |
| 52 | + await hashing_kv.upsert( |
| 53 | + {args_hash: {"return": response.choices[0].message.content, "model": MODEL}} |
| 54 | + ) |
| 55 | + # ----------------------------------------------------- |
| 56 | + return response.choices[0].message.content |
| 57 | + |
| 58 | + |
| 59 | +def remove_if_exist(file): |
| 60 | + if os.path.exists(file): |
| 61 | + os.remove(file) |
| 62 | + |
| 63 | + |
| 64 | +WORKING_DIR = "./nano_graphrag_cache_llm_TEST" |
| 65 | + |
| 66 | + |
| 67 | +def query(): |
| 68 | + rag = GraphRAG( |
| 69 | + working_dir=WORKING_DIR, |
| 70 | + best_model_func=llm_model_if_cache, |
| 71 | + cheap_model_func=llm_model_if_cache, |
| 72 | + embedding_func=ollama_embedding, |
| 73 | + ) |
| 74 | + print( |
| 75 | + rag.query( |
| 76 | + "What are the top themes in this story?", param=QueryParam(mode="global") |
| 77 | + ) |
| 78 | + ) |
| 79 | + |
| 80 | + |
| 81 | +def insert(): |
| 82 | + from time import time |
| 83 | + |
| 84 | + with open("./tests/mock_data.txt", encoding="utf-8-sig") as f: |
| 85 | + FAKE_TEXT = f.read() |
| 86 | + |
| 87 | + remove_if_exist(f"{WORKING_DIR}/vdb_entities.json") |
| 88 | + remove_if_exist(f"{WORKING_DIR}/kv_store_full_docs.json") |
| 89 | + remove_if_exist(f"{WORKING_DIR}/kv_store_text_chunks.json") |
| 90 | + remove_if_exist(f"{WORKING_DIR}/kv_store_community_reports.json") |
| 91 | + remove_if_exist(f"{WORKING_DIR}/graph_chunk_entity_relation.graphml") |
| 92 | + |
| 93 | + rag = GraphRAG( |
| 94 | + working_dir=WORKING_DIR, |
| 95 | + enable_llm_cache=True, |
| 96 | + best_model_func=llm_model_if_cache, |
| 97 | + cheap_model_func=llm_model_if_cache, |
| 98 | + embedding_func=ollama_embedding, |
| 99 | + ) |
| 100 | + start = time() |
| 101 | + rag.insert(FAKE_TEXT) |
| 102 | + print("indexing time:", time() - start) |
| 103 | + # rag = GraphRAG(working_dir=WORKING_DIR, enable_llm_cache=True) |
| 104 | + # rag.insert(FAKE_TEXT[half_len:]) |
| 105 | + |
| 106 | +# We're using Ollama to generate embeddings for the BGE model |
| 107 | +@wrap_embedding_func_with_attrs( |
| 108 | + embedding_dim= EMBEDDING_MODEL_DIM, |
| 109 | + max_token_size= EMBEDDING_MODEL_MAX_TOKENS, |
| 110 | +) |
| 111 | + |
| 112 | +async def ollama_embedding(texts :list[str]) -> np.ndarray: |
| 113 | + embed_text = [] |
| 114 | + for text in texts: |
| 115 | + data = ollama.embeddings(model=EMBEDDING_MODEL, prompt=text) |
| 116 | + embed_text.append(data["embedding"]) |
| 117 | + |
| 118 | + return embed_text |
| 119 | + |
| 120 | +if __name__ == "__main__": |
| 121 | + insert() |
| 122 | + query() |
0 commit comments