Skip to content
Merged
Show file tree
Hide file tree
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
113 changes: 113 additions & 0 deletions agentstack/templates/crewai/tools/agentql_tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import os
import httpx

from pydantic import BaseModel, Field
from typing import Optional, Type

from crewai_tools import BaseTool

from dotenv import load_dotenv
load_dotenv()

QUERY_DATA_ENDPOINT = "https://api.agentql.com/v1/query-data"
API_TIMEOUT_SECONDS = 900

API_KEY = os.getenv("AGENTQL_API_KEY")

class AgentQLQueryDataSchema(BaseModel):
url: str = Field(description="Website URL")
query: Optional[str] = Field(
default=None,
description="""
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.)[]
}
```
"""
)
prompt: Optional[str] = Field(
default=None,
description="Natural language description of the data you want to scrape"
)

class AgentQLQueryDataTool(BaseTool):
name: str = "query_data"
description: str = "Scrape a url with a given AgentQL query or a natural language description of the data you want to scrape."
args_schema: Type[BaseModel] = AgentQLQueryDataSchema

def __init__(self, **kwargs):
super().__init__(**kwargs)

def _run(
self,
url: str,
query: Optional[str] = None,
prompt: Optional[str] = None
) -> dict:
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"]

def createTool(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper()

@createTool
def query_data():
return AgentQLQueryDataTool()
11 changes: 11 additions & 0 deletions agentstack/tools/agentql.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "agentql",
"url": "https://agentql.com/",
"category": "web-retrieval",
"packages": [],
"env": {
"AGENTQL_API_KEY": "..."
},
"tools": ["query_data"],
"cta": "Create your AgentQL API key at https://dev.agentql.com"
}
2 changes: 1 addition & 1 deletion docs/templates/community.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: 'Community Templates'
description: 'Extending templating outside what's in the repo'
description: 'Extending templating outside what is in the repo'
---

The easiest way to create your own templates right now is to host them online.
Expand Down
3 changes: 3 additions & 0 deletions docs/tools/community.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ title: 'Community Tools'
description: 'AgentStack tools from community contributors'
---

## Web Retrieval
- [AgentQL](/tools/tool/agentql)

## Browsing

[//]: # (- [Browserbase](/tools/tool/browserbase))
Expand Down
38 changes: 38 additions & 0 deletions docs/tools/tool/agentql.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
title: AgentQL Web Loader
description: Precise web data extraction for agents
icon: browser
---

AgentQL Web Loader is a tool that Scrape a url with a given AgentQL query or a natural language description of the data you want to scrape.
Create your own AgentQL API key [here](https://dev.agentql.com).

## Description
AgentQL Web Loader is powered by AgentQL, an AI-powered query language for scraping web sites and automating workflows.
If you want to extract data in a precise format, use AgentQL natural language queries under the `query` field to pinpoint data on any web page, including authenticated and dynamically generated content.
Users can define structured data output and apply transforms within queries.
You could also directly describe the data you want to extract under the `prompt` field to let AgentQL Web Loader automatically generate the format and data.

## Installation

```bash
agentstack tools add agentql
```

Set the environment variable

```env
AGENTQL_API_KEY=...
```

## Arguments

The following parameters can be used to customize the `AgentQL Web Loader`'s behavior:

| Argument | Type | Description |
|:---------------|:---------|:-------------------------------------------------------------------------------------------------------------------------------------|
| **url** | `string` | Url of the website to scrape from. |
| **query** | `string` | _Optional_. AgentQL query to scrape the url. Please visit [AgentQL Query Language Introduction](https://docs.agentql.com/agentql-query) for more information. |
| **prompt** | `string` | _Optional_. Natural language description of the data you want to scrape. Either `query` or `prompt` is required. |

If you want to hack our tool, feel free to do so by modifying `src/tools/agentql_tool.py` and reference our documentation for [AgentQL REST API](https://docs.agentql.com/rest-api/api-reference).
5 changes: 5 additions & 0 deletions examples/sentiment_analyser/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
AGENTOPS_API_KEY=...
OPENAI_API_KEY=...

# Tools
AGENTQL_API_KEY=...
164 changes: 164 additions & 0 deletions examples/sentiment_analyser/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

.agentops/
10 changes: 10 additions & 0 deletions examples/sentiment_analyser/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

MIT License

Copyright (c) 2024 Name <Email>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Loading
Loading