meshagent-anthropic 0.21.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,13 @@
1
+ from .tools import (
2
+ AnthropicMessagesAdapter,
3
+ AnthropicMessagesToolResponseAdapter,
4
+ AnthropicOpenAIResponsesStreamAdapter,
5
+ )
6
+ from .version import __version__
7
+
8
+ __all__ = [
9
+ __version__,
10
+ AnthropicMessagesAdapter,
11
+ AnthropicMessagesToolResponseAdapter,
12
+ AnthropicOpenAIResponsesStreamAdapter,
13
+ ]
@@ -0,0 +1,3 @@
1
+ from .proxy import get_client, get_logging_httpx_client
2
+
3
+ __all__ = [get_client, get_logging_httpx_client]
@@ -0,0 +1,90 @@
1
+ from meshagent.api import RoomClient
2
+ import logging
3
+ import json
4
+ import httpx
5
+ from typing import Optional, Any
6
+
7
+ try:
8
+ from anthropic import AsyncAnthropic
9
+ except Exception: # pragma: no cover
10
+ AsyncAnthropic = None # type: ignore
11
+
12
+ logger = logging.getLogger("anthropic.client")
13
+
14
+
15
+ def _redact_headers(headers: httpx.Headers) -> dict:
16
+ h = dict(headers)
17
+ if "x-api-key" in {k.lower() for k in h.keys()}:
18
+ for k in list(h.keys()):
19
+ if k.lower() == "x-api-key":
20
+ h[k] = "***REDACTED***"
21
+ if "authorization" in {k.lower() for k in h.keys()}:
22
+ for k in list(h.keys()):
23
+ if k.lower() == "authorization":
24
+ h[k] = "***REDACTED***"
25
+ return h
26
+
27
+
28
+ def _truncate_bytes(b: bytes, limit: int = 4000) -> str:
29
+ s = b.decode("utf-8", errors="replace")
30
+ return (
31
+ s
32
+ if len(s) <= limit
33
+ else (s[:limit] + f"\n... (truncated, {len(s)} chars total)")
34
+ )
35
+
36
+
37
+ async def log_request(request: httpx.Request):
38
+ logging.info("==> %s %s", request.method, request.url)
39
+ logging.info("headers=%s", json.dumps(_redact_headers(request.headers), indent=2))
40
+ if request.content:
41
+ logging.info("body=%s", _truncate_bytes(request.content))
42
+
43
+
44
+ async def log_response(response: httpx.Response):
45
+ body = await response.aread()
46
+ logging.info("<== %s %s", response.status_code, response.request.url)
47
+ logging.info("headers=%s", json.dumps(_redact_headers(response.headers), indent=2))
48
+ if body:
49
+ logging.info("body=%s", _truncate_bytes(body))
50
+
51
+
52
+ def get_logging_httpx_client() -> httpx.AsyncClient:
53
+ return httpx.AsyncClient(
54
+ event_hooks={"request": [log_request], "response": [log_response]},
55
+ timeout=60.0,
56
+ )
57
+
58
+
59
+ def get_client(
60
+ *, room: RoomClient, http_client: Optional[httpx.AsyncClient] = None
61
+ ) -> Any:
62
+ if AsyncAnthropic is None: # pragma: no cover
63
+ raise RuntimeError(
64
+ "anthropic is not installed. Install `meshagent-anthropic` extras/deps."
65
+ )
66
+
67
+ token: str = room.protocol.token
68
+
69
+ url = getattr(room.protocol, "url")
70
+ if url is None:
71
+ logger.debug(
72
+ "protocol does not have url, anthropic client falling back to room url %s",
73
+ room.room_url,
74
+ )
75
+ url = room.room_url
76
+ else:
77
+ logger.debug("protocol had url, anthropic client will use %s", url)
78
+
79
+ room_proxy_url = f"{url}/anthropic"
80
+
81
+ if room_proxy_url.startswith("ws:") or room_proxy_url.startswith("wss:"):
82
+ room_proxy_url = room_proxy_url.replace("ws", "http", 1)
83
+
84
+ # The MeshAgent room proxy validates `x-api-key` and `Meshagent-Session`.
85
+ return AsyncAnthropic(
86
+ api_key=token,
87
+ base_url=room_proxy_url,
88
+ http_client=http_client,
89
+ default_headers={"Meshagent-Session": room.session_id},
90
+ )
@@ -0,0 +1,11 @@
1
+ from .messages_adapter import (
2
+ AnthropicMessagesAdapter,
3
+ AnthropicMessagesToolResponseAdapter,
4
+ )
5
+ from .openai_responses_stream_adapter import AnthropicOpenAIResponsesStreamAdapter
6
+
7
+ __all__ = [
8
+ AnthropicMessagesAdapter,
9
+ AnthropicMessagesToolResponseAdapter,
10
+ AnthropicOpenAIResponsesStreamAdapter,
11
+ ]
@@ -0,0 +1,419 @@
1
+ from __future__ import annotations
2
+
3
+ from meshagent.agents.agent import AgentChatContext
4
+ from meshagent.api import RoomClient, RoomException, RemoteParticipant
5
+ from meshagent.tools import Toolkit, ToolContext, Tool
6
+ from meshagent.api.messaging import (
7
+ Response,
8
+ LinkResponse,
9
+ FileResponse,
10
+ JsonResponse,
11
+ TextResponse,
12
+ EmptyResponse,
13
+ RawOutputs,
14
+ ensure_response,
15
+ )
16
+ from meshagent.agents.adapter import ToolResponseAdapter, LLMAdapter
17
+
18
+ import json
19
+ from typing import Any, Optional, Callable
20
+ import os
21
+ import logging
22
+ import re
23
+ import asyncio
24
+
25
+ from meshagent.anthropic.proxy import get_client, get_logging_httpx_client
26
+
27
+ try:
28
+ from anthropic import APIStatusError
29
+ except Exception: # pragma: no cover
30
+ APIStatusError = Exception # type: ignore
31
+
32
+ logger = logging.getLogger("anthropic_agent")
33
+
34
+
35
+ def _replace_non_matching(text: str, allowed_chars: str, replacement: str) -> str:
36
+ pattern = rf"[^{allowed_chars}]"
37
+ return re.sub(pattern, replacement, text)
38
+
39
+
40
+ def safe_tool_name(name: str) -> str:
41
+ return _replace_non_matching(name, "a-zA-Z0-9_-", "_")
42
+
43
+
44
+ def _as_jsonable(obj: Any) -> Any:
45
+ if isinstance(obj, dict):
46
+ return obj
47
+ return obj.model_dump(mode="json")
48
+
49
+
50
+ def _text_block(text: str) -> dict:
51
+ return {"type": "text", "text": text}
52
+
53
+
54
+ class MessagesToolBundle:
55
+ def __init__(self, toolkits: list[Toolkit]):
56
+ self._executors: dict[str, Toolkit] = {}
57
+ self._safe_names: dict[str, str] = {}
58
+ self._tools_by_safe_name: dict[str, Tool] = {}
59
+
60
+ tools: list[dict] = []
61
+
62
+ for toolkit in toolkits:
63
+ for v in toolkit.tools:
64
+ if not isinstance(v, Tool):
65
+ raise RoomException(f"unsupported tool type {type(v)}")
66
+
67
+ original_name = v.name
68
+ safe_name = safe_tool_name(original_name)
69
+
70
+ if original_name in self._executors:
71
+ raise Exception(
72
+ f"duplicate in bundle '{original_name}', tool names must be unique."
73
+ )
74
+
75
+ self._executors[original_name] = toolkit
76
+ self._safe_names[safe_name] = original_name
77
+ self._tools_by_safe_name[safe_name] = v
78
+
79
+ schema = {**v.input_schema}
80
+ if v.defs is not None:
81
+ schema["$defs"] = v.defs
82
+
83
+ tools.append(
84
+ {
85
+ "name": safe_name,
86
+ "description": v.description,
87
+ "input_schema": schema,
88
+ }
89
+ )
90
+
91
+ self._tools = tools or None
92
+
93
+ def to_json(self) -> list[dict] | None:
94
+ return None if self._tools is None else self._tools.copy()
95
+
96
+ def get_tool(self, safe_name: str) -> Tool | None:
97
+ return self._tools_by_safe_name.get(safe_name)
98
+
99
+ async def execute(self, *, context: ToolContext, tool_use: dict) -> Response:
100
+ safe_name = tool_use.get("name")
101
+ if safe_name not in self._safe_names:
102
+ raise RoomException(
103
+ f"Invalid tool name {safe_name}, check the name of the tool"
104
+ )
105
+
106
+ name = self._safe_names[safe_name]
107
+ if name not in self._executors:
108
+ raise Exception(f"Unregistered tool name {name}")
109
+
110
+ arguments = tool_use.get("input") or {}
111
+ proxy = self._executors[name]
112
+ result = await proxy.execute(context=context, name=name, arguments=arguments)
113
+ return ensure_response(result)
114
+
115
+
116
+ class AnthropicMessagesToolResponseAdapter(ToolResponseAdapter):
117
+ async def to_plain_text(self, *, room: RoomClient, response: Response) -> str:
118
+ if isinstance(response, LinkResponse):
119
+ return json.dumps({"name": response.name, "url": response.url})
120
+ if isinstance(response, JsonResponse):
121
+ return json.dumps(response.json)
122
+ if isinstance(response, TextResponse):
123
+ return response.text
124
+ if isinstance(response, FileResponse):
125
+ return response.name
126
+ if isinstance(response, EmptyResponse):
127
+ return "ok"
128
+ if isinstance(response, dict):
129
+ return json.dumps(response)
130
+ if isinstance(response, str):
131
+ return response
132
+ if response is None:
133
+ return "ok"
134
+ raise Exception("unexpected return type: {type}".format(type=type(response)))
135
+
136
+ async def create_messages(
137
+ self,
138
+ *,
139
+ context: AgentChatContext,
140
+ tool_call: Any,
141
+ room: RoomClient,
142
+ response: Response,
143
+ ) -> list:
144
+ tool_use = tool_call if isinstance(tool_call, dict) else _as_jsonable(tool_call)
145
+ tool_use_id = tool_use.get("id")
146
+ if tool_use_id is None:
147
+ raise RoomException("anthropic tool_use block was missing an id")
148
+
149
+ if isinstance(response, RawOutputs):
150
+ # Allow advanced tools to return pre-built Anthropic blocks.
151
+ return [{"role": "user", "content": response.outputs}]
152
+
153
+ output = await self.to_plain_text(room=room, response=response)
154
+
155
+ message = {
156
+ "role": "user",
157
+ "content": [
158
+ {
159
+ "type": "tool_result",
160
+ "tool_use_id": tool_use_id,
161
+ "content": [_text_block(output)],
162
+ }
163
+ ],
164
+ }
165
+
166
+ room.developer.log_nowait(
167
+ type="llm.message",
168
+ data={
169
+ "context": context.id,
170
+ "participant_id": room.local_participant.id,
171
+ "participant_name": room.local_participant.get_attribute("name"),
172
+ "message": message,
173
+ },
174
+ )
175
+
176
+ return [message]
177
+
178
+
179
+ class AnthropicMessagesAdapter(LLMAdapter[dict]):
180
+ def __init__(
181
+ self,
182
+ model: str = os.getenv("ANTHROPIC_MODEL", "claude-3-5-sonnet-latest"),
183
+ max_tokens: int = int(os.getenv("ANTHROPIC_MAX_TOKENS", "1024")),
184
+ client: Optional[Any] = None,
185
+ message_options: Optional[dict] = None,
186
+ provider: str = "anthropic",
187
+ log_requests: bool = False,
188
+ ):
189
+ self._model = model
190
+ self._max_tokens = max_tokens
191
+ self._client = client
192
+ self._message_options = message_options or {}
193
+ self._provider = provider
194
+ self._log_requests = log_requests
195
+
196
+ def default_model(self) -> str:
197
+ return self._model
198
+
199
+ def create_chat_context(self) -> AgentChatContext:
200
+ return AgentChatContext(system_role=None)
201
+
202
+ def get_anthropic_client(self, *, room: RoomClient) -> Any:
203
+ if self._client is not None:
204
+ return self._client
205
+ http_client = get_logging_httpx_client() if self._log_requests else None
206
+ return get_client(room=room, http_client=http_client)
207
+
208
+ def _convert_messages(
209
+ self, *, context: AgentChatContext
210
+ ) -> tuple[list[dict], Optional[str]]:
211
+ system = context.get_system_instructions()
212
+
213
+ messages: list[dict] = []
214
+ for m in context.messages:
215
+ if m.get("role") in {"user", "assistant"}:
216
+ content = m.get("content")
217
+ if isinstance(content, str):
218
+ messages.append(
219
+ {"role": m["role"], "content": [_text_block(content)]}
220
+ )
221
+ elif isinstance(content, list):
222
+ # Allow passing through OpenAI-style image/file blocks if already present.
223
+ # Tool adapters will also insert Anthropic blocks here.
224
+ messages.append({"role": m["role"], "content": content})
225
+ else:
226
+ messages.append(
227
+ {"role": m["role"], "content": [_text_block(str(content))]}
228
+ )
229
+
230
+ return messages, system
231
+
232
+ async def _create_with_optional_headers(self, client: Any, **kwargs) -> Any:
233
+ try:
234
+ return await client.messages.create(**kwargs)
235
+ except TypeError:
236
+ kwargs.pop("extra_headers", None)
237
+ return await client.messages.create(**kwargs)
238
+
239
+ async def _stream_message(
240
+ self,
241
+ *,
242
+ client: Any,
243
+ request: dict,
244
+ event_handler: Callable[[dict], None],
245
+ ) -> Any:
246
+ """Stream text deltas and return the final message.
247
+
248
+ Uses the official Anthropic SDK streaming helper:
249
+
250
+ ```py
251
+ async with client.messages.stream(...) as stream:
252
+ async for text in stream.text_stream:
253
+ ...
254
+ message = await stream.get_final_message()
255
+ ```
256
+ """
257
+
258
+ stream = client.messages.stream(**request)
259
+
260
+ async with stream:
261
+ async for event in stream:
262
+ event_handler({"type": event.type, "event": _as_jsonable(event)})
263
+
264
+ final_message = await stream.get_final_message()
265
+ event_handler(
266
+ {"type": "message.completed", "message": _as_jsonable(final_message)}
267
+ )
268
+ return final_message
269
+
270
+ async def next(
271
+ self,
272
+ *,
273
+ context: AgentChatContext,
274
+ room: RoomClient,
275
+ toolkits: list[Toolkit],
276
+ tool_adapter: Optional[ToolResponseAdapter] = None,
277
+ output_schema: Optional[dict] = None,
278
+ event_handler: Optional[Callable[[dict], None]] = None,
279
+ model: Optional[str] = None,
280
+ on_behalf_of: Optional[RemoteParticipant] = None,
281
+ ) -> Any:
282
+ if model is None:
283
+ model = self.default_model()
284
+
285
+ if tool_adapter is None:
286
+ tool_adapter = AnthropicMessagesToolResponseAdapter()
287
+
288
+ client = self.get_anthropic_client(room=room)
289
+
290
+ validation_attempts = 0
291
+
292
+ try:
293
+ while True:
294
+ tool_bundle = MessagesToolBundle(toolkits=toolkits)
295
+ tools = tool_bundle.to_json()
296
+
297
+ messages, system = self._convert_messages(context=context)
298
+
299
+ if output_schema is not None:
300
+ schema_hint = json.dumps(output_schema)
301
+ schema_system = (
302
+ "Return ONLY valid JSON that matches this JSON Schema. "
303
+ "Do not wrap in markdown. Schema: " + schema_hint
304
+ )
305
+ system = (
306
+ (system + "\n" + schema_system) if system else schema_system
307
+ )
308
+
309
+ extra_headers = {}
310
+ if on_behalf_of is not None:
311
+ extra_headers["Meshagent-On-Behalf-Of"] = (
312
+ on_behalf_of.get_attribute("name")
313
+ )
314
+
315
+ request = {
316
+ "model": model,
317
+ "max_tokens": self._max_tokens,
318
+ "messages": messages,
319
+ "system": system,
320
+ "tools": tools,
321
+ "extra_headers": extra_headers or None,
322
+ **(self._message_options or {}),
323
+ }
324
+
325
+ # remove None fields
326
+ request = {k: v for k, v in request.items() if v is not None}
327
+
328
+ logger.info("requesting response from anthropic with model: %s", model)
329
+
330
+ if event_handler is not None:
331
+ final_message = await self._stream_message(
332
+ client=client,
333
+ request=request,
334
+ event_handler=event_handler,
335
+ )
336
+ response_dict = _as_jsonable(final_message)
337
+ else:
338
+ response = await self._create_with_optional_headers(
339
+ client, **request
340
+ )
341
+ response_dict = _as_jsonable(response)
342
+
343
+ content_blocks = []
344
+ raw_content = response_dict.get("content")
345
+ if isinstance(raw_content, list):
346
+ content_blocks = raw_content
347
+
348
+ tool_uses = [b for b in content_blocks if b.get("type") == "tool_use"]
349
+
350
+ # Keep the assistant message in context.
351
+ assistant_message = {"role": "assistant", "content": content_blocks}
352
+ context.messages.append(assistant_message)
353
+
354
+ if tool_uses:
355
+ tasks = []
356
+
357
+ async def do_tool(tool_use: dict) -> list[dict]:
358
+ tool_context = ToolContext(
359
+ room=room,
360
+ caller=room.local_participant,
361
+ on_behalf_of=on_behalf_of,
362
+ caller_context={"chat": context.to_json()},
363
+ )
364
+ tool_response = await tool_bundle.execute(
365
+ context=tool_context,
366
+ tool_use=tool_use,
367
+ )
368
+ return await tool_adapter.create_messages(
369
+ context=context,
370
+ tool_call=tool_use,
371
+ room=room,
372
+ response=tool_response,
373
+ )
374
+
375
+ for tool_use in tool_uses:
376
+ tasks.append(asyncio.create_task(do_tool(tool_use)))
377
+
378
+ results = await asyncio.gather(*tasks)
379
+ for msgs in results:
380
+ for msg in msgs:
381
+ context.messages.append(msg)
382
+
383
+ continue
384
+
385
+ # no tool calls; return final content
386
+ text = "".join(
387
+ [
388
+ b.get("text", "")
389
+ for b in content_blocks
390
+ if b.get("type") == "text"
391
+ ]
392
+ )
393
+
394
+ if output_schema is None:
395
+ return text
396
+
397
+ # Schema-mode: parse and validate JSON.
398
+ validation_attempts += 1
399
+ try:
400
+ parsed = json.loads(text)
401
+ self.validate(response=parsed, output_schema=output_schema)
402
+ return parsed
403
+ except Exception as e:
404
+ if validation_attempts >= 3:
405
+ raise RoomException(
406
+ f"Invalid JSON response from Anthropic: {e}"
407
+ )
408
+ context.messages.append(
409
+ {
410
+ "role": "user",
411
+ "content": (
412
+ "The previous response did not match the required JSON schema. "
413
+ f"Error: {e}. Please try again and return only valid JSON."
414
+ ),
415
+ }
416
+ )
417
+
418
+ except APIStatusError as e:
419
+ raise RoomException(f"Error from Anthropic: {e}")
@@ -0,0 +1,400 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from dataclasses import dataclass
5
+ from typing import Any, Callable, Optional
6
+
7
+ from meshagent.api import RoomClient, RemoteParticipant
8
+ from meshagent.agents.agent import AgentChatContext
9
+ from meshagent.tools import Toolkit
10
+
11
+ from .messages_adapter import AnthropicMessagesAdapter
12
+
13
+
14
+ @dataclass
15
+ class _OutputBlockState:
16
+ kind: str # "message" | "function_call" | "reasoning"
17
+ item_id: str
18
+ output_index: int
19
+ content_index: int
20
+ name: Optional[str] = None
21
+ call_id: Optional[str] = None
22
+ text: str = ""
23
+ arguments: str = ""
24
+
25
+
26
+ class AnthropicOpenAIResponsesStreamAdapter(AnthropicMessagesAdapter):
27
+ """Anthropic adapter that emits OpenAI Responses-style stream events.
28
+
29
+ This is useful when you have downstream consumers that already understand the
30
+ OpenAI Responses streaming event schema (e.g. UI code), but want to run the
31
+ underlying inference on Anthropic.
32
+
33
+ Notes:
34
+ - This adapter only affects the *streaming* event shape.
35
+ - Tool execution still uses MeshAgent toolkits and the Anthropic tool loop.
36
+ """
37
+
38
+ async def _stream_message(
39
+ self,
40
+ *,
41
+ client: Any,
42
+ request: dict,
43
+ event_handler: Callable[[dict], None],
44
+ ) -> Any:
45
+ seq = 0
46
+ response_id: Optional[str] = None
47
+ response_model: str = str(request.get("model"))
48
+
49
+ output: list[dict] = []
50
+ blocks: dict[int, _OutputBlockState] = {}
51
+
52
+ created_at = int(time.time())
53
+
54
+ def emit(payload: dict) -> None:
55
+ nonlocal seq
56
+ if "sequence_number" not in payload:
57
+ payload["sequence_number"] = seq
58
+ seq += 1
59
+ event_handler(payload)
60
+
61
+ def output_message_item(*, item_id: str, status: str, text: str) -> dict:
62
+ return {
63
+ "type": "message",
64
+ "id": item_id,
65
+ "role": "assistant",
66
+ "status": status,
67
+ "content": [
68
+ {
69
+ "type": "output_text",
70
+ "text": text,
71
+ "annotations": [],
72
+ "logprobs": None,
73
+ }
74
+ ],
75
+ }
76
+
77
+ def output_function_call_item(
78
+ *,
79
+ item_id: str,
80
+ call_id: str,
81
+ name: str,
82
+ status: Optional[str],
83
+ arguments: str,
84
+ ) -> dict:
85
+ return {
86
+ "type": "function_call",
87
+ "id": item_id,
88
+ "call_id": call_id,
89
+ "name": name,
90
+ "arguments": arguments,
91
+ "status": status,
92
+ }
93
+
94
+ def output_reasoning_item(*, item_id: str, status: str, text: str) -> dict:
95
+ return {
96
+ "type": "reasoning",
97
+ "id": item_id,
98
+ "status": status,
99
+ "summary": [],
100
+ "content": [{"type": "reasoning_text", "text": text}],
101
+ "encrypted_content": None,
102
+ }
103
+
104
+ response_obj: dict = {
105
+ "id": None,
106
+ "object": "response",
107
+ "created_at": created_at,
108
+ "model": response_model,
109
+ "output": output,
110
+ "status": "in_progress",
111
+ "error": None,
112
+ "usage": None,
113
+ }
114
+
115
+ async with client.messages.stream(**request) as stream:
116
+ async for event in stream:
117
+ data = event.model_dump(mode="json")
118
+ etype = data.get("type")
119
+
120
+ if etype == "message_start":
121
+ message = data.get("message") or {}
122
+ response_id = message.get("id") or response_id
123
+ response_obj["id"] = response_id
124
+ if message.get("model") is not None:
125
+ response_obj["model"] = message.get("model")
126
+
127
+ emit({"type": "response.created", "response": dict(response_obj)})
128
+
129
+ elif etype == "content_block_start":
130
+ idx = int(data.get("index"))
131
+ block = data.get("content_block") or {}
132
+ btype = block.get("type")
133
+
134
+ output_index = len(output)
135
+ base_item_id = response_id or "anthropic"
136
+ item_id = f"{base_item_id}_out_{output_index}"
137
+
138
+ if btype == "text":
139
+ item = output_message_item(
140
+ item_id=item_id, status="in_progress", text=""
141
+ )
142
+ output.append(item)
143
+ blocks[idx] = _OutputBlockState(
144
+ kind="message",
145
+ item_id=item_id,
146
+ output_index=output_index,
147
+ content_index=0,
148
+ )
149
+
150
+ elif btype == "tool_use":
151
+ call_id = str(block.get("id"))
152
+ name = str(block.get("name"))
153
+ item = output_function_call_item(
154
+ item_id=item_id,
155
+ call_id=call_id,
156
+ name=name,
157
+ status="in_progress",
158
+ arguments="",
159
+ )
160
+ output.append(item)
161
+ blocks[idx] = _OutputBlockState(
162
+ kind="function_call",
163
+ item_id=item_id,
164
+ output_index=output_index,
165
+ content_index=0,
166
+ name=name,
167
+ call_id=call_id,
168
+ )
169
+
170
+ elif btype == "thinking":
171
+ item = output_reasoning_item(
172
+ item_id=item_id, status="in_progress", text=""
173
+ )
174
+ output.append(item)
175
+ blocks[idx] = _OutputBlockState(
176
+ kind="reasoning",
177
+ item_id=item_id,
178
+ output_index=output_index,
179
+ content_index=0,
180
+ )
181
+
182
+ else:
183
+ # Unknown block type: ignore for OpenAI compatibility.
184
+ continue
185
+
186
+ emit(
187
+ {
188
+ "type": "response.output_item.added",
189
+ "output_index": output_index,
190
+ "item": output[output_index],
191
+ }
192
+ )
193
+
194
+ # OpenAI-style content part events (text + reasoning content).
195
+ state = blocks.get(idx)
196
+ if state is not None and state.kind in {"message", "reasoning"}:
197
+ emit(
198
+ {
199
+ "type": "response.content_part.added",
200
+ "output_index": state.output_index,
201
+ "item_id": state.item_id,
202
+ "content_index": state.content_index,
203
+ "part": output[state.output_index]["content"][
204
+ state.content_index
205
+ ],
206
+ }
207
+ )
208
+
209
+ elif etype == "content_block_delta":
210
+ idx = int(data.get("index"))
211
+ state = blocks.get(idx)
212
+ if state is None:
213
+ continue
214
+
215
+ delta = data.get("delta") or {}
216
+ dtype = delta.get("type")
217
+
218
+ if dtype == "text_delta" and state.kind == "message":
219
+ piece = str(delta.get("text") or "")
220
+ state.text += piece
221
+ output[state.output_index]["content"][0]["text"] = state.text
222
+
223
+ emit(
224
+ {
225
+ "type": "response.output_text.delta",
226
+ "output_index": state.output_index,
227
+ "item_id": state.item_id,
228
+ "content_index": state.content_index,
229
+ "delta": piece,
230
+ "logprobs": None,
231
+ }
232
+ )
233
+
234
+ elif dtype == "input_json_delta" and state.kind == "function_call":
235
+ piece = str(delta.get("partial_json") or "")
236
+ state.arguments += piece
237
+ output[state.output_index]["arguments"] = state.arguments
238
+
239
+ emit(
240
+ {
241
+ "type": "response.function_call_arguments.delta",
242
+ "output_index": state.output_index,
243
+ "item_id": state.item_id,
244
+ "delta": piece,
245
+ }
246
+ )
247
+
248
+ elif dtype == "thinking_delta" and state.kind == "reasoning":
249
+ piece = str(delta.get("thinking") or "")
250
+ state.text += piece
251
+ output[state.output_index]["content"][0]["text"] = state.text
252
+
253
+ emit(
254
+ {
255
+ "type": "response.reasoning_text.delta",
256
+ "output_index": state.output_index,
257
+ "item_id": state.item_id,
258
+ "content_index": state.content_index,
259
+ "delta": piece,
260
+ }
261
+ )
262
+
263
+ else:
264
+ # Ignore signature_delta and unknown deltas.
265
+ continue
266
+
267
+ elif etype == "content_block_stop":
268
+ idx = int(data.get("index"))
269
+ state = blocks.get(idx)
270
+ if state is None:
271
+ continue
272
+
273
+ if state.kind == "message":
274
+ emit(
275
+ {
276
+ "type": "response.output_text.done",
277
+ "output_index": state.output_index,
278
+ "item_id": state.item_id,
279
+ "content_index": state.content_index,
280
+ "text": state.text,
281
+ "logprobs": None,
282
+ }
283
+ )
284
+ output[state.output_index] = output_message_item(
285
+ item_id=state.item_id, status="completed", text=state.text
286
+ )
287
+ emit(
288
+ {
289
+ "type": "response.content_part.done",
290
+ "output_index": state.output_index,
291
+ "item_id": state.item_id,
292
+ "content_index": state.content_index,
293
+ "part": output[state.output_index]["content"][
294
+ state.content_index
295
+ ],
296
+ }
297
+ )
298
+
299
+ elif state.kind == "function_call":
300
+ emit(
301
+ {
302
+ "type": "response.function_call_arguments.done",
303
+ "output_index": state.output_index,
304
+ "item_id": state.item_id,
305
+ "name": state.name,
306
+ "arguments": state.arguments,
307
+ }
308
+ )
309
+ output[state.output_index] = output_function_call_item(
310
+ item_id=state.item_id,
311
+ call_id=str(state.call_id),
312
+ name=str(state.name),
313
+ status="completed",
314
+ arguments=state.arguments,
315
+ )
316
+
317
+ elif state.kind == "reasoning":
318
+ emit(
319
+ {
320
+ "type": "response.reasoning_text.done",
321
+ "output_index": state.output_index,
322
+ "item_id": state.item_id,
323
+ "content_index": state.content_index,
324
+ "text": state.text,
325
+ }
326
+ )
327
+ output[state.output_index] = output_reasoning_item(
328
+ item_id=state.item_id, status="completed", text=state.text
329
+ )
330
+ emit(
331
+ {
332
+ "type": "response.content_part.done",
333
+ "output_index": state.output_index,
334
+ "item_id": state.item_id,
335
+ "content_index": state.content_index,
336
+ "part": output[state.output_index]["content"][
337
+ state.content_index
338
+ ],
339
+ }
340
+ )
341
+
342
+ emit(
343
+ {
344
+ "type": "response.output_item.done",
345
+ "output_index": state.output_index,
346
+ "item": output[state.output_index],
347
+ }
348
+ )
349
+
350
+ elif etype == "message_stop":
351
+ # Defer `response.completed` until after we have final usage.
352
+ pass
353
+
354
+ else:
355
+ # ping, message_delta, etc.
356
+ continue
357
+
358
+ final_message = await stream.get_final_message()
359
+ final_dict = final_message.model_dump(mode="json")
360
+ usage = final_dict.get("usage") or {}
361
+ input_tokens = usage.get("input_tokens")
362
+ output_tokens = usage.get("output_tokens")
363
+ if isinstance(input_tokens, int) and isinstance(output_tokens, int):
364
+ response_obj["usage"] = {
365
+ "input_tokens": input_tokens,
366
+ "output_tokens": output_tokens,
367
+ "total_tokens": input_tokens + output_tokens,
368
+ "input_tokens_details": None,
369
+ "output_tokens_details": None,
370
+ }
371
+
372
+ response_obj["status"] = "completed"
373
+ response_obj["output"] = output
374
+
375
+ emit({"type": "response.completed", "response": dict(response_obj)})
376
+ return final_message
377
+
378
+ async def next(
379
+ self,
380
+ *,
381
+ context: AgentChatContext,
382
+ room: RoomClient,
383
+ toolkits: list[Toolkit],
384
+ tool_adapter: Any = None,
385
+ output_schema: Optional[dict] = None,
386
+ event_handler: Optional[Callable[[dict], None]] = None,
387
+ model: Optional[str] = None,
388
+ on_behalf_of: Optional[RemoteParticipant] = None,
389
+ ) -> Any:
390
+ # Keep the same behavior; only streaming shape changes.
391
+ return await super().next(
392
+ context=context,
393
+ room=room,
394
+ toolkits=toolkits,
395
+ tool_adapter=tool_adapter,
396
+ output_schema=output_schema,
397
+ event_handler=event_handler,
398
+ model=model,
399
+ on_behalf_of=on_behalf_of,
400
+ )
@@ -0,0 +1 @@
1
+ __version__ = "0.21.0"
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.4
2
+ Name: meshagent-anthropic
3
+ Version: 0.21.0
4
+ Summary: Anthropic Building Blocks for Meshagent
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Documentation, https://docs.meshagent.com
7
+ Project-URL: Website, https://www.meshagent.com
8
+ Project-URL: Source, https://www.meshagent.com
9
+ Requires-Python: >=3.13
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pytest~=8.4
13
+ Requires-Dist: pytest-asyncio~=0.26
14
+ Requires-Dist: meshagent-api~=0.21.0
15
+ Requires-Dist: meshagent-agents~=0.21.0
16
+ Requires-Dist: meshagent-tools~=0.21.0
17
+ Requires-Dist: anthropic<1.0,>=0.25
18
+ Dynamic: license-file
19
+
20
+ # [Meshagent](https://www.meshagent.com)
21
+
22
+ ## MeshAgent Anthropic
23
+ The `meshagent.anthropic` package provides adapters to integrate Anthropic models (Messages API) with MeshAgent tools and agents.
24
+
25
+ ### Messages Adapter
26
+ - `AnthropicMessagesAdapter`: wraps the Anthropic Messages API. It turns `Toolkit` objects into Anthropic tool definitions, executes tool calls, and returns the final assistant response.
27
+
28
+ ```Python Python
29
+ from meshagent.anthropic import AnthropicMessagesAdapter
30
+
31
+ adapter = AnthropicMessagesAdapter(model="claude-3-5-sonnet-latest")
32
+ ```
33
+
34
+ ### Tool Response Adapter
35
+ `AnthropicMessagesToolResponseAdapter` converts a tool's structured response into Anthropic `tool_result` blocks that can be inserted back into the conversation.
36
+
37
+ ---
38
+ ### Learn more about MeshAgent on our website or check out the docs for additional examples!
39
+
40
+ **Website**: [www.meshagent.com](https://www.meshagent.com/)
41
+
42
+ **Documentation**: [docs.meshagent.com](https://docs.meshagent.com/)
43
+
44
+ ---
@@ -0,0 +1,12 @@
1
+ meshagent/anthropic/__init__.py,sha256=aQVq1WNkmJRwZiV9i7lF_K2MHrTyOSDe3ewuXU7FOEg,318
2
+ meshagent/anthropic/version.py,sha256=-reNiXr25nUU7em7_IKJzimCI10W4nA8ouxAiOr4FaQ,23
3
+ meshagent/anthropic/proxy/__init__.py,sha256=_E4wvJC90tmMnatDodkD0kIB8zsDZ4_zFd-5s86WQ8c,106
4
+ meshagent/anthropic/proxy/proxy.py,sha256=FSVuTao0NyVQ6SVritDNFrL0bborUaMrXt2z-65Zk-4,2821
5
+ meshagent/anthropic/tools/__init__.py,sha256=FwuQWhftwumt_GZJL20kHMBfvb6zpe1Vy6JaSOw6e9E,319
6
+ meshagent/anthropic/tools/messages_adapter.py,sha256=28Op_g-nBD9yCP9wiXQCsxoktxf_J31Fzeyixqnpei4,14821
7
+ meshagent/anthropic/tools/openai_responses_stream_adapter.py,sha256=ODtWusjnPDNedE_Nx5dTdEAhihpWmAXyEbYHuF42D8M,15763
8
+ meshagent_anthropic-0.21.0.dist-info/licenses/LICENSE,sha256=TRD-XzqhdrBbIpokiGa61wuDTBc_ElKoFP9HSNihODc,10255
9
+ meshagent_anthropic-0.21.0.dist-info/METADATA,sha256=RI1gurw9ovXk-yKc5Ij1n4pxASEYOIN5VI_GbQXwqDo,1595
10
+ meshagent_anthropic-0.21.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
+ meshagent_anthropic-0.21.0.dist-info/top_level.txt,sha256=GlcXnHtRP6m7zlG3Df04M35OsHtNXy_DY09oFwWrH74,10
12
+ meshagent_anthropic-0.21.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ meshagent