Skip to content
Open
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.15.20"
rev: "v0.9.7"
hooks:
- id: ruff
args: [--fix]
Expand Down
15 changes: 10 additions & 5 deletions examples/agent/crewAI/research_crew/src/research_crew/crew.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
# src/research_crew/crew.py

from crewai import Agent, Crew, Process, Task
from crewai.agents.agent_builder.base_agent import BaseAgent
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List


@CrewBase
class ResearchCrew:
"""Research crew for comprehensive topic analysis and reporting"""

agents: list[BaseAgent]
tasks: list[Task]
agents: List[BaseAgent]
tasks: List[Task]

@agent
def researcher(self) -> Agent:
Expand All @@ -32,4 +32,9 @@ def analysis_task(self) -> Task:
@crew
def crew(self) -> Crew:
"""Creates the research crew"""
return Crew(agents=self.agents, tasks=self.tasks, process=Process.sequential, verbose=True)
return Crew(
agents=self.agents,
tasks=self.tasks,
process=Process.sequential,
verbose=True,
)
6 changes: 2 additions & 4 deletions examples/agent/crewAI/research_crew/src/research_crew/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
#!/usr/bin/env python
# src/research_crew/main.py
import os

from dotenv import load_dotenv

from research_crew.crew import ResearchCrew
from dotenv import load_dotenv
from splunk_ao.handlers.crewai.handler import CrewAIEventListener

load_dotenv()
Expand All @@ -13,7 +11,7 @@
os.makedirs("output", exist_ok=True)


def run() -> None:
def run():
# Create the event listener for Splunk AO CrewAI integration
CrewAIEventListener()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from crewai.tools import BaseTool
from typing import Type
from pydantic import BaseModel, Field


Expand All @@ -10,10 +11,8 @@ class MyCustomToolInput(BaseModel):

class MyCustomTool(BaseTool):
name: str = "Name of my tool"
description: str = (
"Clear description for what this tool is useful for, your agent will need this information to use it."
)
args_schema: type[BaseModel] = MyCustomToolInput
description: str = "Clear description for what this tool is useful for, your agent will need this information to use it."
args_schema: Type[BaseModel] = MyCustomToolInput

def _run(self, argument: str) -> str:
# Implementation goes here
Expand Down
9 changes: 3 additions & 6 deletions examples/agent/google-adk/my_agent/agent.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
"""Agent logic for the Google ADK example."""

from dotenv import load_dotenv
from google.adk.agents.llm_agent import Agent
from openinference.instrumentation.google_adk import GoogleADKInstrumentor
from opentelemetry.sdk import trace as trace_sdk

from splunk_ao import otel
from openinference.instrumentation.google_adk import GoogleADKInstrumentor
from google.adk.agents.llm_agent import Agent

load_dotenv()

Expand All @@ -32,8 +31,6 @@ def get_current_time(city: str) -> dict:
model="gemini-3-flash-preview",
name="root_agent",
description="Tells the current time in a specified city.",
instruction=(
"You are a helpful assistant that tells the current time in cities.Use the 'get_current_time' tool for this purpose."
),
instruction=("You are a helpful assistant that tells the current time in cities." "Use the 'get_current_time' tool for this purpose."),
tools=[get_current_time],
)
3 changes: 1 addition & 2 deletions examples/agent/langchain-agent/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from dotenv import load_dotenv
from langchain.agents import initialize_agent
from langchain.agents.agent_types import AgentType
from langchain.tools import tool
from langchain_openai import ChatOpenAI

from langchain.tools import tool
from splunk_ao import splunk_ao_context
from splunk_ao.handlers.langchain import SplunkAOCallback

Expand Down
20 changes: 4 additions & 16 deletions examples/agent/langchain-middleware/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@
import os

from dotenv import load_dotenv
from splunk_ao import splunk_ao_context
from splunk_ao.handlers.langchain.middleware import SplunkAOMiddleware
from langchain.agents.factory import create_agent
from langchain.tools import tool
from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI

from splunk_ao import splunk_ao_context
from splunk_ao.handlers.langchain.middleware import SplunkAOMiddleware

# Load environment variables (e.g., API keys)
load_dotenv()

Expand Down Expand Up @@ -43,10 +42,7 @@ def get_stock_price(symbol: str) -> str:
def main() -> None:
# Use the Splunk AO context manager to specify project and log stream
# All traces created within this context will be associated with this project
with splunk_ao_context(
project=os.getenv("SPLUNK_AO_PROJECT", "langchain-middleware"),
log_stream=os.getenv("SPLUNK_AO_LOG_STREAM", "agent_execution"),
):
with splunk_ao_context(project=os.getenv("SPLUNK_AO_PROJECT", "langchain-middleware"), log_stream=os.getenv("SPLUNK_AO_LOG_STREAM", "agent_execution")):
# Create an agent with SplunkAOMiddleware for automatic logging
# SplunkAOMiddleware automatically captures:
# - Agent lifecycle events (start/completion)
Expand All @@ -65,15 +61,7 @@ def main() -> None:
# 3. Understand it needs Apple's stock price
# 4. Call the get_stock_price tool
# 5. Synthesize the results into a coherent response
result = agent.invoke(
{
"messages": [
HumanMessage(
content="What's the weather like in San Francisco and what's the current stock price of Apple?"
)
]
}
)
result = agent.invoke({"messages": [HumanMessage(content="What's the weather like in San Francisco and what's the current stock price of Apple?")]})
print(f"\nAgent Response:\n{result}")


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# A script to generate log streams
# ruff: noqa: E402 -- load_dotenv() must precede all other imports

from dotenv import load_dotenv

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,7 @@ def upload_to_pinecone(chunked_docs, index_name: str, force_upload: bool = False

# Create vector store and upload
print(f"Uploading {len(chunked_docs)} chunks to Pinecone...")
vector_store = PineconeVectorStore.from_documents(
documents=chunked_docs, embedding=EMBEDDINGS, index_name=index_name
)
vector_store = PineconeVectorStore.from_documents(documents=chunked_docs, embedding=EMBEDDINGS, index_name=index_name)

print(f"Successfully uploaded {len(chunked_docs)} document chunks to Pinecone")
return vector_store
Expand Down
7 changes: 1 addition & 6 deletions examples/agent/langgraph-fsi-agent/after/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,7 @@ def test_run_experiment_with_dataset():
experiment_name="langgraph-fsi-experiment",
dataset_name=DATASET_NAME,
function=send_message_to_supervisor_agent,
metrics=[
SplunkAOMetrics.action_advancement,
SplunkAOMetrics.action_completion,
SplunkAOMetrics.tool_error_rate,
SplunkAOMetrics.tool_selection_quality,
],
metrics=[SplunkAOMetrics.action_advancement, SplunkAOMetrics.action_completion, SplunkAOMetrics.tool_error_rate, SplunkAOMetrics.tool_selection_quality],
project=os.getenv("SPLUNK_AO_PROJECT"),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,7 @@ def upload_to_pinecone(chunked_docs, index_name: str, force_upload: bool = False

# Create vector store and upload
print(f"Uploading {len(chunked_docs)} chunks to Pinecone...")
vector_store = PineconeVectorStore.from_documents(
documents=chunked_docs, embedding=EMBEDDINGS, index_name=index_name
)
vector_store = PineconeVectorStore.from_documents(documents=chunked_docs, embedding=EMBEDDINGS, index_name=index_name)

print(f"Successfully uploaded {len(chunked_docs)} document chunks to Pinecone")
return vector_store
Expand Down
10 changes: 6 additions & 4 deletions examples/agent/langgraph-open-telemetry/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import dotenv
import openai
from splunk_ao import otel

# LangGraph imports - this is what we're actually instrumenting
from langgraph.graph import END, StateGraph
Expand All @@ -13,8 +14,6 @@
from opentelemetry.sdk import trace as trace_sdk # SDK for creating traces
from opentelemetry.sdk.resources import Resource

from splunk_ao import otel

dotenv.load_dotenv()
logging.basicConfig(level=logging.DEBUG)

Expand Down Expand Up @@ -85,7 +84,10 @@ def generate_response(state: AgentState):

# Make the OpenAI API call - OpenAI instrumentation handles tracing
response = client.chat.completions.create(
model="gpt-3.5-turbo", messages=[{"role": "user", "content": user_input}], max_tokens=300, temperature=0.7
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": user_input}],
max_tokens=300,
temperature=0.7,
)

# Extract the response content
Expand All @@ -100,7 +102,7 @@ def generate_response(state: AgentState):

except Exception as e:
print(f"❌ Error calling OpenAI: {e}")
return {"llm_response": f"Error: {e!s}"}
return {"llm_response": f"Error: {str(e)}"}


# Node 3: Format Answer
Expand Down
30 changes: 19 additions & 11 deletions examples/agent/langgraph-otel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,25 @@
# "instrument" your code so you can see exactly what's happening during execution.

# Core OpenTelemetry imports
# OpenAI imports for LLM integration
import openai

# LangGraph imports - this is what we're actually instrumenting
from langgraph.graph import END, StateGraph
from opentelemetry.sdk import trace as trace_sdk # SDK for creating traces
from opentelemetry import trace as trace_api # API for interacting with traces
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
) # Efficiently batches spans before export
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
OTLPSpanExporter,
) # Sends traces via HTTP

# OpenInference is a specialized instrumentation library that understands AI frameworks
# It automatically creates meaningful spans for LangChain/LangGraph operations
from openinference.instrumentation.langchain import LangChainInstrumentor
from openinference.instrumentation.openai import OpenAIInstrumentor
from opentelemetry import trace as trace_api # API for interacting with traces
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter # Sends traces via HTTP
from opentelemetry.sdk import trace as trace_sdk # SDK for creating traces
from opentelemetry.sdk.trace.export import BatchSpanProcessor # Efficiently batches spans before export

# LangGraph imports - this is what we're actually instrumenting
from langgraph.graph import StateGraph, END

# OpenAI imports for LLM integration
import openai

# ============================================================================
# STEP 1: CONFIGURE API AUTHENTICATION
Expand Down Expand Up @@ -163,7 +168,10 @@ def generate_response(state: AgentState):

# Make the OpenAI API call - OpenAI instrumentation handles tracing
response = client.chat.completions.create(
model="gpt-3.5-turbo", messages=[{"role": "user", "content": user_input}], max_tokens=300, temperature=0.7
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": user_input}],
max_tokens=300,
temperature=0.7,
)

# Extract the response content
Expand All @@ -175,7 +183,7 @@ def generate_response(state: AgentState):

except Exception as e:
print(f"❌ Error calling OpenAI: {e}")
return {"llm_response": f"Error: {e!s}"}
return {"llm_response": f"Error: {str(e)}"}


# Node 3: Format Answer
Expand Down
4 changes: 1 addition & 3 deletions examples/agent/langgraph-telecom-agent/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,7 @@ async def main(msg: cl.Message) -> None:
main_step.input = msg.content

# Call the graph with the user's message and stream the response back to the user
async for response_msg in supervisor_agent.astream(
input=messages, stream_mode="updates", config=runnable_config
):
async for response_msg in supervisor_agent.astream(input=messages, stream_mode="updates", config=runnable_config):
# Debug: Log the response structure
print(f"Response keys: {response_msg.keys()}")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,7 @@ def upload_to_pinecone(chunked_docs, index_name: str, force_upload: bool = False

# Create vector store and upload
print(f"Uploading {len(chunked_docs)} chunks to Pinecone...")
vector_store = PineconeVectorStore.from_documents(
documents=chunked_docs, embedding=EMBEDDINGS, index_name=index_name
)
vector_store = PineconeVectorStore.from_documents(documents=chunked_docs, embedding=EMBEDDINGS, index_name=index_name)

print(f"Successfully uploaded {len(chunked_docs)} document chunks to Pinecone")
return vector_store
Expand Down
24 changes: 12 additions & 12 deletions examples/agent/langgraph-telecom-agent/src/tools/billing_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,18 @@ def _run(self, customer_id: Optional[str] = None, query_type: str = "summary") -

if query_type == "usage":
return f"""
Usage Summary for {customer["name"]}:
- Data: {customer["data_used"]:.1f} GB used ({customer["data_limit"]})
Usage Summary for {customer['name']}:
- Data: {customer['data_used']:.1f} GB used ({customer['data_limit']})
- Minutes: {random.randint(300, 800)} (Unlimited)
- Texts: {random.randint(500, 2000)} (Unlimited)
- Average daily: {customer["data_used"] / 15:.2f} GB
- Average daily: {customer['data_used'] / 15:.2f} GB
"""

elif query_type == "plan":
return f"""
Current Plan: {customer["plan"]}
- Monthly Cost: ${customer["monthly_charge"]:.2f}
- Data: {customer["data_limit"]}
Current Plan: {customer['plan']}
- Monthly Cost: ${customer['monthly_charge']:.2f}
- Data: {customer['data_limit']}
- Talk & Text: Unlimited
- 5G Access: Included

Expand All @@ -72,10 +72,10 @@ def _run(self, customer_id: Optional[str] = None, query_type: str = "summary") -

# Default summary
return f"""
Account Summary for {customer["name"]}:
- Account: {customer["account"]}
- Plan: {customer["plan"]}
- Amount Due: ${customer["monthly_charge"]:.2f}
- Due Date: {customer["due_date"]}
- Data Used: {customer["data_used"]:.1f} GB ({customer["data_limit"]})
Account Summary for {customer['name']}:
- Account: {customer['account']}
- Plan: {customer['plan']}
- Amount Due: ${customer['monthly_charge']:.2f}
- Due Date: {customer['due_date']}
- Data Used: {customer['data_used']:.1f} GB ({customer['data_limit']})
"""
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def _run(self, issue_type: Optional[str] = None, action: str = "help") -> str:
Support Ticket Created: {ticket_id}
Priority: High
Response Time: Within 2 hours
Callback: {(datetime.now() + timedelta(hours=2)).strftime("%Y-%m-%d %H:%M")}
Callback: {(datetime.now() + timedelta(hours=2)).strftime('%Y-%m-%d %H:%M')}
24/7 Support: 1-800-TELECOM
"""

Expand Down
Loading
Loading