intentkit 0.8.11.dev1__py3-none-any.whl → 0.8.12__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.

Potentially problematic release.


This version of intentkit might be problematic. Click here for more details.

Files changed (183) hide show
  1. intentkit/__init__.py +1 -1
  2. intentkit/abstracts/graph.py +4 -0
  3. intentkit/abstracts/skill.py +2 -140
  4. intentkit/clients/twitter.py +35 -28
  5. intentkit/core/agent.py +2 -374
  6. intentkit/core/asset.py +63 -16
  7. intentkit/core/engine.py +16 -7
  8. intentkit/core/scheduler.py +8 -8
  9. intentkit/models/agent.py +109 -94
  10. intentkit/models/agent_schema.json +6 -9
  11. intentkit/models/llm.csv +15 -12
  12. intentkit/models/skill.py +38 -40
  13. intentkit/skills/acolyt/__init__.py +2 -9
  14. intentkit/skills/acolyt/base.py +2 -5
  15. intentkit/skills/aixbt/__init__.py +2 -13
  16. intentkit/skills/aixbt/base.py +0 -4
  17. intentkit/skills/aixbt/projects.py +1 -2
  18. intentkit/skills/allora/__init__.py +2 -9
  19. intentkit/skills/allora/base.py +2 -5
  20. intentkit/skills/base.py +168 -27
  21. intentkit/skills/basename/__init__.py +1 -3
  22. intentkit/skills/carv/__init__.py +116 -121
  23. intentkit/skills/carv/base.py +184 -185
  24. intentkit/skills/casino/__init__.py +4 -15
  25. intentkit/skills/casino/base.py +0 -4
  26. intentkit/skills/casino/deck_draw.py +4 -6
  27. intentkit/skills/casino/deck_shuffle.py +5 -4
  28. intentkit/skills/casino/dice_roll.py +1 -2
  29. intentkit/skills/cdp/__init__.py +0 -5
  30. intentkit/skills/cdp/base.py +0 -4
  31. intentkit/skills/cdp/schema.json +1 -17
  32. intentkit/skills/chainlist/__init__.py +2 -7
  33. intentkit/skills/chainlist/base.py +0 -4
  34. intentkit/skills/common/__init__.py +2 -9
  35. intentkit/skills/common/base.py +0 -4
  36. intentkit/skills/cookiefun/__init__.py +6 -9
  37. intentkit/skills/cookiefun/base.py +0 -4
  38. intentkit/skills/cryptocompare/__init__.py +7 -24
  39. intentkit/skills/cryptocompare/base.py +4 -18
  40. intentkit/skills/cryptocompare/fetch_news.py +1 -1
  41. intentkit/skills/cryptocompare/fetch_price.py +1 -1
  42. intentkit/skills/cryptocompare/fetch_top_exchanges.py +1 -1
  43. intentkit/skills/cryptocompare/fetch_top_market_cap.py +1 -1
  44. intentkit/skills/cryptocompare/fetch_top_volume.py +1 -1
  45. intentkit/skills/cryptocompare/fetch_trading_signals.py +1 -1
  46. intentkit/skills/cryptopanic/__init__.py +3 -6
  47. intentkit/skills/cryptopanic/base.py +53 -55
  48. intentkit/skills/cryptopanic/fetch_crypto_news.py +0 -2
  49. intentkit/skills/cryptopanic/fetch_crypto_sentiment.py +1 -3
  50. intentkit/skills/dapplooker/__init__.py +2 -9
  51. intentkit/skills/dapplooker/base.py +2 -5
  52. intentkit/skills/defillama/__init__.py +24 -74
  53. intentkit/skills/defillama/base.py +3 -13
  54. intentkit/skills/defillama/coins/fetch_batch_historical_prices.py +2 -2
  55. intentkit/skills/defillama/coins/fetch_block.py +2 -2
  56. intentkit/skills/defillama/coins/fetch_current_prices.py +2 -2
  57. intentkit/skills/defillama/coins/fetch_first_price.py +2 -2
  58. intentkit/skills/defillama/coins/fetch_historical_prices.py +2 -2
  59. intentkit/skills/defillama/coins/fetch_price_chart.py +2 -2
  60. intentkit/skills/defillama/coins/fetch_price_percentage.py +2 -2
  61. intentkit/skills/defillama/fees/fetch_fees_overview.py +2 -2
  62. intentkit/skills/defillama/stablecoins/fetch_stablecoin_chains.py +2 -2
  63. intentkit/skills/defillama/stablecoins/fetch_stablecoin_charts.py +2 -2
  64. intentkit/skills/defillama/stablecoins/fetch_stablecoin_prices.py +2 -2
  65. intentkit/skills/defillama/stablecoins/fetch_stablecoins.py +2 -2
  66. intentkit/skills/defillama/tvl/fetch_chain_historical_tvl.py +2 -2
  67. intentkit/skills/defillama/tvl/fetch_chains.py +2 -2
  68. intentkit/skills/defillama/tvl/fetch_historical_tvl.py +2 -2
  69. intentkit/skills/defillama/tvl/fetch_protocol.py +2 -2
  70. intentkit/skills/defillama/tvl/fetch_protocol_current_tvl.py +2 -2
  71. intentkit/skills/defillama/tvl/fetch_protocols.py +2 -2
  72. intentkit/skills/defillama/volumes/fetch_dex_overview.py +2 -2
  73. intentkit/skills/defillama/volumes/fetch_dex_summary.py +2 -2
  74. intentkit/skills/defillama/volumes/fetch_options_overview.py +2 -2
  75. intentkit/skills/defillama/yields/fetch_pool_chart.py +2 -2
  76. intentkit/skills/defillama/yields/fetch_pools.py +2 -2
  77. intentkit/skills/dexscreener/__init__.py +97 -102
  78. intentkit/skills/dexscreener/base.py +125 -130
  79. intentkit/skills/dexscreener/get_pair_info.py +2 -3
  80. intentkit/skills/dexscreener/get_token_pairs.py +2 -3
  81. intentkit/skills/dexscreener/get_tokens_info.py +2 -3
  82. intentkit/skills/dexscreener/search_token.py +2 -4
  83. intentkit/skills/dune_analytics/__init__.py +4 -6
  84. intentkit/skills/dune_analytics/base.py +50 -52
  85. intentkit/skills/dune_analytics/fetch_kol_buys.py +0 -2
  86. intentkit/skills/dune_analytics/fetch_nation_metrics.py +0 -2
  87. intentkit/skills/elfa/__init__.py +5 -18
  88. intentkit/skills/elfa/base.py +8 -10
  89. intentkit/skills/enso/__init__.py +9 -29
  90. intentkit/skills/enso/base.py +3 -6
  91. intentkit/skills/enso/networks.py +1 -6
  92. intentkit/skills/enso/route.py +4 -8
  93. intentkit/skills/enso/tokens.py +2 -12
  94. intentkit/skills/erc20/__init__.py +1 -5
  95. intentkit/skills/erc721/__init__.py +1 -3
  96. intentkit/skills/firecrawl/__init__.py +5 -18
  97. intentkit/skills/firecrawl/base.py +2 -5
  98. intentkit/skills/firecrawl/clear.py +3 -6
  99. intentkit/skills/firecrawl/crawl.py +10 -9
  100. intentkit/skills/firecrawl/query.py +3 -1
  101. intentkit/skills/firecrawl/scrape.py +10 -14
  102. intentkit/skills/firecrawl/utils.py +39 -31
  103. intentkit/skills/github/__init__.py +2 -7
  104. intentkit/skills/github/base.py +0 -4
  105. intentkit/skills/heurist/__init__.py +8 -27
  106. intentkit/skills/heurist/base.py +2 -5
  107. intentkit/skills/heurist/image_generation_animagine_xl.py +5 -5
  108. intentkit/skills/heurist/image_generation_arthemy_comics.py +5 -5
  109. intentkit/skills/heurist/image_generation_arthemy_real.py +5 -5
  110. intentkit/skills/heurist/image_generation_braindance.py +5 -5
  111. intentkit/skills/heurist/image_generation_cyber_realistic_xl.py +5 -5
  112. intentkit/skills/heurist/image_generation_flux_1_dev.py +5 -5
  113. intentkit/skills/heurist/image_generation_sdxl.py +5 -5
  114. intentkit/skills/http/__init__.py +4 -15
  115. intentkit/skills/http/base.py +0 -4
  116. intentkit/skills/lifi/__init__.py +1 -6
  117. intentkit/skills/lifi/base.py +0 -4
  118. intentkit/skills/lifi/token_execute.py +1 -4
  119. intentkit/skills/lifi/token_quote.py +1 -3
  120. intentkit/skills/moralis/__init__.py +3 -7
  121. intentkit/skills/moralis/base.py +2 -5
  122. intentkit/skills/morpho/__init__.py +1 -3
  123. intentkit/skills/nation/__init__.py +2 -7
  124. intentkit/skills/nation/base.py +4 -7
  125. intentkit/skills/openai/__init__.py +5 -18
  126. intentkit/skills/openai/base.py +8 -10
  127. intentkit/skills/openai/dalle_image_generation.py +2 -5
  128. intentkit/skills/openai/gpt_image_generation.py +2 -5
  129. intentkit/skills/openai/gpt_image_to_image.py +2 -5
  130. intentkit/skills/openai/image_to_text.py +2 -5
  131. intentkit/skills/portfolio/__init__.py +11 -35
  132. intentkit/skills/portfolio/base.py +2 -5
  133. intentkit/skills/pyth/__init__.py +1 -5
  134. intentkit/skills/slack/__init__.py +5 -17
  135. intentkit/skills/slack/base.py +0 -4
  136. intentkit/skills/supabase/__init__.py +7 -23
  137. intentkit/skills/supabase/base.py +0 -4
  138. intentkit/skills/superfluid/__init__.py +1 -3
  139. intentkit/skills/system/__init__.py +7 -24
  140. intentkit/skills/system/add_autonomous_task.py +2 -2
  141. intentkit/skills/system/delete_autonomous_task.py +2 -2
  142. intentkit/skills/system/edit_autonomous_task.py +2 -4
  143. intentkit/skills/system/list_autonomous_tasks.py +2 -2
  144. intentkit/skills/system/read_agent_api_key.py +6 -4
  145. intentkit/skills/system/regenerate_agent_api_key.py +6 -4
  146. intentkit/skills/tavily/__init__.py +3 -12
  147. intentkit/skills/tavily/base.py +2 -5
  148. intentkit/skills/tavily/tavily_extract.py +1 -2
  149. intentkit/skills/tavily/tavily_search.py +3 -3
  150. intentkit/skills/token/__init__.py +5 -10
  151. intentkit/skills/token/base.py +2 -6
  152. intentkit/skills/twitter/__init__.py +11 -35
  153. intentkit/skills/twitter/base.py +18 -29
  154. intentkit/skills/twitter/follow_user.py +1 -4
  155. intentkit/skills/twitter/get_mentions.py +2 -8
  156. intentkit/skills/twitter/get_timeline.py +3 -10
  157. intentkit/skills/twitter/get_user_by_username.py +1 -4
  158. intentkit/skills/twitter/get_user_tweets.py +3 -10
  159. intentkit/skills/twitter/like_tweet.py +1 -4
  160. intentkit/skills/twitter/post_tweet.py +3 -5
  161. intentkit/skills/twitter/reply_tweet.py +3 -5
  162. intentkit/skills/twitter/retweet.py +1 -4
  163. intentkit/skills/twitter/search_tweets.py +3 -10
  164. intentkit/skills/unrealspeech/__init__.py +2 -7
  165. intentkit/skills/unrealspeech/base.py +0 -4
  166. intentkit/skills/venice_audio/__init__.py +99 -106
  167. intentkit/skills/venice_audio/base.py +118 -121
  168. intentkit/skills/venice_audio/venice_audio.py +1 -5
  169. intentkit/skills/venice_image/__init__.py +147 -154
  170. intentkit/skills/venice_image/base.py +185 -192
  171. intentkit/skills/web_scraper/__init__.py +5 -18
  172. intentkit/skills/web_scraper/base.py +20 -4
  173. intentkit/skills/web_scraper/document_indexer.py +6 -4
  174. intentkit/skills/web_scraper/scrape_and_index.py +11 -10
  175. intentkit/skills/web_scraper/utils.py +38 -38
  176. intentkit/skills/web_scraper/website_indexer.py +7 -8
  177. intentkit/skills/weth/__init__.py +1 -5
  178. intentkit/skills/wow/__init__.py +1 -5
  179. intentkit/skills/xmtp/__init__.py +4 -15
  180. {intentkit-0.8.11.dev1.dist-info → intentkit-0.8.12.dist-info}/METADATA +1 -1
  181. {intentkit-0.8.11.dev1.dist-info → intentkit-0.8.12.dist-info}/RECORD +183 -183
  182. {intentkit-0.8.11.dev1.dist-info → intentkit-0.8.12.dist-info}/WHEEL +0 -0
  183. {intentkit-0.8.11.dev1.dist-info → intentkit-0.8.12.dist-info}/licenses/LICENSE +0 -0
@@ -1,121 +1,116 @@
1
- import logging
2
- from typing import List, Literal, Optional, TypedDict
3
-
4
- from intentkit.abstracts.skill import SkillStoreABC
5
- from intentkit.skills.base import SkillConfig, SkillState
6
- from intentkit.skills.carv.base import CarvBaseTool
7
- from intentkit.skills.carv.fetch_news import FetchNewsTool
8
- from intentkit.skills.carv.onchain_query import OnchainQueryTool
9
- from intentkit.skills.carv.token_info_and_price import TokenInfoAndPriceTool
10
-
11
- logger = logging.getLogger(__name__)
12
-
13
-
14
- _cache: dict[str, CarvBaseTool] = {}
15
-
16
- _SKILL_NAME_TO_CLASS_MAP: dict[str, type[CarvBaseTool]] = {
17
- "onchain_query": OnchainQueryTool,
18
- "token_info_and_price": TokenInfoAndPriceTool,
19
- "fetch_news": FetchNewsTool,
20
- }
21
-
22
-
23
- class SkillStates(TypedDict):
24
- onchain_query: SkillState
25
- token_info_and_price: SkillState
26
- fetch_news: SkillState
27
-
28
-
29
- class Config(SkillConfig):
30
- enabled: bool
31
- states: SkillStates # type: ignore
32
- api_key_provider: Optional[Literal["agent_owner", "platform"]]
33
-
34
- # conditionally required
35
- api_key: Optional[str]
36
-
37
- # optional
38
- rate_limit_number: Optional[int]
39
- rate_limit_minutes: Optional[int]
40
-
41
-
42
- async def get_skills(
43
- config: "Config",
44
- is_private: bool,
45
- store: SkillStoreABC,
46
- **_,
47
- ) -> list[CarvBaseTool]:
48
- """
49
- Factory function to create and return CARV skill tools based on the provided configuration.
50
-
51
- Args:
52
- config: The configuration object for the CARV skill.
53
- is_private: A boolean indicating whether the request is from a private context.
54
- store: An instance of `SkillStoreABC`.
55
-
56
- Returns:
57
- A list of `CarvBaseTool` instances.
58
- """
59
- # Check if the entire category is disabled first
60
- if not config.get("enabled", False):
61
- return []
62
-
63
- available_skills: List[CarvBaseTool] = []
64
- skill_states = config.get("states", {})
65
-
66
- # Iterate through all known skills defined in the map
67
- for skill_name in _SKILL_NAME_TO_CLASS_MAP:
68
- state = skill_states.get(
69
- skill_name, "disabled"
70
- ) # Default to disabled if not in config
71
-
72
- if state == "disabled":
73
- continue
74
- elif state == "public" or (state == "private" and is_private):
75
- # If enabled, get the skill instance using the factory function
76
- skill_instance = get_carv_skill(skill_name, store)
77
- if skill_instance:
78
- available_skills.append(skill_instance)
79
- else:
80
- logger.warning(f"Could not instantiate known skill: {skill_name}")
81
-
82
- return available_skills
83
-
84
-
85
- def get_carv_skill(
86
- name: str,
87
- store: SkillStoreABC,
88
- ) -> Optional[CarvBaseTool]:
89
- """
90
- Factory function to retrieve a cached CARV skill instance by name.
91
-
92
- Args:
93
- name: The name of the CARV skill to retrieve.
94
- store: An instance of `SkillStoreABC`.
95
-
96
- Returns:
97
- The requested `CarvBaseTool` instance if found and enabled, otherwise None.
98
- """
99
-
100
- # Return from cache immediately if already exists
101
- if name in _cache:
102
- return _cache[name]
103
-
104
- # Get the class from the map
105
- skill_class = _SKILL_NAME_TO_CLASS_MAP.get(name)
106
-
107
- if skill_class:
108
- try:
109
- # Instantiate the skill and add to cache
110
- instance = skill_class(skill_store=store) # type: ignore
111
- _cache[name] = instance
112
- return instance
113
- except Exception as e:
114
- logger.error(
115
- f"Failed to instantiate Carv skill '{name}': {e}", exc_info=True
116
- )
117
- return None # Failed to instantiate
118
- else:
119
- # This handles cases where a name might be in config but not in our map
120
- logger.warning(f"Attempted to get unknown Carv skill: {name}")
121
- return None
1
+ import logging
2
+ from typing import List, Literal, Optional, TypedDict
3
+
4
+ from intentkit.skills.base import SkillConfig, SkillState
5
+ from intentkit.skills.carv.base import CarvBaseTool
6
+ from intentkit.skills.carv.fetch_news import FetchNewsTool
7
+ from intentkit.skills.carv.onchain_query import OnchainQueryTool
8
+ from intentkit.skills.carv.token_info_and_price import TokenInfoAndPriceTool
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ _cache: dict[str, CarvBaseTool] = {}
14
+
15
+ _SKILL_NAME_TO_CLASS_MAP: dict[str, type[CarvBaseTool]] = {
16
+ "onchain_query": OnchainQueryTool,
17
+ "token_info_and_price": TokenInfoAndPriceTool,
18
+ "fetch_news": FetchNewsTool,
19
+ }
20
+
21
+
22
+ class SkillStates(TypedDict):
23
+ onchain_query: SkillState
24
+ token_info_and_price: SkillState
25
+ fetch_news: SkillState
26
+
27
+
28
+ class Config(SkillConfig):
29
+ enabled: bool
30
+ states: SkillStates # type: ignore
31
+ api_key_provider: Optional[Literal["agent_owner", "platform"]]
32
+
33
+ # conditionally required
34
+ api_key: Optional[str]
35
+
36
+ # optional
37
+ rate_limit_number: Optional[int]
38
+ rate_limit_minutes: Optional[int]
39
+
40
+
41
+ async def get_skills(
42
+ config: "Config",
43
+ is_private: bool,
44
+ **_,
45
+ ) -> list[CarvBaseTool]:
46
+ """
47
+ Factory function to create and return CARV skill tools based on the provided configuration.
48
+
49
+ Args:
50
+ config: The configuration object for the CARV skill.
51
+ is_private: A boolean indicating whether the request is from a private context.
52
+
53
+ Returns:
54
+ A list of `CarvBaseTool` instances.
55
+ """
56
+ # Check if the entire category is disabled first
57
+ if not config.get("enabled", False):
58
+ return []
59
+
60
+ available_skills: List[CarvBaseTool] = []
61
+ skill_states = config.get("states", {})
62
+
63
+ # Iterate through all known skills defined in the map
64
+ for skill_name in _SKILL_NAME_TO_CLASS_MAP:
65
+ state = skill_states.get(
66
+ skill_name, "disabled"
67
+ ) # Default to disabled if not in config
68
+
69
+ if state == "disabled":
70
+ continue
71
+ elif state == "public" or (state == "private" and is_private):
72
+ # If enabled, get the skill instance using the factory function
73
+ skill_instance = get_carv_skill(skill_name)
74
+ if skill_instance:
75
+ available_skills.append(skill_instance)
76
+ else:
77
+ logger.warning(f"Could not instantiate known skill: {skill_name}")
78
+
79
+ return available_skills
80
+
81
+
82
+ def get_carv_skill(
83
+ name: str,
84
+ ) -> Optional[CarvBaseTool]:
85
+ """
86
+ Factory function to retrieve a cached CARV skill instance by name.
87
+
88
+ Args:
89
+ name: The name of the CARV skill to retrieve.
90
+
91
+ Returns:
92
+ The requested `CarvBaseTool` instance if found and enabled, otherwise None.
93
+ """
94
+
95
+ # Return from cache immediately if already exists
96
+ if name in _cache:
97
+ return _cache[name]
98
+
99
+ # Get the class from the map
100
+ skill_class = _SKILL_NAME_TO_CLASS_MAP.get(name)
101
+
102
+ if skill_class:
103
+ try:
104
+ # Instantiate the skill and add to cache
105
+ instance = skill_class() # type: ignore
106
+ _cache[name] = instance
107
+ return instance
108
+ except Exception as e:
109
+ logger.error(
110
+ f"Failed to instantiate Carv skill '{name}': {e}", exc_info=True
111
+ )
112
+ return None # Failed to instantiate
113
+ else:
114
+ # This handles cases where a name might be in config but not in our map
115
+ logger.warning(f"Attempted to get unknown Carv skill: {name}")
116
+ return None
@@ -1,185 +1,184 @@
1
- import logging
2
- from typing import Any, Dict, Optional, Tuple, Type
3
-
4
- import httpx # Ensure httpx is installed: pip install httpx
5
- from langchain_core.tools.base import ToolException
6
- from pydantic import BaseModel, Field
7
-
8
- from intentkit.abstracts.skill import SkillStoreABC
9
- from intentkit.skills.base import IntentKitSkill
10
-
11
- logger = logging.getLogger(__name__)
12
-
13
- CARV_API_BASE_URL = "https://interface.carv.io"
14
-
15
-
16
- class CarvBaseTool(IntentKitSkill):
17
- """Base class for CARV API tools."""
18
-
19
- name: str = Field(description="Tool name") # type: ignore
20
- description: str = Field(description="Tool description")
21
- args_schema: Type[BaseModel] # type: ignore
22
- skill_store: SkillStoreABC = Field(description="Skill store for data persistence")
23
-
24
- @property
25
- def category(self) -> str:
26
- return "carv"
27
-
28
- def get_api_key(self) -> str:
29
- """
30
- Retrieves the CARV API key based on the api_key_provider setting.
31
-
32
- Returns:
33
- The API key if found.
34
-
35
- Raises:
36
- ToolException: If the API key is not found or provider is invalid.
37
- """
38
- try:
39
- context = self.get_context()
40
- skill_config = context.agent.skill_config(self.category)
41
- api_key_provider = skill_config.get("api_key_provider")
42
- if api_key_provider == "agent_owner":
43
- agent_api_key: Optional[str] = skill_config.get("api_key")
44
- if agent_api_key:
45
- logger.debug(
46
- f"Using agent-specific CARV API key for skill {self.name} in category {self.category}"
47
- )
48
- return agent_api_key
49
- raise ToolException(
50
- f"No agent-owned CARV API key found for skill '{self.name}' in category '{self.category}'."
51
- )
52
-
53
- elif api_key_provider == "platform":
54
- system_api_key = self.skill_store.get_system_config("carv_api_key")
55
- if system_api_key:
56
- logger.debug(
57
- f"Using system CARV API key for skill {self.name} in category {self.category}"
58
- )
59
- return system_api_key
60
- raise ToolException(
61
- f"No platform-hosted CARV API key found for skill '{self.name}' in category '{self.category}'."
62
- )
63
-
64
- else:
65
- raise ToolException(
66
- f"Invalid API key provider '{api_key_provider}' for skill '{self.name}'"
67
- )
68
-
69
- except Exception as e:
70
- # Re-raise ToolException if it's already one, otherwise wrap
71
- if isinstance(e, ToolException):
72
- raise
73
- raise ToolException(f"Failed to retrieve CARV API key: {str(e)}") from e
74
-
75
- async def apply_rate_limit(self, context) -> None:
76
- """
77
- Applies rate limiting ONLY if specified in the agent's config ('skill_config').
78
- Checks for 'rate_limit_number' and 'rate_limit_minutes'.
79
- If not configured, NO rate limiting is applied.
80
- Raises ConnectionAbortedError if the configured limit is exceeded.
81
- """
82
- skill_config = context.agent.skill_config(self.category)
83
- user_id = context.agent.id
84
-
85
- limit_num = skill_config.get("rate_limit_number")
86
- limit_min = skill_config.get("rate_limit_minutes")
87
-
88
- # Apply limit ONLY if both values are present and valid (truthy check handles None and 0)
89
- if limit_num and limit_min:
90
- logger.debug(
91
- f"Applying rate limit ({limit_num}/{limit_min} min) for user {user_id} on {self.name}"
92
- )
93
- if user_id:
94
- await self.user_rate_limit_by_category(user_id, limit_num, limit_min)
95
- else:
96
- # No valid agent configuration found, so do nothing.
97
- logger.debug(
98
- f"No agent rate limits configured for category '{self.category}'. Skipping rate limit for user {user_id}."
99
- )
100
-
101
- async def _call_carv_api(
102
- self,
103
- context,
104
- endpoint: str,
105
- method: str = "GET",
106
- params: Optional[Dict[str, Any]] = None,
107
- payload: Optional[Dict[str, Any]] = None,
108
- ) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
109
- """
110
- Makes a call to the CARV API and returns a tuple of (success, error).
111
-
112
- Args:
113
- context: The skill context.
114
- endpoint: The API endpoint path (e.g., "/ai-agent-backend/token_info").
115
- method: HTTP method ("GET", "POST", etc.).
116
- params: Query parameters for the request.
117
- payload: JSON payload for POST/PUT requests.
118
-
119
- Returns:
120
- Tuple where the first element is the response data if successful,
121
- and the second element is an error dict if an error occurred.
122
- """
123
-
124
- url = f"{CARV_API_BASE_URL}{endpoint}"
125
-
126
- try:
127
- api_key = self.get_api_key()
128
-
129
- headers = {
130
- "Authorization": api_key,
131
- "Content-Type": "application/json",
132
- }
133
-
134
- logger.debug(
135
- f"Calling CARV API: {method} {url} with params {params}, payload {payload}"
136
- )
137
-
138
- async with httpx.AsyncClient(timeout=30.0) as client:
139
- if method == "GET":
140
- response = await client.get(url, headers=headers, params=params)
141
- elif method == "POST":
142
- response = await client.post(
143
- url, headers=headers, json=payload, params=params
144
- )
145
- else:
146
- return None, {"error": f"Unsupported HTTP method: {method}"}
147
-
148
- # Do NOT raise for status here; always parse JSON
149
- try:
150
- response_json: dict[str, Any] = response.json()
151
- except Exception as json_err:
152
- err_msg = f"Failed to parse JSON response: {json_err}"
153
- logger.error(err_msg)
154
- return None, {"error": err_msg}
155
-
156
- logger.debug(
157
- f"CARV API Response (status {response.status_code}): {response_json}"
158
- )
159
-
160
- # Check if response_json signals an error explicitly (custom API error)
161
- if response.status_code >= 400 or "error" in response_json:
162
- # Return full error info (including status code, body, etc.)
163
- return None, {
164
- "error": response_json.get("error", "Unknown API error"),
165
- "status_code": response.status_code,
166
- "response": response_json,
167
- "url": url,
168
- "method": method,
169
- "params": params,
170
- "payload": payload,
171
- }
172
-
173
- # Otherwise return the 'data' field if present, else full response
174
- return response_json.get("data", response_json), None
175
-
176
- except Exception as e:
177
- logger.error(
178
- f"Error calling CARV API to {method} > {url}: {e}", exc_info=True
179
- )
180
- return None, {
181
- "error": str(e),
182
- "url": url,
183
- "method": method,
184
- "params": params,
185
- }
1
+ import logging
2
+ from typing import Any, Dict, Optional, Tuple, Type
3
+
4
+ import httpx # Ensure httpx is installed: pip install httpx
5
+ from langchain_core.tools.base import ToolException
6
+ from pydantic import BaseModel, Field
7
+
8
+ from intentkit.config.config import config
9
+ from intentkit.skills.base import IntentKitSkill
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ CARV_API_BASE_URL = "https://interface.carv.io"
14
+
15
+
16
+ class CarvBaseTool(IntentKitSkill):
17
+ """Base class for CARV API tools."""
18
+
19
+ name: str = Field(description="Tool name") # type: ignore
20
+ description: str = Field(description="Tool description")
21
+ args_schema: Type[BaseModel] # type: ignore
22
+
23
+ @property
24
+ def category(self) -> str:
25
+ return "carv"
26
+
27
+ def get_api_key(self) -> str:
28
+ """
29
+ Retrieves the CARV API key based on the api_key_provider setting.
30
+
31
+ Returns:
32
+ The API key if found.
33
+
34
+ Raises:
35
+ ToolException: If the API key is not found or provider is invalid.
36
+ """
37
+ try:
38
+ context = self.get_context()
39
+ skill_config = context.agent.skill_config(self.category)
40
+ api_key_provider = skill_config.get("api_key_provider")
41
+ if api_key_provider == "agent_owner":
42
+ agent_api_key: Optional[str] = skill_config.get("api_key")
43
+ if agent_api_key:
44
+ logger.debug(
45
+ f"Using agent-specific CARV API key for skill {self.name} in category {self.category}"
46
+ )
47
+ return agent_api_key
48
+ raise ToolException(
49
+ f"No agent-owned CARV API key found for skill '{self.name}' in category '{self.category}'."
50
+ )
51
+
52
+ elif api_key_provider == "platform":
53
+ system_api_key = config.carv_api_key
54
+ if system_api_key:
55
+ logger.debug(
56
+ f"Using system CARV API key for skill {self.name} in category {self.category}"
57
+ )
58
+ return system_api_key
59
+ raise ToolException(
60
+ f"No platform-hosted CARV API key found for skill '{self.name}' in category '{self.category}'."
61
+ )
62
+
63
+ else:
64
+ raise ToolException(
65
+ f"Invalid API key provider '{api_key_provider}' for skill '{self.name}'"
66
+ )
67
+
68
+ except Exception as e:
69
+ # Re-raise ToolException if it's already one, otherwise wrap
70
+ if isinstance(e, ToolException):
71
+ raise
72
+ raise ToolException(f"Failed to retrieve CARV API key: {str(e)}") from e
73
+
74
+ async def apply_rate_limit(self, context) -> None:
75
+ """
76
+ Applies rate limiting ONLY if specified in the agent's config ('skill_config').
77
+ Checks for 'rate_limit_number' and 'rate_limit_minutes'.
78
+ If not configured, NO rate limiting is applied.
79
+ Raises ConnectionAbortedError if the configured limit is exceeded.
80
+ """
81
+ skill_config = context.agent.skill_config(self.category)
82
+ user_id = context.agent.id
83
+
84
+ limit_num = skill_config.get("rate_limit_number")
85
+ limit_min = skill_config.get("rate_limit_minutes")
86
+
87
+ # Apply limit ONLY if both values are present and valid (truthy check handles None and 0)
88
+ if limit_num and limit_min:
89
+ logger.debug(
90
+ f"Applying rate limit ({limit_num}/{limit_min} min) for user {user_id} on {self.name}"
91
+ )
92
+ if user_id:
93
+ await self.user_rate_limit_by_category(limit_num, limit_min * 60)
94
+ else:
95
+ # No valid agent configuration found, so do nothing.
96
+ logger.debug(
97
+ f"No agent rate limits configured for category '{self.category}'. Skipping rate limit for user {user_id}."
98
+ )
99
+
100
+ async def _call_carv_api(
101
+ self,
102
+ context,
103
+ endpoint: str,
104
+ method: str = "GET",
105
+ params: Optional[Dict[str, Any]] = None,
106
+ payload: Optional[Dict[str, Any]] = None,
107
+ ) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
108
+ """
109
+ Makes a call to the CARV API and returns a tuple of (success, error).
110
+
111
+ Args:
112
+ context: The skill context.
113
+ endpoint: The API endpoint path (e.g., "/ai-agent-backend/token_info").
114
+ method: HTTP method ("GET", "POST", etc.).
115
+ params: Query parameters for the request.
116
+ payload: JSON payload for POST/PUT requests.
117
+
118
+ Returns:
119
+ Tuple where the first element is the response data if successful,
120
+ and the second element is an error dict if an error occurred.
121
+ """
122
+
123
+ url = f"{CARV_API_BASE_URL}{endpoint}"
124
+
125
+ try:
126
+ api_key = self.get_api_key()
127
+
128
+ headers = {
129
+ "Authorization": api_key,
130
+ "Content-Type": "application/json",
131
+ }
132
+
133
+ logger.debug(
134
+ f"Calling CARV API: {method} {url} with params {params}, payload {payload}"
135
+ )
136
+
137
+ async with httpx.AsyncClient(timeout=30.0) as client:
138
+ if method == "GET":
139
+ response = await client.get(url, headers=headers, params=params)
140
+ elif method == "POST":
141
+ response = await client.post(
142
+ url, headers=headers, json=payload, params=params
143
+ )
144
+ else:
145
+ return None, {"error": f"Unsupported HTTP method: {method}"}
146
+
147
+ # Do NOT raise for status here; always parse JSON
148
+ try:
149
+ response_json: dict[str, Any] = response.json()
150
+ except Exception as json_err:
151
+ err_msg = f"Failed to parse JSON response: {json_err}"
152
+ logger.error(err_msg)
153
+ return None, {"error": err_msg}
154
+
155
+ logger.debug(
156
+ f"CARV API Response (status {response.status_code}): {response_json}"
157
+ )
158
+
159
+ # Check if response_json signals an error explicitly (custom API error)
160
+ if response.status_code >= 400 or "error" in response_json:
161
+ # Return full error info (including status code, body, etc.)
162
+ return None, {
163
+ "error": response_json.get("error", "Unknown API error"),
164
+ "status_code": response.status_code,
165
+ "response": response_json,
166
+ "url": url,
167
+ "method": method,
168
+ "params": params,
169
+ "payload": payload,
170
+ }
171
+
172
+ # Otherwise return the 'data' field if present, else full response
173
+ return response_json.get("data", response_json), None
174
+
175
+ except Exception as e:
176
+ logger.error(
177
+ f"Error calling CARV API to {method} > {url}: {e}", exc_info=True
178
+ )
179
+ return None, {
180
+ "error": str(e),
181
+ "url": url,
182
+ "method": method,
183
+ "params": params,
184
+ }