llama-index-tools-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,8 @@
1
+ from llama_index.tools.tikdataapi.base import (
2
+ TikdataapiAuthError,
3
+ TikdataapiClient,
4
+ TikdataapiError,
5
+ TikdataapiToolSpec,
6
+ )
7
+
8
+ __all__ = ["TikdataapiToolSpec", "TikdataapiClient", "TikdataapiError", "TikdataapiAuthError"]
@@ -0,0 +1,614 @@
1
+ """LlamaIndex tool spec for tikdataapi.com: read-only public TikTok data.
2
+
3
+ Every method is a tool. The docstring is what the model reads, so each one says
4
+ what the call costs in credits. The method names are the names of the tools of
5
+ the hosted MCP server.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import functools
11
+ import re
12
+ from typing import Any, Callable, List, Optional
13
+ from urllib.parse import quote
14
+
15
+ from llama_index.core.tools.tool_spec.base import BaseToolSpec
16
+
17
+ from .client import TikdataapiAuthError, TikdataapiClient, TikdataapiError
18
+
19
+ __all__ = ["TikdataapiToolSpec", "TikdataapiClient", "TikdataapiError", "TikdataapiAuthError"]
20
+
21
+
22
+ def _bad_request(message: str) -> dict:
23
+ """An argument error in the shape of an API error, so the model can repair the call."""
24
+ return {"error": {"code": "bad_request", "message": message}}
25
+
26
+
27
+ #: A video or comment id: the digits at the end of the address of the video.
28
+ _NUMERIC_ID = re.compile(r"^\d{1,20}$")
29
+ #: The id of a sound or of a playlist: up to 25 digits.
30
+ _LONG_ID = re.compile(r"^\d{1,25}$")
31
+ #: A transcript language: a LanguageCodeName of TikTok ("eng-US") or its first part ("eng").
32
+ _LANG = re.compile(r"^[A-Za-z0-9-]{2,20}$")
33
+
34
+
35
+ def _user(value: str) -> str:
36
+ """A username arrives with or without the @; a sec_uid has none to remove."""
37
+ return str(value).strip().lstrip("@")
38
+
39
+
40
+ def _hashtag(value: str) -> str:
41
+ return str(value).strip().lstrip("#")
42
+
43
+
44
+ class _BadArgument(ValueError):
45
+ """An argument no request can be built from."""
46
+
47
+
48
+ def _seg(value: Any) -> str:
49
+ """One URL path segment. The value comes from a model, so nothing in it may
50
+ act as a path: a slash is sent percent-encoded, and a segment that is empty
51
+ or only dots ("..") is refused, because encoding does not change a dot."""
52
+ s = str(value).strip()
53
+ if s.strip(".") == "":
54
+ raise _BadArgument("a user, id or hashtag must not be empty or only dots")
55
+ return quote(s, safe="")
56
+
57
+
58
+ def _numeric(value: Any, what: str, digits: int = 20) -> str:
59
+ """A video, comment, sound or playlist id: digits only."""
60
+ s = str(value).strip()
61
+ if not (_LONG_ID if digits == 25 else _NUMERIC_ID).match(s):
62
+ raise _BadArgument(f"{what} must be a numeric id, 1 to {digits} digits")
63
+ return s
64
+
65
+
66
+ def _repairable(fn: Callable[..., dict]) -> Callable[..., dict]:
67
+ """Give a bad argument back as data, like an API error, so the model can repair the call."""
68
+
69
+ @functools.wraps(fn)
70
+ def wrapper(*args: Any, **kwargs: Any) -> dict:
71
+ try:
72
+ return fn(*args, **kwargs)
73
+ except _BadArgument as err:
74
+ return _bad_request(str(err))
75
+
76
+ return wrapper
77
+
78
+
79
+ class TikdataapiToolSpec(BaseToolSpec):
80
+ """Read public TikTok data: profiles, the videos of an account, its reposts, playlists, followers and
81
+ following, whether it is live, videos, transcripts, related and trending videos, comments, replies, hashtags,
82
+ sounds and their videos, the videos of a playlist, and video, account, sound, live and hashtag search.
83
+
84
+ Read-only. No posting, no likes, no direct messages, no private data, no
85
+ TikTok login: what a logged-out visitor of tiktok.com sees. That includes
86
+ the general ("Top") search of TikTok, videos only, its account search (the
87
+ "Users" tab), its sound and live search (the "Sounds" and "LIVE" tabs),
88
+ and the follower and following lists of an account. TikTok gives a
89
+ logged-out visitor no hashtag search, so hashtag search ranks the hashtags
90
+ of the videos of the general search. It does not include the filters and
91
+ sorting of the Videos tab of search, liked videos, video files, or the
92
+ streams of live rooms.
93
+
94
+ Args:
95
+ api_key: Key from https://tikdataapi.com/dashboard. Read from
96
+ ``TIKDATAAPI_KEY`` when not given.
97
+ max_results: Ceiling on the page size of every paging tool, so one agent
98
+ step cannot spend more than you allow.
99
+ """
100
+
101
+ spec_functions = [
102
+ "get_user",
103
+ "get_users",
104
+ "get_user_videos",
105
+ "get_users_videos",
106
+ "get_user_followers",
107
+ "get_user_following",
108
+ "get_user_reposts",
109
+ "get_user_playlists",
110
+ "get_user_live",
111
+ "get_video",
112
+ "get_videos",
113
+ "get_related_videos",
114
+ "get_trending_videos",
115
+ "get_video_transcript",
116
+ "get_comments",
117
+ "get_comment_replies",
118
+ "get_hashtag",
119
+ "get_hashtag_videos",
120
+ "get_music",
121
+ "get_music_videos",
122
+ "get_playlist_videos",
123
+ "search_videos",
124
+ "search_users",
125
+ "search_music",
126
+ "search_live",
127
+ "search_hashtags",
128
+ "get_balance",
129
+ ]
130
+
131
+ def __init__(
132
+ self,
133
+ api_key: Optional[str] = None,
134
+ *,
135
+ max_results: Optional[int] = None,
136
+ **client_kwargs: Any,
137
+ ) -> None:
138
+ self.client = TikdataapiClient(api_key, max_results=max_results, **client_kwargs)
139
+
140
+ # --- users -----------------------------------------------------------
141
+
142
+ @_repairable
143
+ def get_user(self, user: str) -> dict:
144
+ """Read the public profile of one TikTok account. Costs 1 credit.
145
+
146
+ Gives the nickname, bio, the counts of followers, following, likes and
147
+ videos, and whether the account is verified or private.
148
+
149
+ Args:
150
+ user: Username, with or without the leading @ (for example tiktok),
151
+ or the sec_uid of the account. The sec_uid stays the same when the
152
+ username changes.
153
+ """
154
+ return self.client.get(f"/v1/users/{_seg(_user(user))}")
155
+
156
+ def get_users(self, usernames: List[str]) -> dict:
157
+ """Read up to 100 TikTok profiles in ONE call, by username.
158
+
159
+ Prefer this over repeated single reads: one request, one rate-limit slot.
160
+ Costs 1 credit per profile found; usernames that do not exist are listed
161
+ in ``errors`` with a reason and cost nothing.
162
+
163
+ Args:
164
+ usernames: Usernames, at most 100.
165
+ """
166
+ clean = [_user(u) for u in usernames if _user(u)]
167
+ if not clean:
168
+ return _bad_request("give at least one username")
169
+ if len(clean) > 100:
170
+ return _bad_request("at most 100 usernames in one call")
171
+ return self.client.get("/v1/users/batch", {"usernames": ",".join(clean)})
172
+
173
+ @_repairable
174
+ def get_user_videos(self, user: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
175
+ """Read the videos of one TikTok account: pinned first, then newest first.
176
+
177
+ Each video has its counts of plays, likes, comments and shares. Costs 1
178
+ credit per video; a private account gives an empty list and costs nothing.
179
+
180
+ Args:
181
+ user: Username (with or without @) or sec_uid.
182
+ count: Videos on this page, 1 to 50. Default 16. A page can come back
183
+ shorter; next_cursor then continues with no gap.
184
+ cursor: next_cursor from the previous page.
185
+ """
186
+ if count is not None and not 1 <= count <= 50:
187
+ return _bad_request("count must be from 1 to 50")
188
+ return self.client.get(
189
+ f"/v1/users/{_seg(_user(user))}/videos", {"count": self.client.cap(count), "cursor": cursor}
190
+ )
191
+
192
+ def get_users_videos(self, users: List[str], count: Optional[int] = None) -> dict:
193
+ """Read the newest videos of up to 20 TikTok accounts in ONE call.
194
+
195
+ One entry per account, pinned videos first. Prefer this over repeated
196
+ get_user_videos calls. Costs 1 credit per video; an account with no
197
+ public videos, or a private one, is an empty list and costs nothing.
198
+
199
+ Args:
200
+ users: Usernames or sec_uids, at most 20.
201
+ count: Videos for each account, 1 to 16. Default 3.
202
+ """
203
+ clean = [_user(u) for u in users if _user(u)]
204
+ if not clean:
205
+ return _bad_request("give at least one username or sec_uid")
206
+ if len(clean) > 20:
207
+ return _bad_request("at most 20 users in one call")
208
+ if count is not None and not 1 <= count <= 16:
209
+ return _bad_request("count must be from 1 to 16")
210
+ # max_results caps the videos for each account, as it caps a page elsewhere.
211
+ per_user = self.client.cap(count if count is not None else 3)
212
+ return self.client.get("/v1/users/videos/batch", {"users": ",".join(clean), "count": per_user})
213
+
214
+ @_repairable
215
+ def get_user_reposts(self, user: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
216
+ """Read the videos that one TikTok account reposted, in the order of TikTok.
217
+
218
+ Costs 1 credit per video; a private account or an account with no repost
219
+ gives an empty list and costs nothing.
220
+
221
+ Args:
222
+ user: Username (with or without @) or sec_uid.
223
+ count: Videos on this page, 1 to 50. Default 16. A page can come back
224
+ shorter; next_cursor then continues with no gap.
225
+ cursor: next_cursor from the previous page.
226
+ """
227
+ return self._user_list(user, "reposts", count, cursor)
228
+
229
+ @_repairable
230
+ def get_user_playlists(self, user: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
231
+ """Read the playlists that one TikTok account made: id, name, number of videos, cover and author.
232
+
233
+ Read the videos of one with get_playlist_videos. Costs 1 credit per
234
+ playlist; an account with no playlist gives an empty list and costs
235
+ nothing.
236
+
237
+ Args:
238
+ user: Username (with or without @) or sec_uid.
239
+ count: Playlists on this page, 1 to 50. Default 20.
240
+ cursor: next_cursor from the previous page.
241
+ """
242
+ return self._user_list(user, "playlists", count, cursor)
243
+
244
+ @_repairable
245
+ def get_user_live(self, user: str) -> dict:
246
+ """Read whether one TikTok account is live now. Costs 1 credit, live or not.
247
+
248
+ When it is live: the room id, title, viewers now, start time and cover.
249
+ When it is not: live false and no room fields. No stream addresses.
250
+
251
+ Args:
252
+ user: Username (with or without @) or sec_uid.
253
+ """
254
+ return self.client.get(f"/v1/users/{_seg(_user(user))}/live")
255
+
256
+ def _user_list(self, user: str, which: str, count: Optional[int], cursor: Optional[str]) -> dict:
257
+ if count is not None and not 1 <= count <= 50:
258
+ return _bad_request("count must be from 1 to 50")
259
+ return self.client.get(
260
+ f"/v1/users/{_seg(_user(user))}/{which}", {"count": self.client.cap(count), "cursor": cursor}
261
+ )
262
+
263
+ @_repairable
264
+ def get_user_followers(self, user: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
265
+ """Read the accounts that follow one TikTok account, newest first, as TikTok gives them.
266
+
267
+ Each entry is a profile with its counts; the counts may be rounded,
268
+ get_user gives the exact ones. Costs 1 credit per account; an empty list
269
+ costs nothing.
270
+
271
+ Args:
272
+ user: Username (with or without @) or sec_uid.
273
+ count: Accounts on this page, 1 to 50. Default 30. A page can come back
274
+ shorter; next_cursor then continues with no gap.
275
+ cursor: next_cursor from the previous page.
276
+ """
277
+ return self._user_list(user, "followers", count, cursor)
278
+
279
+ @_repairable
280
+ def get_user_following(self, user: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
281
+ """Read the accounts that one TikTok account follows, newest first, as TikTok gives them.
282
+
283
+ Each entry is a profile with its counts; the counts may be rounded,
284
+ get_user gives the exact ones. Costs 1 credit per account; an empty list
285
+ costs nothing.
286
+
287
+ Args:
288
+ user: Username (with or without @) or sec_uid.
289
+ count: Accounts on this page, 1 to 50. Default 30. A page can come back
290
+ shorter; next_cursor then continues with no gap.
291
+ cursor: next_cursor from the previous page.
292
+ """
293
+ return self._user_list(user, "following", count, cursor)
294
+
295
+ # --- videos ----------------------------------------------------------
296
+
297
+ @_repairable
298
+ def get_video(self, id: str) -> dict:
299
+ """Read one TikTok video by id. Costs 1 credit.
300
+
301
+ Gives the caption, author, sound, hashtags, and the counts of plays,
302
+ likes, comments, shares and saves.
303
+
304
+ Args:
305
+ id: Numeric video id, as a string: the number at the end of the
306
+ address of the video.
307
+ """
308
+ return self.client.get(f"/v1/videos/{_numeric(id, 'id')}")
309
+
310
+ @_repairable
311
+ def get_videos(self, ids: List[str]) -> dict:
312
+ """Read up to 100 TikTok videos by id in ONE call.
313
+
314
+ Prefer this over repeated single reads: one request, one rate-limit slot.
315
+ Costs 1 credit per video found; deleted, private or removed videos are
316
+ listed in ``errors`` with a reason and cost nothing.
317
+
318
+ Args:
319
+ ids: Numeric video ids, at most 100.
320
+ """
321
+ clean = [_numeric(i, "each id") for i in ids]
322
+ if not clean:
323
+ return _bad_request("give at least one video id")
324
+ if len(clean) > 100:
325
+ return _bad_request("at most 100 ids in one call")
326
+ return self.client.get("/v1/videos/batch", {"ids": ",".join(clean)})
327
+
328
+ @_repairable
329
+ def get_related_videos(self, video_id: str, count: Optional[int] = None) -> dict:
330
+ """Read the videos that TikTok shows next to one video ("You may like"), in its order.
331
+
332
+ One page of at most 16 videos, with no next page. Costs 1 credit per video.
333
+
334
+ Args:
335
+ video_id: Numeric id of the video, as a string.
336
+ count: Videos to return, 1 to 16. Default 16.
337
+ """
338
+ if count is not None and not 1 <= count <= 16:
339
+ return _bad_request("count must be from 1 to 16")
340
+ return self.client.get(
341
+ f"/v1/videos/{_numeric(video_id, 'video_id')}/related", {"count": self.client.cap(count)}
342
+ )
343
+
344
+ def get_trending_videos(self, count: Optional[int] = None) -> dict:
345
+ """Read the videos of the explore feed that TikTok shows a logged-out visitor.
346
+
347
+ No repeats in one answer. No cursor and no next page: a call after the
348
+ cache window (2 minutes) gives a new set. Costs 1 credit per video.
349
+
350
+ Args:
351
+ count: Videos to return, 1 to 50. Default 16.
352
+ """
353
+ if count is not None and not 1 <= count <= 50:
354
+ return _bad_request("count must be from 1 to 50")
355
+ return self.client.get("/v1/trending/videos", {"count": self.client.cap(count)})
356
+
357
+ @_repairable
358
+ def get_video_transcript(self, video_id: str, lang: Optional[str] = None) -> dict:
359
+ """Read the transcript of one TikTok video, from its subtitles. Costs 1 credit.
360
+
361
+ Most subtitles are made by the speech recognition of TikTok (source ASR).
362
+ Gives timed segments (start and end in seconds, text), the whole text,
363
+ the language, and the languages the video has. A video with no subtitles
364
+ gives a not_found with reason unavailable and costs nothing.
365
+
366
+ Args:
367
+ video_id: Numeric id of the video, as a string.
368
+ lang: Language of the transcript, as TikTok names it (eng-US) or its
369
+ first part (eng). Default: the first speech-recognition
370
+ transcript, else the first one.
371
+ """
372
+ if lang is not None and not _LANG.match(str(lang)):
373
+ return _bad_request("lang must be 2 to 20 letters, digits or -, as eng-US or eng")
374
+ return self.client.get(f"/v1/videos/{_numeric(video_id, 'video_id')}/transcript", {"lang": lang})
375
+
376
+ @_repairable
377
+ def get_comments(self, video_id: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
378
+ """Read the comments of one TikTok video: pinned first, then the most relevant.
379
+
380
+ Only the comments of the video; read the replies to one comment with
381
+ get_comment_replies. Costs 1 credit per comment; a video with comments
382
+ turned off gives an empty list and costs nothing.
383
+
384
+ Args:
385
+ video_id: Numeric id of the video, as a string.
386
+ count: Comments on this page, 1 to 50. Default 20.
387
+ cursor: next_cursor from the previous page.
388
+ """
389
+ if count is not None and not 1 <= count <= 50:
390
+ return _bad_request("count must be from 1 to 50")
391
+ return self.client.get(
392
+ f"/v1/videos/{_numeric(video_id, 'video_id')}/comments",
393
+ {"count": self.client.cap(count), "cursor": cursor},
394
+ )
395
+
396
+ @_repairable
397
+ def get_comment_replies(
398
+ self, video_id: str, comment_id: str, count: Optional[int] = None, cursor: Optional[str] = None
399
+ ) -> dict:
400
+ """Read the replies to one comment of a TikTok video, oldest first. Costs 1 credit per reply.
401
+
402
+ The ``replies`` field of a comment says how many there are.
403
+
404
+ Args:
405
+ video_id: Numeric id of the video, as a string.
406
+ comment_id: Numeric id of the comment, from get_comments.
407
+ count: Replies on this page, 1 to 50. Default 20.
408
+ cursor: next_cursor from the previous page.
409
+ """
410
+ if count is not None and not 1 <= count <= 50:
411
+ return _bad_request("count must be from 1 to 50")
412
+ video = _numeric(video_id, "video_id")
413
+ comment = _numeric(comment_id, "comment_id")
414
+ return self.client.get(
415
+ f"/v1/videos/{video}/comments/{comment}/replies",
416
+ {"count": self.client.cap(count), "cursor": cursor},
417
+ )
418
+
419
+ # --- hashtags --------------------------------------------------------
420
+
421
+ @_repairable
422
+ def get_hashtag(self, name: str) -> dict:
423
+ """Read one TikTok hashtag: its id, and the counts of its videos and views. Costs 1 credit.
424
+
425
+ Args:
426
+ name: The hashtag, with or without the leading #, in any case. Example: fyp
427
+ """
428
+ return self.client.get(f"/v1/hashtags/{_seg(_hashtag(name))}")
429
+
430
+ @_repairable
431
+ def get_hashtag_videos(self, name: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
432
+ """Read the videos of one TikTok hashtag, in the order of its hashtag page. Costs 1 credit per video.
433
+
434
+ The order is the one of TikTok: popular videos, not newest first.
435
+
436
+ Args:
437
+ name: The hashtag, with or without the leading #, in any case.
438
+ count: Videos on this page, 1 to 50. Default 30.
439
+ cursor: next_cursor from the previous page.
440
+ """
441
+ if count is not None and not 1 <= count <= 50:
442
+ return _bad_request("count must be from 1 to 50")
443
+ return self.client.get(
444
+ f"/v1/hashtags/{_seg(_hashtag(name))}/videos", {"count": self.client.cap(count), "cursor": cursor}
445
+ )
446
+
447
+ # --- sounds and playlists --------------------------------------------
448
+
449
+ @_repairable
450
+ def get_music(self, music_id: str) -> dict:
451
+ """Read one TikTok sound (music) by id. Costs 1 credit.
452
+
453
+ Gives the title, author, album, duration, whether it is an original
454
+ sound, the account of the artist or of its maker, and the number of
455
+ videos that use it (rounded by TikTok).
456
+
457
+ Args:
458
+ music_id: Numeric id of the sound, as a string: the number at the end
459
+ of its address (tiktok.com/music/<name>-<id>), or music.id of a
460
+ video. Example: 6696419263248336898
461
+ """
462
+ return self.client.get(f"/v1/music/{_numeric(music_id, 'music_id', 25)}")
463
+
464
+ @_repairable
465
+ def get_music_videos(self, music_id: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
466
+ """Read the videos that use one TikTok sound, in the order of its sound page. Costs 1 credit per video.
467
+
468
+ The order is the one of TikTok: popular videos, not newest first.
469
+
470
+ Args:
471
+ music_id: Numeric id of the sound, as a string.
472
+ count: Videos on this page, 1 to 50. Default 30.
473
+ cursor: next_cursor from the previous page.
474
+ """
475
+ if count is not None and not 1 <= count <= 50:
476
+ return _bad_request("count must be from 1 to 50")
477
+ return self.client.get(
478
+ f"/v1/music/{_numeric(music_id, 'music_id', 25)}/videos",
479
+ {"count": self.client.cap(count), "cursor": cursor},
480
+ )
481
+
482
+ @_repairable
483
+ def get_playlist_videos(
484
+ self, playlist_id: str, count: Optional[int] = None, cursor: Optional[str] = None
485
+ ) -> dict:
486
+ """Read the videos of one TikTok playlist, in its order. Costs 1 credit per video.
487
+
488
+ Args:
489
+ playlist_id: Numeric id of the playlist, as a string: the id of an
490
+ entry of get_user_playlists, or the number at the end of the
491
+ address of the playlist.
492
+ count: Videos on this page, 1 to 50. Default 30.
493
+ cursor: next_cursor from the previous page.
494
+ """
495
+ if count is not None and not 1 <= count <= 50:
496
+ return _bad_request("count must be from 1 to 50")
497
+ return self.client.get(
498
+ f"/v1/playlists/{_numeric(playlist_id, 'playlist_id', 25)}/videos",
499
+ {"count": self.client.cap(count), "cursor": cursor},
500
+ )
501
+
502
+ # --- search ----------------------------------------------------------
503
+
504
+ def search_videos(self, query: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
505
+ """Search TikTok videos: what the general search of TikTok (the "Top" tab) finds, in its order.
506
+
507
+ Videos only: for accounts use search_users, for sounds search_music, for
508
+ live rooms search_live, for hashtags search_hashtags. No filters or
509
+ sorting. Costs 1 credit per video; a query with no result gives an empty
510
+ list and costs nothing.
511
+
512
+ Args:
513
+ query: Words to search for, as typed in the search box of TikTok: 1 to
514
+ 100 characters after runs of spaces are made one. Example: street food
515
+ count: Videos on this page, 1 to 50. Default 12. A page can come back
516
+ shorter; next_cursor then continues with no gap.
517
+ cursor: next_cursor from the previous page.
518
+ """
519
+ return self._search("videos", query, count, cursor)
520
+
521
+ def search_users(self, query: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
522
+ """Search TikTok accounts: what the account search of TikTok (the "Users" tab) finds, in its order.
523
+
524
+ Each entry is a short profile: id, username, sec_uid, nickname, bio,
525
+ avatar, verified, followers (rounded by TikTok) and likes. For the full,
526
+ exact profile use get_user or get_users. Costs 1 credit per account; a
527
+ query with no result gives an empty list and costs nothing.
528
+
529
+ Args:
530
+ query: Words to search for, as typed in the search box of TikTok: 1 to
531
+ 100 characters after runs of spaces are made one. Example: cooking
532
+ count: Accounts on this page, 1 to 50. Default 10, the size of one
533
+ TikTok page. A page can come back shorter; next_cursor then
534
+ continues with no gap.
535
+ cursor: next_cursor from the previous page.
536
+ """
537
+ return self._search("users", query, count, cursor)
538
+
539
+ def search_music(self, query: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
540
+ """Search TikTok sounds: what the sound search of TikTok (the "Sounds" tab) finds, in its order.
541
+
542
+ Each entry is a short sound: id, title, author, album, duration, cover,
543
+ whether it is an original sound, and the number of videos that use it
544
+ when TikTok gives it. For the full sound use get_music, for its videos
545
+ get_music_videos. Costs 1 credit per sound; a query with no result gives
546
+ an empty list and costs nothing.
547
+
548
+ Args:
549
+ query: Words to search for, as typed in the search box of TikTok: 1 to
550
+ 100 characters after runs of spaces are made one. Example: lofi
551
+ count: Sounds on this page, 1 to 50. Default 12, the size of one
552
+ TikTok page. A page can come back shorter; next_cursor then
553
+ continues with no gap.
554
+ cursor: next_cursor from the previous page.
555
+ """
556
+ return self._search("music", query, count, cursor)
557
+
558
+ def search_live(self, query: str, count: Optional[int] = None, cursor: Optional[str] = None) -> dict:
559
+ """Search TikTok live rooms: what the live search of TikTok (the "LIVE" tab) finds, in its order.
560
+
561
+ Each entry is a room: room id, title, viewers now, start time, cover and
562
+ the account that hosts it. No stream addresses. Results change fast; the
563
+ cache window is 1 minute. Costs 1 credit per room; a query with no
564
+ result gives an empty list and costs nothing.
565
+
566
+ Args:
567
+ query: Words to search for, as typed in the search box of TikTok: 1 to
568
+ 100 characters after runs of spaces are made one. Example: cooking
569
+ count: Rooms on this page, 1 to 50. Default 12.
570
+ cursor: next_cursor from the previous page.
571
+ """
572
+ return self._search("live", query, count, cursor)
573
+
574
+ def search_hashtags(self, query: str, count: Optional[int] = None) -> dict:
575
+ """Search TikTok hashtags for a query, most used first.
576
+
577
+ TikTok gives no hashtag search to a logged-out visitor, so this reads
578
+ about 24 videos of the general search (search_videos) and ranks the
579
+ hashtags of those videos: result_videos is how many of them use the
580
+ hashtag, result_plays the sum of their plays. These are not the totals
581
+ of TikTok: for the total views and videos of a hashtag use get_hashtag.
582
+ No next page. Costs 1 credit per hashtag; a query with no result gives
583
+ an empty list and costs nothing.
584
+
585
+ Args:
586
+ query: Words to search for, as typed in the search box of TikTok: 1 to
587
+ 100 characters after runs of spaces are made one. Example: street food
588
+ count: Hashtags to return, 1 to 30. Default 10. There is no next page.
589
+ """
590
+ q = " ".join(str(query).split())
591
+ if not q:
592
+ return _bad_request("query must not be empty")
593
+ if count is not None and not 1 <= count <= 30:
594
+ return _bad_request("count must be from 1 to 30")
595
+ return self.client.get("/v1/search/hashtags", {"query": q, "count": self.client.cap(count)})
596
+
597
+ def _search(self, kind: str, query: str, count: Optional[int], cursor: Optional[str]) -> dict:
598
+ q = " ".join(str(query).split())
599
+ if not q:
600
+ return _bad_request("query must not be empty")
601
+ if count is not None and not 1 <= count <= 50:
602
+ return _bad_request("count must be from 1 to 50")
603
+ return self.client.get(
604
+ f"/v1/search/{kind}", {"query": q, "count": self.client.cap(count), "cursor": cursor}
605
+ )
606
+
607
+ # --- account ---------------------------------------------------------
608
+
609
+ def get_balance(self) -> dict:
610
+ """Read the credits left on this key and its rate limit. Free.
611
+
612
+ Call it before a large read to check the budget covers the plan.
613
+ """
614
+ return self.client.get("/v1/me")
@@ -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": "llama-index-tools-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,160 @@
1
+ Metadata-Version: 2.5
2
+ Name: llama-index-tools-tikdataapi
3
+ Version: 0.1.0
4
+ Summary: LlamaIndex tool spec 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,live,llama-index,llamahub,llamaindex,llm,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: <4.0,>=3.9
18
+ Requires-Dist: httpx<0.29.0,>=0.27.0
19
+ Requires-Dist: llama-index-core<0.15,>=0.12.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # llama-index-tools-tikdataapi
23
+
24
+ LlamaIndex tool spec for [tikdataapi.com](https://tikdataapi.com): read-only public TikTok data.
25
+ Profiles, the videos of an account, its reposts, playlists, followers and following, videos, comments,
26
+ replies, transcripts, related and trending videos, hashtags, sounds and their videos, the videos of a
27
+ playlist, whether an account is live, and video, account, sound, live and hashtag search.
28
+
29
+ Read-only by design. No posting, no likes, no direct messages, no private data, and no TikTok login: the
30
+ tools read what a logged-out visitor of tiktok.com sees. That includes the general ("Top") search of TikTok,
31
+ videos only, its account search (the "Users" tab), its sound and live search (the "Sounds" and "LIVE" tabs),
32
+ and the follower and following lists of an account. TikTok gives a logged-out visitor no hashtag search, so
33
+ hashtag search ranks the hashtags of the videos of the general search. It does not include the filters and
34
+ sorting of the Videos tab of search (TikTok ignores them for a logged-out visitor), liked videos, video files or
35
+ the streams of live rooms.
36
+ Not affiliated with TikTok or ByteDance.
37
+
38
+ ```bash
39
+ pip install llama-index-tools-tikdataapi
40
+ ```
41
+
42
+ ## Use
43
+
44
+ ```python
45
+ from llama_index.tools.tikdataapi import TikdataapiToolSpec
46
+
47
+ # Reads TIKDATAAPI_KEY from the environment.
48
+ tool_spec = TikdataapiToolSpec()
49
+ tools = tool_spec.to_tool_list()
50
+ ```
51
+
52
+ With an agent:
53
+
54
+ ```python
55
+ from llama_index.core.agent.workflow import FunctionAgent
56
+ from llama_index.llms.anthropic import Anthropic
57
+ from llama_index.tools.tikdataapi import TikdataapiToolSpec
58
+
59
+ agent = FunctionAgent(
60
+ tools=TikdataapiToolSpec(max_results=25).to_tool_list(),
61
+ llm=Anthropic(model="claude-opus-5"),
62
+ )
63
+ print(await agent.run("What did @nba post this week, and how did people react?"))
64
+ ```
65
+
66
+ One call on its own:
67
+
68
+ ```python
69
+ TikdataapiToolSpec().get_user_videos("nba", count=10)
70
+ ```
71
+
72
+ ## Tools
73
+
74
+ The names are the names of the tools of the hosted MCP server.
75
+
76
+ | Tool | Reads | Credits |
77
+ |---|---|---|
78
+ | `get_user` | One profile, by username or `sec_uid` | 1 |
79
+ | `get_users` | Up to 100 profiles in one call, by username | 1 per profile |
80
+ | `get_user_videos` | The videos of an account: pinned first, then newest first | 1 per video |
81
+ | `get_users_videos` | The newest 1 to 16 videos of up to 20 accounts in one call | 1 per video |
82
+ | `get_user_followers` | The accounts that follow an account, newest first | 1 per profile |
83
+ | `get_user_following` | The accounts an account follows, newest first | 1 per profile |
84
+ | `get_user_reposts` | The videos an account reposted | 1 per video |
85
+ | `get_user_playlists` | The playlists an account made | 1 per playlist |
86
+ | `get_user_live` | Whether an account is live now, with its room | 1, live or not |
87
+ | `get_video` | One video, with its author, sound and counts | 1 |
88
+ | `get_videos` | Up to 100 videos in one call | 1 per video |
89
+ | `get_related_videos` | The videos TikTok shows next to a video: one page of up to 16, no cursor | 1 per video |
90
+ | `get_trending_videos` | The explore feed of a logged-out visitor: up to 50, no cursor | 1 per video |
91
+ | `get_video_transcript` | The transcript of a video from its subtitles: timed segments and text | 1 |
92
+ | `get_comments` | The comments of a video: pinned first, then the most relevant | 1 per comment |
93
+ | `get_comment_replies` | The replies to one comment, oldest first | 1 per reply |
94
+ | `get_hashtag` | One hashtag with its counts of videos and views | 1 |
95
+ | `get_hashtag_videos` | The videos of a hashtag, in the order of the hashtag page | 1 per video |
96
+ | `get_music` | One sound (music) by id, with the number of videos that use it | 1 |
97
+ | `get_music_videos` | The videos that use a sound, in the order of the sound page | 1 per video |
98
+ | `get_playlist_videos` | The videos of a playlist, in its order | 1 per video |
99
+ | `search_videos` | The videos that the general ("Top") search of TikTok finds for a query | 1 per video |
100
+ | `search_users` | The accounts that the account search of TikTok finds for a query, as short profiles | 1 per profile |
101
+ | `search_music` | The sounds that the sound search of TikTok finds for a query, as short sounds | 1 per sound |
102
+ | `search_live` | The live rooms that the live search of TikTok finds for a query | 1 per room |
103
+ | `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 |
104
+ | `get_balance` | Credits left and rate limit | free |
105
+
106
+ Empty results and failed requests cost nothing: a private account, a video with comments turned off, a deleted
107
+ video, a search with no result. A repeated read inside the cache window costs half.
108
+ Every response carries `credits_charged` and `balance_remaining`, so the model can watch the budget
109
+ and stop on its own.
110
+
111
+ In an entry of a follower or following list the counts may be rounded; `get_user` gives the exact ones.
112
+ An entry of `search_users` is a short profile: the follower count is rounded, and there is no following count,
113
+ video count or private flag; `get_user` or `get_users` gives the full profile.
114
+ A sound and a playlist are read by their numeric id (up to 25 digits): the number at the end of the address
115
+ of the sound, `music.id` of a video, or the `id` of an entry of `get_user_playlists`. The count of videos
116
+ of a sound is rounded by TikTok. `get_related_videos` and `get_trending_videos` have no next page.
117
+ `get_user_live` costs 1 credit whether the account is live or not; when it is not, `live` is false and the
118
+ room fields are absent. `get_video_transcript` takes an optional `lang` (`eng-US` or `eng`); a video with no
119
+ subtitles is a `not_found` with reason `unavailable`, free.
120
+ `search_hashtags` reads about 24 videos of the general search and ranks their hashtags by `result_videos`
121
+ (how many of those videos use the hashtag), then `result_plays` (the sum of their plays). These counts are of
122
+ those videos only, not the totals of TikTok: `get_hashtag` gives those. `count` is 1 to 30, default 10, and
123
+ there is no next page.
124
+ Not known yet: how deep TikTok lets a follower list or a search be read, and what it gives for a private
125
+ account or a hidden following list.
126
+
127
+ ## Spending guards
128
+
129
+ `max_results` caps the page size of every paging tool, and the videos for each account in
130
+ `get_users_videos`:
131
+
132
+ ```python
133
+ tool_spec = TikdataapiToolSpec(max_results=25)
134
+ ```
135
+
136
+ Narrow the surface with the LlamaIndex argument:
137
+
138
+ ```python
139
+ tools = TikdataapiToolSpec().to_tool_list(spec_functions=["get_user", "get_user_videos", "get_balance"])
140
+ ```
141
+
142
+ ## Errors
143
+
144
+ A failure the model can act on — no credits, not found (with a `reason`: nonexistent, banned, private,
145
+ removed, unavailable), a bad argument — comes back as a dict with `error.code`, so the model can change plan.
146
+ None of those are charged.
147
+ A missing or revoked key raises `TikdataapiAuthError`, because no model can repair it.
148
+ Rate limits and upstream faults raise `TikdataapiError`.
149
+
150
+ ## MCP instead
151
+
152
+ An agent that speaks MCP needs no package. The hosted server is at `https://api.tikdataapi.com/mcp`
153
+ (Streamable HTTP, OAuth or `x-api-key`), with the registry name `com.tikdataapi/tikdataapi`.
154
+
155
+ ## Keys and pricing
156
+
157
+ Get a key at [tikdataapi.com/dashboard](https://tikdataapi.com/dashboard). 1,000 credits to start, no card.
158
+ Prepaid packs from $10; credits never expire. Live status: [tikdataapi.com/status](https://tikdataapi.com/status).
159
+
160
+ MIT licensed.
@@ -0,0 +1,7 @@
1
+ llama_index/tools/tikdataapi/__init__.py,sha256=Fj7ZRosIe2AKF6mhoOd_Ut9_Wn4Ul8V5qNEhn16g7k4,238
2
+ llama_index/tools/tikdataapi/base.py,sha256=Z9KMZO8tU0WuLQOR8YI65XK0uLSFSsiRO1Q5jFNf7Tk,27371
3
+ llama_index/tools/tikdataapi/client.py,sha256=A205pIChIGnPl0jM5zmKKSBiYVARBuAImA9YTahhC28,5340
4
+ llama_index_tools_tikdataapi-0.1.0.dist-info/METADATA,sha256=Un0HOWh4XmC0u2Puqu0F3rp_ALRvSdHynEjn46u5qH0,8597
5
+ llama_index_tools_tikdataapi-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ llama_index_tools_tikdataapi-0.1.0.dist-info/licenses/LICENSE,sha256=XVMstaphO8td8MXbJDStQ-HioxR0vAUtNSh3LAJMZjs,1071
7
+ llama_index_tools_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.