-
Notifications
You must be signed in to change notification settings - Fork 215
Expand file tree
/
Copy path__init__.py
More file actions
80 lines (63 loc) · 2.33 KB
/
__init__.py
File metadata and controls
80 lines (63 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import os
import httpx
from typing import Optional
QUERY_DATA_ENDPOINT = "https://api.agentql.com/v1/query-data"
API_TIMEOUT_SECONDS = 900
API_KEY = os.getenv("AGENTQL_API_KEY")
def extract_data(url: str, query: Optional[str], prompt: Optional[str]) -> dict:
"""
url: url of website to scrape
query: described below
prompt: Natural language description of the data you want to scrape
AgentQL query to scrape the url.
Here is a guide on AgentQL query syntax:
Enclose all AgentQL query terms within curly braces `{}`. The following query structure isn't valid because the term "social_media_links" is wrongly enclosed within parenthesis `()`.
```
( # Should be {
social_media_links(The icons that lead to Facebook, Snapchat, etc.)[]
) # Should be }
```
The following query is also invalid since its missing the curly braces `{}`
```
# should include {
social_media_links(The icons that lead to Facebook, Snapchat, etc.)[]
# should include }
```
You can't include new lines in your semantic context. The following query structure isn't valid because the semantic context isn't contained within one line.
```
{
social_media_links(The icons that lead
to Facebook, Snapchat, etc.)[]
}
```
"""
payload = {"url": url, "query": query, "prompt": prompt}
headers = {"X-API-Key": f"{API_KEY}", "Content-Type": "application/json"}
try:
response = httpx.post(
QUERY_DATA_ENDPOINT,
headers=headers,
json=payload,
timeout=API_TIMEOUT_SECONDS,
)
response.raise_for_status()
except httpx.HTTPStatusError as e:
response = e.response
if response.status_code in [401, 403]:
raise ValueError(
"Please, provide a valid API Key. You can create one at https://dev.agentql.com."
) from e
else:
try:
error_json = response.json()
msg = (
error_json["error_info"]
if "error_info" in error_json
else error_json["detail"]
)
except (ValueError, TypeError):
msg = f"HTTP {e}."
raise ValueError(msg) from e
else:
json = response.json()
return json["data"]