langchain-tikdataapi 0.1.0__py3-none-any.whl

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,81 @@
1
+ """LangChain tools for tikdataapi.com: read-only public TikTok data.
2
+
3
+ from langchain_tikdataapi import TikdataapiToolkit
4
+
5
+ tools = TikdataapiToolkit.from_api_key().get_tools()
6
+
7
+ Read-only by design. No posting, no likes, no direct messages, no private data,
8
+ no TikTok login. Not affiliated with TikTok or ByteDance.
9
+ Docs: https://tikdataapi.com/docs
10
+ """
11
+
12
+ from .client import TikdataapiAuthError, TikdataapiClient, TikdataapiError
13
+ from .toolkit import TikdataapiToolkit
14
+ from .tools import (
15
+ ALL_TOOLS,
16
+ GetBalance,
17
+ GetCommentReplies,
18
+ GetComments,
19
+ GetHashtag,
20
+ GetHashtagVideos,
21
+ GetMusic,
22
+ GetMusicVideos,
23
+ GetPlaylistVideos,
24
+ GetRelatedVideos,
25
+ GetTrendingVideos,
26
+ GetUser,
27
+ GetUserFollowers,
28
+ GetUserFollowing,
29
+ GetUserLive,
30
+ GetUserPlaylists,
31
+ GetUserReposts,
32
+ GetUsers,
33
+ GetUsersVideos,
34
+ GetUserVideos,
35
+ GetVideo,
36
+ GetVideos,
37
+ GetVideoTranscript,
38
+ SearchHashtags,
39
+ SearchLive,
40
+ SearchMusic,
41
+ SearchUsers,
42
+ SearchVideos,
43
+ )
44
+
45
+ __version__ = "0.1.0"
46
+
47
+ __all__ = [
48
+ "ALL_TOOLS",
49
+ "GetBalance",
50
+ "GetCommentReplies",
51
+ "GetComments",
52
+ "GetHashtag",
53
+ "GetHashtagVideos",
54
+ "GetMusic",
55
+ "GetMusicVideos",
56
+ "GetPlaylistVideos",
57
+ "GetRelatedVideos",
58
+ "GetTrendingVideos",
59
+ "GetUser",
60
+ "GetUserFollowers",
61
+ "GetUserFollowing",
62
+ "GetUserLive",
63
+ "GetUserPlaylists",
64
+ "GetUserReposts",
65
+ "GetUserVideos",
66
+ "GetUsers",
67
+ "GetUsersVideos",
68
+ "GetVideo",
69
+ "GetVideoTranscript",
70
+ "GetVideos",
71
+ "SearchHashtags",
72
+ "SearchLive",
73
+ "SearchMusic",
74
+ "SearchUsers",
75
+ "SearchVideos",
76
+ "TikdataapiAuthError",
77
+ "TikdataapiClient",
78
+ "TikdataapiError",
79
+ "TikdataapiToolkit",
80
+ "__version__",
81
+ ]
@@ -0,0 +1,149 @@
1
+ """HTTP client for the tikdataapi.com REST API.
2
+
3
+ The tools hand the model the JSON the API returns, unchanged, so it sees
4
+ ``credits_charged`` and ``balance_remaining`` on every call and can stop before
5
+ the balance runs out.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ from typing import Any, Mapping
12
+
13
+ import httpx
14
+
15
+ BASE_URL = "https://api.tikdataapi.com"
16
+
17
+ #: Failures the model can act on: try another username, ask for a smaller page,
18
+ #: tell the user the balance is empty. These come back as data.
19
+ _REPORTED = frozenset({400, 402, 403, 404})
20
+
21
+
22
+ class TikdataapiError(RuntimeError):
23
+ """A call failed in a way the model cannot repair."""
24
+
25
+ def __init__(self, message: str, *, code: str = "", status: int = 0, request_id: str = "") -> None:
26
+ super().__init__(message)
27
+ self.code = code
28
+ self.status = status
29
+ self.request_id = request_id
30
+
31
+
32
+ class TikdataapiAuthError(TikdataapiError):
33
+ """The key is missing, unknown or revoked. A configuration fault."""
34
+
35
+
36
+ def _problem(response: httpx.Response) -> dict[str, Any]:
37
+ try:
38
+ body = response.json()
39
+ except ValueError:
40
+ body = {}
41
+ return body if isinstance(body, dict) else {}
42
+
43
+
44
+ class TikdataapiClient:
45
+ """Thin wrapper over the REST API. Sync and async, one key.
46
+
47
+ Args:
48
+ api_key: Key from https://tikdataapi.com/dashboard. Read from
49
+ ``TIKDATAAPI_KEY`` when not given.
50
+ base_url: Override for testing or for a private deployment.
51
+ timeout: Seconds per request.
52
+ max_results: Ceiling on ``count`` for every paging tool. Set it to cap
53
+ what one agent step can spend. ``None`` leaves the API default.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ api_key: str | None = None,
59
+ *,
60
+ base_url: str = BASE_URL,
61
+ timeout: float = 30.0,
62
+ max_results: int | None = None,
63
+ client: httpx.Client | None = None,
64
+ async_client: httpx.AsyncClient | None = None,
65
+ ) -> None:
66
+ key = api_key or os.environ.get("TIKDATAAPI_KEY")
67
+ if not key:
68
+ raise TikdataapiAuthError(
69
+ "No API key. Pass api_key=... or set TIKDATAAPI_KEY. "
70
+ "Get one at https://tikdataapi.com/dashboard."
71
+ )
72
+ self.api_key = key
73
+ self.base_url = base_url.rstrip("/")
74
+ self.timeout = timeout
75
+ self.max_results = max_results
76
+ self._client = client
77
+ self._async_client = async_client
78
+
79
+ @property
80
+ def _headers(self) -> dict[str, str]:
81
+ return {
82
+ "x-api-key": self.api_key,
83
+ "accept": "application/json",
84
+ "user-agent": "langchain-tikdataapi",
85
+ }
86
+
87
+ def cap(self, count: int | None) -> int | None:
88
+ """Apply ``max_results`` to a requested page size."""
89
+ if count is None:
90
+ return self.max_results
91
+ if self.max_results is None:
92
+ return count
93
+ return min(count, self.max_results)
94
+
95
+ def _handle(self, response: httpx.Response) -> dict[str, Any]:
96
+ if response.status_code < 400:
97
+ return _problem(response)
98
+
99
+ body = _problem(response)
100
+ error = body.get("error") or {}
101
+ code = str(error.get("code") or "")
102
+ message = str(error.get("message") or response.reason_phrase or "request failed")
103
+ request_id = str(body.get("request_id") or "")
104
+
105
+ if response.status_code == 401:
106
+ raise TikdataapiAuthError(
107
+ f"{message} (code {code or 'invalid_key'}). "
108
+ "Check TIKDATAAPI_KEY against https://tikdataapi.com/dashboard.",
109
+ code=code,
110
+ status=401,
111
+ request_id=request_id,
112
+ )
113
+ if response.status_code in _REPORTED:
114
+ # Nothing was charged for these. Let the model read and decide.
115
+ return body
116
+ raise TikdataapiError(
117
+ f"{message} (HTTP {response.status_code}, code {code}, request {request_id})",
118
+ code=code,
119
+ status=response.status_code,
120
+ request_id=request_id,
121
+ )
122
+
123
+ @staticmethod
124
+ def _clean(params: Mapping[str, Any] | None) -> dict[str, Any]:
125
+ return {k: v for k, v in (params or {}).items() if v is not None}
126
+
127
+ def get(self, path: str, params: Mapping[str, Any] | None = None) -> dict[str, Any]:
128
+ client = self._client
129
+ if client is None:
130
+ with httpx.Client(timeout=self.timeout) as fresh:
131
+ return self._handle(
132
+ fresh.get(f"{self.base_url}{path}", params=self._clean(params), headers=self._headers)
133
+ )
134
+ return self._handle(
135
+ client.get(f"{self.base_url}{path}", params=self._clean(params), headers=self._headers)
136
+ )
137
+
138
+ async def aget(self, path: str, params: Mapping[str, Any] | None = None) -> dict[str, Any]:
139
+ client = self._async_client
140
+ if client is None:
141
+ async with httpx.AsyncClient(timeout=self.timeout) as fresh:
142
+ return self._handle(
143
+ await fresh.get(
144
+ f"{self.base_url}{path}", params=self._clean(params), headers=self._headers
145
+ )
146
+ )
147
+ return self._handle(
148
+ await client.get(f"{self.base_url}{path}", params=self._clean(params), headers=self._headers)
149
+ )
@@ -0,0 +1,64 @@
1
+ """The whole read surface as one toolkit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Iterable
6
+
7
+ from langchain_core.tools import BaseTool
8
+ from langchain_core.tools.base import BaseToolkit
9
+ from pydantic import ConfigDict
10
+
11
+ from .client import TikdataapiClient
12
+ from .tools import ALL_TOOLS
13
+
14
+
15
+ class TikdataapiToolkit(BaseToolkit):
16
+ """Every read tool, sharing one client and one credit budget.
17
+
18
+ Example:
19
+ >>> from langchain_tikdataapi import TikdataapiToolkit
20
+ >>> toolkit = TikdataapiToolkit.from_api_key(max_results=25)
21
+ >>> tools = toolkit.get_tools()
22
+
23
+ Args:
24
+ client: A configured :class:`TikdataapiClient`.
25
+ include: Tool names to keep. ``None`` keeps them all.
26
+ exclude: Tool names to drop, applied after ``include``.
27
+ """
28
+
29
+ model_config = ConfigDict(arbitrary_types_allowed=True)
30
+
31
+ client: TikdataapiClient
32
+ include: tuple[str, ...] | None = None
33
+ exclude: tuple[str, ...] = ()
34
+
35
+ @classmethod
36
+ def from_api_key(
37
+ cls,
38
+ api_key: str | None = None,
39
+ *,
40
+ max_results: int | None = None,
41
+ include: Iterable[str] | None = None,
42
+ exclude: Iterable[str] = (),
43
+ **client_kwargs: object,
44
+ ) -> "TikdataapiToolkit":
45
+ """Build a toolkit from a key, or from ``TIKDATAAPI_KEY``.
46
+
47
+ ``max_results`` caps the page size of every paging tool, which caps what
48
+ one agent step can spend.
49
+ """
50
+ return cls(
51
+ client=TikdataapiClient(api_key, max_results=max_results, **client_kwargs), # type: ignore[arg-type]
52
+ include=tuple(include) if include is not None else None,
53
+ exclude=tuple(exclude),
54
+ )
55
+
56
+ def get_tools(self) -> list[BaseTool]:
57
+ tools = [tool(client=self.client) for tool in ALL_TOOLS]
58
+ if self.include is not None:
59
+ wanted = set(self.include)
60
+ tools = [t for t in tools if t.name in wanted]
61
+ if self.exclude:
62
+ unwanted = set(self.exclude)
63
+ tools = [t for t in tools if t.name not in unwanted]
64
+ return tools
@@ -0,0 +1,780 @@
1
+ """LangChain tools over the tikdataapi.com read endpoints.
2
+
3
+ Every tool is read-only. The credit cost is written into each description, so a
4
+ model that plans a multi-step read knows what the plan costs before it runs it.
5
+
6
+ The tool names are the names of the tools of the hosted MCP server with a
7
+ ``tiktok_`` prefix, so they stay unique next to the tools of other toolkits:
8
+ ``tiktok_get_user_videos`` is the MCP tool ``get_user_videos``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import re
15
+ from typing import Any, Sequence
16
+ from urllib.parse import quote
17
+
18
+ from langchain_core.callbacks import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun
19
+ from langchain_core.tools import BaseTool
20
+ from pydantic import BaseModel, ConfigDict, Field
21
+
22
+ from .client import TikdataapiClient
23
+
24
+
25
+ #: A video or comment id: the digits at the end of the address of the video.
26
+ _NUMERIC_ID = re.compile(r"^\d{1,20}$")
27
+ #: The id of a sound or of a playlist: up to 25 digits.
28
+ _LONG_ID = re.compile(r"^\d{1,25}$")
29
+ #: A transcript language: a LanguageCodeName of TikTok ("eng-US") or its first part ("eng").
30
+ _LANG = re.compile(r"^[A-Za-z0-9-]{2,20}$")
31
+
32
+
33
+ def _user(value: str) -> str:
34
+ """A username arrives with or without the @; a sec_uid has none to remove."""
35
+ return str(value).strip().lstrip("@")
36
+
37
+
38
+ def _hashtag(value: str) -> str:
39
+ return str(value).strip().lstrip("#")
40
+
41
+
42
+ def _seg(value: Any) -> str:
43
+ """One URL path segment. The value comes from a model, so nothing in it may
44
+ act as a path: a slash is sent percent-encoded, and a segment that is empty
45
+ or only dots ("..") is refused, because encoding does not change a dot."""
46
+ s = str(value).strip()
47
+ if s.strip(".") == "":
48
+ raise ValueError("a user, id or hashtag must not be empty or only dots")
49
+ return quote(s, safe="")
50
+
51
+
52
+ def _numeric(value: Any, what: str, digits: int = 20) -> str:
53
+ """A video, comment, sound or playlist id for a path. Digits only, also
54
+ when the tool is called without its schema."""
55
+ s = str(value).strip()
56
+ if not (_LONG_ID if digits == 25 else _NUMERIC_ID).match(s):
57
+ raise ValueError(f"{what} must be a numeric id, 1 to {digits} digits")
58
+ return s
59
+
60
+
61
+ def _dump(payload: dict[str, Any]) -> str:
62
+ return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
63
+
64
+
65
+ class _Base(BaseTool):
66
+ """Shared plumbing: one client, JSON in and JSON out."""
67
+
68
+ model_config = ConfigDict(arbitrary_types_allowed=True)
69
+
70
+ client: TikdataapiClient
71
+ response_format: str = "content"
72
+
73
+ def _call(self, **kwargs: Any) -> tuple[str, dict[str, Any] | None]:
74
+ raise NotImplementedError
75
+
76
+ def _run(self, run_manager: CallbackManagerForToolRun | None = None, **kwargs: Any) -> str:
77
+ path, params = self._call(**kwargs)
78
+ return _dump(self.client.get(path, params))
79
+
80
+ async def _arun(self, run_manager: AsyncCallbackManagerForToolRun | None = None, **kwargs: Any) -> str:
81
+ path, params = self._call(**kwargs)
82
+ return _dump(await self.client.aget(path, params))
83
+
84
+
85
+ _FRESH = "Read TikTok again and skip the cache. Costs double for an item that has a cached copy."
86
+ _CURSOR = "next_cursor from the previous page."
87
+ _USER = (
88
+ "Username, with or without the leading @ (for example tiktok), or the sec_uid of the account. "
89
+ "The sec_uid stays the same when the username changes."
90
+ )
91
+
92
+
93
+ def _count(default: int, maximum: int) -> Any:
94
+ # The API answers `default` items when count is left out. Both numbers
95
+ # differ per endpoint, so say them here.
96
+ return Field(
97
+ default=None,
98
+ ge=1,
99
+ le=maximum,
100
+ description=(
101
+ f"Results on this page, 1 to {maximum}. Default {default}. A page can come back shorter; "
102
+ "next_cursor then continues with no gap."
103
+ ),
104
+ )
105
+
106
+
107
+ # --- users ---------------------------------------------------------------
108
+
109
+
110
+ class _UserArgs(BaseModel):
111
+ user: str = Field(description=_USER)
112
+ fresh: bool | None = Field(default=None, description=_FRESH)
113
+
114
+
115
+ class GetUser(_Base):
116
+ name: str = "tiktok_get_user"
117
+ description: str = (
118
+ "Public profile of one TikTok account, by username or sec_uid: nickname, bio, counts of "
119
+ "followers, following, likes and videos, verified and private state. Costs 1 credit."
120
+ )
121
+ args_schema: type[BaseModel] = _UserArgs
122
+
123
+ def _call(self, user: str, fresh: bool | None = None) -> tuple[str, dict[str, Any] | None]:
124
+ return f"/v1/users/{_seg(_user(user))}", {"fresh": fresh}
125
+
126
+
127
+ class _UsersArgs(BaseModel):
128
+ usernames: Sequence[str] = Field(min_length=1, max_length=100, description="Up to 100 usernames in one call.")
129
+ fresh: bool | None = Field(default=None, description=_FRESH)
130
+
131
+
132
+ class GetUsers(_Base):
133
+ name: str = "tiktok_get_users"
134
+ description: str = (
135
+ "Profiles of up to 100 TikTok accounts in ONE call, by username. Prefer this over repeated "
136
+ "single reads: it is one request and one rate-limit slot. Costs 1 credit per profile found; "
137
+ "usernames that do not exist are listed in errors with a reason and cost nothing."
138
+ )
139
+ args_schema: type[BaseModel] = _UsersArgs
140
+
141
+ def _call(self, usernames: Sequence[str], fresh: bool | None = None) -> tuple[str, dict[str, Any] | None]:
142
+ clean = [_user(u) for u in usernames if _user(u)]
143
+ if not clean:
144
+ raise ValueError("give at least one username")
145
+ if len(clean) > 100:
146
+ raise ValueError("at most 100 usernames in one call")
147
+ return "/v1/users/batch", {"usernames": ",".join(clean), "fresh": fresh}
148
+
149
+
150
+ class _UserVideosArgs(BaseModel):
151
+ user: str = Field(description=_USER)
152
+ count: int | None = _count(16, 50)
153
+ cursor: str | None = Field(default=None, description=_CURSOR)
154
+ fresh: bool | None = Field(default=None, description=_FRESH)
155
+
156
+
157
+ class GetUserVideos(_Base):
158
+ name: str = "tiktok_get_user_videos"
159
+ description: str = (
160
+ "Videos of one TikTok account: pinned videos first, then newest first, with their counts of "
161
+ "plays, likes, comments and shares. Pages with next_cursor. Costs 1 credit per video; a private "
162
+ "account gives an empty list and costs nothing."
163
+ )
164
+ args_schema: type[BaseModel] = _UserVideosArgs
165
+
166
+ def _call(
167
+ self, user: str, count: int | None = None, cursor: str | None = None, fresh: bool | None = None
168
+ ) -> tuple[str, dict[str, Any] | None]:
169
+ return f"/v1/users/{_seg(_user(user))}/videos", {
170
+ "count": self.client.cap(count),
171
+ "cursor": cursor,
172
+ "fresh": fresh,
173
+ }
174
+
175
+
176
+ class _UsersVideosArgs(BaseModel):
177
+ users: Sequence[str] = Field(
178
+ min_length=1, max_length=20, description="Up to 20 usernames or sec_uids in one call."
179
+ )
180
+ count: int | None = Field(default=None, ge=1, le=16, description="Videos for each account, 1 to 16. Default 3.")
181
+ fresh: bool | None = Field(default=None, description=_FRESH)
182
+
183
+
184
+ class GetUsersVideos(_Base):
185
+ name: str = "tiktok_get_users_videos"
186
+ description: str = (
187
+ "Newest videos of up to 20 TikTok accounts in ONE call: count videos for each account, pinned "
188
+ "first, one entry per account. Prefer this over repeated tiktok_get_user_videos calls. Costs 1 "
189
+ "credit per video; an account with no public videos, or a private one, is an empty list and "
190
+ "costs nothing."
191
+ )
192
+ args_schema: type[BaseModel] = _UsersVideosArgs
193
+
194
+ def _call(
195
+ self, users: Sequence[str], count: int | None = None, fresh: bool | None = None
196
+ ) -> tuple[str, dict[str, Any] | None]:
197
+ clean = [_user(u) for u in users if _user(u)]
198
+ if not clean:
199
+ raise ValueError("give at least one username or sec_uid")
200
+ if len(clean) > 20:
201
+ raise ValueError("at most 20 users in one call")
202
+ if count is not None and not 1 <= count <= 16:
203
+ raise ValueError("count must be from 1 to 16")
204
+ # max_results caps the videos for each account, as it caps a page elsewhere.
205
+ per_user = self.client.cap(count if count is not None else 3)
206
+ return "/v1/users/videos/batch", {"users": ",".join(clean), "count": per_user, "fresh": fresh}
207
+
208
+
209
+ class _UserListArgs(BaseModel):
210
+ user: str = Field(description=_USER)
211
+ count: int | None = _count(30, 50)
212
+ cursor: str | None = Field(default=None, description=_CURSOR)
213
+ fresh: bool | None = Field(default=None, description=_FRESH)
214
+
215
+
216
+ def _user_list(what: str) -> str:
217
+ return (
218
+ f"{what} newest first, as TikTok gives them. Each entry is a profile with its counts; the "
219
+ "counts may be rounded, tiktok_get_user gives the exact ones. Pages with next_cursor. Costs 1 "
220
+ "credit per account; an empty list costs nothing."
221
+ )
222
+
223
+
224
+ class _UserList(_Base):
225
+ #: The last segment of the route: followers or following.
226
+ list_name: str = ""
227
+
228
+ def _call(
229
+ self, user: str, count: int | None = None, cursor: str | None = None, fresh: bool | None = None
230
+ ) -> tuple[str, dict[str, Any] | None]:
231
+ return f"/v1/users/{_seg(_user(user))}/{self.list_name}", {
232
+ "count": self.client.cap(count),
233
+ "cursor": cursor,
234
+ "fresh": fresh,
235
+ }
236
+
237
+
238
+ class GetUserFollowers(_UserList):
239
+ name: str = "tiktok_get_user_followers"
240
+ description: str = _user_list("Accounts that follow one TikTok account, by username or sec_uid:")
241
+ args_schema: type[BaseModel] = _UserListArgs
242
+ list_name: str = "followers"
243
+
244
+
245
+ class GetUserFollowing(_UserList):
246
+ name: str = "tiktok_get_user_following"
247
+ description: str = _user_list("Accounts that one TikTok account follows, by username or sec_uid:")
248
+ args_schema: type[BaseModel] = _UserListArgs
249
+ list_name: str = "following"
250
+
251
+
252
+ class GetUserReposts(_UserList):
253
+ name: str = "tiktok_get_user_reposts"
254
+ description: str = (
255
+ "Videos that one TikTok account reposted, by username or sec_uid, in the order of TikTok. Pages "
256
+ "with next_cursor. Costs 1 credit per video; a private account or an account with no repost "
257
+ "gives an empty list and costs nothing."
258
+ )
259
+ args_schema: type[BaseModel] = _UserVideosArgs
260
+ list_name: str = "reposts"
261
+
262
+
263
+ class _UserPlaylistsArgs(BaseModel):
264
+ user: str = Field(description=_USER)
265
+ count: int | None = _count(20, 50)
266
+ cursor: str | None = Field(default=None, description=_CURSOR)
267
+ fresh: bool | None = Field(default=None, description=_FRESH)
268
+
269
+
270
+ class GetUserPlaylists(_UserList):
271
+ name: str = "tiktok_get_user_playlists"
272
+ description: str = (
273
+ "Playlists that one TikTok account made, by username or sec_uid: id, name, number of videos, "
274
+ "cover and author of each. Read the videos of one with tiktok_get_playlist_videos. Pages with "
275
+ "next_cursor. Costs 1 credit per playlist; an account with no playlist gives an empty list and "
276
+ "costs nothing."
277
+ )
278
+ args_schema: type[BaseModel] = _UserPlaylistsArgs
279
+ list_name: str = "playlists"
280
+
281
+
282
+ class GetUserLive(_Base):
283
+ name: str = "tiktok_get_user_live"
284
+ description: str = (
285
+ "Whether one TikTok account, by username or sec_uid, is live now. When it is: the room id, "
286
+ "title, viewers now, start time and cover. When it is not: live false and no room fields. No "
287
+ "stream addresses. Costs 1 credit either way."
288
+ )
289
+ args_schema: type[BaseModel] = _UserArgs
290
+
291
+ def _call(self, user: str, fresh: bool | None = None) -> tuple[str, dict[str, Any] | None]:
292
+ return f"/v1/users/{_seg(_user(user))}/live", {"fresh": fresh}
293
+
294
+
295
+ # --- videos --------------------------------------------------------------
296
+
297
+
298
+ class _VideoArgs(BaseModel):
299
+ id: str = Field(
300
+ pattern=r"^\d{1,20}$",
301
+ description="Numeric video id, as a string: the number at the end of the address of the video.",
302
+ )
303
+ fresh: bool | None = Field(default=None, description=_FRESH)
304
+
305
+
306
+ class GetVideo(_Base):
307
+ name: str = "tiktok_get_video"
308
+ description: str = (
309
+ "One TikTok video by id: caption, author, sound, hashtags, counts of plays, likes, comments, "
310
+ "shares and saves. Costs 1 credit."
311
+ )
312
+ args_schema: type[BaseModel] = _VideoArgs
313
+
314
+ def _call(self, id: str, fresh: bool | None = None) -> tuple[str, dict[str, Any] | None]:
315
+ return f"/v1/videos/{_numeric(id, 'id')}", {"fresh": fresh}
316
+
317
+
318
+ class _VideosArgs(BaseModel):
319
+ ids: Sequence[str] = Field(min_length=1, max_length=100, description="Up to 100 numeric video ids in one call.")
320
+ fresh: bool | None = Field(default=None, description=_FRESH)
321
+
322
+
323
+ class GetVideos(_Base):
324
+ name: str = "tiktok_get_videos"
325
+ description: str = (
326
+ "Up to 100 TikTok videos by id in ONE call. Prefer this over repeated single reads. Costs 1 "
327
+ "credit per video found; deleted, private or removed videos are listed in errors with a reason "
328
+ "and cost nothing."
329
+ )
330
+ args_schema: type[BaseModel] = _VideosArgs
331
+
332
+ def _call(self, ids: Sequence[str], fresh: bool | None = None) -> tuple[str, dict[str, Any] | None]:
333
+ clean = [_numeric(i, "each id") for i in ids]
334
+ if not clean:
335
+ raise ValueError("give at least one video id")
336
+ if len(clean) > 100:
337
+ raise ValueError("at most 100 ids in one call")
338
+ return "/v1/videos/batch", {"ids": ",".join(clean), "fresh": fresh}
339
+
340
+
341
+ class _RelatedArgs(BaseModel):
342
+ video_id: str = Field(pattern=r"^\d{1,20}$", description="Numeric id of the video, as a string.")
343
+ count: int | None = Field(
344
+ default=None, ge=1, le=16, description="Videos to return, 1 to 16. Default 16. There is no next page."
345
+ )
346
+ fresh: bool | None = Field(default=None, description=_FRESH)
347
+
348
+
349
+ class GetRelatedVideos(_Base):
350
+ name: str = "tiktok_get_related_videos"
351
+ description: str = (
352
+ 'Videos that TikTok shows next to one video ("You may like"), in the order of TikTok. One page '
353
+ "of at most 16 videos, with no next page. Costs 1 credit per video."
354
+ )
355
+ args_schema: type[BaseModel] = _RelatedArgs
356
+
357
+ def _call(
358
+ self, video_id: str, count: int | None = None, fresh: bool | None = None
359
+ ) -> tuple[str, dict[str, Any] | None]:
360
+ return f"/v1/videos/{_numeric(video_id, 'video_id')}/related", {
361
+ "count": self.client.cap(count),
362
+ "fresh": fresh,
363
+ }
364
+
365
+
366
+ class _TrendingArgs(BaseModel):
367
+ count: int | None = Field(
368
+ default=None, ge=1, le=50, description="Videos to return, 1 to 50. Default 16. There is no next page."
369
+ )
370
+ fresh: bool | None = Field(default=None, description=_FRESH)
371
+
372
+
373
+ class GetTrendingVideos(_Base):
374
+ name: str = "tiktok_get_trending_videos"
375
+ description: str = (
376
+ "Videos of the explore feed that TikTok shows a logged-out visitor, as TikTok gives them, with "
377
+ "no repeats in one answer. No cursor: a call after the cache window (2 minutes) gives a new "
378
+ "set. Costs 1 credit per video."
379
+ )
380
+ args_schema: type[BaseModel] = _TrendingArgs
381
+
382
+ def _call(self, count: int | None = None, fresh: bool | None = None) -> tuple[str, dict[str, Any] | None]:
383
+ return "/v1/trending/videos", {"count": self.client.cap(count), "fresh": fresh}
384
+
385
+
386
+ class _TranscriptArgs(BaseModel):
387
+ video_id: str = Field(pattern=r"^\d{1,20}$", description="Numeric id of the video, as a string.")
388
+ lang: str | None = Field(
389
+ default=None,
390
+ pattern=r"^[A-Za-z0-9-]{2,20}$",
391
+ description=(
392
+ "Language of the transcript, as TikTok names it (eng-US) or its first part (eng). Default: the "
393
+ "first speech-recognition transcript, else the first one. The languages of a video are in the "
394
+ "field languages."
395
+ ),
396
+ )
397
+ fresh: bool | None = Field(default=None, description=_FRESH)
398
+
399
+
400
+ class GetVideoTranscript(_Base):
401
+ name: str = "tiktok_get_video_transcript"
402
+ description: str = (
403
+ "The transcript of one TikTok video, from the subtitles of TikTok (most are made by its speech "
404
+ "recognition, source ASR): timed segments (start and end in seconds, text), the whole text, the "
405
+ "language, and the languages the video has. Costs 1 credit; a video with no subtitles gives a "
406
+ "not_found with reason unavailable and costs nothing."
407
+ )
408
+ args_schema: type[BaseModel] = _TranscriptArgs
409
+
410
+ def _call(
411
+ self, video_id: str, lang: str | None = None, fresh: bool | None = None
412
+ ) -> tuple[str, dict[str, Any] | None]:
413
+ if lang is not None and not _LANG.match(str(lang)):
414
+ raise ValueError("lang must be 2 to 20 letters, digits or -, as eng-US or eng")
415
+ return f"/v1/videos/{_numeric(video_id, 'video_id')}/transcript", {"lang": lang, "fresh": fresh}
416
+
417
+
418
+ class _CommentsArgs(BaseModel):
419
+ video_id: str = Field(pattern=r"^\d{1,20}$", description="Numeric id of the video, as a string.")
420
+ count: int | None = _count(20, 50)
421
+ cursor: str | None = Field(default=None, description=_CURSOR)
422
+ fresh: bool | None = Field(default=None, description=_FRESH)
423
+
424
+
425
+ class GetComments(_Base):
426
+ name: str = "tiktok_get_comments"
427
+ description: str = (
428
+ "Comments of one TikTok video, in the order of TikTok: pinned first, then the most relevant. "
429
+ "Only the comments of the video; read the replies to one comment with "
430
+ "tiktok_get_comment_replies. Pages with next_cursor. Costs 1 credit per comment; a video with "
431
+ "comments turned off gives an empty list and costs nothing."
432
+ )
433
+ args_schema: type[BaseModel] = _CommentsArgs
434
+
435
+ def _call(
436
+ self, video_id: str, count: int | None = None, cursor: str | None = None, fresh: bool | None = None
437
+ ) -> tuple[str, dict[str, Any] | None]:
438
+ return f"/v1/videos/{_numeric(video_id, 'video_id')}/comments", {
439
+ "count": self.client.cap(count),
440
+ "cursor": cursor,
441
+ "fresh": fresh,
442
+ }
443
+
444
+
445
+ class _RepliesArgs(BaseModel):
446
+ video_id: str = Field(pattern=r"^\d{1,20}$", description="Numeric id of the video, as a string.")
447
+ comment_id: str = Field(
448
+ pattern=r"^\d{1,20}$", description="Numeric id of the comment, from tiktok_get_comments."
449
+ )
450
+ count: int | None = _count(20, 50)
451
+ cursor: str | None = Field(default=None, description=_CURSOR)
452
+ fresh: bool | None = Field(default=None, description=_FRESH)
453
+
454
+
455
+ class GetCommentReplies(_Base):
456
+ name: str = "tiktok_get_comment_replies"
457
+ description: str = (
458
+ "Replies to one comment of a TikTok video, oldest first, as TikTok shows them under the "
459
+ "comment. The replies field of a comment says how many there are. Pages with next_cursor. "
460
+ "Costs 1 credit per reply."
461
+ )
462
+ args_schema: type[BaseModel] = _RepliesArgs
463
+
464
+ def _call(
465
+ self,
466
+ video_id: str,
467
+ comment_id: str,
468
+ count: int | None = None,
469
+ cursor: str | None = None,
470
+ fresh: bool | None = None,
471
+ ) -> tuple[str, dict[str, Any] | None]:
472
+ video = _numeric(video_id, "video_id")
473
+ comment = _numeric(comment_id, "comment_id")
474
+ return f"/v1/videos/{video}/comments/{comment}/replies", {
475
+ "count": self.client.cap(count),
476
+ "cursor": cursor,
477
+ "fresh": fresh,
478
+ }
479
+
480
+
481
+ # --- hashtags ------------------------------------------------------------
482
+
483
+
484
+ class _HashtagArgs(BaseModel):
485
+ name: str = Field(description="The hashtag, with or without the leading #, in any case. Example: fyp")
486
+ fresh: bool | None = Field(default=None, description=_FRESH)
487
+
488
+
489
+ class GetHashtag(_Base):
490
+ name: str = "tiktok_get_hashtag"
491
+ description: str = (
492
+ "One TikTok hashtag: its id, description, and the counts of its videos and of their views. "
493
+ "Costs 1 credit."
494
+ )
495
+ args_schema: type[BaseModel] = _HashtagArgs
496
+
497
+ def _call(self, name: str, fresh: bool | None = None) -> tuple[str, dict[str, Any] | None]:
498
+ return f"/v1/hashtags/{_seg(_hashtag(name))}", {"fresh": fresh}
499
+
500
+
501
+ class _HashtagVideosArgs(BaseModel):
502
+ name: str = Field(description="The hashtag, with or without the leading #, in any case. Example: fyp")
503
+ count: int | None = _count(30, 50)
504
+ cursor: str | None = Field(default=None, description=_CURSOR)
505
+ fresh: bool | None = Field(default=None, description=_FRESH)
506
+
507
+
508
+ class GetHashtagVideos(_Base):
509
+ name: str = "tiktok_get_hashtag_videos"
510
+ description: str = (
511
+ "Videos of one TikTok hashtag, in the order of the hashtag page of TikTok: popular videos, not "
512
+ "newest first. Pages with next_cursor. Costs 1 credit per video."
513
+ )
514
+ args_schema: type[BaseModel] = _HashtagVideosArgs
515
+
516
+ def _call(
517
+ self, name: str, count: int | None = None, cursor: str | None = None, fresh: bool | None = None
518
+ ) -> tuple[str, dict[str, Any] | None]:
519
+ return f"/v1/hashtags/{_seg(_hashtag(name))}/videos", {
520
+ "count": self.client.cap(count),
521
+ "cursor": cursor,
522
+ "fresh": fresh,
523
+ }
524
+
525
+
526
+ # --- sounds and playlists ------------------------------------------------
527
+
528
+ _MUSIC_ID = (
529
+ "Numeric id of the sound, as a string: the number at the end of its address "
530
+ "(tiktok.com/music/<name>-<id>), or music.id of a video. Example: 6696419263248336898"
531
+ )
532
+
533
+
534
+ class _MusicArgs(BaseModel):
535
+ music_id: str = Field(pattern=r"^\d{1,25}$", description=_MUSIC_ID)
536
+ fresh: bool | None = Field(default=None, description=_FRESH)
537
+
538
+
539
+ class GetMusic(_Base):
540
+ name: str = "tiktok_get_music"
541
+ description: str = (
542
+ "One TikTok sound (music) by id: title, author, album, duration, whether it is an original "
543
+ "sound, the account of the artist or of its maker, and the number of videos that use it "
544
+ "(rounded by TikTok). Costs 1 credit."
545
+ )
546
+ args_schema: type[BaseModel] = _MusicArgs
547
+
548
+ def _call(self, music_id: str, fresh: bool | None = None) -> tuple[str, dict[str, Any] | None]:
549
+ return f"/v1/music/{_numeric(music_id, 'music_id', 25)}", {"fresh": fresh}
550
+
551
+
552
+ class _MusicVideosArgs(BaseModel):
553
+ music_id: str = Field(pattern=r"^\d{1,25}$", description=_MUSIC_ID)
554
+ count: int | None = _count(30, 50)
555
+ cursor: str | None = Field(default=None, description=_CURSOR)
556
+ fresh: bool | None = Field(default=None, description=_FRESH)
557
+
558
+
559
+ class GetMusicVideos(_Base):
560
+ name: str = "tiktok_get_music_videos"
561
+ description: str = (
562
+ "Videos that use one TikTok sound, in the order of the sound page of TikTok: popular videos, "
563
+ "not newest first. Pages with next_cursor. Costs 1 credit per video."
564
+ )
565
+ args_schema: type[BaseModel] = _MusicVideosArgs
566
+
567
+ def _call(
568
+ self, music_id: str, count: int | None = None, cursor: str | None = None, fresh: bool | None = None
569
+ ) -> tuple[str, dict[str, Any] | None]:
570
+ return f"/v1/music/{_numeric(music_id, 'music_id', 25)}/videos", {
571
+ "count": self.client.cap(count),
572
+ "cursor": cursor,
573
+ "fresh": fresh,
574
+ }
575
+
576
+
577
+ class _PlaylistVideosArgs(BaseModel):
578
+ playlist_id: str = Field(
579
+ pattern=r"^\d{1,25}$",
580
+ description=(
581
+ "Numeric id of the playlist, as a string: the id of an entry of tiktok_get_user_playlists, "
582
+ "or the number at the end of the address of the playlist."
583
+ ),
584
+ )
585
+ count: int | None = _count(30, 50)
586
+ cursor: str | None = Field(default=None, description=_CURSOR)
587
+ fresh: bool | None = Field(default=None, description=_FRESH)
588
+
589
+
590
+ class GetPlaylistVideos(_Base):
591
+ name: str = "tiktok_get_playlist_videos"
592
+ description: str = (
593
+ "Videos of one TikTok playlist, in the order of the playlist. Pages with next_cursor. Costs 1 "
594
+ "credit per video; an empty playlist costs nothing."
595
+ )
596
+ args_schema: type[BaseModel] = _PlaylistVideosArgs
597
+
598
+ def _call(
599
+ self, playlist_id: str, count: int | None = None, cursor: str | None = None, fresh: bool | None = None
600
+ ) -> tuple[str, dict[str, Any] | None]:
601
+ return f"/v1/playlists/{_numeric(playlist_id, 'playlist_id', 25)}/videos", {
602
+ "count": self.client.cap(count),
603
+ "cursor": cursor,
604
+ "fresh": fresh,
605
+ }
606
+
607
+
608
+ # --- search --------------------------------------------------------------
609
+
610
+
611
+ def _search_args(example: str, default: int) -> type[BaseModel]:
612
+ class _SearchArgs(BaseModel):
613
+ query: str = Field(
614
+ min_length=1,
615
+ max_length=200,
616
+ description=(
617
+ "Words to search for, as typed in the search box of TikTok: 1 to 100 characters after runs "
618
+ f"of spaces are made one. Example: {example}"
619
+ ),
620
+ )
621
+ count: int | None = _count(default, 50)
622
+ cursor: str | None = Field(default=None, description=_CURSOR)
623
+ fresh: bool | None = Field(default=None, description=_FRESH)
624
+
625
+ return _SearchArgs
626
+
627
+
628
+ class _Search(_Base):
629
+ #: The last segment of the route: videos or users.
630
+ kind: str = ""
631
+
632
+ def _call(
633
+ self, query: str, count: int | None = None, cursor: str | None = None, fresh: bool | None = None
634
+ ) -> tuple[str, dict[str, Any] | None]:
635
+ q = " ".join(str(query).split())
636
+ if not q:
637
+ raise ValueError("query must not be empty")
638
+ return f"/v1/search/{self.kind}", {
639
+ "query": q,
640
+ "count": self.client.cap(count),
641
+ "cursor": cursor,
642
+ "fresh": fresh,
643
+ }
644
+
645
+
646
+ class SearchVideos(_Search):
647
+ name: str = "tiktok_search_videos"
648
+ description: str = (
649
+ 'Videos that the general search of TikTok (the "Top" tab) finds for a query, in the order of '
650
+ "TikTok. Videos only: for accounts use tiktok_search_users, for sounds tiktok_search_music, for "
651
+ "live rooms tiktok_search_live, for hashtags tiktok_search_hashtags. No filters or sorting. Pages "
652
+ "with next_cursor. Costs 1 credit per video; a query with no result gives an empty list and costs "
653
+ "nothing."
654
+ )
655
+ args_schema: type[BaseModel] = _search_args("street food", 12)
656
+ kind: str = "videos"
657
+
658
+
659
+ class SearchUsers(_Search):
660
+ name: str = "tiktok_search_users"
661
+ description: str = (
662
+ 'Accounts that the account search of TikTok (the "Users" tab) finds for a query, in the order '
663
+ "of TikTok. Each entry is a short profile: id, username, sec_uid, nickname, bio, avatar, "
664
+ "verified, followers (rounded by TikTok) and likes. For the full, exact profile use "
665
+ "tiktok_get_user or tiktok_get_users. Pages with next_cursor. Costs 1 credit per account; a "
666
+ "query with no result gives an empty list and costs nothing."
667
+ )
668
+ args_schema: type[BaseModel] = _search_args("cooking", 10)
669
+ kind: str = "users"
670
+
671
+
672
+ class SearchMusic(_Search):
673
+ name: str = "tiktok_search_music"
674
+ description: str = (
675
+ 'Sounds (music) that the sound search of TikTok (the "Sounds" tab) finds for a query, in the '
676
+ "order of TikTok. Each entry is a short sound: id, title, author, album, duration, cover, whether "
677
+ "it is an original sound, and the number of videos that use it when TikTok gives it. For the full "
678
+ "sound use tiktok_get_music, for its videos tiktok_get_music_videos. Pages with next_cursor. Costs "
679
+ "1 credit per sound; a query with no result gives an empty list and costs nothing."
680
+ )
681
+ args_schema: type[BaseModel] = _search_args("lofi", 12)
682
+ kind: str = "music"
683
+
684
+
685
+ class SearchLive(_Search):
686
+ name: str = "tiktok_search_live"
687
+ description: str = (
688
+ 'Live rooms that the live search of TikTok (the "LIVE" tab) finds for a query, in the order of '
689
+ "TikTok: room id, title, viewers now, start time, cover and the account that hosts it. No stream "
690
+ "addresses. Results change fast; the cache window is 1 minute. Costs 1 credit per room; a query "
691
+ "with no result gives an empty list and costs nothing."
692
+ )
693
+ args_schema: type[BaseModel] = _search_args("cooking", 12)
694
+ kind: str = "live"
695
+
696
+
697
+ class _HashtagSearchArgs(BaseModel):
698
+ query: str = Field(
699
+ min_length=1,
700
+ max_length=200,
701
+ description=(
702
+ "Words to search for, as typed in the search box of TikTok: 1 to 100 characters after runs "
703
+ "of spaces are made one. Example: street food"
704
+ ),
705
+ )
706
+ count: int | None = Field(
707
+ default=None, ge=1, le=30, description="Hashtags to return, 1 to 30. Default 10. There is no next page."
708
+ )
709
+ fresh: bool | None = Field(default=None, description=_FRESH)
710
+
711
+
712
+ class SearchHashtags(_Base):
713
+ name: str = "tiktok_search_hashtags"
714
+ description: str = (
715
+ "Hashtags for a query, most used first. TikTok gives no hashtag search to a logged-out visitor, so "
716
+ "this reads about 24 videos of the general search (tiktok_search_videos) and ranks the hashtags of "
717
+ "those videos: result_videos is how many of them use the hashtag, result_plays the sum of their "
718
+ "plays. These are not the totals of TikTok: for the total views and videos of a hashtag use "
719
+ "tiktok_get_hashtag. No next page. Costs 1 credit per hashtag; a query with no result gives an "
720
+ "empty list and costs nothing."
721
+ )
722
+ args_schema: type[BaseModel] = _HashtagSearchArgs
723
+
724
+ def _call(
725
+ self, query: str, count: int | None = None, fresh: bool | None = None
726
+ ) -> tuple[str, dict[str, Any] | None]:
727
+ q = " ".join(str(query).split())
728
+ if not q:
729
+ raise ValueError("query must not be empty")
730
+ return "/v1/search/hashtags", {"query": q, "count": self.client.cap(count), "fresh": fresh}
731
+
732
+
733
+ # --- account -------------------------------------------------------------
734
+
735
+
736
+ class _NoArgs(BaseModel):
737
+ pass
738
+
739
+
740
+ class GetBalance(_Base):
741
+ name: str = "tiktok_get_balance"
742
+ description: str = (
743
+ "Credits left on this key and its rate limit. Free. Call it before a large read to check "
744
+ "the budget covers the plan."
745
+ )
746
+ args_schema: type[BaseModel] = _NoArgs
747
+
748
+ def _call(self) -> tuple[str, dict[str, Any] | None]:
749
+ return "/v1/me", None
750
+
751
+
752
+ ALL_TOOLS: tuple[type[_Base], ...] = (
753
+ GetUser,
754
+ GetUsers,
755
+ GetUserVideos,
756
+ GetUsersVideos,
757
+ GetUserFollowers,
758
+ GetUserFollowing,
759
+ GetUserReposts,
760
+ GetUserPlaylists,
761
+ GetUserLive,
762
+ GetVideo,
763
+ GetVideos,
764
+ GetRelatedVideos,
765
+ GetTrendingVideos,
766
+ GetVideoTranscript,
767
+ GetComments,
768
+ GetCommentReplies,
769
+ GetHashtag,
770
+ GetHashtagVideos,
771
+ GetMusic,
772
+ GetMusicVideos,
773
+ GetPlaylistVideos,
774
+ SearchVideos,
775
+ SearchUsers,
776
+ SearchMusic,
777
+ SearchLive,
778
+ SearchHashtags,
779
+ GetBalance,
780
+ )
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-tikdataapi
3
+ Version: 0.1.0
4
+ Summary: LangChain tools for tikdataapi.com: read-only public TikTok profiles, videos, comments, replies, hashtags, sounds, playlists, reposts, related and trending videos, transcripts, live state, video, account, sound, live and hashtag search and follower lists.
5
+ Project-URL: Homepage, https://tikdataapi.com
6
+ Project-URL: Documentation, https://tikdataapi.com/docs
7
+ Project-URL: API reference, https://tikdataapi.com/reference
8
+ Project-URL: Source code, https://github.com/tikdataapi/tikdataapi
9
+ Project-URL: Issue tracker, https://github.com/tikdataapi/tikdataapi/issues
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,comments,followers,hashtags,langchain,langgraph,live,llm,mcp,music,playlists,search,tikdataapi,tiktok,tiktok-api,tools,transcripts,trending,videos
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: httpx<0.29.0,>=0.27.0
19
+ Requires-Dist: langchain-core<2.0.0,>=0.3.0
20
+ Requires-Dist: pydantic<3.0.0,>=2.7.0
21
+ Description-Content-Type: text/markdown
22
+
23
+ # langchain-tikdataapi
24
+
25
+ LangChain tools for [tikdataapi.com](https://tikdataapi.com): read-only public TikTok data.
26
+ Profiles, the videos of an account, its reposts, playlists, followers and following, videos, comments,
27
+ replies, transcripts, related and trending videos, hashtags, sounds and their videos, the videos of a
28
+ playlist, whether an account is live, and video, account, sound, live and hashtag search.
29
+
30
+ Read-only by design. No posting, no likes, no direct messages, no private data, and no TikTok login: the
31
+ tools read what a logged-out visitor of tiktok.com sees. That includes the general ("Top") search of TikTok,
32
+ videos only, its account search (the "Users" tab), its sound and live search (the "Sounds" and "LIVE" tabs),
33
+ and the follower and following lists of an account. TikTok gives a logged-out visitor no hashtag search, so
34
+ hashtag search ranks the hashtags of the videos of the general search. It does not include the filters and
35
+ sorting of the Videos tab of search (TikTok ignores them for a logged-out visitor), liked videos, video files or
36
+ the streams of live rooms.
37
+ Not affiliated with TikTok or ByteDance.
38
+
39
+ ```bash
40
+ pip install langchain-tikdataapi
41
+ ```
42
+
43
+ ## Use
44
+
45
+ ```python
46
+ from langchain_tikdataapi import TikdataapiToolkit
47
+
48
+ # Reads TIKDATAAPI_KEY from the environment.
49
+ tools = TikdataapiToolkit.from_api_key().get_tools()
50
+ ```
51
+
52
+ With an agent:
53
+
54
+ ```python
55
+ from langchain.agents import create_agent
56
+ from langchain_tikdataapi import TikdataapiToolkit
57
+
58
+ agent = create_agent(
59
+ "anthropic:claude-opus-5",
60
+ tools=TikdataapiToolkit.from_api_key(max_results=25).get_tools(),
61
+ )
62
+ result = agent.invoke({"messages": [{"role": "user", "content": "What did @nba post this week, and how did people react?"}]})
63
+ ```
64
+
65
+ One tool on its own:
66
+
67
+ ```python
68
+ from langchain_tikdataapi import GetUserVideos, TikdataapiClient
69
+
70
+ videos = GetUserVideos(client=TikdataapiClient())
71
+ print(videos.invoke({"user": "nba", "count": 10}))
72
+ ```
73
+
74
+ ## Tools
75
+
76
+ The names are the tools of the hosted MCP server with a `tiktok_` prefix, so they stay unique next to the
77
+ tools of other toolkits.
78
+
79
+ | Tool | Reads | Credits |
80
+ |---|---|---|
81
+ | `tiktok_get_user` | One profile, by username or `sec_uid` | 1 |
82
+ | `tiktok_get_users` | Up to 100 profiles in one call, by username | 1 per profile |
83
+ | `tiktok_get_user_videos` | The videos of an account: pinned first, then newest first | 1 per video |
84
+ | `tiktok_get_users_videos` | The newest 1 to 16 videos of up to 20 accounts in one call | 1 per video |
85
+ | `tiktok_get_user_followers` | The accounts that follow an account, newest first | 1 per profile |
86
+ | `tiktok_get_user_following` | The accounts an account follows, newest first | 1 per profile |
87
+ | `tiktok_get_user_reposts` | The videos an account reposted | 1 per video |
88
+ | `tiktok_get_user_playlists` | The playlists an account made | 1 per playlist |
89
+ | `tiktok_get_user_live` | Whether an account is live now, with its room | 1, live or not |
90
+ | `tiktok_get_video` | One video, with its author, sound and counts | 1 |
91
+ | `tiktok_get_videos` | Up to 100 videos in one call | 1 per video |
92
+ | `tiktok_get_related_videos` | The videos TikTok shows next to a video: one page of up to 16, no cursor | 1 per video |
93
+ | `tiktok_get_trending_videos` | The explore feed of a logged-out visitor: up to 50, no cursor | 1 per video |
94
+ | `tiktok_get_video_transcript` | The transcript of a video from its subtitles: timed segments and text | 1 |
95
+ | `tiktok_get_comments` | The comments of a video: pinned first, then the most relevant | 1 per comment |
96
+ | `tiktok_get_comment_replies` | The replies to one comment, oldest first | 1 per reply |
97
+ | `tiktok_get_hashtag` | One hashtag with its counts of videos and views | 1 |
98
+ | `tiktok_get_hashtag_videos` | The videos of a hashtag, in the order of the hashtag page | 1 per video |
99
+ | `tiktok_get_music` | One sound (music) by id, with the number of videos that use it | 1 |
100
+ | `tiktok_get_music_videos` | The videos that use a sound, in the order of the sound page | 1 per video |
101
+ | `tiktok_get_playlist_videos` | The videos of a playlist, in its order | 1 per video |
102
+ | `tiktok_search_videos` | The videos that the general ("Top") search of TikTok finds for a query | 1 per video |
103
+ | `tiktok_search_users` | The accounts that the account search of TikTok finds for a query, as short profiles | 1 per profile |
104
+ | `tiktok_search_music` | The sounds that the sound search of TikTok finds for a query, as short sounds | 1 per sound |
105
+ | `tiktok_search_live` | The live rooms that the live search of TikTok finds for a query | 1 per room |
106
+ | `tiktok_search_hashtags` | The hashtags of the videos of the general search for a query, most used first: up to 30, no cursor | 1 per hashtag |
107
+ | `tiktok_get_balance` | Credits left and rate limit | free |
108
+
109
+ Empty results and failed requests cost nothing: a private account, a video with comments turned off, a deleted
110
+ video, a search with no result. A repeated read inside the cache window costs half.
111
+ Every response carries `credits_charged` and `balance_remaining`, so the model can see the budget shrink
112
+ and stop on its own.
113
+
114
+ A `user` is a username, with or without the `@`, or a `sec_uid`. Video and comment ids are strings of digits.
115
+ In an entry of a follower or following list the counts may be rounded; `tiktok_get_user` gives the exact ones.
116
+ An entry of `tiktok_search_users` is a short profile: the follower count is rounded, and there is no following
117
+ count, video count or private flag; `tiktok_get_user` or `tiktok_get_users` gives the full profile.
118
+ A sound and a playlist are read by their numeric id (up to 25 digits): the number at the end of the address
119
+ of the sound, `music.id` of a video, or the `id` of an entry of `tiktok_get_user_playlists`. The count of videos
120
+ of a sound is rounded by TikTok. `tiktok_get_related_videos` and `tiktok_get_trending_videos` have no next page.
121
+ `tiktok_get_user_live` costs 1 credit whether the account is live or not; when it is not, `live` is false and
122
+ the room fields are absent. `tiktok_get_video_transcript` takes an optional `lang` (`eng-US` or `eng`); a video
123
+ with no subtitles is a `not_found` with reason `unavailable`, free.
124
+ `tiktok_search_hashtags` reads about 24 videos of the general search and ranks their hashtags by `result_videos`
125
+ (how many of those videos use the hashtag), then `result_plays` (the sum of their plays). These counts are of
126
+ those videos only, not the totals of TikTok: `tiktok_get_hashtag` gives those. `count` is 1 to 30, default 10, and
127
+ there is no next page.
128
+ Not known yet: how deep TikTok lets a follower list or a search be read, and what it gives for a private
129
+ account or a hidden following list.
130
+
131
+ ## Spending guards
132
+
133
+ `max_results` caps the page size of every paging tool, and the videos for each account in
134
+ `tiktok_get_users_videos`, so one agent step cannot ask for more than you allow:
135
+
136
+ ```python
137
+ toolkit = TikdataapiToolkit.from_api_key(max_results=25)
138
+ ```
139
+
140
+ Narrow the surface with `include` or `exclude`:
141
+
142
+ ```python
143
+ toolkit = TikdataapiToolkit.from_api_key(include=["tiktok_get_user", "tiktok_get_user_videos", "tiktok_get_balance"])
144
+ ```
145
+
146
+ ## Errors
147
+
148
+ A failure the model can act on — no credits, not found (with a `reason`: nonexistent, banned, private,
149
+ removed, unavailable), a bad argument — comes back as JSON with `error.code`, so the model can change plan.
150
+ None of those are charged.
151
+ A missing or revoked key raises `TikdataapiAuthError`, because no model can repair it.
152
+ Rate limits and upstream faults raise `TikdataapiError`, so your framework's retry policy sees them.
153
+
154
+ ## MCP instead
155
+
156
+ An agent that speaks MCP needs no package. Connect the hosted server:
157
+
158
+ ```bash
159
+ claude mcp add --transport http tikdataapi https://api.tikdataapi.com/mcp
160
+ ```
161
+
162
+ It signs in with OAuth on first use. Its registry name is `com.tikdataapi/tikdataapi`.
163
+
164
+ ## Keys and pricing
165
+
166
+ Get a key at [tikdataapi.com/dashboard](https://tikdataapi.com/dashboard). 1,000 credits to start, no card.
167
+ Prepaid packs from $10; credits never expire. Live status: [tikdataapi.com/status](https://tikdataapi.com/status).
168
+
169
+ MIT licensed.
@@ -0,0 +1,8 @@
1
+ langchain_tikdataapi/__init__.py,sha256=HTkLIu9rzVCnRQJkB5RzBU2-FnPq2oyhZgT86M0GHaQ,1752
2
+ langchain_tikdataapi/client.py,sha256=Op-XMRWb1q_IceQeGGj1epBB32QOr_S5BFElcdyWAjE,5332
3
+ langchain_tikdataapi/toolkit.py,sha256=3MNZUg_WgHZXz9vNbO9vu6MB9DuJ2qLyI5p6S88NJek,2089
4
+ langchain_tikdataapi/tools.py,sha256=p1jT8O048NH65G2Bn1MH5gAWsKP5hS90K6Ft48IE_rU,30477
5
+ langchain_tikdataapi-0.1.0.dist-info/METADATA,sha256=ztHwqBvZ8sG5N7zeQYekABC0BwieA0SGtJpJg0T48yA,9271
6
+ langchain_tikdataapi-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ langchain_tikdataapi-0.1.0.dist-info/licenses/LICENSE,sha256=XVMstaphO8td8MXbJDStQ-HioxR0vAUtNSh3LAJMZjs,1071
8
+ langchain_tikdataapi-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tikdataapi.com
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.