kikocis/llama-stack public
Changesets · Branches · Tags · Compare
| Changeset | b2b1c7375a992949aa51b7b1fb8fa8f06364189db0850b3ceb69672f29c08d34 |
|---|---|
| Author | Ashwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-11 14:25 -07:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-11 14:25 -07:00 |
| Parents | ee73715955cc |
15 files changed
modified llama_toolchain/agentic_system/providers.py +1 −1
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | from llama_toolchain.core.datatypes import Api, InlineProviderSpec, ProviderSpec |
| 10 | 10 | |
| 11 | 11 | |
| 12 | -def available_agentic_system_providers() -> List[ProviderSpec]: | |
| 12 | +def available_providers() -> List[ProviderSpec]: | |
| 13 | 13 | return [ |
| 14 | 14 | InlineProviderSpec( |
| 15 | 15 | api=Api.agentic_system, |
modified llama_toolchain/core/datatypes.py +1 −0
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | safety = "safety" |
| 20 | 20 | agentic_system = "agentic_system" |
| 21 | 21 | memory = "memory" |
| 22 | + telemetry = "telemetry" | |
| 22 | 23 | |
| 23 | 24 | |
| 24 | 25 | @json_schema_type |
modified llama_toolchain/core/distribution.py +12 −20
| @@ -4,17 +4,15 @@ | ||
| 4 | 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | +import importlib | |
| 7 | 8 | import inspect |
| 8 | 9 | from typing import Dict, List |
| 9 | 10 | |
| 10 | 11 | from llama_toolchain.agentic_system.api import AgenticSystem |
| 11 | -from llama_toolchain.agentic_system.providers import available_agentic_system_providers | |
| 12 | 12 | from llama_toolchain.inference.api import Inference |
| 13 | -from llama_toolchain.inference.providers import available_inference_providers | |
| 14 | 13 | from llama_toolchain.memory.api import Memory |
| 15 | -from llama_toolchain.memory.providers import available_memory_providers | |
| 16 | 14 | from llama_toolchain.safety.api import Safety |
| 17 | -from llama_toolchain.safety.providers import available_safety_providers | |
| 15 | +from llama_toolchain.telemetry.api import Telemetry | |
| 18 | 16 | |
| 19 | 17 | from .datatypes import ( |
| 20 | 18 | Api, |
| @@ -44,7 +42,7 @@ | ||
| 44 | 42 | |
| 45 | 43 | |
| 46 | 44 | def stack_apis() -> List[Api]: |
| 47 | - return [Api.inference, Api.safety, Api.agentic_system, Api.memory] | |
| 45 | + return [v for v in Api] | |
| 48 | 46 | |
| 49 | 47 | |
| 50 | 48 | def api_endpoints() -> Dict[Api, List[ApiEndpoint]]: |
| @@ -55,6 +53,7 @@ | ||
| 55 | 53 | Api.safety: Safety, |
| 56 | 54 | Api.agentic_system: AgenticSystem, |
| 57 | 55 | Api.memory: Memory, |
| 56 | + Api.telemetry: Telemetry, | |
| 58 | 57 | } |
| 59 | 58 | |
| 60 | 59 | for api, protocol in protocols.items(): |
| @@ -82,20 +81,13 @@ | ||
| 82 | 81 | |
| 83 | 82 | |
| 84 | 83 | def api_providers() -> Dict[Api, Dict[str, ProviderSpec]]: |
| 85 | - inference_providers_by_id = { | |
| 86 | - a.provider_type: a for a in available_inference_providers() | |
| 87 | - } | |
| 88 | - safety_providers_by_id = {a.provider_type: a for a in available_safety_providers()} | |
| 89 | - agentic_system_providers_by_id = { | |
| 90 | - a.provider_type: a for a in available_agentic_system_providers() | |
| 91 | - } | |
| 84 | + ret = {} | |
| 85 | + for api in stack_apis(): | |
| 86 | + name = api.name.lower() | |
| 87 | + module = importlib.import_module(f"llama_toolchain.{name}.providers") | |
| 88 | + ret[api] = { | |
| 89 | + "remote": remote_provider_spec(api), | |
| 90 | + **{a.provider_type: a for a in module.available_providers()}, | |
| 91 | + } | |
| 92 | 92 | |
| 93 | - ret = { | |
| 94 | - Api.inference: inference_providers_by_id, | |
| 95 | - Api.safety: safety_providers_by_id, | |
| 96 | - Api.agentic_system: agentic_system_providers_by_id, | |
| 97 | - Api.memory: {a.provider_type: a for a in available_memory_providers()}, | |
| 98 | - } | |
| 99 | - for k, v in ret.items(): | |
| 100 | - v["remote"] = remote_provider_spec(k) | |
| 101 | 93 | return ret |
modified llama_toolchain/core/distribution_registry.py +8 −1
| @@ -21,12 +21,16 @@ | ||
| 21 | 21 | Api.memory: "meta-reference-faiss", |
| 22 | 22 | Api.safety: "meta-reference", |
| 23 | 23 | Api.agentic_system: "meta-reference", |
| 24 | + Api.telemetry: "console", | |
| 24 | 25 | }, |
| 25 | 26 | ), |
| 26 | 27 | DistributionSpec( |
| 27 | 28 | distribution_type="remote", |
| 28 | 29 | description="Point to remote services for all llama stack APIs", |
| 29 | - providers={x: "remote" for x in Api}, | |
| 30 | + providers={ | |
| 31 | + **{x: "remote" for x in Api}, | |
| 32 | + Api.telemetry: "console", | |
| 33 | + }, | |
| 30 | 34 | ), |
| 31 | 35 | DistributionSpec( |
| 32 | 36 | distribution_type="local-ollama", |
| @@ -36,6 +40,7 @@ | ||
| 36 | 40 | Api.safety: "meta-reference", |
| 37 | 41 | Api.agentic_system: "meta-reference", |
| 38 | 42 | Api.memory: "meta-reference-faiss", |
| 43 | + Api.telemetry: "console", | |
| 39 | 44 | }, |
| 40 | 45 | ), |
| 41 | 46 | DistributionSpec( |
| @@ -46,6 +51,7 @@ | ||
| 46 | 51 | Api.safety: "meta-reference", |
| 47 | 52 | Api.agentic_system: "meta-reference", |
| 48 | 53 | Api.memory: "meta-reference-faiss", |
| 54 | + Api.telemetry: "console", | |
| 49 | 55 | }, |
| 50 | 56 | ), |
| 51 | 57 | DistributionSpec( |
| @@ -56,6 +62,7 @@ | ||
| 56 | 62 | Api.safety: "meta-reference", |
| 57 | 63 | Api.agentic_system: "meta-reference", |
| 58 | 64 | Api.memory: "meta-reference-faiss", |
| 65 | + Api.telemetry: "console", | |
| 59 | 66 | }, |
| 60 | 67 | ), |
| 61 | 68 | ] |
modified llama_toolchain/core/server.py +28 −1
| @@ -38,6 +38,13 @@ | ||
| 38 | 38 | from termcolor import cprint |
| 39 | 39 | from typing_extensions import Annotated |
| 40 | 40 | |
| 41 | +from llama_toolchain.telemetry.tracing import ( | |
| 42 | + end_trace, | |
| 43 | + setup_logger, | |
| 44 | + SpanStatus, | |
| 45 | + start_trace, | |
| 46 | +) | |
| 47 | + | |
| 41 | 48 | from .datatypes import Api, InlineProviderSpec, ProviderSpec, RemoteProviderSpec |
| 42 | 49 | from .distribution import api_endpoints, api_providers |
| 43 | 50 | from .dynamic import instantiate_provider |
| @@ -88,6 +95,8 @@ | ||
| 88 | 95 | downstream_url: str, |
| 89 | 96 | downstream_headers: Optional[Dict[str, str]] = None, |
| 90 | 97 | ): |
| 98 | + await start_trace(request.path, {"downstream_url": downstream_url}) | |
| 99 | + | |
| 91 | 100 | headers = dict(request.headers) |
| 92 | 101 | headers.pop("host", None) |
| 93 | 102 | headers.update(downstream_headers or {}) |
| @@ -95,6 +104,7 @@ | ||
| 95 | 104 | content = await request.body() |
| 96 | 105 | |
| 97 | 106 | client = httpx.AsyncClient() |
| 107 | + erred = False | |
| 98 | 108 | try: |
| 99 | 109 | req = client.build_request( |
| 100 | 110 | method=request.method, |
| @@ -120,17 +130,25 @@ | ||
| 120 | 130 | ) |
| 121 | 131 | |
| 122 | 132 | except httpx.ReadTimeout: |
| 133 | + erred = True | |
| 123 | 134 | return Response(content="Downstream server timed out", status_code=504) |
| 124 | 135 | except httpx.NetworkError as e: |
| 136 | + erred = True | |
| 125 | 137 | return Response(content=f"Network error: {str(e)}", status_code=502) |
| 126 | 138 | except httpx.TooManyRedirects: |
| 139 | + erred = True | |
| 127 | 140 | return Response(content="Too many redirects", status_code=502) |
| 128 | 141 | except SSLError as e: |
| 142 | + erred = True | |
| 129 | 143 | return Response(content=f"SSL error: {str(e)}", status_code=502) |
| 130 | 144 | except httpx.HTTPStatusError as e: |
| 145 | + erred = True | |
| 131 | 146 | return Response(content=str(e), status_code=e.response.status_code) |
| 132 | 147 | except Exception as e: |
| 148 | + erred = True | |
| 133 | 149 | return Response(content=f"Unexpected error: {str(e)}", status_code=500) |
| 150 | + finally: | |
| 151 | + await end_trace(SpanStatus.OK if not erred else SpanStatus.ERROR) | |
| 134 | 152 | |
| 135 | 153 | |
| 136 | 154 | def handle_sigint(*args, **kwargs): |
| @@ -159,7 +177,7 @@ | ||
| 159 | 177 | |
| 160 | 178 | def create_dynamic_typed_route(func: Any, method: str): |
| 161 | 179 | hints = get_type_hints(func) |
| 162 | - response_model = hints["return"] | |
| 180 | + response_model = hints.get("return") | |
| 163 | 181 | |
| 164 | 182 | # NOTE: I think it is better to just add a method within each Api |
| 165 | 183 | # "Protocol" / adapter-impl to tell what sort of a response this request |
| @@ -170,6 +188,8 @@ | ||
| 170 | 188 | if is_streaming: |
| 171 | 189 | |
| 172 | 190 | async def endpoint(**kwargs): |
| 191 | + await start_trace(func.__name__) | |
| 192 | + | |
| 173 | 193 | async def sse_generator(event_gen): |
| 174 | 194 | try: |
| 175 | 195 | async for item in event_gen: |
| @@ -187,6 +207,8 @@ | ||
| 187 | 207 | }, |
| 188 | 208 | } |
| 189 | 209 | ) |
| 210 | + finally: | |
| 211 | + await end_trace() | |
| 190 | 212 | |
| 191 | 213 | return StreamingResponse( |
| 192 | 214 | sse_generator(func(**kwargs)), media_type="text/event-stream" |
| @@ -195,6 +217,7 @@ | ||
| 195 | 217 | else: |
| 196 | 218 | |
| 197 | 219 | async def endpoint(**kwargs): |
| 220 | + await start_trace(func.__name__) | |
| 198 | 221 | try: |
| 199 | 222 | return ( |
| 200 | 223 | await func(**kwargs) |
| @@ -204,6 +227,8 @@ | ||
| 204 | 227 | except Exception as e: |
| 205 | 228 | traceback.print_exception(e) |
| 206 | 229 | raise translate_exception(e) from e |
| 230 | + finally: | |
| 231 | + await end_trace() | |
| 207 | 232 | |
| 208 | 233 | sig = inspect.signature(func) |
| 209 | 234 | if method == "post": |
| @@ -293,6 +318,8 @@ | ||
| 293 | 318 | provider_specs[api] = providers[provider_type] |
| 294 | 319 | |
| 295 | 320 | impls = resolve_impls(provider_specs, config) |
| 321 | + if Api.telemetry in impls: | |
| 322 | + setup_logger(impls[Api.telemetry]) | |
| 296 | 323 | |
| 297 | 324 | for provider_spec in provider_specs.values(): |
| 298 | 325 | api = provider_spec.api |
modified llama_toolchain/inference/providers.py +1 −1
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | from llama_toolchain.core.datatypes import * # noqa: F403 |
| 10 | 10 | |
| 11 | 11 | |
| 12 | -def available_inference_providers() -> List[ProviderSpec]: | |
| 12 | +def available_providers() -> List[ProviderSpec]: | |
| 13 | 13 | return [ |
| 14 | 14 | InlineProviderSpec( |
| 15 | 15 | api=Api.inference, |
modified llama_toolchain/memory/meta_reference/faiss/faiss.py +6 −1
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | # This source code is licensed under the terms described in the LICENSE file in |
| 5 | 5 | # the root directory of this source tree. |
| 6 | 6 | |
| 7 | +import logging | |
| 7 | 8 | import uuid |
| 8 | 9 | |
| 9 | 10 | from typing import Any, Dict, List, Optional |
| @@ -20,8 +21,11 @@ | ||
| 20 | 21 | BankWithIndex, |
| 21 | 22 | EmbeddingIndex, |
| 22 | 23 | ) |
| 24 | +from llama_toolchain.telemetry import tracing | |
| 23 | 25 | from .config import FaissImplConfig |
| 24 | 26 | |
| 27 | +logger = logging.getLogger(__name__) | |
| 28 | + | |
| 25 | 29 | |
| 26 | 30 | class FaissIndex(EmbeddingIndex): |
| 27 | 31 | id_by_index: Dict[int, str] |
| @@ -32,11 +36,12 @@ | ||
| 32 | 36 | self.id_by_index = {} |
| 33 | 37 | self.chunk_by_index = {} |
| 34 | 38 | |
| 39 | + @tracing.span(name="add_chunks") | |
| 35 | 40 | async def add_chunks(self, chunks: List[Chunk], embeddings: NDArray): |
| 36 | 41 | indexlen = len(self.id_by_index) |
| 37 | 42 | for i, chunk in enumerate(chunks): |
| 38 | 43 | self.chunk_by_index[indexlen + i] = chunk |
| 39 | - print(f"Adding chunk #{indexlen + i} tokens={chunk.token_count}") | |
| 44 | + logger.info(f"Adding chunk #{indexlen + i} tokens={chunk.token_count}") | |
| 40 | 45 | self.id_by_index[indexlen + i] = chunk.document_id |
| 41 | 46 | |
| 42 | 47 | self.index.add(np.array(embeddings).astype(np.float32)) |
modified llama_toolchain/memory/providers.py +1 −1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | ] |
| 15 | 15 | |
| 16 | 16 | |
| 17 | -def available_memory_providers() -> List[ProviderSpec]: | |
| 17 | +def available_providers() -> List[ProviderSpec]: | |
| 18 | 18 | return [ |
| 19 | 19 | InlineProviderSpec( |
| 20 | 20 | api=Api.memory, |
modified llama_toolchain/safety/providers.py +1 −1
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | from llama_toolchain.core.datatypes import Api, InlineProviderSpec, ProviderSpec |
| 10 | 10 | |
| 11 | 11 | |
| 12 | -def available_safety_providers() -> List[ProviderSpec]: | |
| 12 | +def available_providers() -> List[ProviderSpec]: | |
| 13 | 13 | return [ |
| 14 | 14 | InlineProviderSpec( |
| 15 | 15 | api=Api.safety, |
modified llama_toolchain/telemetry/api/api.py +78 −122
| @@ -6,170 +6,126 @@ | ||
| 6 | 6 | |
| 7 | 7 | from datetime import datetime |
| 8 | 8 | from enum import Enum |
| 9 | - | |
| 10 | -from typing import Any, Dict, List, Optional, Protocol, Union | |
| 9 | +from typing import Any, Dict, Literal, Optional, Protocol, Union | |
| 11 | 10 | |
| 12 | 11 | from llama_models.schema_utils import json_schema_type, webmethod |
| 13 | - | |
| 14 | -from pydantic import BaseModel | |
| 15 | - | |
| 16 | - | |
| 17 | -@json_schema_type | |
| 18 | -class ExperimentStatus(Enum): | |
| 19 | - NOT_STARTED = "not_started" | |
| 20 | - RUNNING = "running" | |
| 21 | - COMPLETED = "completed" | |
| 22 | - FAILED = "failed" | |
| 23 | - | |
| 24 | - | |
| 25 | -@json_schema_type | |
| 26 | -class Experiment(BaseModel): | |
| 27 | - id: str | |
| 28 | - name: str | |
| 29 | - status: ExperimentStatus | |
| 30 | - created_at: datetime | |
| 31 | - updated_at: datetime | |
| 32 | - metadata: Dict[str, Any] | |
| 12 | +from pydantic import BaseModel, Field | |
| 13 | +from typing_extensions import Annotated | |
| 33 | 14 | |
| 34 | 15 | |
| 35 | 16 | @json_schema_type |
| 36 | -class Run(BaseModel): | |
| 37 | - id: str | |
| 38 | - experiment_id: str | |
| 39 | - status: str | |
| 40 | - started_at: datetime | |
| 41 | - ended_at: Optional[datetime] | |
| 42 | - metadata: Dict[str, Any] | |
| 17 | +class SpanStatus(Enum): | |
| 18 | + OK = "ok" | |
| 19 | + ERROR = "error" | |
| 43 | 20 | |
| 44 | 21 | |
| 45 | 22 | @json_schema_type |
| 46 | -class Metric(BaseModel): | |
| 23 | +class Span(BaseModel): | |
| 24 | + span_id: str | |
| 25 | + trace_id: str | |
| 26 | + parent_span_id: Optional[str] = None | |
| 47 | 27 | name: str |
| 48 | - value: Union[float, int, str, bool] | |
| 49 | - timestamp: datetime | |
| 50 | - run_id: str | |
| 28 | + start_time: datetime | |
| 29 | + end_time: Optional[datetime] = None | |
| 30 | + attributes: Optional[Dict[str, Any]] = Field(default_factory=dict) | |
| 51 | 31 | |
| 52 | 32 | |
| 53 | 33 | @json_schema_type |
| 54 | -class Log(BaseModel): | |
| 55 | - message: str | |
| 56 | - level: str | |
| 57 | - timestamp: datetime | |
| 58 | - additional_info: Dict[str, Any] | |
| 34 | +class Trace(BaseModel): | |
| 35 | + trace_id: str | |
| 36 | + root_span_id: str | |
| 37 | + start_time: datetime | |
| 38 | + end_time: Optional[datetime] = None | |
| 59 | 39 | |
| 60 | 40 | |
| 61 | 41 | @json_schema_type |
| 62 | -class ArtifactType(Enum): | |
| 63 | - MODEL = "model" | |
| 64 | - DATASET = "dataset" | |
| 65 | - CHECKPOINT = "checkpoint" | |
| 66 | - PLOT = "plot" | |
| 42 | +class EventType(Enum): | |
| 43 | + UNSTRUCTURED_LOG = "unstructured_log" | |
| 44 | + STRUCTURED_LOG = "structured_log" | |
| 67 | 45 | METRIC = "metric" |
| 68 | - CONFIG = "config" | |
| 69 | - CODE = "code" | |
| 70 | - OTHER = "other" | |
| 71 | - | |
| 72 | - | |
| 73 | -@json_schema_type | |
| 74 | -class Artifact(BaseModel): | |
| 75 | - id: str | |
| 76 | - name: str | |
| 77 | - type: ArtifactType | |
| 78 | - size: int | |
| 79 | - created_at: datetime | |
| 80 | - metadata: Dict[str, Any] | |
| 81 | 46 | |
| 82 | 47 | |
| 83 | 48 | @json_schema_type |
| 84 | -class CreateExperimentRequest(BaseModel): | |
| 85 | - name: str | |
| 86 | - metadata: Optional[Dict[str, Any]] = None | |
| 87 | - | |
| 88 | - | |
| 89 | -@json_schema_type | |
| 90 | -class UpdateExperimentRequest(BaseModel): | |
| 91 | - experiment_id: str | |
| 92 | - status: Optional[ExperimentStatus] = None | |
| 93 | - metadata: Optional[Dict[str, Any]] = None | |
| 49 | +class LogSeverity(Enum): | |
| 50 | + VERBOSE = "verbose" | |
| 51 | + DEBUG = "debug" | |
| 52 | + INFO = "info" | |
| 53 | + WARN = "warn" | |
| 54 | + ERROR = "error" | |
| 55 | + CRITICAL = "critical" | |
| 94 | 56 | |
| 95 | 57 | |
| 96 | -@json_schema_type | |
| 97 | -class CreateRunRequest(BaseModel): | |
| 98 | - experiment_id: str | |
| 99 | - metadata: Optional[Dict[str, Any]] = None | |
| 58 | +class EventCommon(BaseModel): | |
| 59 | + trace_id: str | |
| 60 | + span_id: str | |
| 61 | + timestamp: datetime | |
| 62 | + attributes: Optional[Dict[str, Any]] = Field(default_factory=dict) | |
| 100 | 63 | |
| 101 | 64 | |
| 102 | 65 | @json_schema_type |
| 103 | -class UpdateRunRequest(BaseModel): | |
| 104 | - run_id: str | |
| 105 | - status: Optional[str] = None | |
| 106 | - ended_at: Optional[datetime] = None | |
| 107 | - metadata: Optional[Dict[str, Any]] = None | |
| 66 | +class UnstructuredLogEvent(EventCommon): | |
| 67 | + type: Literal[EventType.UNSTRUCTURED_LOG.value] = EventType.UNSTRUCTURED_LOG.value | |
| 68 | + message: str | |
| 69 | + severity: LogSeverity | |
| 108 | 70 | |
| 109 | 71 | |
| 110 | 72 | @json_schema_type |
| 111 | -class LogMetricsRequest(BaseModel): | |
| 112 | - run_id: str | |
| 113 | - metrics: List[Metric] | |
| 73 | +class MetricEvent(EventCommon): | |
| 74 | + type: Literal[EventType.METRIC.value] = EventType.METRIC.value | |
| 75 | + metric: str # this would be an enum | |
| 76 | + value: Union[int, float] | |
| 77 | + unit: str | |
| 114 | 78 | |
| 115 | 79 | |
| 116 | 80 | @json_schema_type |
| 117 | -class LogMessagesRequest(BaseModel): | |
| 118 | - logs: List[Log] | |
| 119 | - run_id: Optional[str] = None | |
| 81 | +class StructuredLogType(Enum): | |
| 82 | + SPAN_START = "span_start" | |
| 83 | + SPAN_END = "span_end" | |
| 120 | 84 | |
| 121 | 85 | |
| 122 | 86 | @json_schema_type |
| 123 | -class UploadArtifactRequest(BaseModel): | |
| 124 | - experiment_id: str | |
| 87 | +class SpanStartPayload(BaseModel): | |
| 88 | + type: Literal[StructuredLogType.SPAN_START.value] = ( | |
| 89 | + StructuredLogType.SPAN_START.value | |
| 90 | + ) | |
| 125 | 91 | name: str |
| 126 | - artifact_type: str | |
| 127 | - content: bytes | |
| 128 | - metadata: Optional[Dict[str, Any]] = None | |
| 92 | + parent_span_id: Optional[str] = None | |
| 129 | 93 | |
| 130 | 94 | |
| 131 | 95 | @json_schema_type |
| 132 | -class LogSearchRequest(BaseModel): | |
| 133 | - query: str | |
| 134 | - filters: Optional[Dict[str, Any]] = None | |
| 135 | - | |
| 96 | +class SpanEndPayload(BaseModel): | |
| 97 | + type: Literal[StructuredLogType.SPAN_END.value] = StructuredLogType.SPAN_END.value | |
| 98 | + status: SpanStatus | |
| 136 | 99 | |
| 137 | -class Telemetry(Protocol): | |
| 138 | - @webmethod(route="/experiments/create") | |
| 139 | - def create_experiment(self, request: CreateExperimentRequest) -> Experiment: ... | |
| 140 | - | |
| 141 | - @webmethod(route="/experiments/list") | |
| 142 | - def list_experiments(self) -> List[Experiment]: ... | |
| 143 | - | |
| 144 | - @webmethod(route="/experiments/get") | |
| 145 | - def get_experiment(self, experiment_id: str) -> Experiment: ... | |
| 146 | - | |
| 147 | - @webmethod(route="/experiments/update") | |
| 148 | - def update_experiment(self, request: UpdateExperimentRequest) -> Experiment: ... | |
| 149 | 100 | |
| 150 | - @webmethod(route="/experiments/create_run") | |
| 151 | - def create_run(self, request: CreateRunRequest) -> Run: ... | |
| 101 | +StructuredLogPayload = Annotated[ | |
| 102 | + Union[ | |
| 103 | + SpanStartPayload, | |
| 104 | + SpanEndPayload, | |
| 105 | + ], | |
| 106 | + Field(discriminator="type"), | |
| 107 | +] | |
| 152 | 108 | |
| 153 | - @webmethod(route="/runs/update") | |
| 154 | - def update_run(self, request: UpdateRunRequest) -> Run: ... | |
| 155 | 109 | |
| 156 | - @webmethod(route="/runs/log_metrics") | |
| 157 | - def log_metrics(self, request: LogMetricsRequest) -> None: ... | |
| 158 | - | |
| 159 | - @webmethod(route="/runs/metrics", method="GET") | |
| 160 | - def get_metrics(self, run_id: str) -> List[Metric]: ... | |
| 161 | - | |
| 162 | - @webmethod(route="/logging/log_messages") | |
| 163 | - def log_messages(self, request: LogMessagesRequest) -> None: ... | |
| 110 | +@json_schema_type | |
| 111 | +class StructuredLogEvent(EventCommon): | |
| 112 | + type: Literal[EventType.STRUCTURED_LOG.value] = EventType.STRUCTURED_LOG.value | |
| 113 | + payload: StructuredLogPayload | |
| 164 | 114 | |
| 165 | - @webmethod(route="/logging/get_logs") | |
| 166 | - def get_logs(self, request: LogSearchRequest) -> List[Log]: ... | |
| 167 | 115 | |
| 168 | - @webmethod(route="/experiments/artifacts/upload") | |
| 169 | - def upload_artifact(self, request: UploadArtifactRequest) -> Artifact: ... | |
| 116 | +Event = Annotated[ | |
| 117 | + Union[ | |
| 118 | + UnstructuredLogEvent, | |
| 119 | + MetricEvent, | |
| 120 | + StructuredLogEvent, | |
| 121 | + ], | |
| 122 | + Field(discriminator="type"), | |
| 123 | +] | |
| 170 | 124 | |
| 171 | - @webmethod(route="/experiments/artifacts/get") | |
| 172 | - def list_artifacts(self, experiment_id: str) -> List[Artifact]: ... | |
| 173 | 125 | |
| 174 | - @webmethod(route="/artifacts/get") | |
| 175 | - def get_artifact(self, artifact_id: str) -> Artifact: ... | |
| 126 | +class Telemetry(Protocol): | |
| 127 | + @webmethod(route="/telemetry/log_event") | |
| 128 | + async def log_event(self, event: Event): ... | |
| 129 | + | |
| 130 | + @webmethod(route="/telemetry/get_trace", method="GET") | |
| 131 | + async def get_trace(self, trace_id: str) -> Trace: ... |
added llama_toolchain/telemetry/console/__init__.py +15 −0
| @@ -0,0 +1,15 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | +# the root directory of this source tree. | |
| 6 | + | |
| 7 | +from .config import ConsoleConfig | |
| 8 | + | |
| 9 | + | |
| 10 | +async def get_provider_impl(config: ConsoleConfig, _deps): | |
| 11 | + from .console import ConsoleTelemetryImpl | |
| 12 | + | |
| 13 | + impl = ConsoleTelemetryImpl(config) | |
| 14 | + await impl.initialize() | |
| 15 | + return impl |
added llama_toolchain/telemetry/console/config.py +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | +# the root directory of this source tree. | |
| 6 | + | |
| 7 | +from llama_models.schema_utils import json_schema_type | |
| 8 | + | |
| 9 | +from pydantic import BaseModel | |
| 10 | + | |
| 11 | + | |
| 12 | +@json_schema_type | |
| 13 | +class ConsoleConfig(BaseModel): ... |
added llama_toolchain/telemetry/console/console.py +89 −0
| @@ -0,0 +1,89 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | +# the root directory of this source tree. | |
| 6 | + | |
| 7 | +from typing import Optional | |
| 8 | + | |
| 9 | +from llama_toolchain.telemetry.api import * # noqa: F403 | |
| 10 | +from .config import ConsoleConfig | |
| 11 | + | |
| 12 | + | |
| 13 | +class ConsoleTelemetryImpl(Telemetry): | |
| 14 | + def __init__(self, config: ConsoleConfig) -> None: | |
| 15 | + self.config = config | |
| 16 | + self.spans = {} | |
| 17 | + | |
| 18 | + async def initialize(self) -> None: ... | |
| 19 | + | |
| 20 | + async def shutdown(self) -> None: ... | |
| 21 | + | |
| 22 | + async def log_event(self, event: Event): | |
| 23 | + if ( | |
| 24 | + isinstance(event, StructuredLogEvent) | |
| 25 | + and event.payload.type == StructuredLogType.SPAN_START.value | |
| 26 | + ): | |
| 27 | + self.spans[event.span_id] = event.payload | |
| 28 | + | |
| 29 | + names = [] | |
| 30 | + span_id = event.span_id | |
| 31 | + while True: | |
| 32 | + span_payload = self.spans.get(span_id) | |
| 33 | + if not span_payload: | |
| 34 | + break | |
| 35 | + | |
| 36 | + names = [span_payload.name] + names | |
| 37 | + span_id = span_payload.parent_span_id | |
| 38 | + | |
| 39 | + span_name = ".".join(names) if names else None | |
| 40 | + | |
| 41 | + formatted = format_event(event, span_name) | |
| 42 | + if formatted: | |
| 43 | + print(formatted) | |
| 44 | + | |
| 45 | + async def get_trace(self, trace_id: str) -> Trace: | |
| 46 | + raise NotImplementedError() | |
| 47 | + | |
| 48 | + | |
| 49 | +COLORS = { | |
| 50 | + "reset": "\033[0m", | |
| 51 | + "bold": "\033[1m", | |
| 52 | + "dim": "\033[2m", | |
| 53 | + "red": "\033[31m", | |
| 54 | + "green": "\033[32m", | |
| 55 | + "yellow": "\033[33m", | |
| 56 | + "blue": "\033[34m", | |
| 57 | + "magenta": "\033[35m", | |
| 58 | + "cyan": "\033[36m", | |
| 59 | + "white": "\033[37m", | |
| 60 | +} | |
| 61 | + | |
| 62 | +SEVERITY_COLORS = { | |
| 63 | + LogSeverity.VERBOSE: COLORS["dim"] + COLORS["white"], | |
| 64 | + LogSeverity.DEBUG: COLORS["cyan"], | |
| 65 | + LogSeverity.INFO: COLORS["green"], | |
| 66 | + LogSeverity.WARN: COLORS["yellow"], | |
| 67 | + LogSeverity.ERROR: COLORS["red"], | |
| 68 | + LogSeverity.CRITICAL: COLORS["bold"] + COLORS["red"], | |
| 69 | +} | |
| 70 | + | |
| 71 | + | |
| 72 | +def format_event(event: Event, span_name: str) -> Optional[str]: | |
| 73 | + timestamp = event.timestamp.strftime("%H:%M:%S.%f")[:-3] | |
| 74 | + span = "" | |
| 75 | + if span_name: | |
| 76 | + span = f"{COLORS['magenta']}[{span_name}]{COLORS['reset']} " | |
| 77 | + if isinstance(event, UnstructuredLogEvent): | |
| 78 | + severity_color = SEVERITY_COLORS.get(event.severity, COLORS["reset"]) | |
| 79 | + return ( | |
| 80 | + f"{COLORS['dim']}{timestamp}{COLORS['reset']} " | |
| 81 | + f"{severity_color}[{event.severity.name}]{COLORS['reset']} " | |
| 82 | + f"{span}" | |
| 83 | + f"{event.message}" | |
| 84 | + ) | |
| 85 | + | |
| 86 | + elif isinstance(event, StructuredLogEvent): | |
| 87 | + return None | |
| 88 | + | |
| 89 | + return f"Unknown event type: {event}" |
added llama_toolchain/telemetry/providers.py +21 −0
| @@ -0,0 +1,21 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | +# the root directory of this source tree. | |
| 6 | + | |
| 7 | +from typing import List | |
| 8 | + | |
| 9 | +from llama_toolchain.core.datatypes import * # noqa: F403 | |
| 10 | + | |
| 11 | + | |
| 12 | +def available_providers() -> List[ProviderSpec]: | |
| 13 | + return [ | |
| 14 | + InlineProviderSpec( | |
| 15 | + api=Api.telemetry, | |
| 16 | + provider_type="console", | |
| 17 | + pip_packages=[], | |
| 18 | + module="llama_toolchain.telemetry.console", | |
| 19 | + config_class="llama_toolchain.telemetry.console.ConsoleConfig", | |
| 20 | + ), | |
| 21 | + ] |
added llama_toolchain/telemetry/tracing.py +236 −0
| @@ -0,0 +1,236 @@ | ||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | |
| 2 | +# All rights reserved. | |
| 3 | +# | |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in | |
| 5 | +# the root directory of this source tree. | |
| 6 | + | |
| 7 | +import asyncio | |
| 8 | +import base64 | |
| 9 | +import logging | |
| 10 | +import queue | |
| 11 | +import threading | |
| 12 | +import uuid | |
| 13 | +from datetime import datetime | |
| 14 | +from functools import wraps | |
| 15 | +from typing import Any, Dict, List | |
| 16 | + | |
| 17 | + | |
| 18 | +from llama_toolchain.telemetry.api import * # noqa: F403 | |
| 19 | + | |
| 20 | + | |
| 21 | +def generate_short_uuid(len: int = 12): | |
| 22 | + full_uuid = uuid.uuid4() | |
| 23 | + uuid_bytes = full_uuid.bytes | |
| 24 | + encoded = base64.urlsafe_b64encode(uuid_bytes) | |
| 25 | + return encoded.rstrip(b"=").decode("ascii")[:len] | |
| 26 | + | |
| 27 | + | |
| 28 | +CURRENT_TRACE_CONTEXT = None | |
| 29 | +BACKGROUND_LOGGER = None | |
| 30 | + | |
| 31 | + | |
| 32 | +class BackgroundLogger: | |
| 33 | + def __init__(self, api: Telemetry, capacity: int = 1000): | |
| 34 | + self.api = api | |
| 35 | + self.log_queue = queue.Queue(maxsize=capacity) | |
| 36 | + self.worker_thread = threading.Thread(target=self._process_logs, daemon=True) | |
| 37 | + self.worker_thread.start() | |
| 38 | + | |
| 39 | + def log_event(self, event): | |
| 40 | + try: | |
| 41 | + self.log_queue.put_nowait(event) | |
| 42 | + except queue.Full: | |
| 43 | + print("Log queue is full, dropping event") | |
| 44 | + | |
| 45 | + def _process_logs(self): | |
| 46 | + while True: | |
| 47 | + try: | |
| 48 | + event = self.log_queue.get() | |
| 49 | + # figure out how to use a thread's native loop | |
| 50 | + asyncio.run(self.api.log_event(event)) | |
| 51 | + except Exception: | |
| 52 | + import traceback | |
| 53 | + | |
| 54 | + traceback.print_exc() | |
| 55 | + print("Error processing log event") | |
| 56 | + finally: | |
| 57 | + self.log_queue.task_done() | |
| 58 | + | |
| 59 | + def __del__(self): | |
| 60 | + self.log_queue.join() | |
| 61 | + | |
| 62 | + | |
| 63 | +class TraceContext: | |
| 64 | + spans: List[Span] = [] | |
| 65 | + | |
| 66 | + def __init__(self, logger: BackgroundLogger, trace_id: str): | |
| 67 | + self.logger = logger | |
| 68 | + self.trace_id = trace_id | |
| 69 | + | |
| 70 | + def push_span(self, name: str, attributes: Dict[str, Any] = None): | |
| 71 | + current_span = self.get_current_span() | |
| 72 | + span = Span( | |
| 73 | + span_id=generate_short_uuid(), | |
| 74 | + trace_id=self.trace_id, | |
| 75 | + name=name, | |
| 76 | + start_time=datetime.now(), | |
| 77 | + parent_span_id=current_span.span_id if current_span else None, | |
| 78 | + attributes=attributes, | |
| 79 | + ) | |
| 80 | + | |
| 81 | + self.logger.log_event( | |
| 82 | + StructuredLogEvent( | |
| 83 | + trace_id=span.trace_id, | |
| 84 | + span_id=span.span_id, | |
| 85 | + timestamp=span.start_time, | |
| 86 | + attributes=span.attributes, | |
| 87 | + payload=SpanStartPayload( | |
| 88 | + name=span.name, | |
| 89 | + parent_span_id=span.parent_span_id, | |
| 90 | + ), | |
| 91 | + ) | |
| 92 | + ) | |
| 93 | + | |
| 94 | + self.spans.append(span) | |
| 95 | + | |
| 96 | + def pop_span(self, status: SpanStatus = SpanStatus.OK): | |
| 97 | + span = self.spans.pop() | |
| 98 | + if span is not None: | |
| 99 | + self.logger.log_event( | |
| 100 | + StructuredLogEvent( | |
| 101 | + trace_id=span.trace_id, | |
| 102 | + span_id=span.span_id, | |
| 103 | + timestamp=span.start_time, | |
| 104 | + attributes=span.attributes, | |
| 105 | + payload=SpanEndPayload( | |
| 106 | + status=status, | |
| 107 | + ), | |
| 108 | + ) | |
| 109 | + ) | |
| 110 | + | |
| 111 | + def get_current_span(self): | |
| 112 | + return self.spans[-1] if self.spans else None | |
| 113 | + | |
| 114 | + | |
| 115 | +def setup_logger(api: Telemetry, level: int = logging.INFO): | |
| 116 | + global BACKGROUND_LOGGER | |
| 117 | + | |
| 118 | + BACKGROUND_LOGGER = BackgroundLogger(api) | |
| 119 | + logger = logging.getLogger() | |
| 120 | + logger.setLevel(level) | |
| 121 | + logger.addHandler(TelemetryHandler()) | |
| 122 | + | |
| 123 | + | |
| 124 | +async def start_trace(name: str, attributes: Dict[str, Any] = None): | |
| 125 | + global CURRENT_TRACE_CONTEXT, BACKGROUND_LOGGER | |
| 126 | + | |
| 127 | + if BACKGROUND_LOGGER is None: | |
| 128 | + print("No Telemetry implementation set. Skipping trace initialization...") | |
| 129 | + return | |
| 130 | + | |
| 131 | + trace_id = generate_short_uuid() | |
| 132 | + context = TraceContext(BACKGROUND_LOGGER, trace_id) | |
| 133 | + context.push_span(name, {"__root__": True, **(attributes or {})}) | |
| 134 | + | |
| 135 | + CURRENT_TRACE_CONTEXT = context | |
| 136 | + | |
| 137 | + | |
| 138 | +async def end_trace(status: SpanStatus = SpanStatus.OK): | |
| 139 | + global CURRENT_TRACE_CONTEXT | |
| 140 | + | |
| 141 | + context = CURRENT_TRACE_CONTEXT | |
| 142 | + if context is None: | |
| 143 | + return | |
| 144 | + | |
| 145 | + context.pop_span(status) | |
| 146 | + CURRENT_TRACE_CONTEXT = None | |
| 147 | + | |
| 148 | + | |
| 149 | +def severity(levelname: str) -> LogSeverity: | |
| 150 | + if levelname == "DEBUG": | |
| 151 | + return LogSeverity.DEBUG | |
| 152 | + elif levelname == "INFO": | |
| 153 | + return LogSeverity.INFO | |
| 154 | + elif levelname == "WARNING": | |
| 155 | + return LogSeverity.WARNING | |
| 156 | + elif levelname == "ERROR": | |
| 157 | + return LogSeverity.ERROR | |
| 158 | + elif levelname == "CRITICAL": | |
| 159 | + return LogSeverity.CRITICAL | |
| 160 | + else: | |
| 161 | + raise ValueError(f"Unknown log level: {levelname}") | |
| 162 | + | |
| 163 | + | |
| 164 | +# TODO: ideally, the actual emitting should be done inside a separate daemon | |
| 165 | +# process completely isolated from the server | |
| 166 | +class TelemetryHandler(logging.Handler): | |
| 167 | + def emit(self, record: logging.LogRecord): | |
| 168 | + # horrendous hack to avoid logging from asyncio and getting into an infinite loop | |
| 169 | + if record.module in ("asyncio", "selector_events"): | |
| 170 | + return | |
| 171 | + | |
| 172 | + global CURRENT_TRACE_CONTEXT, BACKGROUND_LOGGER | |
| 173 | + | |
| 174 | + if BACKGROUND_LOGGER is None: | |
| 175 | + raise RuntimeError("Telemetry API not initialized") | |
| 176 | + | |
| 177 | + context = CURRENT_TRACE_CONTEXT | |
| 178 | + if context is None: | |
| 179 | + return | |
| 180 | + | |
| 181 | + span = context.get_current_span() | |
| 182 | + if span is None: | |
| 183 | + return | |
| 184 | + | |
| 185 | + BACKGROUND_LOGGER.log_event( | |
| 186 | + UnstructuredLogEvent( | |
| 187 | + trace_id=span.trace_id, | |
| 188 | + span_id=span.span_id, | |
| 189 | + timestamp=datetime.now(), | |
| 190 | + message=self.format(record), | |
| 191 | + severity=severity(record.levelname), | |
| 192 | + ) | |
| 193 | + ) | |
| 194 | + | |
| 195 | + def close(self): | |
| 196 | + pass | |
| 197 | + | |
| 198 | + | |
| 199 | +def span(name: str, attributes: Dict[str, Any] = None): | |
| 200 | + def decorator(func): | |
| 201 | + @wraps(func) | |
| 202 | + def sync_wrapper(*args, **kwargs): | |
| 203 | + try: | |
| 204 | + global CURRENT_TRACE_CONTEXT | |
| 205 | + | |
| 206 | + context = CURRENT_TRACE_CONTEXT | |
| 207 | + if context: | |
| 208 | + context.push_span(name, attributes) | |
| 209 | + result = func(*args, **kwargs) | |
| 210 | + finally: | |
| 211 | + context.pop_span() | |
| 212 | + return result | |
| 213 | + | |
| 214 | + @wraps(func) | |
| 215 | + async def async_wrapper(*args, **kwargs): | |
| 216 | + try: | |
| 217 | + global CURRENT_TRACE_CONTEXT | |
| 218 | + | |
| 219 | + context = CURRENT_TRACE_CONTEXT | |
| 220 | + if context: | |
| 221 | + context.push_span(name, attributes) | |
| 222 | + result = await func(*args, **kwargs) | |
| 223 | + finally: | |
| 224 | + context.pop_span() | |
| 225 | + return result | |
| 226 | + | |
| 227 | + @wraps(func) | |
| 228 | + def wrapper(*args, **kwargs): | |
| 229 | + if asyncio.iscoroutinefunction(func): | |
| 230 | + return async_wrapper(*args, **kwargs) | |
| 231 | + else: | |
| 232 | + return sync_wrapper(*args, **kwargs) | |
| 233 | + | |
| 234 | + return wrapper | |
| 235 | + | |
| 236 | + return decorator |