pangolin-agent 0.1.0b1__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.
Files changed (79) hide show
  1. pangolin_agent/__init__.py +32 -0
  2. pangolin_agent/agent_runtimes/__init__.py +7 -0
  3. pangolin_agent/agent_runtimes/pangolin_runtime.py +299 -0
  4. pangolin_agent/api_providers/__init__.py +2 -0
  5. pangolin_agent/api_providers/anthropic_provider.py +294 -0
  6. pangolin_agent/api_providers/gemini_provider.py +180 -0
  7. pangolin_agent/api_providers/open_ai_provider.py +193 -0
  8. pangolin_agent/api_providers/smoke_test_client.py +91 -0
  9. pangolin_agent/cli.py +62 -0
  10. pangolin_agent/core/__init__.py +0 -0
  11. pangolin_agent/core/exceptions/__init__.py +11 -0
  12. pangolin_agent/core/exceptions/exceptions.py +18 -0
  13. pangolin_agent/core/interfaces/__init__.py +28 -0
  14. pangolin_agent/core/interfaces/agent_runtime.py +24 -0
  15. pangolin_agent/core/interfaces/client.py +12 -0
  16. pangolin_agent/core/interfaces/guardrail.py +9 -0
  17. pangolin_agent/core/interfaces/memory_manager.py +18 -0
  18. pangolin_agent/core/interfaces/provider.py +13 -0
  19. pangolin_agent/core/interfaces/rag_component.py +9 -0
  20. pangolin_agent/core/interfaces/response_composer.py +14 -0
  21. pangolin_agent/core/interfaces/skill_manager.py +25 -0
  22. pangolin_agent/core/interfaces/toolbox.py +23 -0
  23. pangolin_agent/core/types/__init__.py +10 -0
  24. pangolin_agent/core/types/chat_summary.py +10 -0
  25. pangolin_agent/core/types/guardrail_events.py +25 -0
  26. pangolin_agent/guardrails/__init__.py +7 -0
  27. pangolin_agent/guardrails/default_guardrail.py +37 -0
  28. pangolin_agent/memory_managers/__init__.py +9 -0
  29. pangolin_agent/memory_managers/simple_memory_manager.py +48 -0
  30. pangolin_agent/memory_managers/sqlite_memory_manager.py +229 -0
  31. pangolin_agent/messages/__init__.py +19 -0
  32. pangolin_agent/messages/agent_message.py +16 -0
  33. pangolin_agent/messages/api_event.py +15 -0
  34. pangolin_agent/messages/chat_record.py +43 -0
  35. pangolin_agent/messages/tool_call.py +13 -0
  36. pangolin_agent/messages/tool_call_result.py +11 -0
  37. pangolin_agent/py.typed +0 -0
  38. pangolin_agent/rag_routers/__init__.py +7 -0
  39. pangolin_agent/rag_routers/rag_router.py +32 -0
  40. pangolin_agent/response_composers/__init__.py +7 -0
  41. pangolin_agent/response_composers/pangolin_composer.py +47 -0
  42. pangolin_agent/skill_managers/__init__.py +11 -0
  43. pangolin_agent/skill_managers/advanced_skill_manager.py +108 -0
  44. pangolin_agent/skill_managers/rag_skill_manager.py +221 -0
  45. pangolin_agent/skill_managers/simple_skill_manager.py +38 -0
  46. pangolin_agent/skill_managers/skills/__init__.py +0 -0
  47. pangolin_agent/skill_managers/skills/pangolin_architecture.md +95 -0
  48. pangolin_agent/skill_managers/skills/pangolin_guardrail.md +80 -0
  49. pangolin_agent/skill_managers/skills/pangolin_memory.md +82 -0
  50. pangolin_agent/skill_managers/skills/pangolin_provider.md +86 -0
  51. pangolin_agent/skill_managers/skills/pangolin_skill_manager.md +89 -0
  52. pangolin_agent/skill_managers/skills/pangolin_toolbox.md +121 -0
  53. pangolin_agent/skill_managers/skills/pangolin_use.md +147 -0
  54. pangolin_agent/toolboxes/__init__.py +9 -0
  55. pangolin_agent/toolboxes/basic_toolbox.py +90 -0
  56. pangolin_agent/toolboxes/pangolin_toolbox.py +106 -0
  57. pangolin_agent/toolboxes/power_tools/create_tool.py +20 -0
  58. pangolin_agent/toolboxes/power_tools/delete_file.py +51 -0
  59. pangolin_agent/toolboxes/power_tools/run_sh.py +81 -0
  60. pangolin_agent/toolboxes/power_tools/write_file.py +51 -0
  61. pangolin_agent/toolboxes/tools/__init__.py +0 -0
  62. pangolin_agent/toolboxes/tools/browse_files.py +77 -0
  63. pangolin_agent/toolboxes/tools/create_skill.py +28 -0
  64. pangolin_agent/toolboxes/tools/fetch_page.py +26 -0
  65. pangolin_agent/toolboxes/tools/get_utc_time.py +16 -0
  66. pangolin_agent/toolboxes/tools/load_skill.py +26 -0
  67. pangolin_agent/toolboxes/tools/read_file.py +40 -0
  68. pangolin_agent/toolboxes/tools/unload_skill.py +26 -0
  69. pangolin_agent/toolboxes/tools/update_chat_summary.py +29 -0
  70. pangolin_agent/toolboxes/tools/web_search.py +24 -0
  71. pangolin_agent/toolboxes/tools/web_search_playwright.py +116 -0
  72. pangolin_agent/utils/__init__.py +16 -0
  73. pangolin_agent/utils/copy_built_ins.py +41 -0
  74. pangolin_agent/utils/ensure_async.py +19 -0
  75. pangolin_agent/utils/token_calculator.py +37 -0
  76. pangolin_agent-0.1.0b1.dist-info/METADATA +36 -0
  77. pangolin_agent-0.1.0b1.dist-info/RECORD +79 -0
  78. pangolin_agent-0.1.0b1.dist-info/WHEEL +4 -0
  79. pangolin_agent-0.1.0b1.dist-info/licenses/LICENSE +85 -0
@@ -0,0 +1,32 @@
1
+ #Copyright (c) 2026 Gene B. Denney. All Rights Reserved.
2
+
3
+ from .cli import cli
4
+ from .agent_runtimes import PangolinRuntime
5
+ from .toolboxes import BasicToolbox, PangolinToolbox
6
+ from .skill_managers import AdvancedSkillManager, SimpleSkillManager, RAGSkillManager
7
+ from .rag_routers import RAGRouter
8
+ from .guardrails import DefaultGuardrail
9
+ from.response_composers import PangolinComposer
10
+ from .utils import copy_built_in_skills, copy_built_in_tools, copy_built_in_power_tools, ensure_async, ensure_async_gen
11
+ from .memory_managers import SQLiteMemoryManager, SimpleMemoryManager
12
+
13
+
14
+ __all__ = [
15
+ 'cli',
16
+ 'PangolinRuntime',
17
+ 'PangolinComposer',
18
+ 'DefaultGuardrail',
19
+ 'BasicToolbox',
20
+ 'PangolinToolbox',
21
+ 'copy_built_in_tools',
22
+ 'copy_built_in_power_tools',
23
+ 'copy_built_in_skills',
24
+ 'ensure_async',
25
+ 'ensure_async_gen',
26
+ 'AdvancedSkillManager',
27
+ 'SimpleSkillManager',
28
+ 'RAGSkillManager',
29
+ 'RAGRouter',
30
+ 'SQLiteMemoryManager',
31
+ 'SimpleMemoryManager'
32
+ ]
@@ -0,0 +1,7 @@
1
+ #Copyright (c) 2026 Gene B. Denney. All Rights Reserved.
2
+
3
+ from .pangolin_runtime import PangolinRuntime
4
+
5
+ __all__ = [
6
+ 'PangolinRuntime'
7
+ ]
@@ -0,0 +1,299 @@
1
+ #Copyright (c) 2026 Gene B. Denney. All Rights Reserved.
2
+
3
+ from typing import Protocol, AsyncGenerator
4
+ import logging, asyncio, threading
5
+ from ..core.interfaces import AgentRuntime, AgentRuntimeToQueue, MemoryManager,SkillManager, Toolbox, ToolboxAdvanced, ResponseComposer, Guardrail, RAGComponent
6
+ from ..core.exceptions import PangolinTypeError, PangolinGuardRailDenial
7
+ from ..core.types import GuardrailEvent
8
+ from ..messages import ChatRecord, Part, AgentMessage, ToolCall
9
+ from ..utils import count_tokens, ensure_async, ensure_async_gen
10
+ from ..memory_managers import SimpleMemoryManager
11
+
12
+ LOGGER = logging.getLogger(__name__)
13
+
14
+
15
+ class PangolinRuntime(AgentRuntime, AgentRuntimeToQueue, Protocol):
16
+ '''
17
+ default implementation of AgentRuntime.
18
+ the only required parameter is composer: ResponseComposer (recommend the PangolinComposer)
19
+ memory_manager will default to SimpleMemoryManager which only tracks the current session in memory.
20
+ '''
21
+ def __init__(self,
22
+ composer: ResponseComposer,
23
+ system_prompt: str = '',
24
+ memory_manager: MemoryManager | None = None,
25
+ skill_manager: SkillManager | None = None,
26
+ toolbox: Toolbox | None = None,
27
+ guardrail: Guardrail | None = None,
28
+ rag_connection: RAGComponent | None = None,
29
+ max_tokens: int = 32_000,
30
+ max_rounds: int = 10):
31
+ '''
32
+ aggregator: initilialized with an api_provider.Client instance.
33
+ system_prompt: system prompt that will be injected at the start of each turn, appended with any skills provided by the skill manager
34
+ memory_manager: maintains the chat history for the session. If None the SimpleMemoryManager will be used, which only stores the current session history in memory with old messages trimmed to keep system prompt, skills, chat history, and tools list under max_token size
35
+ skill_manager: provides skills to the session
36
+ toolbox: provides the available tools and executes them
37
+ rag_component: can be the same as skill_manager or toolbox if RAGComponent | RAGComponentAsync is implemented on them or use the RAGRouter to connect the hook to both
38
+ max_tokens: sets the ceiling for the max context sent to the model (system prompt, skills, chat history, and tools list)
39
+ max_rounds: int = 10 sets the maxiumum rounds the agent can make for a single user message (one round can have multiple tool calls)
40
+ '''
41
+
42
+ LOGGER.info(f'__init__: \n{composer}\n{system_prompt}\n{memory_manager}\n{skill_manager}\n{toolbox}\n{max_tokens}\n{max_rounds} ')
43
+
44
+ if not isinstance(composer, ResponseComposer):
45
+ raise PangolinTypeError('composer parameter does not implement ResponseComposer')
46
+ if memory_manager and not isinstance(memory_manager, MemoryManager):
47
+ raise PangolinTypeError('memory_manager parameter does not implement MemoryManger')
48
+ if skill_manager and not isinstance(skill_manager, SkillManager):
49
+ raise PangolinTypeError('skill_manager parameter does not implement SkillManager')
50
+ if toolbox and not isinstance(toolbox, Toolbox):
51
+ raise PangolinTypeError('toolbox parameter does not implement Toolbox')
52
+ if guardrail and not isinstance(guardrail, Guardrail):
53
+ raise PangolinTypeError('guardrail parameter does not implement Guardrail')
54
+ if rag_connection and not isinstance(rag_connection, RAGComponent):
55
+ raise PangolinTypeError('rag_component parameter does not implement RAGComponent')
56
+
57
+ self.composer: ResponseComposer = composer
58
+ self.system_prompt: str = system_prompt
59
+ self.memory_manager = memory_manager or SimpleMemoryManager()
60
+ self.skill_manager: SkillManager = skill_manager
61
+ self.toolbox: Toolbox = toolbox
62
+ if self.toolbox:
63
+ LOGGER.debug('toolbox found')
64
+ # Advanced toolbox can enable 'session aware tools' giving them access to talk with the skills manager and memory manager but only if the session is provided
65
+ if isinstance(self.toolbox, ToolboxAdvanced):
66
+ LOGGER.debug('toolbox is ToolboxAdvanced')
67
+ self.toolbox.set_session(self)
68
+ # Initaliaze the toolbox
69
+ self.toolbox.load()
70
+ LOGGER.info('toolbox loaded')
71
+ self.guardrail = guardrail
72
+ self.rag_connection = rag_connection
73
+ self.max_tokens = max_tokens
74
+ self.max_rounds = max_rounds
75
+
76
+ async def _add_context(self, record):
77
+ '''
78
+ adds a ChatRecord to the Memory Manger
79
+ '''
80
+ await ensure_async(self.memory_manager.add_record, record)
81
+ while True:
82
+ context = await self._get_context()
83
+ tools = await self._tools()
84
+ if count_tokens(context, tools) > self.max_tokens:
85
+ LOGGER.debug('trimming context')
86
+ await ensure_async(self.memory_manager.trim_history)
87
+ continue
88
+ break
89
+
90
+ async def _get_context(self):
91
+ '''
92
+ Assembles the current record set, without the tools list, as a list[TARecord]
93
+ '''
94
+ LOGGER.debug('_get_context')
95
+ skills = await ensure_async(self.skill_manager.skills) if self.skill_manager else ''
96
+ system = f'{self.system_prompt}\n{skills}'
97
+ system_prompt_record = ChatRecord(role='system', content=[Part(type='text', data={'text':system})])
98
+ history = await ensure_async(self.memory_manager.get_history)
99
+ return [system_prompt_record] + history
100
+
101
+ async def _tools(self) -> str | None:
102
+ ''' Get the list of tool schemas '''
103
+ return await ensure_async(self.toolbox.schemas) if self.toolbox else None
104
+
105
+ async def _handle_agent_message(self, agent_message: AgentMessage, tool_calls: list, blocked_tool_call_ids: list, reason: list):
106
+ # if the ApiAggregator yields a message event add it to the context and check it for tool_calls
107
+ if agent_message.behavior == 'message':
108
+ LOGGER.info(f'assistant message recieved: {agent_message.chat_record}')
109
+ if agent_message.chat_record and self.guardrail:
110
+ ger = await ensure_async(self.guardrail.handle_guardrail_event,
111
+ GuardrailEvent(
112
+ event_type='assistant_output',
113
+ chat_record=agent_message.chat_record
114
+ )
115
+ )
116
+
117
+ if ger.event_type == 'deny':
118
+ raise PangolinGuardRailDenial(f'AgentMessage triggered a Guardrail denial {ger.reason}')
119
+ if ger.event_type == 'modify':
120
+ agent_message.chat_record = ger.chat_record
121
+ reason['reason'] = ger.reason
122
+ for rtci in ger.rejected_tool_call_ids or []:
123
+ blocked_tool_call_ids.append(rtci)
124
+
125
+ if agent_message.chat_record.tool_calls:
126
+ for tc in agent_message.chat_record.tool_calls:
127
+ tool_calls.append(tc)
128
+
129
+ await self._add_context(agent_message.chat_record)
130
+
131
+ async def _handle_agent_message(self, agent_message: AgentMessage, tool_calls: list, blocked_tool_call_ids: list, reason: list):
132
+ # if the ApiAggregator yields a message event add it to the context and check it for tool_calls
133
+ if agent_message.behavior == 'message':
134
+ LOGGER.info(f'assistant message recieved: {agent_message.chat_record}')
135
+ if agent_message.chat_record and self.guardrail:
136
+ ger = await self.guardrail.handle_guardrail_event(
137
+ GuardrailEvent(
138
+ event_type='assistant_output',
139
+ chat_record=agent_message.chat_record
140
+ )
141
+ )
142
+
143
+ if ger.event_type == 'deny':
144
+ raise PangolinGuardRailDenial(f'AgentMessage triggered a Guardrail denial {ger.reason}')
145
+ if ger.event_type == 'modify':
146
+ agent_message.chat_record = ger.chat_record
147
+ reason['reason'] = ger.reason
148
+ for rtci in ger.rejected_tool_call_ids or []:
149
+ blocked_tool_call_ids.append(rtci)
150
+
151
+ if agent_message.chat_record.tool_calls:
152
+ for tc in agent_message.chat_record.tool_calls:
153
+ tool_calls.append(tc)
154
+
155
+ await self._add_context(agent_message.chat_record)
156
+
157
+ async def _handle_tool_calls(self, tool_calls: list[ToolCall], blocked_tool_call_ids: list, reason: str) -> None:
158
+ LOGGER.info('making tool calls')
159
+ calls_to_run = []
160
+ for tc in tool_calls:
161
+ if tc.id in blocked_tool_call_ids:
162
+ await self._add_context(ChatRecord(
163
+ role='tool',
164
+ content=[Part(type='text', data={'text': reason})],
165
+ tool_call_id=tc.id))
166
+ else:
167
+ calls_to_run.append(tc)
168
+
169
+ async for result in ensure_async_gen(self.toolbox.handle_tool_calls, calls_to_run):
170
+ chat_record = ChatRecord(role='tool', content=[Part(type='text', data={'text': result.result})], tool_call_id=result.id)
171
+ if self.guardrail:
172
+ ger = await ensure_async(self.guardrail.handle_guardrail_event,
173
+ GuardrailEvent(
174
+ event_type='tool_call_result',
175
+ chat_record=chat_record
176
+ )
177
+ )
178
+ if ger.event_type == 'modify':
179
+ chat_record = ger.chat_record
180
+
181
+ LOGGER.debug(f'TOOL CALL RESULT {chat_record.to_json()}')
182
+ await self._add_context(chat_record)
183
+
184
+ async def _user_message_guardrail_check(self, record: ChatRecord):
185
+ if self.guardrail:
186
+ ger = await ensure_async(self.guardrail.handle_guardrail_event,
187
+ GuardrailEvent(event_type='user_input',
188
+ chat_record=record
189
+ )
190
+ )
191
+
192
+ if ger.event_type == 'deny':
193
+ raise PangolinGuardRailDenial(f'User Message triggered a Guardrail denial {ger.reason}')
194
+ if ger.event_type == 'modify':
195
+ await self._add_context(ger.chat_record)
196
+ return
197
+
198
+ await self._add_context(record)
199
+
200
+ async def handle_user_message(self, record: ChatRecord | str, stop: threading.Event = threading.Event()) -> AsyncGenerator[AgentMessage]:
201
+ ''' Main entry point to start the agentic loop. '''
202
+
203
+ if isinstance(record, str):
204
+ record = ChatRecord(role='user', content=[Part(type='text', data={'text': record})])
205
+ elif not isinstance(record, ChatRecord):
206
+ raise PangolinTypeError('message does not implement ChatRecord')
207
+
208
+ LOGGER.info(f'user message recieved: {record.to_json()}')
209
+ try:
210
+ await self._user_message_guardrail_check(record)
211
+
212
+ if self.rag_connection:
213
+ history = await ensure_async(self.memory_manager.get_history)
214
+ await ensure_async(self.rag_connection.retrieve_with_chat_history, history)
215
+
216
+ LOGGER.debug('entering outer loop')
217
+ for _ in range(self.max_rounds):
218
+ if stop.is_set(): break
219
+
220
+ context = await self._get_context() # get the context to send to the api
221
+ tools = await self._tools()
222
+ tool_calls = [] # initialzed to store tool calls
223
+ blocked_tool_call_ids = []
224
+ reason = {'reason': ''}
225
+
226
+ LOGGER.debug('entering inner loop')
227
+ async for agent_message in ensure_async_gen(self.composer.process_context,context, tools):
228
+ if stop.is_set(): break
229
+ LOGGER.debug(f'agent message recieved: {agent_message}')
230
+ await self._handle_agent_message(agent_message, tool_calls, blocked_tool_call_ids, reason)
231
+
232
+ yield agent_message
233
+
234
+ # if the stream ends with no tool calls the loop exits
235
+ if tool_calls and self.toolbox:
236
+ LOGGER.debug(f'runtime got {len(tool_calls)} tool calls')
237
+ await self._handle_tool_calls(tool_calls, blocked_tool_call_ids, reason['reason'])
238
+ else:
239
+ break
240
+ except PangolinGuardRailDenial as grd:
241
+ yield AgentMessage(behavior='guardrail', content=grd)
242
+ except BaseException as e:
243
+ yield AgentMessage(behavior='error', content=e)
244
+
245
+ async def handle_user_message_to_queue(self, record: ChatRecord | str,
246
+ queue: asyncio.Queue[AgentMessage | None],
247
+ stop: threading.Event = threading.Event(),
248
+ done: threading.Event = threading.Event()):
249
+ ''' To ansycio.Queue entry point to start the agentic loop. '''
250
+
251
+ if isinstance(record, str):
252
+ record = ChatRecord(role='user', content=[Part(type='text', data={'text': record})])
253
+ elif not isinstance(record, ChatRecord):
254
+ raise PangolinTypeError('message does not implement ChatRecord')
255
+
256
+ LOGGER.info(f'user message recieved: {record.to_json()}')
257
+
258
+ async def task_done():
259
+ await queue.put(None)
260
+ done.set()
261
+
262
+ try:
263
+ await self._user_message_guardrail_check(record)
264
+
265
+ if self.rag_connection:
266
+ history = await ensure_async(self.memory_manager.get_history)
267
+ await ensure_async(self.rag_connection.retrieve_with_chat_history, history)
268
+
269
+ for _ in range(self.max_rounds):
270
+ if stop.is_set(): break
271
+
272
+ context = await self._get_context() # get the context to send to the api
273
+ tools = await self._tools()
274
+ tool_calls = [] # initialzed to store tool calls
275
+ blocked_tool_call_ids = []
276
+ reason = {'reason': ''}
277
+
278
+ async for agent_message in ensure_async_gen(self.composer.process_context, context,tools):
279
+ await self._handle_agent_message(agent_message, tool_calls, blocked_tool_call_ids, reason)
280
+ await queue.put(agent_message)
281
+
282
+ if stop.is_set():
283
+ break
284
+
285
+ # if the stream ends with no tool calls the loop exits
286
+ if tool_calls and self.toolbox:
287
+ LOGGER.debug(f'runtime got {len(tool_calls)} tool calls')
288
+ await self._handle_tool_calls(tool_calls, blocked_tool_call_ids, reason['reason'])
289
+ else:
290
+ await task_done()
291
+ break
292
+
293
+ if stop.is_set():
294
+ await task_done()
295
+ break
296
+ except PangolinGuardRailDenial as grd:
297
+ await queue.put(AgentMessage(behavior='guardrail', content=grd))
298
+ except BaseException as e:
299
+ await queue.put(AgentMessage(behavior='error', content=e))
@@ -0,0 +1,2 @@
1
+ #Copyright (c) 2026 Gene B. Denney. All Rights Reserved.
2
+
@@ -0,0 +1,294 @@
1
+ #Copyright (c) 2026 Gene B. Denney. All Rights Reserved.
2
+
3
+ from ..core.exceptions import PangolinImportError
4
+ try:
5
+ from anthropic import Anthropic, AsyncAnthropic
6
+ except:
7
+ raise PangolinImportError('using anthropic_provider requires the anthropic library, pip install pangolin[anthropic]')
8
+ from typing import Iterator, Protocol, AsyncGenerator
9
+ import logging
10
+ from ..messages import ChatRecord, Part, ApiEvent, ToolCall
11
+ from ..core.interfaces import Client, Provider, MemoryManager, Toolbox, SkillManager, Guardrail, RAGComponent
12
+ from ..memory_managers import SimpleMemoryManager
13
+ from ..response_composers import PangolinComposer
14
+ from ..agent_runtimes import PangolinRuntime
15
+
16
+ LOGGER = logging.getLogger(__name__)
17
+
18
+ DEFAULT_MAX_TOKENS = 8192
19
+
20
+ class AnthropicClient(Client, Protocol):
21
+ def __init__(self, connection: Anthropic, model_name: str, max_tokens: int = DEFAULT_MAX_TOKENS, **api_kwargs):
22
+ '''
23
+ connection: instance of anthropic.Anthropic
24
+ model_name: must match a known name to the api (use AnthropicProvider to get a list of models)
25
+ max_tokens: controls the api response size. (unlike runtime max_tokens that control size sent to the api)
26
+ api_kwargs: sent to messages.stream(). model, max_tokens, message, system, and tools set internally and should not be set in api_kwargs
27
+ '''
28
+ LOGGER.info(f'__init__: {connection} {model_name} {max_tokens}')
29
+ self.connection = connection
30
+ self.connection_async = AsyncAnthropic(base_url=self.connection.base_url, api_key=self.connection.api_key)
31
+ self.model_name = model_name
32
+ self.max_tokens = max_tokens
33
+ self.api_kwargs = api_kwargs
34
+ self.api_kwargs["model"] = self.model_name
35
+ self.api_kwargs["max_tokens"] = self.max_tokens
36
+
37
+ # convert Part to the format the Anthropic API expects
38
+ def _part_to_anthropic(self, part: Part) -> dict:
39
+ if part.type == "text":
40
+ return {"type": "text", "text": part.data.get("text", "")}
41
+ if part.type == "image":
42
+ return {
43
+ "type": "image",
44
+ "source": {
45
+ "type": "base64",
46
+ "media_type": part.data.get("media_type"),
47
+ "data": part.data.get("data", ""),
48
+ },
49
+ }
50
+ return {"type": part.type, **part.data}
51
+
52
+ # converts the ChatRecord to the format expected by the Anthropic API
53
+ def _record_to_anthropic(self, record: ChatRecord) -> dict | None:
54
+ if record.role == "system":
55
+ return None
56
+
57
+ if record.role == "assistant":
58
+ content = []
59
+ for part in record.content or []:
60
+ if part.type == "text" and not part.data.get("text"):
61
+ continue
62
+ content.append(self._part_to_anthropic(part))
63
+ for call in record.tool_calls or []:
64
+ content.append({
65
+ "type": "tool_use",
66
+ "id": call.id,
67
+ "name": call.name,
68
+ "input": call.args or {},
69
+ })
70
+ if not content:
71
+ return None
72
+ return {"role": "assistant", "content": content}
73
+
74
+ if record.role == "tool":
75
+ text = ""
76
+ if record.content:
77
+ text = record.content[0].data.get("text", "")
78
+ return {
79
+ "role": "user",
80
+ "content": [{
81
+ "type": "tool_result",
82
+ "tool_use_id": record.tool_call_id,
83
+ "content": text,
84
+ }],
85
+ }
86
+
87
+ return {
88
+ "role": record.role,
89
+ "content": [self._part_to_anthropic(p) for p in (record.content or [])],
90
+ }
91
+
92
+ # converts a list[ChatRecord] to the format the Anthropic API format expects
93
+ def _records_to_anthropic(self, records: list[ChatRecord]) -> tuple[str | None, list[dict]]:
94
+ system_parts: list[str] = []
95
+ wire: list[dict] = []
96
+ seen_tool_use_ids: set[str] = set()
97
+
98
+ for record in records:
99
+ # Anthropic takes the system prompt as a separate parameter
100
+ if record.role == "system":
101
+ for part in record.content or []:
102
+ text = part.data.get("text", "") if part.type == "text" else ""
103
+ if text.strip():
104
+ system_parts.append(text)
105
+ continue
106
+
107
+ converted = self._record_to_anthropic(record)
108
+ if converted is None:
109
+ continue
110
+
111
+ # Anthropic requires the conversation to start with a user turn.
112
+ # Trimming can leave an assistant message first, so skip it.
113
+ if not wire and converted["role"] != "user":
114
+ continue
115
+
116
+ content = []
117
+ for block in converted["content"]:
118
+ block_type = block.get("type")
119
+
120
+ if block_type == "text":
121
+ text = block.get("text", "")
122
+ if converted["role"] == "assistant":
123
+ text = text.rstrip() # trailing whitespace is rejected on the final assistant turn
124
+ if not text.strip():
125
+ continue # empty or whitespace-only text is rejected
126
+ block = {**block, "text": text}
127
+
128
+ elif block_type == "tool_use":
129
+ seen_tool_use_ids.add(block["id"])
130
+
131
+ elif block_type == "tool_result":
132
+ # Its tool_use was trimmed or skipped, so the result is orphaned and would be rejected
133
+ if block.get("tool_use_id") not in seen_tool_use_ids:
134
+ continue
135
+
136
+ content.append(block)
137
+
138
+ if not content:
139
+ continue
140
+
141
+ # Messages must alternate user/assistant. Merge back-to-back messages from
142
+ # the same role (consecutive tool results, or messages left adjacent after
143
+ # an empty one was dropped).
144
+ if wire and wire[-1]["role"] == converted["role"]:
145
+ wire[-1]["content"].extend(content)
146
+ else:
147
+ wire.append({"role": converted["role"], "content": content})
148
+
149
+ system = "\n\n".join(system_parts) if system_parts else None
150
+ return system, wire
151
+
152
+ # converts OpenAI tools schemas to the format Anthropic API expects
153
+ def _to_anthropic_tools(self, tools: list[dict] | None) -> list[dict] | None:
154
+ if not tools:
155
+ return None
156
+ converted = []
157
+ for tool in tools:
158
+ fn = tool.get("function", tool)
159
+ converted.append({
160
+ "name": fn["name"],
161
+ "description": fn.get("description", ""),
162
+ "input_schema": fn.get("parameters") or {"type": "object", "properties": {}},
163
+ })
164
+ return converted
165
+
166
+ def _process_event(self, event):
167
+ calls: dict[str,ToolCall] = {}
168
+ event_type = getattr(event, "type", None)
169
+
170
+ if event_type == "text":
171
+ LOGGER.debug(f'replying {event.text}')
172
+ return ApiEvent(event_type="replying", content=event.text)
173
+
174
+ if event_type == "thinking":
175
+ LOGGER.debug(f'thinking: {event.thinking}')
176
+ return ApiEvent(event_type="thinking", content=event.thinking)
177
+
178
+ # tool call start
179
+ if event_type == "content_block_start":
180
+ block = event.content_block
181
+ if getattr(block, "type", None) == "tool_use":
182
+ LOGGER.debug(f'tool call start: {block.name}')
183
+ calls[event.index] = ToolCall(id=block.id, name=block.name, args={})
184
+ return
185
+
186
+ if event_type == "input_json":
187
+ return
188
+
189
+ # convert Anthropic tool call to the internal ToolCall format
190
+ if event_type == "content_block_stop":
191
+ block = getattr(event, "content_block", None)
192
+ if block is not None and getattr(block, "type", None) == "tool_use":
193
+ args = getattr(block, "input", None) or {}
194
+ if not isinstance(args, dict):
195
+ args = {"_value": args}
196
+ call = calls.get(event.index) or ToolCall(id=getattr(block, "id", ""), name=getattr(block, "name", ""))
197
+ call.id = getattr(block, "id", call.id)
198
+ call.name = getattr(block, "name", call.name)
199
+ call.args = args
200
+ calls[event.index] = call
201
+ LOGGER.debug(f'tool calls: {calls}')
202
+ return ApiEvent(event_type="tool_call", tool_calls=list(calls.values()))
203
+
204
+
205
+ if event_type == "error":
206
+ err = getattr(event, "error", None)
207
+ message = getattr(err, "message", None) or str(err or event)
208
+ LOGGER.error(f'api error {message}')
209
+ return ApiEvent(event_type='error', content=message)
210
+
211
+ async def get_stream(self, records: list[ChatRecord], tools: list[dict] | None = None) -> AsyncGenerator[ApiEvent]:
212
+ ''' calls Anthropic.connection.messages.stream() and converts the MessageStream events to the internal ApiEvent format '''
213
+ LOGGER.info(f'get_stream with {len(records)} records and {len(tools) if tools else '0'} tools')
214
+ system, wire = self._records_to_anthropic(records)
215
+ anthropic_tools = self._to_anthropic_tools(tools)
216
+
217
+ self.api_kwargs["messages"] = wire
218
+ if system:
219
+ self.api_kwargs["system"] = system
220
+ if anthropic_tools:
221
+ self.api_kwargs["tools"] = anthropic_tools
222
+
223
+
224
+ # messages.stream() yields SDK helper events (text, thinking, input_json,
225
+ # content_block_start/stop), not the raw SSE event types.
226
+ async with self.connection_async.messages.stream(**self.api_kwargs) as stream:
227
+ async for event in stream:
228
+ api_event = self._process_event(event)
229
+ if api_event:
230
+ yield api_event
231
+
232
+ yield ApiEvent(event_type="done", content="")
233
+
234
+
235
+ class AnthropicProvider(Provider):
236
+ def __init__(self, url: str, key: str, max_tokens: int = DEFAULT_MAX_TOKENS):
237
+ '''
238
+ url: https://api.anthropic.com is the anthropic provided api but other services use the same spec
239
+ key: your api key
240
+ max_tokens: limits the output size from the api. passed by default to make_client but can be set in that call too
241
+ '''
242
+ LOGGER.info(f'__init__: {url} {max_tokens}')
243
+ LOGGER.debug(key)
244
+ kwargs = {"api_key": key or None}
245
+ kwargs["base_url"] = url
246
+ self.connection = Anthropic(**kwargs)
247
+ self.max_tokens = max_tokens
248
+
249
+ def list_models(self) -> list[str]:
250
+ try:
251
+ models = []
252
+ page = self.connection.models.list(limit=100)
253
+ models.extend(m.id for m in page.data)
254
+ while getattr(page, "has_more", False) and getattr(page, "last_id", None):
255
+ page = self.connection.models.list(limit=100, after_id=page.last_id)
256
+ models.extend(m.id for m in page.data)
257
+ return models
258
+ except Exception as e:
259
+ LOGGER.error(f'list_models error: {e}')
260
+ return []
261
+
262
+ def make_client(self, model_name: str, **api_kwargs) -> AnthropicClient:
263
+ return AnthropicClient(self.connection, model_name, max_tokens=self.max_tokens, **api_kwargs)
264
+
265
+
266
+ def create_anthropic_client(url: str, model: str, key: str, **api_kwargs):
267
+ '''helper function to make an AnthropicClient'''
268
+ return AnthropicProvider(url, key).make_client(model, **api_kwargs)
269
+
270
+
271
+ def anthropic_agent_runtime(url: str,
272
+ model: str,
273
+ key: str = 'no key',
274
+ system_prompt: str = '',
275
+ memory_manager: MemoryManager | None = None,
276
+ skill_manager: SkillManager | None = None,
277
+ toolbox: Toolbox | None = None,
278
+ guardrail: Guardrail | None = None,
279
+ rag_connection: RAGComponent | None = None,
280
+ max_tokens: int = 32_000,
281
+ max_rounds: int = 10,
282
+ **api_kwargs):
283
+ ''' helper function to simplify creating an AgentRuntime session with the Anthropic api. api_kwargs are passed into messages.stream() model, messages, tools, system, and max_tokens are set internal and should not be added to api_kwargs. '''
284
+ return PangolinRuntime(
285
+ composer= PangolinComposer(client=create_anthropic_client(url=url, model=model, key=key, **api_kwargs)),
286
+ system_prompt=system_prompt,
287
+ memory_manager=memory_manager or SimpleMemoryManager(),
288
+ skill_manager=skill_manager,
289
+ toolbox=toolbox,
290
+ guardrail=guardrail,
291
+ rag_connection=rag_connection,
292
+ max_tokens=max_tokens,
293
+ max_rounds=max_rounds
294
+ )