langchain-acedatacloud 0.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.
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .env
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ build/
9
+ *.egg-info/
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ace Data Cloud
4
+
5
+ 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:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ 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.
@@ -0,0 +1,134 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-acedatacloud
3
+ Version: 0.1.0
4
+ Summary: Ace Data Cloud chat model and shared LangChain service runtime
5
+ Project-URL: Homepage, https://github.com/AceDataCloud/LangChain
6
+ Project-URL: Source, https://github.com/AceDataCloud/LangChain
7
+ Project-URL: Issues, https://github.com/AceDataCloud/LangChain/issues
8
+ Author-email: Ace Data Cloud Dev <dev@acedata.cloud>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: acedatacloud,chat,langchain,provider
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: httpx<1,>=0.27
16
+ Requires-Dist: langchain-openai<2,>=1.7
17
+ Description-Content-Type: text/markdown
18
+
19
+ # Ace Data Cloud for LangChain
20
+
21
+ A named `ChatAceDataCloud` chat model and **five separately installable service toolkits**: Suno, Seedance, HappyHorse, GPT Image and Nano Banana **by Ace Data Cloud**. This project is maintained by Ace Data Cloud; it is not an official client of those service brands.
22
+
23
+ [简体中文](https://github.com/AceDataCloud/LangChain/blob/main/readme/README_zh_Hans.md) · [Privacy](https://github.com/AceDataCloud/LangChain/blob/main/PRIVACY.md) · [Source](https://github.com/AceDataCloud/LangChain)
24
+
25
+ **Stable release preparation:** the native integration source is merged on `main`. Version `0.1.0` is being prepared for all six packages; verify [release status](https://github.com/AceDataCloud/LangChain/blob/main/RELEASE_STATUS.md) for actual uploaded versions. Existing `0.1.0rc1` packages are historical prereleases. Package publication and official LangChain directory approval are separate gates. No new graphical chat button or upstream default-provider registration is claimed.
26
+
27
+ ## Install only the integration you need
28
+
29
+ Use Python 3.10+ in a virtual environment. Each service package installs only its own tool classes plus the shared runtime, not the other four services.
30
+
31
+ | Integration | Package / official registry destination | Guide |
32
+ | --- | --- | --- |
33
+ | Ace chat model | [`langchain-acedatacloud`](https://pypi.org/project/langchain-acedatacloud/) | [Chat model](#chat-without-a-custom-base-url) |
34
+ | Suno by Ace Data Cloud | [`langchain-suno-acedatacloud`](https://pypi.org/project/langchain-suno-acedatacloud/) | [suno](https://github.com/AceDataCloud/LangChain/blob/main/packages/suno/README.md) |
35
+ | Seedance by Ace Data Cloud | [`langchain-seedance-acedatacloud`](https://pypi.org/project/langchain-seedance-acedatacloud/) | [seedance](https://github.com/AceDataCloud/LangChain/blob/main/packages/seedance/README.md) |
36
+ | HappyHorse by Ace Data Cloud | [`langchain-happyhorse-acedatacloud`](https://pypi.org/project/langchain-happyhorse-acedatacloud/) | [happyhorse](https://github.com/AceDataCloud/LangChain/blob/main/packages/happyhorse/README.md) |
37
+ | GPT Image by Ace Data Cloud | [`langchain-gpt-image-acedatacloud`](https://pypi.org/project/langchain-gpt-image-acedatacloud/) | [gpt-image](https://github.com/AceDataCloud/LangChain/blob/main/packages/gpt-image/README.md) |
38
+ | Nano Banana by Ace Data Cloud | [`langchain-nano-banana-acedatacloud`](https://pypi.org/project/langchain-nano-banana-acedatacloud/) | [nano-banana](https://github.com/AceDataCloud/LangChain/blob/main/packages/nano-banana/README.md) |
39
+
40
+ ```bash
41
+ python3 -m venv .venv
42
+ source .venv/bin/activate
43
+ # Stable version (after registry readback):
44
+ python -m pip install langchain-acedatacloud==0.1.0
45
+ # Or one service:
46
+ python -m pip install langchain-happyhorse-acedatacloud==0.1.0
47
+ ```
48
+
49
+ For source installation, run `git clone --branch main https://github.com/AceDataCloud/LangChain.git`, `cd LangChain`, then `pip install -e packages/core -e packages/suno`. Package artifacts are not proof of official listing.
50
+
51
+ ## Get the application API Key
52
+
53
+ 1. [Register or sign in → Applications](https://platform.acedata.cloud/console/applications?utm_source=opensource&utm_medium=referral&utm_campaign=evergreen&utm_content=langchain_readme_api_key). If no **General application** exists, choose **Initialize General Application**.
54
+ 2. Open the General application. Copy its **API Key**, or choose **Manage Keys → Create** to make a separately named LangChain key. Review expiration, usage limitations and **Allowed APIs**. Allow both the generation and same-ID task query paths used below. Confirm service access, balance and [current pricing](https://platform.acedata.cloud/models?utm_source=opensource&utm_medium=referral&utm_campaign=evergreen&utm_content=langchain_readme_pricing). No trial allowance is promised.
55
+ 3. Copy the raw token only, without `Bearer `, quotation marks or redacted characters. A `platform-...` account-management token cannot replace this application key.
56
+
57
+ ![Copy the redacted application API Key or open Manage Keys](https://raw.githubusercontent.com/AceDataCloud/SunoDify/8d3d03570e73324220f111f7fe343da0792a8071/_assets/tutorial/get-api-key-en.png)
58
+
59
+ ![Create a separately named key with optional restrictions](https://raw.githubusercontent.com/AceDataCloud/SunoDify/8d3d03570e73324220f111f7fe343da0792a8071/_assets/tutorial/create-api-key-en.png)
60
+
61
+ The historical create-key image says `Dify tutorial`; name the actual key `LangChain <service>`. These are real Ace console screenshots reused from [SunoDify](https://github.com/AceDataCloud/SunoDify/tree/8d3d03570e73324220f111f7fe343da0792a8071/_assets/tutorial), retrieved 2026-10-18; later console layouts may differ. They show credential setup, not a LangChain GUI. Real tokens are redacted.
62
+
63
+ ```bash
64
+ export ACEDATACLOUD_API_TOKEN='your application key'
65
+ ```
66
+
67
+ PowerShell: `$env:ACEDATACLOUD_API_TOKEN='your application key'`. Keep the token in the environment or secret manager, never in a prompt or workflow export.
68
+
69
+ ## Chat without a custom base URL
70
+
71
+ ```python
72
+ from langchain_acedatacloud import ChatAceDataCloud
73
+
74
+ model = ChatAceDataCloud(model="gpt-4o-mini")
75
+ reply = model.invoke("Reply in one short sentence.") # One paid API request.
76
+ print(reply.content)
77
+ print(reply.usage_metadata) # Token counts, not charged Credits.
78
+ ```
79
+
80
+ The named class owns Ace credential and endpoint defaults. Standard chat, async, stream and tool binding reuse LangChain's OpenAI protocol implementation. It fixes Chat Completions mode, disables automatic retries by default, and identifies traces as `acedatacloud`. Model-specific capabilities still depend on the selected model. For stream token counts use `stream_usage=True` only where supported.
81
+
82
+ Use `model.bind_tools([...])`, execute a returned local tool, and supply `ToolMessage` to complete a tool loop. Each model invocation may be charged; a tool selection plus final answer normally means two calls. This does **not** mean `init_chat_model(model_provider="acedatacloud")` is built into the upstream release. A maintainer-approved provider-registry entry is a separate goal.
83
+
84
+ ## Add a single service to an agent
85
+
86
+ ```python
87
+ from langchain_acedatacloud import AceAPIClient
88
+ from langchain_suno_acedatacloud import SunoToolkit
89
+
90
+ # Query-only by default: enabling a toolkit must not silently enable paid generation.
91
+ tools = SunoToolkit(client=AceAPIClient()).get_tools()
92
+ print([tool.name for tool in tools])
93
+ # ['suno_retrieve_task']
94
+ ```
95
+
96
+ An application deliberately enables generation with `include_generation=True` after showing current prices and obtaining its user's authorization. Pass those BaseTool instances to your LangChain agent or invoke them directly. The client credential is not part of the LLM tool schema.
97
+
98
+ ## Asynchronous results and billing
99
+
100
+ One generation-tool invocation submits one request with `async=true`, returns a task ID, and does not loop or retry. Query tools call the service's task endpoint with the **same** ID. A successful submission or preview URL is not terminal completion. The normalized result exposes `terminal` and `status`; a pending result must be queried again later, never regenerated merely to poll. Media URLs are exposed as final only after `finished_at`; raw API data remains available for diagnosis. The tools do not download remote media.
101
+
102
+ Inspect [Usage History](https://platform.acedata.cloud/console/usages?utm_source=opensource&utm_medium=referral&utm_campaign=evergreen&utm_content=langchain_readme_usage) for actual Credits and uncertain submissions. Token counts and package downloads are not revenue. No integration test is configured to issue paid calls in CI.
103
+
104
+ ## Troubleshooting
105
+
106
+ | Result | What to check |
107
+ | --- | --- |
108
+ | 401 / missing key | Use the raw application API Key and `ACEDATACLOUD_API_TOKEN`. |
109
+ | 403 | Service access, balance, expiry, usage/API restrictions and response policy details. |
110
+ | 429 | Reduce concurrency; no automatic paid retry is performed. |
111
+ | Pending / empty media | Query the same task ID; do not resubmit generation. |
112
+ | Timeout / 5xx | Check original task and Usage History before deciding on another paid request. |
113
+ | Unsupported provider in `init_chat_model` | Import `ChatAceDataCloud` directly; upstream default-provider registration is not claimed. |
114
+
115
+ ## Development and contribution
116
+
117
+ ```bash
118
+ pip install -r requirements-dev.txt
119
+ pip install -e packages/core
120
+ pip install --no-deps -e packages/suno -e packages/seedance -e packages/happyhorse -e packages/gpt-image -e packages/nano-banana
121
+ python scripts/check_packages.py
122
+ ruff check .
123
+ ruff format --check .
124
+ pytest
125
+ python scripts/build_packages.py
126
+ python -m twine check dist/*
127
+ ```
128
+
129
+ The repository is a single source for shared transport/task behavior. Packages have independent identities, service names, schemas and listing materials. The [LangChain integration process](https://docs.langchain.com/oss/python/contributing/integrations-langchain) requires published packages and a listing issue; see `submissions/` for reviewable forms. No unsolicited manual listing PR or promotional message is sent.
130
+
131
+
132
+ ## Official requests (2026-10-18)
133
+
134
+ These are submissions, not approved entries: [ChatAceDataCloud](https://github.com/langchain-ai/docs/issues/6809), [HappyHorse by Ace Data Cloud](https://github.com/langchain-ai/docs/issues/6810), [GPT Image by Ace Data Cloud](https://github.com/langchain-ai/docs/issues/6811), [Nano Banana by Ace Data Cloud](https://github.com/langchain-ai/docs/issues/6812). The [native default-provider request](https://github.com/langchain-ai/langchain/issues/41291) was automatically closed because programmatic submission is disallowed; it needs the official web template. No API resubmission or issue-type workaround is used. Suno and Seedance listing forms are submitted only after their public package installation is verified.
@@ -0,0 +1,116 @@
1
+ # Ace Data Cloud for LangChain
2
+
3
+ A named `ChatAceDataCloud` chat model and **five separately installable service toolkits**: Suno, Seedance, HappyHorse, GPT Image and Nano Banana **by Ace Data Cloud**. This project is maintained by Ace Data Cloud; it is not an official client of those service brands.
4
+
5
+ [简体中文](https://github.com/AceDataCloud/LangChain/blob/main/readme/README_zh_Hans.md) · [Privacy](https://github.com/AceDataCloud/LangChain/blob/main/PRIVACY.md) · [Source](https://github.com/AceDataCloud/LangChain)
6
+
7
+ **Stable release preparation:** the native integration source is merged on `main`. Version `0.1.0` is being prepared for all six packages; verify [release status](https://github.com/AceDataCloud/LangChain/blob/main/RELEASE_STATUS.md) for actual uploaded versions. Existing `0.1.0rc1` packages are historical prereleases. Package publication and official LangChain directory approval are separate gates. No new graphical chat button or upstream default-provider registration is claimed.
8
+
9
+ ## Install only the integration you need
10
+
11
+ Use Python 3.10+ in a virtual environment. Each service package installs only its own tool classes plus the shared runtime, not the other four services.
12
+
13
+ | Integration | Package / official registry destination | Guide |
14
+ | --- | --- | --- |
15
+ | Ace chat model | [`langchain-acedatacloud`](https://pypi.org/project/langchain-acedatacloud/) | [Chat model](#chat-without-a-custom-base-url) |
16
+ | Suno by Ace Data Cloud | [`langchain-suno-acedatacloud`](https://pypi.org/project/langchain-suno-acedatacloud/) | [suno](https://github.com/AceDataCloud/LangChain/blob/main/packages/suno/README.md) |
17
+ | Seedance by Ace Data Cloud | [`langchain-seedance-acedatacloud`](https://pypi.org/project/langchain-seedance-acedatacloud/) | [seedance](https://github.com/AceDataCloud/LangChain/blob/main/packages/seedance/README.md) |
18
+ | HappyHorse by Ace Data Cloud | [`langchain-happyhorse-acedatacloud`](https://pypi.org/project/langchain-happyhorse-acedatacloud/) | [happyhorse](https://github.com/AceDataCloud/LangChain/blob/main/packages/happyhorse/README.md) |
19
+ | GPT Image by Ace Data Cloud | [`langchain-gpt-image-acedatacloud`](https://pypi.org/project/langchain-gpt-image-acedatacloud/) | [gpt-image](https://github.com/AceDataCloud/LangChain/blob/main/packages/gpt-image/README.md) |
20
+ | Nano Banana by Ace Data Cloud | [`langchain-nano-banana-acedatacloud`](https://pypi.org/project/langchain-nano-banana-acedatacloud/) | [nano-banana](https://github.com/AceDataCloud/LangChain/blob/main/packages/nano-banana/README.md) |
21
+
22
+ ```bash
23
+ python3 -m venv .venv
24
+ source .venv/bin/activate
25
+ # Stable version (after registry readback):
26
+ python -m pip install langchain-acedatacloud==0.1.0
27
+ # Or one service:
28
+ python -m pip install langchain-happyhorse-acedatacloud==0.1.0
29
+ ```
30
+
31
+ For source installation, run `git clone --branch main https://github.com/AceDataCloud/LangChain.git`, `cd LangChain`, then `pip install -e packages/core -e packages/suno`. Package artifacts are not proof of official listing.
32
+
33
+ ## Get the application API Key
34
+
35
+ 1. [Register or sign in → Applications](https://platform.acedata.cloud/console/applications?utm_source=opensource&utm_medium=referral&utm_campaign=evergreen&utm_content=langchain_readme_api_key). If no **General application** exists, choose **Initialize General Application**.
36
+ 2. Open the General application. Copy its **API Key**, or choose **Manage Keys → Create** to make a separately named LangChain key. Review expiration, usage limitations and **Allowed APIs**. Allow both the generation and same-ID task query paths used below. Confirm service access, balance and [current pricing](https://platform.acedata.cloud/models?utm_source=opensource&utm_medium=referral&utm_campaign=evergreen&utm_content=langchain_readme_pricing). No trial allowance is promised.
37
+ 3. Copy the raw token only, without `Bearer `, quotation marks or redacted characters. A `platform-...` account-management token cannot replace this application key.
38
+
39
+ ![Copy the redacted application API Key or open Manage Keys](https://raw.githubusercontent.com/AceDataCloud/SunoDify/8d3d03570e73324220f111f7fe343da0792a8071/_assets/tutorial/get-api-key-en.png)
40
+
41
+ ![Create a separately named key with optional restrictions](https://raw.githubusercontent.com/AceDataCloud/SunoDify/8d3d03570e73324220f111f7fe343da0792a8071/_assets/tutorial/create-api-key-en.png)
42
+
43
+ The historical create-key image says `Dify tutorial`; name the actual key `LangChain <service>`. These are real Ace console screenshots reused from [SunoDify](https://github.com/AceDataCloud/SunoDify/tree/8d3d03570e73324220f111f7fe343da0792a8071/_assets/tutorial), retrieved 2026-10-18; later console layouts may differ. They show credential setup, not a LangChain GUI. Real tokens are redacted.
44
+
45
+ ```bash
46
+ export ACEDATACLOUD_API_TOKEN='your application key'
47
+ ```
48
+
49
+ PowerShell: `$env:ACEDATACLOUD_API_TOKEN='your application key'`. Keep the token in the environment or secret manager, never in a prompt or workflow export.
50
+
51
+ ## Chat without a custom base URL
52
+
53
+ ```python
54
+ from langchain_acedatacloud import ChatAceDataCloud
55
+
56
+ model = ChatAceDataCloud(model="gpt-4o-mini")
57
+ reply = model.invoke("Reply in one short sentence.") # One paid API request.
58
+ print(reply.content)
59
+ print(reply.usage_metadata) # Token counts, not charged Credits.
60
+ ```
61
+
62
+ The named class owns Ace credential and endpoint defaults. Standard chat, async, stream and tool binding reuse LangChain's OpenAI protocol implementation. It fixes Chat Completions mode, disables automatic retries by default, and identifies traces as `acedatacloud`. Model-specific capabilities still depend on the selected model. For stream token counts use `stream_usage=True` only where supported.
63
+
64
+ Use `model.bind_tools([...])`, execute a returned local tool, and supply `ToolMessage` to complete a tool loop. Each model invocation may be charged; a tool selection plus final answer normally means two calls. This does **not** mean `init_chat_model(model_provider="acedatacloud")` is built into the upstream release. A maintainer-approved provider-registry entry is a separate goal.
65
+
66
+ ## Add a single service to an agent
67
+
68
+ ```python
69
+ from langchain_acedatacloud import AceAPIClient
70
+ from langchain_suno_acedatacloud import SunoToolkit
71
+
72
+ # Query-only by default: enabling a toolkit must not silently enable paid generation.
73
+ tools = SunoToolkit(client=AceAPIClient()).get_tools()
74
+ print([tool.name for tool in tools])
75
+ # ['suno_retrieve_task']
76
+ ```
77
+
78
+ An application deliberately enables generation with `include_generation=True` after showing current prices and obtaining its user's authorization. Pass those BaseTool instances to your LangChain agent or invoke them directly. The client credential is not part of the LLM tool schema.
79
+
80
+ ## Asynchronous results and billing
81
+
82
+ One generation-tool invocation submits one request with `async=true`, returns a task ID, and does not loop or retry. Query tools call the service's task endpoint with the **same** ID. A successful submission or preview URL is not terminal completion. The normalized result exposes `terminal` and `status`; a pending result must be queried again later, never regenerated merely to poll. Media URLs are exposed as final only after `finished_at`; raw API data remains available for diagnosis. The tools do not download remote media.
83
+
84
+ Inspect [Usage History](https://platform.acedata.cloud/console/usages?utm_source=opensource&utm_medium=referral&utm_campaign=evergreen&utm_content=langchain_readme_usage) for actual Credits and uncertain submissions. Token counts and package downloads are not revenue. No integration test is configured to issue paid calls in CI.
85
+
86
+ ## Troubleshooting
87
+
88
+ | Result | What to check |
89
+ | --- | --- |
90
+ | 401 / missing key | Use the raw application API Key and `ACEDATACLOUD_API_TOKEN`. |
91
+ | 403 | Service access, balance, expiry, usage/API restrictions and response policy details. |
92
+ | 429 | Reduce concurrency; no automatic paid retry is performed. |
93
+ | Pending / empty media | Query the same task ID; do not resubmit generation. |
94
+ | Timeout / 5xx | Check original task and Usage History before deciding on another paid request. |
95
+ | Unsupported provider in `init_chat_model` | Import `ChatAceDataCloud` directly; upstream default-provider registration is not claimed. |
96
+
97
+ ## Development and contribution
98
+
99
+ ```bash
100
+ pip install -r requirements-dev.txt
101
+ pip install -e packages/core
102
+ pip install --no-deps -e packages/suno -e packages/seedance -e packages/happyhorse -e packages/gpt-image -e packages/nano-banana
103
+ python scripts/check_packages.py
104
+ ruff check .
105
+ ruff format --check .
106
+ pytest
107
+ python scripts/build_packages.py
108
+ python -m twine check dist/*
109
+ ```
110
+
111
+ The repository is a single source for shared transport/task behavior. Packages have independent identities, service names, schemas and listing materials. The [LangChain integration process](https://docs.langchain.com/oss/python/contributing/integrations-langchain) requires published packages and a listing issue; see `submissions/` for reviewable forms. No unsolicited manual listing PR or promotional message is sent.
112
+
113
+
114
+ ## Official requests (2026-10-18)
115
+
116
+ These are submissions, not approved entries: [ChatAceDataCloud](https://github.com/langchain-ai/docs/issues/6809), [HappyHorse by Ace Data Cloud](https://github.com/langchain-ai/docs/issues/6810), [GPT Image by Ace Data Cloud](https://github.com/langchain-ai/docs/issues/6811), [Nano Banana by Ace Data Cloud](https://github.com/langchain-ai/docs/issues/6812). The [native default-provider request](https://github.com/langchain-ai/langchain/issues/41291) was automatically closed because programmatic submission is disallowed; it needs the official web template. No API resubmission or issue-type workaround is used. Suno and Seedance listing forms are submitted only after their public package installation is verified.
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "langchain-acedatacloud"
7
+ version = "0.1.0"
8
+ description = "Ace Data Cloud chat model and shared LangChain service runtime"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{name="Ace Data Cloud Dev", email="dev@acedata.cloud"}]
13
+ keywords = ["acedatacloud", "langchain", "chat", "provider"]
14
+ dependencies = ["langchain-openai>=1.7,<2", "httpx>=0.27,<1"]
15
+ classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent"]
16
+
17
+ [project.urls]
18
+ Homepage = "https://github.com/AceDataCloud/LangChain"
19
+ Source = "https://github.com/AceDataCloud/LangChain"
20
+ Issues = "https://github.com/AceDataCloud/LangChain/issues"
21
+
22
+ [tool.hatch.build.targets.wheel]
23
+ packages = ["src/langchain_acedatacloud"]
@@ -0,0 +1,7 @@
1
+ """Chat models and common runtime for Ace Data Cloud LangChain integrations."""
2
+
3
+ from .chat_models import ChatAceDataCloud
4
+ from .client import AceAPIClient
5
+
6
+ __all__ = ["AceAPIClient", "ChatAceDataCloud"]
7
+ __version__ = "0.1.0"
@@ -0,0 +1,41 @@
1
+ """A named LangChain chat integration with Ace credential and endpoint defaults."""
2
+
3
+ from typing import Literal
4
+
5
+ from langchain_core.utils import secret_from_env
6
+ from langchain_openai.chat_models.base import BaseChatOpenAI
7
+ from pydantic import Field, SecretStr
8
+
9
+
10
+ class ChatAceDataCloud(BaseChatOpenAI):
11
+ """Use Ace Data Cloud without specifying a custom OpenAI endpoint.
12
+
13
+ Reuses the standard protocol implementation; only the Ace endpoint, credential
14
+ environment, provider identity and billing-sensitive defaults are owned here.
15
+ This class does not register itself in LangChain's upstream provider registry.
16
+ """
17
+
18
+ openai_api_key: SecretStr = Field(
19
+ alias="api_key", default_factory=secret_from_env("ACEDATACLOUD_API_TOKEN")
20
+ )
21
+ openai_api_base: Literal["https://api.acedata.cloud/v1"] = Field(
22
+ default="https://api.acedata.cloud/v1", alias="base_url"
23
+ )
24
+ model_name: str = Field(default="gpt-4o-mini", alias="model")
25
+ use_responses_api: Literal[False] = False
26
+ max_retries: int = 0
27
+ stream_usage: bool = False
28
+ request_timeout: float = Field(default=60, alias="timeout")
29
+
30
+ @property
31
+ def _llm_type(self) -> str:
32
+ return "acedatacloud-chat"
33
+
34
+ @property
35
+ def lc_secrets(self) -> dict[str, str]:
36
+ return {"openai_api_key": "ACEDATACLOUD_API_TOKEN"}
37
+
38
+ def _get_ls_params(self, stop=None, **kwargs):
39
+ params = super()._get_ls_params(stop=stop, **kwargs)
40
+ params["ls_provider"] = "acedatacloud"
41
+ return params
@@ -0,0 +1,69 @@
1
+ """Shared authenticated HTTP boundary. No automatic retries or background polling."""
2
+
3
+ import os
4
+ from typing import Any
5
+
6
+ import httpx
7
+ from pydantic import SecretStr
8
+
9
+
10
+ class AceAPIClient:
11
+ """HTTP client whose credential is excluded from tool schemas and representations."""
12
+
13
+ def __init__(
14
+ self,
15
+ api_token: str | SecretStr | None = None,
16
+ *,
17
+ http_client: httpx.Client | None = None,
18
+ http_async_client: httpx.AsyncClient | None = None,
19
+ ):
20
+ value = api_token or os.environ.get("ACEDATACLOUD_API_TOKEN")
21
+ if not value:
22
+ raise ValueError("Set ACEDATACLOUD_API_TOKEN to an application API Key.")
23
+ self._token = value if isinstance(value, SecretStr) else SecretStr(value)
24
+ self._http = http_client
25
+ self._async_http = http_async_client
26
+
27
+ def __repr__(self) -> str:
28
+ return "AceAPIClient(api_token=SecretStr('**********'))"
29
+
30
+ def _headers(self) -> dict[str, str]:
31
+ return {
32
+ "Authorization": f"Bearer {self._token.get_secret_value()}",
33
+ "Content-Type": "application/json",
34
+ }
35
+
36
+ @staticmethod
37
+ def _url(path: str) -> str:
38
+ # Only fixed service endpoint paths supplied by tool classes are accepted.
39
+ if not path.startswith("/") or path.startswith("//") or "?" in path or "#" in path:
40
+ raise ValueError("Expected a fixed service API path.")
41
+ return "https://api.acedata.cloud" + path
42
+
43
+ def post(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
44
+ if self._http is not None:
45
+ response = self._http.post(self._url(path), json=body, headers=self._headers())
46
+ else:
47
+ with httpx.Client(timeout=60, follow_redirects=False) as client:
48
+ response = client.post(self._url(path), json=body, headers=self._headers())
49
+ return self._decode(response)
50
+
51
+ async def apost(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
52
+ if self._async_http is not None:
53
+ response = await self._async_http.post(
54
+ self._url(path), json=body, headers=self._headers()
55
+ )
56
+ else:
57
+ async with httpx.AsyncClient(timeout=60, follow_redirects=False) as client:
58
+ response = await client.post(self._url(path), json=body, headers=self._headers())
59
+ return self._decode(response)
60
+
61
+ @staticmethod
62
+ def _decode(response: httpx.Response) -> dict[str, Any]:
63
+ # Preserve HTTP status/type. The caller decides whether to retry after
64
+ # checking usage; an uncertain generation is never automatically resubmitted.
65
+ response.raise_for_status()
66
+ data = response.json()
67
+ if not isinstance(data, dict):
68
+ raise ValueError("Expected an object from the Ace API.")
69
+ return data
@@ -0,0 +1,130 @@
1
+ """LangChain-native tools with one submission or one same-ID query per invocation."""
2
+
3
+ from typing import Any, ClassVar
4
+
5
+ from langchain_core.tools import BaseTool
6
+ from langchain_core.tools.base import BaseToolkit
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+ from .client import AceAPIClient
10
+
11
+
12
+ class StrictInput(BaseModel):
13
+ model_config = ConfigDict(extra="forbid")
14
+
15
+
16
+ class TaskInput(StrictInput):
17
+ task_id: str = Field(min_length=1, description="Existing task ID. Never submit again to poll.")
18
+
19
+
20
+ def task_result(data: dict[str, Any], task_id: str | None = None) -> dict[str, Any]:
21
+ """Never treat a preview URL or accepted success=true as a completed task."""
22
+ record = data.get("data") if isinstance(data.get("data"), dict) else data
23
+ task_id = task_id or data.get("task_id") or record.get("task_id") or record.get("id")
24
+ response = record.get("response")
25
+ state = str(record.get("status") or record.get("state") or "").lower()
26
+ failure = state in {"failed", "error", "cancelled", "canceled"}
27
+ finished = record.get("finished_at") is not None
28
+ terminal = finished or failure
29
+ if isinstance(response, dict):
30
+ response_state = str(response.get("status") or response.get("state") or "").lower()
31
+ response_failed = (
32
+ response.get("success") is False
33
+ or bool(response.get("error"))
34
+ or response_state in {"failed", "error", "cancelled", "canceled"}
35
+ )
36
+ if terminal and response_failed:
37
+ failure = True
38
+ if record.get("error") and terminal:
39
+ failure = True
40
+ urls: list[str] = []
41
+
42
+ def collect(value):
43
+ if isinstance(value, dict):
44
+ for key, item in value.items():
45
+ if key in {"url", "image_url", "video_url", "audio_url"} and isinstance(item, str):
46
+ if item.startswith("https://") and item not in urls:
47
+ urls.append(item)
48
+ elif isinstance(item, (dict, list)):
49
+ collect(item)
50
+ elif isinstance(value, list):
51
+ for item in value:
52
+ collect(item)
53
+
54
+ if terminal and not failure:
55
+ collect(response)
56
+ return {
57
+ "task_id": task_id,
58
+ "status": "failed" if failure else ("succeeded" if terminal else "pending"),
59
+ "terminal": terminal,
60
+ "media_urls": urls,
61
+ "raw": data,
62
+ "next_step": (
63
+ "Inspect the final result or failure; do not resubmit to poll."
64
+ if terminal
65
+ else "Query this same task_id later. Generation must not be repeated for polling."
66
+ ),
67
+ }
68
+
69
+
70
+ class AceSubmitTool(BaseTool):
71
+ client: AceAPIClient = Field(exclude=True, repr=False)
72
+ endpoint: ClassVar[str]
73
+ metadata: dict[str, Any] = Field(
74
+ default_factory=lambda: {"billable": True, "provider": "Ace Data Cloud"}
75
+ )
76
+
77
+ @staticmethod
78
+ def submission_result(data: dict[str, Any]) -> dict[str, Any]:
79
+ result = task_result(data)
80
+ if not result["task_id"]:
81
+ raise ValueError(
82
+ "Generation response has no task ID; inspect Usage History before any retry."
83
+ )
84
+ return result
85
+
86
+ def payload(self, args: dict[str, Any]) -> dict[str, Any]:
87
+ return {**args, "async": True}
88
+
89
+ def _run(self, **kwargs) -> dict[str, Any]:
90
+ args = self.args_schema.model_validate(kwargs).model_dump(exclude_none=True)
91
+ return self.submission_result(self.client.post(self.endpoint, self.payload(args)))
92
+
93
+ async def _arun(self, **kwargs) -> dict[str, Any]:
94
+ args = self.args_schema.model_validate(kwargs).model_dump(exclude_none=True)
95
+ return self.submission_result(await self.client.apost(self.endpoint, self.payload(args)))
96
+
97
+
98
+ class AceRetrieveTool(BaseTool):
99
+ client: AceAPIClient = Field(exclude=True, repr=False)
100
+ args_schema: type[BaseModel] = TaskInput
101
+ endpoint: ClassVar[str]
102
+ metadata: dict[str, Any] = Field(
103
+ default_factory=lambda: {"billable_generation": False, "provider": "Ace Data Cloud"}
104
+ )
105
+
106
+ def _run(self, task_id: str) -> dict[str, Any]:
107
+ return task_result(
108
+ self.client.post(self.endpoint, {"action": "retrieve", "id": task_id}), task_id
109
+ )
110
+
111
+ async def _arun(self, task_id: str) -> dict[str, Any]:
112
+ result = await self.client.apost(self.endpoint, {"action": "retrieve", "id": task_id})
113
+ return task_result(result, task_id)
114
+
115
+
116
+ class AceServiceToolkit(BaseToolkit):
117
+ """Choose a service's two tools explicitly; queries alone are the default."""
118
+
119
+ model_config = ConfigDict(arbitrary_types_allowed=True)
120
+ client: AceAPIClient = Field(exclude=True, repr=False)
121
+ include_generation: bool = False
122
+ submit_tool: ClassVar[type[AceSubmitTool]]
123
+ retrieve_tool: ClassVar[type[AceRetrieveTool]]
124
+
125
+ def get_tools(self) -> list[BaseTool]:
126
+ tools: list[BaseTool] = []
127
+ if self.include_generation:
128
+ tools.append(self.submit_tool(client=self.client))
129
+ tools.append(self.retrieve_tool(client=self.client))
130
+ return tools