Logic Optimization
This commit is contained in:
@@ -1,16 +1,14 @@
|
||||
|
||||
from fastapi import FastAPI, HTTPException, File, UploadFile
|
||||
from fastapi import Query
|
||||
from contextlib import asynccontextmanager
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, Any
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
import sys, os
|
||||
print(os.getcwd())
|
||||
import sys
|
||||
import os
|
||||
|
||||
|
||||
from pathlib import Path
|
||||
script_directory = Path(__file__).resolve().parent.parent
|
||||
sys.path.append(os.path.abspath(script_directory))
|
||||
|
||||
import asyncio
|
||||
import nest_asyncio
|
||||
@@ -18,10 +16,12 @@ from lightrag import LightRAG, QueryParam
|
||||
from lightrag.llm import openai_complete_if_cache, openai_embedding
|
||||
from lightrag.utils import EmbeddingFunc
|
||||
import numpy as np
|
||||
from datetime import datetime
|
||||
|
||||
from lightrag.kg.oracle_impl import OracleDB
|
||||
|
||||
print(os.getcwd())
|
||||
script_directory = Path(__file__).resolve().parent.parent
|
||||
sys.path.append(os.path.abspath(script_directory))
|
||||
|
||||
|
||||
# Apply nest_asyncio to solve event loop issues
|
||||
@@ -48,6 +48,7 @@ print(f"EMBEDDING_MAX_TOKEN_SIZE: {EMBEDDING_MAX_TOKEN_SIZE}")
|
||||
if not os.path.exists(WORKING_DIR):
|
||||
os.mkdir(WORKING_DIR)
|
||||
|
||||
|
||||
async def llm_model_func(
|
||||
prompt, system_prompt=None, history_messages=[], **kwargs
|
||||
) -> str:
|
||||
@@ -77,8 +78,8 @@ async def get_embedding_dim():
|
||||
embedding_dim = embedding.shape[1]
|
||||
return embedding_dim
|
||||
|
||||
async def init():
|
||||
|
||||
async def init():
|
||||
# Detect embedding dimension
|
||||
embedding_dimension = 1024 # await get_embedding_dim()
|
||||
print(f"Detected embedding dimension: {embedding_dimension}")
|
||||
@@ -88,15 +89,15 @@ async def init():
|
||||
# We storage data in unified tables, so we need to set a `workspace` parameter to specify which docs we want to store and query
|
||||
# Below is an example of how to connect to Oracle Autonomous Database on Oracle Cloud
|
||||
|
||||
|
||||
oracle_db = OracleDB(config={
|
||||
oracle_db = OracleDB(
|
||||
config={
|
||||
"user": "",
|
||||
"password": "",
|
||||
"dsn": "",
|
||||
"config_dir": "path_to_config_dir",
|
||||
"wallet_location": "path_to_wallet_location",
|
||||
"wallet_password": "wallet_password",
|
||||
"workspace":"company"
|
||||
"workspace": "company",
|
||||
} # specify which docs you want to store and query
|
||||
)
|
||||
|
||||
@@ -116,7 +117,7 @@ async def init():
|
||||
),
|
||||
graph_storage="OracleGraphStorage",
|
||||
kv_storage="OracleKVStorage",
|
||||
vector_storage="OracleVectorDBStorage"
|
||||
vector_storage="OracleVectorDBStorage",
|
||||
)
|
||||
|
||||
# Setthe KV/vector/graph storage's `db` property, so all operation will use same connection pool
|
||||
@@ -147,9 +148,11 @@ class QueryRequest(BaseModel):
|
||||
only_need_context: bool = False
|
||||
only_need_prompt: bool = False
|
||||
|
||||
|
||||
class DataRequest(BaseModel):
|
||||
limit: int = 100
|
||||
|
||||
|
||||
class InsertRequest(BaseModel):
|
||||
text: str
|
||||
|
||||
@@ -164,6 +167,7 @@ class Response(BaseModel):
|
||||
|
||||
rag = None
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
global rag
|
||||
@@ -172,7 +176,10 @@ async def lifespan(app: FastAPI):
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="LightRAG API", description="API for RAG operations",lifespan=lifespan)
|
||||
app = FastAPI(
|
||||
title="LightRAG API", description="API for RAG operations", lifespan=lifespan
|
||||
)
|
||||
|
||||
|
||||
@app.post("/query", response_model=Response)
|
||||
async def query_endpoint(request: QueryRequest):
|
||||
@@ -188,7 +195,7 @@ async def query_endpoint(request: QueryRequest):
|
||||
mode=request.mode,
|
||||
only_need_context=request.only_need_context,
|
||||
only_need_prompt=request.only_need_prompt,
|
||||
top_k=top_k
|
||||
top_k=top_k,
|
||||
),
|
||||
)
|
||||
return Response(status="success", data=result)
|
||||
|
@@ -97,7 +97,6 @@ async def main():
|
||||
graph_storage="OracleGraphStorage",
|
||||
kv_storage="OracleKVStorage",
|
||||
vector_storage="OracleVectorDBStorage",
|
||||
|
||||
addon_params={"example_number": 1, "language": "Simplfied Chinese"},
|
||||
)
|
||||
|
||||
|
@@ -114,7 +114,9 @@ class OracleDB:
|
||||
|
||||
logger.info("Finished check all tables in Oracle database")
|
||||
|
||||
async def query(self, sql: str, multirows: bool = False) -> Union[dict, None]:
|
||||
async def query(
|
||||
self, sql: str, params: dict = None, multirows: bool = False
|
||||
) -> Union[dict, None]:
|
||||
async with self.pool.acquire() as connection:
|
||||
connection.inputtypehandler = self.input_type_handler
|
||||
connection.outputtypehandler = self.output_type_handler
|
||||
@@ -256,7 +258,7 @@ class OracleKVStorage(BaseKVStorage):
|
||||
item["__vector__"],
|
||||
]
|
||||
# print(merge_sql)
|
||||
await self.db.execute(merge_sql, data)
|
||||
await self.db.execute(merge_sql, values)
|
||||
|
||||
if self.namespace == "full_docs":
|
||||
for k, v in self._data.items():
|
||||
@@ -266,7 +268,7 @@ class OracleKVStorage(BaseKVStorage):
|
||||
)
|
||||
values = [k, self._data[k]["content"], self.db.workspace]
|
||||
# print(merge_sql)
|
||||
await self.db.execute(merge_sql, data)
|
||||
await self.db.execute(merge_sql, values)
|
||||
return left_data
|
||||
|
||||
async def index_done_callback(self):
|
||||
|
@@ -70,8 +70,8 @@ async def openai_complete_if_cache(
|
||||
model=model, messages=messages, **kwargs
|
||||
)
|
||||
content = response.choices[0].message.content
|
||||
if r'\u' in content:
|
||||
content = content.encode('utf-8').decode('unicode_escape')
|
||||
if r"\u" in content:
|
||||
content = content.encode("utf-8").decode("unicode_escape")
|
||||
print(content)
|
||||
if hashing_kv is not None:
|
||||
await hashing_kv.upsert(
|
||||
@@ -542,7 +542,7 @@ async def openai_embedding(
|
||||
texts: list[str],
|
||||
model: str = "text-embedding-3-small",
|
||||
base_url: str = None,
|
||||
api_key: str = None
|
||||
api_key: str = None,
|
||||
) -> np.ndarray:
|
||||
if api_key:
|
||||
os.environ["OPENAI_API_KEY"] = api_key
|
||||
|
@@ -249,10 +249,14 @@ async def extract_entities(
|
||||
|
||||
ordered_chunks = list(chunks.items())
|
||||
# add language and example number params to prompt
|
||||
language = global_config["addon_params"].get("language",PROMPTS["DEFAULT_LANGUAGE"])
|
||||
language = global_config["addon_params"].get(
|
||||
"language", PROMPTS["DEFAULT_LANGUAGE"]
|
||||
)
|
||||
example_number = global_config["addon_params"].get("example_number", None)
|
||||
if example_number and example_number < len(PROMPTS["entity_extraction_examples"]):
|
||||
examples="\n".join(PROMPTS["entity_extraction_examples"][:int(example_number)])
|
||||
examples = "\n".join(
|
||||
PROMPTS["entity_extraction_examples"][: int(example_number)]
|
||||
)
|
||||
else:
|
||||
examples = "\n".join(PROMPTS["entity_extraction_examples"])
|
||||
|
||||
@@ -263,7 +267,8 @@ async def extract_entities(
|
||||
completion_delimiter=PROMPTS["DEFAULT_COMPLETION_DELIMITER"],
|
||||
entity_types=",".join(PROMPTS["DEFAULT_ENTITY_TYPES"]),
|
||||
examples=examples,
|
||||
language=language)
|
||||
language=language,
|
||||
)
|
||||
|
||||
continue_prompt = PROMPTS["entiti_continue_extraction"]
|
||||
if_loop_prompt = PROMPTS["entiti_if_loop_extraction"]
|
||||
@@ -396,6 +401,7 @@ async def extract_entities(
|
||||
|
||||
return knowledge_graph_inst
|
||||
|
||||
|
||||
async def kg_query(
|
||||
query,
|
||||
knowledge_graph_inst: BaseGraphStorage,
|
||||
@@ -408,7 +414,9 @@ async def kg_query(
|
||||
context = None
|
||||
example_number = global_config["addon_params"].get("example_number", None)
|
||||
if example_number and example_number < len(PROMPTS["keywords_extraction_examples"]):
|
||||
examples = "\n".join(PROMPTS["keywords_extraction_examples"][:int(example_number)])
|
||||
examples = "\n".join(
|
||||
PROMPTS["keywords_extraction_examples"][: int(example_number)]
|
||||
)
|
||||
else:
|
||||
examples = "\n".join(PROMPTS["keywords_extraction_examples"])
|
||||
|
||||
@@ -422,7 +430,7 @@ async def kg_query(
|
||||
kw_prompt_temp = PROMPTS["keywords_extraction"]
|
||||
kw_prompt = kw_prompt_temp.format(query=query, examples=examples)
|
||||
result = await use_model_func(kw_prompt)
|
||||
logger.info(f"kw_prompt result:")
|
||||
logger.info("kw_prompt result:")
|
||||
print(result)
|
||||
try:
|
||||
json_text = locate_json_string_body_from_string(result)
|
||||
@@ -500,40 +508,68 @@ async def _build_query_context(
|
||||
ll_kewwords, hl_keywrds = query[0], query[1]
|
||||
if query_param.mode in ["local", "hybrid"]:
|
||||
if ll_kewwords == "":
|
||||
ll_entities_context,ll_relations_context,ll_text_units_context = "","",""
|
||||
warnings.warn("Low Level context is None. Return empty Low entity/relationship/source")
|
||||
ll_entities_context, ll_relations_context, ll_text_units_context = (
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
)
|
||||
warnings.warn(
|
||||
"Low Level context is None. Return empty Low entity/relationship/source"
|
||||
)
|
||||
query_param.mode = "global"
|
||||
else:
|
||||
ll_entities_context,ll_relations_context,ll_text_units_context = await _get_node_data(
|
||||
(
|
||||
ll_entities_context,
|
||||
ll_relations_context,
|
||||
ll_text_units_context,
|
||||
) = await _get_node_data(
|
||||
ll_kewwords,
|
||||
knowledge_graph_inst,
|
||||
entities_vdb,
|
||||
text_chunks_db,
|
||||
query_param
|
||||
query_param,
|
||||
)
|
||||
if query_param.mode in ["global", "hybrid"]:
|
||||
if hl_keywrds == "":
|
||||
hl_entities_context,hl_relations_context,hl_text_units_context = "","",""
|
||||
warnings.warn("High Level context is None. Return empty High entity/relationship/source")
|
||||
hl_entities_context, hl_relations_context, hl_text_units_context = (
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
)
|
||||
warnings.warn(
|
||||
"High Level context is None. Return empty High entity/relationship/source"
|
||||
)
|
||||
query_param.mode = "local"
|
||||
else:
|
||||
hl_entities_context,hl_relations_context,hl_text_units_context = await _get_edge_data(
|
||||
(
|
||||
hl_entities_context,
|
||||
hl_relations_context,
|
||||
hl_text_units_context,
|
||||
) = await _get_edge_data(
|
||||
hl_keywrds,
|
||||
knowledge_graph_inst,
|
||||
relationships_vdb,
|
||||
text_chunks_db,
|
||||
query_param
|
||||
query_param,
|
||||
)
|
||||
if query_param.mode == 'hybrid':
|
||||
if query_param.mode == "hybrid":
|
||||
entities_context, relations_context, text_units_context = combine_contexts(
|
||||
[hl_entities_context, ll_entities_context],
|
||||
[hl_relations_context, ll_relations_context],
|
||||
[hl_text_units_context,ll_text_units_context]
|
||||
[hl_text_units_context, ll_text_units_context],
|
||||
)
|
||||
elif query_param.mode == "local":
|
||||
entities_context, relations_context, text_units_context = (
|
||||
ll_entities_context,
|
||||
ll_relations_context,
|
||||
ll_text_units_context,
|
||||
)
|
||||
elif query_param.mode == "global":
|
||||
entities_context, relations_context, text_units_context = (
|
||||
hl_entities_context,
|
||||
hl_relations_context,
|
||||
hl_text_units_context,
|
||||
)
|
||||
elif query_param.mode == 'local':
|
||||
entities_context,relations_context,text_units_context = ll_entities_context,ll_relations_context,ll_text_units_context
|
||||
elif query_param.mode == 'global':
|
||||
entities_context,relations_context,text_units_context = hl_entities_context,hl_relations_context,hl_text_units_context
|
||||
return f"""
|
||||
# -----Entities-----
|
||||
# ```csv
|
||||
@@ -550,7 +586,6 @@ async def _build_query_context(
|
||||
# """
|
||||
|
||||
|
||||
|
||||
async def _get_node_data(
|
||||
query,
|
||||
knowledge_graph_inst: BaseGraphStorage,
|
||||
@@ -824,7 +859,6 @@ async def _get_edge_data(
|
||||
return entities_context, relations_context, text_units_context
|
||||
|
||||
|
||||
|
||||
async def _find_most_related_entities_from_relationships(
|
||||
edge_datas: list[dict],
|
||||
query_param: QueryParam,
|
||||
|
@@ -121,10 +121,12 @@ Output:
|
||||
("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Humanity's Response"{tuple_delimiter}"Alex and his team are the key figures in Humanity's Response to the unknown intelligence."{tuple_delimiter}"collective action, cosmic significance"{tuple_delimiter}8){record_delimiter}
|
||||
("relationship"{tuple_delimiter}"Control"{tuple_delimiter}"Intelligence"{tuple_delimiter}"The concept of Control is challenged by the Intelligence that writes its own rules."{tuple_delimiter}"power dynamics, autonomy"{tuple_delimiter}7){record_delimiter}
|
||||
("content_keywords"{tuple_delimiter}"first contact, control, communication, cosmic significance"){completion_delimiter}
|
||||
#############################"""
|
||||
#############################""",
|
||||
]
|
||||
|
||||
PROMPTS["summarize_entity_descriptions"] = """You are a helpful assistant responsible for generating a comprehensive summary of the data provided below.
|
||||
PROMPTS[
|
||||
"summarize_entity_descriptions"
|
||||
] = """You are a helpful assistant responsible for generating a comprehensive summary of the data provided below.
|
||||
Given one or two entities, and a list of descriptions, all related to the same entity or group of entities.
|
||||
Please concatenate all of these into a single, comprehensive description. Make sure to include information collected from all the descriptions.
|
||||
If the provided descriptions are contradictory, please resolve the contradictions and provide a single, coherent summary.
|
||||
@@ -139,10 +141,14 @@ Description List: {description_list}
|
||||
Output:
|
||||
"""
|
||||
|
||||
PROMPTS["entiti_continue_extraction"] = """MANY entities were missed in the last extraction. Add them below using the same format:
|
||||
PROMPTS[
|
||||
"entiti_continue_extraction"
|
||||
] = """MANY entities were missed in the last extraction. Add them below using the same format:
|
||||
"""
|
||||
|
||||
PROMPTS["entiti_if_loop_extraction"] = """It appears some entities may have still been missed. Answer YES | NO if there are still entities that need to be added.
|
||||
PROMPTS[
|
||||
"entiti_if_loop_extraction"
|
||||
] = """It appears some entities may have still been missed. Answer YES | NO if there are still entities that need to be added.
|
||||
"""
|
||||
|
||||
PROMPTS["fail_response"] = "Sorry, I'm not able to provide an answer to that question."
|
||||
@@ -230,7 +236,7 @@ Output:
|
||||
"high_level_keywords": ["Education", "Poverty reduction", "Socioeconomic development"],
|
||||
"low_level_keywords": ["School access", "Literacy rates", "Job training", "Income inequality"]
|
||||
}}
|
||||
#############################"""
|
||||
#############################""",
|
||||
]
|
||||
|
||||
|
||||
|
@@ -56,7 +56,8 @@ def locate_json_string_body_from_string(content: str) -> Union[str, None]:
|
||||
maybe_json_str = maybe_json_str.replace("'", '"')
|
||||
json.loads(maybe_json_str)
|
||||
return maybe_json_str
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
# try:
|
||||
# content = (
|
||||
# content.replace(kw_prompt[:-1], "")
|
||||
|
Reference in New Issue
Block a user