agentscope-runtime 0.1.6__py3-none-any.whl → 0.2.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.
Files changed (87) hide show
  1. agentscope_runtime/common/container_clients/__init__.py +0 -0
  2. agentscope_runtime/{sandbox/manager → common}/container_clients/kubernetes_client.py +546 -6
  3. agentscope_runtime/engine/__init__.py +12 -0
  4. agentscope_runtime/engine/agents/agentscope_agent.py +130 -10
  5. agentscope_runtime/engine/agents/agno_agent.py +8 -10
  6. agentscope_runtime/engine/agents/langgraph_agent.py +52 -9
  7. agentscope_runtime/engine/app/__init__.py +6 -0
  8. agentscope_runtime/engine/app/agent_app.py +239 -0
  9. agentscope_runtime/engine/app/base_app.py +181 -0
  10. agentscope_runtime/engine/app/celery_mixin.py +92 -0
  11. agentscope_runtime/engine/deployers/__init__.py +13 -0
  12. agentscope_runtime/engine/deployers/adapter/responses/__init__.py +0 -0
  13. agentscope_runtime/engine/deployers/adapter/responses/response_api_adapter_utils.py +2890 -0
  14. agentscope_runtime/engine/deployers/adapter/responses/response_api_agent_adapter.py +51 -0
  15. agentscope_runtime/engine/deployers/adapter/responses/response_api_protocol_adapter.py +314 -0
  16. agentscope_runtime/engine/deployers/base.py +1 -0
  17. agentscope_runtime/engine/deployers/cli_fc_deploy.py +203 -0
  18. agentscope_runtime/engine/deployers/kubernetes_deployer.py +272 -0
  19. agentscope_runtime/engine/deployers/local_deployer.py +414 -501
  20. agentscope_runtime/engine/deployers/modelstudio_deployer.py +838 -0
  21. agentscope_runtime/engine/deployers/utils/__init__.py +0 -0
  22. agentscope_runtime/engine/deployers/utils/deployment_modes.py +14 -0
  23. agentscope_runtime/engine/deployers/utils/docker_image_utils/__init__.py +8 -0
  24. agentscope_runtime/engine/deployers/utils/docker_image_utils/docker_image_builder.py +429 -0
  25. agentscope_runtime/engine/deployers/utils/docker_image_utils/dockerfile_generator.py +240 -0
  26. agentscope_runtime/engine/deployers/utils/docker_image_utils/runner_image_factory.py +306 -0
  27. agentscope_runtime/engine/deployers/utils/package_project_utils.py +1163 -0
  28. agentscope_runtime/engine/deployers/utils/service_utils/__init__.py +9 -0
  29. agentscope_runtime/engine/deployers/utils/service_utils/fastapi_factory.py +1064 -0
  30. agentscope_runtime/engine/deployers/utils/service_utils/fastapi_templates.py +157 -0
  31. agentscope_runtime/engine/deployers/utils/service_utils/process_manager.py +268 -0
  32. agentscope_runtime/engine/deployers/utils/service_utils/service_config.py +75 -0
  33. agentscope_runtime/engine/deployers/utils/service_utils/service_factory.py +220 -0
  34. agentscope_runtime/engine/deployers/utils/service_utils/standalone_main.py.j2 +211 -0
  35. agentscope_runtime/engine/deployers/utils/wheel_packager.py +389 -0
  36. agentscope_runtime/engine/helpers/agent_api_builder.py +651 -0
  37. agentscope_runtime/engine/runner.py +76 -35
  38. agentscope_runtime/engine/schemas/agent_schemas.py +112 -2
  39. agentscope_runtime/engine/schemas/embedding.py +37 -0
  40. agentscope_runtime/engine/schemas/modelstudio_llm.py +310 -0
  41. agentscope_runtime/engine/schemas/oai_llm.py +538 -0
  42. agentscope_runtime/engine/schemas/realtime.py +254 -0
  43. agentscope_runtime/engine/services/tablestore_memory_service.py +4 -1
  44. agentscope_runtime/engine/tracing/__init__.py +9 -3
  45. agentscope_runtime/engine/tracing/asyncio_util.py +24 -0
  46. agentscope_runtime/engine/tracing/base.py +66 -34
  47. agentscope_runtime/engine/tracing/local_logging_handler.py +45 -31
  48. agentscope_runtime/engine/tracing/message_util.py +528 -0
  49. agentscope_runtime/engine/tracing/tracing_metric.py +20 -8
  50. agentscope_runtime/engine/tracing/tracing_util.py +130 -0
  51. agentscope_runtime/engine/tracing/wrapper.py +794 -169
  52. agentscope_runtime/sandbox/box/base/base_sandbox.py +2 -1
  53. agentscope_runtime/sandbox/box/browser/browser_sandbox.py +2 -1
  54. agentscope_runtime/sandbox/box/dummy/dummy_sandbox.py +2 -1
  55. agentscope_runtime/sandbox/box/filesystem/filesystem_sandbox.py +2 -1
  56. agentscope_runtime/sandbox/box/gui/gui_sandbox.py +2 -1
  57. agentscope_runtime/sandbox/box/training_box/training_box.py +0 -42
  58. agentscope_runtime/sandbox/client/http_client.py +52 -18
  59. agentscope_runtime/sandbox/constant.py +3 -0
  60. agentscope_runtime/sandbox/custom/custom_sandbox.py +2 -1
  61. agentscope_runtime/sandbox/custom/example.py +2 -1
  62. agentscope_runtime/sandbox/enums.py +0 -1
  63. agentscope_runtime/sandbox/manager/sandbox_manager.py +29 -22
  64. agentscope_runtime/sandbox/model/container.py +6 -0
  65. agentscope_runtime/sandbox/registry.py +1 -1
  66. agentscope_runtime/sandbox/tools/tool.py +4 -0
  67. agentscope_runtime/version.py +1 -1
  68. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/METADATA +103 -59
  69. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/RECORD +87 -52
  70. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/entry_points.txt +1 -0
  71. /agentscope_runtime/{sandbox/manager/container_clients → common}/__init__.py +0 -0
  72. /agentscope_runtime/{sandbox/manager → common}/collections/__init__.py +0 -0
  73. /agentscope_runtime/{sandbox/manager → common}/collections/base_mapping.py +0 -0
  74. /agentscope_runtime/{sandbox/manager → common}/collections/base_queue.py +0 -0
  75. /agentscope_runtime/{sandbox/manager → common}/collections/base_set.py +0 -0
  76. /agentscope_runtime/{sandbox/manager → common}/collections/in_memory_mapping.py +0 -0
  77. /agentscope_runtime/{sandbox/manager → common}/collections/in_memory_queue.py +0 -0
  78. /agentscope_runtime/{sandbox/manager → common}/collections/in_memory_set.py +0 -0
  79. /agentscope_runtime/{sandbox/manager → common}/collections/redis_mapping.py +0 -0
  80. /agentscope_runtime/{sandbox/manager → common}/collections/redis_queue.py +0 -0
  81. /agentscope_runtime/{sandbox/manager → common}/collections/redis_set.py +0 -0
  82. /agentscope_runtime/{sandbox/manager → common}/container_clients/agentrun_client.py +0 -0
  83. /agentscope_runtime/{sandbox/manager → common}/container_clients/base_client.py +0 -0
  84. /agentscope_runtime/{sandbox/manager → common}/container_clients/docker_client.py +0 -0
  85. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/WHEEL +0 -0
  86. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/licenses/LICENSE +0 -0
  87. {agentscope_runtime-0.1.6.dist-info → agentscope_runtime-0.2.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,254 @@
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import uuid
4
+ from enum import Enum
5
+ from typing import Optional, List, Union, Any
6
+
7
+ from openai.types.chat.chat_completion_chunk import ChoiceDeltaToolCall
8
+ from pydantic import BaseModel, model_validator, Field
9
+
10
+
11
+ class AsrVendor(str, Enum):
12
+ MODELSTUDIO = "modelstudio"
13
+ AZURE = "azure"
14
+
15
+
16
+ class TtsVendor(str, Enum):
17
+ MODELSTUDIO = "modelstudio"
18
+ AZURE = "azure"
19
+
20
+
21
+ class ModelstudioConnection(BaseModel):
22
+ base_url: Optional[str] = None
23
+ api_key: Optional[str] = None
24
+ workspace_id: Optional[str] = None
25
+ user_agent: Optional[str] = None
26
+ data_inspection: Optional[str] = None
27
+
28
+
29
+ class TtsConfig(BaseModel):
30
+ model: Optional[str] = None
31
+ voice: Optional[str] = None
32
+ sample_rate: Optional[int] = None
33
+ format: Optional[str] = None
34
+ bits_per_sample: Optional[int] = None
35
+ nb_channels: Optional[int] = None
36
+ chat_id: Optional[str] = None
37
+
38
+
39
+ class ModelstudioTtsConfig(TtsConfig, ModelstudioConnection):
40
+ model: str = "cosyvoice-v2"
41
+ voice: str = os.getenv("TTS_VOICE", "longcheng_v2")
42
+ sample_rate: int = 16000
43
+ format: Optional[str] = "pcm"
44
+
45
+
46
+ class AsrConfig(BaseModel):
47
+ model: Optional[str] = None
48
+ language: Optional[str] = None
49
+ sample_rate: Optional[int] = None
50
+ format: Optional[str] = None
51
+ bits_per_sample: Optional[int] = None
52
+ nb_channels: Optional[int] = None
53
+ initial_silence_timeout: Optional[int] = None
54
+ max_end_silence: Optional[int] = None
55
+ fast_vad_min_duration: Optional[int] = None
56
+ fast_vad_max_duration: Optional[int] = None
57
+
58
+
59
+ class ModelstudioAsrConfig(AsrConfig, ModelstudioConnection):
60
+ model: Optional[str] = "gummy-realtime-v1"
61
+ sample_rate: Optional[int] = 16000
62
+ format: Optional[str] = "pcm"
63
+ max_end_silence: Optional[int] = 700
64
+ fast_vad_min_duration: Optional[int] = 200
65
+ fast_vad_max_duration: Optional[int] = 1100
66
+
67
+
68
+ class ModelstudioKnowledgeBaseConfig(BaseModel):
69
+ index_ids: List[str]
70
+ workspace_id: str
71
+ api_key: str
72
+
73
+
74
+ class ModelstudioVoiceChatUpstream(BaseModel):
75
+ dialog_mode: Optional[str] = "duplex"
76
+ enable_server_vad: Optional[bool] = True
77
+ modalities: Optional[List[str]] = Field(default_factory=lambda: ["audio"])
78
+ asr_vendor: Optional[AsrVendor] = AsrVendor(
79
+ os.getenv("ASR_VENDOR", AsrVendor.MODELSTUDIO.value),
80
+ )
81
+ asr_options: Optional[AsrConfig] = AsrConfig()
82
+
83
+
84
+ class ModelstudioVoiceChatDownstream(BaseModel):
85
+ modalities: Optional[List[str]] = Field(
86
+ default_factory=lambda: ["audio", "text"],
87
+ )
88
+ tts_vendor: Optional[TtsVendor] = TtsVendor(
89
+ os.getenv("TTS_VENDOR", TtsVendor.MODELSTUDIO.value),
90
+ )
91
+ tts_options: Optional[TtsConfig] = TtsConfig()
92
+
93
+
94
+ class ModelstudioVoiceChatParameters(BaseModel):
95
+ modelstudio_kb: Optional[ModelstudioKnowledgeBaseConfig] = None
96
+ enable_tool_call: Optional[bool] = False
97
+
98
+
99
+ class ModelstudioVoiceChatInput(BaseModel):
100
+ dialog_id: Optional[str] = None
101
+ app_id: Optional[str] = None
102
+ text: Optional[str] = None
103
+
104
+
105
+ class ModelstudioVoiceChatDirective(str, Enum):
106
+ SESSION_START = "SessionStart"
107
+ SESSION_STOP = "SessionStop"
108
+
109
+
110
+ class ModelstudioVoiceChatEvent(str, Enum):
111
+ SESSION_STARTED = "SessionStarted"
112
+ SESSION_STOPPED = "SessionStopped"
113
+ AUDIO_TRANSCRIPT = "AudioTranscript"
114
+ RESPONSE_TEXT = "ResponseText"
115
+ RESPONSE_AUDIO_STARTED = "ResponseAudioStarted"
116
+ RESPONSE_AUDIO_ENDED = "ResponseAudioEnded"
117
+
118
+
119
+ class ModelstudioVoiceChatInPayload(BaseModel):
120
+ pass
121
+
122
+
123
+ class ModelstudioVoiceChatSessionStartPayload(ModelstudioVoiceChatInPayload):
124
+ session_id: Optional[str] = Field(
125
+ default_factory=lambda: str(uuid.uuid4()),
126
+ )
127
+ upstream: Optional[
128
+ ModelstudioVoiceChatUpstream
129
+ ] = ModelstudioVoiceChatUpstream()
130
+ downstream: Optional[
131
+ ModelstudioVoiceChatDownstream
132
+ ] = ModelstudioVoiceChatDownstream()
133
+ parameters: Optional[
134
+ ModelstudioVoiceChatParameters
135
+ ] = ModelstudioVoiceChatParameters()
136
+
137
+
138
+ class ModelstudioVoiceChatSessionStopPayload(ModelstudioVoiceChatInPayload):
139
+ pass
140
+
141
+
142
+ class ModelstudioVoiceChatRequest(BaseModel):
143
+ directive: ModelstudioVoiceChatDirective
144
+ payload: Union[
145
+ ModelstudioVoiceChatSessionStartPayload,
146
+ ModelstudioVoiceChatSessionStopPayload,
147
+ ]
148
+
149
+ @model_validator(mode="wrap")
150
+ def parse_payload_based_on_directive(
151
+ self,
152
+ values: Any,
153
+ handler: Any,
154
+ ) -> None:
155
+ data = values if isinstance(values, dict) else values.model_dump()
156
+
157
+ directive = data.get("directive")
158
+ payload_data = data.get("payload", {})
159
+
160
+ if directive == ModelstudioVoiceChatDirective.SESSION_START:
161
+ data["payload"] = ModelstudioVoiceChatSessionStartPayload(
162
+ **payload_data,
163
+ )
164
+ elif directive == ModelstudioVoiceChatDirective.SESSION_STOP:
165
+ data["payload"] = ModelstudioVoiceChatSessionStopPayload(
166
+ **payload_data,
167
+ )
168
+ else:
169
+ raise ValueError(f"Unsupported directive: {directive}")
170
+
171
+ return handler(data)
172
+
173
+
174
+ class ModelstudioVoiceChatOutPayload(BaseModel):
175
+ session_id: Optional[str] = None
176
+
177
+
178
+ class ModelstudioVoiceChatSessionStartedPayload(
179
+ ModelstudioVoiceChatOutPayload,
180
+ ):
181
+ pass
182
+
183
+
184
+ class ModelstudioVoiceChatSessionStoppedPayload(
185
+ ModelstudioVoiceChatOutPayload,
186
+ ):
187
+ pass
188
+
189
+
190
+ class ModelstudioVoiceChatAudioTranscriptPayload(
191
+ ModelstudioVoiceChatOutPayload,
192
+ ):
193
+ text: Optional[str] = ""
194
+ finished: bool
195
+
196
+
197
+ class ModelstudioVoiceChatResponseTextPayload(
198
+ ModelstudioVoiceChatOutPayload,
199
+ ):
200
+ text: Optional[str] = ""
201
+ tool_calls: Optional[List[ChoiceDeltaToolCall]] = Field(
202
+ default_factory=list,
203
+ )
204
+ finished: bool
205
+
206
+
207
+ class ModelstudioVoiceChatResponseAudioStartedPayload(
208
+ ModelstudioVoiceChatOutPayload,
209
+ ):
210
+ pass
211
+
212
+
213
+ class ModelstudioVoiceChatResponseAudioStoppedPayload(
214
+ ModelstudioVoiceChatOutPayload,
215
+ ):
216
+ pass
217
+
218
+
219
+ class ModelstudioVoiceChatResponse(BaseModel):
220
+ event: Optional[ModelstudioVoiceChatEvent]
221
+ payload: Union[
222
+ ModelstudioVoiceChatSessionStartedPayload,
223
+ ModelstudioVoiceChatSessionStoppedPayload,
224
+ ModelstudioVoiceChatAudioTranscriptPayload,
225
+ ModelstudioVoiceChatResponseTextPayload,
226
+ ModelstudioVoiceChatResponseAudioStartedPayload,
227
+ ModelstudioVoiceChatResponseAudioStoppedPayload,
228
+ ]
229
+
230
+
231
+ class AzureConnection(BaseModel):
232
+ key: Optional[str] = None
233
+ region: Optional[str] = None
234
+
235
+
236
+ class AzureAsrConfig(AsrConfig, AzureConnection):
237
+ sample_rate: Optional[int] = 16000
238
+ format: Optional[str] = "pcm"
239
+ bits_per_sample: Optional[int] = 16
240
+ nb_channels: Optional[int] = 1
241
+ initial_silence_timeout: Optional[int] = 5000
242
+ max_end_silence: Optional[int] = 800
243
+ language: Optional[str] = os.getenv("ASR_LANG", "en-US")
244
+
245
+
246
+ class AzureTtsConfig(TtsConfig, AzureConnection):
247
+ voice: Optional[str] = os.getenv(
248
+ "TTS_VOICE",
249
+ "en-US-AvaMultilingualNeural",
250
+ )
251
+ sample_rate: Optional[int] = 16000
252
+ format: Optional[str] = "pcm"
253
+ bits_per_sample: Optional[int] = 16
254
+ nb_channels: Optional[int] = 1
@@ -51,7 +51,7 @@ class TablestoreMemoryService(MemoryService):
51
51
  self,
52
52
  tablestore_client: AsyncTablestoreClient,
53
53
  search_strategy: SearchStrategy = SearchStrategy.FULL_TEXT,
54
- embedding_model: Optional[Embeddings] = DashScopeEmbeddings(),
54
+ embedding_model: Optional[Embeddings] = None,
55
55
  vector_dimension: int = 1536,
56
56
  table_name: Optional[str] = "agentscope_runtime_memory",
57
57
  search_index_schema: Optional[List[tablestore.FieldSchema]] = (
@@ -63,6 +63,9 @@ class TablestoreMemoryService(MemoryService):
63
63
  vector_metric_type: VectorMetricType = VectorMetricType.VM_COSINE,
64
64
  **kwargs: Any,
65
65
  ):
66
+ if embedding_model is None:
67
+ embedding_model = DashScopeEmbeddings()
68
+
66
69
  self._search_strategy = search_strategy
67
70
  self._embedding_model = (
68
71
  embedding_model # the parameter is None, don't store vector.
@@ -3,6 +3,14 @@ from typing import Any, List, Union
3
3
 
4
4
  from .base import BaseLogHandler, Tracer, TracerHandler
5
5
  from .tracing_metric import TraceType
6
+ from .tracing_util import TracingUtil
7
+ from .wrapper import trace
8
+
9
+ __all__ = [
10
+ "trace",
11
+ "TraceType",
12
+ "TracingUtil",
13
+ ]
6
14
 
7
15
 
8
16
  def create_handler(
@@ -15,9 +23,7 @@ def create_handler(
15
23
  if "default" in eval_mode:
16
24
  handlers.append(BaseLogHandler())
17
25
  elif "local_logging" in eval_mode:
18
- from .local_logging_handler import (
19
- LocalLogHandler,
20
- )
26
+ from .local_logging_handler import LocalLogHandler
21
27
 
22
28
  handlers.append(LocalLogHandler(**eval_params))
23
29
  return handlers
@@ -0,0 +1,24 @@
1
+ # -*- coding: utf-8 -*-
2
+ from typing import AsyncIterable, AsyncIterator, Tuple, TypeVar
3
+
4
+ T_co = TypeVar("T_co", covariant=True)
5
+
6
+
7
+ async def aenumerate(
8
+ asequence: AsyncIterable[T_co],
9
+ start: int = 0,
10
+ ) -> AsyncIterator[Tuple[int, T_co]]:
11
+ """Asynchronously enumerate an async iterator from a given start value.
12
+
13
+ Args:
14
+ asequence (AsyncIterable[T_co]): The async iterable to enumerate.
15
+ start (int): The starting value for enumeration. Defaults to 0.
16
+
17
+ Yields:
18
+ Tuple[int, T_co]: A tuple containing the index and the item from the
19
+ async iterable.
20
+ """
21
+ n = start
22
+ async for elem in asequence:
23
+ yield n, elem
24
+ n += 1
@@ -1,12 +1,12 @@
1
1
  # -*- coding: utf-8 -*-
2
- # pylint: disable=protected-access
3
2
  import time
4
3
  import traceback
5
4
  from abc import ABC, abstractmethod
6
5
  from contextlib import contextmanager
7
6
  from typing import Any, Dict, List
8
7
 
9
- from .tracing_metric import TraceType
8
+ from opentelemetry.propagate import inject, extract
9
+ from opentelemetry.context.context import Context
10
10
 
11
11
 
12
12
  # Handler Interface
@@ -16,22 +16,23 @@ class TracerHandler(ABC):
16
16
  @abstractmethod
17
17
  def on_start(
18
18
  self,
19
- event_type: TraceType,
19
+ event_name: str,
20
20
  payload: Dict[str, Any],
21
21
  **kwargs: Any,
22
22
  ) -> None:
23
23
  """Handle the start of a trace event.
24
24
 
25
25
  Args:
26
- event_type (TraceType): The type of event being traced.
26
+ event_name (str): The name of event being traced.
27
27
  payload (Dict[str, Any]): The payload data for the event.
28
28
  **kwargs (Any): Additional keyword arguments.
29
29
  """
30
+ raise NotImplementedError("Subclasses must implement on_start method")
30
31
 
31
32
  @abstractmethod
32
33
  def on_end(
33
34
  self,
34
- event_type: TraceType,
35
+ event_name: str,
35
36
  start_payload: Dict[str, Any],
36
37
  end_payload: Dict[str, Any],
37
38
  start_time: float,
@@ -40,12 +41,13 @@ class TracerHandler(ABC):
40
41
  """Handle the end of a trace event.
41
42
 
42
43
  Args:
43
- event_type (TraceType): The type of event being traced.
44
+ event_name (str): The name of event being traced.
44
45
  start_payload (Dict[str, Any]): The payload data from event start.
45
46
  end_payload (Dict[str, Any]): The payload data from event end.
46
47
  start_time (float): The timestamp when the event started.
47
48
  **kwargs (Any): Additional keyword arguments.
48
49
  """
50
+ raise NotImplementedError("Subclasses must implement on_end method")
49
51
 
50
52
  @abstractmethod
51
53
  def on_log(self, message: str, **kwargs: Any) -> None:
@@ -55,11 +57,12 @@ class TracerHandler(ABC):
55
57
  message (str): The log message.
56
58
  **kwargs (Any): Additional keyword arguments.
57
59
  """
60
+ raise NotImplementedError("Subclasses must implement on_log method")
58
61
 
59
62
  @abstractmethod
60
63
  def on_error(
61
64
  self,
62
- event_type: TraceType,
65
+ event_name: str,
63
66
  start_payload: Dict[str, Any],
64
67
  error: Exception,
65
68
  start_time: float,
@@ -69,15 +72,17 @@ class TracerHandler(ABC):
69
72
  """Handle an error during tracing.
70
73
 
71
74
  Args:
72
- event_type (TraceType): The type of event being traced.
75
+ event_name (str): The type of event being traced.
73
76
  start_payload (Dict[str, Any]): The payload data from event start.
74
77
  error (Exception): The exception that occurred.
75
78
  start_time (float): The timestamp when the event started.
76
79
  traceback_info (str): The traceback information.
77
80
  **kwargs (Any): Additional keyword arguments.
78
81
  """
82
+ raise NotImplementedError("Subclasses must implement on_error method")
79
83
 
80
84
 
85
+ # 新增基础的LogHandler类
81
86
  class BaseLogHandler(TracerHandler):
82
87
  """Basic log handler implementation using Python's logging module."""
83
88
 
@@ -87,22 +92,22 @@ class BaseLogHandler(TracerHandler):
87
92
 
88
93
  def on_start(
89
94
  self,
90
- event_type: TraceType,
95
+ event_name: str,
91
96
  payload: Dict[str, Any],
92
97
  **kwargs: Any,
93
98
  ) -> None:
94
99
  """Log the start of a trace event.
95
100
 
96
101
  Args:
97
- event_type (TraceType): The type of event being traced.
102
+ event_name (str): The name of event being traced.
98
103
  payload (Dict[str, Any]): The payload data for the event.
99
104
  **kwargs (Any): Additional keyword arguments.
100
105
  """
101
- self.logger.info(f"Event {event_type} started with payload: {payload}")
106
+ self.logger.info(f"Event {event_name} started with payload: {payload}")
102
107
 
103
108
  def on_end(
104
109
  self,
105
- event_type: TraceType,
110
+ event_name: str,
106
111
  start_payload: Dict[str, Any],
107
112
  end_payload: Dict[str, Any],
108
113
  start_time: float,
@@ -111,14 +116,14 @@ class BaseLogHandler(TracerHandler):
111
116
  """Log the end of a trace event.
112
117
 
113
118
  Args:
114
- event_type (TraceType): The type of event being traced.
119
+ event_name (str): The name of event being traced.
115
120
  start_payload (Dict[str, Any]): The payload data from event start.
116
121
  end_payload (Dict[str, Any]): The payload data from event end.
117
122
  start_time (float): The timestamp when the event started.
118
123
  **kwargs (Any): Additional keyword arguments.
119
124
  """
120
125
  self.logger.info(
121
- f"Event {event_type} ended with start payload: {start_payload}, "
126
+ f"Event {event_name} ended with start payload: {start_payload}, "
122
127
  f"end payload: {end_payload}, duration: "
123
128
  f"{time.time() - start_time} seconds, kwargs: {kwargs}",
124
129
  )
@@ -130,12 +135,11 @@ class BaseLogHandler(TracerHandler):
130
135
  message (str): The log message.
131
136
  **kwargs (Any): Additional keyword arguments.
132
137
  """
133
- if message:
134
- self.logger.info(f"Log: {message}")
138
+ self.logger.info(f"Log: {message}")
135
139
 
136
140
  def on_error(
137
141
  self,
138
- event_type: TraceType,
142
+ event_name: str,
139
143
  start_payload: Dict[str, Any],
140
144
  error: Exception,
141
145
  start_time: float,
@@ -145,7 +149,7 @@ class BaseLogHandler(TracerHandler):
145
149
  """Log an error during tracing.
146
150
 
147
151
  Args:
148
- event_type (TraceType): The type of event being traced.
152
+ event_name (str): The name of event being traced.
149
153
  start_payload (Dict[str, Any]): The payload data from event start.
150
154
  error (Exception): The exception that occurred.
151
155
  start_time (float): The timestamp when the event started.
@@ -153,7 +157,7 @@ class BaseLogHandler(TracerHandler):
153
157
  **kwargs (Any): Additional keyword arguments.
154
158
  """
155
159
  self.logger.error(
156
- f"Error in event {event_type} with payload: {start_payload}, "
160
+ f"Error in event {event_name} with payload: {start_payload}, "
157
161
  f"error: {error}, "
158
162
  f"traceback: {traceback_info}, duration: "
159
163
  f"{time.time() - start_time} seconds, kwargs: {kwargs}",
@@ -184,14 +188,16 @@ class Tracer:
184
188
  @contextmanager
185
189
  def event(
186
190
  self,
187
- event_type: TraceType,
191
+ span: Any,
192
+ event_name: str,
188
193
  payload: Dict[str, Any],
189
194
  **kwargs: Any,
190
195
  ) -> Any:
191
196
  """Create a context manager for tracing an event.
192
197
 
193
198
  Args:
194
- event_type (TraceType): The type of event being traced.
199
+ span(Any): span of event
200
+ event_name (str): The name of event being traced.
195
201
  payload (Dict[str, Any]): The payload data for the event.
196
202
  **kwargs (Any): Additional keyword arguments.
197
203
 
@@ -201,28 +207,35 @@ class Tracer:
201
207
  start_time = time.time()
202
208
 
203
209
  for handle in self.handlers:
204
- handle.on_start(event_type, payload, **kwargs)
210
+ handle.on_start(
211
+ event_name,
212
+ payload,
213
+ **kwargs,
214
+ )
205
215
 
206
216
  event_context = EventContext(
217
+ span,
207
218
  self.handlers,
208
- event_type,
219
+ event_name,
209
220
  start_time,
210
221
  payload,
211
222
  )
223
+
212
224
  try:
213
225
  yield event_context
214
226
  except Exception as e:
215
227
  traceback_info = traceback.format_exc()
216
228
  for handle in self.handlers:
217
229
  handle.on_error(
218
- event_type,
230
+ event_name,
219
231
  payload,
220
232
  e,
221
233
  start_time,
222
234
  traceback_info=traceback_info,
223
235
  )
224
236
  raise
225
- event_context._end(payload)
237
+
238
+ event_context.finalize(payload)
226
239
 
227
240
  def log(self, message: str, **kwargs: Any) -> None:
228
241
  """Log a message using all registered handlers.
@@ -240,8 +253,9 @@ class EventContext:
240
253
 
241
254
  def __init__(
242
255
  self,
256
+ span: Any,
243
257
  handlers: List[TracerHandler],
244
- event_type: TraceType,
258
+ event_name: str,
245
259
  start_time: float,
246
260
  start_payload: Dict[str, Any],
247
261
  ) -> None:
@@ -250,12 +264,13 @@ class EventContext:
250
264
  Args:
251
265
  handlers (List[TracerHandler]): List of handlers to process
252
266
  trace events.
253
- event_type (TraceType): The type of event being traced.
267
+ event_name (str): The name of event being traced.
254
268
  start_time (float): The timestamp when the event started.
255
269
  start_payload (Dict[str, Any]): The payload data from event start.
256
270
  """
271
+ self.span = span
257
272
  self.handlers = handlers
258
- self.event_type = event_type
273
+ self.event_name = event_name
259
274
  self.start_time = start_time
260
275
  self.start_payload = start_payload
261
276
  self.end_payload = {}
@@ -278,12 +293,21 @@ class EventContext:
278
293
  message (str): The log message.
279
294
  **kwargs (Any): Additional keyword arguments.
280
295
  """
281
- kwargs["event_type"] = self.event_type
296
+ kwargs["event_name"] = self.event_name
282
297
  kwargs["start_time"] = self.start_time
283
298
  kwargs["start_payload"] = self.start_payload
284
299
  for handle in self.handlers:
285
300
  handle.on_log(message, **kwargs)
286
301
 
302
+ def finalize(self, start_payload: Dict[str, Any] = None) -> None:
303
+ """Public method to finalize the event.
304
+
305
+ Args:
306
+ start_payload (Dict[str, Any], optional): The payload data from
307
+ event start.
308
+ """
309
+ self._end(start_payload)
310
+
287
311
  def _end(self, start_payload: Dict[str, Any] = None) -> None:
288
312
  """Finalize the event by calling on_end for all handlers.
289
313
 
@@ -293,17 +317,25 @@ class EventContext:
293
317
  """
294
318
  for handle in self.handlers:
295
319
  handle.on_end(
296
- self.event_type,
320
+ self.event_name,
297
321
  start_payload,
298
322
  self.end_payload,
299
323
  self.start_time,
300
324
  **self.kwargs,
301
325
  )
302
326
 
303
- def set_trace_header(self, trace_header: Dict[str, Any]) -> None:
304
- """Set trace header for compatible handlers.
327
+ def set_attribute(self, key: str, value: Any) -> None:
328
+ """Set attribute for the current span.
305
329
 
306
330
  Args:
307
- trace_header (Dict[str, Any]): The trace header information.
331
+ key (str): key of attribute
332
+ value(str): value of attribute
308
333
  """
309
- # TODO: Implement this
334
+
335
+ self.span.set_attribute(key, value)
336
+
337
+ def get_trace_context(self) -> Context:
338
+ carrier = {}
339
+ inject(carrier)
340
+ context = extract(carrier)
341
+ return context