Error in custom query #15602
Replies: 3 comments 2 replies
-
The error you're encountering is due to the fact that the To resolve this, you need to define from pydantic import Field
from typing import Any, Dict, Optional, cast
import os
class LoadQuestions(CustomQueryComponent):
_index: Optional[VectorStoreIndex] = Field(default=None, exclude=True)
_dir_name: Optional[str] = Field(default=None, exclude=True)
def __init__(self):
super().__init__()
def _run_component(self, **kwargs) -> Dict[str, Any]:
query_str = kwargs.get('query_str')
table_name = kwargs.get('table_name')
if query_str is None:
raise ValueError("query_str cannot be None")
self._dir_name = table_name.replace("_responses", "") if table_name else "default"
PERSIST_DIR = f"./surveys/{self._dir_name}/RAGFiles/quesindex"
try:
if not os.path.exists(PERSIST_DIR):
reader = SimpleDirectoryReader(f"./surveys/{self._dir_name}")
documents = reader.load_data()
self._index = VectorStoreIndex.from_documents(documents)
self._index.storage_context.persist(persist_dir=PERSIST_DIR)
else:
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
self._index = cast(VectorStoreIndex, load_index_from_storage(storage_context))
# Retrieve relevant nodes for context
vector_retriever = self._index.as_retriever(similarity_top_k=3)
relevant_nodes = vector_retriever.retrieve(query_str)
question_context = ""
if len(relevant_nodes) > 0:
question_context = "\nHere are questions that are relevant to this query\n"
for node in relevant_nodes:
question_context += str(node.get_content()) + "\n"
return {"quesindex": question_context}
except Exception as e:
print(f"Error in LoadQuestions: {str(e)}")
return {"quesindex": ""}
def get_query_engine(self):
if self._index is None:
raise ValueError("Index has not been initialized. Run _run_component first.")
class QuestionQueryEngine(CustomQueryEngine):
def __init__(self, _index):
self._index = _index
def custom_query(self, query_str: str):
# Retrieve relevant nodes
retriever = self._index.as_retriever(similarity_top_k=3)
nodes = retriever.retrieve(query_str)
# Prepare context from retrieved nodes
context = "\n".join([node.get_content() for node in nodes])
# Prepare prompt for the LLM
prompt = f"Based on the following survey questions:\n\n{context}\n\nPlease answer the following question: {query_str}"
# Query LLM
#llm = OpenAI(temperature=0, model="gpt-3.5-turbo")
llm_response = llm.complete(prompt)
# Create and return Response object
return str(llm_response)
return QuestionQueryEngine(self._index)
@property
def _input_keys(self):
return {"query_str", "table_name"}
@property
def _optional_input_keys(self):
return set()
@property
def _output_keys(self):
return {"quesindex"} By defining |
Beta Was this translation helpful? Give feedback.
-
I am trying to access it like this in a function:
I made the changes you suggested but still getting the error |
Beta Was this translation helpful? Give feedback.
-
here is how custom query engine is implemented in llama index. Do you see a reson for the error I continue to get?
|
Beta Was this translation helpful? Give feedback.
-
I have this custom query functions.
Why am I getting the error:
File "/home/runner/surveyanalysis/llama.py", line 141, in _run_component
self._dir_name = table_name.replace("_responses", "") if table_name else "default"
File "/home/runner/surveyanalysis/.pythonlibs/lib/python3.10/site-packages/pydantic/v1/main.py", line 357, in setattr
raise ValueError(f'"{self.class.name}" object has no field "{name}"')
ValueError: "LoadQuestions" object has no field "_dir_name"
Beta Was this translation helpful? Give feedback.
All reactions