Skip to content
Merged

Dev #63

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 0 additions & 18 deletions python/fi_instrumentation/grpc/tracer.proto

This file was deleted.

41 changes: 0 additions & 41 deletions python/fi_instrumentation/grpc/tracer_pb2.py

This file was deleted.

97 changes: 0 additions & 97 deletions python/fi_instrumentation/grpc/tracer_pb2_grpc.py

This file was deleted.

108 changes: 1 addition & 107 deletions python/fi_instrumentation/otel.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,13 @@
import os
import signal
import sys
import time
import uuid
import warnings
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast
from typing import Any, Dict, List, Optional, Tuple, Type, Union
from urllib.parse import ParseResult, urlparse

import requests
from fi_instrumentation.fi_types import (
Endpoints,
EvalName,
EvalTag,
ProjectType,
Expand Down Expand Up @@ -46,9 +43,6 @@
from opentelemetry.sdk.trace.export import BatchSpanProcessor as _BatchSpanProcessor
from opentelemetry.sdk.trace.export import SimpleSpanProcessor as _SimpleSpanProcessor
from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
import grpc
from google.protobuf.struct_pb2 import Struct
from fi_instrumentation.grpc import tracer_pb2, tracer_pb2_grpc

PROJECT_NAME = "project_name"
PROJECT_TYPE = "project_type"
Expand Down Expand Up @@ -505,106 +499,6 @@ def __init__(self, *args: Any, **kwargs: Any):
bound_args.arguments["endpoint"] = endpoint
super().__init__(*bound_args.args, **bound_args.kwargs)

def _convert_attributes(self, attributes):
"""Convert mappingproxy objects to regular dictionaries."""
if attributes is None:
return {}
if not isinstance(attributes, dict):
return dict(attributes)
return attributes

def _format_trace_id(self, trace_id: int) -> str:
# Format the trace_id as a 32-character hexadecimal UUID
return f"{trace_id:032x}"

def _format_span_id(self, span_id: int) -> str:
# Format the span_id as a 16-character hexadecimal
return f"{span_id:016x}"

def export(self, spans) -> SpanExportResult:
"""
Exports a batch of spans in JSON format.
Args:
spans (list): A list of spans to export.
Returns:
SpanExportResult: Indicates the success or failure of the export.
"""
if not self._endpoint:
warnings.warn("gRPC Exporter endpoint is not configured. Cannot export spans.")
return SpanExportResult.FAILURE

spans_data = []
for span in spans:
span_data = {
"trace_id": self._format_trace_id(span.context.trace_id),
"span_id": self._format_span_id(span.context.span_id),
"name": span.name,
"start_time": span.start_time,
"end_time": span.end_time,
"attributes": self._convert_attributes(span.attributes),
"events": [
{
"name": event.name,
"attributes": self._convert_attributes(event.attributes),
"timestamp": event.timestamp,
}
for event in span.events
],
"status": span.status.status_code.name,
"parent_id": (
self._format_span_id(span.parent.span_id)
if span.parent
else None
),
"project_name": span.resource.attributes.get(PROJECT_NAME),
"project_type": span.resource.attributes.get(PROJECT_TYPE),
"project_version_name": span.resource.attributes.get(
PROJECT_VERSION_NAME
),
"project_version_id": span.resource.attributes.get(
PROJECT_VERSION_ID
),
"latency": math.floor(
(span.end_time - span.start_time) / 1000000
),
"eval_tags": span.resource.attributes.get(EVAL_TAGS),
"metadata": span.resource.attributes.get(METADATA),
"session_name": span.resource.attributes.get(SESSION_NAME),
}
spans_data.append(span_data)

if not spans_data:
return SpanExportResult.SUCCESS

try:

with grpc.insecure_channel(self._endpoint) as channel:
stub = tracer_pb2_grpc.ObservationSpanControllerStub(channel)
metadata = list(self._headers) if self._headers else None

otel_data_list = []
for span_data_item in spans_data:
s = Struct()
s.update(span_data_item)
otel_data_list.append(s)

request = tracer_pb2.CreateOtelSpanRequest(
otel_data_list=otel_data_list
)

try:
stub.CreateOtelSpan(request, metadata=metadata)
except grpc.RpcError as e:
print(f"Failed to export spans via gRPC: {e.details()}")

return SpanExportResult.SUCCESS

except Exception as e:
import traceback
print(traceback.format_exc())
print(f"Failed to export spans due to an unexpected error: {e}")
return SpanExportResult.FAILURE

def shutdown(self) -> None:
"""Clean up any resources before shutting down."""
try:
Expand Down
2 changes: 0 additions & 2 deletions python/frameworks/anthropic/examples/guardrail_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
from fi.evals import Evaluator, Protect
from fi_instrumentation import register
from fi_instrumentation.fi_types import ProjectType
from fi_instrumentation.instrumentation.config import TraceConfig
from opentelemetry import trace
from traceai_anthropic import AnthropicInstrumentor

# Initialize tracer
Expand Down
2 changes: 0 additions & 2 deletions python/frameworks/anthropic/traceai_anthropic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ def _instrument(self, **kwargs: Any) -> None:
except ImportError:
logger.warning("ai-evaluation is not installed, please install it to trace protect")
Protect = None
pass

if not (tracer_provider := kwargs.get("tracer_provider")):
tracer_provider = trace_api.get_tracer_provider()
Expand Down Expand Up @@ -110,7 +109,6 @@ def _uninstrument(self, **kwargs: Any) -> None:
except ImportError:
logger.warning("ai-evaluation is not installed, please install it to trace protect")
Protect = None
pass

if self._original_completions_create is not None:
Completions.create = self._original_completions_create # type: ignore[method-assign]
Expand Down
4 changes: 0 additions & 4 deletions python/frameworks/dspy/examples/embedding.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import dspy
from fi_instrumentation import register
from fi_instrumentation.fi_types import (
EvalName,
EvalSpanKind,
EvalTag,
EvalTagType,
ProjectType,
)
from traceai_dspy import DSPyInstrumentor
Expand Down
3 changes: 0 additions & 3 deletions python/frameworks/google-adk/examples/testing_google_adk.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
from google.genai import types

from traceai_google_adk import GoogleADKInstrumentor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk import trace as trace_sdk
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from fi_instrumentation import register
from fi_instrumentation.fi_types import ProjectType

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os

from dotenv import load_dotenv
from fi_instrumentation import register
Expand Down
3 changes: 0 additions & 3 deletions python/frameworks/langchain/examples/exchange_rate_tool.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from datetime import date
from typing import Optional

import requests
from fi_instrumentation import register
Expand All @@ -8,7 +6,6 @@
EvalSpanKind,
EvalTag,
EvalTagType,
ProjectType,
)
from langchain import agents
from langchain.tools import tool
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import math
from collections import defaultdict, deque
from typing import Literal, Optional
from collections import deque
from typing import Optional

from fi_instrumentation import register
from fi_instrumentation.fi_types import ProjectType
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_community.utilities.tavily_search import TavilySearchAPIWrapper
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
from langchain_core.output_parsers.openai_tools import (
JsonOutputToolsParser,
PydanticToolsParser,
Expand Down
2 changes: 0 additions & 2 deletions python/frameworks/langchain/examples/multimodal.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import base64
from io import BytesIO

import httpx
from fi_instrumentation import register
Expand All @@ -13,7 +12,6 @@
from langchain.chains import LLMChain
from langchain.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from PIL import Image
from traceai_langchain import LangChainInstrumentor

# Configure trace provider with custom evaluation tags
Expand Down
Loading