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

agent sync actions #3

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion .github/workflows/push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ jobs:
TAG="${GITHUB_REF##*/}"
IS_SEMANTIC_TAG=$(echo "$TAG" | grep -q '^v\?[0-9]\+\.[0-9]\+\.[0-9]\+$' && echo true || echo false)
echo "is_semantic_tag=$IS_SEMANTIC_TAG" | tee -a $GITHUB_OUTPUT
echo "app_image_tag=$TAG" | tee -a $GITHUB_OUTPUT
echo "app_image_tag=$TAG-${{ github.run_id }}" | tee -a $GITHUB_OUTPUT

- name: Deploy-Ready check
id: deploy_ready
Expand Down
2 changes: 2 additions & 0 deletions flake8.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
[flake8]
extend-ignore = E203
exclude =
.git,
.venv,
__pycache__,
tests,
example
Expand Down
149 changes: 145 additions & 4 deletions src/component.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import csv
import json
import logging
import os
import shutil
Expand All @@ -8,7 +9,7 @@
from os import mkdir, path

from keboola.component.base import ComponentBase, sync_action
from keboola.component.dao import SupportedDataTypes, BaseType, ColumnDefinition
from keboola.component.dao import BaseType, ColumnDefinition, SupportedDataTypes
from keboola.component.exceptions import UserException
from keboola.component.sync_actions import MessageType, SelectElement, ValidationResult
from keboola.utils.header_normalizer import NormalizerStrategy, get_normalizer
Expand Down Expand Up @@ -60,6 +61,115 @@

DEFAULT_LOGIN_METHOD = "security_token"

# the listSkills response shall be generated based on user config in a very near future,
# so I just hardcoded it here for now
LIST_SKILLS_STATIC_RESPONSE = [
{
"name": "Get Salesforce contacts",
"description": "Returns list of Salesforce contacts.",
"parameters": [
{
"name": "action",
"type": "string",
"required": True,
"enum": ["runSkill"],
},
{
"name": "parameters",
"type": "object",
"required": True,
"parameters": {
"name": "configData",
"type": "object",
"required": True,
"parameters": [
{
"name": "object",
"type": "string",
"required": True,
"enum": ["Contact"],
"description": "String identifer of the agent skill to run.",
},
],
},
},
],
"response": {
"type": "object",
"properties": {
"status": {
"title": "Response status",
"type": "string",
"enum": ["ok", "error"],
},
"number_of_records": {
"title": "Number of records in the response",
"type": "integer",
},
"records": {
"title": "Salesforce records",
"type": "array",
"items": {
"type": "object",
},
},
},
},
},
{
"name": "Get Salesforce reports",
"description": "Returns list of Salesforce reports.",
"parameters": [
{
"name": "action",
"type": "string",
"required": True,
"enum": ["runSkill"],
},
{
"name": "parameters",
"type": "object",
"required": True,
"parameters": {
"name": "configData",
"type": "object",
"required": True,
"parameters": [
{
"name": "object",
"type": "string",
"required": True,
"enum": ["Report"],
"description": "String identifer of the agent skill to run.",
},
],
},
},
],
"response": {
"type": "object",
"properties": {
"status": {
"title": "Response status",
"type": "string",
"enum": ["ok", "error"],
},
"number_of_records": {
"title": "Number of records in the response",
"type": "integer",
},
"records": {
"title": "Salesforce records",
"type": "array",
"items": {
"type": "object",
},
},
},
},
},
]


class LoginType(str, Enum):
SECURITY_TOKEN_LOGIN = "security_token"
Expand All @@ -86,13 +196,16 @@ class Component(ComponentBase):
def __init__(self):
super().__init__()

def run(self):
def run(self, return_json=False):
self.validate_configuration_parameters(REQUIRED_PARAMETERS)
self.validate_image_parameters(REQUIRED_IMAGE_PARS)

start_run_time = str(datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"))

params = self.configuration.parameters

logging.info("%s", json.dumps(params, indent=4))

loading_options = params.get(KEY_LOADING_OPTIONS, {})

bucket_name = params.get(KEY_BUCKET_NAME, self.get_bucket_name())
Expand Down Expand Up @@ -130,6 +243,17 @@ def run(self):
logging.debug([result for result in results])
logging.info(f"Downloaded {total_records} records in total")

if return_json:
for result in results:
if "file" not in result:
result["status"] = "fileError"
continue
result["records"] = list(self._csv_result_to_dict(result.pop("file")))
result["status"] = "ok"
with open("response.json", "w") as f:
json.dump(results, f)
return results

# remove headers and get columns
output_columns = self._fix_header_from_csv(results)
output_columns = self.normalize_column_names(output_columns)
Expand Down Expand Up @@ -177,6 +301,12 @@ def _fix_header_from_csv(results: list[dict]) -> list[str]:
os.replace(temp_file_path, result_file_path)
return expected_header

def _csv_result_to_dict(self, filename: str):
with open(filename) as f:
reader = csv.DictReader(f)
for row in reader:
yield row

def set_proxy(self) -> None:
"""Sets proxy if defined"""
proxy_config = self.configuration.parameters.get(KEY_PROXY, {})
Expand Down Expand Up @@ -419,9 +549,9 @@ def _get_login_method(self) -> LoginType:
@staticmethod
def process_salesforce_domain(url):
if url.startswith("http://"):
url = url[len("http://"):]
url = url[len("http://") :]
if url.startswith("https://"):
url = url[len("https://"):]
url = url[len("https://") :]
if url.endswith(".salesforce.com"):
url = url[: -len(".salesforce.com")]

Expand Down Expand Up @@ -619,6 +749,17 @@ def load_possible_primary_keys(self) -> list[SelectElement]:
else:
raise UserException(f"Invalid {KEY_QUERY_TYPE}")

@sync_action("runSkill")
def sync_run_component(self):
"""
Run the component as a skill for an AI agent
"""
return self.run(return_json=True)

@sync_action("listSkills")
def list_skills(self):
return LIST_SKILLS_STATIC_RESPONSE

def _get_object_name_from_custom_query(self) -> str:
params = self.configuration.parameters
salesforce_client = self.get_salesforce_client(params)
Expand Down