Skip to content
Closed
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
22 changes: 20 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ description = "The official Python library for the LayerLens Stratix API"
license = "Apache-2.0"
authors = [{ name = "LayerLens", email = "support@layerlens.ai" }]
dependencies = ["httpx>=0.23.0, <1", "pydantic>=1.9.0, <3"]
requires-python = ">= 3.8"
requires-python = ">= 3.9"
classifiers = [
"Typing :: Typed",
"Intended Audience :: Developers",
Expand All @@ -31,6 +31,23 @@ classifiers = [
"Topic :: Software Development :: Libraries :: Python Modules",
]

[project.optional-dependencies]
instrument = ["pydantic>=2.0"]
otel = ["opentelemetry-api>=1.20", "opentelemetry-sdk>=1.20", "opentelemetry-exporter-otlp-proto-grpc>=1.20"]
langgraph = ["langgraph>=0.2"]
langchain = ["langchain-core>=0.2"]
crewai = ["crewai>=0.28"]
autogen = ["pyautogen>=0.2"]
openai-agents = ["openai>=1.0"]
google-adk = ["google-adk>=0.1"]
bedrock = ["boto3>=1.28"]
llama-index = ["llama-index-core>=0.10"]
pydantic-ai = ["pydantic-ai>=0.1"]
semantic-kernel = ["semantic-kernel>=0.9"]
smolagents = ["smolagents>=0.1"]
langfuse = ["langfuse>=2.0"]
all = ["layerlens[instrument,otel,langgraph,langchain,crewai,autogen,openai-agents,google-adk,bedrock,llama-index,pydantic-ai,semantic-kernel,smolagents,langfuse]"]

[project.urls]
Homepage = "https://github.com/LayerLens/stratix-python"
Repository = "https://github.com/LayerLens/stratix-python"
Expand Down Expand Up @@ -133,10 +150,11 @@ known-first-party = ["openai", "tests"]
"tests/**.py" = ["T201", "T203"]
"examples/**.py" = ["T201", "T203"]
"src/layerlens/cli.py" = ["T201", "T203"]
"src/layerlens/instrument/**.py" = ["T201", "T203", "F401"]

[tool.pyright]
include = ["src", "tests"]
exclude = ["**/__pycache__"]
exclude = ["**/__pycache__", "src/layerlens/instrument/**"]
reportMissingTypeStubs = false

# Less strict settings for tests
Expand Down
119 changes: 119 additions & 0 deletions samples/adapters/frameworks/autogen_conversation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#!/usr/bin/env python3
"""
AutoGen Multi-Agent Conversation with STRATIX Instrumentation

Demonstrates a multi-agent conversation where agents collaborate to solve
a task, with STRATIX tracing of message exchanges and tool usage.

Requirements:
pip install pyautogen

Set OPENAI_API_KEY in your environment before running.
"""

from __future__ import annotations

import argparse
import os
import sys

try:
import autogen
from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager
except ImportError:
sys.exit(
"This sample requires autogen. Install with:\n"
" pip install pyautogen"
)

from layerlens.instrument import STRATIX, emit_handoff


def main():
parser = argparse.ArgumentParser(description="AutoGen multi-agent conversation with STRATIX tracing")
parser.add_argument("--task", default="Write a Python function to compute the Fibonacci sequence and test it.")
parser.add_argument("--model", default="gpt-4o-mini")
parser.add_argument("--agent-id", default="autogen-conversation-demo")
parser.add_argument("--policy", default="stratix-demo@1.0.0")
args = parser.parse_args()

if not os.environ.get("OPENAI_API_KEY"):
sys.exit("Set OPENAI_API_KEY environment variable before running this sample.")

# Initialize STRATIX
stratix = STRATIX(
policy_ref=args.policy,
agent_id=args.agent_id,
framework="autogen",
)
ctx = stratix.start_trial()
stratix.emit_input(args.task)

# LLM config
llm_config = {
"config_list": [{"model": args.model, "api_key": os.environ["OPENAI_API_KEY"]}],
"temperature": 0,
}

# Define agents
coder = AssistantAgent(
name="Coder",
system_message=(
"You are a senior Python developer. Write clean, well-documented code. "
"When you produce code, wrap it in ```python blocks."
),
llm_config=llm_config,
)

reviewer = AssistantAgent(
name="Reviewer",
system_message=(
"You are a code reviewer. Review the code for correctness, style, and "
"edge cases. Suggest improvements if needed. Say APPROVED when satisfied."
),
llm_config=llm_config,
)

executor = UserProxyAgent(
name="Executor",
human_input_mode="NEVER",
max_consecutive_auto_reply=3,
code_execution_config={"work_dir": "/tmp/autogen_work", "use_docker": False},
system_message="Execute code and report results. Terminate when the task is complete.",
)

# Set up group chat
group_chat = GroupChat(
agents=[coder, reviewer, executor],
messages=[],
max_round=8,
speaker_selection_method="round_robin",
)
manager = GroupChatManager(groupchat=group_chat, llm_config=llm_config)

print(f"Task: {args.task}\n")
print("Starting multi-agent conversation...\n")

# Run the conversation
executor.initiate_chat(manager, message=args.task)

# Collect final output
final_messages = [
msg.get("content", "") for msg in group_chat.messages if msg.get("content")
]
output = final_messages[-1] if final_messages else "(no output)"
print(f"\nFinal output:\n{output[:500]}{'...' if len(output) > 500 else ''}\n")
stratix.emit_output(output[:1000])

# Summary
summary = stratix.end_trial()
events = stratix.get_events()
print(f"\n--- STRATIX Trace Summary ---")
print(f"Status: {summary.get('status')}")
print(f"Captured {len(events)} events:")
for e in events:
print(f" {e.get_event_type()}: {str(e.payload)[:80]}")


if __name__ == "__main__":
main()
104 changes: 104 additions & 0 deletions samples/adapters/frameworks/browseruse_web_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""
BrowserUse Web Browsing Agent with STRATIX Instrumentation

Demonstrates a BrowserUse agent that navigates the web to complete tasks,
with STRATIX tracing of navigation steps, page interactions, and results.

Requirements:
pip install browser-use langchain-openai

Set OPENAI_API_KEY in your environment before running.
"""

from __future__ import annotations

import argparse
import asyncio
import os
import sys

try:
from browser_use import Agent as BrowserAgent
from langchain_openai import ChatOpenAI
except ImportError:
sys.exit(
"This sample requires browser-use. Install with:\n"
" pip install browser-use langchain-openai"
)

from layerlens.instrument import STRATIX


async def run_browser_agent(args):
"""Execute the browser agent with STRATIX tracing."""
# Initialize STRATIX
stratix = STRATIX(
policy_ref=args.policy,
agent_id=args.agent_id,
framework="langchain",
)
ctx = stratix.start_trial()
stratix.emit_input(args.task)

# Configure LLM
llm = ChatOpenAI(model=args.model, temperature=0)

# Create browser agent
agent = BrowserAgent(
task=args.task,
llm=llm,
max_actions_per_step=3,
)

print(f"Task: {args.task}\n")
print("Running browser agent (this may take a moment)...\n")

# Run the agent
result = await agent.run(max_steps=args.max_steps)

# Extract and display results
output = str(result)
print(f"Result:\n{output[:600]}{'...' if len(output) > 600 else ''}\n")

# Show action history if available
history = getattr(agent, "history", None)
if history:
print(f"Actions taken ({len(history)}):")
for i, action in enumerate(history, 1):
action_str = str(action)[:100]
print(f" {i}. {action_str}")
print()

stratix.emit_output(output[:1000])

# Summary
summary = stratix.end_trial()
events = stratix.get_events()
print(f"\n--- STRATIX Trace Summary ---")
print(f"Status: {summary.get('status')}")
print(f"Captured {len(events)} events:")
for e in events:
print(f" {e.get_event_type()}: {str(e.payload)[:80]}")


def main():
parser = argparse.ArgumentParser(description="BrowserUse web agent with STRATIX tracing")
parser.add_argument(
"--task",
default="Go to the Python Package Index (pypi.org) and find the latest version of the 'requests' library.",
)
parser.add_argument("--model", default="gpt-4o-mini")
parser.add_argument("--max-steps", type=int, default=5)
parser.add_argument("--agent-id", default="browseruse-agent-demo")
parser.add_argument("--policy", default="stratix-demo@1.0.0")
args = parser.parse_args()

if not os.environ.get("OPENAI_API_KEY"):
sys.exit("Set OPENAI_API_KEY environment variable before running this sample.")

asyncio.run(run_browser_agent(args))


if __name__ == "__main__":
main()
Loading
Loading