### Run Langtrace Python SDK Examples Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Execute provided examples for the Langtrace Python SDK by setting the `ENABLED_EXAMPLES` flag in `run_example.py` and running the script. This helps in understanding various SDK functionalities. ```python # In run_example.py, set ENABLED_EXAMPLES flag to True for desired example python src/run_example.py ``` -------------------------------- ### Run Langtrace Python SDK Tests Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Set up the test environment and execute unit tests for the Langtrace Python SDK using `pip install` and `pytest`. This ensures the integrity and functionality of the SDK. ```bash pip install '.[test]' && pip install '.[dev]' pytest -v ``` -------------------------------- ### Install Langtrace Python SDK Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md This command installs the Langtrace Python SDK using pip, making it available for use in your Python projects. It's the first step to integrate Langtrace's observability features into your LLM applications. ```bash pip install langtrace-python-sdk ``` -------------------------------- ### Integrate Langtrace with FastAPI Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md This example demonstrates how to integrate Langtrace with a FastAPI application. It initializes Langtrace, sets up a basic FastAPI app, and includes an OpenAI API call, automatically tracing the LLM interaction through Langtrace for observability. ```python from fastapi import FastAPI from langtrace_python_sdk import langtrace from openai import OpenAI langtrace.init() app = FastAPI() client = OpenAI() @app.get("/") def root(): client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": "Say this is a test"}], stream=False, ) return {"Hello": "World"} ``` -------------------------------- ### Integrate Langtrace with Django Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md This snippet shows how to integrate Langtrace into a Django project. It includes modifications to `settings.py` for SDK initialization and a `views.py` example demonstrating an OpenAI API call, ensuring LLM interactions are traced by Langtrace for debugging and performance monitoring. ```python # settings.py from langtrace_python_sdk import langtrace langtrace.init() # views.py from django.http import JsonResponse from openai import OpenAI client = OpenAI() def chat_view(request): response = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": request.GET.get('message', '')}] ) return JsonResponse({"response": response.choices[0].message.content}) ``` -------------------------------- ### Langtrace SDK Initialization Configuration Details Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Detailed description of each parameter for the `langtrace.init()` function, including its type, default value, and purpose, allowing for fine-grained control over the SDK's behavior. ```APIDOC langtrace.init() parameters: api_key: Type: Optional[str] Default: LANGTRACE_API_KEY or None Description: The API key for authentication. Can be set via environment variable. batch: Type: bool Default: True Description: Whether to batch spans before sending them to reduce API calls. write_spans_to_console: Type: bool Default: False Description: Enable console logging for debugging purposes. custom_remote_exporter: Type: Optional[Exporter] Default: None Description: Custom exporter for sending traces to your own backend. api_host: Type: Optional[str] Default: https://langtrace.ai/ Description: Custom API endpoint for self-hosted deployments. disable_instrumentations: Type: Optional[Dict] Default: None Description: Disable specific vendor instrumentations (e.g., {'only': ['openai']}). service_name: Type: Optional[str] Default: None Description: Custom service name for trace identification. disable_logging: Type: bool Default: False Description: Disable SDK logging completely. headers: Type: Dict[str, str] Default: {} Description: Custom headers for API requests. ``` -------------------------------- ### Initialize Langtrace for Self-Hosted Deployments Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Configure the Langtrace SDK for self-hosted environments by initializing it with console logging or a custom remote exporter. This enables flexible deployment and data management options. ```python from langtrace_python_sdk import langtrace langtrace.init(write_spans_to_console=True) # For console logging # OR langtrace.init(custom_remote_exporter=, batch=) # For custom exporter ``` -------------------------------- ### Initialize Langtrace Python SDK Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md This Python code snippet initializes the Langtrace SDK within your application. It requires an API key, which can be obtained from langtrace.ai, to connect your application's traces and metrics to the Langtrace platform for monitoring and analysis. ```python from langtrace_python_sdk import langtrace langtrace.init(api_key='') # Get your API key at langtrace.ai ``` -------------------------------- ### Langtrace SDK Initialization Options Signature Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md The signature of the `langtrace.init()` function, detailing the various parameters available for configuring the Langtrace Python SDK's behavior upon initialization. ```python langtrace.init( api_key: Optional[str] = None, # API key for authentication batch: bool = True, # Enable/disable batch processing write_spans_to_console: bool = False, # Console logging custom_remote_exporter: Optional[Any] = None, # Custom exporter api_host: Optional[str] = None, # Custom API host disable_instrumentations: Optional[Dict] = None, # Disable specific integrations service_name: Optional[str] = None, # Custom service name disable_logging: bool = False, # Disable all logging headers: Dict[str, str] = {}, # Custom headers ) ``` -------------------------------- ### Register and Use Prompt Templates in Langtrace Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Manage and reuse prompt templates by registering them with `langtrace.register_prompt`. This allows for consistent prompt generation and improved traceability when interacting with language models. ```python from langtrace_python_sdk import langtrace # Register a prompt template langtrace.register_prompt("greeting", "Hello, {name}!") # Use registered prompt response = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": langtrace.get_prompt("greeting", name="Alice")}] ) ``` -------------------------------- ### Integrate Langtrace with DSPy for Program Tracing Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Demonstrates integrating the Langtrace Python SDK with DSPy. DSPy operations, including language model configuration and program compilation, are automatically traced, providing visibility into the optimization and execution of your DSPy programs. ```python from langtrace_python_sdk import langtrace import dspy from dspy.teleprompt import BootstrapFewShot langtrace.init() # DSPy operations are automatically traced lm = dspy.OpenAI(model="gpt-4") dspy.settings.configure(lm=lm) class SimpleQA(dspy.Signature): """Answer questions with short responses.""" question = dspy.InputField() answer = dspy.OutputField(desc="short answer") compiler = BootstrapFewShot(metric=dspy.metrics.Answer()) program = compiler.compile(SimpleQA) ``` -------------------------------- ### Integrate Langtrace with LlamaIndex for Document Indexing and Queries Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Illustrates integrating the Langtrace Python SDK with LlamaIndex. Document loading, indexing, and queries are automatically traced, offering comprehensive insights into your Retrieval-Augmented Generation (RAG) pipeline operations. ```python from langtrace_python_sdk import langtrace from llama_index import VectorStoreIndex, SimpleDirectoryReader langtrace.init() # Document loading and indexing are automatically traced documents = SimpleDirectoryReader('data').load_data() index = VectorStoreIndex.from_documents(documents) # Queries are traced with metadata query_engine = index.as_query_engine() response = query_engine.query("What's in the documents?") ``` -------------------------------- ### Langtrace Python SDK Environment Variables Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Configure the Langtrace Python SDK's behavior using these environment variables, controlling aspects like API key, prompt/completion data tracing, DSPy checkpoint tracing, error reporting, and custom API endpoints. ```APIDOC Variable: LANGTRACE_API_KEY Description: Primary authentication method Default: Required* Impact: Required if not passed to init() Variable: TRACE_PROMPT_COMPLETION_DATA Description: Control prompt/completion tracing Default: true Impact: Set to 'false' to opt out of prompt/completion data collection Variable: TRACE_DSPY_CHECKPOINT Description: Control DSPy checkpoint tracing Default: true Impact: Set to 'false' to disable checkpoint tracing Variable: LANGTRACE_ERROR_REPORTING Description: Control error reporting Default: true Impact: Set to 'false' to disable Sentry error reporting Variable: LANGTRACE_API_HOST Description: Custom API endpoint Default: https://langtrace.ai/ Impact: Override default API endpoint for self-hosted deployments ``` -------------------------------- ### Integrate Langtrace with Flask for OpenAI Chat Completions Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Demonstrates how to integrate the Langtrace Python SDK with a Flask application to automatically trace OpenAI chat completion calls. It initializes Flask, Langtrace, and the OpenAI client, then defines a route to make a chat completion request, ensuring all related operations are traced. ```python from flask import Flask from langtrace_python_sdk import langtrace from openai import OpenAI app = Flask(__name__) langtrace.init() client = OpenAI() @app.route('/') def chat(): response = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": "Hello!"}] ) return {"response": response.choices[0].message.content} ``` -------------------------------- ### Integrate Langtrace with LangChain for Automatic Tracing Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Shows how to integrate the Langtrace Python SDK with LangChain. After SDK initialization, LangChain operations such as chat model interactions and prompt chaining are automatically traced, providing visibility into your LLM application's workflow. ```python from langtrace_python_sdk import langtrace from langchain.chat_models import ChatOpenAI from langchain.prompts import ChatPromptTemplate langtrace.init() # LangChain operations are automatically traced chat = ChatOpenAI() prompt = ChatPromptTemplate.from_messages([ ("system", "You are a helpful assistant."), ("user", "{input}") ]) chain = prompt | chat response = chain.invoke({"input": "Hello!"}) ``` -------------------------------- ### Integrate Langtrace with CrewAI for Agent and Task Tracing Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Shows how to integrate the Langtrace Python SDK with CrewAI. Agent and task definitions, along with crew execution, are automatically traced, providing insights into the collaborative AI workflows. ```python from langtrace_python_sdk import langtrace from crewai import Agent, Task, Crew langtrace.init() # Agents and tasks are automatically traced researcher = Agent( role="Researcher", goal="Research and analyze data", backstory="Expert data researcher", allow_delegation=False ) task = Task( description="Analyze market trends", agent=researcher ) crew = Crew( agents=[researcher], tasks=[task] ) result = crew.kickoff() ``` -------------------------------- ### Record User Feedback for Langtrace Traces Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Integrate user feedback into your tracing system using `langtrace.record_feedback`. This function allows you to associate ratings, text feedback, and custom metadata with specific traces for performance and quality analysis. ```python from langtrace_python_sdk import langtrace # Record user feedback for a trace langtrace.record_feedback( trace_id="your_trace_id", rating=5, feedback_text="Great response!", metadata={"user_id": "123"} ) ``` -------------------------------- ### Trace Vector Database Operations with Langtrace Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Automatically trace vector database operations by wrapping them with `langtrace.inject_additional_attributes`. This allows for contextualizing vector search results within your overall application traces. ```python from langtrace_python_sdk import langtrace # Vector operations are automatically traced with langtrace.inject_additional_attributes({"operation_type": "similarity_search"}): results = vector_db.similarity_search("query", k=5) ``` -------------------------------- ### Enable DSPy Checkpoint Tracing in Langtrace Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Control DSPy checkpoint tracing behavior by setting `dspy_checkpoint_tracing` during Langtrace initialization. This feature, though potentially impacting latency due to state serialization, helps track DSPy workflow progress. ```python from langtrace_python_sdk import langtrace # Enable checkpoint tracing (disabled by default in production) langtrace.init( api_key="your_api_key", dspy_checkpoint_tracing=True ) ``` -------------------------------- ### Create Custom Trace Hierarchies with Root Span Decorator Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Use the `@langtrace.with_langtrace_root_span` decorator to define custom root spans, allowing for the creation of tailored trace hierarchies for specific operations within your application. ```python from langtrace_python_sdk import langtrace @langtrace.with_langtrace_root_span(name="custom_operation") def my_function(): # Your code here pass ``` -------------------------------- ### Inject Custom Attributes into Langtrace Spans Source: https://github.com/scale3-labs/langtrace-python-sdk/blob/main/README.md Add custom key-value pairs to your traces using either the `@langtrace.with_additional_attributes` decorator or the `langtrace.inject_additional_attributes` context manager, providing extra context for debugging and analysis. ```python # Using decorator @langtrace.with_additional_attributes({"custom_key": "custom_value"}) def my_function(): pass # Using context manager with langtrace.inject_additional_attributes({"custom_key": "custom_value"}): # Your code here pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.