salesforce-data-customcode 7.0.0rc5__tar.gz → 7.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/PKG-INFO +1 -1
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/pyproject.toml +1 -1
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/auth.py +72 -13
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/cli.py +21 -6
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/constants.py +4 -3
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/deploy.py +44 -10
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/function/chunking/payload/tests/test.json +33 -0
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/function/example/chunking_with_external_callout/README.md +120 -0
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/function/example/chunking_with_external_callout/entrypoint.py +162 -0
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/function/example/chunking_with_external_callout/external_callout_config.json +11 -0
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/function/example/chunking_with_external_callout/tests/test.json +16 -0
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/function/example/chunking_with_prediction/config.json +3 -0
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/script/examples/external_callout/README.md +169 -0
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/script/examples/external_callout/entrypoint.py +144 -0
- salesforce_data_customcode-7.1.0/src/datacustomcode/templates/script/examples/external_callout/external_callout_config.json +11 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/LICENSE.txt +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/README.md +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/client.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/cmd.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/common_config.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/config.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/config.yaml +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/credentials.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_platform_client.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_platform_config.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_predictions/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_predictions/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_predictions/errors.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_predictions/impl/default.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_predictions/spark_base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_predictions/spark_default.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_predictions/types.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/einstein_predictions_config.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/file/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/file/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/file/path/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/file/path/default.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/function/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/function/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/function/feature_types/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/function/feature_types/chunking.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/function/runtime.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/function_utils.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/cdf.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/reader/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/reader/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/reader/local_deltas.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/reader/query_api.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/reader/sf_cli.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/reader/streaming_seeder.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/reader/utils.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/writer/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/writer/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/writer/csv.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/writer/local_deltas.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/io/writer/print.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/lineage/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/lineage/_worker.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/lineage/capture.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/lineage/tracer.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/default.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/errors.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/spark_base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/spark_default.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/types/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/types/generate_text_request.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/types/generate_text_request_builder.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/types/generate_text_response.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway/types/generate_text_response_builder.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/llm_gateway_config.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/mixin.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/default.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/direct/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/direct/auth.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/direct/credentials.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/direct/transport.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/direct/url_resolver.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/errors.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/spark_base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/spark_default.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/types/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/types/http_method.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/types/http_request.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/types/http_request_builder.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/types/http_response.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential/types/http_response_builder.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/named_credential_config.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/py.typed +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/run.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/scan.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/spark/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/spark/base.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/spark/column_hints.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/spark/default.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/template.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/__init__.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/.devcontainer/devcontainer.json +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/Dockerfile.dependencies +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/README.md +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/build_native_dependencies.sh +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/chunking/payload/config.json +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/chunking/payload/entrypoint.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/chunking/requirements.txt +0 -0
- {salesforce_data_customcode-7.0.0rc5/src/datacustomcode/templates/function/example/chunking_with_llm → salesforce_data_customcode-7.1.0/src/datacustomcode/templates/function/example/chunking_with_external_callout}/config.json +0 -0
- {salesforce_data_customcode-7.0.0rc5/src/datacustomcode/templates/function/example/chunking_with_prediction → salesforce_data_customcode-7.1.0/src/datacustomcode/templates/function/example/chunking_with_llm}/config.json +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/example/chunking_with_llm/entrypoint.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/example/chunking_with_llm/files/chunking_prompt.txt +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/example/chunking_with_llm/tests/test.json +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/example/chunking_with_prediction/entrypoint.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/example/chunking_with_prediction/tests/test.json +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/payload/config.json +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/payload/entrypoint.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/payload/utility.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/requirements-dev.txt +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/function/requirements.txt +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/.devcontainer/devcontainer.json +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/Dockerfile +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/Dockerfile.dependencies +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/README.md +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/account.ipynb +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/build_native_dependencies.sh +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/examples/employee_hierarchy/employee_data.csv +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/examples/employee_hierarchy/entrypoint.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/examples/streaming_deltas/entrypoint.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/jupyterlab.sh +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/payload/config.json +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/payload/entrypoint.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/requirements-dev.txt +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/templates/script/requirements.txt +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/token_provider.py +0 -0
- {salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/version.py +0 -0
{salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/auth.py
RENAMED
|
@@ -12,13 +12,21 @@
|
|
|
12
12
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
13
|
# See the License for the specific language governing permissions and
|
|
14
14
|
# limitations under the License.
|
|
15
|
+
import base64
|
|
16
|
+
import hashlib
|
|
17
|
+
import hmac
|
|
15
18
|
import http.server
|
|
16
19
|
import queue
|
|
20
|
+
import secrets
|
|
17
21
|
import socketserver
|
|
18
22
|
import threading
|
|
19
23
|
import time
|
|
20
24
|
from typing import Any
|
|
21
|
-
from urllib.parse import
|
|
25
|
+
from urllib.parse import (
|
|
26
|
+
parse_qs,
|
|
27
|
+
urlencode,
|
|
28
|
+
urlparse,
|
|
29
|
+
)
|
|
22
30
|
import webbrowser
|
|
23
31
|
|
|
24
32
|
import click
|
|
@@ -28,16 +36,35 @@ import requests
|
|
|
28
36
|
class OAuthCallbackHandler(http.server.SimpleHTTPRequestHandler):
|
|
29
37
|
"""HTTP request handler to capture OAuth callback."""
|
|
30
38
|
|
|
31
|
-
def __init__(self, *args, auth_code_queue=None, **kwargs):
|
|
39
|
+
def __init__(self, *args, auth_code_queue=None, expected_state=None, **kwargs):
|
|
32
40
|
self.auth_code_queue = auth_code_queue
|
|
41
|
+
self.expected_state = expected_state
|
|
33
42
|
super().__init__(*args, **kwargs)
|
|
34
43
|
|
|
44
|
+
def _state_matches(self, query_params: dict) -> bool:
|
|
45
|
+
"""Check the callback's state parameter against the expected value."""
|
|
46
|
+
received = query_params.get("state", [""])[0]
|
|
47
|
+
if not self.expected_state or not received:
|
|
48
|
+
return False
|
|
49
|
+
return hmac.compare_digest(received, self.expected_state)
|
|
50
|
+
|
|
35
51
|
def do_GET(self):
|
|
36
|
-
"""Handle GET request from OAuth callback.
|
|
52
|
+
"""Handle GET request from OAuth callback.
|
|
53
|
+
|
|
54
|
+
Callbacks whose ``state`` does not match are rejected without touching
|
|
55
|
+
the queue, so a forged request can neither inject an authorization code
|
|
56
|
+
nor abort the legitimate login.
|
|
57
|
+
"""
|
|
37
58
|
parsed_path = urlparse(self.path)
|
|
38
59
|
query_params = parse_qs(parsed_path.query)
|
|
39
60
|
|
|
40
|
-
|
|
61
|
+
is_callback = "code" in query_params or "error" in query_params
|
|
62
|
+
if is_callback and not self._state_matches(query_params):
|
|
63
|
+
self.send_response(400)
|
|
64
|
+
self.send_header("Content-type", "text/html")
|
|
65
|
+
self.end_headers()
|
|
66
|
+
self.wfile.write(b"<html><body><h1>Invalid callback</h1></body></html>")
|
|
67
|
+
elif "code" in query_params:
|
|
41
68
|
auth_code = query_params["code"][0]
|
|
42
69
|
self.auth_code_queue.put(auth_code)
|
|
43
70
|
self.send_response(200)
|
|
@@ -70,14 +97,27 @@ class OAuthCallbackHandler(http.server.SimpleHTTPRequestHandler):
|
|
|
70
97
|
"""Suppress default logging."""
|
|
71
98
|
|
|
72
99
|
|
|
100
|
+
def _generate_pkce_pair() -> tuple[str, str]:
|
|
101
|
+
"""Generate a PKCE (RFC 7636) code verifier and its S256 code challenge.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
Tuple of (code_verifier, code_challenge)
|
|
105
|
+
"""
|
|
106
|
+
code_verifier = secrets.token_urlsafe(64)
|
|
107
|
+
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
|
|
108
|
+
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
|
|
109
|
+
return code_verifier, code_challenge
|
|
110
|
+
|
|
111
|
+
|
|
73
112
|
def _run_oauth_callback_server(
|
|
74
|
-
redirect_uri: str, auth_code_queue: "queue.Queue[str]"
|
|
113
|
+
redirect_uri: str, auth_code_queue: "queue.Queue[str]", expected_state: str
|
|
75
114
|
) -> tuple[socketserver.TCPServer, int]:
|
|
76
115
|
"""Start a local HTTP server to catch OAuth callback.
|
|
77
116
|
|
|
78
117
|
Args:
|
|
79
118
|
redirect_uri: The redirect URI configured in the OAuth app
|
|
80
119
|
auth_code_queue: Queue to put the authorization code in
|
|
120
|
+
expected_state: OAuth state value the callback must echo back
|
|
81
121
|
|
|
82
122
|
Returns:
|
|
83
123
|
Tuple of (server instance, actual port number)
|
|
@@ -90,7 +130,12 @@ def _run_oauth_callback_server(
|
|
|
90
130
|
|
|
91
131
|
# Create a custom handler factory
|
|
92
132
|
def handler_factory(*args, **kwargs):
|
|
93
|
-
return OAuthCallbackHandler(
|
|
133
|
+
return OAuthCallbackHandler(
|
|
134
|
+
*args,
|
|
135
|
+
auth_code_queue=auth_code_queue,
|
|
136
|
+
expected_state=expected_state,
|
|
137
|
+
**kwargs,
|
|
138
|
+
)
|
|
94
139
|
|
|
95
140
|
server = socketserver.TCPServer((host, port), handler_factory)
|
|
96
141
|
server.allow_reuse_address = True
|
|
@@ -113,6 +158,7 @@ def _exchange_code_for_tokens(
|
|
|
113
158
|
client_secret: str,
|
|
114
159
|
redirect_uri: str,
|
|
115
160
|
auth_code: str,
|
|
161
|
+
code_verifier: str,
|
|
116
162
|
) -> Any:
|
|
117
163
|
"""Exchange authorization code for access and refresh tokens.
|
|
118
164
|
|
|
@@ -122,6 +168,7 @@ def _exchange_code_for_tokens(
|
|
|
122
168
|
client_secret: OAuth client secret
|
|
123
169
|
redirect_uri: Redirect URI used in authorization
|
|
124
170
|
auth_code: Authorization code from callback
|
|
171
|
+
code_verifier: PKCE code verifier matching the authorize request
|
|
125
172
|
|
|
126
173
|
Returns:
|
|
127
174
|
Dictionary containing access_token and refresh_token
|
|
@@ -136,6 +183,7 @@ def _exchange_code_for_tokens(
|
|
|
136
183
|
"client_id": client_id,
|
|
137
184
|
"client_secret": client_secret,
|
|
138
185
|
"redirect_uri": redirect_uri,
|
|
186
|
+
"code_verifier": code_verifier,
|
|
139
187
|
}
|
|
140
188
|
|
|
141
189
|
try:
|
|
@@ -168,17 +216,28 @@ def do_oauth_browser_flow(
|
|
|
168
216
|
# Create queue for communication between server and main thread
|
|
169
217
|
auth_code_queue: queue.Queue[str] = queue.Queue()
|
|
170
218
|
|
|
219
|
+
# CSRF protection (RFC 6749 10.12) and PKCE (RFC 7636 / RFC 8252)
|
|
220
|
+
state = secrets.token_urlsafe(32)
|
|
221
|
+
code_verifier, code_challenge = _generate_pkce_pair()
|
|
222
|
+
|
|
171
223
|
# Start callback server
|
|
172
224
|
click.echo(f"\nStarting local callback server on {redirect_uri}...")
|
|
173
|
-
server, _actual_port = _run_oauth_callback_server(
|
|
225
|
+
server, _actual_port = _run_oauth_callback_server(
|
|
226
|
+
redirect_uri, auth_code_queue, state
|
|
227
|
+
)
|
|
174
228
|
|
|
175
229
|
# Build authorization URL with final redirect_uri
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
230
|
+
query = urlencode(
|
|
231
|
+
{
|
|
232
|
+
"response_type": "code",
|
|
233
|
+
"client_id": client_id,
|
|
234
|
+
"redirect_uri": redirect_uri,
|
|
235
|
+
"state": state,
|
|
236
|
+
"code_challenge": code_challenge,
|
|
237
|
+
"code_challenge_method": "S256",
|
|
238
|
+
}
|
|
181
239
|
)
|
|
240
|
+
auth_url = f"{login_url.rstrip('/')}/services/oauth2/authorize?{query}"
|
|
182
241
|
|
|
183
242
|
# Open browser
|
|
184
243
|
click.echo("Opening browser for authentication...")
|
|
@@ -208,7 +267,7 @@ def do_oauth_browser_flow(
|
|
|
208
267
|
# Exchange code for tokens
|
|
209
268
|
click.echo("Exchanging authorization code for tokens...")
|
|
210
269
|
token_response = _exchange_code_for_tokens(
|
|
211
|
-
login_url, client_id, client_secret, redirect_uri, auth_code
|
|
270
|
+
login_url, client_id, client_secret, redirect_uri, auth_code, code_verifier
|
|
212
271
|
)
|
|
213
272
|
|
|
214
273
|
refresh_token = token_response.get("refresh_token")
|
{salesforce_data_customcode-7.0.0rc5 → salesforce_data_customcode-7.1.0}/src/datacustomcode/cli.py
RENAMED
|
@@ -215,6 +215,7 @@ def deploy(
|
|
|
215
215
|
COMPUTE_TYPES,
|
|
216
216
|
CodeExtensionMetadata,
|
|
217
217
|
deploy_full,
|
|
218
|
+
describe_supported_signatures,
|
|
218
219
|
infer_use_in_feature,
|
|
219
220
|
)
|
|
220
221
|
from datacustomcode.token_provider import (
|
|
@@ -252,8 +253,9 @@ def deploy(
|
|
|
252
253
|
else:
|
|
253
254
|
click.secho(
|
|
254
255
|
"Error: Function signature does not match a supported type. "
|
|
255
|
-
"Use
|
|
256
|
-
"
|
|
256
|
+
"Use a supported Request/Response pair in the function "
|
|
257
|
+
"signature. For example, "
|
|
258
|
+
f"{describe_supported_signatures(entrypoint_path)}.",
|
|
257
259
|
fg="red",
|
|
258
260
|
)
|
|
259
261
|
raise click.Abort()
|
|
@@ -349,14 +351,27 @@ def init(directory: str, code_type: str, use_in_feature: Optional[str]):
|
|
|
349
351
|
+ " to automatically update config.json when you make changes to your code"
|
|
350
352
|
)
|
|
351
353
|
|
|
352
|
-
#
|
|
354
|
+
# Prefer the sample tests/test.json shipped in the template; only
|
|
355
|
+
# generate one from the request model if the template doesn't have it
|
|
353
356
|
if code_type == "function":
|
|
354
|
-
|
|
355
|
-
|
|
357
|
+
template_test_json = os.path.join(
|
|
358
|
+
os.path.dirname(entrypoint_path), TESTS_DIR, TEST_FILE
|
|
359
|
+
)
|
|
360
|
+
test_json_path: Optional[str]
|
|
361
|
+
if os.path.isfile(template_test_json):
|
|
362
|
+
test_json_path = template_test_json
|
|
356
363
|
click.echo(
|
|
357
|
-
"
|
|
364
|
+
"Sample test file at "
|
|
358
365
|
+ click.style(test_json_path, fg="blue", bold=True)
|
|
359
366
|
)
|
|
367
|
+
else:
|
|
368
|
+
test_json_path = _generate_function_test_file(entrypoint_path)
|
|
369
|
+
if test_json_path:
|
|
370
|
+
click.echo(
|
|
371
|
+
"Generated test file at "
|
|
372
|
+
+ click.style(test_json_path, fg="blue", bold=True)
|
|
373
|
+
)
|
|
374
|
+
if test_json_path:
|
|
360
375
|
click.echo(
|
|
361
376
|
"Test your function locally with "
|
|
362
377
|
+ click.style(
|
|
@@ -46,8 +46,9 @@ SCRIPT_USE_IN_FEATURE_OPTIONS = [
|
|
|
46
46
|
SCRIPT_USE_IN_FEATURE_STREAMING,
|
|
47
47
|
]
|
|
48
48
|
|
|
49
|
-
#
|
|
49
|
+
# (request type name, response type name) pair to feature name
|
|
50
50
|
REQUEST_TYPE_TO_FEATURE = {
|
|
51
|
-
"SearchIndexChunkingV1Request"
|
|
52
|
-
|
|
51
|
+
("SearchIndexChunkingV1Request", "SearchIndexChunkingV1Response"): (
|
|
52
|
+
"SearchIndexChunking"
|
|
53
|
+
),
|
|
53
54
|
}
|
|
@@ -27,6 +27,7 @@ from typing import (
|
|
|
27
27
|
Callable,
|
|
28
28
|
Dict,
|
|
29
29
|
List,
|
|
30
|
+
Mapping,
|
|
30
31
|
Optional,
|
|
31
32
|
Union,
|
|
32
33
|
)
|
|
@@ -95,15 +96,35 @@ def infer_use_in_feature(entrypoint_path: str) -> Union[str, None]:
|
|
|
95
96
|
if not request_type_name or not response_type_name:
|
|
96
97
|
return None
|
|
97
98
|
|
|
98
|
-
|
|
99
|
-
request_feature = REQUEST_TYPE_TO_FEATURE.get(request_type_name)
|
|
100
|
-
response_feature = REQUEST_TYPE_TO_FEATURE.get(response_type_name)
|
|
99
|
+
return REQUEST_TYPE_TO_FEATURE.get((request_type_name, response_type_name))
|
|
101
100
|
|
|
102
|
-
# Both must be present and must match
|
|
103
|
-
if request_feature and response_feature and request_feature == response_feature:
|
|
104
|
-
return request_feature
|
|
105
101
|
|
|
106
|
-
|
|
102
|
+
def describe_supported_signatures(entrypoint_path: str) -> str:
|
|
103
|
+
"""Build a contract-mismatch hint based on the function's feature type.
|
|
104
|
+
|
|
105
|
+
If the request or response type belongs to a known feature, only that
|
|
106
|
+
feature's expected pair is listed; otherwise all supported pairs are.
|
|
107
|
+
Each pair is followed by the use_in_feature it maps to, e.g.
|
|
108
|
+
``Req/Resp for use_in_feature: SearchIndexChunking``.
|
|
109
|
+
"""
|
|
110
|
+
from datacustomcode.function_utils import inspect_function_types_static
|
|
111
|
+
|
|
112
|
+
request_type_name, response_type_name = inspect_function_types_static(
|
|
113
|
+
entrypoint_path
|
|
114
|
+
)
|
|
115
|
+
supported = list(REQUEST_TYPE_TO_FEATURE.items())
|
|
116
|
+
sharing_a_type = [
|
|
117
|
+
((expected_request, expected_response), feature)
|
|
118
|
+
for (expected_request, expected_response), feature in supported
|
|
119
|
+
if request_type_name == expected_request
|
|
120
|
+
or response_type_name == expected_response
|
|
121
|
+
]
|
|
122
|
+
# Narrow the hint only when the detected types point at a single feature
|
|
123
|
+
to_show = sharing_a_type if len(sharing_a_type) == 1 else supported
|
|
124
|
+
return " or ".join(
|
|
125
|
+
f"{expected_request}/{expected_response} for use_in_feature: {feature}"
|
|
126
|
+
for (expected_request, expected_response), feature in to_show
|
|
127
|
+
)
|
|
107
128
|
|
|
108
129
|
|
|
109
130
|
class CodeExtensionMetadata(BaseModel):
|
|
@@ -146,6 +167,19 @@ JSONValue = Union[
|
|
|
146
167
|
]
|
|
147
168
|
|
|
148
169
|
|
|
170
|
+
_SENSITIVE_HEADERS = frozenset(
|
|
171
|
+
{"authorization", "proxy-authorization", "cookie", "set-cookie"}
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _redact_headers(headers: Mapping[str, Any]) -> dict[str, Any]:
|
|
176
|
+
"""Return a copy of ``headers`` safe to log, with secret-bearing values masked."""
|
|
177
|
+
return {
|
|
178
|
+
key: "[REDACTED]" if key.lower() in _SENSITIVE_HEADERS else value
|
|
179
|
+
for key, value in headers.items()
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
|
|
149
183
|
def _make_api_call(
|
|
150
184
|
url: str,
|
|
151
185
|
method: str,
|
|
@@ -159,13 +193,13 @@ def _make_api_call(
|
|
|
159
193
|
headers["Authorization"] = f"Bearer {token}"
|
|
160
194
|
|
|
161
195
|
logger.debug(f"Making API call: {method} {url}")
|
|
162
|
-
logger.debug(f"Headers: {headers}")
|
|
163
|
-
logger.debug(f"Request params: {kwargs}")
|
|
196
|
+
logger.debug(f"Headers: {_redact_headers(headers)}")
|
|
197
|
+
logger.debug(f"Request params: {sorted(kwargs)}")
|
|
164
198
|
|
|
165
199
|
response = requests.request(method=method, url=url, headers=headers, **kwargs)
|
|
166
200
|
if response.status_code >= 400:
|
|
167
201
|
logger.warning(f"Error Response Status: {response.status_code}")
|
|
168
|
-
logger.debug(f"Error Response Headers: {response.headers}")
|
|
202
|
+
logger.debug(f"Error Response Headers: {_redact_headers(response.headers)}")
|
|
169
203
|
logger.warning(f"Error Response Text: {response.text[:500]}")
|
|
170
204
|
|
|
171
205
|
if not response.text or response.text.strip() == "":
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"input": [
|
|
3
|
+
{
|
|
4
|
+
"text": "Online Remittance Instructions",
|
|
5
|
+
"metadata": {
|
|
6
|
+
"type": "text",
|
|
7
|
+
"page_number": 1,
|
|
8
|
+
"transcript_fields": {
|
|
9
|
+
"speaker": "Agent",
|
|
10
|
+
"start_timestamp": 1.0,
|
|
11
|
+
"end_timestamp": 8.75
|
|
12
|
+
},
|
|
13
|
+
"text_as_html": "<p>Online Remittance Instructions</p>",
|
|
14
|
+
"source_dmo_fields": {
|
|
15
|
+
"FilePath__c": "quarterly_report.pdf",
|
|
16
|
+
"Size__c": 1377454.0,
|
|
17
|
+
"ContentType__c": "pdf",
|
|
18
|
+
"LastModified__c": "2026-03-25T02:01:24.918000"
|
|
19
|
+
},
|
|
20
|
+
"prepend": [
|
|
21
|
+
{
|
|
22
|
+
"dmo_name": "udmo_1__dlm",
|
|
23
|
+
"field_name": "ResolvedFilePath__c",
|
|
24
|
+
"value": "udlo_1__dll:quarterly_report.pdf"
|
|
25
|
+
}
|
|
26
|
+
],
|
|
27
|
+
"image_base64": "sample_image_base64",
|
|
28
|
+
"image_mime_type": "image/png",
|
|
29
|
+
"image_type": "diagram"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# Chunking with a Gemini Named Credential Callout
|
|
2
|
+
|
|
3
|
+
Splits each input document into paragraph-sized chunks and calls Google's
|
|
4
|
+
**Gemini** `generateContent` API for every chunk. The model returns a summary,
|
|
5
|
+
category, sentiment, and topics, which are attached to the chunk as citations so
|
|
6
|
+
the search index can filter and rank on them. Gemini is reached through a
|
|
7
|
+
**Named Credential**, so this code never handles the endpoint URL or the API key.
|
|
8
|
+
|
|
9
|
+
## How the callout works
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
CALLOUT_URL = "callout:gemini" # callout:<NC name>[/<path>]
|
|
13
|
+
|
|
14
|
+
request = (
|
|
15
|
+
HTTPRequestBuilder()
|
|
16
|
+
.set_url(CALLOUT_URL)
|
|
17
|
+
.set_method(HTTPMethod.POST)
|
|
18
|
+
.set_headers({"Content-Type": "application/json"})
|
|
19
|
+
.set_response_timeout_seconds(60) # optional: per-callout timeout (seconds)
|
|
20
|
+
.build()
|
|
21
|
+
)
|
|
22
|
+
# Body is sent verbatim (serialize it yourself); the response body is a raw string.
|
|
23
|
+
response = runtime.named_credential.request(request, json.dumps(payload))
|
|
24
|
+
if response.is_success:
|
|
25
|
+
envelope = json.loads(response.body)
|
|
26
|
+
text = envelope["candidates"][0]["content"]["parts"][0]["text"]
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The request asks for `responseMimeType: application/json` with a `responseSchema`,
|
|
30
|
+
so Gemini returns the classification as a JSON string in
|
|
31
|
+
`candidates[0].content.parts[0].text` — decode it, then decode that text again.
|
|
32
|
+
|
|
33
|
+
The `gemini` Named Credential's URL already includes the full
|
|
34
|
+
`/v1beta/models/<model>:generateContent` path, so the callout is just
|
|
35
|
+
`callout:gemini` with **no path suffix** (anything after the name is appended to
|
|
36
|
+
the credential's URL).
|
|
37
|
+
|
|
38
|
+
## Configure the Named Credential
|
|
39
|
+
|
|
40
|
+
1. Create an **External Credential** (e.g. `google_api_key`) that injects your
|
|
41
|
+
Gemini API key as the `X-goog-api-key` header.
|
|
42
|
+
2. Create a **Named Credential** named `gemini`:
|
|
43
|
+
- **URL**: `https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent`
|
|
44
|
+
- **Enabled for Callouts** + **Generate Authorization Header**: on
|
|
45
|
+
- **External Credential**: `google_api_key`
|
|
46
|
+
|
|
47
|
+
## Test locally
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
DATACUSTOMCODE_EXTERNAL_CALLOUT_CONFIG=/abs/path/to/external_callout_config.json \
|
|
51
|
+
sf data-code-extension function run \
|
|
52
|
+
--entrypoint payload/entrypoint.py \
|
|
53
|
+
--test-with payload/tests/test.json \
|
|
54
|
+
--target-org <your-org-alias>
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
With `--target-org` the SDK fetches only the **URL** from the org's Named
|
|
58
|
+
Credential; **auth is always taken from `external_callout_config.json`** locally
|
|
59
|
+
(the org's External Credential is used only in the Data Cloud runtime). So the
|
|
60
|
+
`X-goog-api-key` must be in the local config for a local test. Omit
|
|
61
|
+
`--target-org` to run fully offline using `target_url`.
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"credentials": {
|
|
66
|
+
"callout:gemini": {
|
|
67
|
+
"auth_type": "Custom",
|
|
68
|
+
"custom_headers": { "X-goog-api-key": "YOUR_GEMINI_API_KEY" },
|
|
69
|
+
"target_url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent"
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Place `external_callout_config.json` in the **parent of your payload folder** (or
|
|
76
|
+
point `DATACUSTOMCODE_EXTERNAL_CALLOUT_CONFIG` at it). It is never packaged into
|
|
77
|
+
the deployment zip. Get a key from [Google AI Studio](https://aistudio.google.com/apikey);
|
|
78
|
+
**do not commit it.**
|
|
79
|
+
|
|
80
|
+
## Auth types
|
|
81
|
+
|
|
82
|
+
`auth_type` selects how auth is injected for local testing. It should mirror the
|
|
83
|
+
External Credential your Named Credential uses in the org, so local and deployed
|
|
84
|
+
runs behave the same. This example uses `Custom` (Gemini's `X-goog-api-key`);
|
|
85
|
+
all four supported types:
|
|
86
|
+
|
|
87
|
+
```json
|
|
88
|
+
{
|
|
89
|
+
"credentials": {
|
|
90
|
+
"callout:my_custom_api": {
|
|
91
|
+
"auth_type": "Custom",
|
|
92
|
+
"custom_headers": { "X-goog-api-key": "YOUR_API_KEY" }
|
|
93
|
+
},
|
|
94
|
+
"callout:my_basic_api": {
|
|
95
|
+
"auth_type": "Basic",
|
|
96
|
+
"username": "svc_user",
|
|
97
|
+
"password": "YOUR_PASSWORD"
|
|
98
|
+
},
|
|
99
|
+
"callout:my_oauth_api": {
|
|
100
|
+
"auth_type": "OAuth",
|
|
101
|
+
"access_token": "YOUR_ACCESS_TOKEN"
|
|
102
|
+
},
|
|
103
|
+
"callout:my_jwt_api": {
|
|
104
|
+
"auth_type": "Jwt",
|
|
105
|
+
"token": "YOUR_JWT"
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
| `auth_type` | Fields read | Header sent |
|
|
112
|
+
| ----------- | ------------------------------- | --------------------------------------- |
|
|
113
|
+
| `Basic` | `username`, `password` | `Authorization: Basic <base64 user:pw>` |
|
|
114
|
+
| `Custom` | `custom_headers` (sent verbatim)| the headers you list |
|
|
115
|
+
| `OAuth` | `access_token` or `token` | `Authorization: Bearer <token>` |
|
|
116
|
+
| `Jwt` | `access_token` or `token` | `Authorization: Bearer <token>` |
|
|
117
|
+
|
|
118
|
+
`OAuth`/`Jwt` take a token you supply for the local run — the SDK does not fetch
|
|
119
|
+
or refresh it. In the Data Cloud runtime the Named Credential handles token
|
|
120
|
+
acquisition; this local config only stands in for that during testing.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) 2025, Salesforce, Inc.
|
|
3
|
+
# SPDX-License-Identifier: Apache-2
|
|
4
|
+
|
|
5
|
+
"""
|
|
6
|
+
Document Chunking with a Gemini Named Credential Callout
|
|
7
|
+
|
|
8
|
+
Splits each input document into paragraph-sized chunks and classifies every
|
|
9
|
+
chunk via Google's Gemini ``generateContent`` API, reached through a Named
|
|
10
|
+
Credential (``callout:gemini``) so the endpoint URL and API key are resolved
|
|
11
|
+
outside this code. The classification is attached to each chunk as citations.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
|
|
17
|
+
from datacustomcode.function import Runtime
|
|
18
|
+
from datacustomcode.function.feature_types.chunking import (
|
|
19
|
+
ChunkType,
|
|
20
|
+
SearchIndexChunkingV1Output,
|
|
21
|
+
SearchIndexChunkingV1Request,
|
|
22
|
+
SearchIndexChunkingV1Response,
|
|
23
|
+
)
|
|
24
|
+
from datacustomcode.named_credential.types.http_method import HTTPMethod
|
|
25
|
+
from datacustomcode.named_credential.types.http_request_builder import (
|
|
26
|
+
HTTPRequestBuilder,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
logging.basicConfig(level=logging.INFO)
|
|
31
|
+
|
|
32
|
+
CALLOUT_URL = "callout:gemini"
|
|
33
|
+
|
|
34
|
+
_ANALYSIS_FIELDS = ("summary", "category", "sentiment")
|
|
35
|
+
|
|
36
|
+
_PROMPT = (
|
|
37
|
+
"Analyze the following document chunk and classify it. Respond with its "
|
|
38
|
+
"one-sentence summary, a single-word category, overall sentiment "
|
|
39
|
+
"(positive, negative, or neutral), and up to five key topics.\n\nChunk:\n"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# Force Gemini to return the classification as JSON in a fixed shape.
|
|
43
|
+
_GENERATION_CONFIG = {
|
|
44
|
+
"responseMimeType": "application/json",
|
|
45
|
+
"responseSchema": {
|
|
46
|
+
"type": "object",
|
|
47
|
+
"properties": {
|
|
48
|
+
"summary": {"type": "string"},
|
|
49
|
+
"category": {"type": "string"},
|
|
50
|
+
"sentiment": {"type": "string"},
|
|
51
|
+
"topics": {"type": "array", "items": {"type": "string"}},
|
|
52
|
+
},
|
|
53
|
+
"required": ["summary", "category", "sentiment", "topics"],
|
|
54
|
+
},
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _chunk_text(text: str, max_words: int = 80) -> list[str]:
|
|
59
|
+
"""Split text into paragraph-aligned chunks of at most ``max_words`` words."""
|
|
60
|
+
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
|
|
61
|
+
|
|
62
|
+
chunks: list[str] = []
|
|
63
|
+
current: list[str] = []
|
|
64
|
+
current_words = 0
|
|
65
|
+
|
|
66
|
+
for paragraph in paragraphs:
|
|
67
|
+
paragraph_words = len(paragraph.split())
|
|
68
|
+
if current and current_words + paragraph_words > max_words:
|
|
69
|
+
chunks.append("\n\n".join(current))
|
|
70
|
+
current = []
|
|
71
|
+
current_words = 0
|
|
72
|
+
current.append(paragraph)
|
|
73
|
+
current_words += paragraph_words
|
|
74
|
+
|
|
75
|
+
if current:
|
|
76
|
+
chunks.append("\n\n".join(current))
|
|
77
|
+
|
|
78
|
+
return chunks
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _extract_model_json(body: str) -> dict:
|
|
82
|
+
"""Decode the model's JSON classification from a Gemini response.
|
|
83
|
+
|
|
84
|
+
The generated text sits at ``candidates[0].content.parts[0].text`` and is
|
|
85
|
+
itself a JSON string, so decode twice. Any malformed layer yields ``{}``.
|
|
86
|
+
"""
|
|
87
|
+
try:
|
|
88
|
+
envelope = json.loads(body) if body else {}
|
|
89
|
+
except json.JSONDecodeError:
|
|
90
|
+
return {}
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
text = envelope["candidates"][0]["content"]["parts"][0]["text"]
|
|
94
|
+
except (KeyError, IndexError, TypeError):
|
|
95
|
+
return {}
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
payload = json.loads(text)
|
|
99
|
+
except json.JSONDecodeError:
|
|
100
|
+
return {}
|
|
101
|
+
return payload if isinstance(payload, dict) else {}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _analyze_chunk(chunk_text: str, runtime: Runtime) -> dict[str, str]:
|
|
105
|
+
"""Classify one chunk via the Gemini callout and return it as citations."""
|
|
106
|
+
request = (
|
|
107
|
+
HTTPRequestBuilder()
|
|
108
|
+
.set_url(CALLOUT_URL)
|
|
109
|
+
.set_method(HTTPMethod.POST)
|
|
110
|
+
.set_headers({"Content-Type": "application/json", "Accept": "application/json"})
|
|
111
|
+
.set_response_timeout_seconds(60)
|
|
112
|
+
.build()
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
payload = {
|
|
116
|
+
"contents": [{"parts": [{"text": _PROMPT + chunk_text}]}],
|
|
117
|
+
"generationConfig": _GENERATION_CONFIG,
|
|
118
|
+
}
|
|
119
|
+
response = runtime.named_credential.request(request, json.dumps(payload))
|
|
120
|
+
|
|
121
|
+
# Don't raise: a single failed callout shouldn't abort the whole job.
|
|
122
|
+
if not response.is_success:
|
|
123
|
+
logger.error(f"Gemini callout failed with status {response.status_code}")
|
|
124
|
+
return {"analysis_status": "failed", "http_status": str(response.status_code)}
|
|
125
|
+
|
|
126
|
+
data = _extract_model_json(response.body)
|
|
127
|
+
citations = {"analysis_status": "success"}
|
|
128
|
+
for field in _ANALYSIS_FIELDS:
|
|
129
|
+
value = data.get(field)
|
|
130
|
+
citations[field] = str(value) if value is not None else "unavailable"
|
|
131
|
+
|
|
132
|
+
topics = data.get("topics")
|
|
133
|
+
if isinstance(topics, list):
|
|
134
|
+
citations["topics"] = ", ".join(str(topic) for topic in topics)
|
|
135
|
+
|
|
136
|
+
return citations
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def function(
|
|
140
|
+
request: SearchIndexChunkingV1Request, runtime: Runtime
|
|
141
|
+
) -> SearchIndexChunkingV1Response:
|
|
142
|
+
"""Chunk each input document and classify every chunk via the Gemini API."""
|
|
143
|
+
logger.info(f"Received {len(request.input)} documents to chunk")
|
|
144
|
+
|
|
145
|
+
chunks = []
|
|
146
|
+
chunk_id = 1
|
|
147
|
+
|
|
148
|
+
for doc in request.input:
|
|
149
|
+
for chunk_text in _chunk_text(doc.text):
|
|
150
|
+
citations = _analyze_chunk(chunk_text, runtime)
|
|
151
|
+
|
|
152
|
+
chunk = SearchIndexChunkingV1Output(
|
|
153
|
+
text=chunk_text,
|
|
154
|
+
seq_no=chunk_id,
|
|
155
|
+
chunk_type=ChunkType.TEXT,
|
|
156
|
+
citations=citations,
|
|
157
|
+
)
|
|
158
|
+
chunks.append(chunk)
|
|
159
|
+
chunk_id += 1
|
|
160
|
+
|
|
161
|
+
logger.info(f"Produced {len(chunks)} classified chunks")
|
|
162
|
+
return SearchIndexChunkingV1Response(output=chunks)
|