Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(AstraDBCQL): resolve partition key error and improve AstraDB CQL component handling #5527

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 55 additions & 20 deletions src/backend/base/langflow/components/tools/astradb_cql.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import urllib
from http import HTTPStatus
from typing import Any

Expand Down Expand Up @@ -91,51 +90,83 @@
]

def astra_rest(self, args):
headers = {"Accept": "application/json", "X-Cassandra-Token": f"{self.token}"}
astra_url = f"{self.api_endpoint}/api/rest/v2/keyspaces/{self.keyspace}/{self.table_name}/"
key = []
headers = {
"Accept": "application/json",
"X-Cassandra-Token": f"{self.token}",
"Content-Type": "application/json",
}

# Partition keys are mandatory
key = [self.partition_keys[k] for k in self.partition_keys]
astra_url = f"{self.api_endpoint}/api/rest/v2/keyspaces/{self.keyspace}/{self.table_name}/rows"

# Clustering keys are optional
for k in self.clustering_keys:
if k in args:
key.append(args[k])
elif self.static_filters[k] is not None:
key.append(self.static_filters[k])
where_clauses = []

url = f"{astra_url}{'/'.join(key)}?page-size={self.number_of_results}"
for key in self.partition_keys:
if key in args:
where_clauses.append({"column": key, "operator": "EQ", "value": args[key]})
elif key in self.static_filters:
where_clauses.append({"column": key, "operator": "EQ", "value": self.static_filters[key]})

if self.projection_fields != "*":
url += f"&fields={urllib.parse.quote(self.projection_fields.replace(' ', ''))}"
for key in self.clustering_keys:
clean_key = key[1:] if key.startswith("!") else key
if clean_key in args and args[clean_key] is not None:
where_clauses.append({"column": clean_key, "operator": "EQ", "value": args[clean_key]})
elif clean_key in self.static_filters:
where_clauses.append(
{
"column": clean_key,
"operator": "EQ",
"value": self.static_filters[clean_key],
}
)

params = {
"page-size": self.number_of_results,
"where": {"filters": where_clauses},
}

res = requests.request("GET", url=url, headers=headers, timeout=10)
if self.projection_fields != "*":
params["fields"] = [field.strip() for field in self.projection_fields.split(",")]

res = requests.request(
"GET",
url=astra_url,
headers=headers,
params={"raw": "true"},
json=params,
timeout=10,
)

if int(res.status_code) >= HTTPStatus.BAD_REQUEST:
return res.text

try:
res_data = res.json()
return res_data["data"]
if isinstance(res_data, dict) and "data" in res_data:
return res_data["data"]
if isinstance(res_data, list):
return res_data
if isinstance(res_data, dict):
return [res_data]
return []

Check failure on line 150 in src/backend/base/langflow/components/tools/astradb_cql.py

View workflow job for this annotation

GitHub Actions / Ruff Style Check (3.12)

Ruff (TRY300)

src/backend/base/langflow/components/tools/astradb_cql.py:150:13: TRY300 Consider moving this statement to an `else` block
except ValueError:
return res.status_code

def create_args_schema(self) -> dict[str, BaseModel]:
args: dict[str, tuple[Any, Field]] = {}

for key in self.partition_keys:
# Partition keys are mandatory is it doesn't have a static filter
if key not in self.static_filters:
args[key] = (str, Field(description=self.partition_keys[key]))

for key in self.clustering_keys:
# Partition keys are mandatory if has the exclamation mark and doesn't have a static filter
if key not in self.static_filters:
if key.startswith("!"): # Mandatory
args[key[1:]] = (str, Field(description=self.clustering_keys[key]))
else: # Optional
args[key] = (str | None, Field(description=self.clustering_keys[key], default=None))
args[key] = (
str | None,
Field(description=self.clustering_keys[key], default=None),
)

model = create_model("ToolInput", **args, __base__=BaseModel)
return {"ToolInput": model}
Expand Down Expand Up @@ -172,6 +203,10 @@

def run_model(self, **args) -> Data | list[Data]:
results = self.astra_rest(args)

if isinstance(results, str):
raise ValueError(f"Error from Astra DB: {results}")

Check failure on line 208 in src/backend/base/langflow/components/tools/astradb_cql.py

View workflow job for this annotation

GitHub Actions / Ruff Style Check (3.12)

Ruff (TRY004)

src/backend/base/langflow/components/tools/astradb_cql.py:208:13: TRY004 Prefer `TypeError` exception for invalid type

Check failure on line 208 in src/backend/base/langflow/components/tools/astradb_cql.py

View workflow job for this annotation

GitHub Actions / Ruff Style Check (3.12)

Ruff (TRY003)

src/backend/base/langflow/components/tools/astradb_cql.py:208:19: TRY003 Avoid specifying long messages outside the exception class

Check failure on line 208 in src/backend/base/langflow/components/tools/astradb_cql.py

View workflow job for this annotation

GitHub Actions / Ruff Style Check (3.12)

Ruff (EM102)

src/backend/base/langflow/components/tools/astradb_cql.py:208:30: EM102 Exception must not use an f-string literal, assign to variable first

data: list[Data] = [Data(data=doc) for doc in results]
self.status = data
return results
Loading