anthropic.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import os
  2. from collections.abc import Iterable
  3. from typing import Any, Literal, Union
  4. import anthropic
  5. import pytest
  6. from _pytest.monkeypatch import MonkeyPatch
  7. from anthropic import Stream
  8. from anthropic.resources import Messages
  9. from anthropic.types import (
  10. ContentBlock,
  11. ContentBlockDeltaEvent,
  12. Message,
  13. MessageDeltaEvent,
  14. MessageDeltaUsage,
  15. MessageParam,
  16. MessageStartEvent,
  17. MessageStopEvent,
  18. MessageStreamEvent,
  19. TextDelta,
  20. Usage,
  21. )
  22. from anthropic.types.message_delta_event import Delta
  23. MOCK = os.getenv("MOCK_SWITCH", "false") == "true"
  24. class MockAnthropicClass:
  25. @staticmethod
  26. def mocked_anthropic_chat_create_sync(model: str) -> Message:
  27. return Message(
  28. id="msg-123",
  29. type="message",
  30. role="assistant",
  31. content=[ContentBlock(text="hello, I'm a chatbot from anthropic", type="text")],
  32. model=model,
  33. stop_reason="stop_sequence",
  34. usage=Usage(input_tokens=1, output_tokens=1),
  35. )
  36. @staticmethod
  37. def mocked_anthropic_chat_create_stream(model: str) -> Stream[MessageStreamEvent]:
  38. full_response_text = "hello, I'm a chatbot from anthropic"
  39. yield MessageStartEvent(
  40. type="message_start",
  41. message=Message(
  42. id="msg-123",
  43. content=[],
  44. role="assistant",
  45. model=model,
  46. stop_reason=None,
  47. type="message",
  48. usage=Usage(input_tokens=1, output_tokens=1),
  49. ),
  50. )
  51. index = 0
  52. for i in range(0, len(full_response_text)):
  53. yield ContentBlockDeltaEvent(
  54. type="content_block_delta", delta=TextDelta(text=full_response_text[i], type="text_delta"), index=index
  55. )
  56. index += 1
  57. yield MessageDeltaEvent(
  58. type="message_delta", delta=Delta(stop_reason="stop_sequence"), usage=MessageDeltaUsage(output_tokens=1)
  59. )
  60. yield MessageStopEvent(type="message_stop")
  61. def mocked_anthropic(
  62. self: Messages,
  63. *,
  64. max_tokens: int,
  65. messages: Iterable[MessageParam],
  66. model: str,
  67. stream: Literal[True],
  68. **kwargs: Any,
  69. ) -> Union[Message, Stream[MessageStreamEvent]]:
  70. if len(self._client.api_key) < 18:
  71. raise anthropic.AuthenticationError("Invalid API key")
  72. if stream:
  73. return MockAnthropicClass.mocked_anthropic_chat_create_stream(model=model)
  74. else:
  75. return MockAnthropicClass.mocked_anthropic_chat_create_sync(model=model)
  76. @pytest.fixture
  77. def setup_anthropic_mock(request, monkeypatch: MonkeyPatch):
  78. if MOCK:
  79. monkeypatch.setattr(Messages, "create", MockAnthropicClass.mocked_anthropic)
  80. yield
  81. if MOCK:
  82. monkeypatch.undo()