MCPcopy Create free account
hub / github.com/anthropics/anthropic-sdk-python / sse

Function sse

tests/lib/tools/test_open_telemetry.py:87–113  ·  view source on GitHub ↗

`message` as the response of a streamed request.

(message: dict[str, Any])

Source from the content-addressed store, hash-verified

85
86
87def sse(message: dict[str, Any]) -> httpx2.Response:
88 """`message` as the response of a streamed request."""
89 start: dict[str, Any] = {**message, "content": [], "stop_reason": None}
90 events: list[dict[str, Any]] = [{"type": "message_start", "message": start}]
91 for index, block in enumerate(message["content"]):
92 empty: dict[str, Any]
93 delta: dict[str, Any]
94 if block["type"] == "tool_use":
95 empty = {**block, "input": {}}
96 delta = {"type": "input_json_delta", "partial_json": json.dumps(block["input"])}
97 elif block["type"] == "compaction":
98 empty = {"type": "compaction", "content": None}
99 delta = {"type": "compaction_delta", "content": block["content"]}
100 else:
101 empty = {"type": "text", "text": ""}
102 delta = {"type": "text_delta", "text": block["text"]}
103 events += [
104 {"type": "content_block_start", "index": index, "content_block": empty},
105 {"type": "content_block_delta", "index": index, "delta": delta},
106 {"type": "content_block_stop", "index": index},
107 ]
108 events += [
109 {"type": "message_delta", "delta": {"stop_reason": message["stop_reason"]}, "usage": USAGE},
110 {"type": "message_stop"},
111 ]
112 body = b"".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n".encode() for e in events)
113 return httpx2.Response(200, content=body, headers={"content-type": "text/event-stream"})
114
115
116class Spans:

Calls

no outgoing calls

Tested by

no test coverage detected