同步完整源码 - 2026-05-25
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
import time
|
||||
|
||||
|
||||
"""
|
||||
Benchmark script for measuring global tracer initialization time.
|
||||
"""
|
||||
|
||||
|
||||
def run_benchmark():
|
||||
"""
|
||||
Run a benchmark of global tracer initialization.
|
||||
|
||||
Returns:
|
||||
Dictionary with timing results
|
||||
"""
|
||||
import agentops
|
||||
|
||||
# Measure initialization time
|
||||
start_init = time.time()
|
||||
agentops.init()
|
||||
end_init = time.time()
|
||||
init_time = end_init - start_init
|
||||
|
||||
return {
|
||||
"init": init_time,
|
||||
"total": init_time, # Total time is just init time now
|
||||
}
|
||||
|
||||
|
||||
def print_results(results):
|
||||
"""
|
||||
Print benchmark results in a formatted way.
|
||||
|
||||
Args:
|
||||
results: Dictionary with timing results
|
||||
"""
|
||||
print("\n=== BENCHMARK RESULTS ===")
|
||||
|
||||
print(f"\nINIT TIME: {results['init']:.6f}s")
|
||||
print(f"TOTAL TIME: {results['total']:.6f}s")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Running global tracer benchmark...")
|
||||
results = run_benchmark()
|
||||
print_results(results)
|
||||
@@ -0,0 +1,10 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def runtime():
|
||||
class _BagOfGoodies(object):
|
||||
config_mock_applied = False
|
||||
pass
|
||||
|
||||
yield _BagOfGoodies()
|
||||
@@ -0,0 +1,18 @@
|
||||
import concurrent.futures
|
||||
import requests
|
||||
|
||||
|
||||
def fetch_url(url):
|
||||
response = requests.get(url)
|
||||
return response
|
||||
|
||||
|
||||
url = "http://localhost:9696/completion"
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor() as executor:
|
||||
futures = [executor.submit(fetch_url, url), executor.submit(fetch_url, url)]
|
||||
responses = [future.result() for future in concurrent.futures.as_completed(futures)]
|
||||
|
||||
response1, response2 = responses
|
||||
print(response1.text)
|
||||
print(response2.text)
|
||||
@@ -0,0 +1,37 @@
|
||||
import agentops
|
||||
from fastapi import FastAPI
|
||||
import uvicorn
|
||||
from dotenv import load_dotenv
|
||||
from agentops import record_tool
|
||||
from openai import OpenAI
|
||||
import time
|
||||
|
||||
load_dotenv()
|
||||
|
||||
openai = OpenAI()
|
||||
agentops.init(auto_start_session=False)
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.get("/completion")
|
||||
def completion():
|
||||
start_time = time.time()
|
||||
|
||||
session = agentops.start_session(tags=["api-server-test"])
|
||||
|
||||
@record_tool(tool_name="foo")
|
||||
def foo(x: str):
|
||||
print(x)
|
||||
|
||||
foo("Hello")
|
||||
|
||||
session.end_session(end_state="Success")
|
||||
|
||||
end_time = time.time()
|
||||
execution_time = end_time - start_time
|
||||
|
||||
return {"response": "Done", "execution_time_seconds": round(execution_time, 3)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
|
||||
@@ -0,0 +1,15 @@
|
||||
# API server test
|
||||
This is a manual test with two files. It checks to make sure that the SDK works in an API environment.
|
||||
|
||||
## Running the FastAPI Server
|
||||
You can run FastAPI with:
|
||||
1. `uvicorn main:app --reload`
|
||||
2. To test, run `curl http://localhost:8000/completion` in a different terminal.
|
||||
|
||||
## Validate
|
||||
Check in your AgentOps Dashboard
|
||||
|
||||
1. two sessions are created with the `api-server-test` tag.
|
||||
2. Each session should have one `LLMEvent` and one `ActionEvent`.
|
||||
3. Both sessions should have an end state of `Success`
|
||||
4. Neither session should have multiple agents
|
||||
@@ -0,0 +1,46 @@
|
||||
# logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
|
||||
import openai
|
||||
from pyinstrument import Profiler
|
||||
|
||||
import agentops
|
||||
|
||||
|
||||
def make_openai_call():
|
||||
client = openai.Client()
|
||||
return client.chat.completions.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a chatbot."},
|
||||
{"role": "user", "content": "What are you talking about?"},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
# Initialize profiler
|
||||
profiler = Profiler()
|
||||
profiler.start()
|
||||
|
||||
try:
|
||||
# Initialize AgentOps with auto_start_session=False
|
||||
agentops.init(auto_start_session=False)
|
||||
# Start a single test session
|
||||
session = agentops.start_session()
|
||||
assert session is not None
|
||||
|
||||
# Make multiple calls
|
||||
responses = []
|
||||
# Make 20 sequential calls for benchmarking
|
||||
for _ in range(1):
|
||||
responses.append(make_openai_call())
|
||||
|
||||
# End the session properly
|
||||
session.end_session(end_state="Success")
|
||||
|
||||
finally:
|
||||
# Stop profiling and print results
|
||||
profiler.stop()
|
||||
# with open("profiling_reports/{}.txt".format(datetime.now(timezone.utc).isoformat()), "w") as f:
|
||||
# f.write(profiler.output_text(unicode=True, color=False))
|
||||
print(profiler.output_text(unicode=True, color=True))
|
||||
@@ -0,0 +1,25 @@
|
||||
import agentops
|
||||
from openai import OpenAI
|
||||
from dotenv import load_dotenv
|
||||
from agentops import ActionEvent
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["canary"])
|
||||
openai = OpenAI()
|
||||
|
||||
messages = [{"role": "user", "content": "Hello"}]
|
||||
|
||||
# option 1: use session.patch
|
||||
response = openai.chat.completions.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=messages,
|
||||
temperature=0.5,
|
||||
)
|
||||
|
||||
agentops.record(ActionEvent(action_type="test event"))
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with one LLM event
|
||||
###
|
||||
@@ -0,0 +1 @@
|
||||
{"messages": "[]"}
|
||||
@@ -0,0 +1,35 @@
|
||||
import agentops
|
||||
from openai import OpenAI
|
||||
from dotenv import load_dotenv
|
||||
from agentops import ActionEvent
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(auto_start_session=False)
|
||||
openai = OpenAI()
|
||||
|
||||
session_1 = agentops.start_session(tags=["multi-session-test-1"])
|
||||
session_2 = agentops.start_session(tags=["multi-session-test-2"])
|
||||
|
||||
print("session_id_1: {}".format(session_1))
|
||||
print("session_id_2: {}".format(session_2))
|
||||
|
||||
messages = [{"role": "user", "content": "Hello"}]
|
||||
|
||||
# option 1: use session.patch
|
||||
response = session_1.patch(openai.chat.completions.create)(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=messages,
|
||||
temperature=0.5,
|
||||
)
|
||||
|
||||
session_1.record(ActionEvent(action_type="test event"))
|
||||
|
||||
# option 2: add session as a keyword argument
|
||||
response2 = openai.chat.completions.create(model="gpt-3.5-turbo", messages=messages, temperature=0.5, session=session_2)
|
||||
|
||||
session_1.end_session(end_state="Success")
|
||||
session_2.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that two sessions are created, each with one LLM event
|
||||
###
|
||||
@@ -0,0 +1,64 @@
|
||||
import asyncio
|
||||
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
import ai21
|
||||
from ai21.models.chat import ChatMessage
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["ai21-provider-test"])
|
||||
|
||||
api_key = os.getenv("AI2I_API_KEY")
|
||||
ai21_client = ai21.AI21Client(api_key=api_key)
|
||||
async_ai21_client = ai21.AsyncAI21Client(api_key=api_key)
|
||||
|
||||
messages = [
|
||||
ChatMessage(content="You are an expert mathematician.", role="system"),
|
||||
ChatMessage(
|
||||
content="Write a summary of 5 lines on the Shockley diode equation.",
|
||||
role="user",
|
||||
),
|
||||
]
|
||||
|
||||
response = ai21_client.chat.completions.create(
|
||||
model="jamba-1.5-mini",
|
||||
messages=messages,
|
||||
)
|
||||
|
||||
|
||||
stream_response = ai21_client.chat.completions.create(
|
||||
model="jamba-1.5-mini",
|
||||
messages=messages,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
response = ""
|
||||
for chunk in stream_response:
|
||||
response += chunk.choices[0].delta.content
|
||||
print(response)
|
||||
|
||||
|
||||
async def async_test():
|
||||
async_response = await async_ai21_client.chat.completions.create(
|
||||
model="jamba-1.5-mini",
|
||||
messages=messages,
|
||||
)
|
||||
print(async_response)
|
||||
|
||||
|
||||
asyncio.run(async_test())
|
||||
|
||||
agentops.stop_instrumenting()
|
||||
|
||||
untracked_response = ai21_client.chat.completions.create(
|
||||
model="jamba-1.5-mini",
|
||||
messages=messages,
|
||||
)
|
||||
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with one LLM event
|
||||
###
|
||||
@@ -0,0 +1,78 @@
|
||||
import asyncio
|
||||
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import anthropic
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["anthropic-provider-test"])
|
||||
anthropic_client = anthropic.Anthropic()
|
||||
async_anthropic_client = anthropic.AsyncAnthropic()
|
||||
|
||||
response = anthropic_client.messages.create(
|
||||
max_tokens=1024,
|
||||
model="claude-3-5-sonnet-20240620",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "say hi",
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
stream_response = anthropic_client.messages.create(
|
||||
max_tokens=1024,
|
||||
model="claude-3-5-sonnet-20240620",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "say hi 2",
|
||||
}
|
||||
],
|
||||
stream=True,
|
||||
)
|
||||
|
||||
response = ""
|
||||
for event in stream_response:
|
||||
if event.type == "content_block_delta":
|
||||
response += event.delta.text
|
||||
elif event.type == "message_stop":
|
||||
print(response)
|
||||
|
||||
|
||||
async def async_test():
|
||||
async_response = await async_anthropic_client.messages.create(
|
||||
max_tokens=1024,
|
||||
model="claude-3-5-sonnet-20240620",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "say hi 3",
|
||||
}
|
||||
],
|
||||
)
|
||||
print(async_response)
|
||||
|
||||
|
||||
asyncio.run(async_test())
|
||||
|
||||
agentops.stop_instrumenting()
|
||||
|
||||
untracked_response = anthropic_client.messages.create(
|
||||
max_tokens=1024,
|
||||
model="claude-3-5-sonnet-20240620",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "say hi 4",
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with one LLM event
|
||||
###
|
||||
@@ -0,0 +1,45 @@
|
||||
import asyncio
|
||||
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import cohere
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["cohere-provider-test"])
|
||||
co = cohere.Client()
|
||||
aco = cohere.AsyncClient()
|
||||
|
||||
chat = co.chat(message="say hi 1")
|
||||
|
||||
stream = co.chat_stream(message="say hi 2")
|
||||
response = ""
|
||||
for event in stream:
|
||||
if event.event_type == "text-generation":
|
||||
response += event.text
|
||||
print(event.text, end="")
|
||||
elif event.event_type == "stream-end":
|
||||
print("\n")
|
||||
print(event)
|
||||
print("\n")
|
||||
|
||||
|
||||
async def main():
|
||||
async_response = await aco.chat(message="say hi 3")
|
||||
print(async_response)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
agentops.stop_instrumenting()
|
||||
|
||||
# for cohere, because the client is not a singleton, calling `stop_instrumenting()` only affects
|
||||
# new clients created, not existing clients.
|
||||
|
||||
co_untracked = cohere.Client()
|
||||
chat_untracked = co_untracked.chat(message="say hi untracked")
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with one LLM event
|
||||
###
|
||||
@@ -0,0 +1,60 @@
|
||||
import asyncio
|
||||
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
from groq import Groq, AsyncGroq
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["groq-provider-test"])
|
||||
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
||||
async_groq_client = AsyncGroq(api_key=os.getenv("GROQ_API_KEY"))
|
||||
|
||||
messages = [{"role": "user", "content": "Hello"}]
|
||||
|
||||
# option 1: use session.patch
|
||||
res = groq_client.chat.completions.create(
|
||||
model="llama3-70b-8192",
|
||||
messages=[
|
||||
{"role": "user", "content": "Say hello"},
|
||||
],
|
||||
)
|
||||
|
||||
stream_res = groq_client.chat.completions.create(
|
||||
model="llama3-70b-8192",
|
||||
messages=[
|
||||
{"role": "user", "content": "Say hello"},
|
||||
],
|
||||
stream=True,
|
||||
)
|
||||
|
||||
for chunk in stream_res:
|
||||
print(chunk)
|
||||
|
||||
|
||||
async def async_test():
|
||||
async_res = await async_groq_client.chat.completions.create(
|
||||
model="llama3-70b-8192",
|
||||
messages=[
|
||||
{"role": "user", "content": "Say hello"},
|
||||
],
|
||||
)
|
||||
print(async_res)
|
||||
|
||||
|
||||
asyncio.run(async_test())
|
||||
|
||||
agentops.stop_instrumenting()
|
||||
|
||||
untracked_res = groq_client.chat.completions.create(
|
||||
model="llama3-70b-8192",
|
||||
messages=[
|
||||
{"role": "user", "content": "Say hello"},
|
||||
],
|
||||
)
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with one LLM event
|
||||
###
|
||||
@@ -0,0 +1,42 @@
|
||||
import asyncio
|
||||
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import litellm
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["litellm-provider-test"])
|
||||
|
||||
response = litellm.completion(model="gpt-3.5-turbo", messages=[{"content": "Hello, how are you?", "role": "user"}])
|
||||
|
||||
stream_response = litellm.completion(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"content": "Hello, how are you?", "role": "user"}],
|
||||
stream=True,
|
||||
)
|
||||
print(stream_response)
|
||||
for chunk in stream_response:
|
||||
print(chunk)
|
||||
|
||||
|
||||
async def main():
|
||||
async_response = await litellm.acompletion(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"content": "Hello, how are you?", "role": "user"}],
|
||||
)
|
||||
print(async_response)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
agentops.stop_instrumenting()
|
||||
|
||||
untracked_response = litellm.completion(
|
||||
model="gpt-3.5-turbo", messages=[{"content": "Hello, how are you?", "role": "user"}]
|
||||
)
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with one LLM event
|
||||
###
|
||||
@@ -0,0 +1,83 @@
|
||||
import agentops
|
||||
import asyncio
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from llama_stack_client import LlamaStackClient
|
||||
from llama_stack_client.lib.agents.agent import Agent
|
||||
from llama_stack_client.lib.agents.event_logger import EventLogger
|
||||
from llama_stack_client.types.agent_create_params import AgentConfig
|
||||
|
||||
load_dotenv()
|
||||
|
||||
agentops.init(os.getenv("AGENTOPS_API_KEY"), default_tags=["llama-stack-client-example"], auto_start_session=False)
|
||||
|
||||
LLAMA_STACK_HOST = "0.0.0.0"
|
||||
LLAMA_STACK_PORT = 5001
|
||||
INFERENCE_MODEL = "meta-llama/Llama-3.2-1B-Instruct"
|
||||
|
||||
|
||||
async def agent_test():
|
||||
client = LlamaStackClient(
|
||||
base_url=f"http://{LLAMA_STACK_HOST}:{LLAMA_STACK_PORT}",
|
||||
)
|
||||
|
||||
available_shields = [shield.identifier for shield in client.shields.list()]
|
||||
if not available_shields:
|
||||
print("No available shields. Disable safety.")
|
||||
else:
|
||||
print(f"Available shields found: {available_shields}")
|
||||
available_models = [model.identifier for model in client.models.list()]
|
||||
if not available_models:
|
||||
raise ValueError("No available models")
|
||||
else:
|
||||
selected_model = available_models[0]
|
||||
print(f"Using model: {selected_model}")
|
||||
|
||||
agent_config = AgentConfig(
|
||||
model=selected_model,
|
||||
instructions="You are a helpful assistant. Just say hello as a greeting.",
|
||||
sampling_params={
|
||||
"strategy": "greedy",
|
||||
"temperature": 1.0,
|
||||
"top_p": 0.9,
|
||||
},
|
||||
tools=[
|
||||
{
|
||||
"type": "brave_search",
|
||||
"engine": "brave",
|
||||
"api_key": os.getenv("BRAVE_SEARCH_API_KEY"),
|
||||
}
|
||||
],
|
||||
tool_choice="auto",
|
||||
tool_prompt_format="json",
|
||||
input_shields=available_shields if available_shields else [],
|
||||
output_shields=available_shields if available_shields else [],
|
||||
enable_session_persistence=False,
|
||||
)
|
||||
agent = Agent(client, agent_config)
|
||||
user_prompts = [
|
||||
"Hello",
|
||||
"Which players played in the winning team of the NBA western conference semifinals of 2014, please use tools",
|
||||
]
|
||||
|
||||
session_id = agent.create_session("test-session")
|
||||
|
||||
for prompt in user_prompts:
|
||||
response = agent.create_turn(
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": prompt,
|
||||
}
|
||||
],
|
||||
session_id=session_id,
|
||||
)
|
||||
|
||||
for log in EventLogger().log(response):
|
||||
log.print()
|
||||
|
||||
|
||||
agentops.start_session()
|
||||
asyncio.run(agent_test())
|
||||
agentops.end_session(end_state="Success")
|
||||
@@ -0,0 +1,45 @@
|
||||
import asyncio
|
||||
import agentops
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from llama_stack_client import LlamaStackClient
|
||||
from llama_stack_client.types import UserMessage
|
||||
from llama_stack_client.lib.inference.event_logger import EventLogger
|
||||
|
||||
load_dotenv()
|
||||
|
||||
agentops.init(os.getenv("AGENTOPS_API_KEY"), default_tags=["llama-stack-client-example"], auto_start_session=False)
|
||||
|
||||
host = "0.0.0.0" # LLAMA_STACK_HOST
|
||||
port = 5001 # LLAMA_STACK_PORT
|
||||
|
||||
full_host = f"http://{host}:{port}"
|
||||
|
||||
client = LlamaStackClient(
|
||||
base_url=f"{full_host}",
|
||||
)
|
||||
|
||||
|
||||
async def stream_test():
|
||||
response = client.inference.chat_completion(
|
||||
messages=[
|
||||
UserMessage(
|
||||
content="hello world, write me a 3 word poem about the moon",
|
||||
role="user",
|
||||
),
|
||||
],
|
||||
model_id="meta-llama/Llama-3.2-1B-Instruct",
|
||||
stream=True,
|
||||
)
|
||||
|
||||
async for log in EventLogger().log(response):
|
||||
log.print()
|
||||
|
||||
|
||||
def main():
|
||||
agentops.start_session()
|
||||
asyncio.run(stream_test())
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,57 @@
|
||||
import agentops
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from llama_stack_client import LlamaStackClient
|
||||
from llama_stack_client.types import UserMessage
|
||||
from llama_stack_client.lib.inference.event_logger import EventLogger
|
||||
|
||||
load_dotenv()
|
||||
|
||||
agentops.init(os.getenv("AGENTOPS_API_KEY"), default_tags=["llama-stack-client-example"], auto_start_session=False)
|
||||
|
||||
host = "0.0.0.0" # LLAMA_STACK_HOST
|
||||
port = 5001 # LLAMA_STACK_PORT
|
||||
|
||||
full_host = f"http://{host}:{port}"
|
||||
|
||||
client = LlamaStackClient(
|
||||
base_url=f"{full_host}",
|
||||
)
|
||||
|
||||
|
||||
async def stream_test():
|
||||
response = client.inference.chat_completion(
|
||||
messages=[
|
||||
UserMessage(
|
||||
content="hello world, write me a 3 word poem about the moon",
|
||||
role="user",
|
||||
),
|
||||
],
|
||||
model_id="meta-llama/Llama-3.2-1B-Instruct",
|
||||
stream=True,
|
||||
)
|
||||
|
||||
async for log in EventLogger().log(response):
|
||||
log.print()
|
||||
|
||||
|
||||
def main():
|
||||
agentops.start_session()
|
||||
|
||||
response = client.inference.chat_completion(
|
||||
messages=[
|
||||
UserMessage(
|
||||
content="hello world, write me a 3 word poem about the moon",
|
||||
role="user",
|
||||
),
|
||||
],
|
||||
model_id="meta-llama/Llama-3.2-1B-Instruct",
|
||||
stream=False,
|
||||
)
|
||||
|
||||
print(response.completion_message.content)
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
import asyncio
|
||||
|
||||
import agentops
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from mistralai import Mistral
|
||||
|
||||
load_dotenv()
|
||||
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
|
||||
|
||||
agentops.init(default_tags=["mistral-provider-test"])
|
||||
client = Mistral(MISTRAL_API_KEY)
|
||||
|
||||
response = client.chat.complete(
|
||||
model="open-mistral-nemo",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Say Hello",
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
stream_response = client.chat.stream(
|
||||
model="open-mistral-nemo",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Say Hello again",
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
response = ""
|
||||
for event in stream_response:
|
||||
if event.data.choices[0].finish_reason == "stop":
|
||||
print(response)
|
||||
else:
|
||||
response += event.data.choices[0].delta.content
|
||||
|
||||
|
||||
async def async_test():
|
||||
async_response = await client.chat.complete_async(
|
||||
model="open-mistral-nemo",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Say Hello in the Hindi language",
|
||||
}
|
||||
],
|
||||
)
|
||||
print(async_response.choices[0].message.content)
|
||||
|
||||
|
||||
async def async_stream_test():
|
||||
async_stream_response = await client.chat.stream_async(
|
||||
model="open-mistral-nemo",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "Say Hello in the Japanese language",
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
response = ""
|
||||
async for event in async_stream_response:
|
||||
if event.data.choices[0].finish_reason == "stop":
|
||||
print(response)
|
||||
else:
|
||||
response += event.data.choices[0].delta.content
|
||||
|
||||
|
||||
async def main():
|
||||
await async_test()
|
||||
await async_stream_test()
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with one LLM event
|
||||
###
|
||||
@@ -0,0 +1,58 @@
|
||||
import asyncio
|
||||
|
||||
import agentops
|
||||
from dotenv import load_dotenv
|
||||
import ollama
|
||||
from ollama import AsyncClient
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["ollama-provider-test"])
|
||||
|
||||
response = ollama.chat(
|
||||
model="llama3.1",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "say hello sync",
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
stream_response = ollama.chat(
|
||||
model="llama3.1",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "say hello str",
|
||||
},
|
||||
],
|
||||
stream=True,
|
||||
)
|
||||
for chunk in stream_response:
|
||||
print(chunk)
|
||||
|
||||
|
||||
async def main():
|
||||
message = {"role": "user", "content": "say hello mr. async"}
|
||||
await AsyncClient().chat(model="llama3.1", messages=[message])
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
agentops.stop_instrumenting()
|
||||
|
||||
untracked_response = ollama.chat(
|
||||
model="llama3.1",
|
||||
messages=[
|
||||
{
|
||||
"role": "user",
|
||||
"content": "say hello",
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with one LLM event
|
||||
###
|
||||
@@ -0,0 +1,96 @@
|
||||
import agentops
|
||||
from openai import OpenAI
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["openai-assistants-test"])
|
||||
openai = OpenAI()
|
||||
|
||||
try:
|
||||
# Basic Assistant Creation
|
||||
assistant = openai.beta.assistants.create(
|
||||
name="Math Tutor",
|
||||
instructions="You are a personal math tutor. Write and run code to answer math questions.",
|
||||
tools=[{"type": "code_interpreter"}],
|
||||
model="gpt-4o-mini",
|
||||
)
|
||||
print(f"\nCreated assistant: {assistant.id}")
|
||||
print(f"Assistant name: {assistant.name}")
|
||||
print(f"Assistant instructions: {assistant.instructions}")
|
||||
print(f"Assistant model: {assistant.model}")
|
||||
print(f"Assistant tools: {assistant.tools}")
|
||||
|
||||
# Thread Creation and Message Handling
|
||||
thread = openai.beta.threads.create()
|
||||
print(f"\nCreated thread: {thread.id}")
|
||||
|
||||
# Add Multiple Messages
|
||||
message1 = openai.beta.threads.messages.create(
|
||||
thread_id=thread.id, role="user", content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
|
||||
)
|
||||
message2 = openai.beta.threads.messages.create(
|
||||
thread_id=thread.id, role="user", content="Also, what is the square root of 144?"
|
||||
)
|
||||
print("\nAdded messages:")
|
||||
print(f"Message 1 ID: {message1.id}")
|
||||
print(f"Message 1 content: {message1.content[0].text.value}")
|
||||
print(f"Message 2 ID: {message2.id}")
|
||||
print(f"Message 2 content: {message2.content[0].text.value}")
|
||||
|
||||
# Run Assistant with Multiple Questions
|
||||
run = openai.beta.threads.runs.create(thread_id=thread.id, assistant_id=assistant.id)
|
||||
print(f"\nStarted run: {run.id}")
|
||||
|
||||
# Run Status Monitoring
|
||||
while run.status not in ["completed", "failed"]:
|
||||
run = openai.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
|
||||
print(f"Run status: {run.status}")
|
||||
|
||||
if run.status == "failed":
|
||||
print("\nRun failed!")
|
||||
if run.last_error:
|
||||
print(f"Error code: {run.last_error.code}")
|
||||
print(f"Error message: {run.last_error.message}")
|
||||
|
||||
# Message Retrieval and Display
|
||||
messages = openai.beta.threads.messages.list(thread_id=thread.id)
|
||||
print("\nThread Messages:")
|
||||
for msg in reversed(messages.data):
|
||||
print(f"{msg.role.capitalize()}: {msg.content[0].text.value}")
|
||||
|
||||
# Assistant Update
|
||||
updated_assistant = openai.beta.assistants.update(
|
||||
assistant.id,
|
||||
name="Advanced Math Tutor",
|
||||
instructions="You are an advanced math tutor. Explain concepts in detail.",
|
||||
)
|
||||
print(f"\nUpdated assistant: {updated_assistant.id}")
|
||||
print(f"New name: {updated_assistant.name}")
|
||||
print(f"New instructions: {updated_assistant.instructions}")
|
||||
|
||||
# Run Step Retrieval
|
||||
run_steps = openai.beta.threads.runs.steps.list(thread_id=thread.id, run_id=run.id)
|
||||
print("\nRun Steps:")
|
||||
for step in run_steps.data:
|
||||
print(f"Step ID: {step.id}")
|
||||
print(f"Status: {step.status}")
|
||||
if hasattr(step.step_details, "message_creation"):
|
||||
print(f"Message ID: {step.step_details.message_creation.message_id}")
|
||||
|
||||
# Thread Update
|
||||
updated_thread = openai.beta.threads.update(thread.id, metadata={"test": "value"})
|
||||
print(f"\nUpdated thread: {updated_thread.id}")
|
||||
|
||||
# Message Retrieval and Display
|
||||
messages = openai.beta.threads.messages.list(thread_id=updated_thread.id)
|
||||
print("\nThread Messages:")
|
||||
for msg in reversed(messages.data):
|
||||
print(f"{msg.role.capitalize()}: {msg.content[0].text.value}")
|
||||
|
||||
finally:
|
||||
# Clean up
|
||||
if "assistant" in locals():
|
||||
openai.beta.assistants.delete(assistant.id)
|
||||
print(f"\nDeleted assistant: {assistant.id}")
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
@@ -0,0 +1,46 @@
|
||||
import agentops
|
||||
from openai import OpenAI
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
agentops.init(default_tags=["openai-v1-provider-test"])
|
||||
openai = OpenAI()
|
||||
async_openai = OpenAI()
|
||||
|
||||
|
||||
# option 1: use session.patch
|
||||
response = openai.chat.completions.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "user", "content": "Hello"}],
|
||||
temperature=0.5,
|
||||
)
|
||||
|
||||
stream_response = openai.chat.completions.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "user", "content": "Hello streamed"}],
|
||||
temperature=0.5,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
for chunk in stream_response:
|
||||
print(chunk)
|
||||
|
||||
async_response = async_openai.chat.completions.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "user", "content": "Hello async"}],
|
||||
temperature=0.5,
|
||||
)
|
||||
|
||||
agentops.stop_instrumenting()
|
||||
|
||||
not_tracked_response = openai.chat.completions.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[{"role": "user", "content": "Hello untracked"}],
|
||||
temperature=0.5,
|
||||
)
|
||||
|
||||
agentops.end_session(end_state="Success")
|
||||
|
||||
###
|
||||
# Used to verify that one session is created with two LLM events
|
||||
###
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
|
||||
from agentops import Client
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_client():
|
||||
"""Reset the client singleton before and after each test"""
|
||||
# Reset the Client singleton by resetting its class attributes
|
||||
if getattr(Client, "__instance", None):
|
||||
del Client.__instance
|
||||
yield
|
||||
# Reset again after the test
|
||||
Client.__instance = None
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_client(reset_client):
|
||||
# Resets the client with a clear env
|
||||
Client()
|
||||
yield
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def llm_event_spy(agentops_client, mocker: "MockerFixture") -> dict[str, "MockerFixture"]:
|
||||
"""
|
||||
Fixture that provides spies on both providers' response handling
|
||||
|
||||
These fixtures are reset on each test run (function scope). To use it,
|
||||
simply pass it as an argument to the test function. Example:
|
||||
|
||||
```
|
||||
def test_my_test(llm_event_spy):
|
||||
# test code here
|
||||
llm_event_spy["litellm"].assert_called_once()
|
||||
```
|
||||
"""
|
||||
from agentops.llms.providers.anthropic import AnthropicProvider
|
||||
from agentops.llms.providers.litellm import LiteLLMProvider
|
||||
from agentops.llms.providers.openai import OpenAiProvider
|
||||
|
||||
return {
|
||||
"litellm": mocker.spy(LiteLLMProvider(agentops_client), "handle_response"),
|
||||
"openai": mocker.spy(OpenAiProvider(agentops_client), "handle_response"),
|
||||
"anthropic": mocker.spy(AnthropicProvider(agentops_client), "handle_response"),
|
||||
}
|
||||
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
import builtins
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hide_available_pkg(monkeypatch):
|
||||
"""
|
||||
Hide the availability of a package by mocking the __import__ function.
|
||||
|
||||
Usage:
|
||||
@pytest.mark.usefixtures('hide_available_pkg')
|
||||
def test_message():
|
||||
with pytest.raises(ImportError, match='Install "pkg" to use test_function'):
|
||||
foo('test_function')
|
||||
|
||||
Source:
|
||||
https://stackoverflow.com/questions/60227582/making-a-python-test-think-an-installed-package-is-not-available
|
||||
"""
|
||||
import_orig = builtins.__import__
|
||||
|
||||
def mocked_import(name, *args, **kwargs):
|
||||
if name == "pkg":
|
||||
raise ImportError()
|
||||
return import_orig(name, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(builtins, "__import__", mocked_import)
|
||||
Vendored
+98
@@ -0,0 +1,98 @@
|
||||
import os
|
||||
import pytest
|
||||
import litellm
|
||||
from openai import OpenAI
|
||||
from anthropic import Anthropic
|
||||
from ai21 import AI21Client, AsyncAI21Client
|
||||
from cohere import Client as CohereClient
|
||||
from groq import Groq
|
||||
from mistralai import Mistral
|
||||
from ai21.models.chat import ChatMessage
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
# Test messages for different providers
|
||||
@pytest.fixture
|
||||
def test_messages():
|
||||
return [
|
||||
{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Write a short greeting."},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ai21_test_messages():
|
||||
return [
|
||||
ChatMessage(content="You are an expert mathematician.", role="system"),
|
||||
ChatMessage(
|
||||
content="Write a summary of 5 lines on the Shockley diode equation.",
|
||||
role="user",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# Client fixtures
|
||||
@pytest.fixture
|
||||
def openai_client():
|
||||
"""Initialize OpenAI client."""
|
||||
api_key = os.getenv("OPENAI_API_KEY", "test-api-key")
|
||||
return OpenAI(api_key=api_key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anthropic_client():
|
||||
"""Initialize Anthropic client."""
|
||||
api_key = os.getenv("ANTHROPIC_API_KEY", "test-api-key")
|
||||
return Anthropic(api_key=api_key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ai21_client():
|
||||
"""Initialize AI21 sync client."""
|
||||
api_key = os.getenv("AI21_API_KEY", "test-api-key")
|
||||
return AI21Client(api_key=api_key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ai21_async_client():
|
||||
"""Initialize AI21 async client."""
|
||||
api_key = os.getenv("AI21_API_KEY", "test-api-key")
|
||||
return AsyncAI21Client(api_key=api_key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohere_client():
|
||||
"""Initialize Cohere client."""
|
||||
api_key = os.getenv("COHERE_API_KEY", "test-api-key")
|
||||
return CohereClient(api_key=api_key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def groq_client():
|
||||
"""Initialize Groq client."""
|
||||
api_key = os.getenv("GROQ_API_KEY", "test-api-key")
|
||||
return Groq(api_key=api_key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mistral_client():
|
||||
"""Initialize Mistral client."""
|
||||
api_key = os.getenv("MISTRAL_API_KEY", "test-api-key")
|
||||
return Mistral(api_key=api_key)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def litellm_client():
|
||||
"""Initialize LiteLLM client."""
|
||||
|
||||
openai_key = os.getenv("OPENAI_API_KEY", "test-api-key")
|
||||
anthropic_key = os.getenv("ANTHROPIC_API_KEY", "test-api-key")
|
||||
openrouter_key = os.getenv("OPENROUTER_API_KEY", "test-api-key")
|
||||
|
||||
litellm.openai_key = openai_key
|
||||
litellm.anthropic_key = anthropic_key
|
||||
litellm.openrouter_key = openrouter_key
|
||||
|
||||
return litellm
|
||||
+543
@@ -0,0 +1,543 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"model": "jamba-1.5-mini", "messages": [{"role": "system", "content":
|
||||
"You are an expert mathematician."}, {"role": "user", "content": "Write a summary
|
||||
of 5 lines on the Shockley diode equation."}], "stream": false}'
|
||||
headers:
|
||||
accept:
|
||||
- '*/*'
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '216'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.ai21.com
|
||||
user-agent:
|
||||
- AI21 studio SDK 2.15.2 Python 3.10.16 Operating System macOS-15.2-arm64-arm-64bit
|
||||
method: POST
|
||||
uri: https://api.ai21.com/studio/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: '{"id":"chatcmpl-549f4199-3264-729e-a529-cda4502f0f48","choices":[{"index":0,"message":{"role":"assistant","content":"The
|
||||
Shockley diode equation, also known as the diode law, describes the current-voltage
|
||||
characteristics of a diode. It is given by $$I = I_S \\left( e^{\\frac{V}{n
|
||||
V_T}} - 1 \\right)$$\n\n, where $$I$$\n\n is the diode current, $$I_S$$\n\n
|
||||
is the reverse saturation current, $$V$$\n\n is the applied voltage, $$n$$\n\n
|
||||
is the ideality factor, and $$V_T$$\n\n is the thermal voltage. The equation
|
||||
highlights the exponential relationship between the voltage across the diode
|
||||
and the current through it, with the ideality factor $$n$$\n\n accounting
|
||||
for deviations from ideal behavior. This model is fundamental in understanding
|
||||
semiconductor diode operation in circuits.","tool_calls":null},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":30,"completion_tokens":162,"total_tokens":192}}'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:34 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Strict-Transport-Security:
|
||||
- max-age=15552000; includeSubDomains
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
content-length:
|
||||
- '919'
|
||||
request-id:
|
||||
- 549f4199-3264-729e-a529-cda4502f0f48
|
||||
via:
|
||||
- 1.1 google
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"model": "jamba-1.5-mini", "messages": [{"role": "system", "content":
|
||||
"You are an expert mathematician."}, {"role": "user", "content": "Write a summary
|
||||
of 5 lines on the Shockley diode equation."}], "stream": true}'
|
||||
headers:
|
||||
accept:
|
||||
- '*/*'
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '215'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.ai21.com
|
||||
user-agent:
|
||||
- AI21 studio SDK 2.15.2 Python 3.10.16 Operating System macOS-15.2-arm64-arm-64bit
|
||||
method: POST
|
||||
uri: https://api.ai21.com/studio/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: "data: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\", \"choices\":
|
||||
[{\"index\": 0, \"delta\": {\"role\": \"assistant\"}, \"logprobs\": null,
|
||||
\"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"The\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" Shock\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"ley\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" diode\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" equation\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" also\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" known\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" as\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" diode\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" law\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" describes\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" current\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"-\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"voltage\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" characteristic\"},
|
||||
\"logprobs\": null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" of\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" a\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" diode\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \".\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" It\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" is\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" given\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" by\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" $$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"I\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" =\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" I\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"_\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"S\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" \\\\\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"left\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"(\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" e\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"^{\\\\\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"frac\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"{\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"V\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"}{\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" V\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"_\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"T\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"}}\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" -\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" \"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"1\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" \\\\\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"right\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \")$$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" where\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" $$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"I\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"$$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" is\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" diode\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" current\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" $$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"I\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"_\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"S\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"$$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" is\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" reverse\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" saturation\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" current\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" $$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"V\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"$$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" is\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" voltage\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" across\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" diode\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" $$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"$$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" is\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" ide\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"ality\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" factor\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" and\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" $$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"V\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"_\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"T\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"$$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" is\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" thermal\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" voltage\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \".\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" The\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" equation\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" accounts\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" for\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" exponential\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" increase\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" in\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" current\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" with\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" increasing\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" forward\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" voltage\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" while\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" term\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" $$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"e\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"^{\\\\\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"frac\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"{\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"V\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"}{\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" V\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"_\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"T\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"}}\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" -\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" \"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"1\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"$$\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\\n\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" ensures\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" the\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" current\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" is\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" very\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" small\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" for\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" reverse\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" volt\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"ages\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \".\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" This\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" model\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" developed\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" by\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" William\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" Shock\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"ley\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \",\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" is\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" fundamental\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" in\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" understanding\"},
|
||||
\"logprobs\": null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" and\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" analyzing\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" diode\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" behavior\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" in\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" electronic\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \" circuits\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \".\"}, \"logprobs\":
|
||||
null, \"finish_reason\": null}]}\r\n\r\ndata: {\"id\": \"chatcmpl-fb9ce6f7-20dc-d385-5fb2-90e86a364bc9\",
|
||||
\"choices\": [{\"index\": 0, \"delta\": {\"content\": \"\"}, \"logprobs\":
|
||||
null, \"finish_reason\": \"stop\"}], \"usage\": {\"prompt_tokens\": 30, \"completion_tokens\":
|
||||
184, \"total_tokens\": 214}}\r\n\r\ndata: [DONE]\r\n\r\n"
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- text/event-stream; charset=utf-8
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:34 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Strict-Transport-Security:
|
||||
- max-age=15552000; includeSubDomains
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
request-id:
|
||||
- fb9ce6f7-20dc-d385-5fb2-90e86a364bc9
|
||||
via:
|
||||
- 1.1 google
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"model": "jamba-1.5-mini", "messages": [{"role": "system", "content":
|
||||
"You are an expert mathematician."}, {"role": "user", "content": "Write a summary
|
||||
of 5 lines on the Shockley diode equation."}], "stream": false}'
|
||||
headers:
|
||||
accept:
|
||||
- '*/*'
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '216'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.ai21.com
|
||||
user-agent:
|
||||
- AI21 studio SDK 2.15.2 Python 3.10.16 Operating System macOS-15.2-arm64-arm-64bit
|
||||
method: POST
|
||||
uri: https://api.ai21.com/studio/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: '{"id":"chatcmpl-e8bd0279-192b-0d7d-d28c-734d0b0b13c9","choices":[{"index":0,"message":{"role":"assistant","content":"The
|
||||
Shockley diode equation, also known as the diode current equation, describes
|
||||
the current $$I$$\n\n through a diode as a function of the voltage $$V$$\n\n
|
||||
across it. It is given by $$I = I_S \\left( e^{\\frac{V}{n V_T}} - 1 \\right)$$\n\n,
|
||||
where $$I_S$$\n\n is the reverse saturation current, $$V$$\n\n is the voltage
|
||||
across the diode, $$n$$\n\n is the ideality factor, and $$V_T$$\n\n is the
|
||||
thermal voltage. This equation models the exponential increase of current
|
||||
with increasing voltage in a diode, accounting for the diode''s rectification
|
||||
behavior. The ideality factor $$n$$\n\n adjusts the curve to fit real diode
|
||||
characteristics, while $$V_T$$\n\n is approximately 26 millivolts at room
|
||||
temperature.","tool_calls":null},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":30,"completion_tokens":187,"total_tokens":217}}'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:37 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Strict-Transport-Security:
|
||||
- max-age=15552000; includeSubDomains
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
content-length:
|
||||
- '960'
|
||||
request-id:
|
||||
- e8bd0279-192b-0d7d-d28c-734d0b0b13c9
|
||||
via:
|
||||
- 1.1 google
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
@@ -0,0 +1,234 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"max_tokens": 1024, "messages": [{"role": "user", "content": "Write a
|
||||
short greeting."}], "model": "claude-3-5-sonnet-latest", "system": "You are
|
||||
a helpful assistant."}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
anthropic-version:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '169'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.anthropic.com
|
||||
user-agent:
|
||||
- Anthropic/Python 0.43.0
|
||||
x-api-key:
|
||||
- REDACTED
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 0.43.0
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.anthropic.com/v1/messages
|
||||
response:
|
||||
body:
|
||||
string: '{"id":"msg_01FuxB6Gq5QdsdPdafGVavMe","type":"message","role":"assistant","model":"claude-3-5-sonnet-20241022","content":[{"type":"text","text":"Hi
|
||||
there! How are you today?"}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":18,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":11}}'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:32 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Robots-Tag:
|
||||
- none
|
||||
anthropic-ratelimit-input-tokens-limit:
|
||||
- '400000'
|
||||
anthropic-ratelimit-input-tokens-remaining:
|
||||
- '400000'
|
||||
anthropic-ratelimit-input-tokens-reset:
|
||||
- '2025-01-14T22:01:32Z'
|
||||
anthropic-ratelimit-output-tokens-limit:
|
||||
- '80000'
|
||||
anthropic-ratelimit-output-tokens-remaining:
|
||||
- '80000'
|
||||
anthropic-ratelimit-output-tokens-reset:
|
||||
- '2025-01-14T22:01:32Z'
|
||||
anthropic-ratelimit-requests-limit:
|
||||
- '4000'
|
||||
anthropic-ratelimit-requests-remaining:
|
||||
- '3999'
|
||||
anthropic-ratelimit-requests-reset:
|
||||
- '2025-01-14T22:01:31Z'
|
||||
anthropic-ratelimit-tokens-limit:
|
||||
- '480000'
|
||||
anthropic-ratelimit-tokens-remaining:
|
||||
- '480000'
|
||||
anthropic-ratelimit-tokens-reset:
|
||||
- '2025-01-14T22:01:32Z'
|
||||
content-length:
|
||||
- '329'
|
||||
request-id:
|
||||
- req_011Ar8gjbPNQwhNBvQQY5ZcC
|
||||
via:
|
||||
- 1.1 google
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"max_tokens": 1024, "messages": [{"role": "user", "content": "Write a
|
||||
short greeting."}], "model": "claude-3-5-sonnet-latest", "stream": true}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
anthropic-version:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '143'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.anthropic.com
|
||||
user-agent:
|
||||
- Anthropic/Python 0.43.0
|
||||
x-api-key:
|
||||
- REDACTED
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 0.43.0
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.anthropic.com/v1/messages
|
||||
response:
|
||||
body:
|
||||
string: 'event: message_start
|
||||
|
||||
data: {"type":"message_start","message":{"id":"msg_01KoEzb5DsZ7cLWaVCKnxBA7","type":"message","role":"assistant","model":"claude-3-5-sonnet-20241022","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":1}} }
|
||||
|
||||
|
||||
event: content_block_start
|
||||
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""} }
|
||||
|
||||
|
||||
event: ping
|
||||
|
||||
data: {"type": "ping"}
|
||||
|
||||
|
||||
event: content_block_delta
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hi"} }
|
||||
|
||||
|
||||
event: content_block_delta
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"
|
||||
there! How are you today"} }
|
||||
|
||||
|
||||
event: content_block_delta
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"?"} }
|
||||
|
||||
|
||||
event: content_block_stop
|
||||
|
||||
data: {"type":"content_block_stop","index":0 }
|
||||
|
||||
|
||||
event: message_delta
|
||||
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":11} }
|
||||
|
||||
|
||||
event: message_stop
|
||||
|
||||
data: {"type":"message_stop" }
|
||||
|
||||
|
||||
'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Cache-Control:
|
||||
- no-cache
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- text/event-stream; charset=utf-8
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:32 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Robots-Tag:
|
||||
- none
|
||||
anthropic-ratelimit-input-tokens-limit:
|
||||
- '400000'
|
||||
anthropic-ratelimit-input-tokens-remaining:
|
||||
- '400000'
|
||||
anthropic-ratelimit-input-tokens-reset:
|
||||
- '2025-01-14T22:01:32Z'
|
||||
anthropic-ratelimit-output-tokens-limit:
|
||||
- '80000'
|
||||
anthropic-ratelimit-output-tokens-remaining:
|
||||
- '79000'
|
||||
anthropic-ratelimit-output-tokens-reset:
|
||||
- '2025-01-14T22:01:33Z'
|
||||
anthropic-ratelimit-requests-limit:
|
||||
- '4000'
|
||||
anthropic-ratelimit-requests-remaining:
|
||||
- '3999'
|
||||
anthropic-ratelimit-requests-reset:
|
||||
- '2025-01-14T22:01:32Z'
|
||||
anthropic-ratelimit-tokens-limit:
|
||||
- '480000'
|
||||
anthropic-ratelimit-tokens-remaining:
|
||||
- '479000'
|
||||
anthropic-ratelimit-tokens-reset:
|
||||
- '2025-01-14T22:01:32Z'
|
||||
request-id:
|
||||
- req_01BJY5zW9vj8SeRTfFgxKNjX
|
||||
via:
|
||||
- 1.1 google
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"message": "Say hello in spanish", "stream": false}'
|
||||
headers:
|
||||
accept:
|
||||
- '*/*'
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '52'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.cohere.com
|
||||
user-agent:
|
||||
- python-httpx/0.27.2
|
||||
x-fern-language:
|
||||
- Python
|
||||
x-fern-sdk-name:
|
||||
- cohere
|
||||
x-fern-sdk-version:
|
||||
- 5.13.8
|
||||
method: POST
|
||||
uri: https://api.cohere.com/v1/chat
|
||||
response:
|
||||
body:
|
||||
string: '{"response_id":"71e69e77-134e-4f12-b5c7-e25616b5c5d6","text":"Hola.","generation_id":"cefa7ac1-4039-49a0-a9e1-ee2ea41383d5","chat_history":[{"role":"USER","message":"Say
|
||||
hello in spanish"},{"role":"CHATBOT","message":"Hola."}],"finish_reason":"COMPLETE","meta":{"api_version":{"version":"1"},"billed_units":{"input_tokens":5,"output_tokens":3},"tokens":{"input_tokens":206,"output_tokens":3}}}'
|
||||
headers:
|
||||
Alt-Svc:
|
||||
- h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
|
||||
Content-Length:
|
||||
- '393'
|
||||
Via:
|
||||
- 1.1 google
|
||||
access-control-expose-headers:
|
||||
- X-Debug-Trace-ID
|
||||
cache-control:
|
||||
- no-cache, no-store, no-transform, must-revalidate, private, max-age=0
|
||||
content-type:
|
||||
- application/json
|
||||
date:
|
||||
- Tue, 14 Jan 2025 22:01:37 GMT
|
||||
expires:
|
||||
- Thu, 01 Jan 1970 00:00:00 UTC
|
||||
num_chars:
|
||||
- '1198'
|
||||
num_tokens:
|
||||
- '8'
|
||||
pragma:
|
||||
- no-cache
|
||||
server:
|
||||
- envoy
|
||||
vary:
|
||||
- Origin
|
||||
x-accel-expires:
|
||||
- '0'
|
||||
x-debug-trace-id:
|
||||
- d6e85fbdb5552f572a20a4b5ea25ef2f
|
||||
x-envoy-upstream-service-time:
|
||||
- '127'
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"message": "Say hello in spanish", "stream": true}'
|
||||
headers:
|
||||
accept:
|
||||
- '*/*'
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '51'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.cohere.com
|
||||
user-agent:
|
||||
- python-httpx/0.27.2
|
||||
x-fern-language:
|
||||
- Python
|
||||
x-fern-sdk-name:
|
||||
- cohere
|
||||
x-fern-sdk-version:
|
||||
- 5.13.8
|
||||
method: POST
|
||||
uri: https://api.cohere.com/v1/chat
|
||||
response:
|
||||
body:
|
||||
string: '{"is_finished":false,"event_type":"stream-start","generation_id":"04f2b675-2121-401c-bebf-91166f3c0b14"}
|
||||
|
||||
{"is_finished":false,"event_type":"text-generation","text":"H"}
|
||||
|
||||
{"is_finished":false,"event_type":"text-generation","text":"ola"}
|
||||
|
||||
{"is_finished":false,"event_type":"text-generation","text":"."}
|
||||
|
||||
{"is_finished":true,"event_type":"stream-end","response":{"response_id":"6dec46f4-9c33-4f6a-baab-269d06eb49b5","text":"Hola.","generation_id":"04f2b675-2121-401c-bebf-91166f3c0b14","chat_history":[{"role":"USER","message":"Say
|
||||
hello in spanish"},{"role":"CHATBOT","message":"Hola."}],"finish_reason":"COMPLETE","meta":{"api_version":{"version":"1"},"billed_units":{"input_tokens":5,"output_tokens":3},"tokens":{"input_tokens":206,"output_tokens":3}}},"finish_reason":"COMPLETE"}
|
||||
|
||||
'
|
||||
headers:
|
||||
Alt-Svc:
|
||||
- h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
Via:
|
||||
- 1.1 google
|
||||
access-control-expose-headers:
|
||||
- X-Debug-Trace-ID
|
||||
cache-control:
|
||||
- no-cache, no-store, no-transform, must-revalidate, private, max-age=0
|
||||
content-type:
|
||||
- application/stream+json
|
||||
date:
|
||||
- Tue, 14 Jan 2025 22:01:37 GMT
|
||||
expires:
|
||||
- Thu, 01 Jan 1970 00:00:00 UTC
|
||||
pragma:
|
||||
- no-cache
|
||||
server:
|
||||
- envoy
|
||||
vary:
|
||||
- Origin
|
||||
x-accel-expires:
|
||||
- '0'
|
||||
x-debug-trace-id:
|
||||
- 36ba7fdde02f7842568e5dd334e4e895
|
||||
x-envoy-upstream-service-time:
|
||||
- '20'
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
@@ -0,0 +1,313 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"session": {"end_timestamp": null, "end_state": "Indeterminate", "session_id":
|
||||
"b6dde605-486f-4b05-a2da-21587b2c43c3", "init_timestamp": "2025-01-12T03:23:33.063611+00:00",
|
||||
"tags": [], "video": null, "end_state_reason": null, "host_env": {"SDK": {"AgentOps
|
||||
SDK Version": "0.3.22", "Python Version": "3.13.0", "System Packages": {"future_fstrings":
|
||||
"1.2.0", "importlib.metadata": "6.7.0", "pluggy": "1.2.0", "iniconfig": "2.0.0",
|
||||
"pytest": "7.4.0", "pytest_recording": "0.13.2", "termcolor": "2.3.0", "pytest_sugar":
|
||||
"1.0.0", "pytest_cov": "4.1.0", "coverage": "7.2.7", "pytest_mock": "3.11.1",
|
||||
"pytest_asyncio": "0.21.2", "urllib3": "2.3.0", "charset_normalizer": "3.4.0",
|
||||
"idna": "3.10", "certifi": "2024.8.30", "requests": "2.31.0", "six": "1.16.0",
|
||||
"requests_mock": "1.11.0", "pyfakefs": "5.7.1", "fancycompleter": "0.9.1", "sniffio":
|
||||
"1.3.1", "anyio": "4.7.0", "colorama": "0.4.6", "networkx": "2.6.3", "pytest_depends":
|
||||
"1.0.1", "psutil": "5.9.8", "packaging": "23.2", "wrapt": "1.16.0", "deprecated":
|
||||
"1.2.15", "zipp": "3.15.0", "importlib_metadata": "6.7.0", "opentelemetry.sdk":
|
||||
"1.29.0", "agentops": "0.3.22", "typing_extensions": "4.12.2", "pydantic": "2.10.4",
|
||||
"annotated_types": "0.7.0", "pydantic_core": "2.27.2", "click": "8.1.8", "pygments":
|
||||
"2.17.2", "rich": "13.8.1", "httpx": "0.28.1", "distro": "1.9.0", "jiter": "0.8.2",
|
||||
"openai": "1.58.1", "starlette": "0.41.3", "email_validator": "2.2.0", "python_multipart":
|
||||
"0.0.20", "fastapi": "0.115.6", "h11": "0.14.0", "httpcore": "1.0.7"}}, "OS":
|
||||
{"Hostname": "c0.station", "OS": "Darwin", "OS Version": "Darwin Kernel Version
|
||||
24.1.0: Thu Oct 10 21:03:11 PDT 2024; root:xnu-11215.41.3~2/RELEASE_ARM64_T6020",
|
||||
"OS Release": "24.1.0"}, "CPU": {"Physical cores": 12, "Total cores": 12, "CPU
|
||||
Usage": "17.0%"}, "RAM": {"Total": "16.00 GB", "Available": "4.45 GB", "Used":
|
||||
"6.39 GB", "Percentage": "72.2%"}, "Disk": {"/dev/disk3s1s1": {"Mountpoint":
|
||||
"/", "Total": "926.35 GB", "Used": "10.00 GB", "Free": "121.31 GB", "Percentage":
|
||||
"7.6%"}, "/dev/disk3s6": {"Mountpoint": "/System/Volumes/VM", "Total": "926.35
|
||||
GB", "Used": "3.00 GB", "Free": "121.31 GB", "Percentage": "2.4%"}, "/dev/disk3s2":
|
||||
{"Mountpoint": "/System/Volumes/Preboot", "Total": "926.35 GB", "Used": "6.15
|
||||
GB", "Free": "121.31 GB", "Percentage": "4.8%"}, "/dev/disk3s4": {"Mountpoint":
|
||||
"/System/Volumes/Update", "Total": "926.35 GB", "Used": "0.00 GB", "Free": "121.31
|
||||
GB", "Percentage": "0.0%"}, "/dev/disk1s2": {"Mountpoint": "/System/Volumes/xarts",
|
||||
"Total": "0.49 GB", "Used": "0.01 GB", "Free": "0.47 GB", "Percentage": "1.2%"},
|
||||
"/dev/disk1s1": {"Mountpoint": "/System/Volumes/iSCPreboot", "Total": "0.49
|
||||
GB", "Used": "0.01 GB", "Free": "0.47 GB", "Percentage": "1.1%"}, "/dev/disk1s3":
|
||||
{"Mountpoint": "/System/Volumes/Hardware", "Total": "0.49 GB", "Used": "0.00
|
||||
GB", "Free": "0.47 GB", "Percentage": "0.8%"}, "/dev/disk3s5": {"Mountpoint":
|
||||
"/System/Volumes/Data", "Total": "926.35 GB", "Used": "784.80 GB", "Free": "121.31
|
||||
GB", "Percentage": "86.6%"}}, "Installed Packages": {"Installed Packages": {"agentops":
|
||||
"0.3.22", "rich": "13.8.1", "rich-toolkit": "0.12.0", "pytest-recording": "0.13.2",
|
||||
"shellingham": "1.5.4", "opentelemetry-api": "1.29.0", "opentelemetry-proto":
|
||||
"1.29.0", "idna": "3.10", "fastapi": "0.115.6", "PyYAML": "6.0.1", "types-urllib3":
|
||||
"1.26.25.14", "Pygments": "2.17.2", "networkx": "2.6.3", "colorama": "0.4.6",
|
||||
"uvicorn": "0.34.0", "typer": "0.15.1", "fancycompleter": "0.9.1", "googleapis-common-protos":
|
||||
"1.66.0", "dnspython": "2.7.0", "multidict": "6.0.5", "six": "1.16.0", "mypy-extensions":
|
||||
"1.0.0", "pluggy": "1.2.0", "h11": "0.14.0", "opentelemetry-sdk": "1.29.0",
|
||||
"pytest-sugar": "1.0.0", "pyrepl": "0.9.0", "iniconfig": "2.0.0", "tqdm": "4.67.1",
|
||||
"urllib3": "2.3.0", "protobuf": "5.29.3", "python-dotenv": "0.21.1", "click":
|
||||
"8.1.8", "numpy": "1.26.4", "zipp": "3.15.0", "packaging": "23.2", "markdown-it-py":
|
||||
"2.2.0", "certifi": "2024.8.30", "pytest-cov": "4.1.0", "openai": "1.58.1",
|
||||
"opentelemetry-semantic-conventions": "0.50b0", "propcache": "0.2.1", "Jinja2":
|
||||
"3.1.5", "SQLAlchemy": "2.0.36", "vcrpy": "7.0.0", "requests": "2.31.0", "pytest":
|
||||
"7.4.0", "sniffio": "1.3.1", "pytest-mock": "3.11.1", "fastapi-cli": "0.0.7",
|
||||
"mdurl": "0.1.2", "opentelemetry-exporter-otlp-proto-common": "1.29.0", "yarl":
|
||||
"1.18.3", "Deprecated": "1.2.15", "importlib-metadata": "6.7.0", "psutil": "5.9.8",
|
||||
"pydantic_core": "2.27.2", "httpcore": "1.0.7", "websockets": "14.1", "pydantic":
|
||||
"2.10.4", "future-fstrings": "1.2.0", "pytest-asyncio": "0.21.2", "python-multipart":
|
||||
"0.0.20", "starlette": "0.41.3", "requests-mock": "1.11.0", "distro": "1.9.0",
|
||||
"jiter": "0.8.2", "ruff": "0.8.1", "pyfakefs": "5.7.1", "httptools": "0.6.4",
|
||||
"typing_extensions": "4.12.2", "wmctrl": "0.5", "httpx": "0.28.1", "attrs":
|
||||
"24.3.0", "anyio": "4.7.0", "mypy": "1.4.1", "watchfiles": "1.0.4", "email_validator":
|
||||
"2.2.0", "charset-normalizer": "3.4.0", "pdbpp": "0.10.3", "langchain": "0.0.27",
|
||||
"uvloop": "0.21.0", "termcolor": "2.3.0", "annotated-types": "0.7.0", "pytest-depends":
|
||||
"1.0.1", "opentelemetry-exporter-otlp-proto-http": "1.29.0", "types-requests":
|
||||
"2.31.0.6", "wrapt": "1.16.0", "coverage": "7.2.7", "MarkupSafe": "3.0.2"}},
|
||||
"Project Working Directory": {"Project Working Directory": "/Users/noob/agentops"},
|
||||
"Virtual Environment": {"Virtual Environment": "/Users/noob/agentops/.venv"}},
|
||||
"config": "", "jwt": null, "_lock": "", "_end_session_lock": "", "token_cost":
|
||||
"", "_session_url": "", "event_counts": {"llms": 0, "tools": 0, "actions": 0,
|
||||
"errors": 0, "apis": 0}}}'
|
||||
headers:
|
||||
Accept:
|
||||
- '*/*'
|
||||
Accept-Encoding:
|
||||
- gzip, deflate
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Length:
|
||||
- '5519'
|
||||
Content-Type:
|
||||
- application/json; charset=UTF-8
|
||||
Keep-Alive:
|
||||
- timeout=10, max=1000
|
||||
User-Agent:
|
||||
- python-requests/2.31.0
|
||||
x-agentops-api-key:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.agentops.ai/v2/create_session
|
||||
response:
|
||||
body:
|
||||
string: '{"jwt":"REDACTED","session_url":"https://app.agentops.ai/drilldown?session_id=b6dde605-486f-4b05-a2da-21587b2c43c3","status":"Success"}'
|
||||
headers:
|
||||
Content-Length:
|
||||
- '310'
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Sun, 12 Jan 2025 03:23:33 GMT
|
||||
Server:
|
||||
- railway-edge
|
||||
X-Railway-Request-Id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: ''
|
||||
headers:
|
||||
accept:
|
||||
- '*/*'
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
connection:
|
||||
- keep-alive
|
||||
host:
|
||||
- testserver
|
||||
user-agent:
|
||||
- testclient
|
||||
method: GET
|
||||
uri: http://testserver/completion
|
||||
response:
|
||||
body:
|
||||
string: '{"response":"Done","execution_time_seconds":0.066}'
|
||||
headers:
|
||||
content-length:
|
||||
- '50'
|
||||
content-type:
|
||||
- application/json
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: ''
|
||||
headers:
|
||||
accept:
|
||||
- '*/*'
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
connection:
|
||||
- keep-alive
|
||||
host:
|
||||
- testserver
|
||||
user-agent:
|
||||
- testclient
|
||||
method: GET
|
||||
uri: http://testserver/completion
|
||||
response:
|
||||
body:
|
||||
string: '{"response":"Done","execution_time_seconds":0.066}'
|
||||
headers:
|
||||
content-length:
|
||||
- '50'
|
||||
content-type:
|
||||
- application/json
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"events": [{"id": "ff3bac2b-9c2f-42b2-bf72-1acf0ea17bb2", "event_type":
|
||||
"tools", "init_timestamp": "2025-01-12T03:23:33.896970+00:00", "end_timestamp":
|
||||
"2025-01-12T03:23:33.963196+00:00", "params": {"x": "Hello"}, "returns": null,
|
||||
"agent_id": null, "name": "foo", "logs": null, "tool_name": "foo", "session_id":
|
||||
"b6dde605-486f-4b05-a2da-21587b2c43c3"}, {"id": "fb4199a4-f39b-41a4-ad84-e33137ad57c4",
|
||||
"event_type": "tools", "init_timestamp": "2025-01-12T03:23:33.897051+00:00",
|
||||
"end_timestamp": "2025-01-12T03:23:33.963347+00:00", "params": {"x": "Hello"},
|
||||
"returns": null, "agent_id": null, "name": "foo", "logs": null, "tool_name":
|
||||
"foo", "session_id": "b6dde605-486f-4b05-a2da-21587b2c43c3"}]}'
|
||||
headers:
|
||||
Accept:
|
||||
- '*/*'
|
||||
Accept-Encoding:
|
||||
- gzip, deflate
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Length:
|
||||
- '696'
|
||||
Content-Type:
|
||||
- application/json; charset=UTF-8
|
||||
Keep-Alive:
|
||||
- timeout=10, max=1000
|
||||
User-Agent:
|
||||
- python-requests/2.31.0
|
||||
authorization:
|
||||
- REDACTED
|
||||
x-agentops-api-key:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.agentops.ai/v2/create_events
|
||||
response:
|
||||
body:
|
||||
string: '"Success"'
|
||||
headers:
|
||||
Content-Length:
|
||||
- '9'
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Sun, 12 Jan 2025 03:23:34 GMT
|
||||
Server:
|
||||
- railway-edge
|
||||
X-Railway-Request-Id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"session": {"end_timestamp": "2025-01-12T03:23:34.764692+00:00", "end_state":
|
||||
"Indeterminate", "session_id": "b6dde605-486f-4b05-a2da-21587b2c43c3", "init_timestamp":
|
||||
"2025-01-12T03:23:33.063611+00:00", "tags": [], "video": null, "end_state_reason":
|
||||
null, "host_env": {"SDK": {"AgentOps SDK Version": "0.3.22", "Python Version":
|
||||
"3.13.0", "System Packages": {"future_fstrings": "1.2.0", "importlib.metadata":
|
||||
"6.7.0", "pluggy": "1.2.0", "iniconfig": "2.0.0", "pytest": "7.4.0", "pytest_recording":
|
||||
"0.13.2", "termcolor": "2.3.0", "pytest_sugar": "1.0.0", "pytest_cov": "4.1.0",
|
||||
"coverage": "7.2.7", "pytest_mock": "3.11.1", "pytest_asyncio": "0.21.2", "urllib3":
|
||||
"2.3.0", "charset_normalizer": "3.4.0", "idna": "3.10", "certifi": "2024.8.30",
|
||||
"requests": "2.31.0", "six": "1.16.0", "requests_mock": "1.11.0", "pyfakefs":
|
||||
"5.7.1", "fancycompleter": "0.9.1", "sniffio": "1.3.1", "anyio": "4.7.0", "colorama":
|
||||
"0.4.6", "networkx": "2.6.3", "pytest_depends": "1.0.1", "psutil": "5.9.8",
|
||||
"packaging": "23.2", "wrapt": "1.16.0", "deprecated": "1.2.15", "zipp": "3.15.0",
|
||||
"importlib_metadata": "6.7.0", "opentelemetry.sdk": "1.29.0", "agentops": "0.3.22",
|
||||
"typing_extensions": "4.12.2", "pydantic": "2.10.4", "annotated_types": "0.7.0",
|
||||
"pydantic_core": "2.27.2", "click": "8.1.8", "pygments": "2.17.2", "rich": "13.8.1",
|
||||
"httpx": "0.28.1", "distro": "1.9.0", "jiter": "0.8.2", "openai": "1.58.1",
|
||||
"starlette": "0.41.3", "email_validator": "2.2.0", "python_multipart": "0.0.20",
|
||||
"fastapi": "0.115.6", "h11": "0.14.0", "httpcore": "1.0.7"}}, "OS": {"Hostname":
|
||||
"c0.station", "OS": "Darwin", "OS Version": "Darwin Kernel Version 24.1.0: Thu
|
||||
Oct 10 21:03:11 PDT 2024; root:xnu-11215.41.3~2/RELEASE_ARM64_T6020", "OS Release":
|
||||
"24.1.0"}, "CPU": {"Physical cores": 12, "Total cores": 12, "CPU Usage": "17.0%"},
|
||||
"RAM": {"Total": "16.00 GB", "Available": "4.45 GB", "Used": "6.39 GB", "Percentage":
|
||||
"72.2%"}, "Disk": {"/dev/disk3s1s1": {"Mountpoint": "/", "Total": "926.35 GB",
|
||||
"Used": "10.00 GB", "Free": "121.31 GB", "Percentage": "7.6%"}, "/dev/disk3s6":
|
||||
{"Mountpoint": "/System/Volumes/VM", "Total": "926.35 GB", "Used": "3.00 GB",
|
||||
"Free": "121.31 GB", "Percentage": "2.4%"}, "/dev/disk3s2": {"Mountpoint": "/System/Volumes/Preboot",
|
||||
"Total": "926.35 GB", "Used": "6.15 GB", "Free": "121.31 GB", "Percentage":
|
||||
"4.8%"}, "/dev/disk3s4": {"Mountpoint": "/System/Volumes/Update", "Total": "926.35
|
||||
GB", "Used": "0.00 GB", "Free": "121.31 GB", "Percentage": "0.0%"}, "/dev/disk1s2":
|
||||
{"Mountpoint": "/System/Volumes/xarts", "Total": "0.49 GB", "Used": "0.01 GB",
|
||||
"Free": "0.47 GB", "Percentage": "1.2%"}, "/dev/disk1s1": {"Mountpoint": "/System/Volumes/iSCPreboot",
|
||||
"Total": "0.49 GB", "Used": "0.01 GB", "Free": "0.47 GB", "Percentage": "1.1%"},
|
||||
"/dev/disk1s3": {"Mountpoint": "/System/Volumes/Hardware", "Total": "0.49 GB",
|
||||
"Used": "0.00 GB", "Free": "0.47 GB", "Percentage": "0.8%"}, "/dev/disk3s5":
|
||||
{"Mountpoint": "/System/Volumes/Data", "Total": "926.35 GB", "Used": "784.80
|
||||
GB", "Free": "121.31 GB", "Percentage": "86.6%"}}, "Installed Packages": {"Installed
|
||||
Packages": {"agentops": "0.3.22", "rich": "13.8.1", "rich-toolkit": "0.12.0",
|
||||
"pytest-recording": "0.13.2", "shellingham": "1.5.4", "opentelemetry-api": "1.29.0",
|
||||
"opentelemetry-proto": "1.29.0", "idna": "3.10", "fastapi": "0.115.6", "PyYAML":
|
||||
"6.0.1", "types-urllib3": "1.26.25.14", "Pygments": "2.17.2", "networkx": "2.6.3",
|
||||
"colorama": "0.4.6", "uvicorn": "0.34.0", "typer": "0.15.1", "fancycompleter":
|
||||
"0.9.1", "googleapis-common-protos": "1.66.0", "dnspython": "2.7.0", "multidict":
|
||||
"6.0.5", "six": "1.16.0", "mypy-extensions": "1.0.0", "pluggy": "1.2.0", "h11":
|
||||
"0.14.0", "opentelemetry-sdk": "1.29.0", "pytest-sugar": "1.0.0", "pyrepl":
|
||||
"0.9.0", "iniconfig": "2.0.0", "tqdm": "4.67.1", "urllib3": "2.3.0", "protobuf":
|
||||
"5.29.3", "python-dotenv": "0.21.1", "click": "8.1.8", "numpy": "1.26.4", "zipp":
|
||||
"3.15.0", "packaging": "23.2", "markdown-it-py": "2.2.0", "certifi": "2024.8.30",
|
||||
"pytest-cov": "4.1.0", "openai": "1.58.1", "opentelemetry-semantic-conventions":
|
||||
"0.50b0", "propcache": "0.2.1", "Jinja2": "3.1.5", "SQLAlchemy": "2.0.36", "vcrpy":
|
||||
"7.0.0", "requests": "2.31.0", "pytest": "7.4.0", "sniffio": "1.3.1", "pytest-mock":
|
||||
"3.11.1", "fastapi-cli": "0.0.7", "mdurl": "0.1.2", "opentelemetry-exporter-otlp-proto-common":
|
||||
"1.29.0", "yarl": "1.18.3", "Deprecated": "1.2.15", "importlib-metadata": "6.7.0",
|
||||
"psutil": "5.9.8", "pydantic_core": "2.27.2", "httpcore": "1.0.7", "websockets":
|
||||
"14.1", "pydantic": "2.10.4", "future-fstrings": "1.2.0", "pytest-asyncio":
|
||||
"0.21.2", "python-multipart": "0.0.20", "starlette": "0.41.3", "requests-mock":
|
||||
"1.11.0", "distro": "1.9.0", "jiter": "0.8.2", "ruff": "0.8.1", "pyfakefs":
|
||||
"5.7.1", "httptools": "0.6.4", "typing_extensions": "4.12.2", "wmctrl": "0.5",
|
||||
"httpx": "0.28.1", "attrs": "24.3.0", "anyio": "4.7.0", "mypy": "1.4.1", "watchfiles":
|
||||
"1.0.4", "email_validator": "2.2.0", "charset-normalizer": "3.4.0", "pdbpp":
|
||||
"0.10.3", "langchain": "0.0.27", "uvloop": "0.21.0", "termcolor": "2.3.0", "annotated-types":
|
||||
"0.7.0", "pytest-depends": "1.0.1", "opentelemetry-exporter-otlp-proto-http":
|
||||
"1.29.0", "types-requests": "2.31.0.6", "wrapt": "1.16.0", "coverage": "7.2.7",
|
||||
"MarkupSafe": "3.0.2"}}, "Project Working Directory": {"Project Working Directory":
|
||||
"/Users/noob/agentops"}, "Virtual Environment": {"Virtual Environment": "/Users/noob/agentops/.venv"}},
|
||||
"config": "", "jwt": "REDACTED",
|
||||
"_lock": "", "_end_session_lock": "", "token_cost": "", "_session_url": "",
|
||||
"event_counts": {"llms": 0, "tools": 2, "actions": 0, "errors": 0, "apis": 0},
|
||||
"is_running": false, "_tracer_provider": "", "_otel_tracer": "", "_otel_exporter":
|
||||
""}}'
|
||||
headers:
|
||||
Accept:
|
||||
- '*/*'
|
||||
Accept-Encoding:
|
||||
- gzip, deflate
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Length:
|
||||
- '5817'
|
||||
Content-Type:
|
||||
- application/json; charset=UTF-8
|
||||
Keep-Alive:
|
||||
- timeout=10, max=1000
|
||||
User-Agent:
|
||||
- python-requests/2.31.0
|
||||
authorization:
|
||||
- REDACTED
|
||||
x-agentops-api-key:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.agentops.ai/v2/update_session
|
||||
response:
|
||||
body:
|
||||
string: '{"session_url":"https://app.agentops.ai/drilldown?session_id=b6dde605-486f-4b05-a2da-21587b2c43c3","status":"success","token_cost":"0.00"}'
|
||||
headers:
|
||||
Content-Length:
|
||||
- '138'
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Sun, 12 Jan 2025 03:23:35 GMT
|
||||
Server:
|
||||
- railway-edge
|
||||
X-Railway-Request-Id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"messages": [{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Write a short greeting."}], "model": "llama3-70b-8192"}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '161'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.groq.com
|
||||
user-agent:
|
||||
- Groq/Python 0.15.0
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 0.15.0
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.groq.com/openai/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: '{"id":"chatcmpl-2af4c427-2bd9-4cd3-96f6-b606fdbb3861","object":"chat.completion","created":1736892098,"model":"llama3-70b-8192","choices":[{"index":0,"message":{"role":"assistant","content":"Hello!
|
||||
It''s nice to meet you. I''m here to help with any questions or tasks you
|
||||
may have. How can I assist you today?"},"logprobs":null,"finish_reason":"stop"}],"usage":{"queue_time":0.01813716,"prompt_tokens":26,"prompt_time":0.006384788,"completion_tokens":31,"completion_time":0.088571429,"total_tokens":57,"total_time":0.094956217},"system_fingerprint":"fp_7ab5f7e105","x_groq":{"id":"req_01jhkdc9s1fkms5t70nkenz0cd"}}
|
||||
|
||||
'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-Ray: REDACTED
|
||||
Cache-Control:
|
||||
- private, max-age=0, no-store, no-cache, must-revalidate
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:38 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Set-Cookie:
|
||||
- __cf_bm=ttiNqGMk_BV10hGzDbQabayHPX0LU1ADt6NJaAlH2OM-1736892098-1.0.1.1-.GWvzeomKWsJHt1xJAw4kJuhHIUKtslXZHmRDTdU47DdRpcxcJVAgCnWqGMlt7BrbNHqNXyyj9LozFn4hECs6w;
|
||||
path=/; expires=Tue, 14-Jan-25 22:31:38 GMT; domain=.groq.com; HttpOnly; Secure;
|
||||
SameSite=None
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
Vary:
|
||||
- Origin, Accept-Encoding
|
||||
Via:
|
||||
- 1.1 google
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '613'
|
||||
x-groq-region:
|
||||
- us-west-1
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"messages": [{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Write a short greeting."}], "model": "llama3-70b-8192",
|
||||
"stream": true}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '177'
|
||||
content-type:
|
||||
- application/json
|
||||
cookie:
|
||||
- __cf_bm=ttiNqGMk_BV10hGzDbQabayHPX0LU1ADt6NJaAlH2OM-1736892098-1.0.1.1-.GWvzeomKWsJHt1xJAw4kJuhHIUKtslXZHmRDTdU47DdRpcxcJVAgCnWqGMlt7BrbNHqNXyyj9LozFn4hECs6w
|
||||
host:
|
||||
- api.groq.com
|
||||
user-agent:
|
||||
- Groq/Python 0.15.0
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 0.15.0
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.groq.com/openai/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: 'data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}],"x_groq":{"id":"req_01jhkdca4qfqka69k9g78d7p8m"}}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"!"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
It"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"''s"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
nice"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
to"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
meet"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
you"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
I"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"''m"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
here"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
to"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
help"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
with"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
any"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
questions"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
or"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
tasks"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
you"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
may"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
have"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":","},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
so"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
please"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
don"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"''t"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
hesitate"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
to"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
ask"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
me"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
anything"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
How"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
can"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
I"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
assist"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
you"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"
|
||||
today"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{"content":"?"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-f4f29f6f-d3f9-4d3e-afb6-0d0d23604b33","object":"chat.completion.chunk","created":1736892098,"model":"llama3-70b-8192","system_fingerprint":"fp_7ab5f7e105","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}],"x_groq":{"id":"req_01jhkdca4qfqka69k9g78d7p8m","usage":{"queue_time":0.017442521,"prompt_tokens":26,"prompt_time":0.006383798,"completion_tokens":41,"completion_time":0.117142857,"total_tokens":67,"total_time":0.123526655}}}
|
||||
|
||||
|
||||
data: [DONE]
|
||||
|
||||
|
||||
'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-Ray: REDACTED
|
||||
Cache-Control:
|
||||
- no-cache
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- text/event-stream
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:38 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
Vary:
|
||||
- Origin, Accept-Encoding
|
||||
Via:
|
||||
- 1.1 google
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
x-groq-region:
|
||||
- us-west-1
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
@@ -0,0 +1,310 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"messages": [{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Write a short greeting."}], "model": "gpt-4o-mini"}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '157'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.openai.com
|
||||
user-agent:
|
||||
- OpenAI/Python 1.59.7
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 1.59.7
|
||||
x-stainless-raw-response:
|
||||
- 'true'
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.openai.com/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: "{\n \"id\": \"chatcmpl-ApjGiJn585luUEit6xN0jw5dKDo2h\",\n \"object\":
|
||||
\"chat.completion\",\n \"created\": 1736892104,\n \"model\": \"gpt-4o-mini-2024-07-18\",\n
|
||||
\ \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\":
|
||||
\"assistant\",\n \"content\": \"Hello! I hope you\u2019re having a
|
||||
wonderful day. If there\u2019s anything you need or want to talk about, I\u2019m
|
||||
here to help!\",\n \"refusal\": null\n },\n \"logprobs\":
|
||||
null,\n \"finish_reason\": \"stop\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\":
|
||||
22,\n \"completion_tokens\": 30,\n \"total_tokens\": 52,\n \"prompt_tokens_details\":
|
||||
{\n \"cached_tokens\": 0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\":
|
||||
{\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\":
|
||||
0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\":
|
||||
\"default\",\n \"system_fingerprint\": \"fp_72ed7ab54c\"\n}\n"
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:46 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Set-Cookie:
|
||||
- __cf_bm=VZJx_faFj6770ez9UQRJPHiVOar8.rDZHHjgopTXIvI-1736892106-1.0.1.1-pXcK6sMQ1OET.xkYliaYrHl7oD0w1_4M94x_L1O6nolXXWj7vAEf4aQeHngF8o1GrAMIvsmIok3HkQ1tq6cJgA;
|
||||
path=/; expires=Tue, 14-Jan-25 22:31:46 GMT; domain=.api.openai.com; HttpOnly;
|
||||
Secure; SameSite=None
|
||||
- _cfuvid=i1qHe5Dq7I0tQx8N2yiSC49IpHCpAnBX.8W87TNF3Uk-1736892106225-0.0.1.1-604800000;
|
||||
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Content-Type-Options:
|
||||
- nosniff
|
||||
access-control-expose-headers:
|
||||
- X-Request-ID
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '900'
|
||||
openai-organization: REDACTED
|
||||
openai-processing-ms:
|
||||
- '1148'
|
||||
openai-version:
|
||||
- '2020-10-01'
|
||||
strict-transport-security:
|
||||
- max-age=31536000; includeSubDomains; preload
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"model": "claude-3-5-sonnet-latest", "messages": [{"role": "user", "content":
|
||||
[{"type": "text", "text": "Write a short greeting."}]}], "system": [{"type":
|
||||
"text", "text": "You are a helpful assistant."}], "max_tokens": 4096, "stream":
|
||||
true}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
anthropic-version:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '241'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.anthropic.com
|
||||
user-agent:
|
||||
- litellm/1.58.1
|
||||
x-api-key:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.anthropic.com/v1/messages
|
||||
response:
|
||||
body:
|
||||
string: 'event: message_start
|
||||
|
||||
data: {"type":"message_start","message":{"id":"msg_01NHdXbMbxAY5St4JoFySmKD","type":"message","role":"assistant","model":"claude-3-5-sonnet-20241022","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":18,"cache_creation_input_tokens":0,"cache_read_input_tokens":0,"output_tokens":1}} }
|
||||
|
||||
|
||||
event: content_block_start
|
||||
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""} }
|
||||
|
||||
|
||||
event: ping
|
||||
|
||||
data: {"type": "ping"}
|
||||
|
||||
|
||||
event: content_block_delta
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hi"} }
|
||||
|
||||
|
||||
event: content_block_delta
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"
|
||||
there! I hope"} }
|
||||
|
||||
|
||||
event: content_block_delta
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"
|
||||
you''re having a great day. How can I"} }
|
||||
|
||||
|
||||
event: content_block_delta
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"
|
||||
help you?"} }
|
||||
|
||||
|
||||
event: content_block_stop
|
||||
|
||||
data: {"type":"content_block_stop","index":0 }
|
||||
|
||||
|
||||
event: message_delta
|
||||
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":21} }
|
||||
|
||||
|
||||
event: message_stop
|
||||
|
||||
data: {"type":"message_stop" }
|
||||
|
||||
|
||||
'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Cache-Control:
|
||||
- no-cache
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- text/event-stream; charset=utf-8
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:47 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Robots-Tag:
|
||||
- none
|
||||
anthropic-ratelimit-input-tokens-limit:
|
||||
- '400000'
|
||||
anthropic-ratelimit-input-tokens-remaining:
|
||||
- '400000'
|
||||
anthropic-ratelimit-input-tokens-reset:
|
||||
- '2025-01-14T22:01:47Z'
|
||||
anthropic-ratelimit-output-tokens-limit:
|
||||
- '80000'
|
||||
anthropic-ratelimit-output-tokens-remaining:
|
||||
- '76000'
|
||||
anthropic-ratelimit-output-tokens-reset:
|
||||
- '2025-01-14T22:01:50Z'
|
||||
anthropic-ratelimit-requests-limit:
|
||||
- '4000'
|
||||
anthropic-ratelimit-requests-remaining:
|
||||
- '3999'
|
||||
anthropic-ratelimit-requests-reset:
|
||||
- '2025-01-14T22:01:47Z'
|
||||
anthropic-ratelimit-tokens-limit:
|
||||
- '480000'
|
||||
anthropic-ratelimit-tokens-remaining:
|
||||
- '476000'
|
||||
anthropic-ratelimit-tokens-reset:
|
||||
- '2025-01-14T22:01:47Z'
|
||||
request-id:
|
||||
- req_0152ZgzyVZ1evwa14rFvgbPc
|
||||
via:
|
||||
- 1.1 google
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"messages": [{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Write a short greeting."}], "model": "deepseek/deepseek-chat"}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '168'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- openrouter.ai
|
||||
http-referer:
|
||||
- https://litellm.ai
|
||||
user-agent:
|
||||
- AsyncOpenAI/Python 1.59.7
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 1.59.7
|
||||
x-stainless-raw-response:
|
||||
- 'true'
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
x-title:
|
||||
- liteLLM
|
||||
method: POST
|
||||
uri: https://openrouter.ai/api/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: "\n \n\n \n\n \n\n \n\n \n\n
|
||||
\ \n\n \n\n \n\n \n\n \n\n \n\n
|
||||
\ \n\n \n\n \n\n \n{\"id\":\"gen-1736892109-Bw6T8Zz8t3IlUpRWImy8\",\"provider\":\"DeepSeek\",\"model\":\"deepseek/deepseek-chat\",\"object\":\"chat.completion\",\"created\":1736892109,\"choices\":[{\"logprobs\":null,\"finish_reason\":\"stop\",\"index\":0,\"message\":{\"role\":\"assistant\",\"content\":\"Hello!
|
||||
How can I assist you today? \U0001F60A\",\"refusal\":\"\"}}],\"system_fingerprint\":\"fp_3a5770e1b4\",\"usage\":{\"prompt_tokens\":14,\"completion_tokens\":11,\"total_tokens\":25}}"
|
||||
headers:
|
||||
Access-Control-Allow-Origin:
|
||||
- '*'
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:49 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
Vary:
|
||||
- Accept-Encoding
|
||||
content-length:
|
||||
- '578'
|
||||
x-clerk-auth-message:
|
||||
- Invalid JWT form. A JWT consists of three parts separated by dots. (reason=token-invalid,
|
||||
token-carrier=header)
|
||||
x-clerk-auth-reason:
|
||||
- token-invalid
|
||||
x-clerk-auth-status:
|
||||
- signed-out
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
@@ -0,0 +1,270 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"messages":[{"content":"You are a helpful assistant.","role":"system"},{"content":"Write
|
||||
a short greeting.","role":"user"}],"model":"open-mistral-nemo","stream":false}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '168'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.mistral.ai
|
||||
user-agent:
|
||||
- mistral-client-python/1.3.0
|
||||
method: POST
|
||||
uri: https://api.mistral.ai/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: '{"id":"8ba623141b9b4f5eaecae7ffc8ccaad1","object":"chat.completion","created":1736892100,"model":"open-mistral-nemo","choices":[{"index":0,"message":{"role":"assistant","tool_calls":null,"content":"Hello!
|
||||
How can I assist you today?"},"finish_reason":"stop"}],"usage":{"prompt_tokens":14,"total_tokens":23,"completion_tokens":9}}'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:41 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Set-Cookie:
|
||||
- __cf_bm=eOaAsx8Q_tJBx9Y8XK6N_OmptJS7ygq_R1CyJNKvGrs-1736892101-1.0.1.1-91nk9JpKLYNaewJbxskPZy3lICk86CsUfNc4524VkHHfHy.JlifHQxwFX4s2XV5Qd8gA.TG.d5iWIeCgjVRZ.w;
|
||||
path=/; expires=Tue, 14-Jan-25 22:31:41 GMT; domain=.mistral.ai; HttpOnly;
|
||||
Secure; SameSite=None
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
access-control-allow-origin:
|
||||
- '*'
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '329'
|
||||
ratelimitbysize-limit:
|
||||
- '2000000'
|
||||
ratelimitbysize-query-cost:
|
||||
- '32013'
|
||||
ratelimitbysize-remaining:
|
||||
- '1967987'
|
||||
ratelimitbysize-reset:
|
||||
- '21'
|
||||
x-envoy-upstream-service-time:
|
||||
- '1715'
|
||||
x-kong-proxy-latency:
|
||||
- '2'
|
||||
x-kong-request-id:
|
||||
- ec96aa1f9ba7d351901eba2c2df9620b
|
||||
x-kong-upstream-latency:
|
||||
- '1716'
|
||||
x-ratelimitbysize-limit-minute:
|
||||
- '2000000'
|
||||
x-ratelimitbysize-limit-month:
|
||||
- '10000000000'
|
||||
x-ratelimitbysize-remaining-minute:
|
||||
- '1967987'
|
||||
x-ratelimitbysize-remaining-month:
|
||||
- '9999679870'
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"messages":[{"content":"You are a helpful assistant.","role":"system"},{"content":"Write
|
||||
a short greeting.","role":"user"}],"model":"open-mistral-nemo","stream":true}'
|
||||
headers:
|
||||
accept:
|
||||
- text/event-stream
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '167'
|
||||
content-type:
|
||||
- application/json
|
||||
cookie:
|
||||
- __cf_bm=eOaAsx8Q_tJBx9Y8XK6N_OmptJS7ygq_R1CyJNKvGrs-1736892101-1.0.1.1-91nk9JpKLYNaewJbxskPZy3lICk86CsUfNc4524VkHHfHy.JlifHQxwFX4s2XV5Qd8gA.TG.d5iWIeCgjVRZ.w
|
||||
host:
|
||||
- api.mistral.ai
|
||||
user-agent:
|
||||
- mistral-client-python/1.3.0
|
||||
method: POST
|
||||
uri: https://api.mistral.ai/v1/chat/completions#stream
|
||||
response:
|
||||
body:
|
||||
string: 'data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"
|
||||
How"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"
|
||||
can"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"
|
||||
I"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"
|
||||
assist"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"
|
||||
you"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"
|
||||
today"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":"?"},"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"96c448d0a6bd4e389575fe6a7bd76ba3","object":"chat.completion.chunk","created":1736892102,"model":"open-mistral-nemo","choices":[{"index":0,"delta":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":14,"total_tokens":23,"completion_tokens":9}}
|
||||
|
||||
|
||||
data: [DONE]
|
||||
|
||||
|
||||
'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- text/event-stream; charset=utf-8
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:42 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
access-control-allow-origin:
|
||||
- '*'
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
ratelimitbysize-limit:
|
||||
- '2000000'
|
||||
ratelimitbysize-query-cost:
|
||||
- '32013'
|
||||
ratelimitbysize-remaining:
|
||||
- '1935974'
|
||||
ratelimitbysize-reset:
|
||||
- '19'
|
||||
x-envoy-upstream-service-time:
|
||||
- '1744'
|
||||
x-kong-proxy-latency:
|
||||
- '2'
|
||||
x-kong-request-id:
|
||||
- 60e9c22b4c008f26f558655e1d408860
|
||||
x-kong-upstream-latency:
|
||||
- '1745'
|
||||
x-ratelimitbysize-limit-minute:
|
||||
- '2000000'
|
||||
x-ratelimitbysize-limit-month:
|
||||
- '10000000000'
|
||||
x-ratelimitbysize-remaining-minute:
|
||||
- '1935974'
|
||||
x-ratelimitbysize-remaining-month:
|
||||
- '9999647857'
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"messages":[{"content":"You are a helpful assistant.","role":"system"},{"content":"Write
|
||||
a short greeting.","role":"user"}],"model":"open-mistral-nemo","stream":false}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '168'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.mistral.ai
|
||||
user-agent:
|
||||
- mistral-client-python/1.3.0
|
||||
method: POST
|
||||
uri: https://api.mistral.ai/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: '{"id":"9b6634916c5f40e2a0d37fe4b27dc931","object":"chat.completion","created":1736892104,"model":"open-mistral-nemo","choices":[{"index":0,"message":{"role":"assistant","tool_calls":null,"content":"Hello!
|
||||
How can I assist you today?"},"finish_reason":"stop"}],"usage":{"prompt_tokens":14,"total_tokens":23,"completion_tokens":9}}'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:44 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Set-Cookie:
|
||||
- __cf_bm=CmqbjAgaZWC9qzehM26mYcWWmb9ZK_eFQpIukBefQlU-1736892104-1.0.1.1-D8RfrgJlaperKjR7p1wsuRydF5VcrL8XlvdC9CmDzH0zQge.69UwcDViZsY6HGwR2daaR_VoR0PZiiltbZWOOQ;
|
||||
path=/; expires=Tue, 14-Jan-25 22:31:44 GMT; domain=.mistral.ai; HttpOnly;
|
||||
Secure; SameSite=None
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
access-control-allow-origin:
|
||||
- '*'
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '329'
|
||||
ratelimitbysize-limit:
|
||||
- '2000000'
|
||||
ratelimitbysize-query-cost:
|
||||
- '32013'
|
||||
ratelimitbysize-remaining:
|
||||
- '1903961'
|
||||
ratelimitbysize-reset:
|
||||
- '17'
|
||||
x-envoy-upstream-service-time:
|
||||
- '921'
|
||||
x-kong-proxy-latency:
|
||||
- '1'
|
||||
x-kong-request-id:
|
||||
- be34c7639659dc342e3cb75e1e919876
|
||||
x-kong-upstream-latency:
|
||||
- '922'
|
||||
x-ratelimitbysize-limit-minute:
|
||||
- '2000000'
|
||||
x-ratelimitbysize-limit-month:
|
||||
- '10000000000'
|
||||
x-ratelimitbysize-remaining-minute:
|
||||
- '1903961'
|
||||
x-ratelimitbysize-remaining-month:
|
||||
- '9999615844'
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"messages": [{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Write a short greeting."}], "model": "gpt-4o-mini",
|
||||
"temperature": 0.5}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '177'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.openai.com
|
||||
user-agent:
|
||||
- OpenAI/Python 1.59.7
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 1.59.7
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.openai.com/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: "{\n \"id\": \"chatcmpl-ApkAbxV6BBqNLiaQQ6a5HCEwXLmAA\",\n \"object\":
|
||||
\"chat.completion\",\n \"created\": 1736895569,\n \"model\": \"gpt-4o-mini-2024-07-18\",\n
|
||||
\ \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\":
|
||||
\"assistant\",\n \"content\": \"Hello! I hope you\u2019re having a
|
||||
wonderful day. If there\u2019s anything you need or want to chat about, I\u2019m
|
||||
here to help!\",\n \"refusal\": null\n },\n \"logprobs\":
|
||||
null,\n \"finish_reason\": \"stop\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\":
|
||||
22,\n \"completion_tokens\": 30,\n \"total_tokens\": 52,\n \"prompt_tokens_details\":
|
||||
{\n \"cached_tokens\": 0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\":
|
||||
{\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\":
|
||||
0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\":
|
||||
\"default\",\n \"system_fingerprint\": \"fp_72ed7ab54c\"\n}\n"
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:59:29 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Set-Cookie:
|
||||
- __cf_bm=nTeqBB.FJ5L9.tbK3OsjnVgVy7JPWjJ9RZnapxrmcLM-1736895569-1.0.1.1-vCajXrvKFmqMzUrU9zgBZJ77gDpRA.cbrXEeDgDrsAu3arBGzLXq57EGoqyUKccq78JSRukW3JgDJ9rCV1.kcA;
|
||||
path=/; expires=Tue, 14-Jan-25 23:29:29 GMT; domain=.api.openai.com; HttpOnly;
|
||||
Secure; SameSite=None
|
||||
- _cfuvid=1c1CTy6EGeF_f8IKNuP8XGQ5Dhogd_43ONVfCynasWg-1736895569861-0.0.1.1-604800000;
|
||||
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Content-Type-Options:
|
||||
- nosniff
|
||||
access-control-expose-headers:
|
||||
- X-Request-ID
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '900'
|
||||
openai-organization: REDACTED
|
||||
openai-processing-ms:
|
||||
- '673'
|
||||
openai-version:
|
||||
- '2020-10-01'
|
||||
strict-transport-security:
|
||||
- max-age=31536000; includeSubDomains; preload
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"messages": [{"role": "system", "content": "You are a helpful assistant."},
|
||||
{"role": "user", "content": "Write a short greeting."}], "model": "gpt-4o-mini",
|
||||
"stream": true, "temperature": 0.5}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '193'
|
||||
content-type:
|
||||
- application/json
|
||||
cookie:
|
||||
- __cf_bm=nTeqBB.FJ5L9.tbK3OsjnVgVy7JPWjJ9RZnapxrmcLM-1736895569-1.0.1.1-vCajXrvKFmqMzUrU9zgBZJ77gDpRA.cbrXEeDgDrsAu3arBGzLXq57EGoqyUKccq78JSRukW3JgDJ9rCV1.kcA;
|
||||
_cfuvid=1c1CTy6EGeF_f8IKNuP8XGQ5Dhogd_43ONVfCynasWg-1736895569861-0.0.1.1-604800000
|
||||
host:
|
||||
- api.openai.com
|
||||
user-agent:
|
||||
- OpenAI/Python 1.59.7
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 1.59.7
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.openai.com/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: 'data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"role":"assistant","content":"","refusal":null},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"!"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
I"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
hope"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
this"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
message"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
finds"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
you"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
well"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"."},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
W"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"ishing"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
you"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
a"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
day"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
filled"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
with"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
joy"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
and"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"
|
||||
positivity"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{"content":"!"},"logprobs":null,"finish_reason":null}]}
|
||||
|
||||
|
||||
data: {"id":"chatcmpl-ApkAcllY6kSBAXEp65QnRYCC1clJq","object":"chat.completion.chunk","created":1736895570,"model":"gpt-4o-mini-2024-07-18","service_tier":"default","system_fingerprint":"fp_72ed7ab54c","choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]}
|
||||
|
||||
|
||||
data: [DONE]
|
||||
|
||||
|
||||
'
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- text/event-stream; charset=utf-8
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:59:30 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Content-Type-Options:
|
||||
- nosniff
|
||||
access-control-expose-headers:
|
||||
- X-Request-ID
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
openai-organization: REDACTED
|
||||
openai-processing-ms:
|
||||
- '115'
|
||||
openai-version:
|
||||
- '2020-10-01'
|
||||
strict-transport-security:
|
||||
- max-age=31536000; includeSubDomains; preload
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
@@ -0,0 +1,383 @@
|
||||
interactions:
|
||||
- request:
|
||||
body: '{"messages":[{"content":"Come up with a random superpower that isn''t time
|
||||
travel. Just return the superpower in the format: ''Superpower: [superpower]''","role":"user"}],"model":"gpt-3.5-turbo-0125"}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '197'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.openai.com
|
||||
user-agent:
|
||||
- OpenAI/Python 1.58.1
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 1.58.1
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.openai.com/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: "{\n \"id\": \"chatcmpl-AoHTPHqwbIZuJtmSp27xPV1dJgdqU\",\n \"object\":
|
||||
\"chat.completion\",\n \"created\": 1736546931,\n \"model\": \"gpt-3.5-turbo-0125\",\n
|
||||
\ \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\":
|
||||
\"assistant\",\n \"content\": \"Superpower: Teleportation with a 10-second
|
||||
cooldown.\",\n \"refusal\": null\n },\n \"logprobs\": null,\n
|
||||
\ \"finish_reason\": \"stop\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\":
|
||||
37,\n \"completion_tokens\": 14,\n \"total_tokens\": 51,\n \"prompt_tokens_details\":
|
||||
{\n \"cached_tokens\": 0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\":
|
||||
{\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\":
|
||||
0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\":
|
||||
\"default\",\n \"system_fingerprint\": null\n}\n"
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Fri, 10 Jan 2025 22:08:52 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Set-Cookie:
|
||||
- __cf_bm=gVSuKE090cwCPGC2ij1P3M6P.TjqHcUowRM__4IefBc-1736546932-1.0.1.1-syFJSN768bpGgo3L.CXQTGK6FSmpcapJM5yEkELw0Ry_ICiOhfTqnjE0iK7gdhezhqHqqjVpYhiqnnVklxcWOg;
|
||||
path=/; expires=Fri, 10-Jan-25 22:38:52 GMT; domain=.api.openai.com; HttpOnly;
|
||||
Secure; SameSite=None
|
||||
- _cfuvid=H.a7r115OhkHYrVbjWLyEDbWuSeS437hGWvQsrOypsw-1736546932100-0.0.1.1-604800000;
|
||||
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Content-Type-Options:
|
||||
- nosniff
|
||||
access-control-expose-headers:
|
||||
- X-Request-ID
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '817'
|
||||
openai-organization: REDACTED
|
||||
openai-processing-ms:
|
||||
- '223'
|
||||
openai-version:
|
||||
- '2020-10-01'
|
||||
strict-transport-security:
|
||||
- max-age=31536000; includeSubDomains; preload
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"messages":[{"content":"Come up with a superhero name given this superpower:
|
||||
Teleportation with a 10-second cooldown.. Just return the superhero name in
|
||||
this format: ''Superhero: [superhero name]''","role":"user"}],"model":"gpt-3.5-turbo-0125"}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '243'
|
||||
content-type:
|
||||
- application/json
|
||||
cookie:
|
||||
- __cf_bm=gVSuKE090cwCPGC2ij1P3M6P.TjqHcUowRM__4IefBc-1736546932-1.0.1.1-syFJSN768bpGgo3L.CXQTGK6FSmpcapJM5yEkELw0Ry_ICiOhfTqnjE0iK7gdhezhqHqqjVpYhiqnnVklxcWOg;
|
||||
_cfuvid=H.a7r115OhkHYrVbjWLyEDbWuSeS437hGWvQsrOypsw-1736546932100-0.0.1.1-604800000
|
||||
host:
|
||||
- api.openai.com
|
||||
user-agent:
|
||||
- OpenAI/Python 1.58.1
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 1.58.1
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.openai.com/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: "{\n \"id\": \"chatcmpl-AoHTQOXJl7sPJkuNv3WWKCbIGmkPx\",\n \"object\":
|
||||
\"chat.completion\",\n \"created\": 1736546932,\n \"model\": \"gpt-3.5-turbo-0125\",\n
|
||||
\ \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\":
|
||||
\"assistant\",\n \"content\": \"Superhero: Warp Runner\",\n \"refusal\":
|
||||
null\n },\n \"logprobs\": null,\n \"finish_reason\": \"stop\"\n
|
||||
\ }\n ],\n \"usage\": {\n \"prompt_tokens\": 46,\n \"completion_tokens\":
|
||||
6,\n \"total_tokens\": 52,\n \"prompt_tokens_details\": {\n \"cached_tokens\":
|
||||
0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\":
|
||||
{\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\":
|
||||
0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\":
|
||||
\"default\",\n \"system_fingerprint\": null\n}\n"
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Fri, 10 Jan 2025 22:08:52 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Content-Type-Options:
|
||||
- nosniff
|
||||
access-control-expose-headers:
|
||||
- X-Request-ID
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '786'
|
||||
openai-organization: REDACTED
|
||||
openai-processing-ms:
|
||||
- '155'
|
||||
openai-version:
|
||||
- '2020-10-01'
|
||||
strict-transport-security:
|
||||
- max-age=31536000; includeSubDomains; preload
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"messages": [{"content": "Come up with a random superpower that isn''t
|
||||
time travel. Just return the superpower in the format: ''Superpower: [superpower]''",
|
||||
"role": "user"}], "model": "gpt-3.5-turbo-0125"}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '203'
|
||||
content-type:
|
||||
- application/json
|
||||
host:
|
||||
- api.openai.com
|
||||
user-agent:
|
||||
- OpenAI/Python 1.59.7
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 1.59.7
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.openai.com/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: "{\n \"id\": \"chatcmpl-ApjGpJLZKBGzQuUCeGIOaUgpXt6i7\",\n \"object\":
|
||||
\"chat.completion\",\n \"created\": 1736892111,\n \"model\": \"gpt-3.5-turbo-0125\",\n
|
||||
\ \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\":
|
||||
\"assistant\",\n \"content\": \"Superpower: Teleportation through shadows\",\n
|
||||
\ \"refusal\": null\n },\n \"logprobs\": null,\n \"finish_reason\":
|
||||
\"stop\"\n }\n ],\n \"usage\": {\n \"prompt_tokens\": 37,\n \"completion_tokens\":
|
||||
9,\n \"total_tokens\": 46,\n \"prompt_tokens_details\": {\n \"cached_tokens\":
|
||||
0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\":
|
||||
{\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\":
|
||||
0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\":
|
||||
\"default\",\n \"system_fingerprint\": null\n}\n"
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:52 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Set-Cookie:
|
||||
- __cf_bm=ZPVtn0TX1xambDiDBLMcc4GeI8m9t7gQEuS6tIDMi38-1736892112-1.0.1.1-5ig.abnmjesQIT5LM6d2kP.pXUFFpLYSFn4fHEVM01xGlRgYxSJRK98EwgFm0pho_8kla2mcW7sTPfnA3RrJYg;
|
||||
path=/; expires=Tue, 14-Jan-25 22:31:52 GMT; domain=.api.openai.com; HttpOnly;
|
||||
Secure; SameSite=None
|
||||
- _cfuvid=XclfZFSELOpjFqPgDD70pD0Fsoopn6I_HlkxPw.5ST0-1736892112381-0.0.1.1-604800000;
|
||||
path=/; domain=.api.openai.com; HttpOnly; Secure; SameSite=None
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Content-Type-Options:
|
||||
- nosniff
|
||||
access-control-expose-headers:
|
||||
- X-Request-ID
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '805'
|
||||
openai-organization: REDACTED
|
||||
openai-processing-ms:
|
||||
- '453'
|
||||
openai-version:
|
||||
- '2020-10-01'
|
||||
strict-transport-security:
|
||||
- max-age=31536000; includeSubDomains; preload
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
- request:
|
||||
body: '{"messages": [{"content": "Come up with a superhero name given this superpower:
|
||||
Teleportation through shadows. Just return the superhero name in this format:
|
||||
''Superhero: [superhero name]''", "role": "user"}], "model": "gpt-3.5-turbo-0125"}'
|
||||
headers:
|
||||
accept:
|
||||
- application/json
|
||||
accept-encoding:
|
||||
- gzip, deflate
|
||||
authorization:
|
||||
- REDACTED
|
||||
connection:
|
||||
- keep-alive
|
||||
content-length:
|
||||
- '238'
|
||||
content-type:
|
||||
- application/json
|
||||
cookie:
|
||||
- __cf_bm=ZPVtn0TX1xambDiDBLMcc4GeI8m9t7gQEuS6tIDMi38-1736892112-1.0.1.1-5ig.abnmjesQIT5LM6d2kP.pXUFFpLYSFn4fHEVM01xGlRgYxSJRK98EwgFm0pho_8kla2mcW7sTPfnA3RrJYg;
|
||||
_cfuvid=XclfZFSELOpjFqPgDD70pD0Fsoopn6I_HlkxPw.5ST0-1736892112381-0.0.1.1-604800000
|
||||
host:
|
||||
- api.openai.com
|
||||
user-agent:
|
||||
- OpenAI/Python 1.59.7
|
||||
x-stainless-arch:
|
||||
- REDACTED
|
||||
x-stainless-async:
|
||||
- REDACTED
|
||||
x-stainless-lang:
|
||||
- REDACTED
|
||||
x-stainless-os:
|
||||
- REDACTED
|
||||
x-stainless-package-version:
|
||||
- 1.59.7
|
||||
x-stainless-retry-count:
|
||||
- '0'
|
||||
x-stainless-runtime:
|
||||
- REDACTED
|
||||
x-stainless-runtime-version:
|
||||
- REDACTED
|
||||
method: POST
|
||||
uri: https://api.openai.com/v1/chat/completions
|
||||
response:
|
||||
body:
|
||||
string: "{\n \"id\": \"chatcmpl-ApjGqLWaiyYdARpbf52BP2RNnBDiu\",\n \"object\":
|
||||
\"chat.completion\",\n \"created\": 1736892112,\n \"model\": \"gpt-3.5-turbo-0125\",\n
|
||||
\ \"choices\": [\n {\n \"index\": 0,\n \"message\": {\n \"role\":
|
||||
\"assistant\",\n \"content\": \"Superhero: Shadow Dasher\",\n \"refusal\":
|
||||
null\n },\n \"logprobs\": null,\n \"finish_reason\": \"stop\"\n
|
||||
\ }\n ],\n \"usage\": {\n \"prompt_tokens\": 42,\n \"completion_tokens\":
|
||||
7,\n \"total_tokens\": 49,\n \"prompt_tokens_details\": {\n \"cached_tokens\":
|
||||
0,\n \"audio_tokens\": 0\n },\n \"completion_tokens_details\":
|
||||
{\n \"reasoning_tokens\": 0,\n \"audio_tokens\": 0,\n \"accepted_prediction_tokens\":
|
||||
0,\n \"rejected_prediction_tokens\": 0\n }\n },\n \"service_tier\":
|
||||
\"default\",\n \"system_fingerprint\": null\n}\n"
|
||||
headers:
|
||||
CF-Cache-Status:
|
||||
- DYNAMIC
|
||||
CF-RAY: REDACTED
|
||||
Connection:
|
||||
- keep-alive
|
||||
Content-Type:
|
||||
- application/json
|
||||
Date:
|
||||
- Tue, 14 Jan 2025 22:01:53 GMT
|
||||
Server:
|
||||
- cloudflare
|
||||
Transfer-Encoding:
|
||||
- chunked
|
||||
X-Content-Type-Options:
|
||||
- nosniff
|
||||
access-control-expose-headers:
|
||||
- X-Request-ID
|
||||
alt-svc:
|
||||
- h3=":443"; ma=86400
|
||||
content-length:
|
||||
- '788'
|
||||
openai-organization: REDACTED
|
||||
openai-processing-ms:
|
||||
- '355'
|
||||
openai-version:
|
||||
- '2020-10-01'
|
||||
strict-transport-security:
|
||||
- max-age=31536000; includeSubDomains; preload
|
||||
x-ratelimit-limit-requests: REDACTED
|
||||
x-ratelimit-limit-tokens: REDACTED
|
||||
x-ratelimit-remaining-requests: REDACTED
|
||||
x-ratelimit-remaining-tokens: REDACTED
|
||||
x-ratelimit-reset-requests: REDACTED
|
||||
x-ratelimit-reset-tokens: REDACTED
|
||||
x-request-id: REDACTED
|
||||
status:
|
||||
code: 200
|
||||
message: OK
|
||||
version: 1
|
||||
Vendored
+108
@@ -0,0 +1,108 @@
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
import os
|
||||
from vcr.record_mode import RecordMode
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def vcr_config():
|
||||
"""Configure VCR.py for recording HTTP interactions.
|
||||
|
||||
This fixture sets up VCR.py with:
|
||||
- YAML serialization
|
||||
- Cassette storage in fixtures/recordings
|
||||
- Comprehensive header filtering for API keys and sensitive data
|
||||
- Request matching on URI, method, and body
|
||||
"""
|
||||
# Define cassette storage location
|
||||
vcr_cassettes = Path(__file__).parent / "recordings"
|
||||
vcr_cassettes.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Define sensitive headers to filter
|
||||
sensitive_headers = [
|
||||
# Generic API authentication
|
||||
("authorization", "REDACTED"),
|
||||
("x-api-key", "REDACTED"),
|
||||
("api-key", "REDACTED"),
|
||||
("bearer", "REDACTED"),
|
||||
# AgentOps API keys
|
||||
("x-agentops-api-key", "REDACTED"),
|
||||
# LLM service API keys
|
||||
("openai-api-key", "REDACTED"),
|
||||
("anthropic-api-key", "REDACTED"),
|
||||
("cohere-api-key", "REDACTED"),
|
||||
("x-cohere-api-key", "REDACTED"),
|
||||
("ai21-api-key", "REDACTED"),
|
||||
("x-ai21-api-key", "REDACTED"),
|
||||
("replicate-api-token", "REDACTED"),
|
||||
("huggingface-api-key", "REDACTED"),
|
||||
("x-huggingface-api-key", "REDACTED"),
|
||||
("claude-api-key", "REDACTED"),
|
||||
("x-claude-api-key", "REDACTED"),
|
||||
("x-railway-request-id", "REDACTED"),
|
||||
("X-Railway-Request-Id", "REDACTED"),
|
||||
# Authentication tokens
|
||||
("x-api-token", "REDACTED"),
|
||||
("api-token", "REDACTED"),
|
||||
("x-auth-token", "REDACTED"),
|
||||
("x-session-token", "REDACTED"),
|
||||
# OpenAI specific headers
|
||||
("openai-organization", "REDACTED"),
|
||||
("x-request-id", "REDACTED"),
|
||||
("__cf_bm", "REDACTED"),
|
||||
("_cfuvid", "REDACTED"),
|
||||
("cf-ray", "REDACTED"),
|
||||
# Rate limit headers
|
||||
("x-ratelimit-limit-requests", "REDACTED"),
|
||||
("x-ratelimit-limit-tokens", "REDACTED"),
|
||||
("x-ratelimit-remaining-requests", "REDACTED"),
|
||||
("x-ratelimit-remaining-tokens", "REDACTED"),
|
||||
("x-ratelimit-reset-requests", "REDACTED"),
|
||||
("x-ratelimit-reset-tokens", "REDACTED"),
|
||||
# Mistral headers
|
||||
("x-mistral-api-key", "REDACTED"),
|
||||
# Groq headers
|
||||
("x-groq-api-key", "REDACTED"),
|
||||
# LiteLLM headers
|
||||
("x-litellm-api-key", "REDACTED"),
|
||||
# Ollama headers
|
||||
("x-ollama-api-key", "REDACTED"),
|
||||
# TaskWeaver headers
|
||||
("x-taskweaver-api-key", "REDACTED"),
|
||||
# Additional provider version headers
|
||||
("anthropic-version", "REDACTED"),
|
||||
("cohere-version", "REDACTED"),
|
||||
("x-stainless-lang", "REDACTED"),
|
||||
("x-stainless-arch", "REDACTED"),
|
||||
("x-stainless-os", "REDACTED"),
|
||||
("x-stainless-async", "REDACTED"),
|
||||
("x-stainless-runtime", "REDACTED"),
|
||||
("x-stainless-runtime-version", "REDACTED"),
|
||||
]
|
||||
|
||||
def filter_response_headers(response):
|
||||
"""Filter sensitive headers from response."""
|
||||
headers = response["headers"]
|
||||
headers_lower = {k.lower(): k for k in headers} # Map of lowercase -> original header names
|
||||
|
||||
for header, replacement in sensitive_headers:
|
||||
header_lower = header.lower()
|
||||
if header_lower in headers_lower:
|
||||
# Replace using the original header name from the response
|
||||
original_header = headers_lower[header_lower]
|
||||
headers[original_header] = replacement
|
||||
return response
|
||||
|
||||
vcr_config = {
|
||||
"filter_headers": [
|
||||
"authorization",
|
||||
"Authorization",
|
||||
"X-OpenAI-Client-User-Agent",
|
||||
],
|
||||
"match_on": ["method", "scheme", "host", "port", "path", "query"],
|
||||
"record_mode": RecordMode.ONCE if os.getenv("CI") else RecordMode.NEW_EPISODES,
|
||||
"path_transformer": lambda path: path.replace("\\", "/"),
|
||||
"record_on_exception": False,
|
||||
}
|
||||
|
||||
return vcr_config
|
||||
@@ -0,0 +1,86 @@
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import agentops
|
||||
|
||||
import openai
|
||||
import anthropic
|
||||
from agentops.client import Client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_api_key():
|
||||
"""Fixture to provide a mock API key."""
|
||||
return "test-api-key-" + "x" * 32
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_auth_response():
|
||||
"""Fixture to provide a mock authentication response."""
|
||||
return MagicMock(status_code=200, json=lambda: {"access_token": "mock_token"})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def agentops_client(mock_api_key, monkeypatch):
|
||||
"""Fixture to provide an initialized AgentOps client."""
|
||||
# Create a mock auth response
|
||||
mock_auth = MagicMock()
|
||||
mock_auth.authenticate = lambda x: True
|
||||
mock_auth.is_authenticated = True
|
||||
|
||||
# Create the client
|
||||
client = Client()
|
||||
|
||||
# Mock the auth module
|
||||
monkeypatch.setattr(client, "api", MagicMock(auth=mock_auth))
|
||||
|
||||
# Initialize with mock key
|
||||
client.init(api_key=mock_api_key)
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def agentops_session(agentops_client):
|
||||
"""Fixture to manage AgentOps session."""
|
||||
agentops.start_session()
|
||||
yield
|
||||
agentops.end_all_sessions()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def openai_client():
|
||||
"""Fixture to provide OpenAI client with mock API key."""
|
||||
client = openai.OpenAI(api_key="test-openai-key")
|
||||
# Mock the completions API
|
||||
client.chat.completions.create = MagicMock()
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anthropic_client():
|
||||
"""Fixture to provide Anthropic client with mock API key."""
|
||||
client = anthropic.Anthropic(api_key="test-anthropic-key")
|
||||
# Mock the messages API
|
||||
client.messages.create = MagicMock()
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_messages():
|
||||
"""Fixture to provide test messages."""
|
||||
return [{"role": "user", "content": "Write a short greeting."}]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_response():
|
||||
"""Fixture to provide a mock response for testing."""
|
||||
return MagicMock(choices=[MagicMock(message=MagicMock(content="Hello! This is a test response."))])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_stream_response():
|
||||
"""Fixture to provide a mock streaming response."""
|
||||
return [
|
||||
MagicMock(choices=[MagicMock(delta=MagicMock(content="Hello"))]),
|
||||
MagicMock(choices=[MagicMock(delta=MagicMock(content=" World!"))]),
|
||||
]
|
||||
@@ -0,0 +1,52 @@
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from agentops.client import Client
|
||||
from agentops.exceptions import InvalidApiKeyException, ApiServerException
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_client():
|
||||
"""Reset the client singleton between tests"""
|
||||
# Reset the singleton instance
|
||||
Client._Client__instance = None
|
||||
yield
|
||||
# Clean up after test
|
||||
Client._Client__instance = None
|
||||
|
||||
|
||||
@pytest.mark.vcr()
|
||||
def test_auth_flow(mock_api_key):
|
||||
"""Test the authentication flow using the AgentOps client."""
|
||||
with patch("agentops.client.client.ApiClient") as mock_api_client:
|
||||
# Create mock API instance
|
||||
mock_api = MagicMock()
|
||||
mock_api.v3.fetch_auth_token.return_value = {"token": "mock_token", "project_id": "mock_project_id"}
|
||||
mock_api_client.return_value = mock_api
|
||||
|
||||
# Initialize the client
|
||||
client = Client()
|
||||
session = client.init(api_key=mock_api_key)
|
||||
|
||||
# Verify client is initialized
|
||||
assert client.initialized
|
||||
assert client.api is not None
|
||||
|
||||
# Verify session is created if auto_start_session is True
|
||||
if client.config.auto_start_session:
|
||||
assert session is not None
|
||||
|
||||
|
||||
@pytest.mark.vcr()
|
||||
def test_auth_flow_invalid_key():
|
||||
"""Test authentication flow with invalid API key."""
|
||||
with patch("agentops.client.client.ApiClient") as mock_api_client:
|
||||
# Create mock API instance that raises an error
|
||||
mock_api = MagicMock()
|
||||
mock_api.v3.fetch_auth_token.side_effect = ApiServerException("Invalid API key")
|
||||
mock_api_client.return_value = mock_api
|
||||
|
||||
client = Client()
|
||||
with pytest.raises((InvalidApiKeyException, ApiServerException)) as exc_info:
|
||||
client.init(api_key="invalid-key")
|
||||
|
||||
assert "Invalid API key" in str(exc_info.value)
|
||||
@@ -0,0 +1,360 @@
|
||||
import asyncio
|
||||
from asyncio import TimeoutError
|
||||
from typing import Any, Dict, List
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def collect_stream_content(stream_response: Any, provider: str) -> List[str]:
|
||||
"""Collect streaming content based on provider-specific response format."""
|
||||
collected_content = []
|
||||
|
||||
handlers = {
|
||||
"openai": lambda chunk: chunk.choices[0].delta.content,
|
||||
"anthropic": lambda event: event.delta.text if event.type == "content_block_delta" else None,
|
||||
"cohere": lambda event: event.text if event.event_type == "text-generation" else None,
|
||||
"ai21": lambda chunk: chunk.choices[0].delta.content,
|
||||
"groq": lambda chunk: chunk.choices[0].delta.content,
|
||||
"mistral": lambda event: event.data.choices[0].delta.content
|
||||
if hasattr(event.data.choices[0].delta, "content")
|
||||
else None,
|
||||
"litellm": lambda chunk: chunk.choices[0].delta.content if hasattr(chunk.choices[0].delta, "content") else None,
|
||||
"ollama": lambda chunk: chunk["message"]["content"] if "message" in chunk else None,
|
||||
}
|
||||
|
||||
handler = handlers.get(provider)
|
||||
if not handler:
|
||||
raise ValueError(f"Unknown provider: {provider}")
|
||||
|
||||
for chunk in stream_response:
|
||||
if chunk_content := handler(chunk):
|
||||
collected_content.append(chunk_content)
|
||||
|
||||
return collected_content
|
||||
|
||||
|
||||
# OpenAI Tests
|
||||
@pytest.mark.vcr()
|
||||
def test_openai_provider(openai_client, test_messages: List[Dict[str, Any]], mock_response):
|
||||
"""Test OpenAI provider integration."""
|
||||
# Mock the client's create method
|
||||
openai_client.chat.completions.create = MagicMock(return_value=mock_response)
|
||||
|
||||
# Sync completion
|
||||
response = openai_client.chat.completions.create(
|
||||
model="gpt-4",
|
||||
messages=test_messages,
|
||||
temperature=0.5,
|
||||
)
|
||||
assert response.choices[0].message.content
|
||||
|
||||
# Stream completion
|
||||
mock_stream = [
|
||||
MagicMock(choices=[MagicMock(delta=MagicMock(content="Hello"))]),
|
||||
MagicMock(choices=[MagicMock(delta=MagicMock(content=" World"))]),
|
||||
]
|
||||
openai_client.chat.completions.create = MagicMock(return_value=mock_stream)
|
||||
|
||||
stream = openai_client.chat.completions.create(
|
||||
model="gpt-4",
|
||||
messages=test_messages,
|
||||
temperature=0.5,
|
||||
stream=True,
|
||||
)
|
||||
content = collect_stream_content(stream, "openai")
|
||||
assert len(content) > 0
|
||||
assert "".join(content) == "Hello World"
|
||||
|
||||
|
||||
# Assistants API Tests (OpenAI)
|
||||
@pytest.mark.skip(reason="TODO: OpenAI Assistants API integration test needs to be implemented")
|
||||
@pytest.mark.vcr()
|
||||
async def test_openai_assistants_provider(openai_client):
|
||||
"""Test OpenAI Assistants API integration for all overridden methods."""
|
||||
# Test Assistants CRUD operations
|
||||
# Create
|
||||
assistant = openai_client.beta.assistants.create(
|
||||
name="Math Tutor",
|
||||
instructions="You are a personal math tutor. Write and run code to answer math questions.",
|
||||
tools=[{"type": "code_interpreter"}],
|
||||
model="gpt-4o-mini",
|
||||
)
|
||||
assert assistant.id.startswith("asst_")
|
||||
|
||||
# Retrieve
|
||||
retrieved_assistant = openai_client.beta.assistants.retrieve(assistant.id)
|
||||
assert retrieved_assistant.id == assistant.id
|
||||
|
||||
# Update
|
||||
updated_assistant = openai_client.beta.assistants.update(
|
||||
assistant.id,
|
||||
name="Advanced Math Tutor",
|
||||
instructions="You are an advanced math tutor. Explain concepts in detail.",
|
||||
)
|
||||
assert updated_assistant.name == "Advanced Math Tutor"
|
||||
|
||||
# List
|
||||
assistants_list = openai_client.beta.assistants.list()
|
||||
assert any(a.id == assistant.id for a in assistants_list.data)
|
||||
|
||||
# Test Threads CRUD operations
|
||||
# Create
|
||||
thread = openai_client.beta.threads.create()
|
||||
assert thread.id.startswith("thread_")
|
||||
|
||||
# Add Multiple Messages
|
||||
message1 = openai_client.beta.threads.messages.create(
|
||||
thread_id=thread.id, role="user", content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
|
||||
)
|
||||
message2 = openai_client.beta.threads.messages.create(
|
||||
thread_id=thread.id, role="user", content="Also, what is the square root of 144?"
|
||||
)
|
||||
assert message1.content[0].text.value
|
||||
assert message2.content[0].text.value
|
||||
|
||||
# Create and monitor run
|
||||
run = openai_client.beta.threads.runs.create(thread_id=thread.id, assistant_id=assistant.id)
|
||||
assert run.id.startswith("run_")
|
||||
|
||||
# Monitor run status with timeout
|
||||
async def check_run_status():
|
||||
while True:
|
||||
run_status = openai_client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
|
||||
print(f"Current run status: {run_status.status}") # Print status for debugging
|
||||
if run_status.status in ["completed", "failed", "cancelled", "expired"]:
|
||||
return run_status
|
||||
await asyncio.sleep(1)
|
||||
|
||||
try:
|
||||
await asyncio.wait_for(check_run_status(), timeout=10) # Shorter timeout
|
||||
except TimeoutError:
|
||||
# Cancel the run if it's taking too long
|
||||
openai_client.beta.threads.runs.cancel(thread_id=thread.id, run_id=run.id)
|
||||
pytest.skip("Assistant run timed out and was cancelled")
|
||||
|
||||
# Get run steps
|
||||
run_steps = openai_client.beta.threads.runs.steps.list(thread_id=thread.id, run_id=run.id)
|
||||
assert len(run_steps.data) > 0
|
||||
|
||||
# List messages
|
||||
messages = openai_client.beta.threads.messages.list(thread_id=thread.id)
|
||||
assert len(messages.data) > 0
|
||||
|
||||
# Update thread
|
||||
updated_thread = openai_client.beta.threads.update(thread.id, metadata={"test": "value"})
|
||||
assert updated_thread.metadata.get("test") == "value"
|
||||
|
||||
# Clean up
|
||||
openai_client.beta.threads.delete(thread.id)
|
||||
openai_client.beta.assistants.delete(assistant.id)
|
||||
|
||||
|
||||
# Anthropic Tests
|
||||
@pytest.mark.vcr()
|
||||
def test_anthropic_provider(anthropic_client, test_messages: List[Dict[str, Any]], mock_response):
|
||||
"""Test Anthropic provider integration."""
|
||||
# Mock the client's create method
|
||||
anthropic_client.messages.create = MagicMock(return_value=mock_response)
|
||||
|
||||
# Sync completion
|
||||
response = anthropic_client.messages.create(
|
||||
max_tokens=1024,
|
||||
model="claude-3-sonnet-20240229",
|
||||
messages=test_messages,
|
||||
system="You are a helpful assistant.",
|
||||
)
|
||||
assert response.content[0].text
|
||||
|
||||
# Stream completion
|
||||
mock_stream = [
|
||||
MagicMock(type="content_block_delta", delta=MagicMock(text="Hello")),
|
||||
MagicMock(type="content_block_delta", delta=MagicMock(text=" World")),
|
||||
]
|
||||
anthropic_client.messages.create = MagicMock(return_value=mock_stream)
|
||||
|
||||
stream = anthropic_client.messages.create(
|
||||
max_tokens=1024,
|
||||
model="claude-3-sonnet-20240229",
|
||||
messages=test_messages,
|
||||
stream=True,
|
||||
)
|
||||
content = collect_stream_content(stream, "anthropic")
|
||||
assert len(content) > 0
|
||||
assert "".join(content) == "Hello World"
|
||||
|
||||
|
||||
# AI21 Tests
|
||||
@pytest.mark.skip(reason="TODO: instrumentation")
|
||||
def test_ai21_provider(ai21_client, ai21_async_client, ai21_test_messages: List[Dict[str, Any]]):
|
||||
"""Test AI21 provider integration."""
|
||||
# Sync completion
|
||||
response = ai21_client.chat.completions.create(
|
||||
model="jamba-1.5-mini",
|
||||
messages=ai21_test_messages,
|
||||
)
|
||||
assert response.choices[0].message.content
|
||||
|
||||
# Stream completion
|
||||
stream = ai21_client.chat.completions.create(
|
||||
model="jamba-1.5-mini",
|
||||
messages=ai21_test_messages,
|
||||
stream=True,
|
||||
)
|
||||
content = collect_stream_content(stream, "ai21")
|
||||
assert len(content) > 0
|
||||
|
||||
# Async completion
|
||||
async def async_test():
|
||||
response = await ai21_async_client.chat.completions.create(
|
||||
model="jamba-1.5-mini",
|
||||
messages=ai21_test_messages,
|
||||
)
|
||||
return response
|
||||
|
||||
async_response = asyncio.run(async_test())
|
||||
assert async_response.choices[0].message.content
|
||||
|
||||
|
||||
# Cohere Tests
|
||||
@pytest.mark.skip(reason="TODO: instrumentation")
|
||||
def test_cohere_provider(cohere_client):
|
||||
"""Test Cohere provider integration."""
|
||||
# Sync chat
|
||||
response = cohere_client.chat(message="Say hello in spanish")
|
||||
assert response.text
|
||||
|
||||
# Stream chat
|
||||
stream = cohere_client.chat_stream(message="Say hello in spanish")
|
||||
content = collect_stream_content(stream, "cohere")
|
||||
assert len(content) > 0
|
||||
|
||||
|
||||
# Groq Tests
|
||||
@pytest.mark.skip(reason="TODO: instrumentation")
|
||||
def test_groq_provider(groq_client, test_messages: List[Dict[str, Any]]):
|
||||
"""Test Groq provider integration."""
|
||||
# Sync completion
|
||||
response = groq_client.chat.completions.create(
|
||||
model="llama3-70b-8192",
|
||||
messages=test_messages,
|
||||
)
|
||||
assert response.choices[0].message.content
|
||||
|
||||
# Stream completion
|
||||
stream = groq_client.chat.completions.create(
|
||||
model="llama3-70b-8192",
|
||||
messages=test_messages,
|
||||
stream=True,
|
||||
)
|
||||
content = collect_stream_content(stream, "groq")
|
||||
assert len(content) > 0
|
||||
|
||||
|
||||
# Mistral Tests
|
||||
@pytest.mark.skip(reason="TODO: instrumentation")
|
||||
def test_mistral_provider(mistral_client, test_messages: List[Dict[str, Any]]):
|
||||
"""Test Mistral provider integration."""
|
||||
# Sync completion
|
||||
response = mistral_client.chat.complete(
|
||||
model="open-mistral-nemo",
|
||||
messages=test_messages,
|
||||
)
|
||||
assert response.choices[0].message.content
|
||||
|
||||
# Stream completion
|
||||
stream = mistral_client.chat.stream(
|
||||
model="open-mistral-nemo",
|
||||
messages=test_messages,
|
||||
)
|
||||
content = collect_stream_content(stream, "mistral")
|
||||
assert len(content) > 0
|
||||
|
||||
# Async completion
|
||||
async def async_test():
|
||||
response = await mistral_client.chat.complete_async(
|
||||
model="open-mistral-nemo",
|
||||
messages=test_messages,
|
||||
)
|
||||
return response
|
||||
|
||||
async_response = asyncio.run(async_test())
|
||||
assert async_response.choices[0].message.content
|
||||
|
||||
|
||||
# LiteLLM Tests
|
||||
@pytest.mark.skip(reason="TODO: instrumentation for callback handlers and external integrations")
|
||||
def test_litellm_provider(litellm_client, test_messages: List[Dict[str, Any]]):
|
||||
"""Test LiteLLM provider integration."""
|
||||
# Sync completion
|
||||
response = litellm_client.completion(
|
||||
model="openai/gpt-4o-mini",
|
||||
messages=test_messages,
|
||||
)
|
||||
assert response.choices[0].message.content
|
||||
|
||||
# Stream completion
|
||||
stream_response = litellm_client.completion(
|
||||
model="anthropic/claude-3-5-sonnet-latest",
|
||||
messages=test_messages,
|
||||
stream=True,
|
||||
)
|
||||
content = collect_stream_content(stream_response, "litellm")
|
||||
assert len(content) > 0
|
||||
|
||||
# Async completion
|
||||
async def async_test():
|
||||
async_response = await litellm_client.acompletion(
|
||||
model="openrouter/deepseek/deepseek-chat",
|
||||
messages=test_messages,
|
||||
)
|
||||
return async_response
|
||||
|
||||
async_response = asyncio.run(async_test())
|
||||
assert async_response.choices[0].message.content
|
||||
|
||||
|
||||
# Ollama Tests
|
||||
@pytest.mark.skip(reason="TODO: instrumentation")
|
||||
def test_ollama_provider(test_messages: List[Dict[str, Any]]):
|
||||
"""Test Ollama provider integration."""
|
||||
import ollama
|
||||
from ollama import AsyncClient
|
||||
|
||||
try:
|
||||
# Test if Ollama server is running
|
||||
ollama.list()
|
||||
except Exception as e:
|
||||
pytest.skip(f"Ollama server not running: {e}")
|
||||
|
||||
try:
|
||||
# Sync chat
|
||||
response = ollama.chat(
|
||||
model="llama3.2:1b",
|
||||
messages=test_messages,
|
||||
)
|
||||
assert response["message"]["content"]
|
||||
|
||||
# Stream chat
|
||||
stream = ollama.chat(
|
||||
model="llama3.2:1b",
|
||||
messages=test_messages,
|
||||
stream=True,
|
||||
)
|
||||
content = collect_stream_content(stream, "ollama")
|
||||
assert len(content) > 0
|
||||
|
||||
# Async chat
|
||||
async def async_test():
|
||||
client = AsyncClient()
|
||||
response = await client.chat(
|
||||
model="llama3.2:1b",
|
||||
messages=test_messages,
|
||||
)
|
||||
return response
|
||||
|
||||
async_response = asyncio.run(async_test())
|
||||
assert async_response["message"]["content"]
|
||||
|
||||
except Exception as e:
|
||||
pytest.skip(f"Ollama test failed: {e}")
|
||||
@@ -0,0 +1,121 @@
|
||||
import pytest
|
||||
import concurrent.futures
|
||||
from unittest.mock import patch, MagicMock
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
import agentops
|
||||
from agentops.client import Client
|
||||
|
||||
# Create FastAPI app
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
def process_request(x: str):
|
||||
"""Process a request and return a response."""
|
||||
return f"Processed: {x}"
|
||||
|
||||
|
||||
@app.get("/completion")
|
||||
def completion():
|
||||
result = process_request("Hello")
|
||||
return {"response": result, "status": "success"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Fixture to provide FastAPI test client."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_agentops(mock_api_key):
|
||||
"""Setup AgentOps with mock API key."""
|
||||
# Reset client singleton
|
||||
Client._Client__instance = None
|
||||
|
||||
# Mock the API client to avoid real authentication
|
||||
with patch("agentops.client.client.ApiClient") as mock_api_client:
|
||||
# Create mock API instance
|
||||
mock_api = MagicMock()
|
||||
mock_api.v3.fetch_auth_token.return_value = {"token": "mock_token", "project_id": "mock_project_id"}
|
||||
mock_api_client.return_value = mock_api
|
||||
|
||||
# Mock global tracer to avoid actual initialization
|
||||
with patch("agentops.tracer") as mock_tracer:
|
||||
mock_tracer.initialized = True
|
||||
|
||||
agentops.init(api_key=mock_api_key, auto_start_session=True)
|
||||
yield
|
||||
|
||||
try:
|
||||
agentops.end_all_sessions()
|
||||
except:
|
||||
pass
|
||||
|
||||
# Clean up client singleton
|
||||
Client._Client__instance = None
|
||||
|
||||
|
||||
def test_concurrent_api_requests(client):
|
||||
"""Test concurrent API requests to ensure proper session handling."""
|
||||
|
||||
def fetch_url(test_client):
|
||||
response = test_client.get("/completion")
|
||||
assert response.status_code == 200
|
||||
return response.json()
|
||||
|
||||
# Make concurrent requests
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
||||
futures = [executor.submit(fetch_url, client) for _ in range(3)]
|
||||
responses = [future.result() for future in concurrent.futures.as_completed(futures)]
|
||||
|
||||
# Verify responses
|
||||
assert len(responses) == 3
|
||||
for response in responses:
|
||||
assert "response" in response
|
||||
assert response["response"] == "Processed: Hello"
|
||||
assert response["status"] == "success"
|
||||
|
||||
|
||||
def test_session_isolation():
|
||||
"""Test that basic functions work in parallel (simplified concurrency test)."""
|
||||
|
||||
def session_a():
|
||||
return process_request("A")
|
||||
|
||||
def session_b():
|
||||
return process_request("B")
|
||||
|
||||
# Run sessions in parallel
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||
future_a = executor.submit(session_a)
|
||||
future_b = executor.submit(session_b)
|
||||
|
||||
result_a = future_a.result()
|
||||
result_b = future_b.result()
|
||||
|
||||
assert result_a == "Processed: A"
|
||||
assert result_b == "Processed: B"
|
||||
|
||||
|
||||
def test_session_error_handling():
|
||||
"""Test error handling in concurrent execution."""
|
||||
|
||||
def error_session():
|
||||
raise ValueError("Test error")
|
||||
|
||||
def success_session():
|
||||
return process_request("Success")
|
||||
|
||||
# Run sessions in parallel
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||
error_future = executor.submit(error_session)
|
||||
success_future = executor.submit(success_session)
|
||||
|
||||
# Verify success case
|
||||
assert success_future.result() == "Processed: Success"
|
||||
|
||||
# Verify error case
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
error_future.result()
|
||||
assert "Test error" in str(exc_info.value)
|
||||
@@ -0,0 +1,17 @@
|
||||
import openai
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
|
||||
|
||||
def test_openai():
|
||||
import agentops
|
||||
|
||||
agentops.init(exporter=InMemorySpanExporter())
|
||||
agentops.start_session()
|
||||
|
||||
openai.chat.completions.create(
|
||||
model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Write a one-line joke"}]
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_openai()
|
||||
@@ -0,0 +1 @@
|
||||
"""Unit tests for the agentops.client package."""
|
||||
@@ -0,0 +1,205 @@
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from requests.models import Response
|
||||
|
||||
from agentops.client.api.versions.v4 import V4Client
|
||||
from agentops.exceptions import ApiServerException
|
||||
|
||||
|
||||
class TestV4Client:
|
||||
def setup_method(self):
|
||||
"""Set up test fixtures."""
|
||||
self.client = V4Client("https://api.agentops.com")
|
||||
self.client.auth_token = "test_token"
|
||||
|
||||
def test_set_auth_token(self):
|
||||
"""Test setting the authentication token."""
|
||||
client = V4Client("https://api.agentops.com")
|
||||
client.set_auth_token("new_token")
|
||||
assert client.auth_token == "new_token"
|
||||
|
||||
def test_prepare_headers_without_custom_headers(self):
|
||||
"""Test preparing headers without custom headers."""
|
||||
with patch("agentops.client.api.versions.v4.get_agentops_version", return_value="1.2.3"):
|
||||
headers = self.client.prepare_headers()
|
||||
|
||||
assert headers["Authorization"] == "Bearer test_token"
|
||||
assert headers["User-Agent"] == "agentops-python/1.2.3"
|
||||
|
||||
def test_prepare_headers_with_custom_headers(self):
|
||||
"""Test preparing headers with custom headers."""
|
||||
with patch("agentops.client.api.versions.v4.get_agentops_version", return_value="1.2.3"):
|
||||
custom_headers = {"X-Custom-Header": "custom_value"}
|
||||
headers = self.client.prepare_headers(custom_headers)
|
||||
|
||||
assert headers["Authorization"] == "Bearer test_token"
|
||||
assert headers["User-Agent"] == "agentops-python/1.2.3"
|
||||
assert headers["X-Custom-Header"] == "custom_value"
|
||||
|
||||
def test_prepare_headers_with_unknown_version(self):
|
||||
"""Test preparing headers when version is unknown."""
|
||||
with patch("agentops.client.api.versions.v4.get_agentops_version", return_value=None):
|
||||
headers = self.client.prepare_headers()
|
||||
|
||||
assert headers["Authorization"] == "Bearer test_token"
|
||||
assert headers["User-Agent"] == "agentops-python/unknown"
|
||||
|
||||
def test_upload_object_success_string(self):
|
||||
"""Test successful object upload with string body."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"url": "http://example.com", "size": 123}
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
result = self.client.upload_object("test content")
|
||||
|
||||
# Check that result is a dict with the expected structure
|
||||
assert isinstance(result, dict)
|
||||
assert result["url"] == "http://example.com"
|
||||
assert result["size"] == 123
|
||||
self.client.post.assert_called_once_with(
|
||||
"/v4/objects/upload/", "test content", self.client.prepare_headers()
|
||||
)
|
||||
|
||||
def test_upload_object_success_bytes(self):
|
||||
"""Test successful object upload with bytes body."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"url": "http://example.com", "size": 456}
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
result = self.client.upload_object(b"test content")
|
||||
|
||||
# Check that result is a dict with the expected structure
|
||||
assert isinstance(result, dict)
|
||||
assert result["url"] == "http://example.com"
|
||||
assert result["size"] == 456
|
||||
self.client.post.assert_called_once_with(
|
||||
"/v4/objects/upload/", "test content", self.client.prepare_headers()
|
||||
)
|
||||
|
||||
def test_upload_object_http_error(self):
|
||||
"""Test object upload with HTTP error."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 400
|
||||
mock_response.json.return_value = {"error": "Bad request"}
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
with pytest.raises(ApiServerException, match="Bad request"):
|
||||
self.client.upload_object("test content")
|
||||
|
||||
def test_upload_object_http_error_no_error_field(self):
|
||||
"""Test object upload with HTTP error but no error field in response."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 500
|
||||
mock_response.json.return_value = {"message": "Internal error"}
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
with pytest.raises(ApiServerException, match="Upload failed: 500"):
|
||||
self.client.upload_object("test content")
|
||||
|
||||
def test_upload_object_http_error_json_parse_failure(self):
|
||||
"""Test object upload with HTTP error and JSON parse failure."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 404
|
||||
mock_response.json.side_effect = Exception("JSON error")
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
with pytest.raises(ApiServerException, match="Upload failed: 404"):
|
||||
self.client.upload_object("test content")
|
||||
|
||||
def test_upload_object_response_parse_failure(self):
|
||||
"""Test object upload with successful HTTP but response parse failure."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 200
|
||||
# Make the json() call fail in the success block
|
||||
mock_response.json.side_effect = Exception("JSON parse error")
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
with pytest.raises(ApiServerException, match="Failed to process upload response"):
|
||||
self.client.upload_object("test content")
|
||||
|
||||
def test_upload_logfile_success_string(self):
|
||||
"""Test successful logfile upload with string body."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"url": "http://example.com/log", "size": 789}
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
result = self.client.upload_logfile("log content", 123)
|
||||
|
||||
# Check that result is a dict with the expected structure
|
||||
assert isinstance(result, dict)
|
||||
assert result["url"] == "http://example.com/log"
|
||||
assert result["size"] == 789
|
||||
|
||||
# Check that the post was called with the correct headers including Trace-Id
|
||||
call_args = self.client.post.call_args
|
||||
assert call_args[0][0] == "/v4/logs/upload/"
|
||||
assert call_args[0][1] == "log content"
|
||||
headers = call_args[0][2]
|
||||
assert headers["Trace-Id"] == "123"
|
||||
assert headers["Authorization"] == "Bearer test_token"
|
||||
|
||||
def test_upload_logfile_success_bytes(self):
|
||||
"""Test successful logfile upload with bytes body."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"url": "http://example.com/log", "size": 101}
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
result = self.client.upload_logfile(b"log content", 456)
|
||||
|
||||
# Check that result is a dict with the expected structure
|
||||
assert isinstance(result, dict)
|
||||
assert result["url"] == "http://example.com/log"
|
||||
assert result["size"] == 101
|
||||
|
||||
# Check that the post was called with the correct headers including Trace-Id
|
||||
call_args = self.client.post.call_args
|
||||
assert call_args[0][0] == "/v4/logs/upload/"
|
||||
assert call_args[0][1] == "log content"
|
||||
headers = call_args[0][2]
|
||||
assert headers["Trace-Id"] == "456"
|
||||
assert headers["Authorization"] == "Bearer test_token"
|
||||
|
||||
def test_upload_logfile_http_error(self):
|
||||
"""Test logfile upload with HTTP error."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 403
|
||||
mock_response.json.return_value = {"error": "Forbidden"}
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
with pytest.raises(ApiServerException, match="Forbidden"):
|
||||
self.client.upload_logfile("log content", 123)
|
||||
|
||||
def test_upload_logfile_http_error_no_error_field(self):
|
||||
"""Test logfile upload with HTTP error but no error field in response."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 500
|
||||
mock_response.json.return_value = {"message": "Internal error"}
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
with pytest.raises(ApiServerException, match="Upload failed: 500"):
|
||||
self.client.upload_logfile("log content", 123)
|
||||
|
||||
def test_upload_logfile_http_error_json_parse_failure(self):
|
||||
"""Test logfile upload with HTTP error and JSON parse failure."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 404
|
||||
mock_response.json.side_effect = Exception("JSON error")
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
with pytest.raises(ApiServerException, match="Upload failed: 404"):
|
||||
self.client.upload_logfile("log content", 123)
|
||||
|
||||
def test_upload_logfile_response_parse_failure(self):
|
||||
"""Test logfile upload with successful HTTP but response parse failure."""
|
||||
mock_response = Mock(spec=Response)
|
||||
mock_response.status_code = 200
|
||||
# Make the json() call fail in the success block
|
||||
mock_response.json.side_effect = Exception("JSON parse error")
|
||||
|
||||
with patch.object(self.client, "post", return_value=mock_response):
|
||||
with pytest.raises(ApiServerException, match="Failed to process upload response"):
|
||||
self.client.upload_logfile("log content", 123)
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Tests for the HTTP adapter classes."""
|
||||
|
||||
from urllib3.util import Retry
|
||||
|
||||
from agentops.client.http.http_adapter import BaseHTTPAdapter
|
||||
|
||||
# from agentops.client.auth_manager import AuthManager
|
||||
|
||||
|
||||
class TestBaseHTTPAdapter:
|
||||
"""Tests for the BaseHTTPAdapter class."""
|
||||
|
||||
def test_init_with_default_params(self):
|
||||
"""Test that the adapter initializes with default parameters."""
|
||||
adapter = BaseHTTPAdapter()
|
||||
|
||||
# Verify the adapter was created with the expected parameters
|
||||
assert adapter.poolmanager is not None
|
||||
|
||||
# Check that max_retries was set
|
||||
assert adapter.max_retries is not None
|
||||
assert isinstance(adapter.max_retries, Retry)
|
||||
assert adapter.max_retries.total == 3
|
||||
assert adapter.max_retries.backoff_factor == 0.1
|
||||
assert adapter.max_retries.status_forcelist == [500, 502, 503, 504]
|
||||
|
||||
def test_init_with_custom_params(self):
|
||||
"""Test that the adapter initializes with custom parameters."""
|
||||
custom_retry = Retry(total=5, backoff_factor=0.5, status_forcelist=[429, 500, 502, 503, 504])
|
||||
|
||||
adapter = BaseHTTPAdapter(pool_connections=20, pool_maxsize=300, max_retries=custom_retry)
|
||||
|
||||
# Verify the adapter was created with the expected parameters
|
||||
assert adapter.poolmanager is not None
|
||||
|
||||
# Check that max_retries was set to our custom value
|
||||
assert adapter.max_retries is custom_retry
|
||||
assert adapter.max_retries.total == 5
|
||||
assert adapter.max_retries.backoff_factor == 0.5
|
||||
assert adapter.max_retries.status_forcelist == [429, 500, 502, 503, 504]
|
||||
|
||||
|
||||
# class TestAuthenticatedHttpAdapter:
|
||||
# """Tests for the AuthenticatedHttpAdapter class."""
|
||||
#
|
||||
# @pytest.fixture
|
||||
# def auth_manager(self):
|
||||
# """Create an AuthManager for testing."""
|
||||
# return AuthManager(token_endpoint="https://api.example.com/auth/token")
|
||||
#
|
||||
# @pytest.fixture
|
||||
# def token_fetcher(self):
|
||||
# """Create a token fetcher function for testing."""
|
||||
# return mock.Mock(return_value={"token": "test-token", "project_id": "test-project"})
|
||||
#
|
||||
# def test_init(self, auth_manager, token_fetcher):
|
||||
# """Test that the adapter initializes correctly."""
|
||||
# adapter = AuthenticatedHttpAdapter(
|
||||
# auth_manager=auth_manager,
|
||||
# api_key="test-api-key",
|
||||
# token_fetcher=token_fetcher
|
||||
# )
|
||||
#
|
||||
# # Verify the adapter was created with the expected parameters
|
||||
# assert adapter.auth_manager is auth_manager
|
||||
# assert adapter.api_key == "test-api-key"
|
||||
# assert adapter.token_fetcher is token_fetcher
|
||||
#
|
||||
# # Verify it's a subclass of BaseHTTPAdapter
|
||||
# assert isinstance(adapter, BaseHTTPAdapter)
|
||||
#
|
||||
# def test_add_headers(self, auth_manager, token_fetcher):
|
||||
# """Test that add_headers adds authentication headers to the request."""
|
||||
# # Setup
|
||||
# adapter = AuthenticatedHttpAdapter(
|
||||
# auth_manager=auth_manager,
|
||||
# api_key="test-api-key",
|
||||
# token_fetcher=token_fetcher
|
||||
# )
|
||||
#
|
||||
# # Mock the auth manager methods
|
||||
# auth_manager.maybe_fetch = mock.Mock(return_value={"token": "test-token", "project_id": "test-project"})
|
||||
# auth_manager.prepare_auth_headers = mock.Mock(return_value={
|
||||
# "Authorization": "Bearer test-token",
|
||||
# "Content-Type": "application/json; charset=UTF-8",
|
||||
# "X-Agentops-Api-Key": "test-api-key"
|
||||
# })
|
||||
#
|
||||
# # Create a request
|
||||
# request = requests.Request('GET', 'https://api.example.com/test').prepare()
|
||||
#
|
||||
# # Call add_headers
|
||||
# modified_request = adapter.add_headers(request)
|
||||
#
|
||||
# # Verify the auth manager methods were called
|
||||
# auth_manager.maybe_fetch.assert_called_once_with("test-api-key", token_fetcher)
|
||||
# auth_manager.prepare_auth_headers.assert_called_once_with("test-api-key")
|
||||
#
|
||||
# # Verify the headers were added to the request
|
||||
# assert modified_request.headers["Authorization"] == "Bearer test-token"
|
||||
# assert modified_request.headers["Content-Type"] == "application/json; charset=UTF-8"
|
||||
# assert modified_request.headers["X-Agentops-Api-Key"] == "test-api-key"
|
||||
#
|
||||
# def test_send_success(self, auth_manager, token_fetcher, mocker: MockerFixture):
|
||||
# """Test that send successfully sends a request."""
|
||||
# # Setup
|
||||
# adapter = AuthenticatedHttpAdapter(
|
||||
# auth_manager=auth_manager,
|
||||
# api_key="test-api-key",
|
||||
# token_fetcher=token_fetcher
|
||||
# )
|
||||
#
|
||||
# # Mock the add_headers method
|
||||
# mocker.patch.object(adapter, 'add_headers', side_effect=lambda r, **kw: r)
|
||||
#
|
||||
# # Mock the parent send method
|
||||
# mock_response = mock.Mock(spec=requests.Response)
|
||||
# mock_response.status_code = 200
|
||||
# mocker.patch.object(BaseHTTPAdapter, 'send', return_value=mock_response)
|
||||
#
|
||||
# # Mock the is_token_expired_response method
|
||||
# auth_manager.is_token_expired_response = mock.Mock(return_value=False)
|
||||
#
|
||||
# # Create a request
|
||||
# request = requests.Request('GET', 'https://api.example.com/test').prepare()
|
||||
#
|
||||
# # Call send
|
||||
# response = adapter.send(request)
|
||||
#
|
||||
# # Verify the response
|
||||
# assert response is mock_response
|
||||
# assert response.status_code == 200
|
||||
#
|
||||
# # Verify the methods were called
|
||||
# adapter.add_headers.assert_called_once()
|
||||
# BaseHTTPAdapter.send.assert_called_once()
|
||||
# auth_manager.is_token_expired_response.assert_called_once_with(mock_response)
|
||||
#
|
||||
# def test_send_with_token_refresh(self, auth_manager, token_fetcher, mocker: MockerFixture):
|
||||
# """Test that send refreshes the token if it's expired."""
|
||||
# # Setup
|
||||
# adapter = AuthenticatedHttpAdapter(
|
||||
# auth_manager=auth_manager,
|
||||
# api_key="test-api-key",
|
||||
# token_fetcher=token_fetcher
|
||||
# )
|
||||
#
|
||||
# # Mock the add_headers method
|
||||
# mocker.patch.object(adapter, 'add_headers', side_effect=lambda r, **kw: r)
|
||||
#
|
||||
# # Mock the parent send method to return a 401 response first, then a 200 response
|
||||
# expired_response = mock.Mock(spec=requests.Response)
|
||||
# expired_response.status_code = 401
|
||||
#
|
||||
# success_response = mock.Mock(spec=requests.Response)
|
||||
# success_response.status_code = 200
|
||||
#
|
||||
# mocker.patch.object(
|
||||
# BaseHTTPAdapter,
|
||||
# 'send',
|
||||
# side_effect=[expired_response, success_response]
|
||||
# )
|
||||
#
|
||||
# # Mock the auth manager methods
|
||||
# auth_manager.is_token_expired_response = mock.Mock(return_value=True)
|
||||
# auth_manager.clear_token = mock.Mock()
|
||||
# auth_manager.maybe_fetch = mock.Mock(return_value={"token": "new-token", "project_id": "test-project"})
|
||||
#
|
||||
# # Create a request
|
||||
# request = requests.Request('GET', 'https://api.example.com/test').prepare()
|
||||
#
|
||||
# # Call send
|
||||
# response = adapter.send(request)
|
||||
#
|
||||
# # Verify the auth manager methods were called
|
||||
# auth_manager.is_token_expired_response.assert_called_once_with(expired_response)
|
||||
# auth_manager.clear_token.assert_called_once()
|
||||
# auth_manager.maybe_fetch.assert_called_once_with("test-api-key", token_fetcher)
|
||||
#
|
||||
# # Verify the response is the success response
|
||||
# assert response is success_response
|
||||
#
|
||||
# def test_send_with_token_refresh_failure(self, auth_manager, token_fetcher, mocker: MockerFixture):
|
||||
# """Test that send handles token refresh failures gracefully."""
|
||||
# # Setup
|
||||
# adapter = AuthenticatedHttpAdapter(
|
||||
# auth_manager=auth_manager,
|
||||
# api_key="test-api-key",
|
||||
# token_fetcher=token_fetcher
|
||||
# )
|
||||
#
|
||||
# # Mock the add_headers method
|
||||
# mocker.patch.object(adapter, 'add_headers', side_effect=lambda r, **kw: r)
|
||||
#
|
||||
# # Mock the parent send method to return a 401 response
|
||||
# expired_response = mock.Mock(spec=requests.Response)
|
||||
# expired_response.status_code = 401
|
||||
#
|
||||
# mocker.patch.object(BaseHTTPAdapter, 'send', return_value=expired_response)
|
||||
#
|
||||
# # Mock the auth manager methods
|
||||
# auth_manager.is_token_expired_response = mock.Mock(return_value=True)
|
||||
# auth_manager.clear_token = mock.Mock()
|
||||
# auth_manager.maybe_fetch = mock.Mock(side_effect=AgentOpsApiJwtExpiredException("Failed to refresh token"))
|
||||
#
|
||||
# # Create a request
|
||||
# request = requests.Request('GET', 'https://api.example.com/test').prepare()
|
||||
#
|
||||
# # Call send
|
||||
# response = adapter.send(request)
|
||||
#
|
||||
# # Verify the response is the original 401 response
|
||||
# assert response is expired_response
|
||||
# assert response.status_code == 401
|
||||
#
|
||||
# # Verify the methods were called
|
||||
# adapter.add_headers.assert_called_once() # Only called for initial request
|
||||
# BaseHTTPAdapter.send.assert_called_once() # Only called for initial request
|
||||
# auth_manager.is_token_expired_response.assert_called_once_with(expired_response)
|
||||
# auth_manager.clear_token.assert_called_once()
|
||||
# auth_manager.maybe_fetch.assert_called_once_with("test-api-key", token_fetcher)
|
||||
@@ -0,0 +1,206 @@
|
||||
# """Tests for the HttpClient class."""
|
||||
#
|
||||
# import pytest
|
||||
# import requests
|
||||
# from unittest import mock
|
||||
# from pytest_mock import MockerFixture
|
||||
#
|
||||
# from agentops.client.http.http_client import HttpClient
|
||||
# from agentops.client.http.http_adapter import AuthenticatedHttpAdapter, BaseHTTPAdapter
|
||||
# from agentops.client.auth_manager import AuthManager
|
||||
#
|
||||
#
|
||||
# class TestHttpClient:
|
||||
# """Tests for the HttpClient class."""
|
||||
#
|
||||
# def test_get_session_creates_new_session_if_none_exists(self):
|
||||
# """Test that get_session creates a new session if none exists."""
|
||||
# # Reset the session to ensure we're testing from a clean state
|
||||
# HttpClient._session = None
|
||||
#
|
||||
# # Call get_session
|
||||
# session = HttpClient.get_session()
|
||||
#
|
||||
# # Verify a session was created
|
||||
# assert session is not None
|
||||
# assert isinstance(session, requests.Session)
|
||||
#
|
||||
# # Verify the session has the expected adapters
|
||||
# assert any(isinstance(adapter, BaseHTTPAdapter) for adapter in session.adapters.values())
|
||||
#
|
||||
# # Verify the session has the expected headers
|
||||
# assert "Content-Type" in session.headers
|
||||
# assert "Connection" in session.headers
|
||||
# assert "Keep-Alive" in session.headers
|
||||
#
|
||||
# def test_get_session_returns_existing_session(self):
|
||||
# """Test that get_session returns the existing session if one exists."""
|
||||
# # Create a session
|
||||
# HttpClient._session = None
|
||||
# session1 = HttpClient.get_session()
|
||||
#
|
||||
# # Call get_session again
|
||||
# session2 = HttpClient.get_session()
|
||||
#
|
||||
# # Verify the same session was returned
|
||||
# assert session2 is session1
|
||||
#
|
||||
# def test_get_authenticated_session_creates_new_session(self):
|
||||
# """Test that get_authenticated_session creates a new authenticated session."""
|
||||
# # Call get_authenticated_session
|
||||
# session = HttpClient.get_authenticated_session(
|
||||
# endpoint="https://api.example.com",
|
||||
# api_key="test-api-key"
|
||||
# )
|
||||
#
|
||||
# # Verify a session was created
|
||||
# assert session is not None
|
||||
# assert isinstance(session, requests.Session)
|
||||
#
|
||||
# # Verify the session has the expected adapters
|
||||
# assert any(isinstance(adapter, AuthenticatedHttpAdapter) for adapter in session.adapters.values())
|
||||
#
|
||||
# # Verify the session has the expected headers
|
||||
# assert "Content-Type" in session.headers
|
||||
# assert "Connection" in session.headers
|
||||
# assert "Keep-Alive" in session.headers
|
||||
#
|
||||
# def test_get_authenticated_session_with_custom_token_fetcher(self, mocker: MockerFixture):
|
||||
# """Test that get_authenticated_session accepts a custom token fetcher."""
|
||||
# # Create a mock token fetcher
|
||||
# mock_token_fetcher = mock.Mock(return_value="test-token")
|
||||
#
|
||||
# # Call get_authenticated_session with the custom token fetcher
|
||||
# session = HttpClient.get_authenticated_session(
|
||||
# endpoint="https://api.example.com",
|
||||
# api_key="test-api-key",
|
||||
# token_fetcher=mock_token_fetcher
|
||||
# )
|
||||
#
|
||||
# # Verify a session was created
|
||||
# assert session is not None
|
||||
# assert isinstance(session, requests.Session)
|
||||
#
|
||||
# # Get the adapter
|
||||
# adapter = next(adapter for adapter in session.adapters.values()
|
||||
# if isinstance(adapter, AuthenticatedHttpAdapter))
|
||||
#
|
||||
# # Verify the adapter has the custom token fetcher
|
||||
# assert adapter.token_fetcher is mock_token_fetcher
|
||||
#
|
||||
# def test_request_get(self, mocker: MockerFixture):
|
||||
# """Test that request makes a GET request."""
|
||||
# # Mock the session
|
||||
# mock_session = mock.Mock()
|
||||
# mock_get = mock.Mock()
|
||||
# mock_session.get = mock_get
|
||||
#
|
||||
# # Mock get_session to return our mock session
|
||||
# mocker.patch.object(HttpClient, "get_session", return_value=mock_session)
|
||||
#
|
||||
# # Call request
|
||||
# HttpClient.request(
|
||||
# method="get",
|
||||
# url="https://api.example.com/test",
|
||||
# headers={"X-Test": "test"},
|
||||
# timeout=10
|
||||
# )
|
||||
#
|
||||
# # Verify the session method was called with the expected arguments
|
||||
# mock_get.assert_called_once_with(
|
||||
# "https://api.example.com/test",
|
||||
# headers={"X-Test": "test"},
|
||||
# timeout=10,
|
||||
# allow_redirects=False
|
||||
# )
|
||||
#
|
||||
# def test_request_post(self, mocker: MockerFixture):
|
||||
# """Test that request makes a POST request."""
|
||||
# # Mock the session
|
||||
# mock_session = mock.Mock()
|
||||
# mock_post = mock.Mock()
|
||||
# mock_session.post = mock_post
|
||||
#
|
||||
# # Mock get_session to return our mock session
|
||||
# mocker.patch.object(HttpClient, "get_session", return_value=mock_session)
|
||||
#
|
||||
# # Call request
|
||||
# HttpClient.request(
|
||||
# method="post",
|
||||
# url="https://api.example.com/test",
|
||||
# data={"test": "data"},
|
||||
# headers={"X-Test": "test"},
|
||||
# timeout=10
|
||||
# )
|
||||
#
|
||||
# # Verify the session method was called with the expected arguments
|
||||
# mock_post.assert_called_once_with(
|
||||
# "https://api.example.com/test",
|
||||
# json={"test": "data"},
|
||||
# headers={"X-Test": "test"},
|
||||
# timeout=10,
|
||||
# allow_redirects=False
|
||||
# )
|
||||
#
|
||||
# def test_request_put(self, mocker: MockerFixture):
|
||||
# """Test that request makes a PUT request."""
|
||||
# # Mock the session
|
||||
# mock_session = mock.Mock()
|
||||
# mock_put = mock.Mock()
|
||||
# mock_session.put = mock_put
|
||||
#
|
||||
# # Mock get_session to return our mock session
|
||||
# mocker.patch.object(HttpClient, "get_session", return_value=mock_session)
|
||||
#
|
||||
# # Call request
|
||||
# HttpClient.request(
|
||||
# method="put",
|
||||
# url="https://api.example.com/test",
|
||||
# data={"test": "data"},
|
||||
# headers={"X-Test": "test"},
|
||||
# timeout=10
|
||||
# )
|
||||
#
|
||||
# # Verify the session method was called with the expected arguments
|
||||
# mock_put.assert_called_once_with(
|
||||
# "https://api.example.com/test",
|
||||
# json={"test": "data"},
|
||||
# headers={"X-Test": "test"},
|
||||
# timeout=10,
|
||||
# allow_redirects=False
|
||||
# )
|
||||
#
|
||||
# def test_request_delete(self, mocker: MockerFixture):
|
||||
# """Test that request makes a DELETE request."""
|
||||
# # Mock the session
|
||||
# mock_session = mock.Mock()
|
||||
# mock_delete = mock.Mock()
|
||||
# mock_session.delete = mock_delete
|
||||
#
|
||||
# # Mock get_session to return our mock session
|
||||
# mocker.patch.object(HttpClient, "get_session", return_value=mock_session)
|
||||
#
|
||||
# # Call request
|
||||
# HttpClient.request(
|
||||
# method="delete",
|
||||
# url="https://api.example.com/test",
|
||||
# headers={"X-Test": "test"},
|
||||
# timeout=10
|
||||
# )
|
||||
#
|
||||
# # Verify the session method was called with the expected arguments
|
||||
# mock_delete.assert_called_once_with(
|
||||
# "https://api.example.com/test",
|
||||
# headers={"X-Test": "test"},
|
||||
# timeout=10,
|
||||
# allow_redirects=False
|
||||
# )
|
||||
#
|
||||
# def test_request_unsupported_method(self):
|
||||
# """Test that request raises an error for unsupported methods."""
|
||||
# # Call request with an unsupported method
|
||||
# with pytest.raises(ValueError, match="Unsupported HTTP method: patch"):
|
||||
# HttpClient.request(
|
||||
# method="patch",
|
||||
# url="https://api.example.com/test"
|
||||
# )
|
||||
@@ -0,0 +1,54 @@
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
import requests_mock
|
||||
|
||||
from agentops.config import Config
|
||||
from tests.fixtures.client import * # noqa
|
||||
from tests.unit.sdk.instrumentation_tester import InstrumentationTester
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api_key() -> str:
|
||||
"""Standard API key for testing"""
|
||||
return "test-api-key"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def endpoint() -> str:
|
||||
"""Base API URL"""
|
||||
return Config().endpoint
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_req(endpoint, api_key):
|
||||
"""
|
||||
Mocks AgentOps backend API requests.
|
||||
"""
|
||||
with requests_mock.Mocker(real_http=False) as m:
|
||||
# Map session IDs to their JWTs
|
||||
m.post(
|
||||
endpoint + "/v3/auth/token",
|
||||
json={"token": str(uuid.uuid4()), "project_id": "test-project-id", "api_key": api_key},
|
||||
)
|
||||
yield m
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def noinstrument():
|
||||
# Tells the client to not instrument LLM calls
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config(mocker):
|
||||
"""Mock the Client.configure method"""
|
||||
return mocker.patch("agentops.client.Client.configure")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def instrumentation():
|
||||
"""Fixture for the instrumentation tester."""
|
||||
tester = InstrumentationTester()
|
||||
yield tester
|
||||
tester.reset()
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
Unit tests for dashboard URL generation and logging.
|
||||
"""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from agentops.helpers.dashboard import get_trace_url, log_trace_url
|
||||
|
||||
|
||||
class TestDashboardHelpers(unittest.TestCase):
|
||||
"""Tests for dashboard URL generation and logging functions."""
|
||||
|
||||
@patch("agentops.get_client")
|
||||
def test_get_trace_url_with_hex_trace_id(self, mock_get_client):
|
||||
"""Test get_trace_url with a hexadecimal trace ID."""
|
||||
# Mock the config's app_url
|
||||
mock_client = MagicMock()
|
||||
mock_client.config.app_url = "https://test-app.agentops.ai"
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
# Create a mock span with a hex string trace ID (using a full 32-character trace ID)
|
||||
mock_span = MagicMock()
|
||||
mock_span.context.trace_id = "1234567890abcdef1234567890abcdef"
|
||||
|
||||
# Call get_trace_url
|
||||
url = get_trace_url(mock_span)
|
||||
|
||||
# Assert that the URL is correctly formed with the config's app_url
|
||||
self.assertEqual(url, "https://test-app.agentops.ai/sessions?trace_id=1234567890abcdef1234567890abcdef")
|
||||
|
||||
@patch("agentops.get_client")
|
||||
def test_get_trace_url_with_int_trace_id(self, mock_get_client):
|
||||
"""Test get_trace_url with an integer trace ID."""
|
||||
# Mock the config's app_url
|
||||
mock_client = MagicMock()
|
||||
mock_client.config.app_url = "https://test-app.agentops.ai"
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
# Create a mock span with an int trace ID
|
||||
mock_span = MagicMock()
|
||||
mock_span.context.trace_id = 12345
|
||||
|
||||
# Call get_trace_url
|
||||
url = get_trace_url(mock_span)
|
||||
|
||||
# Assert that the URL follows the expected format with a 32-character hex string
|
||||
self.assertTrue(url.startswith("https://test-app.agentops.ai/sessions?trace_id="))
|
||||
|
||||
# Verify the format is a 32-character hex string (no dashes)
|
||||
hex_part = url.split("trace_id=")[1]
|
||||
self.assertRegex(hex_part, r"^[0-9a-f]{32}$")
|
||||
|
||||
# Verify the value is correctly formatted from the integer 12345
|
||||
expected_hex = format(12345, "032x")
|
||||
self.assertEqual(hex_part, expected_hex)
|
||||
|
||||
@patch("agentops.helpers.dashboard.logger")
|
||||
@patch("agentops.get_client")
|
||||
def test_log_trace_url(self, mock_get_client, mock_logger):
|
||||
"""Test log_trace_url includes the session URL in the log message."""
|
||||
# Mock the config's app_url
|
||||
mock_client = MagicMock()
|
||||
mock_client.config.app_url = "https://test-app.agentops.ai"
|
||||
mock_get_client.return_value = mock_client
|
||||
|
||||
# Create a mock span
|
||||
mock_span = MagicMock()
|
||||
mock_span.context.trace_id = "test-trace-id"
|
||||
|
||||
# Mock get_trace_url to return a known value that uses the app_url
|
||||
expected_url = "https://test-app.agentops.ai/sessions?trace_id=test-trace-id"
|
||||
with patch("agentops.helpers.dashboard.get_trace_url", return_value=expected_url):
|
||||
# Call log_trace_url
|
||||
log_trace_url(mock_span)
|
||||
|
||||
# Assert that logger.info was called with a message containing the URL
|
||||
mock_logger.info.assert_called_once()
|
||||
log_message = mock_logger.info.call_args[0][0]
|
||||
self.assertIn(expected_url, log_message)
|
||||
@@ -0,0 +1,108 @@
|
||||
from unittest.mock import Mock, patch
|
||||
from importlib.metadata import PackageNotFoundError
|
||||
|
||||
from agentops.helpers.version import get_agentops_version, check_agentops_update
|
||||
|
||||
|
||||
class TestGetAgentopsVersion:
|
||||
def test_get_agentops_version_success(self):
|
||||
"""Test successful version retrieval."""
|
||||
with patch("agentops.helpers.version.version") as mock_version:
|
||||
mock_version.return_value = "1.2.3"
|
||||
|
||||
result = get_agentops_version()
|
||||
|
||||
assert result == "1.2.3"
|
||||
mock_version.assert_called_once_with("agentops")
|
||||
|
||||
def test_get_agentops_version_exception(self):
|
||||
"""Test version retrieval when an exception occurs."""
|
||||
test_exception = Exception("Test error")
|
||||
|
||||
with patch("agentops.helpers.version.version") as mock_version:
|
||||
mock_version.side_effect = test_exception
|
||||
|
||||
with patch("agentops.helpers.version.logger") as mock_logger:
|
||||
result = get_agentops_version()
|
||||
|
||||
assert result is None
|
||||
mock_logger.warning.assert_called_once_with("Error reading package version: %s", test_exception)
|
||||
|
||||
|
||||
class TestCheckAgentopsUpdate:
|
||||
def test_check_agentops_update_outdated(self):
|
||||
"""Test update check when a newer version is available."""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"info": {"version": "2.0.0"}}
|
||||
|
||||
with patch("agentops.helpers.version.requests.get", return_value=mock_response):
|
||||
with patch("agentops.helpers.version.version", return_value="1.0.0"):
|
||||
with patch("agentops.helpers.version.logger") as mock_logger:
|
||||
check_agentops_update()
|
||||
|
||||
mock_logger.warning.assert_called_once_with(
|
||||
" WARNING: agentops is out of date. Please update with the command: 'pip install --upgrade agentops'"
|
||||
)
|
||||
|
||||
def test_check_agentops_update_current(self):
|
||||
"""Test update check when current version is up to date."""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"info": {"version": "1.0.0"}}
|
||||
|
||||
with patch("agentops.helpers.version.requests.get", return_value=mock_response):
|
||||
with patch("agentops.helpers.version.version", return_value="1.0.0"):
|
||||
with patch("agentops.helpers.version.logger") as mock_logger:
|
||||
check_agentops_update()
|
||||
|
||||
# Should not log any warning when versions match
|
||||
mock_logger.warning.assert_not_called()
|
||||
|
||||
def test_check_agentops_update_package_not_found(self):
|
||||
"""Test update check when package is not found."""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"info": {"version": "2.0.0"}}
|
||||
|
||||
with patch("agentops.helpers.version.requests.get", return_value=mock_response):
|
||||
with patch("agentops.helpers.version.version", side_effect=PackageNotFoundError("agentops")):
|
||||
with patch("agentops.helpers.version.logger") as mock_logger:
|
||||
result = check_agentops_update()
|
||||
|
||||
assert result is None
|
||||
mock_logger.warning.assert_not_called()
|
||||
|
||||
def test_check_agentops_update_request_failure(self):
|
||||
"""Test update check when the HTTP request fails."""
|
||||
with patch("agentops.helpers.version.requests.get", side_effect=Exception("Network error")):
|
||||
with patch("agentops.helpers.version.logger") as mock_logger:
|
||||
result = check_agentops_update()
|
||||
|
||||
assert result is None
|
||||
mock_logger.debug.assert_called_once_with("Failed to check for updates: Network error")
|
||||
|
||||
def test_check_agentops_update_non_200_status(self):
|
||||
"""Test update check when the HTTP response is not 200."""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 404
|
||||
|
||||
with patch("agentops.helpers.version.requests.get", return_value=mock_response):
|
||||
with patch("agentops.helpers.version.logger") as mock_logger:
|
||||
check_agentops_update()
|
||||
|
||||
# Should not log any warning when status is not 200
|
||||
mock_logger.warning.assert_not_called()
|
||||
|
||||
def test_check_agentops_update_json_error(self):
|
||||
"""Test update check when JSON parsing fails."""
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.side_effect = Exception("JSON error")
|
||||
|
||||
with patch("agentops.helpers.version.requests.get", return_value=mock_response):
|
||||
with patch("agentops.helpers.version.logger") as mock_logger:
|
||||
result = check_agentops_update()
|
||||
|
||||
assert result is None
|
||||
mock_logger.debug.assert_called_once_with("Failed to check for updates: JSON error")
|
||||
@@ -0,0 +1,154 @@
|
||||
import json
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
from opentelemetry.trace import Span, SpanContext
|
||||
from opentelemetry.metrics import Meter
|
||||
|
||||
# Load fixture data
|
||||
FIXTURES_DIR = Path(__file__).parent.parent / "fixtures"
|
||||
|
||||
|
||||
def load_fixture(filename):
|
||||
"""Load a JSON fixture file"""
|
||||
with open(FIXTURES_DIR / filename) as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_tracer():
|
||||
"""Create a mock OpenTelemetry tracer with configured span and context"""
|
||||
tracer = MagicMock()
|
||||
span = MagicMock(spec=Span)
|
||||
span_context = MagicMock(spec=SpanContext)
|
||||
span.get_span_context.return_value = span_context
|
||||
tracer.start_span.return_value = span
|
||||
return tracer
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_meter():
|
||||
"""Create a mock OpenTelemetry meter with histogram and counter"""
|
||||
meter = MagicMock(spec=Meter)
|
||||
histogram = MagicMock()
|
||||
counter = MagicMock()
|
||||
meter.create_histogram.return_value = histogram
|
||||
meter.create_counter.return_value = counter
|
||||
return meter
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_anthropic_client():
|
||||
"""Create a mock Anthropic client with configured message and stream responses"""
|
||||
client = MagicMock()
|
||||
message_response = load_fixture("anthropic_message.json")
|
||||
client.messages.create.return_value = MagicMock(**message_response)
|
||||
|
||||
stream_response = load_fixture("anthropic_stream.json")
|
||||
stream_manager = MagicMock()
|
||||
stream_manager.__enter__.return_value = MagicMock(
|
||||
text_stream=iter(stream_response["messages"]),
|
||||
_MessageStreamManager__stream=MagicMock(
|
||||
_MessageStream__final_message_snapshot=MagicMock(**stream_response["final_message"])
|
||||
),
|
||||
)
|
||||
client.messages.stream.return_value = stream_manager
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_event_handler():
|
||||
"""Create a mock event handler with all required event handling methods"""
|
||||
handler = MagicMock()
|
||||
handler.on_event = MagicMock()
|
||||
handler.on_text_delta = MagicMock()
|
||||
handler.on_content_block_start = MagicMock()
|
||||
handler.on_content_block_delta = MagicMock()
|
||||
handler.on_content_block_stop = MagicMock()
|
||||
handler.on_message_start = MagicMock()
|
||||
handler.on_message_delta = MagicMock()
|
||||
handler.on_message_stop = MagicMock()
|
||||
handler.on_error = MagicMock()
|
||||
return handler
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_stream_manager():
|
||||
"""Create a mock stream manager that emits events during text streaming"""
|
||||
manager = MagicMock()
|
||||
stream = MagicMock()
|
||||
|
||||
def text_stream_iter():
|
||||
chunks = ["1", "2", "3", "4", "5"]
|
||||
for chunk in chunks:
|
||||
if hasattr(stream, "event_handler") and stream.event_handler is not None:
|
||||
stream.event_handler.on_text_delta({"text": chunk}, {"text": chunk})
|
||||
yield chunk
|
||||
|
||||
stream.text_stream = text_stream_iter()
|
||||
manager.__enter__.return_value = stream
|
||||
return manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_async_stream_manager():
|
||||
"""Create a mock async stream manager with async iteration support"""
|
||||
manager = MagicMock()
|
||||
stream = MagicMock()
|
||||
stream.text_stream = MagicMock()
|
||||
stream.text_stream.__aiter__.return_value = iter(["1", "2", "3", "4", "5"])
|
||||
manager.__aenter__.return_value = stream
|
||||
return manager
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_stream_event():
|
||||
"""Fixture for a mock streaming event."""
|
||||
|
||||
class MockMessageStartEvent:
|
||||
def __init__(self):
|
||||
self.message = type("obj", (object,), {"id": "msg_123", "model": "claude-3-opus-20240229"})
|
||||
self.__class__.__name__ = "MessageStartEvent"
|
||||
|
||||
return MockMessageStartEvent()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_message_stop_event():
|
||||
"""Fixture for a mock message stop event."""
|
||||
|
||||
class MockMessageStopEvent:
|
||||
def __init__(self):
|
||||
self.message = type("obj", (object,), {"stop_reason": "stop_sequence"})
|
||||
self.__class__.__name__ = "MessageStopEvent"
|
||||
|
||||
return MockMessageStopEvent()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_tool_definition():
|
||||
"""Fixture for a mock tool definition."""
|
||||
return [
|
||||
{
|
||||
"name": "calculator",
|
||||
"description": "A simple calculator",
|
||||
"input_schema": {
|
||||
"type": "object",
|
||||
"properties": {"operation": {"type": "string"}, "numbers": {"type": "array"}},
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_tool_use_content():
|
||||
"""Fixture for mock tool use content."""
|
||||
|
||||
class MockToolUseBlock:
|
||||
def __init__(self):
|
||||
self.type = "tool_use"
|
||||
self.name = "calculator"
|
||||
self.id = "tool_123"
|
||||
self.input = {"operation": "add", "numbers": [1, 2]}
|
||||
|
||||
return [MockToolUseBlock()]
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Tests for Anthropic attribute extraction functionality."""
|
||||
|
||||
from agentops.semconv import (
|
||||
InstrumentationAttributes,
|
||||
SpanAttributes,
|
||||
MessageAttributes,
|
||||
ToolAttributes,
|
||||
ToolStatus,
|
||||
)
|
||||
from agentops.instrumentation.providers.anthropic.attributes.common import (
|
||||
get_common_instrumentation_attributes,
|
||||
extract_request_attributes,
|
||||
)
|
||||
from agentops.instrumentation.providers.anthropic.attributes.message import (
|
||||
get_message_request_attributes,
|
||||
get_stream_attributes,
|
||||
get_stream_event_attributes,
|
||||
)
|
||||
from agentops.instrumentation.providers.anthropic.attributes.tools import (
|
||||
extract_tool_definitions,
|
||||
extract_tool_use_blocks,
|
||||
get_tool_attributes,
|
||||
)
|
||||
|
||||
|
||||
# Common Attributes Tests
|
||||
def test_get_common_instrumentation_attributes():
|
||||
"""Test extraction of common instrumentation attributes."""
|
||||
attributes = get_common_instrumentation_attributes()
|
||||
assert attributes[InstrumentationAttributes.LIBRARY_NAME] == "anthropic"
|
||||
assert attributes[InstrumentationAttributes.LIBRARY_VERSION] >= "0.49.0"
|
||||
|
||||
|
||||
def test_extract_request_attributes():
|
||||
"""Test extraction of request attributes from kwargs."""
|
||||
kwargs = {"model": "claude-3-opus-20240229", "max_tokens": 100, "temperature": 0.7, "top_p": 0.9, "stream": True}
|
||||
attributes = extract_request_attributes(kwargs)
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MODEL] == "claude-3-opus-20240229"
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MAX_TOKENS] == 100
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_TEMPERATURE] == 0.7
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_TOP_P] == 0.9
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_STREAMING] is True
|
||||
|
||||
|
||||
def test_extract_request_attributes_partial():
|
||||
"""Test extraction of request attributes with partial kwargs."""
|
||||
kwargs = {"model": "claude-3-opus-20240229", "temperature": 0.7}
|
||||
attributes = extract_request_attributes(kwargs)
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MODEL] == "claude-3-opus-20240229"
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_TEMPERATURE] == 0.7
|
||||
assert SpanAttributes.LLM_REQUEST_MAX_TOKENS not in attributes
|
||||
assert SpanAttributes.LLM_REQUEST_TOP_P not in attributes
|
||||
assert SpanAttributes.LLM_REQUEST_STREAMING not in attributes
|
||||
|
||||
|
||||
def test_get_message_request_attributes():
|
||||
"""Test extraction of message request attributes."""
|
||||
kwargs = {
|
||||
"model": "claude-3-opus-20240229",
|
||||
"messages": [
|
||||
{"role": "system", "content": "You are a helpful assistant"},
|
||||
{"role": "user", "content": "Hello"},
|
||||
],
|
||||
"max_tokens": 100,
|
||||
}
|
||||
attributes = get_message_request_attributes(kwargs)
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MODEL] == "claude-3-opus-20240229"
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MAX_TOKENS] == 100
|
||||
assert MessageAttributes.PROMPT_ROLE.format(i=0) in attributes
|
||||
assert MessageAttributes.PROMPT_CONTENT.format(i=0) in attributes
|
||||
assert MessageAttributes.PROMPT_ROLE.format(i=1) in attributes
|
||||
assert MessageAttributes.PROMPT_CONTENT.format(i=1) in attributes
|
||||
|
||||
|
||||
# Stream Attributes Tests
|
||||
def test_get_stream_attributes():
|
||||
"""Test extraction of stream attributes."""
|
||||
|
||||
class MockStream:
|
||||
def __init__(self):
|
||||
self.model = "claude-3-opus-20240229"
|
||||
|
||||
stream = MockStream()
|
||||
attributes = get_stream_attributes(stream)
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_STREAMING] is True
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MODEL] == "claude-3-opus-20240229"
|
||||
|
||||
|
||||
def test_get_stream_event_attributes_sequence(mock_stream_event, mock_message_stop_event):
|
||||
"""Test extraction of attributes from a sequence of stream events."""
|
||||
# Test MessageStartEvent
|
||||
start_attributes = get_stream_event_attributes(mock_stream_event)
|
||||
assert start_attributes[SpanAttributes.LLM_RESPONSE_ID] == "msg_123"
|
||||
assert start_attributes[SpanAttributes.LLM_RESPONSE_MODEL] == "claude-3-opus-20240229"
|
||||
assert start_attributes[MessageAttributes.COMPLETION_ID.format(i=0)] == "msg_123"
|
||||
|
||||
# Test MessageStopEvent
|
||||
stop_attributes = get_stream_event_attributes(mock_message_stop_event)
|
||||
assert stop_attributes[SpanAttributes.LLM_RESPONSE_STOP_REASON] == "stop_sequence"
|
||||
assert stop_attributes[SpanAttributes.LLM_RESPONSE_FINISH_REASON] == "stop_sequence"
|
||||
assert stop_attributes[MessageAttributes.COMPLETION_FINISH_REASON.format(i=0)] == "stop_sequence"
|
||||
|
||||
|
||||
def test_get_stream_event_attributes_raw_message_start():
|
||||
"""Test extraction of raw message start event attributes."""
|
||||
|
||||
class MockUsage:
|
||||
def __init__(self):
|
||||
self.input_tokens = 10
|
||||
self.output_tokens = 5
|
||||
|
||||
class MockMessage:
|
||||
def __init__(self):
|
||||
self.usage = MockUsage()
|
||||
|
||||
class MockRawMessageStartEvent:
|
||||
def __init__(self):
|
||||
self.message = MockMessage()
|
||||
self.__class__.__name__ = "RawMessageStartEvent"
|
||||
|
||||
event = MockRawMessageStartEvent()
|
||||
attributes = get_stream_event_attributes(event)
|
||||
|
||||
assert attributes[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 10
|
||||
assert attributes[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 5
|
||||
assert attributes[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 15
|
||||
|
||||
|
||||
def test_get_stream_event_attributes_raw_message_delta():
|
||||
"""Test extraction of raw message delta event attributes."""
|
||||
|
||||
class MockDelta:
|
||||
def __init__(self):
|
||||
self.stop_reason = "end_turn"
|
||||
|
||||
class MockRawMessageDeltaEvent:
|
||||
def __init__(self):
|
||||
self.delta = MockDelta()
|
||||
self.__class__.__name__ = "RawMessageDeltaEvent"
|
||||
|
||||
event = MockRawMessageDeltaEvent()
|
||||
attributes = get_stream_event_attributes(event)
|
||||
|
||||
assert attributes[SpanAttributes.LLM_RESPONSE_STOP_REASON] == "end_turn"
|
||||
assert attributes[SpanAttributes.LLM_RESPONSE_FINISH_REASON] == "end_turn"
|
||||
assert attributes[MessageAttributes.COMPLETION_FINISH_REASON.format(i=0)] == "end_turn"
|
||||
|
||||
|
||||
# Tool Attributes Tests
|
||||
def test_extract_tool_definitions(mock_tool_definition):
|
||||
"""Test extraction of tool definitions."""
|
||||
attributes = extract_tool_definitions(mock_tool_definition)
|
||||
assert attributes[MessageAttributes.TOOL_CALL_NAME.format(i=0)] == "calculator"
|
||||
assert attributes[MessageAttributes.TOOL_CALL_TYPE.format(i=0)] == "function"
|
||||
assert attributes[MessageAttributes.TOOL_CALL_DESCRIPTION.format(i=0)] == "A simple calculator"
|
||||
tool_args = attributes[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
assert isinstance(tool_args, str)
|
||||
assert "type" in tool_args
|
||||
assert "properties" in tool_args
|
||||
assert SpanAttributes.LLM_REQUEST_FUNCTIONS in attributes
|
||||
|
||||
|
||||
def test_extract_tool_use_blocks(mock_tool_use_content):
|
||||
"""Test extraction of tool use blocks."""
|
||||
tool_uses = extract_tool_use_blocks(mock_tool_use_content)
|
||||
assert tool_uses is not None
|
||||
assert len(tool_uses) == 1
|
||||
assert tool_uses[0]["name"] == "calculator"
|
||||
assert tool_uses[0]["id"] == "tool_123"
|
||||
assert tool_uses[0]["input"] == {"operation": "add", "numbers": [1, 2]}
|
||||
|
||||
|
||||
def test_get_tool_attributes(mock_tool_use_content):
|
||||
"""Test extraction of tool attributes from content."""
|
||||
attributes = get_tool_attributes(mock_tool_use_content)
|
||||
assert attributes[MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0)] == "calculator"
|
||||
assert attributes[MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=0, j=0)] == "tool_123"
|
||||
assert attributes[MessageAttributes.COMPLETION_TOOL_CALL_TYPE.format(i=0, j=0)] == "function"
|
||||
tool_args = attributes[MessageAttributes.COMPLETION_TOOL_CALL_ARGUMENTS.format(i=0, j=0)]
|
||||
assert isinstance(tool_args, str)
|
||||
assert "operation" in tool_args
|
||||
assert attributes[MessageAttributes.TOOL_CALL_ID.format(i=0)] == "tool_123"
|
||||
assert attributes[MessageAttributes.TOOL_CALL_NAME.format(i=0)] == "calculator"
|
||||
assert attributes[f"{ToolAttributes.TOOL_STATUS}.0"] == ToolStatus.EXECUTING.value
|
||||
assert attributes["anthropic.tool_calls.count"] == 1
|
||||
|
||||
|
||||
def test_get_tool_attributes_empty():
|
||||
"""Test extraction of tool attributes with empty content."""
|
||||
attributes = get_tool_attributes([])
|
||||
assert not attributes
|
||||
|
||||
|
||||
def test_get_tool_attributes_mixed_content():
|
||||
"""Test extraction of tool attributes with mixed content types."""
|
||||
|
||||
class MockTextBlock:
|
||||
def __init__(self):
|
||||
self.type = "text"
|
||||
self.text = "Hello world"
|
||||
|
||||
class MockToolUseBlock:
|
||||
def __init__(self):
|
||||
self.type = "tool_use"
|
||||
self.name = "calculator"
|
||||
self.id = "tool_123"
|
||||
self.input = {"operation": "add", "numbers": [1, 2]}
|
||||
|
||||
content = [MockTextBlock(), MockToolUseBlock()]
|
||||
attributes = get_tool_attributes(content)
|
||||
assert MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0) in attributes
|
||||
assert attributes[MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0)] == "calculator"
|
||||
|
||||
|
||||
def test_get_message_attributes_with_stream(mock_stream_event, mock_message_stop_event):
|
||||
"""Test extraction of attributes from a Stream object."""
|
||||
|
||||
# Test MessageStartEvent attributes
|
||||
start_attributes = get_stream_event_attributes(mock_stream_event)
|
||||
assert start_attributes[SpanAttributes.LLM_RESPONSE_ID] == "msg_123"
|
||||
assert start_attributes[SpanAttributes.LLM_RESPONSE_MODEL] == "claude-3-opus-20240229"
|
||||
assert start_attributes[MessageAttributes.COMPLETION_ID.format(i=0)] == "msg_123"
|
||||
|
||||
# Test MessageStopEvent attributes
|
||||
stop_attributes = get_stream_event_attributes(mock_message_stop_event)
|
||||
assert stop_attributes[SpanAttributes.LLM_RESPONSE_STOP_REASON] == "stop_sequence"
|
||||
assert stop_attributes[SpanAttributes.LLM_RESPONSE_FINISH_REASON] == "stop_sequence"
|
||||
assert stop_attributes[MessageAttributes.COMPLETION_FINISH_REASON.format(i=0)] == "stop_sequence"
|
||||
@@ -0,0 +1,95 @@
|
||||
from unittest.mock import MagicMock
|
||||
from opentelemetry.trace import Span
|
||||
|
||||
from agentops.instrumentation.providers.anthropic.event_handler_wrapper import EventHandleWrapper
|
||||
from agentops.semconv import CoreAttributes
|
||||
|
||||
|
||||
def test_event_handler_initialization():
|
||||
"""Test that event handler initializes correctly with a span and no original handler."""
|
||||
span = MagicMock(spec=Span)
|
||||
handler = EventHandleWrapper(None, span)
|
||||
assert handler._span == span
|
||||
assert handler._original_handler is None
|
||||
|
||||
|
||||
def test_event_handler_with_original_handler():
|
||||
"""Test that event handler properly stores the original handler reference."""
|
||||
original_handler = MagicMock()
|
||||
span = MagicMock(spec=Span)
|
||||
handler = EventHandleWrapper(original_handler, span)
|
||||
assert handler._original_handler == original_handler
|
||||
|
||||
|
||||
def test_event_forwarding():
|
||||
"""Test that all event types are correctly forwarded to the original handler
|
||||
while maintaining the original event data."""
|
||||
original_handler = MagicMock()
|
||||
span = MagicMock(spec=Span)
|
||||
handler = EventHandleWrapper(original_handler, span)
|
||||
|
||||
event = {"type": "test"}
|
||||
handler.on_event(event)
|
||||
original_handler.on_event.assert_called_with(event)
|
||||
|
||||
delta = {"text": "test"}
|
||||
snapshot = {"content": "test"}
|
||||
handler.on_text_delta(delta, snapshot)
|
||||
original_handler.on_text_delta.assert_called_with(delta, snapshot)
|
||||
|
||||
content_block = {"type": "text"}
|
||||
handler.on_content_block_start(content_block)
|
||||
original_handler.on_content_block_start.assert_called_with(content_block)
|
||||
|
||||
|
||||
def test_event_handler_without_original_handler():
|
||||
"""Test that event handler gracefully handles events when no original handler
|
||||
is provided, ensuring no exceptions are raised."""
|
||||
span = MagicMock(spec=Span)
|
||||
handler = EventHandleWrapper(None, span)
|
||||
|
||||
handler.on_event({})
|
||||
handler.on_text_delta({}, {})
|
||||
handler.on_content_block_start({})
|
||||
|
||||
|
||||
def test_error_handling():
|
||||
"""Test that errors are properly recorded in the span and forwarded to the
|
||||
original handler with correct error attributes."""
|
||||
original_handler = MagicMock()
|
||||
span = MagicMock(spec=Span)
|
||||
handler = EventHandleWrapper(original_handler, span)
|
||||
|
||||
error = Exception("Test error")
|
||||
handler.on_error(error)
|
||||
|
||||
span.record_exception.assert_called_with(error)
|
||||
span.set_attribute.assert_any_call(CoreAttributes.ERROR_MESSAGE, "Test error")
|
||||
span.set_attribute.assert_any_call(CoreAttributes.ERROR_TYPE, "Exception")
|
||||
original_handler.on_error.assert_called_with(error)
|
||||
|
||||
|
||||
def test_error_handling_without_original_handler():
|
||||
"""Test that errors are properly recorded in the span even when no original
|
||||
handler is present."""
|
||||
span = MagicMock(spec=Span)
|
||||
handler = EventHandleWrapper(None, span)
|
||||
|
||||
error = Exception("Test error")
|
||||
handler.on_error(error)
|
||||
|
||||
span.record_exception.assert_called_with(error)
|
||||
span.set_attribute.assert_any_call(CoreAttributes.ERROR_MESSAGE, "Test error")
|
||||
span.set_attribute.assert_any_call(CoreAttributes.ERROR_TYPE, "Exception")
|
||||
|
||||
|
||||
def test_error_in_original_handler():
|
||||
"""Test that errors from the original handler are caught and logged without
|
||||
disrupting the event handling flow."""
|
||||
original_handler = MagicMock()
|
||||
original_handler.on_event.side_effect = Exception("Handler error")
|
||||
span = MagicMock(spec=Span)
|
||||
handler = EventHandleWrapper(original_handler, span)
|
||||
|
||||
handler.on_event({})
|
||||
assert original_handler.on_event.called
|
||||
@@ -0,0 +1,143 @@
|
||||
from unittest.mock import patch, MagicMock, ANY
|
||||
|
||||
from agentops.instrumentation.providers.anthropic.instrumentor import AnthropicInstrumentor
|
||||
from agentops.instrumentation.providers.anthropic import LIBRARY_NAME, LIBRARY_VERSION
|
||||
|
||||
|
||||
def test_instrumentor_initialization():
|
||||
"""Test that the instrumentor initializes with correct dependencies."""
|
||||
instrumentor = AnthropicInstrumentor()
|
||||
assert isinstance(instrumentor, AnthropicInstrumentor)
|
||||
assert instrumentor.instrumentation_dependencies() == ["anthropic >= 0.7.0"]
|
||||
|
||||
|
||||
def test_instrumentor_setup(mock_tracer, mock_meter):
|
||||
"""Test that the instrumentor properly sets up tracers and meters with correct
|
||||
configuration and attributes."""
|
||||
instrumentor = AnthropicInstrumentor()
|
||||
|
||||
with (
|
||||
patch("agentops.instrumentation.common.instrumentor.get_tracer", return_value=mock_tracer) as mock_get_tracer,
|
||||
patch("agentops.instrumentation.common.instrumentor.get_meter", return_value=mock_meter) as mock_get_meter,
|
||||
):
|
||||
# Call _instrument - this is when get_tracer and get_meter are called
|
||||
instrumentor._instrument()
|
||||
|
||||
# Verify tracer and meter were requested with correct params
|
||||
mock_get_tracer.assert_called_with(LIBRARY_NAME, LIBRARY_VERSION, None)
|
||||
mock_get_meter.assert_called_with(LIBRARY_NAME, LIBRARY_VERSION, None)
|
||||
|
||||
# Verify they were stored correctly
|
||||
assert instrumentor._tracer == mock_tracer
|
||||
assert instrumentor._meter == mock_meter
|
||||
|
||||
|
||||
def test_instrumentor_wraps_methods(mock_tracer, mock_meter):
|
||||
"""Test that the instrumentor correctly wraps both standard and streaming methods
|
||||
with proper instrumentation."""
|
||||
instrumentor = AnthropicInstrumentor()
|
||||
|
||||
# Mock the anthropic module structure to prevent import errors
|
||||
mock_anthropic = MagicMock()
|
||||
mock_messages_module = MagicMock()
|
||||
mock_completions_module = MagicMock()
|
||||
|
||||
# Set up the class structure
|
||||
mock_messages_module.Messages = MagicMock()
|
||||
mock_messages_module.AsyncMessages = MagicMock()
|
||||
mock_completions_module.Completions = MagicMock()
|
||||
mock_completions_module.AsyncCompletions = MagicMock()
|
||||
|
||||
with (
|
||||
patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"anthropic": mock_anthropic,
|
||||
"anthropic.resources": mock_anthropic.resources,
|
||||
"anthropic.resources.messages": mock_messages_module,
|
||||
"anthropic.resources.completions": mock_completions_module,
|
||||
"anthropic.resources.messages.messages": mock_messages_module,
|
||||
},
|
||||
),
|
||||
patch("agentops.instrumentation.common.instrumentor.get_tracer", return_value=mock_tracer),
|
||||
patch("agentops.instrumentation.common.instrumentor.get_meter", return_value=mock_meter),
|
||||
patch("agentops.instrumentation.common.wrappers.wrap_function_wrapper") as mock_wrap_function,
|
||||
patch("agentops.instrumentation.providers.anthropic.instrumentor.wrap_function_wrapper") as mock_stream_wrap,
|
||||
):
|
||||
instrumentor._instrument()
|
||||
|
||||
# The base instrumentor will call wrap_function_wrapper for each wrapped method
|
||||
assert mock_wrap_function.call_count == 4
|
||||
|
||||
# Check that streaming methods were wrapped with custom wrappers
|
||||
mock_stream_wrap.assert_any_call("anthropic.resources.messages.messages", "Messages.stream", ANY)
|
||||
mock_stream_wrap.assert_any_call("anthropic.resources.messages.messages", "AsyncMessages.stream", ANY)
|
||||
|
||||
|
||||
def test_instrumentor_uninstrument(mock_tracer, mock_meter):
|
||||
"""Test that the instrumentor properly unwraps all instrumented methods and
|
||||
cleans up resources."""
|
||||
instrumentor = AnthropicInstrumentor()
|
||||
mock_unwrap = MagicMock()
|
||||
|
||||
# Mock the anthropic module structure
|
||||
mock_anthropic = MagicMock()
|
||||
mock_messages_module = MagicMock()
|
||||
mock_completions_module = MagicMock()
|
||||
|
||||
# Set up the class structure
|
||||
mock_messages_module.Messages = MagicMock()
|
||||
mock_messages_module.AsyncMessages = MagicMock()
|
||||
mock_completions_module.Completions = MagicMock()
|
||||
mock_completions_module.AsyncCompletions = MagicMock()
|
||||
|
||||
with (
|
||||
patch.dict(
|
||||
"sys.modules",
|
||||
{
|
||||
"anthropic": mock_anthropic,
|
||||
"anthropic.resources": mock_anthropic.resources,
|
||||
"anthropic.resources.messages": mock_messages_module,
|
||||
"anthropic.resources.completions": mock_completions_module,
|
||||
"anthropic.resources.messages.messages": mock_messages_module,
|
||||
},
|
||||
),
|
||||
patch("agentops.instrumentation.common.instrumentor.get_tracer", return_value=mock_tracer),
|
||||
patch("agentops.instrumentation.common.instrumentor.get_meter", return_value=mock_meter),
|
||||
patch("agentops.instrumentation.common.instrumentor.unwrap", mock_unwrap), # Patch where it's imported
|
||||
patch(
|
||||
"agentops.instrumentation.providers.anthropic.instrumentor.otel_unwrap"
|
||||
) as mock_otel_unwrap, # Patch in anthropic module
|
||||
patch("agentops.instrumentation.common.wrappers.wrap_function_wrapper"),
|
||||
patch("agentops.instrumentation.providers.anthropic.instrumentor.wrap_function_wrapper"),
|
||||
):
|
||||
# Instrument first
|
||||
instrumentor._instrument()
|
||||
|
||||
# Now uninstrument
|
||||
instrumentor._uninstrument()
|
||||
|
||||
# Should unwrap all 4 configured methods
|
||||
assert mock_unwrap.call_count == 4
|
||||
|
||||
# Should also unwrap the custom stream methods
|
||||
mock_otel_unwrap.assert_any_call("anthropic.resources.messages.messages", "Messages.stream")
|
||||
mock_otel_unwrap.assert_any_call("anthropic.resources.messages.messages", "AsyncMessages.stream")
|
||||
|
||||
|
||||
def test_instrumentor_handles_missing_methods(mock_tracer, mock_meter):
|
||||
"""Test that the instrumentor gracefully handles missing or inaccessible methods
|
||||
without raising exceptions."""
|
||||
instrumentor = AnthropicInstrumentor()
|
||||
mock_wrap = MagicMock(side_effect=AttributeError)
|
||||
mock_wrap_function = MagicMock(side_effect=AttributeError)
|
||||
|
||||
with (
|
||||
patch("agentops.instrumentation.common.instrumentor.get_tracer", return_value=mock_tracer),
|
||||
patch("agentops.instrumentation.common.instrumentor.get_meter", return_value=mock_meter),
|
||||
patch("agentops.instrumentation.common.wrappers.wrap", mock_wrap),
|
||||
patch("agentops.instrumentation.providers.anthropic.instrumentor.wrap_function_wrapper", mock_wrap_function),
|
||||
):
|
||||
# Should not raise exceptions even when wrapping fails
|
||||
instrumentor._instrument()
|
||||
instrumentor._uninstrument()
|
||||
@@ -0,0 +1,125 @@
|
||||
import pytest
|
||||
from unittest.mock import MagicMock
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from agentops.instrumentation.providers.anthropic.stream_wrapper import (
|
||||
messages_stream_wrapper,
|
||||
messages_stream_async_wrapper,
|
||||
AsyncStreamContextManagerWrapper,
|
||||
)
|
||||
from agentops.semconv import SpanAttributes, LLMRequestTypeValues, CoreAttributes, MessageAttributes
|
||||
|
||||
|
||||
def test_sync_stream_wrapper(mock_tracer, mock_stream_manager):
|
||||
"""Test the synchronous stream wrapper functionality including span creation,
|
||||
context manager behavior, and token counting."""
|
||||
wrapper = messages_stream_wrapper(mock_tracer)
|
||||
wrapped = MagicMock(return_value=mock_stream_manager)
|
||||
result = wrapper(wrapped, None, [], {})
|
||||
|
||||
assert hasattr(result, "__enter__")
|
||||
assert hasattr(result, "__exit__")
|
||||
|
||||
mock_tracer.start_span.assert_called_with(
|
||||
"anthropic.messages.stream",
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={SpanAttributes.LLM_REQUEST_TYPE: LLMRequestTypeValues.CHAT.value},
|
||||
)
|
||||
|
||||
span = mock_tracer.start_span.return_value
|
||||
with result as stream:
|
||||
assert span.set_attribute.called
|
||||
text = list(stream.text_stream)
|
||||
assert len(text) == 5
|
||||
assert span.set_attribute.call_count > 0
|
||||
|
||||
|
||||
def test_async_stream_wrapper(mock_tracer, mock_async_stream_manager):
|
||||
"""Test the asynchronous stream wrapper functionality including span creation
|
||||
and proper async context manager setup."""
|
||||
wrapper = messages_stream_async_wrapper(mock_tracer)
|
||||
wrapped = MagicMock(return_value=mock_async_stream_manager)
|
||||
result = wrapper(wrapped, None, [], {})
|
||||
|
||||
assert isinstance(result, AsyncStreamContextManagerWrapper)
|
||||
|
||||
mock_tracer.start_span.assert_called_with(
|
||||
"anthropic.messages.stream",
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={SpanAttributes.LLM_REQUEST_TYPE: LLMRequestTypeValues.CHAT.value},
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_stream_context_manager(mock_tracer, mock_async_stream_manager):
|
||||
"""Test the async stream context manager functionality including token counting
|
||||
and attribute setting."""
|
||||
wrapper = messages_stream_async_wrapper(mock_tracer)
|
||||
wrapped = MagicMock(return_value=mock_async_stream_manager)
|
||||
result = wrapper(wrapped, None, [], {})
|
||||
|
||||
async with result as stream:
|
||||
span = mock_tracer.start_span.return_value
|
||||
assert span.set_attribute.called
|
||||
|
||||
text = []
|
||||
async for chunk in stream.text_stream:
|
||||
text.append(chunk)
|
||||
assert len(text) == 5
|
||||
assert span.set_attribute.call_count > 0
|
||||
|
||||
|
||||
def test_stream_error_handling(mock_tracer):
|
||||
"""Test error handling in stream wrapper including exception recording and
|
||||
attribute setting."""
|
||||
wrapper = messages_stream_wrapper(mock_tracer)
|
||||
wrapped = MagicMock(side_effect=Exception("Test error"))
|
||||
|
||||
with pytest.raises(Exception):
|
||||
wrapper(wrapped, None, [], {})
|
||||
|
||||
span = mock_tracer.start_span.return_value
|
||||
span.record_exception.assert_called()
|
||||
span.set_attribute.assert_any_call(CoreAttributes.ERROR_MESSAGE, "Test error")
|
||||
span.set_attribute.assert_any_call(CoreAttributes.ERROR_TYPE, "Exception")
|
||||
span.end.assert_called()
|
||||
|
||||
|
||||
def test_stream_with_event_handler(mock_tracer, mock_stream_manager, mock_event_handler):
|
||||
"""Test stream wrapper with event handler including proper event forwarding
|
||||
and handler integration."""
|
||||
wrapper = messages_stream_wrapper(mock_tracer)
|
||||
wrapped = MagicMock(return_value=mock_stream_manager)
|
||||
result = wrapper(wrapped, None, [], {"event_handler": mock_event_handler})
|
||||
|
||||
assert hasattr(result, "__enter__")
|
||||
assert hasattr(result, "__exit__")
|
||||
|
||||
with result as stream:
|
||||
text = list(stream.text_stream)
|
||||
assert len(text) == 5
|
||||
assert mock_event_handler.on_text_delta.call_count > 0
|
||||
|
||||
|
||||
def test_stream_final_message_attributes(mock_tracer, mock_stream_manager):
|
||||
"""Test that final message attributes are properly captured and set on the span."""
|
||||
wrapper = messages_stream_wrapper(mock_tracer)
|
||||
wrapped = MagicMock(return_value=mock_stream_manager)
|
||||
|
||||
final_message = MagicMock()
|
||||
final_message.content = [MagicMock(text="Final response")]
|
||||
final_message.usage = MagicMock(input_tokens=10, output_tokens=20)
|
||||
mock_stream_manager._MessageStreamManager__stream._MessageStream__final_message_snapshot = final_message
|
||||
|
||||
result = wrapper(wrapped, None, [], {})
|
||||
|
||||
with result as stream:
|
||||
list(stream.text_stream)
|
||||
|
||||
span = mock_tracer.start_span.return_value
|
||||
span.set_attribute.assert_any_call(MessageAttributes.COMPLETION_TYPE.format(i=0), "text")
|
||||
span.set_attribute.assert_any_call(MessageAttributes.COMPLETION_ROLE.format(i=0), "assistant")
|
||||
span.set_attribute.assert_any_call(MessageAttributes.COMPLETION_CONTENT.format(i=0), "Final response")
|
||||
span.set_attribute.assert_any_call(SpanAttributes.LLM_USAGE_PROMPT_TOKENS, 10)
|
||||
span.set_attribute.assert_any_call(SpanAttributes.LLM_USAGE_COMPLETION_TOKENS, 20)
|
||||
span.set_attribute.assert_any_call(SpanAttributes.LLM_USAGE_TOTAL_TOKENS, 30)
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
Unit tests for the common instrumentation utilities.
|
||||
|
||||
This package contains tests for the shared utilities used across
|
||||
OpenTelemetry instrumentation modules, including wrappers, attributes,
|
||||
and other common functionality.
|
||||
"""
|
||||
@@ -0,0 +1,272 @@
|
||||
"""
|
||||
Unit tests for the common attributes module.
|
||||
|
||||
This module tests the functionality of the common attribute processing utilities
|
||||
shared across all instrumentors, including attribute extraction, common attribute
|
||||
getters, and base trace/span attribute functions.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import patch
|
||||
|
||||
from agentops.instrumentation.common.attributes import (
|
||||
_extract_attributes_from_mapping,
|
||||
get_common_attributes,
|
||||
get_base_trace_attributes,
|
||||
get_base_span_attributes,
|
||||
)
|
||||
from agentops.semconv import (
|
||||
CoreAttributes,
|
||||
InstrumentationAttributes,
|
||||
WorkflowAttributes,
|
||||
)
|
||||
|
||||
|
||||
class TestAttributeExtraction:
|
||||
"""Tests for attribute extraction utilities."""
|
||||
|
||||
def test_extract_attributes_from_object(self):
|
||||
"""Test extracting attributes from an object."""
|
||||
|
||||
# Create a test object with attributes
|
||||
class TestObject:
|
||||
def __init__(self):
|
||||
self.attr1 = "value1"
|
||||
self.attr2 = 42
|
||||
self.attr3 = None
|
||||
self.attr4 = []
|
||||
self.attr5 = {}
|
||||
self.attr6 = ["list", "of", "values"]
|
||||
self.attr7 = {"key": "value"}
|
||||
|
||||
test_obj = TestObject()
|
||||
|
||||
# Define a mapping of target attributes to source attributes
|
||||
mapping = {
|
||||
"target_attr1": "attr1",
|
||||
"target_attr2": "attr2",
|
||||
"target_attr3": "attr3", # None value, should be skipped
|
||||
"target_attr4": "attr4", # Empty list, should be skipped
|
||||
"target_attr5": "attr5", # Empty dict, should be skipped
|
||||
"target_attr6": "attr6", # List value, should be handled
|
||||
"target_attr7": "attr7", # Dict value, should be handled
|
||||
"target_attr8": "missing_attr", # Missing attribute, should be skipped
|
||||
}
|
||||
|
||||
# Extract attributes
|
||||
attributes = _extract_attributes_from_mapping(test_obj, mapping)
|
||||
|
||||
# Verify extracted attributes
|
||||
assert "target_attr1" in attributes
|
||||
assert attributes["target_attr1"] == "value1"
|
||||
assert "target_attr2" in attributes
|
||||
assert attributes["target_attr2"] == 42
|
||||
assert "target_attr3" not in attributes # None value should be skipped
|
||||
assert "target_attr4" not in attributes # Empty list should be skipped
|
||||
assert "target_attr5" not in attributes # Empty dict should be skipped
|
||||
assert "target_attr6" in attributes # List value should be handled
|
||||
assert attributes["target_attr6"] == '["list", "of", "values"]' # JSON encoded
|
||||
assert "target_attr7" in attributes # Dict value should be handled
|
||||
assert attributes["target_attr7"] == '{"key": "value"}' # JSON encoded
|
||||
assert "target_attr8" not in attributes # Missing attribute should be skipped
|
||||
|
||||
def test_extract_attributes_from_dict(self):
|
||||
"""Test extracting attributes from a dictionary."""
|
||||
# Create a test dictionary
|
||||
test_dict = {
|
||||
"attr1": "value1",
|
||||
"attr2": 42,
|
||||
"attr3": None,
|
||||
"attr4": [],
|
||||
"attr5": {},
|
||||
"attr6": ["list", "of", "values"],
|
||||
"attr7": {"key": "value"},
|
||||
}
|
||||
|
||||
# Define a mapping of target attributes to source attributes
|
||||
mapping = {
|
||||
"target_attr1": "attr1",
|
||||
"target_attr2": "attr2",
|
||||
"target_attr3": "attr3", # None value, should be skipped
|
||||
"target_attr4": "attr4", # Empty list, should be skipped
|
||||
"target_attr5": "attr5", # Empty dict, should be skipped
|
||||
"target_attr6": "attr6", # List value, should be handled
|
||||
"target_attr7": "attr7", # Dict value, should be handled
|
||||
"target_attr8": "missing_attr", # Missing key, should be skipped
|
||||
}
|
||||
|
||||
# Extract attributes
|
||||
attributes = _extract_attributes_from_mapping(test_dict, mapping)
|
||||
|
||||
# Verify extracted attributes
|
||||
assert "target_attr1" in attributes
|
||||
assert attributes["target_attr1"] == "value1"
|
||||
assert "target_attr2" in attributes
|
||||
assert attributes["target_attr2"] == 42
|
||||
assert "target_attr3" not in attributes # None value should be skipped
|
||||
assert "target_attr4" not in attributes # Empty list should be skipped
|
||||
assert "target_attr5" not in attributes # Empty dict should be skipped
|
||||
assert "target_attr6" in attributes # List value should be handled
|
||||
assert attributes["target_attr6"] == '["list", "of", "values"]' # JSON encoded
|
||||
assert "target_attr7" in attributes # Dict value should be handled
|
||||
assert attributes["target_attr7"] == '{"key": "value"}' # JSON encoded
|
||||
assert "target_attr8" not in attributes # Missing key should be skipped
|
||||
|
||||
|
||||
class TestCommonAttributes:
|
||||
"""Tests for common attribute getters."""
|
||||
|
||||
def test_get_common_attributes(self):
|
||||
"""Test getting common instrumentation attributes."""
|
||||
# Mock the version function to return a fixed value
|
||||
with patch("agentops.instrumentation.common.attributes.get_agentops_version", return_value="0.1.2"):
|
||||
# Get common attributes
|
||||
attributes = get_common_attributes()
|
||||
|
||||
# Verify attributes
|
||||
assert InstrumentationAttributes.NAME in attributes
|
||||
assert attributes[InstrumentationAttributes.NAME] == "agentops"
|
||||
assert InstrumentationAttributes.VERSION in attributes
|
||||
assert attributes[InstrumentationAttributes.VERSION] == "0.1.2"
|
||||
|
||||
def test_get_base_trace_attributes_with_valid_trace(self):
|
||||
"""Test getting base trace attributes with a valid trace."""
|
||||
|
||||
# Create a mock trace
|
||||
class MockTrace:
|
||||
def __init__(self):
|
||||
self.trace_id = "test_trace_id"
|
||||
self.name = "test_trace_name"
|
||||
|
||||
mock_trace = MockTrace()
|
||||
|
||||
# Mock the common attributes and tags functions
|
||||
with patch(
|
||||
"agentops.instrumentation.common.attributes.get_common_attributes",
|
||||
return_value={InstrumentationAttributes.NAME: "agentops", InstrumentationAttributes.VERSION: "0.1.2"},
|
||||
):
|
||||
# Get base trace attributes
|
||||
attributes = get_base_trace_attributes(mock_trace)
|
||||
|
||||
# Verify attributes
|
||||
assert CoreAttributes.TRACE_ID in attributes
|
||||
assert attributes[CoreAttributes.TRACE_ID] == "test_trace_id"
|
||||
assert WorkflowAttributes.WORKFLOW_NAME in attributes
|
||||
assert attributes[WorkflowAttributes.WORKFLOW_NAME] == "test_trace_name"
|
||||
assert WorkflowAttributes.WORKFLOW_STEP_TYPE in attributes
|
||||
assert attributes[WorkflowAttributes.WORKFLOW_STEP_TYPE] == "trace"
|
||||
assert InstrumentationAttributes.NAME in attributes
|
||||
assert attributes[InstrumentationAttributes.NAME] == "agentops"
|
||||
assert InstrumentationAttributes.VERSION in attributes
|
||||
assert attributes[InstrumentationAttributes.VERSION] == "0.1.2"
|
||||
|
||||
def test_get_base_trace_attributes_with_invalid_trace(self):
|
||||
"""Test getting base trace attributes with an invalid trace (missing trace_id)."""
|
||||
|
||||
# Create a mock trace without trace_id
|
||||
class MockTrace:
|
||||
def __init__(self):
|
||||
self.name = "test_trace_name"
|
||||
|
||||
mock_trace = MockTrace()
|
||||
|
||||
# Mock the logger
|
||||
with patch("agentops.instrumentation.common.attributes.logger.warning") as mock_warning:
|
||||
# Get base trace attributes
|
||||
attributes = get_base_trace_attributes(mock_trace)
|
||||
|
||||
# Verify logger was called
|
||||
mock_warning.assert_called_once_with("Cannot create trace attributes: missing trace_id")
|
||||
|
||||
# Verify attributes is empty
|
||||
assert attributes == {}
|
||||
|
||||
def test_get_base_span_attributes_with_basic_span(self):
|
||||
"""Test getting base span attributes with a basic span."""
|
||||
|
||||
# Create a mock span
|
||||
class MockSpan:
|
||||
def __init__(self):
|
||||
self.span_id = "test_span_id"
|
||||
self.trace_id = "test_trace_id"
|
||||
|
||||
mock_span = MockSpan()
|
||||
|
||||
# Mock the common attributes function
|
||||
with patch(
|
||||
"agentops.instrumentation.common.attributes.get_common_attributes",
|
||||
return_value={InstrumentationAttributes.NAME: "agentops", InstrumentationAttributes.VERSION: "0.1.2"},
|
||||
):
|
||||
# Get base span attributes
|
||||
attributes = get_base_span_attributes(mock_span)
|
||||
|
||||
# Verify attributes
|
||||
assert CoreAttributes.SPAN_ID in attributes
|
||||
assert attributes[CoreAttributes.SPAN_ID] == "test_span_id"
|
||||
assert CoreAttributes.TRACE_ID in attributes
|
||||
assert attributes[CoreAttributes.TRACE_ID] == "test_trace_id"
|
||||
assert InstrumentationAttributes.NAME in attributes
|
||||
assert attributes[InstrumentationAttributes.NAME] == "agentops"
|
||||
assert InstrumentationAttributes.VERSION in attributes
|
||||
assert attributes[InstrumentationAttributes.VERSION] == "0.1.2"
|
||||
assert CoreAttributes.PARENT_ID not in attributes # No parent_id in span
|
||||
|
||||
def test_get_base_span_attributes_with_parent(self):
|
||||
"""Test getting base span attributes with a span that has a parent."""
|
||||
|
||||
# Create a mock span with parent_id
|
||||
class MockSpan:
|
||||
def __init__(self):
|
||||
self.span_id = "test_span_id"
|
||||
self.trace_id = "test_trace_id"
|
||||
self.parent_id = "test_parent_id"
|
||||
|
||||
mock_span = MockSpan()
|
||||
|
||||
# Mock the common attributes function
|
||||
with patch(
|
||||
"agentops.instrumentation.common.attributes.get_common_attributes",
|
||||
return_value={InstrumentationAttributes.NAME: "agentops", InstrumentationAttributes.VERSION: "0.1.2"},
|
||||
):
|
||||
# Get base span attributes
|
||||
attributes = get_base_span_attributes(mock_span)
|
||||
|
||||
# Verify attributes
|
||||
assert CoreAttributes.SPAN_ID in attributes
|
||||
assert attributes[CoreAttributes.SPAN_ID] == "test_span_id"
|
||||
assert CoreAttributes.TRACE_ID in attributes
|
||||
assert attributes[CoreAttributes.TRACE_ID] == "test_trace_id"
|
||||
assert CoreAttributes.PARENT_ID in attributes
|
||||
assert attributes[CoreAttributes.PARENT_ID] == "test_parent_id"
|
||||
assert InstrumentationAttributes.NAME in attributes
|
||||
assert attributes[InstrumentationAttributes.NAME] == "agentops"
|
||||
assert InstrumentationAttributes.VERSION in attributes
|
||||
assert attributes[InstrumentationAttributes.VERSION] == "0.1.2"
|
||||
|
||||
def test_get_base_span_attributes_with_unknown_values(self):
|
||||
"""Test getting base span attributes with a span that has unknown values."""
|
||||
# Create a mock object that doesn't have the expected attributes
|
||||
mock_object = object()
|
||||
|
||||
# Mock the common attributes function
|
||||
with patch(
|
||||
"agentops.instrumentation.common.attributes.get_common_attributes",
|
||||
return_value={InstrumentationAttributes.NAME: "agentops", InstrumentationAttributes.VERSION: "0.1.2"},
|
||||
):
|
||||
# Get base span attributes
|
||||
attributes = get_base_span_attributes(mock_object)
|
||||
|
||||
# Verify attributes
|
||||
assert CoreAttributes.SPAN_ID in attributes
|
||||
assert attributes[CoreAttributes.SPAN_ID] == "unknown"
|
||||
assert CoreAttributes.TRACE_ID in attributes
|
||||
assert attributes[CoreAttributes.TRACE_ID] == "unknown"
|
||||
assert CoreAttributes.PARENT_ID not in attributes # No parent_id
|
||||
assert InstrumentationAttributes.NAME in attributes
|
||||
assert attributes[InstrumentationAttributes.NAME] == "agentops"
|
||||
assert InstrumentationAttributes.VERSION in attributes
|
||||
assert attributes[InstrumentationAttributes.VERSION] == "0.1.2"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main()
|
||||
@@ -0,0 +1,581 @@
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from types import SimpleNamespace
|
||||
|
||||
from agentops.instrumentation.common.streaming import (
|
||||
BaseStreamWrapper,
|
||||
SyncStreamWrapper,
|
||||
AsyncStreamWrapper,
|
||||
create_stream_wrapper_factory,
|
||||
StreamingResponseHandler,
|
||||
)
|
||||
from agentops.instrumentation.common.token_counting import TokenUsage
|
||||
|
||||
|
||||
class TestBaseStreamWrapper:
|
||||
"""Test the BaseStreamWrapper class."""
|
||||
|
||||
def test_init(self):
|
||||
"""Test BaseStreamWrapper initialization."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
extract_attrs = lambda x: {"key": "value"}
|
||||
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content, extract_attrs)
|
||||
|
||||
assert wrapper.stream is mock_stream
|
||||
assert wrapper.span is mock_span
|
||||
assert wrapper.extract_chunk_content is extract_content
|
||||
assert wrapper.extract_chunk_attributes is extract_attrs
|
||||
assert wrapper.start_time > 0
|
||||
assert wrapper.first_token_time is None
|
||||
assert wrapper.chunks_received == 0
|
||||
assert wrapper.accumulated_content == []
|
||||
assert isinstance(wrapper.token_usage, TokenUsage)
|
||||
|
||||
def test_init_without_extract_chunk_attributes(self):
|
||||
"""Test BaseStreamWrapper initialization without extract_chunk_attributes."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
|
||||
assert wrapper.extract_chunk_attributes is not None
|
||||
assert wrapper.extract_chunk_attributes({}) == {}
|
||||
|
||||
def test_process_chunk_first_token(self):
|
||||
"""Test processing the first chunk (first token timing)."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
|
||||
# Mock the token usage extraction to avoid type errors
|
||||
with patch(
|
||||
"agentops.instrumentation.common.token_counting.TokenUsageExtractor.extract_from_response"
|
||||
) as mock_extract:
|
||||
mock_extract.return_value = Mock(prompt_tokens=None, completion_tokens=None)
|
||||
|
||||
with patch("time.time", return_value=100.0):
|
||||
wrapper._process_chunk(Mock())
|
||||
|
||||
assert wrapper.first_token_time == 100.0
|
||||
assert wrapper.chunks_received == 1
|
||||
assert wrapper.accumulated_content == ["test"]
|
||||
|
||||
def test_process_chunk_subsequent_tokens(self):
|
||||
"""Test processing subsequent chunks (no first token timing)."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
wrapper.first_token_time = 50.0
|
||||
|
||||
# Mock the token usage extraction
|
||||
with patch(
|
||||
"agentops.instrumentation.common.token_counting.TokenUsageExtractor.extract_from_response"
|
||||
) as mock_extract:
|
||||
mock_extract.return_value = Mock(prompt_tokens=None, completion_tokens=None)
|
||||
|
||||
wrapper._process_chunk(Mock())
|
||||
|
||||
assert wrapper.chunks_received == 1
|
||||
assert wrapper.accumulated_content == ["test"]
|
||||
|
||||
def test_process_chunk_with_attributes(self):
|
||||
"""Test processing chunk with custom attributes."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
extract_attrs = lambda x: {"custom_key": "custom_value"}
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content, extract_attrs)
|
||||
|
||||
# Mock the token usage extraction
|
||||
with patch(
|
||||
"agentops.instrumentation.common.token_counting.TokenUsageExtractor.extract_from_response"
|
||||
) as mock_extract:
|
||||
mock_extract.return_value = Mock(prompt_tokens=None, completion_tokens=None)
|
||||
|
||||
wrapper._process_chunk(Mock())
|
||||
|
||||
mock_span.set_attribute.assert_called_with("custom_key", "custom_value")
|
||||
|
||||
def test_process_chunk_with_token_usage(self):
|
||||
"""Test processing chunk with token usage information."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
|
||||
# Mock chunk with usage
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.usage = {"prompt_tokens": 10, "completion_tokens": 5}
|
||||
|
||||
with patch(
|
||||
"agentops.instrumentation.common.token_counting.TokenUsageExtractor.extract_from_response"
|
||||
) as mock_extract:
|
||||
mock_usage = Mock()
|
||||
mock_usage.prompt_tokens = 10
|
||||
mock_usage.completion_tokens = 5
|
||||
mock_extract.return_value = mock_usage
|
||||
|
||||
wrapper._process_chunk(mock_chunk)
|
||||
|
||||
assert wrapper.token_usage.prompt_tokens == 10
|
||||
assert wrapper.token_usage.completion_tokens == 5
|
||||
|
||||
def test_process_chunk_with_usage_metadata(self):
|
||||
"""Test processing chunk with usage_metadata attribute."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
|
||||
# Mock chunk with usage_metadata
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.usage_metadata = {"prompt_tokens": 10, "completion_tokens": 5}
|
||||
|
||||
with patch(
|
||||
"agentops.instrumentation.common.token_counting.TokenUsageExtractor.extract_from_response"
|
||||
) as mock_extract:
|
||||
mock_usage = Mock()
|
||||
mock_usage.prompt_tokens = 10
|
||||
mock_usage.completion_tokens = 5
|
||||
mock_extract.return_value = mock_usage
|
||||
|
||||
wrapper._process_chunk(mock_chunk)
|
||||
|
||||
assert wrapper.token_usage.prompt_tokens == 10
|
||||
assert wrapper.token_usage.completion_tokens == 5
|
||||
|
||||
def test_process_chunk_accumulate_completion_tokens(self):
|
||||
"""Test that completion tokens are accumulated across chunks."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
|
||||
# Mock chunks with usage
|
||||
mock_chunk1 = Mock()
|
||||
mock_chunk2 = Mock()
|
||||
|
||||
with patch(
|
||||
"agentops.instrumentation.common.token_counting.TokenUsageExtractor.extract_from_response"
|
||||
) as mock_extract:
|
||||
mock_usage1 = Mock()
|
||||
mock_usage1.prompt_tokens = 10
|
||||
mock_usage1.completion_tokens = 3
|
||||
mock_usage2 = Mock()
|
||||
mock_usage2.prompt_tokens = 10
|
||||
mock_usage2.completion_tokens = 2
|
||||
mock_extract.side_effect = [mock_usage1, mock_usage2]
|
||||
|
||||
wrapper._process_chunk(mock_chunk1)
|
||||
wrapper._process_chunk(mock_chunk2)
|
||||
|
||||
assert wrapper.token_usage.prompt_tokens == 10
|
||||
assert wrapper.token_usage.completion_tokens == 5 # 3 + 2
|
||||
|
||||
def test_finalize_success(self):
|
||||
"""Test successful finalization of stream."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
|
||||
# Add some content
|
||||
wrapper.accumulated_content = ["Hello", " ", "World"]
|
||||
wrapper.chunks_received = 3
|
||||
wrapper.first_token_time = 99.0 # Set a specific time
|
||||
|
||||
with patch("time.time", return_value=100.0):
|
||||
wrapper._finalize()
|
||||
|
||||
# Check that all attributes were set
|
||||
mock_span.set_attribute.assert_any_call("streaming.final_content", "Hello World")
|
||||
mock_span.set_attribute.assert_any_call("streaming.chunk_count", 3)
|
||||
mock_span.set_attribute.assert_any_call("streaming.total_duration", 100.0 - wrapper.start_time)
|
||||
mock_span.set_attribute.assert_any_call("streaming.generation_duration", 1.0)
|
||||
mock_span.set_status.assert_called_once()
|
||||
mock_span.end.assert_called_once()
|
||||
|
||||
def test_finalize_with_exception(self):
|
||||
"""Test finalization with exception handling."""
|
||||
mock_stream = Mock()
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: "test"
|
||||
wrapper = BaseStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
|
||||
with patch(
|
||||
"agentops.instrumentation.common.span_management.safe_set_attribute", side_effect=Exception("Test error")
|
||||
):
|
||||
wrapper._finalize()
|
||||
|
||||
mock_span.set_status.assert_called()
|
||||
mock_span.end.assert_called_once()
|
||||
|
||||
|
||||
class TestSyncStreamWrapper:
|
||||
"""Test the SyncStreamWrapper class."""
|
||||
|
||||
def test_iteration_success(self):
|
||||
"""Test successful iteration through sync stream."""
|
||||
mock_stream = ["chunk1", "chunk2", "chunk3"]
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: x
|
||||
wrapper = SyncStreamWrapper(mock_stream, mock_span, extract_content)
|
||||
|
||||
result = list(wrapper)
|
||||
|
||||
assert result == ["chunk1", "chunk2", "chunk3"]
|
||||
assert wrapper.chunks_received == 3
|
||||
assert wrapper.accumulated_content == ["chunk1", "chunk2", "chunk3"]
|
||||
mock_span.end.assert_called_once()
|
||||
|
||||
def test_iteration_with_exception(self):
|
||||
"""Test iteration with exception handling."""
|
||||
|
||||
def failing_stream():
|
||||
yield "chunk1"
|
||||
raise ValueError("Test error")
|
||||
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: x
|
||||
wrapper = SyncStreamWrapper(failing_stream(), mock_span, extract_content)
|
||||
|
||||
with pytest.raises(ValueError, match="Test error"):
|
||||
list(wrapper)
|
||||
|
||||
mock_span.set_status.assert_called()
|
||||
mock_span.record_exception.assert_called_once()
|
||||
mock_span.end.assert_called_once()
|
||||
|
||||
|
||||
class TestAsyncStreamWrapper:
|
||||
"""Test the AsyncStreamWrapper class."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_iteration_success(self):
|
||||
"""Test successful async iteration through stream."""
|
||||
|
||||
async def async_stream():
|
||||
yield "chunk1"
|
||||
yield "chunk2"
|
||||
yield "chunk3"
|
||||
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: x
|
||||
wrapper = AsyncStreamWrapper(async_stream(), mock_span, extract_content)
|
||||
|
||||
result = []
|
||||
async for chunk in wrapper:
|
||||
result.append(chunk)
|
||||
|
||||
assert result == ["chunk1", "chunk2", "chunk3"]
|
||||
assert wrapper.chunks_received == 3
|
||||
assert wrapper.accumulated_content == ["chunk1", "chunk2", "chunk3"]
|
||||
mock_span.end.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_iteration_with_exception(self):
|
||||
"""Test async iteration with exception handling."""
|
||||
|
||||
async def failing_async_stream():
|
||||
yield "chunk1"
|
||||
raise ValueError("Test error")
|
||||
|
||||
mock_span = Mock()
|
||||
extract_content = lambda x: x
|
||||
wrapper = AsyncStreamWrapper(failing_async_stream(), mock_span, extract_content)
|
||||
|
||||
with pytest.raises(ValueError, match="Test error"):
|
||||
async for chunk in wrapper:
|
||||
pass
|
||||
|
||||
mock_span.set_status.assert_called()
|
||||
mock_span.record_exception.assert_called_once()
|
||||
mock_span.end.assert_called_once()
|
||||
|
||||
|
||||
class TestCreateStreamWrapperFactory:
|
||||
"""Test the create_stream_wrapper_factory function."""
|
||||
|
||||
def test_create_sync_wrapper(self):
|
||||
"""Test creating a sync stream wrapper."""
|
||||
mock_tracer = Mock()
|
||||
mock_span = Mock()
|
||||
mock_tracer.start_span.return_value = mock_span
|
||||
|
||||
def mock_stream():
|
||||
yield "chunk1"
|
||||
yield "chunk2"
|
||||
|
||||
def mock_wrapped(*args, **kwargs):
|
||||
return mock_stream()
|
||||
|
||||
extract_content = lambda x: x
|
||||
factory = create_stream_wrapper_factory(mock_tracer, "test_span", extract_content)
|
||||
|
||||
result = factory(mock_wrapped, None, (), {})
|
||||
|
||||
assert isinstance(result, SyncStreamWrapper)
|
||||
mock_tracer.start_span.assert_called_with("test_span")
|
||||
|
||||
def test_create_async_wrapper(self):
|
||||
"""Test creating an async stream wrapper."""
|
||||
mock_tracer = Mock()
|
||||
mock_span = Mock()
|
||||
mock_tracer.start_span.return_value = mock_span
|
||||
|
||||
async def mock_async_stream():
|
||||
yield "chunk1"
|
||||
yield "chunk2"
|
||||
|
||||
def mock_wrapped(*args, **kwargs):
|
||||
return mock_async_stream()
|
||||
|
||||
extract_content = lambda x: x
|
||||
factory = create_stream_wrapper_factory(mock_tracer, "test_span", extract_content)
|
||||
|
||||
result = factory(mock_wrapped, None, (), {})
|
||||
|
||||
assert isinstance(result, AsyncStreamWrapper)
|
||||
mock_tracer.start_span.assert_called_with("test_span")
|
||||
|
||||
def test_create_wrapper_with_initial_attributes(self):
|
||||
"""Test creating a wrapper with initial attributes."""
|
||||
mock_tracer = Mock()
|
||||
mock_span = Mock()
|
||||
mock_tracer.start_span.return_value = mock_span
|
||||
|
||||
def mock_stream():
|
||||
yield "chunk1"
|
||||
|
||||
def mock_wrapped(*args, **kwargs):
|
||||
return mock_stream()
|
||||
|
||||
extract_content = lambda x: x
|
||||
initial_attrs = {"initial_key": "initial_value"}
|
||||
factory = create_stream_wrapper_factory(
|
||||
mock_tracer, "test_span", extract_content, initial_attributes=initial_attrs
|
||||
)
|
||||
|
||||
factory(mock_wrapped, None, (), {})
|
||||
|
||||
mock_span.set_attribute.assert_called_with("initial_key", "initial_value")
|
||||
|
||||
def test_create_wrapper_with_exception(self):
|
||||
"""Test creating a wrapper when wrapped function raises exception."""
|
||||
mock_tracer = Mock()
|
||||
mock_span = Mock()
|
||||
mock_tracer.start_span.return_value = mock_span
|
||||
|
||||
def mock_wrapped(*args, **kwargs):
|
||||
raise ValueError("Test error")
|
||||
|
||||
extract_content = lambda x: x
|
||||
factory = create_stream_wrapper_factory(mock_tracer, "test_span", extract_content)
|
||||
|
||||
with pytest.raises(ValueError, match="Test error"):
|
||||
factory(mock_wrapped, None, (), {})
|
||||
|
||||
mock_span.set_status.assert_called()
|
||||
mock_span.record_exception.assert_called_once()
|
||||
mock_span.end.assert_called_once()
|
||||
|
||||
|
||||
class TestStreamingResponseHandler:
|
||||
"""Test the StreamingResponseHandler class."""
|
||||
|
||||
def test_extract_openai_chunk_content_with_choices(self):
|
||||
"""Test extracting content from OpenAI-style chunk with choices."""
|
||||
mock_choice = Mock()
|
||||
mock_delta = Mock()
|
||||
mock_delta.content = "Hello"
|
||||
mock_choice.delta = mock_delta
|
||||
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.choices = [mock_choice]
|
||||
|
||||
result = StreamingResponseHandler.extract_openai_chunk_content(mock_chunk)
|
||||
assert result == "Hello"
|
||||
|
||||
def test_extract_openai_chunk_content_without_choices(self):
|
||||
"""Test extracting content from OpenAI-style chunk without choices."""
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.choices = []
|
||||
|
||||
result = StreamingResponseHandler.extract_openai_chunk_content(mock_chunk)
|
||||
assert result is None
|
||||
|
||||
def test_extract_openai_chunk_content_without_delta(self):
|
||||
"""Test extracting content from OpenAI-style chunk without delta."""
|
||||
mock_choice = Mock()
|
||||
mock_choice.delta = None
|
||||
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.choices = [mock_choice]
|
||||
|
||||
result = StreamingResponseHandler.extract_openai_chunk_content(mock_chunk)
|
||||
assert result is None
|
||||
|
||||
def test_extract_openai_chunk_content_without_content(self):
|
||||
"""Test extracting content from OpenAI-style chunk without content."""
|
||||
mock_choice = Mock()
|
||||
mock_delta = Mock()
|
||||
del mock_delta.content # Remove content attribute
|
||||
mock_choice.delta = mock_delta
|
||||
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.choices = [mock_choice]
|
||||
|
||||
result = StreamingResponseHandler.extract_openai_chunk_content(mock_chunk)
|
||||
assert result is None
|
||||
|
||||
def test_extract_anthropic_chunk_content_content_block_delta(self):
|
||||
"""Test extracting content from Anthropic content_block_delta chunk."""
|
||||
mock_delta = Mock()
|
||||
mock_delta.text = "Hello"
|
||||
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.type = "content_block_delta"
|
||||
mock_chunk.delta = mock_delta
|
||||
|
||||
result = StreamingResponseHandler.extract_anthropic_chunk_content(mock_chunk)
|
||||
assert result == "Hello"
|
||||
|
||||
def test_extract_anthropic_chunk_content_message_delta(self):
|
||||
"""Test extracting content from Anthropic message_delta chunk."""
|
||||
mock_delta = Mock()
|
||||
mock_delta.content = "Hello"
|
||||
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.type = "message_delta"
|
||||
mock_chunk.delta = mock_delta
|
||||
|
||||
result = StreamingResponseHandler.extract_anthropic_chunk_content(mock_chunk)
|
||||
assert result == "Hello"
|
||||
|
||||
def test_extract_anthropic_chunk_content_other_type(self):
|
||||
"""Test extracting content from Anthropic chunk with other type."""
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.type = "other_type"
|
||||
|
||||
result = StreamingResponseHandler.extract_anthropic_chunk_content(mock_chunk)
|
||||
assert result is None
|
||||
|
||||
def test_extract_anthropic_chunk_content_without_delta(self):
|
||||
"""Test extracting content from Anthropic chunk without delta."""
|
||||
mock_chunk = Mock()
|
||||
mock_chunk.type = "content_block_delta"
|
||||
mock_chunk.delta = None
|
||||
|
||||
result = StreamingResponseHandler.extract_anthropic_chunk_content(mock_chunk)
|
||||
assert result is None
|
||||
|
||||
def test_extract_generic_chunk_content_with_content(self):
|
||||
chunk = SimpleNamespace(content="Hello")
|
||||
result = StreamingResponseHandler.extract_generic_chunk_content(chunk)
|
||||
assert result == "Hello"
|
||||
|
||||
def test_extract_generic_chunk_content_with_text(self):
|
||||
chunk = SimpleNamespace(text="Hello")
|
||||
result = StreamingResponseHandler.extract_generic_chunk_content(chunk)
|
||||
assert result == "Hello"
|
||||
|
||||
def test_extract_generic_chunk_content_with_delta_content(self):
|
||||
delta = SimpleNamespace(content="Hello")
|
||||
chunk = SimpleNamespace(delta=delta)
|
||||
result = StreamingResponseHandler.extract_generic_chunk_content(chunk)
|
||||
assert result == "Hello"
|
||||
|
||||
def test_extract_generic_chunk_content_with_delta_text(self):
|
||||
delta = SimpleNamespace(text="Hello")
|
||||
chunk = SimpleNamespace(delta=delta)
|
||||
result = StreamingResponseHandler.extract_generic_chunk_content(chunk)
|
||||
assert result == "Hello"
|
||||
|
||||
def test_extract_generic_chunk_content_string(self):
|
||||
"""Test extracting content from string chunk."""
|
||||
chunk = "Hello"
|
||||
|
||||
result = StreamingResponseHandler.extract_generic_chunk_content(chunk)
|
||||
assert result == "Hello"
|
||||
|
||||
def test_extract_generic_chunk_content_no_match(self):
|
||||
"""Test extracting content from chunk with no matching pattern."""
|
||||
mock_chunk = Mock()
|
||||
# Remove all potential attributes
|
||||
del mock_chunk.content
|
||||
del mock_chunk.text
|
||||
del mock_chunk.delta
|
||||
|
||||
result = StreamingResponseHandler.extract_generic_chunk_content(mock_chunk)
|
||||
assert result is None
|
||||
|
||||
def test_extract_generic_chunk_content_delta_without_content_or_text(self):
|
||||
delta = SimpleNamespace()
|
||||
chunk = SimpleNamespace(delta=delta)
|
||||
result = StreamingResponseHandler.extract_generic_chunk_content(chunk)
|
||||
assert result is None
|
||||
|
||||
|
||||
class TestStreamingIntegration:
|
||||
"""Integration tests for streaming functionality."""
|
||||
|
||||
def test_full_sync_stream_processing(self):
|
||||
"""Test complete sync stream processing workflow."""
|
||||
mock_tracer = Mock()
|
||||
mock_span = Mock()
|
||||
mock_tracer.start_span.return_value = mock_span
|
||||
|
||||
def mock_stream():
|
||||
yield "Hello"
|
||||
yield " "
|
||||
yield "World"
|
||||
|
||||
def mock_wrapped(*args, **kwargs):
|
||||
return mock_stream()
|
||||
|
||||
extract_content = lambda x: x
|
||||
factory = create_stream_wrapper_factory(mock_tracer, "test_span", extract_content)
|
||||
wrapper = factory(mock_wrapped, None, (), {})
|
||||
|
||||
result = list(wrapper)
|
||||
|
||||
assert result == ["Hello", " ", "World"]
|
||||
assert wrapper.accumulated_content == ["Hello", " ", "World"]
|
||||
assert wrapper.chunks_received == 3
|
||||
mock_span.set_attribute.assert_any_call("streaming.final_content", "Hello World")
|
||||
mock_span.set_attribute.assert_any_call("streaming.chunk_count", 3)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_full_async_stream_processing(self):
|
||||
"""Test complete async stream processing workflow."""
|
||||
mock_tracer = Mock()
|
||||
mock_span = Mock()
|
||||
mock_tracer.start_span.return_value = mock_span
|
||||
|
||||
async def mock_async_stream():
|
||||
yield "Hello"
|
||||
yield " "
|
||||
yield "World"
|
||||
|
||||
def mock_wrapped(*args, **kwargs):
|
||||
return mock_async_stream()
|
||||
|
||||
extract_content = lambda x: x
|
||||
factory = create_stream_wrapper_factory(mock_tracer, "test_span", extract_content)
|
||||
wrapper = factory(mock_wrapped, None, (), {})
|
||||
|
||||
result = []
|
||||
async for chunk in wrapper:
|
||||
result.append(chunk)
|
||||
|
||||
assert result == ["Hello", " ", "World"]
|
||||
assert wrapper.accumulated_content == ["Hello", " ", "World"]
|
||||
assert wrapper.chunks_received == 3
|
||||
mock_span.set_attribute.assert_any_call("streaming.final_content", "Hello World")
|
||||
mock_span.set_attribute.assert_any_call("streaming.chunk_count", 3)
|
||||
@@ -0,0 +1,26 @@
|
||||
from agentops.instrumentation.common.token_counting import TokenUsage
|
||||
from agentops.semconv import SpanAttributes
|
||||
|
||||
|
||||
class TestTokenUsageToAttributes:
|
||||
def test_skips_zero_values(self):
|
||||
usage = TokenUsage(
|
||||
prompt_tokens=0,
|
||||
completion_tokens=0,
|
||||
total_tokens=0,
|
||||
cached_prompt_tokens=0,
|
||||
cached_read_tokens=0,
|
||||
reasoning_tokens=0,
|
||||
)
|
||||
|
||||
attrs = usage.to_attributes()
|
||||
assert attrs == {}
|
||||
|
||||
def test_includes_positive_values_only(self):
|
||||
usage = TokenUsage(prompt_tokens=5, completion_tokens=0, total_tokens=5)
|
||||
attrs = usage.to_attributes()
|
||||
assert SpanAttributes.LLM_USAGE_PROMPT_TOKENS in attrs
|
||||
assert attrs[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 5
|
||||
assert SpanAttributes.LLM_USAGE_COMPLETION_TOKENS not in attrs
|
||||
assert SpanAttributes.LLM_USAGE_TOTAL_TOKENS in attrs
|
||||
assert attrs[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 5
|
||||
@@ -0,0 +1,377 @@
|
||||
"""
|
||||
Unit tests for the common wrappers module.
|
||||
|
||||
This module tests the functionality of the common wrapper utilities
|
||||
for OpenTelemetry instrumentation, including WrapConfig, _update_span,
|
||||
_finish_span_success, _finish_span_error, _create_wrapper, wrap, and unwrap.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from typing import Dict, Any, Optional, Tuple
|
||||
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from agentops.instrumentation.common.wrappers import (
|
||||
WrapConfig,
|
||||
_update_span,
|
||||
_finish_span_success,
|
||||
_finish_span_error,
|
||||
_create_wrapper,
|
||||
wrap,
|
||||
unwrap,
|
||||
)
|
||||
from agentops.instrumentation.common.attributes import AttributeMap
|
||||
from tests.unit.instrumentation.mock_span import MockTracingSpan
|
||||
|
||||
|
||||
class TestWrapConfig:
|
||||
"""Tests for the WrapConfig class."""
|
||||
|
||||
def test_wrap_config_initialization(self):
|
||||
"""Test that WrapConfig is initialized properly with default values."""
|
||||
|
||||
# Create a simple attribute handler
|
||||
def dummy_handler(
|
||||
args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, return_value: Optional[Any] = None
|
||||
) -> AttributeMap:
|
||||
return {"key": "value"}
|
||||
|
||||
# Initialize a WrapConfig
|
||||
config = WrapConfig(
|
||||
trace_name="test_trace",
|
||||
package="test_package",
|
||||
class_name="TestClass",
|
||||
method_name="test_method",
|
||||
handler=dummy_handler,
|
||||
)
|
||||
|
||||
# Verify config values
|
||||
assert config.trace_name == "test_trace"
|
||||
assert config.package == "test_package"
|
||||
assert config.class_name == "TestClass"
|
||||
assert config.method_name == "test_method"
|
||||
assert config.handler == dummy_handler
|
||||
assert config.span_kind == SpanKind.CLIENT # Default value
|
||||
|
||||
def test_wrap_config_repr(self):
|
||||
"""Test the string representation of WrapConfig."""
|
||||
|
||||
# Create a simple attribute handler
|
||||
def dummy_handler(
|
||||
args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, return_value: Optional[Any] = None
|
||||
) -> AttributeMap:
|
||||
return {"key": "value"}
|
||||
|
||||
# Initialize a WrapConfig
|
||||
config = WrapConfig(
|
||||
trace_name="test_trace",
|
||||
package="test_package",
|
||||
class_name="TestClass",
|
||||
method_name="test_method",
|
||||
handler=dummy_handler,
|
||||
)
|
||||
|
||||
# Verify the string representation
|
||||
assert repr(config) == "test_package.TestClass.test_method"
|
||||
|
||||
def test_wrap_config_with_custom_span_kind(self):
|
||||
"""Test that WrapConfig accepts a custom span kind."""
|
||||
|
||||
# Create a simple attribute handler
|
||||
def dummy_handler(
|
||||
args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, return_value: Optional[Any] = None
|
||||
) -> AttributeMap:
|
||||
return {"key": "value"}
|
||||
|
||||
# Initialize a WrapConfig with custom span kind
|
||||
config = WrapConfig(
|
||||
trace_name="test_trace",
|
||||
package="test_package",
|
||||
class_name="TestClass",
|
||||
method_name="test_method",
|
||||
handler=dummy_handler,
|
||||
span_kind=SpanKind.SERVER,
|
||||
)
|
||||
|
||||
# Verify the span kind
|
||||
assert config.span_kind == SpanKind.SERVER
|
||||
|
||||
|
||||
class TestSpanHelpers:
|
||||
"""Tests for span helper functions."""
|
||||
|
||||
def test_update_span(self):
|
||||
"""Test _update_span sets attributes on a span."""
|
||||
# Create a mock span
|
||||
mock_span = MockTracingSpan()
|
||||
|
||||
# Define attributes to set
|
||||
attributes = {"key1": "value1", "key2": 42, "key3": True}
|
||||
|
||||
# Call _update_span
|
||||
_update_span(mock_span, attributes)
|
||||
|
||||
# Verify attributes were set
|
||||
for key, value in attributes.items():
|
||||
assert mock_span.attributes[key] == value
|
||||
|
||||
def test_finish_span_success(self):
|
||||
"""Test _finish_span_success sets status to OK."""
|
||||
# Create a mock span
|
||||
mock_span = MockTracingSpan()
|
||||
|
||||
# Call _finish_span_success
|
||||
_finish_span_success(mock_span)
|
||||
|
||||
# Verify status was set
|
||||
assert mock_span.status is not None
|
||||
# The actual object is a real Status with StatusCode.OK
|
||||
# We're not checking the exact type, just that it was called with OK status code
|
||||
|
||||
def test_finish_span_error(self):
|
||||
"""Test _finish_span_error sets error status and records exception."""
|
||||
# Create a mock span
|
||||
mock_span = MockTracingSpan()
|
||||
|
||||
# Create a test exception
|
||||
test_exception = ValueError("Test error")
|
||||
|
||||
# Call _finish_span_error
|
||||
_finish_span_error(mock_span, test_exception)
|
||||
|
||||
# Verify status was set to ERROR
|
||||
assert mock_span.status is not None
|
||||
# The actual object is a real Status with StatusCode.ERROR
|
||||
# We're not checking the exact type, just that it was called with ERROR status code
|
||||
|
||||
# Verify exception was recorded
|
||||
assert len(mock_span.events) == 1
|
||||
assert mock_span.events[0]["name"] == "exception"
|
||||
assert mock_span.events[0]["exception"] == test_exception
|
||||
|
||||
|
||||
class TestCreateWrapper:
|
||||
"""Tests for _create_wrapper and wrapper functionality."""
|
||||
|
||||
def test_create_wrapper_success_path(self):
|
||||
"""Test wrapper created by _create_wrapper handles success path."""
|
||||
# Create a mock tracer
|
||||
mock_tracer = MagicMock()
|
||||
mock_span = MockTracingSpan()
|
||||
|
||||
# Mock start_as_current_span to return our mock span
|
||||
mock_tracer.start_as_current_span.return_value.__enter__.return_value = mock_span
|
||||
|
||||
# Create a simple attribute handler
|
||||
def dummy_handler(
|
||||
args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, return_value: Optional[Any] = None
|
||||
) -> AttributeMap:
|
||||
result = {}
|
||||
if args:
|
||||
result["args"] = str(args)
|
||||
if kwargs:
|
||||
result["kwargs"] = str(kwargs)
|
||||
if return_value is not None:
|
||||
result["return_value"] = str(return_value)
|
||||
return result
|
||||
|
||||
# Create a WrapConfig
|
||||
config = WrapConfig(
|
||||
trace_name="test_trace",
|
||||
package="test_package",
|
||||
class_name="TestClass",
|
||||
method_name="test_method",
|
||||
handler=dummy_handler,
|
||||
)
|
||||
|
||||
# Create the wrapper
|
||||
wrapper = _create_wrapper(config, mock_tracer)
|
||||
|
||||
# Create a mock wrapped function
|
||||
def mock_wrapped(*args, **kwargs):
|
||||
return "success"
|
||||
|
||||
# Call the wrapper with the wrapped function
|
||||
result = wrapper(mock_wrapped, None, ("arg1", "arg2"), {"kwarg1": "value1"})
|
||||
|
||||
# Verify the result
|
||||
assert result == "success"
|
||||
|
||||
# Verify tracer was called correctly
|
||||
mock_tracer.start_as_current_span.assert_called_once_with("test_trace", kind=SpanKind.CLIENT)
|
||||
|
||||
# Verify attributes were set on the span
|
||||
assert "args" in mock_span.attributes
|
||||
assert "('arg1', 'arg2')" == mock_span.attributes["args"]
|
||||
assert "kwargs" in mock_span.attributes
|
||||
assert "{'kwarg1': 'value1'}" == mock_span.attributes["kwargs"]
|
||||
assert "return_value" in mock_span.attributes
|
||||
assert "success" == mock_span.attributes["return_value"]
|
||||
|
||||
def test_create_wrapper_error_path(self):
|
||||
"""Test wrapper created by _create_wrapper handles error path."""
|
||||
# Create a mock tracer
|
||||
mock_tracer = MagicMock()
|
||||
mock_span = MockTracingSpan()
|
||||
|
||||
# Mock start_as_current_span to return our mock span
|
||||
mock_tracer.start_as_current_span.return_value.__enter__.return_value = mock_span
|
||||
|
||||
# Create a simple attribute handler
|
||||
def dummy_handler(
|
||||
args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, return_value: Optional[Any] = None
|
||||
) -> AttributeMap:
|
||||
result = {}
|
||||
if args:
|
||||
result["args"] = str(args)
|
||||
if kwargs:
|
||||
result["kwargs"] = str(kwargs)
|
||||
if return_value is not None:
|
||||
result["return_value"] = str(return_value)
|
||||
return result
|
||||
|
||||
# Create a WrapConfig
|
||||
config = WrapConfig(
|
||||
trace_name="test_trace",
|
||||
package="test_package",
|
||||
class_name="TestClass",
|
||||
method_name="test_method",
|
||||
handler=dummy_handler,
|
||||
)
|
||||
|
||||
# Create the wrapper
|
||||
wrapper = _create_wrapper(config, mock_tracer)
|
||||
|
||||
# Create a mock wrapped function that raises an exception
|
||||
def mock_wrapped(*args, **kwargs):
|
||||
raise ValueError("Test error")
|
||||
|
||||
# Call the wrapper with the wrapped function, expecting an exception
|
||||
with pytest.raises(ValueError, match="Test error"):
|
||||
wrapper(mock_wrapped, None, ("arg1", "arg2"), {"kwarg1": "value1"})
|
||||
|
||||
# Verify tracer was called correctly
|
||||
mock_tracer.start_as_current_span.assert_called_once_with("test_trace", kind=SpanKind.CLIENT)
|
||||
|
||||
# Verify attributes were set on the span
|
||||
assert "args" in mock_span.attributes
|
||||
assert "('arg1', 'arg2')" == mock_span.attributes["args"]
|
||||
assert "kwargs" in mock_span.attributes
|
||||
assert "{'kwarg1': 'value1'}" == mock_span.attributes["kwargs"]
|
||||
|
||||
# Verify exception was recorded
|
||||
assert len(mock_span.events) == 1
|
||||
assert mock_span.events[0]["name"] == "exception"
|
||||
assert isinstance(mock_span.events[0]["exception"], ValueError)
|
||||
|
||||
def test_create_wrapper_suppressed_instrumentation(self):
|
||||
"""Test wrapper respects suppressed instrumentation context."""
|
||||
# Create a mock tracer
|
||||
mock_tracer = MagicMock()
|
||||
|
||||
# Create a simple attribute handler
|
||||
def dummy_handler(
|
||||
args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, return_value: Optional[Any] = None
|
||||
) -> AttributeMap:
|
||||
return {}
|
||||
|
||||
# Create a WrapConfig
|
||||
config = WrapConfig(
|
||||
trace_name="test_trace",
|
||||
package="test_package",
|
||||
class_name="TestClass",
|
||||
method_name="test_method",
|
||||
handler=dummy_handler,
|
||||
)
|
||||
|
||||
# Create the wrapper
|
||||
wrapper = _create_wrapper(config, mock_tracer)
|
||||
|
||||
# Create a mock wrapped function
|
||||
mock_wrapped = MagicMock(return_value="success")
|
||||
|
||||
# Mock the context_api to return True for suppressed instrumentation
|
||||
with patch("agentops.instrumentation.common.wrappers.context_api.get_value", return_value=True):
|
||||
result = wrapper(mock_wrapped, None, ("arg1", "arg2"), {"kwarg1": "value1"})
|
||||
|
||||
# Verify the result
|
||||
assert result == "success"
|
||||
|
||||
# Verify tracer was NOT called
|
||||
mock_tracer.start_as_current_span.assert_not_called()
|
||||
|
||||
# Verify wrapped function was called directly
|
||||
mock_wrapped.assert_called_once_with("arg1", "arg2", kwarg1="value1")
|
||||
|
||||
|
||||
class TestWrapUnwrap:
|
||||
"""Tests for wrap and unwrap functions."""
|
||||
|
||||
def test_wrap_function(self):
|
||||
"""Test that wrap calls wrap_function_wrapper with correct arguments."""
|
||||
|
||||
# Create a simple attribute handler
|
||||
def dummy_handler(
|
||||
args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, return_value: Optional[Any] = None
|
||||
) -> AttributeMap:
|
||||
return {}
|
||||
|
||||
# Create a WrapConfig
|
||||
config = WrapConfig(
|
||||
trace_name="test_trace",
|
||||
package="test_package",
|
||||
class_name="TestClass",
|
||||
method_name="test_method",
|
||||
handler=dummy_handler,
|
||||
)
|
||||
|
||||
# Create a mock tracer
|
||||
mock_tracer = MagicMock()
|
||||
|
||||
# Mock wrap_function_wrapper
|
||||
with patch("agentops.instrumentation.common.wrappers.wrap_function_wrapper") as mock_wrap:
|
||||
# Mock _create_wrapper to return a simple function
|
||||
with patch("agentops.instrumentation.common.wrappers._create_wrapper") as mock_create_wrapper:
|
||||
mock_create_wrapper.return_value = lambda *args: None
|
||||
|
||||
# Call wrap
|
||||
wrap(config, mock_tracer)
|
||||
|
||||
# Verify wrap_function_wrapper was called correctly
|
||||
mock_wrap.assert_called_once_with(
|
||||
"test_package", "TestClass.test_method", mock_create_wrapper.return_value
|
||||
)
|
||||
|
||||
# Verify _create_wrapper was called correctly
|
||||
mock_create_wrapper.assert_called_once_with(config, mock_tracer)
|
||||
|
||||
def test_unwrap_function(self):
|
||||
"""Test that unwrap calls _unwrap with correct arguments."""
|
||||
|
||||
# Create a simple attribute handler
|
||||
def dummy_handler(
|
||||
args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, return_value: Optional[Any] = None
|
||||
) -> AttributeMap:
|
||||
return {}
|
||||
|
||||
# Create a WrapConfig
|
||||
config = WrapConfig(
|
||||
trace_name="test_trace",
|
||||
package="test_package",
|
||||
class_name="TestClass",
|
||||
method_name="test_method",
|
||||
handler=dummy_handler,
|
||||
)
|
||||
|
||||
# Mock _unwrap
|
||||
with patch("agentops.instrumentation.common.wrappers._unwrap") as mock_unwrap:
|
||||
# Call unwrap
|
||||
unwrap(config)
|
||||
|
||||
# Verify _unwrap was called correctly
|
||||
mock_unwrap.assert_called_once_with("test_package.TestClass", "test_method")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main()
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"id": "msg_01NdttFm4EZyLDk6s4hutk9P",
|
||||
"content": [
|
||||
{
|
||||
"citations": null,
|
||||
"text": "Japan is an excellent choice for a trip! It has a rich culture, delicious food, and stunning landscapes. Here are a few steps to help you plan your trip:\n\n1. Decide when to go: Japan has four distinct seasons, each offering unique experiences. Cherry blossom season (late March to early April) and autumn foliage season (October to November) are popular times to visit.\n\n2. Choose your destinations: Some popular cities include Tokyo, Kyoto",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"model": "claude-3-opus-20240229",
|
||||
"role": "assistant",
|
||||
"stop_reason": "max_tokens",
|
||||
"stop_sequence": null,
|
||||
"type": "message",
|
||||
"usage": {
|
||||
"cache_creation_input_tokens": 0,
|
||||
"cache_read_input_tokens": 0,
|
||||
"input_tokens": 43,
|
||||
"output_tokens": 100
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"id": "msg_01BivLm8ByQh7vss4xQptv5u",
|
||||
"content": [
|
||||
{
|
||||
"citations": null,
|
||||
"text": "The capital of France is Paris.",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"model": "claude-3-opus-20240229",
|
||||
"role": "assistant",
|
||||
"stop_reason": "end_turn",
|
||||
"stop_sequence": null,
|
||||
"type": "message",
|
||||
"usage": {
|
||||
"cache_creation_input_tokens": 0,
|
||||
"cache_read_input_tokens": 0,
|
||||
"input_tokens": 14,
|
||||
"output_tokens": 10
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"messages": [
|
||||
{
|
||||
"type": "text",
|
||||
"content": "1..."
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"content": "\n2...\n3"
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"content": "...\n4..."
|
||||
},
|
||||
{
|
||||
"type": "text",
|
||||
"content": "\n5."
|
||||
}
|
||||
],
|
||||
"final_message": {
|
||||
"id": "msg_019SYRnQyEzgoDFAbodrKH1o",
|
||||
"content": [
|
||||
{
|
||||
"citations": null,
|
||||
"text": "Here is me counting slowly from 1 to 5:\n\n1...\n2...\n3...\n4...\n5.",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"model": "claude-3-opus-20240229",
|
||||
"role": "assistant",
|
||||
"stop_reason": "end_turn",
|
||||
"stop_sequence": null,
|
||||
"type": "message",
|
||||
"usage": {
|
||||
"cache_creation_input_tokens": 0,
|
||||
"cache_read_input_tokens": 0,
|
||||
"input_tokens": 18,
|
||||
"output_tokens": 31
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"id": "msg_01B6YbGDPQbBzjnz9F8uXZe3",
|
||||
"content": [
|
||||
{
|
||||
"citations": null,
|
||||
"text": "Python is a high-level, general-purpose programming language known for its simplicity, readability, and versatility. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python is widely used for web development, scientific computing, artificial intelligence, data analysis, and automation tasks. Its extensive standard library and vast ecosystem of third-party packages make it a popular choice among developers.",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"model": "claude-3-opus-20240229",
|
||||
"role": "assistant",
|
||||
"stop_reason": "end_turn",
|
||||
"stop_sequence": null,
|
||||
"type": "message",
|
||||
"usage": {
|
||||
"cache_creation_input_tokens": 0,
|
||||
"cache_read_input_tokens": 0,
|
||||
"input_tokens": 22,
|
||||
"output_tokens": 88
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import os
|
||||
import json
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
from anthropic import Anthropic
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Initialize Anthropic client
|
||||
api_key = os.getenv("ANTHROPIC_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("ANTHROPIC_API_KEY not found in environment variables")
|
||||
|
||||
client = Anthropic()
|
||||
|
||||
# Directory to save fixtures
|
||||
FIXTURES_DIR = Path(__file__).parent
|
||||
|
||||
|
||||
def save_fixture(data, filename):
|
||||
"""Save response data as a JSON fixture"""
|
||||
filepath = FIXTURES_DIR / filename
|
||||
with open(filepath, "w") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
print(f"Saved fixture: {filepath}")
|
||||
|
||||
|
||||
def generate_fixtures():
|
||||
"""Generate various Anthropic API response fixtures"""
|
||||
|
||||
# 1. Basic message completion
|
||||
message_response = client.messages.create(
|
||||
model="claude-3-opus-20240229",
|
||||
max_tokens=100,
|
||||
messages=[{"role": "user", "content": "What is the capital of France?"}],
|
||||
)
|
||||
save_fixture(message_response.model_dump(), "anthropic_message.json")
|
||||
|
||||
# 2. Message with system prompt
|
||||
system_message_response = client.messages.create(
|
||||
model="claude-3-opus-20240229",
|
||||
max_tokens=100,
|
||||
system="You are a helpful assistant that provides concise answers.",
|
||||
messages=[{"role": "user", "content": "What is Python?"}],
|
||||
)
|
||||
save_fixture(system_message_response.model_dump(), "anthropic_system_message.json")
|
||||
|
||||
# 3. Multi-turn conversation
|
||||
conversation_response = client.messages.create(
|
||||
model="claude-3-opus-20240229",
|
||||
max_tokens=100,
|
||||
messages=[
|
||||
{"role": "user", "content": "Let's plan a trip."},
|
||||
{"role": "assistant", "content": "I'd be happy to help plan a trip. Where would you like to go?"},
|
||||
{"role": "user", "content": "I'm thinking about visiting Japan."},
|
||||
],
|
||||
)
|
||||
save_fixture(conversation_response.model_dump(), "anthropic_conversation.json")
|
||||
|
||||
# 4. Streaming response
|
||||
stream_messages = []
|
||||
stream = client.messages.stream(
|
||||
model="claude-3-opus-20240229",
|
||||
max_tokens=100,
|
||||
messages=[{"role": "user", "content": "Count from 1 to 5 slowly."}],
|
||||
)
|
||||
|
||||
with stream as response:
|
||||
for text in response.text_stream:
|
||||
stream_messages.append({"type": "text", "content": text})
|
||||
|
||||
# Get the final message after streaming is complete
|
||||
final_message = client.messages.create(
|
||||
model="claude-3-opus-20240229",
|
||||
max_tokens=100,
|
||||
messages=[{"role": "user", "content": "Count from 1 to 5 slowly."}],
|
||||
)
|
||||
|
||||
save_fixture({"messages": stream_messages, "final_message": final_message.model_dump()}, "anthropic_stream.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
generate_fixtures()
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"final_output": "The capital of France is Paris.",
|
||||
"input": "What is the capital of France?",
|
||||
"raw_responses": [
|
||||
{
|
||||
"referenceable_id": "resp_67db29270db8819290bc1ef0b7e0cf530eb1154d079a2e67",
|
||||
"output": [
|
||||
{
|
||||
"id": "msg_67db29277e6c81928cdceaea2b4893f30eb1154d079a2e67",
|
||||
"content": [
|
||||
{
|
||||
"text": "The capital of France is Paris.",
|
||||
"type": "output_text",
|
||||
"annotations": []
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"status": "completed",
|
||||
"type": "message"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"input_tokens": 54,
|
||||
"output_tokens": 8,
|
||||
"requests": 1,
|
||||
"total_tokens": 62
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"final_output": "I'll help you find the current weather for New York City.",
|
||||
"input": "What's the weather like in New York City?",
|
||||
"raw_responses": [
|
||||
{
|
||||
"referenceable_id": "resp_abc123def456",
|
||||
"output": [
|
||||
{
|
||||
"id": "msg_abc123def456",
|
||||
"content": [
|
||||
{
|
||||
"text": "I'll help you find the current weather for New York City.",
|
||||
"type": "output_text",
|
||||
"annotations": []
|
||||
}
|
||||
],
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "call_xyz789",
|
||||
"type": "tool_call",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": "{\"location\":\"New York City\",\"units\":\"celsius\"}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"status": "completed",
|
||||
"type": "message"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"input_tokens": 48,
|
||||
"output_tokens": 12,
|
||||
"requests": 1,
|
||||
"total_tokens": 60
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"id": "chatcmpl-BBGezJxfNgV3vN3C4AFrmVSQIMOBv",
|
||||
"choices": [
|
||||
{
|
||||
"finish_reason": "stop",
|
||||
"index": 0,
|
||||
"logprobs": null,
|
||||
"message": {
|
||||
"content": "The capital of France is Paris.",
|
||||
"refusal": null,
|
||||
"role": "assistant",
|
||||
"annotations": [],
|
||||
"audio": null,
|
||||
"function_call": null,
|
||||
"tool_calls": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"created": 1742025349,
|
||||
"model": "gpt-4o-2024-08-06",
|
||||
"object": "chat.completion",
|
||||
"service_tier": "default",
|
||||
"system_fingerprint": "fp_f9f4fb6dbf",
|
||||
"usage": {
|
||||
"completion_tokens": 8,
|
||||
"prompt_tokens": 24,
|
||||
"total_tokens": 32,
|
||||
"completion_tokens_details": {
|
||||
"accepted_prediction_tokens": 0,
|
||||
"audio_tokens": 0,
|
||||
"reasoning_tokens": 0,
|
||||
"rejected_prediction_tokens": 0
|
||||
},
|
||||
"prompt_tokens_details": {
|
||||
"audio_tokens": 0,
|
||||
"cached_tokens": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"id": "chatcmpl-BBGezcTVVHN6Q6TyMHvTqe0IUQyvW",
|
||||
"choices": [
|
||||
{
|
||||
"finish_reason": "tool_calls",
|
||||
"index": 0,
|
||||
"logprobs": null,
|
||||
"message": {
|
||||
"content": null,
|
||||
"refusal": null,
|
||||
"role": "assistant",
|
||||
"annotations": [],
|
||||
"audio": null,
|
||||
"function_call": null,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "call_EKUsxI7LNqe2beBJlNAGNsd3",
|
||||
"function": {
|
||||
"arguments": "{\"location\":\"San Francisco, CA\",\"unit\":\"celsius\"}",
|
||||
"name": "get_weather"
|
||||
},
|
||||
"type": "function"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"created": 1742025349,
|
||||
"model": "gpt-4o-2024-08-06",
|
||||
"object": "chat.completion",
|
||||
"service_tier": "default",
|
||||
"system_fingerprint": "fp_f9f4fb6dbf",
|
||||
"usage": {
|
||||
"completion_tokens": 23,
|
||||
"prompt_tokens": 97,
|
||||
"total_tokens": 120,
|
||||
"completion_tokens_details": {
|
||||
"accepted_prediction_tokens": 0,
|
||||
"audio_tokens": 0,
|
||||
"reasoning_tokens": 0,
|
||||
"rejected_prediction_tokens": 0
|
||||
},
|
||||
"prompt_tokens_details": {
|
||||
"audio_tokens": 0,
|
||||
"cached_tokens": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"id": "resp_67d532841d1881929076b53e76e6b37a0d15a4cc30215d60",
|
||||
"created_at": 1742025348.0,
|
||||
"error": null,
|
||||
"incomplete_details": null,
|
||||
"instructions": "You are a helpful assistant.",
|
||||
"metadata": {},
|
||||
"model": "gpt-4o-2024-08-06",
|
||||
"object": "response",
|
||||
"output": [
|
||||
{
|
||||
"id": "msg_67d5328463d881929e9adeb6cd0eff6c0d15a4cc30215d60",
|
||||
"content": [
|
||||
{
|
||||
"annotations": [],
|
||||
"text": "The capital of France is Paris.",
|
||||
"type": "output_text"
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
"status": "completed",
|
||||
"type": "message"
|
||||
}
|
||||
],
|
||||
"parallel_tool_calls": true,
|
||||
"temperature": 0.7,
|
||||
"tool_choice": "auto",
|
||||
"tools": [],
|
||||
"top_p": 1.0,
|
||||
"max_output_tokens": null,
|
||||
"previous_response_id": null,
|
||||
"reasoning": {
|
||||
"effort": null,
|
||||
"generate_summary": null
|
||||
},
|
||||
"status": "completed",
|
||||
"text": {
|
||||
"format": {
|
||||
"type": "text"
|
||||
}
|
||||
},
|
||||
"truncation": "disabled",
|
||||
"usage": {
|
||||
"input_tokens": 42,
|
||||
"output_tokens": 8,
|
||||
"output_tokens_details": {
|
||||
"reasoning_tokens": 0
|
||||
},
|
||||
"total_tokens": 50,
|
||||
"input_tokens_details": {
|
||||
"cached_tokens": 0
|
||||
}
|
||||
},
|
||||
"user": null,
|
||||
"store": true
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
{
|
||||
"id": "resp_67d5328491388192bec10f88bd3100970ff2fe545808f558",
|
||||
"created_at": 1742025348.0,
|
||||
"error": null,
|
||||
"incomplete_details": null,
|
||||
"instructions": "You are a helpful assistant.",
|
||||
"metadata": {},
|
||||
"model": "gpt-4o-2024-08-06",
|
||||
"object": "response",
|
||||
"output": [
|
||||
{
|
||||
"id": "fc_67d532850424819283268d29132a29dc0ff2fe545808f558",
|
||||
"arguments": "{\"location\":\"San Francisco\",\"unit\":\"metric\"}",
|
||||
"call_id": "call_qVCWmymIoOH1B9nFUSr9r4mc",
|
||||
"name": "get_weather",
|
||||
"type": "function_call",
|
||||
"status": "completed"
|
||||
}
|
||||
],
|
||||
"parallel_tool_calls": true,
|
||||
"temperature": 0.7,
|
||||
"tool_choice": "auto",
|
||||
"tools": [
|
||||
{
|
||||
"name": "get_weather",
|
||||
"parameters": {
|
||||
"properties": {
|
||||
"location": {
|
||||
"title": "Location",
|
||||
"type": "string"
|
||||
},
|
||||
"unit": {
|
||||
"title": "Unit",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"location",
|
||||
"unit"
|
||||
],
|
||||
"title": "get_weather_args",
|
||||
"type": "object",
|
||||
"additionalProperties": false
|
||||
},
|
||||
"strict": true,
|
||||
"type": "function",
|
||||
"description": "Get the current weather in a location"
|
||||
}
|
||||
],
|
||||
"top_p": 1.0,
|
||||
"max_output_tokens": null,
|
||||
"previous_response_id": null,
|
||||
"reasoning": {
|
||||
"effort": null,
|
||||
"generate_summary": null
|
||||
},
|
||||
"status": "completed",
|
||||
"text": {
|
||||
"format": {
|
||||
"type": "text"
|
||||
}
|
||||
},
|
||||
"truncation": "disabled",
|
||||
"usage": {
|
||||
"input_tokens": 287,
|
||||
"output_tokens": 20,
|
||||
"output_tokens_details": {
|
||||
"reasoning_tokens": 0
|
||||
},
|
||||
"total_tokens": 307,
|
||||
"input_tokens_details": {
|
||||
"cached_tokens": 0
|
||||
}
|
||||
},
|
||||
"user": null,
|
||||
"store": true
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
"""
|
||||
Utility module for mocking spans and tracers in OpenTelemetry tests.
|
||||
This provides reusable mock classes for testing instrumentation.
|
||||
"""
|
||||
|
||||
import builtins
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
|
||||
class MockSpanData:
|
||||
"""Mock span data object for testing instrumentation."""
|
||||
|
||||
def __init__(self, data: Any, span_type: str = "GenerationSpanData"):
|
||||
"""Initialize mock span data.
|
||||
|
||||
Args:
|
||||
data: The data dictionary to include in the span data
|
||||
span_type: The type of span data (used for __class__.__name__)
|
||||
"""
|
||||
# Set all keys from the data dictionary as attributes
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
self.__class__.__name__ = span_type
|
||||
|
||||
|
||||
class MockSpan:
|
||||
"""Mock span object for testing instrumentation."""
|
||||
|
||||
def __init__(self, data: Any, span_type: str = "GenerationSpanData"):
|
||||
"""Initialize mock span.
|
||||
|
||||
Args:
|
||||
data: The data dictionary to include in the span data
|
||||
span_type: The type of span data
|
||||
"""
|
||||
self.trace_id = data.get("trace_id", "trace123")
|
||||
self.span_id = data.get("span_id", "span456")
|
||||
self.parent_id = data.get("parent_id", None)
|
||||
self.span_data = MockSpanData(data, span_type)
|
||||
self.error = None
|
||||
|
||||
|
||||
class MockTracingSpan:
|
||||
"""Mock span for capturing attributes."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the mock span."""
|
||||
self.attributes = {}
|
||||
self.status = None
|
||||
self.events = []
|
||||
self._is_ended = False
|
||||
|
||||
def set_attribute(self, key: str, value: Any) -> None:
|
||||
"""Set an attribute on the span, capturing it for testing."""
|
||||
self.attributes[key] = value
|
||||
|
||||
def set_status(self, status: Any) -> None:
|
||||
"""Mock setting status."""
|
||||
self.status = status
|
||||
|
||||
def record_exception(self, exception: Exception, attributes: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""Mock recording an exception."""
|
||||
self.events.append({"name": "exception", "exception": exception, "attributes": attributes or {}})
|
||||
|
||||
def end(self) -> None:
|
||||
"""End the span."""
|
||||
self._is_ended = True
|
||||
|
||||
def __enter__(self) -> "MockTracingSpan":
|
||||
"""Context manager entry."""
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
||||
"""Context manager exit."""
|
||||
self._is_ended = True
|
||||
|
||||
|
||||
class MockTracer:
|
||||
"""Mock tracer that captures attributes set on spans."""
|
||||
|
||||
def __init__(self, captured_attributes: Dict[str, Any]):
|
||||
"""Initialize the mock tracer.
|
||||
|
||||
Args:
|
||||
captured_attributes: Dictionary to store captured attributes
|
||||
"""
|
||||
self.captured_attributes = captured_attributes
|
||||
|
||||
def start_as_current_span(self, name: str, kind: Any = None, attributes: Optional[Dict[str, Any]] = None):
|
||||
"""Start a new span and capture attributes."""
|
||||
span = CapturedAttributeSpan(self.captured_attributes)
|
||||
# Set any provided attributes
|
||||
if attributes:
|
||||
for key, val in attributes.items():
|
||||
span.set_attribute(key, val)
|
||||
return span
|
||||
|
||||
def start_span(self, name: str, kind: Any = None, attributes: Optional[Dict[str, Any]] = None):
|
||||
"""Start a new span without making it the current span."""
|
||||
span = CapturedAttributeSpan(self.captured_attributes)
|
||||
# Set any provided attributes
|
||||
if attributes:
|
||||
for key, val in attributes.items():
|
||||
span.set_attribute(key, val)
|
||||
return span
|
||||
|
||||
|
||||
class CapturedAttributeSpan(MockTracingSpan):
|
||||
"""Mock span that captures attributes in a shared dictionary."""
|
||||
|
||||
def __init__(self, captured_attributes: Dict[str, Any]):
|
||||
"""Initialize with a shared dictionary for capturing attributes.
|
||||
|
||||
Args:
|
||||
captured_attributes: Dictionary to store captured attributes
|
||||
"""
|
||||
super().__init__()
|
||||
self.captured_attributes = captured_attributes
|
||||
|
||||
def set_attribute(self, key: str, value: Any) -> None:
|
||||
"""Set an attribute, capturing it in the shared dictionary."""
|
||||
self.captured_attributes[key] = value
|
||||
self.attributes[key] = value
|
||||
|
||||
|
||||
def setup_mock_tracer(captured_attributes: Dict[str, Any]):
|
||||
"""Set up a mock tracer by monkey patching OpenTelemetry.
|
||||
|
||||
Args:
|
||||
captured_attributes: Dictionary to store captured attributes
|
||||
|
||||
Returns:
|
||||
The original import function for cleanup
|
||||
"""
|
||||
original_import = builtins.__import__
|
||||
|
||||
def mocked_import(name, *args, **kwargs):
|
||||
module = original_import(name, *args, **kwargs)
|
||||
if name == "opentelemetry.trace":
|
||||
# Monkey patch the get_tracer function
|
||||
module.get_tracer = lambda *args, **kwargs: MockTracer(captured_attributes)
|
||||
|
||||
# Create a mock Status class
|
||||
if not hasattr(module, "Status") or not isinstance(module.Status, type):
|
||||
mock_status = MagicMock()
|
||||
mock_status.return_value = MagicMock()
|
||||
module.Status = mock_status
|
||||
|
||||
# Create a mock StatusCode enum
|
||||
if not hasattr(module, "StatusCode"):
|
||||
|
||||
class MockStatusCode:
|
||||
OK = "OK"
|
||||
ERROR = "ERROR"
|
||||
UNSET = "UNSET"
|
||||
|
||||
module.StatusCode = MockStatusCode
|
||||
return module
|
||||
|
||||
builtins.__import__ = mocked_import
|
||||
return original_import
|
||||
|
||||
|
||||
def process_with_instrumentor(mock_span, exporter_class, captured_attributes: Dict[str, Any]):
|
||||
"""Process a mock span with an instrumentor exporter.
|
||||
|
||||
Args:
|
||||
mock_span: The mock span to process
|
||||
exporter_class: The exporter class to use
|
||||
captured_attributes: Dictionary to store captured attributes
|
||||
|
||||
Returns:
|
||||
The captured attributes
|
||||
"""
|
||||
# Add core trace/span attributes from the mock_span directly to the captured_attributes
|
||||
# This ensures that both semantic convention attributes and direct access attributes work
|
||||
from agentops.semconv import CoreAttributes, AgentAttributes, WorkflowAttributes
|
||||
|
||||
# Add consistent formats for tools if it's an AgentSpanData
|
||||
if hasattr(mock_span.span_data, "tools"):
|
||||
# If tools is a list of dictionaries, convert it to a list of strings
|
||||
tools = mock_span.span_data.tools
|
||||
if isinstance(tools, list) and tools and isinstance(tools[0], dict):
|
||||
tools_str = [tool.get("name", str(tool)) for tool in tools]
|
||||
mock_span.span_data.tools = tools_str
|
||||
|
||||
# Set base attributes
|
||||
core_attribute_mapping = {
|
||||
CoreAttributes.TRACE_ID: mock_span.trace_id,
|
||||
CoreAttributes.SPAN_ID: mock_span.span_id,
|
||||
}
|
||||
|
||||
if mock_span.parent_id:
|
||||
core_attribute_mapping[CoreAttributes.PARENT_ID] = mock_span.parent_id
|
||||
|
||||
for target_attr, value in core_attribute_mapping.items():
|
||||
if value is not None:
|
||||
captured_attributes[target_attr] = value
|
||||
|
||||
# Set agent attributes based on span type
|
||||
span_type = mock_span.span_data.__class__.__name__
|
||||
if span_type == "AgentSpanData":
|
||||
if hasattr(mock_span.span_data, "name"):
|
||||
captured_attributes[AgentAttributes.AGENT_NAME] = mock_span.span_data.name
|
||||
if hasattr(mock_span.span_data, "input"):
|
||||
captured_attributes[WorkflowAttributes.WORKFLOW_INPUT] = mock_span.span_data.input
|
||||
if hasattr(mock_span.span_data, "output"):
|
||||
captured_attributes[WorkflowAttributes.WORKFLOW_FINAL_OUTPUT] = mock_span.span_data.output
|
||||
if hasattr(mock_span.span_data, "tools"):
|
||||
captured_attributes[AgentAttributes.AGENT_TOOLS] = ",".join(mock_span.span_data.tools)
|
||||
if hasattr(mock_span.span_data, "target_agent"):
|
||||
captured_attributes[AgentAttributes.TO_AGENT] = mock_span.span_data.target_agent
|
||||
|
||||
elif span_type == "FunctionSpanData":
|
||||
if hasattr(mock_span.span_data, "name"):
|
||||
captured_attributes[AgentAttributes.AGENT_NAME] = mock_span.span_data.name
|
||||
if hasattr(mock_span.span_data, "input"):
|
||||
captured_attributes[WorkflowAttributes.WORKFLOW_INPUT] = json.dumps(mock_span.span_data.input)
|
||||
if hasattr(mock_span.span_data, "output"):
|
||||
captured_attributes[WorkflowAttributes.WORKFLOW_FINAL_OUTPUT] = json.dumps(mock_span.span_data.output)
|
||||
if hasattr(mock_span.span_data, "from_agent"):
|
||||
captured_attributes[AgentAttributes.FROM_AGENT] = mock_span.span_data.from_agent
|
||||
|
||||
# Also handle from_agent in AgentSpanData to support the hierarchy test
|
||||
if span_type == "AgentSpanData" and hasattr(mock_span.span_data, "from_agent"):
|
||||
captured_attributes[AgentAttributes.FROM_AGENT] = mock_span.span_data.from_agent
|
||||
|
||||
# Monkey patch the get_tracer function to return our MockTracer
|
||||
with patch("opentelemetry.trace.get_tracer", return_value=MockTracer(captured_attributes)):
|
||||
with patch("opentelemetry.trace.SpanKind"):
|
||||
# Create a mocked Status class
|
||||
with patch("opentelemetry.trace.Status"):
|
||||
with patch("opentelemetry.trace.StatusCode"):
|
||||
# Create a direct instance of the exporter with mocked tracer provider
|
||||
mock_tracer_provider = MagicMock()
|
||||
mock_tracer = MockTracer(captured_attributes)
|
||||
mock_tracer_provider.get_tracer.return_value = mock_tracer
|
||||
|
||||
exporter = exporter_class(tracer_provider=mock_tracer_provider)
|
||||
|
||||
# Call the exporter's export_span method
|
||||
try:
|
||||
exporter.export_span(mock_span)
|
||||
|
||||
# If this span has error attribute, simulate error handling
|
||||
if hasattr(mock_span, "error") and mock_span.error:
|
||||
# Mark as an end event with error
|
||||
mock_span.status = "ERROR"
|
||||
exporter.export_span(mock_span)
|
||||
except Exception as e:
|
||||
print(f"Error during export_span: {e}")
|
||||
|
||||
return captured_attributes
|
||||
@@ -0,0 +1,2 @@
|
||||
# OpenAI Agents Tests
|
||||
# This package contains tests for OpenAI Agents SDK instrumentation
|
||||
@@ -0,0 +1,508 @@
|
||||
"""
|
||||
Tests for OpenAI Agents SDK Instrumentation
|
||||
|
||||
This module contains tests for properly handling and serializing data from the OpenAI Agents SDK.
|
||||
It verifies that our instrumentation correctly captures and instruments agent runs, tool usage,
|
||||
and other operations specific to the OpenAI Agents SDK.
|
||||
|
||||
NOTE: All tests must define expected_attributes dictionaries to validate response data in spans.
|
||||
This helps ensure consistent attribute structure for downstream OpenTelemetry consumers.
|
||||
|
||||
The Agents SDK has its own unique structure with:
|
||||
- Agent runs with specific attributes and properties
|
||||
- Tool calls and agent handoffs
|
||||
- Raw responses that may contain either ChatCompletion or Response API objects
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
from opentelemetry.trace import StatusCode
|
||||
|
||||
from agentops.instrumentation.agentic.openai_agents.instrumentor import OpenAIAgentsInstrumentor
|
||||
from agentops.instrumentation.agentic.openai_agents.exporter import OpenAIAgentsExporter
|
||||
from agentops.instrumentation.agentic.openai_agents.processor import OpenAIAgentsProcessor
|
||||
from agentops.semconv import (
|
||||
SpanAttributes,
|
||||
MessageAttributes,
|
||||
CoreAttributes,
|
||||
AgentAttributes,
|
||||
WorkflowAttributes,
|
||||
)
|
||||
from tests.unit.instrumentation.mock_span import (
|
||||
MockSpan,
|
||||
process_with_instrumentor,
|
||||
)
|
||||
|
||||
|
||||
# Utility function to load fixtures
|
||||
def load_fixture(fixture_name):
|
||||
"""Load a test fixture from the fixtures directory"""
|
||||
fixture_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "fixtures", fixture_name)
|
||||
with open(fixture_path, "r") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
# Load all test fixtures
|
||||
# Standard OpenAI API formats
|
||||
OPENAI_CHAT_COMPLETION = load_fixture(
|
||||
"openai_chat_completion.json"
|
||||
) # Standard ChatCompletion format with choices array
|
||||
OPENAI_CHAT_TOOL_CALLS = load_fixture("openai_chat_tool_calls.json") # ChatCompletion with tool calls
|
||||
OPENAI_RESPONSE = load_fixture("openai_response.json") # Response API format (newer API format) with output array
|
||||
OPENAI_RESPONSE_TOOL_CALLS = load_fixture("openai_response_tool_calls.json") # Response API with tool calls
|
||||
|
||||
# OpenAI Agents SDK formats
|
||||
AGENTS_RESPONSE = load_fixture("openai_agents_response.json") # Agents SDK wrapper around Response API - text only
|
||||
AGENTS_TOOL_RESPONSE = load_fixture("openai_agents_tool_response.json") # Agents SDK wrapper with tool calls
|
||||
|
||||
|
||||
class TestAgentsSdkInstrumentation:
|
||||
"""Tests for OpenAI Agents SDK instrumentation using real fixtures"""
|
||||
|
||||
@pytest.fixture
|
||||
def instrumentation(self):
|
||||
"""Set up instrumentation for tests
|
||||
|
||||
This fixture mocks the OpenAI Agents SDK and sets up the instrumentor
|
||||
to capture spans and traces. It returns a dictionary of objects needed
|
||||
for testing.
|
||||
"""
|
||||
# Mock the agents module
|
||||
with patch("agents.set_trace_processors") as mock_set_trace_processors:
|
||||
with patch("agents.tracing.processors.default_processor", return_value=MagicMock()):
|
||||
# Create a real instrumentation setup for testing
|
||||
mock_tracer_provider = MagicMock()
|
||||
instrumentor = OpenAIAgentsInstrumentor()
|
||||
instrumentor._instrument(tracer_provider=mock_tracer_provider)
|
||||
|
||||
# Extract the processor and exporter for direct testing
|
||||
processor = instrumentor._processor
|
||||
exporter = instrumentor._exporter
|
||||
|
||||
# Clean up after the test
|
||||
yield {
|
||||
"instrumentor": instrumentor,
|
||||
"processor": processor,
|
||||
"exporter": exporter,
|
||||
"tracer_provider": mock_tracer_provider,
|
||||
"mock_set_trace_processors": mock_set_trace_processors,
|
||||
}
|
||||
|
||||
instrumentor._uninstrument()
|
||||
|
||||
def test_response_api_span_serialization(self, instrumentation):
|
||||
"""
|
||||
Test serialization of Generation spans from Agents SDK using Response API with real fixture data.
|
||||
|
||||
Verifies that:
|
||||
- The Response API format is correctly parsed
|
||||
- All semantic conventions are applied properly
|
||||
- Token usage metrics are extracted correctly
|
||||
- Message content is properly formatted with appropriate attributes
|
||||
"""
|
||||
# Modify the mock_span_data to create proper response extraction logic
|
||||
|
||||
# Mock the attribute extraction functions to return the expected message attributes
|
||||
with patch(
|
||||
"agentops.instrumentation.agentic.openai_agents.attributes.completion.get_raw_response_attributes"
|
||||
) as mock_response_attrs:
|
||||
# Set up the mock to return attributes we want to verify
|
||||
mock_response_attrs.return_value = {
|
||||
MessageAttributes.COMPLETION_CONTENT.format(i=0): "The capital of France is Paris.",
|
||||
MessageAttributes.COMPLETION_ROLE.format(i=0): "assistant",
|
||||
SpanAttributes.LLM_SYSTEM: "openai",
|
||||
SpanAttributes.LLM_USAGE_PROMPT_TOKENS: 54,
|
||||
SpanAttributes.LLM_USAGE_COMPLETION_TOKENS: 8,
|
||||
SpanAttributes.LLM_USAGE_TOTAL_TOKENS: 62,
|
||||
}
|
||||
|
||||
# Create a mock span data with the Agents SDK response format
|
||||
mock_gen_data = {
|
||||
"trace_id": "trace123",
|
||||
"span_id": "span456",
|
||||
"parent_id": "parent789",
|
||||
"model": "gpt-4o",
|
||||
"input": "What is the capital of France?",
|
||||
"output": AGENTS_RESPONSE,
|
||||
"from_agent": "test_agent",
|
||||
"model_config": {"temperature": 0.7, "top_p": 1.0},
|
||||
}
|
||||
|
||||
# Create a mock span
|
||||
mock_span = MockSpan(mock_gen_data, "GenerationSpanData")
|
||||
|
||||
# Create a dictionary to capture the attributes that get set on spans
|
||||
captured_attributes = {}
|
||||
|
||||
# Process the mock span with the exporter
|
||||
with patch(
|
||||
"agentops.instrumentation.agentic.openai_agents.attributes.completion.get_generation_output_attributes"
|
||||
) as mock_gen_output:
|
||||
mock_gen_output.return_value = mock_response_attrs.return_value
|
||||
process_with_instrumentor(mock_span, OpenAIAgentsExporter, captured_attributes)
|
||||
|
||||
# Add expected model attributes
|
||||
captured_attributes[SpanAttributes.LLM_REQUEST_MODEL] = "gpt-4o"
|
||||
captured_attributes[SpanAttributes.LLM_RESPONSE_MODEL] = "gpt-4o"
|
||||
|
||||
# Verify attributes were set correctly
|
||||
assert MessageAttributes.COMPLETION_CONTENT.format(i=0) in captured_attributes
|
||||
assert (
|
||||
captured_attributes[MessageAttributes.COMPLETION_CONTENT.format(i=0)]
|
||||
== "The capital of France is Paris."
|
||||
)
|
||||
assert captured_attributes[MessageAttributes.COMPLETION_ROLE.format(i=0)] == "assistant"
|
||||
|
||||
# Verify token usage attributes
|
||||
assert SpanAttributes.LLM_USAGE_PROMPT_TOKENS in captured_attributes
|
||||
assert captured_attributes[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 54
|
||||
assert captured_attributes[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 8
|
||||
assert captured_attributes[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 62
|
||||
|
||||
# Verify model information
|
||||
assert SpanAttributes.LLM_REQUEST_MODEL in captured_attributes
|
||||
assert captured_attributes[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4o"
|
||||
|
||||
def test_tool_calls_span_serialization(self, instrumentation):
|
||||
"""
|
||||
Test serialization of Generation spans with tool calls from Agents SDK using real fixture data.
|
||||
|
||||
Verifies that:
|
||||
- Tool call information is correctly extracted and serialized
|
||||
- Tool call ID, name, and arguments are captured with proper semantic conventions
|
||||
- Appropriate metadata for the model and response is maintained
|
||||
"""
|
||||
# Mock the attribute extraction functions to return the expected message attributes
|
||||
with patch(
|
||||
"agentops.instrumentation.agentic.openai_agents.attributes.completion.get_raw_response_attributes"
|
||||
) as mock_response_attrs:
|
||||
# Set up the mock to return attributes we want to verify
|
||||
mock_response_attrs.return_value = {
|
||||
MessageAttributes.COMPLETION_CONTENT.format(
|
||||
i=0
|
||||
): "I'll help you find the current weather for New York City.",
|
||||
MessageAttributes.COMPLETION_ROLE.format(i=0): "assistant",
|
||||
MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=0, j=0): "call_xyz789",
|
||||
MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0): "get_weather",
|
||||
MessageAttributes.COMPLETION_TOOL_CALL_ARGUMENTS.format(
|
||||
i=0, j=0
|
||||
): '{"location":"New York City","units":"celsius"}',
|
||||
SpanAttributes.LLM_SYSTEM: "openai",
|
||||
SpanAttributes.LLM_USAGE_PROMPT_TOKENS: 48,
|
||||
SpanAttributes.LLM_USAGE_COMPLETION_TOKENS: 12,
|
||||
SpanAttributes.LLM_USAGE_TOTAL_TOKENS: 60,
|
||||
}
|
||||
|
||||
# Create a mock span data with the Agents SDK tool response format
|
||||
mock_gen_data = {
|
||||
"trace_id": "trace123",
|
||||
"span_id": "span456",
|
||||
"parent_id": "parent789",
|
||||
"model": "gpt-4o",
|
||||
"input": "What's the weather like in New York City?",
|
||||
"output": AGENTS_TOOL_RESPONSE,
|
||||
"from_agent": "test_agent",
|
||||
"model_config": {"temperature": 0.8, "top_p": 1.0},
|
||||
}
|
||||
|
||||
# Create a mock span
|
||||
mock_span = MockSpan(mock_gen_data, "GenerationSpanData")
|
||||
|
||||
# Create a dictionary to capture the attributes that get set on spans
|
||||
captured_attributes = {}
|
||||
|
||||
# Process the mock span with the exporter
|
||||
with patch(
|
||||
"agentops.instrumentation.agentic.openai_agents.attributes.completion.get_generation_output_attributes"
|
||||
) as mock_gen_output:
|
||||
mock_gen_output.return_value = mock_response_attrs.return_value
|
||||
process_with_instrumentor(mock_span, OpenAIAgentsExporter, captured_attributes)
|
||||
|
||||
# Add model attributes which would normally be handled by the exporter
|
||||
captured_attributes[SpanAttributes.LLM_REQUEST_MODEL] = "gpt-4o"
|
||||
captured_attributes[SpanAttributes.LLM_RESPONSE_MODEL] = "gpt-4o"
|
||||
|
||||
# Verify tool call attributes were set correctly
|
||||
assert MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0) in captured_attributes
|
||||
assert captured_attributes[MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0)] == "get_weather"
|
||||
assert MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=0, j=0) in captured_attributes
|
||||
assert captured_attributes[MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=0, j=0)] == "call_xyz789"
|
||||
assert MessageAttributes.COMPLETION_TOOL_CALL_ARGUMENTS.format(i=0, j=0) in captured_attributes
|
||||
assert (
|
||||
'{"location":"New York City","units":"celsius"}'
|
||||
in captured_attributes[MessageAttributes.COMPLETION_TOOL_CALL_ARGUMENTS.format(i=0, j=0)]
|
||||
)
|
||||
|
||||
# Verify the text content is also captured
|
||||
assert MessageAttributes.COMPLETION_CONTENT.format(i=0) in captured_attributes
|
||||
assert (
|
||||
captured_attributes[MessageAttributes.COMPLETION_CONTENT.format(i=0)]
|
||||
== "I'll help you find the current weather for New York City."
|
||||
)
|
||||
|
||||
# Verify token usage attributes
|
||||
assert SpanAttributes.LLM_USAGE_PROMPT_TOKENS in captured_attributes
|
||||
assert captured_attributes[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 48
|
||||
assert captured_attributes[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 12
|
||||
assert captured_attributes[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 60
|
||||
|
||||
def test_span_hierarchy_and_attributes(self, instrumentation):
|
||||
"""
|
||||
Test that child nodes (function spans and generation spans) inherit necessary attributes.
|
||||
|
||||
Ensures:
|
||||
- Parent-child relationships are maintained in the span context
|
||||
- Essential attributes are propagated to child spans
|
||||
- Input/output content is preserved in the span hierarchy
|
||||
- Semantic conventions are consistently applied across the hierarchy
|
||||
"""
|
||||
# Create a parent span
|
||||
parent_span_data = {
|
||||
"trace_id": "trace123",
|
||||
"span_id": "parent_span_id",
|
||||
"parent_id": None,
|
||||
"name": "parent_agent",
|
||||
"input": "parent input",
|
||||
"output": "parent output",
|
||||
"tools": ["tool1", "tool2"],
|
||||
}
|
||||
parent_span = MockSpan(parent_span_data, "AgentSpanData")
|
||||
|
||||
# Create a child span with the parent ID
|
||||
child_span_data = {
|
||||
"trace_id": "trace123",
|
||||
"span_id": "child_span_id",
|
||||
"parent_id": "parent_span_id",
|
||||
"name": "child_agent",
|
||||
"input": "child input",
|
||||
"output": "child output",
|
||||
"from_agent": "parent_agent",
|
||||
}
|
||||
child_span = MockSpan(child_span_data, "AgentSpanData")
|
||||
|
||||
# Create dictionaries to capture the attributes that get set on spans
|
||||
parent_captured_attributes = {}
|
||||
child_captured_attributes = {}
|
||||
|
||||
# Process the parent and child spans
|
||||
process_with_instrumentor(parent_span, OpenAIAgentsExporter, parent_captured_attributes)
|
||||
process_with_instrumentor(child_span, OpenAIAgentsExporter, child_captured_attributes)
|
||||
|
||||
# Verify parent span attributes
|
||||
assert parent_captured_attributes[AgentAttributes.AGENT_NAME] == "parent_agent"
|
||||
assert parent_captured_attributes[WorkflowAttributes.WORKFLOW_INPUT] == "parent input"
|
||||
assert parent_captured_attributes[WorkflowAttributes.WORKFLOW_FINAL_OUTPUT] == "parent output"
|
||||
assert parent_captured_attributes[AgentAttributes.AGENT_TOOLS] == '["tool1", "tool2"]' # JSON encoded is fine.
|
||||
|
||||
# Verify child span attributes
|
||||
assert child_captured_attributes[AgentAttributes.AGENT_NAME] == "child_agent"
|
||||
assert child_captured_attributes[WorkflowAttributes.WORKFLOW_INPUT] == "child input"
|
||||
assert child_captured_attributes[WorkflowAttributes.WORKFLOW_FINAL_OUTPUT] == "child output"
|
||||
assert child_captured_attributes[AgentAttributes.FROM_AGENT] == "parent_agent"
|
||||
|
||||
# Verify parent-child relationship
|
||||
assert child_captured_attributes[CoreAttributes.PARENT_ID] == "parent_span_id"
|
||||
assert child_captured_attributes[CoreAttributes.TRACE_ID] == parent_captured_attributes[CoreAttributes.TRACE_ID]
|
||||
|
||||
def test_process_agent_span_fixed(self, instrumentation):
|
||||
"""
|
||||
Test processing of Agent spans by direct span creation and attribute verification.
|
||||
|
||||
Focuses on:
|
||||
- Core attribute propagation (trace ID, span ID, parent ID)
|
||||
- Agent-specific attributes (name, tools, source/target agents)
|
||||
- Input/output content preservation
|
||||
- Message format compliance
|
||||
"""
|
||||
# Create a mock agent span data
|
||||
mock_agent_data = {
|
||||
"trace_id": "trace123",
|
||||
"span_id": "span456",
|
||||
"parent_id": "parent789",
|
||||
"name": "test_agent",
|
||||
"input": "What can you help me with?",
|
||||
"output": "I can help you with finding information, answering questions, and more.",
|
||||
"tools": ["search", "calculator"], # Use simple strings instead of dictionaries
|
||||
"target_agent": "assistant",
|
||||
}
|
||||
|
||||
# Create a mock span
|
||||
mock_span = MockSpan(mock_agent_data, "AgentSpanData")
|
||||
|
||||
# Create a dictionary to capture the attributes that get set on spans
|
||||
captured_attributes = {}
|
||||
|
||||
# Process the mock span with the exporter
|
||||
process_with_instrumentor(mock_span, OpenAIAgentsExporter, captured_attributes)
|
||||
|
||||
# Verify core attributes
|
||||
assert captured_attributes[CoreAttributes.TRACE_ID] == "trace123"
|
||||
assert captured_attributes[CoreAttributes.SPAN_ID] == "span456"
|
||||
assert captured_attributes[CoreAttributes.PARENT_ID] == "parent789"
|
||||
|
||||
# Verify agent-specific attributes
|
||||
assert captured_attributes[AgentAttributes.AGENT_NAME] == "test_agent"
|
||||
assert captured_attributes[WorkflowAttributes.WORKFLOW_INPUT] == "What can you help me with?"
|
||||
assert (
|
||||
captured_attributes[WorkflowAttributes.WORKFLOW_FINAL_OUTPUT]
|
||||
== "I can help you with finding information, answering questions, and more."
|
||||
)
|
||||
assert "search" in captured_attributes[AgentAttributes.AGENT_TOOLS]
|
||||
assert "calculator" in captured_attributes[AgentAttributes.AGENT_TOOLS]
|
||||
assert captured_attributes[AgentAttributes.TO_AGENT] == "assistant"
|
||||
|
||||
# Verify agent role - agent spans don't explicitly store the type
|
||||
# but we can verify the role or other agent-specific attributes are present
|
||||
assert AgentAttributes.AGENT_NAME in captured_attributes
|
||||
assert AgentAttributes.AGENT_TOOLS in captured_attributes
|
||||
|
||||
def test_process_function_span(self, instrumentation):
|
||||
"""
|
||||
Test processing of Function spans in the exporter.
|
||||
|
||||
Ensures that:
|
||||
- Function calls maintain their relationship to parent spans
|
||||
- Function inputs and outputs are correctly serialized
|
||||
- Tool usage information is preserved
|
||||
- Function metadata complies with semantic conventions
|
||||
"""
|
||||
# Create a mock function span data
|
||||
mock_function_data = {
|
||||
"trace_id": "trace123",
|
||||
"span_id": "span456",
|
||||
"parent_id": "parent789",
|
||||
"name": "calculate_distance",
|
||||
"input": {"from": "New York", "to": "Boston"},
|
||||
"output": {"distance": 215, "unit": "miles"},
|
||||
"from_agent": "navigator",
|
||||
}
|
||||
|
||||
# Create a mock span
|
||||
mock_span = MockSpan(mock_function_data, "FunctionSpanData")
|
||||
|
||||
# Create a dictionary to capture the attributes that get set on spans
|
||||
captured_attributes = {}
|
||||
|
||||
# Process the mock span with the exporter
|
||||
process_with_instrumentor(mock_span, OpenAIAgentsExporter, captured_attributes)
|
||||
|
||||
# Verify core attributes
|
||||
assert captured_attributes[CoreAttributes.TRACE_ID] == "trace123"
|
||||
assert captured_attributes[CoreAttributes.SPAN_ID] == "span456"
|
||||
assert captured_attributes[CoreAttributes.PARENT_ID] == "parent789"
|
||||
|
||||
# Verify function-specific attributes
|
||||
assert captured_attributes[AgentAttributes.AGENT_NAME] == "calculate_distance"
|
||||
assert captured_attributes[WorkflowAttributes.WORKFLOW_INPUT] is not None
|
||||
assert "New York" in captured_attributes[WorkflowAttributes.WORKFLOW_INPUT]
|
||||
assert "Boston" in captured_attributes[WorkflowAttributes.WORKFLOW_INPUT]
|
||||
assert captured_attributes[WorkflowAttributes.WORKFLOW_FINAL_OUTPUT] is not None
|
||||
assert "215" in captured_attributes[WorkflowAttributes.WORKFLOW_FINAL_OUTPUT]
|
||||
assert "miles" in captured_attributes[WorkflowAttributes.WORKFLOW_FINAL_OUTPUT]
|
||||
assert captured_attributes[AgentAttributes.FROM_AGENT] == "navigator"
|
||||
|
||||
# Verify function attributes - don't test for a specific type field
|
||||
# Focus on verifying essential function-specific attributes instead
|
||||
assert AgentAttributes.AGENT_NAME in captured_attributes
|
||||
assert AgentAttributes.FROM_AGENT in captured_attributes
|
||||
|
||||
def test_error_handling_in_spans(self, instrumentation):
|
||||
"""
|
||||
Test handling of spans with errors.
|
||||
|
||||
Validates:
|
||||
- Various error formats (dictionaries, strings, exception objects) are handled correctly
|
||||
- Error information is properly captured in span attributes
|
||||
- OpenTelemetry status codes are correctly set
|
||||
- Exception recording functions properly
|
||||
"""
|
||||
mock_exporter = MagicMock()
|
||||
mock_exporter.export_span = MagicMock()
|
||||
|
||||
# Create a mock processor
|
||||
processor = OpenAIAgentsProcessor(exporter=mock_exporter)
|
||||
|
||||
# Create a mock span with error
|
||||
mock_span = MagicMock()
|
||||
mock_span.error = "Test error message"
|
||||
|
||||
# Test error handling on span end
|
||||
with patch("opentelemetry.trace.StatusCode") as mock_status_code:
|
||||
# Configure StatusCode enum to have properties
|
||||
mock_status_code.OK = StatusCode.OK
|
||||
mock_status_code.ERROR = StatusCode.ERROR
|
||||
|
||||
# Call processor with span
|
||||
processor.on_span_end(mock_span)
|
||||
|
||||
# Verify span was passed to exporter
|
||||
mock_exporter.export_span.assert_called_once_with(mock_span)
|
||||
# Verify status was set on span
|
||||
assert hasattr(mock_span, "status")
|
||||
assert mock_span.status == StatusCode.OK.name
|
||||
|
||||
def test_instrumentor_integration(self, instrumentation):
|
||||
"""
|
||||
Test the integration of the OpenAIAgentsProcessor with the Agents SDK tracing system.
|
||||
|
||||
Verifies:
|
||||
- Instrumentor correctly hooks into SDK trace events
|
||||
- Span lifecycle methods function properly
|
||||
- Trace lifecycle methods function properly
|
||||
- Correct span exporting at appropriate lifecycle points
|
||||
"""
|
||||
# Extract the instrumentation components
|
||||
instrumentor = instrumentation["instrumentor"]
|
||||
processor = instrumentation["processor"]
|
||||
exporter = instrumentation["exporter"]
|
||||
mock_set_trace_processors = instrumentation["mock_set_trace_processors"]
|
||||
|
||||
# Verify that the instrumentor registered the processor with Agents SDK
|
||||
mock_set_trace_processors.assert_called_once()
|
||||
processors_arg = mock_set_trace_processors.call_args[0][0]
|
||||
assert len(processors_arg) == 1
|
||||
assert processors_arg[0] == processor
|
||||
|
||||
# Create mock span and trace objects
|
||||
mock_span = MagicMock()
|
||||
mock_span.trace_id = "trace123"
|
||||
mock_span.span_id = "span456"
|
||||
mock_trace = MagicMock()
|
||||
mock_trace.trace_id = "trace123"
|
||||
|
||||
# Mock the exporter's export_span and export_trace methods
|
||||
with patch.object(exporter, "export_span") as mock_export_span:
|
||||
with patch.object(exporter, "export_trace") as mock_export_trace:
|
||||
# Test span lifecycle
|
||||
processor.on_span_start(mock_span)
|
||||
mock_export_span.assert_called_once_with(mock_span)
|
||||
|
||||
mock_export_span.reset_mock()
|
||||
|
||||
# Set status on the span to indicate it's an end event
|
||||
mock_span.status = StatusCode.OK.name
|
||||
processor.on_span_end(mock_span)
|
||||
mock_export_span.assert_called_once_with(mock_span)
|
||||
|
||||
# Test trace lifecycle
|
||||
mock_export_trace.reset_mock()
|
||||
|
||||
processor.on_trace_start(mock_trace)
|
||||
mock_export_trace.assert_called_once_with(mock_trace)
|
||||
|
||||
mock_export_trace.reset_mock()
|
||||
|
||||
# Set status on the trace to indicate it's an end event
|
||||
mock_trace.status = StatusCode.OK.name
|
||||
processor.on_trace_end(mock_trace)
|
||||
mock_export_trace.assert_called_once_with(mock_trace)
|
||||
|
||||
# Verify cleanup on uninstrument
|
||||
with patch.object(exporter, "cleanup", MagicMock()):
|
||||
instrumentor._uninstrument()
|
||||
# Verify the default processor is restored
|
||||
mock_set_trace_processors.assert_called()
|
||||
assert instrumentor._processor is None
|
||||
assert instrumentor._exporter is None
|
||||
@@ -0,0 +1,589 @@
|
||||
"""
|
||||
Tests for OpenAI Agents SDK Attributes
|
||||
|
||||
This module contains tests for the attribute definitions and semantic conventions
|
||||
used in OpenAI Agents SDK instrumentation. It verifies that attribute extraction,
|
||||
handling, and transformations work correctly across different API formats and data structures.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from agentops.instrumentation.agentic.openai_agents import LIBRARY_NAME
|
||||
|
||||
# Import common attribute functions
|
||||
from agentops.instrumentation.agentic.openai_agents.attributes.common import (
|
||||
get_agent_span_attributes,
|
||||
get_function_span_attributes,
|
||||
get_generation_span_attributes,
|
||||
get_handoff_span_attributes,
|
||||
get_response_span_attributes,
|
||||
get_span_attributes,
|
||||
get_common_instrumentation_attributes,
|
||||
)
|
||||
|
||||
# Import model-related functions
|
||||
from agentops.instrumentation.agentic.openai_agents.attributes.model import (
|
||||
get_model_attributes,
|
||||
)
|
||||
|
||||
# Import completion processing functions
|
||||
from agentops.instrumentation.agentic.openai_agents.attributes.completion import (
|
||||
get_chat_completions_attributes,
|
||||
get_raw_response_attributes,
|
||||
)
|
||||
|
||||
# Import token processing functions
|
||||
from agentops.instrumentation.agentic.openai_agents.attributes.tokens import (
|
||||
process_token_usage,
|
||||
extract_nested_usage,
|
||||
get_token_metric_attributes,
|
||||
)
|
||||
|
||||
from agentops.semconv import (
|
||||
SpanAttributes,
|
||||
MessageAttributes,
|
||||
AgentAttributes,
|
||||
InstrumentationAttributes,
|
||||
)
|
||||
|
||||
|
||||
# Helper function to load fixtures
|
||||
def load_fixture(fixture_name):
|
||||
"""Load a test fixture from the fixtures directory"""
|
||||
fixture_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "fixtures", fixture_name)
|
||||
with open(fixture_path, "r") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
# Load test fixtures
|
||||
|
||||
# OpenAI ChatCompletion API Response - Standard Format
|
||||
# Structure: Flat with direct 'id', 'model', 'choices' fields
|
||||
# Content location: choices[0].message.content
|
||||
# Token usage: 'usage' with completion_tokens/prompt_tokens fields
|
||||
# Model info: Available in the 'model' field
|
||||
OPENAI_CHAT_COMPLETION = load_fixture("openai_chat_completion.json")
|
||||
|
||||
# OpenAI ChatCompletion API Response with Tool Calls
|
||||
# Similar to standard ChatCompletion but with tool_calls in message
|
||||
OPENAI_CHAT_TOOL_CALLS = load_fixture("openai_chat_tool_calls.json")
|
||||
|
||||
# OpenAI Response API Format - Direct Response Format
|
||||
# Structure: Uses 'output' array instead of 'choices'
|
||||
# Content location: output[0].content[0].text
|
||||
# Token usage: input_tokens/output_tokens naming
|
||||
# Additional fields: 'instructions', 'tools', etc.
|
||||
OPENAI_RESPONSE = load_fixture("openai_response.json")
|
||||
|
||||
# OpenAI Response API Format with Tool Calls
|
||||
# Similar to standard Response API but with tool calls
|
||||
OPENAI_RESPONSE_TOOL_CALLS = load_fixture("openai_response_tool_calls.json")
|
||||
|
||||
# OpenAI Agents SDK Response - Basic Text Response
|
||||
# Structure: Nested with 'raw_responses' containing actual API responses
|
||||
# Content location: raw_responses[0].output[0].content[0].text
|
||||
# Token usage: input_tokens/output_tokens fields in raw_responses[0].usage
|
||||
# Model info: Not available at the top level, must be extracted from elsewhere
|
||||
AGENTS_RESPONSE = load_fixture("openai_agents_response.json")
|
||||
|
||||
# OpenAI Agents SDK Response - Tool Call Response
|
||||
# Structure: Similar to basic response but with tool_calls
|
||||
# Tool calls location: At the same level as 'content' inside the output
|
||||
# Tool call format: Contains 'function' object with 'name' and 'arguments'
|
||||
# Arguments format: Stringified JSON rather than parsed objects
|
||||
AGENTS_TOOL_RESPONSE = load_fixture("openai_agents_tool_response.json")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_external_dependencies():
|
||||
"""Mock any external dependencies to avoid actual API calls or slow operations"""
|
||||
# Create a more comprehensive mock for JSON serialization
|
||||
# This will directly patch the json.dumps function which is used inside safe_serialize
|
||||
|
||||
# Store the original json.dumps function
|
||||
original_dumps = json.dumps
|
||||
|
||||
# Create a wrapper for json.dumps that handles MagicMock objects
|
||||
def json_dumps_wrapper(*args, **kwargs):
|
||||
"""
|
||||
Our JSON encode method doesn't play well with MagicMock objects and gets stuck iun a recursive loop.
|
||||
Patch the functionality to return a simple string instead of trying to serialize the object.
|
||||
"""
|
||||
# If the first argument is a MagicMock, return a simple string
|
||||
if args and hasattr(args[0], "__module__") and "mock" in args[0].__module__.lower():
|
||||
return '"mock_object"'
|
||||
# Otherwise, use the original function with a custom encoder that handles MagicMock objects
|
||||
cls = kwargs.get("cls", None)
|
||||
if not cls:
|
||||
# Use our own encoder that handles MagicMock objects
|
||||
class MagicMockJSONEncoder(json.JSONEncoder):
|
||||
def default(self, obj):
|
||||
if hasattr(obj, "__module__") and "mock" in obj.__module__.lower():
|
||||
return "mock_object"
|
||||
return super().default(obj)
|
||||
|
||||
kwargs["cls"] = MagicMockJSONEncoder
|
||||
# Call the original dumps with our encoder
|
||||
return original_dumps(*args, **kwargs)
|
||||
|
||||
with patch("json.dumps", side_effect=json_dumps_wrapper):
|
||||
with patch("importlib.metadata.version", return_value="1.0.0"):
|
||||
with patch("agentops.instrumentation.agentic.openai_agents.LIBRARY_NAME", "openai"):
|
||||
with patch("agentops.instrumentation.agentic.openai_agents.LIBRARY_VERSION", "1.0.0"):
|
||||
yield
|
||||
|
||||
|
||||
class TestOpenAIAgentsAttributes:
|
||||
"""Test suite for OpenAI Agents attribute processing"""
|
||||
|
||||
def test_common_instrumentation_attributes(self):
|
||||
"""Test common instrumentation attributes for consistent keys and values"""
|
||||
attrs = get_common_instrumentation_attributes()
|
||||
|
||||
# Verify required keys are present using semantic conventions
|
||||
assert InstrumentationAttributes.NAME in attrs
|
||||
assert InstrumentationAttributes.VERSION in attrs
|
||||
assert InstrumentationAttributes.LIBRARY_NAME in attrs
|
||||
assert InstrumentationAttributes.LIBRARY_VERSION in attrs
|
||||
|
||||
# Verify values
|
||||
assert attrs[InstrumentationAttributes.NAME] == "agentops"
|
||||
# Don't call get_agentops_version() again, just verify it's in the dictionary
|
||||
assert InstrumentationAttributes.VERSION in attrs
|
||||
assert attrs[InstrumentationAttributes.LIBRARY_NAME] == LIBRARY_NAME
|
||||
|
||||
def test_agent_span_attributes(self):
|
||||
"""Test extraction of attributes from an AgentSpanData object"""
|
||||
# Create a mock AgentSpanData
|
||||
mock_agent_span = MagicMock()
|
||||
mock_agent_span.__class__.__name__ = "AgentSpanData"
|
||||
mock_agent_span.name = "test_agent"
|
||||
mock_agent_span.input = "test input"
|
||||
mock_agent_span.output = "test output"
|
||||
mock_agent_span.tools = ["tool1", "tool2"]
|
||||
|
||||
# Extract attributes
|
||||
attrs = get_agent_span_attributes(mock_agent_span)
|
||||
|
||||
# Verify extracted attributes
|
||||
assert attrs[AgentAttributes.AGENT_NAME] == "test_agent"
|
||||
assert "agentops.span.kind" in attrs
|
||||
assert attrs["agentops.span.kind"] == "agent"
|
||||
|
||||
def test_function_span_attributes(self):
|
||||
"""Test extraction of attributes from a FunctionSpanData object"""
|
||||
# Create a mock FunctionSpanData
|
||||
mock_function_span = MagicMock()
|
||||
mock_function_span.__class__.__name__ = "FunctionSpanData"
|
||||
mock_function_span.name = "test_function"
|
||||
mock_function_span.input = {"arg1": "value1"}
|
||||
mock_function_span.output = {"result": "success"}
|
||||
mock_function_span.from_agent = "caller_agent"
|
||||
|
||||
# Extract attributes
|
||||
attrs = get_function_span_attributes(mock_function_span)
|
||||
|
||||
# Verify extracted attributes
|
||||
assert "tool.name" in attrs
|
||||
assert attrs["tool.name"] == "test_function"
|
||||
assert "tool.parameters" in attrs
|
||||
assert '{"arg1": "value1"}' in attrs["tool.parameters"] # Serialized string
|
||||
assert "tool.result" in attrs
|
||||
assert '{"result": "success"}' in attrs["tool.result"] # Serialized string
|
||||
assert "agentops.span.kind" in attrs
|
||||
assert attrs["agentops.span.kind"] == "tool"
|
||||
assert "agent.calling_tool.name" in attrs
|
||||
assert attrs["agent.calling_tool.name"] == "caller_agent"
|
||||
|
||||
def test_generation_span_with_chat_completion(self):
|
||||
"""Test extraction of attributes from a GenerationSpanData with Chat Completion API data"""
|
||||
|
||||
# Create a class instead of MagicMock to avoid serialization issues
|
||||
class GenerationSpanData:
|
||||
def __init__(self):
|
||||
self.__class__.__name__ = "GenerationSpanData"
|
||||
self.model = "gpt-4o-2024-08-06" # Match the model in the fixture
|
||||
self.input = "What is the capital of France?"
|
||||
self.output = OPENAI_CHAT_COMPLETION
|
||||
self.from_agent = "requester_agent"
|
||||
# Add model_config that matches the model parameters in the fixture
|
||||
self.model_config = {"temperature": 0.7, "top_p": 1.0}
|
||||
|
||||
mock_gen_span = GenerationSpanData()
|
||||
|
||||
# Extract attributes
|
||||
attrs = get_generation_span_attributes(mock_gen_span)
|
||||
|
||||
# Verify model and input attributes
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4o-2024-08-06"
|
||||
assert attrs[SpanAttributes.LLM_RESPONSE_MODEL] == "gpt-4o-2024-08-06"
|
||||
assert "gen_ai.prompt.0.role" in attrs
|
||||
assert attrs["gen_ai.prompt.0.role"] == "user"
|
||||
assert "gen_ai.prompt.0.content" in attrs
|
||||
assert attrs["gen_ai.prompt.0.content"] == "What is the capital of France?"
|
||||
|
||||
# Verify model config attributes
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_TEMPERATURE] == 0.7
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_TOP_P] == 1.0
|
||||
|
||||
# The get_chat_completions_attributes functionality is tested separately
|
||||
# in test_chat_completions_attributes_from_fixture
|
||||
|
||||
def test_generation_span_with_response_api(self):
|
||||
"""Test extraction of attributes from a GenerationSpanData with Response API data"""
|
||||
|
||||
# Create a class instead of MagicMock to avoid serialization issues
|
||||
class GenerationSpanData:
|
||||
def __init__(self):
|
||||
self.__class__.__name__ = "GenerationSpanData"
|
||||
self.model = "gpt-4o-2024-08-06" # Match the model in the fixture
|
||||
self.input = "What is the capital of France?"
|
||||
self.output = OPENAI_RESPONSE
|
||||
self.from_agent = "requester_agent"
|
||||
# Set model_config to match what's in the response
|
||||
self.model_config = {"temperature": 0.7, "top_p": 1.0}
|
||||
|
||||
mock_gen_span = GenerationSpanData()
|
||||
|
||||
# Extract attributes
|
||||
attrs = get_generation_span_attributes(mock_gen_span)
|
||||
|
||||
# Verify model and input attributes
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4o-2024-08-06"
|
||||
assert attrs[SpanAttributes.LLM_RESPONSE_MODEL] == "gpt-4o-2024-08-06"
|
||||
assert "gen_ai.prompt.0.role" in attrs
|
||||
assert attrs["gen_ai.prompt.0.role"] == "user"
|
||||
assert "gen_ai.prompt.0.content" in attrs
|
||||
assert attrs["gen_ai.prompt.0.content"] == "What is the capital of France?"
|
||||
|
||||
# Verify token usage - this is handled through model_to_dict now
|
||||
# Since we're using a direct fixture, the serialization might differ
|
||||
|
||||
# Verify model config parameters
|
||||
assert SpanAttributes.LLM_REQUEST_TEMPERATURE in attrs
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_TEMPERATURE] == 0.7
|
||||
assert SpanAttributes.LLM_REQUEST_TOP_P in attrs
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_TOP_P] == 1.0
|
||||
|
||||
# The get_raw_response_attributes functionality is tested separately
|
||||
# in test_response_api_attributes_from_fixture
|
||||
|
||||
def test_generation_span_with_agents_response(self):
|
||||
"""Test extraction of attributes from a GenerationSpanData with OpenAI Agents response data"""
|
||||
# The issue is in the serialization of MagicMock objects with the fixture
|
||||
# Let's directly use a dict instead of a MagicMock for better serialization
|
||||
|
||||
# Create a simplified version of the GenerationSpanData
|
||||
class GenerationSpanData:
|
||||
def __init__(self):
|
||||
self.__class__.__name__ = "GenerationSpanData"
|
||||
self.model = "gpt-4"
|
||||
self.input = "What is the capital of France?"
|
||||
# Use a regular dict instead of the fixture to avoid MagicMock serialization issues
|
||||
self.output = {
|
||||
"raw_responses": [
|
||||
{
|
||||
"usage": {"input_tokens": 54, "output_tokens": 8, "total_tokens": 62},
|
||||
"output": [
|
||||
{
|
||||
"content": [{"type": "output_text", "text": "The capital of France is Paris."}],
|
||||
"role": "assistant",
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
# Add model_config with temperature and top_p
|
||||
self.model_config = {"temperature": 0.7, "top_p": 0.95}
|
||||
|
||||
mock_gen_span = GenerationSpanData()
|
||||
|
||||
# Patch the model_to_dict function to avoid circular references
|
||||
with patch(
|
||||
"agentops.instrumentation.agentic.openai_agents.attributes.completion.model_to_dict",
|
||||
side_effect=lambda x: x if isinstance(x, dict) else {},
|
||||
):
|
||||
# Extract attributes
|
||||
attrs = get_generation_span_attributes(mock_gen_span)
|
||||
|
||||
# Verify core attributes
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4"
|
||||
# Note: We don't expect LLM_RESPONSE_MODEL here because the agents response format
|
||||
# doesn't contain model information - we rely on the request model value
|
||||
|
||||
# Since we patched model_to_dict, we won't get token attributes
|
||||
# We can verify other basic attributes instead
|
||||
assert attrs[SpanAttributes.LLM_SYSTEM] == "openai"
|
||||
# We should now have model config attributes as well
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_TEMPERATURE] == 0.7
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_TOP_P] == 0.95
|
||||
# WorkflowAttributes.WORKFLOW_INPUT is no longer set directly, handled by common.py
|
||||
|
||||
def test_generation_span_with_agents_tool_response(self):
|
||||
"""Test extraction of attributes from a GenerationSpanData with OpenAI Agents tool response data"""
|
||||
|
||||
# Create a simple class and use a real dictionary based on the fixture data
|
||||
class GenerationSpanData:
|
||||
def __init__(self):
|
||||
self.__class__.__name__ = "GenerationSpanData"
|
||||
self.model = "gpt-4" # Not in fixture, so we supply it
|
||||
self.input = "What's the weather like in New York City?"
|
||||
|
||||
# Create a simplified dictionary structure directly from the fixture
|
||||
# This avoids potential recursion issues with the MagicMock object
|
||||
self.output = {
|
||||
"raw_responses": [
|
||||
{
|
||||
"usage": {"input_tokens": 48, "output_tokens": 12, "total_tokens": 60},
|
||||
"output": [
|
||||
{
|
||||
"content": [
|
||||
{
|
||||
"text": "I'll help you find the current weather for New York City.",
|
||||
"type": "output_text",
|
||||
}
|
||||
],
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "call_xyz789",
|
||||
"type": "tool_call",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": '{"location":"New York City","units":"celsius"}',
|
||||
},
|
||||
}
|
||||
],
|
||||
"role": "assistant",
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
}
|
||||
# Add model_config with appropriate settings
|
||||
self.model_config = {"temperature": 0.8, "top_p": 1.0, "frequency_penalty": 0.0}
|
||||
|
||||
mock_gen_span = GenerationSpanData()
|
||||
|
||||
# Now use the actual implementation which should correctly extract the agent response data
|
||||
attrs = get_generation_span_attributes(mock_gen_span)
|
||||
|
||||
# Verify extracted attributes - using data from our patched function
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4"
|
||||
assert attrs[SpanAttributes.LLM_SYSTEM] == "openai"
|
||||
# WorkflowAttributes.WORKFLOW_INPUT is no longer set directly, handled by common.py
|
||||
|
||||
# We should now have model config attributes
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_TEMPERATURE] == 0.8
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_TOP_P] == 1.0
|
||||
|
||||
# Now verify token usage attributes that our patched function provides
|
||||
assert attrs[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 48
|
||||
assert attrs[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 12
|
||||
assert attrs[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 60
|
||||
|
||||
# Verify tool call information - note raw_responses is in index 0, output item 0, tool_call 0
|
||||
tool_id_key = MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=0, j=0)
|
||||
tool_name_key = MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0)
|
||||
tool_args_key = MessageAttributes.COMPLETION_TOOL_CALL_ARGUMENTS.format(i=0, j=0)
|
||||
|
||||
assert attrs[tool_id_key] == "call_xyz789"
|
||||
assert attrs[tool_name_key] == "get_weather"
|
||||
assert "New York City" in attrs[tool_args_key]
|
||||
|
||||
def test_handoff_span_attributes(self):
|
||||
"""Test extraction of attributes from a HandoffSpanData object"""
|
||||
# Create a mock HandoffSpanData
|
||||
mock_handoff_span = MagicMock()
|
||||
mock_handoff_span.__class__.__name__ = "HandoffSpanData"
|
||||
mock_handoff_span.from_agent = "source_agent"
|
||||
mock_handoff_span.to_agent = "target_agent"
|
||||
|
||||
# Extract attributes
|
||||
attrs = get_handoff_span_attributes(mock_handoff_span)
|
||||
|
||||
# Verify extracted attributes
|
||||
assert attrs[AgentAttributes.FROM_AGENT] == "source_agent"
|
||||
assert attrs[AgentAttributes.TO_AGENT] == "target_agent"
|
||||
|
||||
def test_response_span_attributes(self):
|
||||
"""Test extraction of attributes from a ResponseSpanData object"""
|
||||
|
||||
# Create a mock ResponseSpanData with a proper response object that matches OpenAI Response
|
||||
class ResponseObject:
|
||||
def __init__(self):
|
||||
self.__dict__ = {"model": "gpt-4", "output": [], "tools": None, "reasoning": None, "usage": None}
|
||||
self.model = "gpt-4"
|
||||
self.output = []
|
||||
self.tools = None
|
||||
self.reasoning = None
|
||||
self.usage = None
|
||||
|
||||
mock_response_span = MagicMock()
|
||||
mock_response_span.__class__.__name__ = "ResponseSpanData"
|
||||
mock_response_span.input = "user query"
|
||||
mock_response_span.response = ResponseObject()
|
||||
|
||||
# Extract attributes
|
||||
attrs = get_response_span_attributes(mock_response_span)
|
||||
|
||||
# Verify extracted attributes
|
||||
assert "gen_ai.prompt.0.role" in attrs
|
||||
assert attrs["gen_ai.prompt.0.role"] == "user"
|
||||
assert "gen_ai.prompt.0.content" in attrs
|
||||
assert attrs["gen_ai.prompt.0.content"] == "user query"
|
||||
assert "agentops.span.kind" in attrs
|
||||
assert attrs["agentops.span.kind"] == "llm"
|
||||
|
||||
def test_span_attributes_dispatcher(self):
|
||||
"""Test the dispatcher function that routes to type-specific extractors"""
|
||||
|
||||
# Create simple classes instead of MagicMock to avoid serialization recursion
|
||||
class AgentSpanData:
|
||||
def __init__(self):
|
||||
self.__class__.__name__ = "AgentSpanData"
|
||||
self.name = "test_agent"
|
||||
self.input = "test input"
|
||||
|
||||
class FunctionSpanData:
|
||||
def __init__(self):
|
||||
self.__class__.__name__ = "FunctionSpanData"
|
||||
self.name = "test_function"
|
||||
self.input = "test input"
|
||||
|
||||
class UnknownSpanData:
|
||||
def __init__(self):
|
||||
self.__class__.__name__ = "UnknownSpanData"
|
||||
|
||||
# Use our simple classes
|
||||
agent_span = AgentSpanData()
|
||||
function_span = FunctionSpanData()
|
||||
unknown_span = UnknownSpanData()
|
||||
|
||||
# Patch the serialization function to avoid infinite recursion
|
||||
with patch("agentops.helpers.serialization.safe_serialize", side_effect=lambda x: str(x)[:100]):
|
||||
# Test dispatcher for different span types
|
||||
agent_attrs = get_span_attributes(agent_span)
|
||||
assert AgentAttributes.AGENT_NAME in agent_attrs
|
||||
|
||||
function_attrs = get_span_attributes(function_span)
|
||||
assert "tool.name" in function_attrs
|
||||
assert function_attrs["tool.name"] == "test_function"
|
||||
|
||||
# Unknown span type should return empty dict
|
||||
unknown_attrs = get_span_attributes(unknown_span)
|
||||
assert unknown_attrs == {}
|
||||
|
||||
def test_chat_completions_attributes_from_fixture(self):
|
||||
"""Test extraction of attributes from Chat Completions API fixture"""
|
||||
attrs = get_chat_completions_attributes(OPENAI_CHAT_COMPLETION)
|
||||
|
||||
# Verify message content is extracted
|
||||
assert MessageAttributes.COMPLETION_ROLE.format(i=0) in attrs
|
||||
assert MessageAttributes.COMPLETION_CONTENT.format(i=0) in attrs
|
||||
assert MessageAttributes.COMPLETION_FINISH_REASON.format(i=0) in attrs
|
||||
|
||||
# Verify values match the fixture
|
||||
assert attrs[MessageAttributes.COMPLETION_ROLE.format(i=0)] == "assistant"
|
||||
assert attrs[MessageAttributes.COMPLETION_CONTENT.format(i=0)] == "The capital of France is Paris."
|
||||
assert attrs[MessageAttributes.COMPLETION_FINISH_REASON.format(i=0)] == "stop"
|
||||
|
||||
def test_chat_completions_with_tool_calls_from_fixture(self):
|
||||
"""Test extraction of attributes from Chat Completions API with tool calls fixture"""
|
||||
attrs = get_chat_completions_attributes(OPENAI_CHAT_TOOL_CALLS)
|
||||
|
||||
# Verify tool call information is extracted
|
||||
assert MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=0, j=0) in attrs
|
||||
assert MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0) in attrs
|
||||
assert MessageAttributes.COMPLETION_TOOL_CALL_ARGUMENTS.format(i=0, j=0) in attrs
|
||||
|
||||
# Verify values match fixture data (specific values will depend on your fixture content)
|
||||
tool_id = attrs[MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=0, j=0)]
|
||||
tool_name = attrs[MessageAttributes.COMPLETION_TOOL_CALL_NAME.format(i=0, j=0)]
|
||||
assert tool_id is not None and len(tool_id) > 0
|
||||
assert tool_name is not None and len(tool_name) > 0
|
||||
|
||||
def test_response_api_attributes_from_fixture(self):
|
||||
"""Test extraction of attributes from Response API fixture"""
|
||||
attrs = get_raw_response_attributes(OPENAI_RESPONSE)
|
||||
|
||||
# The implementation has changed to only return system information
|
||||
# Verify the system attribute is set correctly
|
||||
assert SpanAttributes.LLM_SYSTEM in attrs
|
||||
assert attrs[SpanAttributes.LLM_SYSTEM] == "openai"
|
||||
|
||||
def test_token_usage_processing_from_fixture(self):
|
||||
"""Test processing of token usage data from different fixtures"""
|
||||
# Test Chat Completions API token format from fixture
|
||||
attrs_chat = {}
|
||||
process_token_usage(OPENAI_CHAT_COMPLETION["usage"], attrs_chat)
|
||||
|
||||
assert attrs_chat[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 24
|
||||
assert attrs_chat[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 8
|
||||
assert attrs_chat[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 32
|
||||
|
||||
# Test Response API token format from fixture
|
||||
attrs_response = {}
|
||||
process_token_usage(OPENAI_RESPONSE["usage"], attrs_response)
|
||||
|
||||
assert attrs_response[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 42
|
||||
assert attrs_response[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 8
|
||||
assert attrs_response[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 50
|
||||
|
||||
# Test Agents SDK response token format from fixture
|
||||
attrs_agents = {}
|
||||
process_token_usage(AGENTS_RESPONSE["raw_responses"][0]["usage"], attrs_agents)
|
||||
|
||||
assert attrs_agents[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 54
|
||||
assert attrs_agents[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 8
|
||||
assert attrs_agents[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 62
|
||||
|
||||
def test_token_metric_attributes_from_fixture(self):
|
||||
"""Test generation of token metric attributes from fixture data"""
|
||||
# Get metrics from the OpenAI chat completion fixture
|
||||
metrics = get_token_metric_attributes(OPENAI_CHAT_COMPLETION["usage"], "gpt-4o-2024-08-06")
|
||||
|
||||
# Verify metrics structure and values match the fixture
|
||||
assert "prompt_tokens" in metrics
|
||||
assert "completion_tokens" in metrics
|
||||
assert "total_tokens" in metrics
|
||||
|
||||
assert metrics["prompt_tokens"]["value"] == 24
|
||||
assert metrics["completion_tokens"]["value"] == 8
|
||||
assert metrics["total_tokens"]["value"] == 32 # Match the value in OPENAI_CHAT_COMPLETION fixture
|
||||
|
||||
# Verify attributes
|
||||
assert metrics["prompt_tokens"]["attributes"]["token_type"] == "input"
|
||||
assert metrics["completion_tokens"]["attributes"]["token_type"] == "output"
|
||||
assert metrics["prompt_tokens"]["attributes"]["model"] == "gpt-4o-2024-08-06"
|
||||
assert metrics["prompt_tokens"]["attributes"][SpanAttributes.LLM_SYSTEM] == "openai"
|
||||
|
||||
def test_extract_nested_usage_from_fixtures(self):
|
||||
"""Test extraction of usage data from nested structures in fixtures"""
|
||||
# Extract from direct OpenAI response
|
||||
usage = extract_nested_usage(OPENAI_CHAT_COMPLETION)
|
||||
assert usage["prompt_tokens"] == 24
|
||||
assert usage["completion_tokens"] == 8
|
||||
|
||||
# Extract from Response API format
|
||||
usage = extract_nested_usage(OPENAI_RESPONSE)
|
||||
assert usage["input_tokens"] == 42
|
||||
assert usage["output_tokens"] == 8
|
||||
|
||||
# Extract from Agents SDK format
|
||||
usage = extract_nested_usage(AGENTS_RESPONSE["raw_responses"][0])
|
||||
assert usage["input_tokens"] == 54
|
||||
assert usage["output_tokens"] == 8
|
||||
|
||||
def test_get_model_attributes(self):
|
||||
"""Test model attributes generation with consistent naming"""
|
||||
attrs = get_model_attributes("gpt-4")
|
||||
|
||||
# Verify both request and response model fields are set
|
||||
assert attrs[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4"
|
||||
assert attrs[SpanAttributes.LLM_RESPONSE_MODEL] == "gpt-4"
|
||||
assert attrs[SpanAttributes.LLM_SYSTEM] == "openai"
|
||||
|
||||
# Common attribute tests have been moved to test_common_attributes.py
|
||||
@@ -0,0 +1,31 @@
|
||||
# OpenAI Agents Test Fixtures Generator
|
||||
|
||||
Dead simple script to grab test fixtures from OpenAI Agents API.
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# Activate venv
|
||||
source .venv/bin/activate
|
||||
|
||||
# Run it
|
||||
python -m tests.unit.instrumentation.openai_agents_tools.generate_fixtures
|
||||
```
|
||||
|
||||
## What it does
|
||||
|
||||
- Makes API calls to OpenAI Agents endpoint:
|
||||
- Standard agent response
|
||||
- Agent response with tool calls
|
||||
- Saves the JSON responses to `../fixtures/`
|
||||
- That's it!
|
||||
|
||||
## Generated Fixtures
|
||||
|
||||
- `openai_agents_response.json` - Standard Agents API response
|
||||
- `openai_agents_tool_response.json` - Agents API with tool calls
|
||||
|
||||
## Requirements
|
||||
|
||||
- OpenAI API key in env or .env file
|
||||
- openai + openai-agents packages installed
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
OpenAI Agents Tools for AgentOps instrumentation.
|
||||
|
||||
This module contains utilities for working with OpenAI Agents API responses,
|
||||
including fixture generation and response analysis.
|
||||
"""
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
Generate OpenAI Agents Test Fixtures
|
||||
|
||||
Quick and dirty script to generate JSON fixtures from real OpenAI Agents API calls.
|
||||
Dev tool only - no frills, just gets the job done.
|
||||
|
||||
Generates fixtures for:
|
||||
- OpenAI Agents API (standard response)
|
||||
- OpenAI Agents API with tool usage
|
||||
|
||||
Usage:
|
||||
python -m tests.unit.instrumentation.openai_agents_tools.generate_fixtures
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
from typing import Any, Dict
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
# Output paths
|
||||
FIXTURES_DIR = "../fixtures" # Relative to this script's location
|
||||
AGENT_RESPONSE_FILE = "openai_agents_response.json"
|
||||
AGENT_TOOL_RESPONSE_FILE = "openai_agents_tool_response.json"
|
||||
|
||||
|
||||
def get_fixtures_dir():
|
||||
"""Get absolute path to fixtures directory"""
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)), FIXTURES_DIR)
|
||||
|
||||
|
||||
def model_to_dict(obj: Any) -> Dict:
|
||||
"""Convert an object to a dictionary, handling nested objects."""
|
||||
if obj is None:
|
||||
return None
|
||||
if isinstance(obj, (str, int, float, bool)):
|
||||
return obj
|
||||
if isinstance(obj, (list, tuple)):
|
||||
return [model_to_dict(item) for item in obj]
|
||||
if isinstance(obj, dict):
|
||||
return {key: model_to_dict(value) for key, value in obj.items()}
|
||||
|
||||
# For other objects, get their attributes
|
||||
result = {}
|
||||
for key in dir(obj):
|
||||
if not key.startswith("_") and not callable(getattr(obj, key)):
|
||||
try:
|
||||
value = getattr(obj, key)
|
||||
result[key] = model_to_dict(value)
|
||||
except Exception as e:
|
||||
result[key] = f"<Error: {e}>"
|
||||
return result
|
||||
|
||||
|
||||
async def generate_standard_agent_response():
|
||||
"""Generate a standard response fixture from OpenAI Agents API."""
|
||||
print("Getting Agents API standard response...")
|
||||
|
||||
try:
|
||||
from agents import Agent, Runner
|
||||
|
||||
agent = Agent(
|
||||
name="Fixture Generation Agent",
|
||||
instructions="You are a helpful assistant designed to generate test fixtures. Respond concisely.",
|
||||
)
|
||||
|
||||
result = await Runner.run(agent, "What is the capital of France?")
|
||||
|
||||
# Convert to dict and save to file
|
||||
result_dict = model_to_dict(result)
|
||||
fixtures_dir = get_fixtures_dir()
|
||||
os.makedirs(fixtures_dir, exist_ok=True)
|
||||
|
||||
output_path = os.path.join(fixtures_dir, AGENT_RESPONSE_FILE)
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(result_dict, f, indent=2, default=str)
|
||||
|
||||
print(f"✅ Saved standard agent response to {output_path}")
|
||||
return result_dict
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error generating standard agent response: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
async def generate_tool_agent_response():
|
||||
"""Generate a tool-using response fixture from OpenAI Agents API."""
|
||||
print("Getting Agents API tool calls response...")
|
||||
|
||||
try:
|
||||
from agents import Agent, Runner, function_tool
|
||||
|
||||
# Define a simple tool
|
||||
def get_weather(location: str, unit: str = "celsius") -> str:
|
||||
"""Get weather information for a location."""
|
||||
return f"The weather in {location} is 22 degrees {unit}."
|
||||
|
||||
weather_tool = function_tool(
|
||||
get_weather, name_override="get_weather", description_override="Get the current weather in a location"
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
name="Tool Fixture Generation Agent",
|
||||
instructions="You are a helpful assistant designed to generate test fixtures. Use tools when appropriate.",
|
||||
tools=[weather_tool],
|
||||
)
|
||||
|
||||
result = await Runner.run(agent, "What's the weather in Paris?")
|
||||
|
||||
# Convert to dict and save to file
|
||||
result_dict = model_to_dict(result)
|
||||
fixtures_dir = get_fixtures_dir()
|
||||
os.makedirs(fixtures_dir, exist_ok=True)
|
||||
|
||||
output_path = os.path.join(fixtures_dir, AGENT_TOOL_RESPONSE_FILE)
|
||||
with open(output_path, "w") as f:
|
||||
json.dump(result_dict, f, indent=2, default=str)
|
||||
|
||||
print(f"✅ Saved tool agent response to {output_path}")
|
||||
return result_dict
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error generating tool agent response: {e}")
|
||||
return {"error": str(e)}
|
||||
|
||||
|
||||
async def main():
|
||||
"""Blast through API calls and save fixtures"""
|
||||
print("Generating fixtures...")
|
||||
|
||||
# Print fixture directory for debugging
|
||||
fixtures_dir = get_fixtures_dir()
|
||||
print(f"Using fixtures directory: {fixtures_dir}")
|
||||
os.makedirs(fixtures_dir, exist_ok=True)
|
||||
|
||||
# Generate all fixtures
|
||||
await generate_standard_agent_response()
|
||||
await generate_tool_agent_response()
|
||||
|
||||
print(f"\n✅ Done! Fixtures saved to {fixtures_dir}/")
|
||||
print(f" - {AGENT_RESPONSE_FILE}")
|
||||
print(f" - {AGENT_TOOL_RESPONSE_FILE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,172 @@
|
||||
"""
|
||||
Tests for OpenAI common attribute handling
|
||||
|
||||
This module contains tests for common attribute handling functions in the OpenAI instrumentation,
|
||||
specifically focusing on the get_response_attributes function which combines various attribute
|
||||
extraction functions.
|
||||
"""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from agentops.instrumentation.providers.openai.attributes.common import (
|
||||
get_common_instrumentation_attributes,
|
||||
get_response_attributes,
|
||||
)
|
||||
from agentops.instrumentation.providers.openai import LIBRARY_NAME, LIBRARY_VERSION
|
||||
from agentops.semconv import SpanAttributes, MessageAttributes, InstrumentationAttributes
|
||||
|
||||
|
||||
class MockResponse:
|
||||
"""Mock Response object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class TestCommonAttributes:
|
||||
"""Tests for OpenAI common attribute handling functions"""
|
||||
|
||||
def test_get_common_instrumentation_attributes(self):
|
||||
"""Test that common instrumentation attributes are correctly generated"""
|
||||
# Call the function
|
||||
attributes = get_common_instrumentation_attributes()
|
||||
|
||||
# Verify library attributes are set
|
||||
assert InstrumentationAttributes.LIBRARY_NAME in attributes
|
||||
assert attributes[InstrumentationAttributes.LIBRARY_NAME] == LIBRARY_NAME
|
||||
assert InstrumentationAttributes.LIBRARY_VERSION in attributes
|
||||
assert attributes[InstrumentationAttributes.LIBRARY_VERSION] == LIBRARY_VERSION
|
||||
|
||||
# Verify common attributes from parent function are included
|
||||
# (these would be added by get_common_attributes)
|
||||
assert InstrumentationAttributes.NAME in attributes
|
||||
|
||||
def test_get_response_attributes_with_kwargs(self):
|
||||
"""Test that response attributes are correctly extracted from kwargs"""
|
||||
# Create kwargs
|
||||
kwargs = {
|
||||
"input": "What is the capital of France?",
|
||||
"model": "gpt-4o",
|
||||
"temperature": 0.7,
|
||||
"top_p": 1.0,
|
||||
}
|
||||
|
||||
# Mock the kwarg extraction function
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.common.get_response_kwarg_attributes"
|
||||
) as mock_kwarg_attributes:
|
||||
mock_kwarg_attributes.return_value = {
|
||||
MessageAttributes.PROMPT_ROLE.format(i=0): "user",
|
||||
MessageAttributes.PROMPT_CONTENT.format(i=0): "What is the capital of France?",
|
||||
SpanAttributes.LLM_REQUEST_MODEL: "gpt-4o",
|
||||
}
|
||||
|
||||
# Call the function
|
||||
attributes = get_response_attributes(kwargs=kwargs)
|
||||
|
||||
# Verify kwarg extraction was called
|
||||
mock_kwarg_attributes.assert_called_once_with(kwargs)
|
||||
|
||||
# Verify attributes from kwarg extraction are included
|
||||
assert MessageAttributes.PROMPT_ROLE.format(i=0) in attributes
|
||||
assert attributes[MessageAttributes.PROMPT_ROLE.format(i=0)] == "user"
|
||||
assert MessageAttributes.PROMPT_CONTENT.format(i=0) in attributes
|
||||
assert attributes[MessageAttributes.PROMPT_CONTENT.format(i=0)] == "What is the capital of France?"
|
||||
assert SpanAttributes.LLM_REQUEST_MODEL in attributes
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4o"
|
||||
|
||||
def test_get_response_attributes_with_return_value(self):
|
||||
"""Test that response attributes are correctly extracted from return value"""
|
||||
# Create a mock Response object with all required attributes
|
||||
response = MockResponse(
|
||||
{
|
||||
"id": "resp_12345",
|
||||
"model": "gpt-4o",
|
||||
"instructions": "You are a helpful assistant.",
|
||||
"output": [],
|
||||
"tools": [],
|
||||
"reasoning": None,
|
||||
"usage": None,
|
||||
"__dict__": {
|
||||
"id": "resp_12345",
|
||||
"model": "gpt-4o",
|
||||
"instructions": "You are a helpful assistant.",
|
||||
"output": [],
|
||||
"tools": [],
|
||||
"reasoning": None,
|
||||
"usage": None,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
# Use direct patching of Response class check instead
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.common.Response", MockResponse):
|
||||
# Call the function
|
||||
attributes = get_response_attributes(return_value=response)
|
||||
|
||||
# Verify attributes are included without mocking the specific function
|
||||
# Just verify some basic attributes are set
|
||||
assert InstrumentationAttributes.LIBRARY_NAME in attributes
|
||||
assert attributes[InstrumentationAttributes.LIBRARY_NAME] == LIBRARY_NAME
|
||||
assert InstrumentationAttributes.LIBRARY_VERSION in attributes
|
||||
assert attributes[InstrumentationAttributes.LIBRARY_VERSION] == LIBRARY_VERSION
|
||||
|
||||
def test_get_response_attributes_with_both(self):
|
||||
"""Test that response attributes are correctly extracted from both kwargs and return value"""
|
||||
# Create kwargs
|
||||
kwargs = {
|
||||
"input": "What is the capital of France?",
|
||||
"model": "gpt-4o",
|
||||
"temperature": 0.7,
|
||||
"top_p": 1.0,
|
||||
}
|
||||
|
||||
# Create a mock Response object with all required attributes
|
||||
response = MockResponse(
|
||||
{
|
||||
"id": "resp_12345",
|
||||
"model": "gpt-4o",
|
||||
"instructions": "You are a helpful assistant.",
|
||||
"output": [],
|
||||
"tools": [],
|
||||
"reasoning": None,
|
||||
"usage": None,
|
||||
"__dict__": {
|
||||
"id": "resp_12345",
|
||||
"model": "gpt-4o",
|
||||
"instructions": "You are a helpful assistant.",
|
||||
"output": [],
|
||||
"tools": [],
|
||||
"reasoning": None,
|
||||
"usage": None,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
# Instead of mocking the internal functions, test the integration directly
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.common.Response", MockResponse):
|
||||
# Call the function
|
||||
attributes = get_response_attributes(kwargs=kwargs, return_value=response)
|
||||
|
||||
# Verify the key response attributes are in the final attributes dict
|
||||
assert InstrumentationAttributes.LIBRARY_NAME in attributes
|
||||
assert attributes[InstrumentationAttributes.LIBRARY_NAME] == LIBRARY_NAME
|
||||
|
||||
def test_get_response_attributes_with_unexpected_return_type(self):
|
||||
"""Test handling of unexpected return value type"""
|
||||
# Create an object that's not a Response
|
||||
not_a_response = "not a response"
|
||||
|
||||
# Should log a debug message but not raise an exception
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.common.logger.debug") as mock_logger:
|
||||
# Call the function
|
||||
attributes = get_response_attributes(return_value=not_a_response)
|
||||
|
||||
# Verify debug message was logged
|
||||
mock_logger.assert_called_once()
|
||||
assert "unexpected return type" in mock_logger.call_args[0][0]
|
||||
|
||||
# Verify common attributes are still present
|
||||
assert InstrumentationAttributes.NAME in attributes
|
||||
assert InstrumentationAttributes.LIBRARY_NAME in attributes
|
||||
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
Tests for OpenAI API Instrumentation
|
||||
|
||||
This module contains tests for properly handling and serializing data from the OpenAI API.
|
||||
It verifies that our instrumentation correctly captures and instruments API calls,
|
||||
specifically focusing on the newer Response API format used in the Agents SDK.
|
||||
|
||||
The OpenAI Instrumentor extends the third-party OpenTelemetry instrumentor and adds
|
||||
our own wrapper for the newer Response API format.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pytest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
|
||||
from agentops.instrumentation.providers.openai.instrumentor import OpenaiInstrumentor
|
||||
|
||||
|
||||
# Utility function to load fixtures
|
||||
def load_fixture(fixture_name):
|
||||
"""Load a test fixture from the fixtures directory"""
|
||||
fixture_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "fixtures", fixture_name)
|
||||
with open(fixture_path, "r") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
# Load response test fixtures
|
||||
OPENAI_RESPONSE = load_fixture("openai_response.json") # Response API format (newer API format) with output array
|
||||
OPENAI_RESPONSE_TOOL_CALLS = load_fixture("openai_response_tool_calls.json") # Response API with tool calls
|
||||
|
||||
|
||||
class TestOpenaiInstrumentor:
|
||||
"""Tests for OpenAI API instrumentation, focusing on Response API support"""
|
||||
|
||||
@pytest.fixture
|
||||
def instrumentor(self):
|
||||
"""Set up OpenAI instrumentor for tests"""
|
||||
# Create patches for tracer and meter
|
||||
with patch("agentops.instrumentation.common.instrumentor.get_tracer") as mock_get_tracer:
|
||||
with patch("agentops.instrumentation.common.instrumentor.get_meter") as mock_get_meter:
|
||||
with patch("agentops.instrumentation.providers.openai.utils.is_openai_v1", return_value=True):
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.instrumentor.is_openai_v1", return_value=True
|
||||
):
|
||||
# Set up mock tracer and meter
|
||||
mock_tracer = MagicMock()
|
||||
mock_meter = MagicMock()
|
||||
mock_get_tracer.return_value = mock_tracer
|
||||
mock_get_meter.return_value = mock_meter
|
||||
|
||||
# Create a real instrumentation setup for testing
|
||||
mock_tracer_provider = MagicMock()
|
||||
instrumentor = OpenaiInstrumentor()
|
||||
|
||||
# To avoid timing issues with the fixture, we need to ensure patch
|
||||
# objects are created before being used in the test
|
||||
mock_wrap = patch("agentops.instrumentation.common.instrumentor.wrap").start()
|
||||
mock_unwrap = patch("agentops.instrumentation.common.instrumentor.unwrap").start()
|
||||
mock_wrap_function_wrapper = patch("wrapt.wrap_function_wrapper").start()
|
||||
mock_instrument = patch.object(
|
||||
instrumentor, "_instrument", wraps=instrumentor._instrument
|
||||
).start()
|
||||
mock_uninstrument = patch.object(
|
||||
instrumentor, "_uninstrument", wraps=instrumentor._uninstrument
|
||||
).start()
|
||||
|
||||
# Instrument
|
||||
instrumentor._instrument(tracer_provider=mock_tracer_provider)
|
||||
|
||||
yield {
|
||||
"instrumentor": instrumentor,
|
||||
"tracer_provider": mock_tracer_provider,
|
||||
"mock_wrap": mock_wrap,
|
||||
"mock_unwrap": mock_unwrap,
|
||||
"mock_wrap_function_wrapper": mock_wrap_function_wrapper,
|
||||
"mock_instrument": mock_instrument,
|
||||
"mock_uninstrument": mock_uninstrument,
|
||||
"mock_tracer": mock_tracer,
|
||||
"mock_meter": mock_meter,
|
||||
}
|
||||
|
||||
# Uninstrument - must happen before stopping patches
|
||||
instrumentor._uninstrument()
|
||||
|
||||
# Stop patches
|
||||
patch.stopall()
|
||||
|
||||
def test_instrumentor_initialization(self):
|
||||
"""Test instrumentor is initialized with correct configuration"""
|
||||
instrumentor = OpenaiInstrumentor()
|
||||
assert instrumentor.__class__.__name__ == "OpenaiInstrumentor"
|
||||
|
||||
# Verify it inherits from BaseInstrumentor
|
||||
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
|
||||
|
||||
assert isinstance(instrumentor, BaseInstrumentor)
|
||||
|
||||
def test_instrument_method_wraps_response_api(self, instrumentor):
|
||||
"""Test the _instrument method wraps the Response API methods"""
|
||||
instrumentor_obj = instrumentor["instrumentor"]
|
||||
|
||||
# Create a new mock for wrap_function_wrapper that we control
|
||||
with patch("agentops.instrumentation.providers.openai.instrumentor.wrap_function_wrapper") as mock_wfw:
|
||||
# Call _custom_wrap directly to test Response API wrapping
|
||||
instrumentor_obj._custom_wrap()
|
||||
|
||||
# Verify wrap_function_wrapper was called for Response API methods
|
||||
assert mock_wfw.call_count >= 2, (
|
||||
f"Expected at least 2 calls to wrap_function_wrapper, got {mock_wfw.call_count}"
|
||||
)
|
||||
|
||||
# Find Response API calls
|
||||
response_api_calls = []
|
||||
for call in mock_wfw.call_args_list:
|
||||
if len(call[0]) >= 2 and "openai.resources.responses" in call[0][0]:
|
||||
response_api_calls.append(
|
||||
{
|
||||
"module": call[0][0],
|
||||
"method": call[0][1],
|
||||
}
|
||||
)
|
||||
|
||||
# Verify we have both sync and async Response API methods
|
||||
assert len(response_api_calls) == 2, f"Expected 2 Response API calls, got {len(response_api_calls)}"
|
||||
|
||||
# Check that we have both Responses.create and AsyncResponses.create
|
||||
methods = [call["method"] for call in response_api_calls]
|
||||
assert "Responses.create" in methods
|
||||
assert "AsyncResponses.create" in methods
|
||||
|
||||
def test_uninstrument_method_unwraps_response_api(self, instrumentor):
|
||||
"""Test the _uninstrument method unwraps the Response API methods"""
|
||||
# For these tests, we'll manually call the unwrap method with the expected configs
|
||||
# since the fixture setup has been changed
|
||||
|
||||
instrumentor_obj = instrumentor["instrumentor"]
|
||||
|
||||
# Reset the mock to clear any previous calls
|
||||
mock_unwrap = instrumentor["mock_unwrap"]
|
||||
mock_unwrap.reset_mock()
|
||||
|
||||
# Call the uninstrument method directly
|
||||
instrumentor_obj._uninstrument()
|
||||
|
||||
# Now verify the method was called
|
||||
assert mock_unwrap.called, "unwrap was not called during _uninstrument"
|
||||
|
||||
def test_calls_parent_instrument(self, instrumentor):
|
||||
"""Test that the instrumentor properly instruments methods"""
|
||||
mock_instrument = instrumentor["mock_instrument"]
|
||||
|
||||
# Verify _instrument was called
|
||||
assert mock_instrument.called
|
||||
|
||||
# Verify the tracer provider was passed
|
||||
call_kwargs = mock_instrument.call_args[1]
|
||||
assert "tracer_provider" in call_kwargs
|
||||
assert call_kwargs["tracer_provider"] == instrumentor["tracer_provider"]
|
||||
|
||||
def test_calls_parent_uninstrument(self, instrumentor):
|
||||
"""Test that the instrumentor properly uninstruments methods"""
|
||||
instrumentor_obj = instrumentor["instrumentor"]
|
||||
mock_uninstrument = instrumentor["mock_uninstrument"]
|
||||
|
||||
# Reset the mock to clear any previous calls
|
||||
mock_uninstrument.reset_mock()
|
||||
|
||||
# Directly call uninstrument
|
||||
instrumentor_obj._uninstrument()
|
||||
|
||||
# Now verify the method was called
|
||||
assert mock_uninstrument.called, "_uninstrument was not called"
|
||||
|
||||
def test_wrapper_error_handling(self):
|
||||
"""Test that the instrumentor handles errors when wrapping methods"""
|
||||
# Create instrumentor
|
||||
instrumentor = OpenaiInstrumentor()
|
||||
|
||||
# Mock wrap to raise an exception
|
||||
with patch("agentops.instrumentation.common.wrappers.wrap") as mock_wrap:
|
||||
mock_wrap.side_effect = AttributeError("Module not found")
|
||||
|
||||
# Instrument should not raise exceptions even if wrapping fails
|
||||
# The instrumentor should handle errors gracefully
|
||||
try:
|
||||
instrumentor._instrument(tracer_provider=MagicMock())
|
||||
except Exception:
|
||||
pytest.fail("Instrumentor should handle wrapping errors gracefully")
|
||||
|
||||
def test_unwrapper_error_handling(self):
|
||||
"""Test that the instrumentor handles errors when unwrapping methods"""
|
||||
# Create instrumentor
|
||||
instrumentor = OpenaiInstrumentor()
|
||||
|
||||
# Mock unwrap to raise an exception
|
||||
with patch("agentops.instrumentation.common.wrappers.unwrap") as mock_unwrap:
|
||||
mock_unwrap.side_effect = Exception("Failed to unwrap")
|
||||
|
||||
# Uninstrument should not raise exceptions even if unwrapping fails
|
||||
# The instrumentor should handle errors gracefully
|
||||
try:
|
||||
instrumentor._uninstrument()
|
||||
except Exception:
|
||||
pytest.fail("Instrumentor should handle unwrapping errors gracefully")
|
||||
|
||||
def test_instrumentation_with_tracer(self):
|
||||
"""Test that the instrumentor gets a tracer with the correct name and version"""
|
||||
# Create instrumentor
|
||||
instrumentor = OpenaiInstrumentor()
|
||||
|
||||
# Since get_tracer is now imported at module level in openai/instrumentor.py,
|
||||
# we can test this through spying on the _instrument method instead
|
||||
with patch.object(instrumentor, "_instrument", wraps=instrumentor._instrument) as mock_instrument_method:
|
||||
# Instrument
|
||||
mock_tracer_provider = MagicMock()
|
||||
instrumentor._instrument(tracer_provider=mock_tracer_provider)
|
||||
|
||||
# Verify the method was called with the expected parameters
|
||||
assert mock_instrument_method.called
|
||||
assert "tracer_provider" in mock_instrument_method.call_args[1]
|
||||
assert mock_instrument_method.call_args[1]["tracer_provider"] == mock_tracer_provider
|
||||
@@ -0,0 +1,742 @@
|
||||
"""
|
||||
Tests for OpenAI Response API attribute extraction
|
||||
|
||||
This module contains tests for extracting attributes from the OpenAI Response API format.
|
||||
It verifies that our instrumentation correctly extracts and transforms data from OpenAI API
|
||||
responses into the appropriate OpenTelemetry span attributes.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from agentops.instrumentation.providers.openai.attributes.response import (
|
||||
get_response_kwarg_attributes,
|
||||
get_response_response_attributes,
|
||||
get_response_output_attributes,
|
||||
get_response_output_message_attributes,
|
||||
get_response_output_text_attributes,
|
||||
get_response_tools_attributes,
|
||||
get_response_usage_attributes,
|
||||
get_response_tool_web_search_attributes,
|
||||
get_response_tool_file_search_attributes,
|
||||
get_response_tool_computer_attributes,
|
||||
)
|
||||
from agentops.semconv import (
|
||||
SpanAttributes,
|
||||
MessageAttributes,
|
||||
)
|
||||
|
||||
|
||||
# Utility function to load fixtures
|
||||
def load_fixture(fixture_name):
|
||||
"""Load a test fixture from the fixtures directory"""
|
||||
fixture_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "fixtures", fixture_name)
|
||||
with open(fixture_path, "r") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
# Load response test fixtures
|
||||
OPENAI_RESPONSE = load_fixture("openai_response.json") # Response API format with output array
|
||||
OPENAI_RESPONSE_TOOL_CALLS = load_fixture("openai_response_tool_calls.json") # Response API with tool calls
|
||||
|
||||
|
||||
class MockResponse:
|
||||
"""Mock Response object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class MockOutputMessage:
|
||||
"""Mock ResponseOutputMessage object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class MockOutputText:
|
||||
"""Mock ResponseOutputText object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class MockResponseUsage:
|
||||
"""Mock ResponseUsage object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class MockOutputTokensDetails:
|
||||
"""Mock OutputTokensDetails object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class MockReasoning:
|
||||
"""Mock Reasoning object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class MockFunctionTool:
|
||||
"""Mock FunctionTool object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
if not hasattr(self, "type"):
|
||||
self.type = "function"
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockWebSearchTool:
|
||||
"""Mock WebSearchTool object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
if not hasattr(self, "type"):
|
||||
self.type = "web_search_preview"
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockFileSearchTool:
|
||||
"""Mock FileSearchTool object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
if not hasattr(self, "type"):
|
||||
self.type = "file_search"
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockComputerTool:
|
||||
"""Mock ComputerTool object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
if not hasattr(self, "type"):
|
||||
self.type = "computer_use_preview"
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockUserLocation:
|
||||
"""Mock UserLocation object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockFilters:
|
||||
"""Mock Filters object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockRankingOptions:
|
||||
"""Mock RankingOptions object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockFunctionWebSearch:
|
||||
"""Mock ResponseFunctionWebSearch object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
if not hasattr(self, "type"):
|
||||
self.type = "web_search_call"
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockFileSearchToolCall:
|
||||
"""Mock ResponseFileSearchToolCall object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
if not hasattr(self, "type"):
|
||||
self.type = "file_search_call"
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockComputerToolCall:
|
||||
"""Mock ResponseComputerToolCall object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
if not hasattr(self, "type"):
|
||||
self.type = "computer_call"
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockReasoningItem:
|
||||
"""Mock ResponseReasoningItem object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
if not hasattr(self, "type"):
|
||||
self.type = "reasoning"
|
||||
self.__dict__.update(data)
|
||||
|
||||
|
||||
class MockFunctionToolCall:
|
||||
"""Mock ResponseFunctionToolCall object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class MockResponseInputParam:
|
||||
"""Mock ResponseInputParam object for testing"""
|
||||
|
||||
def __init__(self, data):
|
||||
for key, value in data.items():
|
||||
setattr(self, key, value)
|
||||
|
||||
|
||||
class TestResponseAttributes:
|
||||
"""Tests for OpenAI Response API attribute extraction"""
|
||||
|
||||
def test_get_response_kwarg_attributes_with_string_input(self):
|
||||
"""Test extraction of attributes from kwargs with string input"""
|
||||
kwargs = {
|
||||
"input": "What is the capital of France?",
|
||||
"model": "gpt-4o",
|
||||
"temperature": 0.7,
|
||||
"top_p": 1.0,
|
||||
}
|
||||
|
||||
attributes = get_response_kwarg_attributes(kwargs)
|
||||
|
||||
# Check that string input is correctly mapped to prompt attributes
|
||||
assert MessageAttributes.PROMPT_ROLE.format(i=0) in attributes
|
||||
assert attributes[MessageAttributes.PROMPT_ROLE.format(i=0)] == "user"
|
||||
assert MessageAttributes.PROMPT_CONTENT.format(i=0) in attributes
|
||||
assert attributes[MessageAttributes.PROMPT_CONTENT.format(i=0)] == "What is the capital of France?"
|
||||
|
||||
# Check that model attribute is correctly mapped
|
||||
assert SpanAttributes.LLM_REQUEST_MODEL in attributes
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4o"
|
||||
|
||||
def test_get_response_kwarg_attributes_with_list_input(self):
|
||||
"""Test extraction of attributes from kwargs with list input"""
|
||||
# Create a list of mock message objects
|
||||
messages = [
|
||||
MockResponseInputParam({"type": "text", "role": "system", "content": "You are a helpful assistant"}),
|
||||
MockResponseInputParam({"type": "text", "role": "user", "content": "What is the capital of France?"}),
|
||||
]
|
||||
|
||||
kwargs = {
|
||||
"input": messages,
|
||||
"model": "gpt-4o",
|
||||
"temperature": 0.7,
|
||||
"top_p": 1.0,
|
||||
}
|
||||
|
||||
attributes = get_response_kwarg_attributes(kwargs)
|
||||
|
||||
# Check that list input is correctly mapped to prompt attributes
|
||||
assert MessageAttributes.PROMPT_ROLE.format(i=0) in attributes
|
||||
assert attributes[MessageAttributes.PROMPT_ROLE.format(i=0)] == "system"
|
||||
assert MessageAttributes.PROMPT_CONTENT.format(i=0) in attributes
|
||||
assert attributes[MessageAttributes.PROMPT_CONTENT.format(i=0)] == "You are a helpful assistant"
|
||||
|
||||
assert MessageAttributes.PROMPT_ROLE.format(i=1) in attributes
|
||||
assert attributes[MessageAttributes.PROMPT_ROLE.format(i=1)] == "user"
|
||||
assert MessageAttributes.PROMPT_CONTENT.format(i=1) in attributes
|
||||
assert attributes[MessageAttributes.PROMPT_CONTENT.format(i=1)] == "What is the capital of France?"
|
||||
|
||||
# Check that model attribute is correctly mapped
|
||||
assert SpanAttributes.LLM_REQUEST_MODEL in attributes
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4o"
|
||||
|
||||
def test_get_response_kwarg_attributes_with_unsupported_input(self):
|
||||
"""Test extraction of attributes from kwargs with unsupported input type"""
|
||||
kwargs = {
|
||||
"input": 123, # Unsupported input type
|
||||
"model": "gpt-4o",
|
||||
}
|
||||
|
||||
# Should not raise an exception but log a debug message
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.logger.debug") as mock_logger:
|
||||
attributes = get_response_kwarg_attributes(kwargs)
|
||||
|
||||
# Verify the debug message was logged
|
||||
mock_logger.assert_called_once()
|
||||
assert "'int'" in mock_logger.call_args[0][0]
|
||||
|
||||
# Check that model attribute is still correctly mapped
|
||||
assert SpanAttributes.LLM_REQUEST_MODEL in attributes
|
||||
assert attributes[SpanAttributes.LLM_REQUEST_MODEL] == "gpt-4o"
|
||||
|
||||
def test_get_response_response_attributes(self):
|
||||
"""Test extraction of attributes from Response object"""
|
||||
# Create a mock Response object using the fixture data
|
||||
response_data = OPENAI_RESPONSE.copy()
|
||||
|
||||
# We need to convert nested objects to appropriate classes for the code to handle them
|
||||
output = []
|
||||
for item in response_data["output"]:
|
||||
content = []
|
||||
for content_item in item["content"]:
|
||||
content.append(MockOutputText(content_item))
|
||||
output.append(MockOutputMessage({**item, "content": content}))
|
||||
|
||||
usage = MockResponseUsage(
|
||||
{
|
||||
**response_data["usage"],
|
||||
"output_tokens_details": MockOutputTokensDetails(response_data["usage"]["output_tokens_details"]),
|
||||
}
|
||||
)
|
||||
|
||||
reasoning = MockReasoning(response_data["reasoning"])
|
||||
|
||||
# Set __dict__ to ensure attribute extraction works properly
|
||||
mock_response = MockResponse(
|
||||
{
|
||||
**response_data,
|
||||
"output": output,
|
||||
"usage": usage,
|
||||
"reasoning": reasoning,
|
||||
"tools": [],
|
||||
"__dict__": {**response_data, "output": output, "usage": usage, "reasoning": reasoning, "tools": []},
|
||||
}
|
||||
)
|
||||
|
||||
# Patch the Response and other type checks for simpler testing
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseOutputMessage", MockOutputMessage
|
||||
):
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseOutputText", MockOutputText
|
||||
):
|
||||
# Extract attributes
|
||||
attributes = get_response_response_attributes(mock_response)
|
||||
|
||||
# Check that basic attributes are extracted
|
||||
assert SpanAttributes.LLM_RESPONSE_ID in attributes
|
||||
assert attributes[SpanAttributes.LLM_RESPONSE_ID] == response_data["id"]
|
||||
assert SpanAttributes.LLM_RESPONSE_MODEL in attributes
|
||||
assert attributes[SpanAttributes.LLM_RESPONSE_MODEL] == response_data["model"]
|
||||
assert SpanAttributes.LLM_OPENAI_RESPONSE_INSTRUCTIONS in attributes
|
||||
assert attributes[SpanAttributes.LLM_OPENAI_RESPONSE_INSTRUCTIONS] == response_data["instructions"]
|
||||
|
||||
# Check usage attributes
|
||||
assert SpanAttributes.LLM_USAGE_PROMPT_TOKENS in attributes
|
||||
assert attributes[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == response_data["usage"]["input_tokens"]
|
||||
assert SpanAttributes.LLM_USAGE_COMPLETION_TOKENS in attributes
|
||||
assert attributes[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == response_data["usage"]["output_tokens"]
|
||||
assert SpanAttributes.LLM_USAGE_TOTAL_TOKENS in attributes
|
||||
assert attributes[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == response_data["usage"]["total_tokens"]
|
||||
|
||||
def test_get_response_output_attributes_simple(self):
|
||||
"""Test extraction of attributes from output list - simple case"""
|
||||
# Now just verify the function exists and doesn't throw an exception
|
||||
output = [] # Empty list is fine for this test
|
||||
|
||||
# Patch all the type checks to make testing simpler
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseOutputMessage", MockOutputMessage
|
||||
):
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseOutputText", MockOutputText
|
||||
):
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseFunctionToolCall",
|
||||
MockFunctionToolCall,
|
||||
):
|
||||
result = get_response_output_attributes(output)
|
||||
|
||||
# Simply verify it returns a dictionary
|
||||
assert isinstance(result, dict)
|
||||
|
||||
def test_get_response_output_message_attributes(self):
|
||||
"""Test extraction of attributes from output message"""
|
||||
# Create a simplest test we can - just verify the function exists
|
||||
# and can be called without exception
|
||||
|
||||
# Patch the ResponseOutputText class to make testing simpler
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.ResponseOutputText", MockOutputText):
|
||||
# Create a minimal mock with required attributes
|
||||
message = MockOutputMessage(
|
||||
{
|
||||
"id": "msg_12345",
|
||||
"content": [], # Empty content for simplicity
|
||||
"role": "assistant",
|
||||
"status": "completed",
|
||||
"type": "message",
|
||||
}
|
||||
)
|
||||
|
||||
# Call the function
|
||||
result = get_response_output_message_attributes(0, message)
|
||||
|
||||
# Verify basic expected attributes
|
||||
assert isinstance(result, dict)
|
||||
|
||||
def test_get_response_output_text_attributes(self):
|
||||
"""Test extraction of attributes from output text"""
|
||||
# Create a mock text content
|
||||
text = MockOutputText(
|
||||
{
|
||||
"annotations": [
|
||||
{
|
||||
"end_index": 636,
|
||||
"start_index": 538,
|
||||
"title": "5 AI Agent Frameworks Compared",
|
||||
"type": "url_citation",
|
||||
"url": "https://www.kdnuggets.com/5-ai-agent-frameworks-compared",
|
||||
}
|
||||
],
|
||||
"text": "CrewAI is the top AI agent library.",
|
||||
"type": "output_text",
|
||||
}
|
||||
)
|
||||
|
||||
# The function doesn't use the mock directly but extracts attributes from it
|
||||
# Using _extract_attributes_from_mapping_with_index internally
|
||||
# We'll test by using patch to simulate the extraction
|
||||
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response._extract_attributes_from_mapping_with_index"
|
||||
) as mock_extract:
|
||||
# Set up the mock to return expected attributes
|
||||
expected_attributes = {
|
||||
MessageAttributes.COMPLETION_ANNOTATION_END_INDEX.format(i=0, j=0): 636,
|
||||
MessageAttributes.COMPLETION_ANNOTATION_START_INDEX.format(i=0, j=1): 538,
|
||||
MessageAttributes.COMPLETION_ANNOTATION_TITLE.format(i=0, j=2): "5 AI Agent Frameworks Compared",
|
||||
MessageAttributes.COMPLETION_ANNOTATION_TYPE.format(i=0, j=3): "url_citation",
|
||||
MessageAttributes.COMPLETION_ANNOTATION_URL.format(
|
||||
i=0, j=5
|
||||
): "https://www.kdnuggets.com/5-ai-agent-frameworks-compared",
|
||||
MessageAttributes.COMPLETION_CONTENT.format(i=0): "CrewAI is the top AI agent library.",
|
||||
MessageAttributes.COMPLETION_TYPE.format(i=0): "output_text",
|
||||
}
|
||||
mock_extract.return_value = expected_attributes
|
||||
|
||||
# Call the function
|
||||
attributes = get_response_output_text_attributes(0, text)
|
||||
|
||||
# Verify mock was called with correct arguments
|
||||
mock_extract.assert_called_once()
|
||||
|
||||
# Check that the return value matches our expected attributes
|
||||
assert attributes == expected_attributes
|
||||
|
||||
def test_get_response_output_attributes_comprehensive(self):
|
||||
"""Test extraction of attributes from output items with all output types"""
|
||||
# Create a mock response output list with all different output types
|
||||
message = MockOutputMessage(
|
||||
{
|
||||
"id": "msg_12345",
|
||||
"content": [
|
||||
MockOutputText(
|
||||
{
|
||||
"text": "This is a test message",
|
||||
"type": "output_text",
|
||||
"annotations": [
|
||||
{
|
||||
"end_index": 636,
|
||||
"start_index": 538,
|
||||
"title": "Test title",
|
||||
"type": "url_citation",
|
||||
"url": "www.test.com",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
],
|
||||
"role": "assistant",
|
||||
"status": "completed",
|
||||
"type": "message",
|
||||
}
|
||||
)
|
||||
|
||||
tool_call = MockFunctionToolCall(
|
||||
{"id": "call_67890", "name": "get_weather", "arguments": '{"location":"Paris"}', "type": "function"}
|
||||
)
|
||||
|
||||
web_search = MockFunctionWebSearch({"id": "ws_12345", "status": "completed", "type": "web_search_call"})
|
||||
|
||||
file_search = MockFileSearchToolCall(
|
||||
{"id": "fsc_12345", "queries": ["search term"], "status": "completed", "type": "file_search_call"}
|
||||
)
|
||||
|
||||
computer_call = MockComputerToolCall({"id": "comp_12345", "status": "completed", "type": "computer_call"})
|
||||
|
||||
reasoning_item = MockReasoningItem({"id": "reason_12345", "status": "completed", "type": "reasoning"})
|
||||
|
||||
# Create an unrecognized output item to test error handling
|
||||
unrecognized_item = MagicMock()
|
||||
unrecognized_item.type = "unknown_type"
|
||||
|
||||
# Patch all the necessary type checks and logger
|
||||
with (
|
||||
patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseOutputMessage", MockOutputMessage
|
||||
),
|
||||
patch("agentops.instrumentation.providers.openai.attributes.response.ResponseOutputText", MockOutputText),
|
||||
patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseFunctionToolCall",
|
||||
MockFunctionToolCall,
|
||||
),
|
||||
patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseFunctionWebSearch",
|
||||
MockFunctionWebSearch,
|
||||
),
|
||||
patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseFileSearchToolCall",
|
||||
MockFileSearchToolCall,
|
||||
),
|
||||
patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseComputerToolCall",
|
||||
MockComputerToolCall,
|
||||
),
|
||||
patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.ResponseReasoningItem", MockReasoningItem
|
||||
),
|
||||
patch("agentops.instrumentation.providers.openai.attributes.response.logger.debug") as mock_logger,
|
||||
):
|
||||
# Test with an output list containing all different types of output items
|
||||
output = [message, tool_call, web_search, file_search, computer_call, reasoning_item, unrecognized_item]
|
||||
|
||||
# Call the function
|
||||
attributes = get_response_output_attributes(output)
|
||||
|
||||
# Check that it extracted attributes from all items
|
||||
assert isinstance(attributes, dict)
|
||||
|
||||
# Check message attributes were extracted (index 0)
|
||||
assert MessageAttributes.COMPLETION_ROLE.format(i=0) in attributes
|
||||
assert attributes[MessageAttributes.COMPLETION_ROLE.format(i=0)] == "assistant"
|
||||
assert MessageAttributes.COMPLETION_CONTENT.format(i=0) in attributes
|
||||
assert attributes[MessageAttributes.COMPLETION_CONTENT.format(i=0)] == "This is a test message"
|
||||
|
||||
# Check function tool call attributes were extracted (index 1)
|
||||
tool_attr_key = MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=1, j=0)
|
||||
assert tool_attr_key in attributes
|
||||
assert attributes[tool_attr_key] == "call_67890"
|
||||
|
||||
# Check web search attributes were extracted (index 2)
|
||||
web_attr_key = MessageAttributes.COMPLETION_TOOL_CALL_ID.format(i=2, j=0)
|
||||
assert web_attr_key in attributes
|
||||
assert attributes[web_attr_key] == "ws_12345"
|
||||
|
||||
# Verify that logger was called for unrecognized item
|
||||
assert any(
|
||||
call.args[0].startswith("[agentops.instrumentation.openai.response]")
|
||||
for call in mock_logger.call_args_list
|
||||
)
|
||||
|
||||
def test_get_response_tools_attributes(self):
|
||||
"""Test extraction of attributes from tools list"""
|
||||
# Create a mock function tool
|
||||
function_tool = MockFunctionTool(
|
||||
{
|
||||
"name": "get_weather",
|
||||
"parameters": {"properties": {"location": {"type": "string"}}, "required": ["location"]},
|
||||
"description": "Get weather information for a location",
|
||||
"type": "function",
|
||||
"strict": True,
|
||||
}
|
||||
)
|
||||
|
||||
# Patch all tool types to make testing simpler
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.FunctionTool", MockFunctionTool):
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.WebSearchTool", MagicMock):
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.FileSearchTool", MagicMock):
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.ComputerTool", MagicMock):
|
||||
# Test with a function tool
|
||||
tools = [function_tool]
|
||||
|
||||
# Call the function
|
||||
result = get_response_tools_attributes(tools)
|
||||
|
||||
# Verify extracted attributes
|
||||
assert isinstance(result, dict)
|
||||
assert MessageAttributes.TOOL_CALL_TYPE.format(i=0) in result
|
||||
assert result[MessageAttributes.TOOL_CALL_TYPE.format(i=0)] == "function"
|
||||
assert MessageAttributes.TOOL_CALL_NAME.format(i=0) in result
|
||||
assert result[MessageAttributes.TOOL_CALL_NAME.format(i=0)] == "get_weather"
|
||||
assert MessageAttributes.TOOL_CALL_DESCRIPTION.format(i=0) in result
|
||||
assert (
|
||||
result[MessageAttributes.TOOL_CALL_DESCRIPTION.format(i=0)]
|
||||
== "Get weather information for a location"
|
||||
)
|
||||
|
||||
def test_get_response_tool_web_search_attributes(self):
|
||||
"""Test extraction of attributes from web search tool"""
|
||||
# Create a mock web search tool
|
||||
user_location = MockUserLocation({"type": "approximate", "country": "US"})
|
||||
|
||||
web_search_tool = MockWebSearchTool(
|
||||
{"type": "web_search_preview", "search_context_size": "medium", "user_location": user_location}
|
||||
)
|
||||
|
||||
# Call the function directly
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.WebSearchTool", MockWebSearchTool):
|
||||
result = get_response_tool_web_search_attributes(web_search_tool, 0)
|
||||
|
||||
# Verify attributes
|
||||
assert isinstance(result, dict)
|
||||
assert MessageAttributes.TOOL_CALL_NAME.format(i=0) in result
|
||||
assert result[MessageAttributes.TOOL_CALL_NAME.format(i=0)] == "web_search_preview"
|
||||
assert MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0) in result
|
||||
# Parameters should be serialized
|
||||
assert "search_context_size" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
assert "user_location" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
|
||||
def test_get_response_tool_file_search_attributes(self):
|
||||
"""Test extraction of attributes from file search tool"""
|
||||
# Create a mock file search tool
|
||||
filters = MockFilters({"key": "value"})
|
||||
|
||||
ranking_options = MockRankingOptions({"ranker": "default-2024-11-15", "score_threshold": 0.8})
|
||||
|
||||
file_search_tool = MockFileSearchTool(
|
||||
{
|
||||
"type": "file_search",
|
||||
"vector_store_ids": ["store_123", "store_456"],
|
||||
"filters": filters,
|
||||
"max_num_results": 10,
|
||||
"ranking_options": ranking_options,
|
||||
}
|
||||
)
|
||||
|
||||
# Call the function directly
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.FileSearchTool", MockFileSearchTool):
|
||||
result = get_response_tool_file_search_attributes(file_search_tool, 0)
|
||||
|
||||
# Verify attributes
|
||||
assert isinstance(result, dict)
|
||||
assert MessageAttributes.TOOL_CALL_TYPE.format(i=0) in result
|
||||
assert result[MessageAttributes.TOOL_CALL_TYPE.format(i=0)] == "file_search"
|
||||
assert MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0) in result
|
||||
# Parameters should be serialized
|
||||
assert "vector_store_ids" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
assert "filters" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
assert "max_num_results" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
assert "ranking_options" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
|
||||
def test_get_response_tool_computer_attributes(self):
|
||||
"""Test extraction of attributes from computer tool"""
|
||||
# Create a mock computer tool
|
||||
computer_tool = MockComputerTool(
|
||||
{"type": "computer_use_preview", "display_height": 1080.0, "display_width": 1920.0, "environment": "mac"}
|
||||
)
|
||||
|
||||
# Call the function directly
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.ComputerTool", MockComputerTool):
|
||||
result = get_response_tool_computer_attributes(computer_tool, 0)
|
||||
|
||||
# Verify attributes
|
||||
assert isinstance(result, dict)
|
||||
assert MessageAttributes.TOOL_CALL_TYPE.format(i=0) in result
|
||||
assert result[MessageAttributes.TOOL_CALL_TYPE.format(i=0)] == "computer_use_preview"
|
||||
assert MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0) in result
|
||||
# Parameters should be serialized
|
||||
assert "display_height" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
assert "display_width" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
assert "environment" in result[MessageAttributes.TOOL_CALL_ARGUMENTS.format(i=0)]
|
||||
|
||||
def test_get_response_usage_attributes(self):
|
||||
"""Test extraction of attributes from usage data"""
|
||||
# Create a more comprehensive test for usage attributes
|
||||
|
||||
# Patch the OutputTokensDetails class to make testing simpler
|
||||
with patch(
|
||||
"agentops.instrumentation.providers.openai.attributes.response.OutputTokensDetails", MockOutputTokensDetails
|
||||
):
|
||||
with patch("agentops.instrumentation.providers.openai.attributes.response.InputTokensDetails", MagicMock):
|
||||
# Test with all fields
|
||||
usage = MockResponseUsage(
|
||||
{
|
||||
"input_tokens": 50,
|
||||
"output_tokens": 20,
|
||||
"total_tokens": 70,
|
||||
"output_tokens_details": MockOutputTokensDetails({"reasoning_tokens": 5}),
|
||||
"input_tokens_details": {"cached_tokens": 10},
|
||||
"__dict__": {
|
||||
"input_tokens": 50,
|
||||
"output_tokens": 20,
|
||||
"total_tokens": 70,
|
||||
"output_tokens_details": MockOutputTokensDetails({"reasoning_tokens": 5}),
|
||||
"input_tokens_details": {"cached_tokens": 10},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
# Test without token details (edge cases)
|
||||
usage_without_details = MockResponseUsage(
|
||||
{
|
||||
"input_tokens": 30,
|
||||
"output_tokens": 15,
|
||||
"total_tokens": 45,
|
||||
"output_tokens_details": None,
|
||||
"input_tokens_details": None,
|
||||
"__dict__": {
|
||||
"input_tokens": 30,
|
||||
"output_tokens": 15,
|
||||
"total_tokens": 45,
|
||||
"output_tokens_details": None,
|
||||
"input_tokens_details": None,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
# Call the function for complete usage
|
||||
result = get_response_usage_attributes(usage)
|
||||
|
||||
# Verify it returns a dictionary with all attributes
|
||||
assert isinstance(result, dict)
|
||||
assert SpanAttributes.LLM_USAGE_PROMPT_TOKENS in result
|
||||
assert result[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 50
|
||||
assert SpanAttributes.LLM_USAGE_COMPLETION_TOKENS in result
|
||||
assert result[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 20
|
||||
assert SpanAttributes.LLM_USAGE_TOTAL_TOKENS in result
|
||||
assert result[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 70
|
||||
assert SpanAttributes.LLM_USAGE_REASONING_TOKENS in result
|
||||
assert result[SpanAttributes.LLM_USAGE_REASONING_TOKENS] == 5
|
||||
assert SpanAttributes.LLM_USAGE_CACHE_READ_INPUT_TOKENS in result
|
||||
assert result[SpanAttributes.LLM_USAGE_CACHE_READ_INPUT_TOKENS] == 10
|
||||
|
||||
# Call the function for usage without details
|
||||
result_without_details = get_response_usage_attributes(usage_without_details)
|
||||
|
||||
# Verify basic attributes are still present
|
||||
assert isinstance(result_without_details, dict)
|
||||
assert SpanAttributes.LLM_USAGE_PROMPT_TOKENS in result_without_details
|
||||
assert result_without_details[SpanAttributes.LLM_USAGE_PROMPT_TOKENS] == 30
|
||||
assert SpanAttributes.LLM_USAGE_COMPLETION_TOKENS in result_without_details
|
||||
assert result_without_details[SpanAttributes.LLM_USAGE_COMPLETION_TOKENS] == 15
|
||||
assert SpanAttributes.LLM_USAGE_TOTAL_TOKENS in result_without_details
|
||||
assert result_without_details[SpanAttributes.LLM_USAGE_TOTAL_TOKENS] == 45
|
||||
# Detailed attributes shouldn't be present
|
||||
assert SpanAttributes.LLM_USAGE_REASONING_TOKENS not in result_without_details
|
||||
assert SpanAttributes.LLM_USAGE_CACHE_READ_INPUT_TOKENS not in result_without_details
|
||||
@@ -0,0 +1,306 @@
|
||||
import os
|
||||
import logging
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock, mock_open
|
||||
from agentops.logging.config import configure_logging, intercept_opentelemetry_logging, logger
|
||||
|
||||
|
||||
class TestConfigureLogging:
|
||||
"""Test the configure_logging function"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_and_teardown(self):
|
||||
"""Setup and teardown for each test"""
|
||||
# Store original logger state
|
||||
original_handlers = logger.handlers[:]
|
||||
original_level = logger.level
|
||||
|
||||
yield
|
||||
|
||||
# Restore original logger state
|
||||
for handler in logger.handlers[:]:
|
||||
logger.removeHandler(handler)
|
||||
for handler in original_handlers:
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(original_level)
|
||||
|
||||
def test_configure_logging_with_no_config(self):
|
||||
"""Test configure_logging when no config is provided"""
|
||||
with patch("agentops.config.Config") as mock_config_class:
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.INFO
|
||||
mock_config_class.return_value = mock_config
|
||||
|
||||
result = configure_logging()
|
||||
|
||||
assert result == logger
|
||||
assert logger.level == logging.INFO
|
||||
assert len(logger.handlers) >= 1 # At least console handler
|
||||
|
||||
def test_configure_logging_with_config_object(self):
|
||||
"""Test configure_logging with a provided config object"""
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.DEBUG
|
||||
|
||||
result = configure_logging(mock_config)
|
||||
|
||||
assert result == logger
|
||||
assert logger.level == logging.DEBUG
|
||||
|
||||
def test_configure_logging_with_env_override(self):
|
||||
"""Test configure_logging with environment variable override"""
|
||||
with patch.dict(os.environ, {"AGENTOPS_LOG_LEVEL": "WARNING"}):
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.DEBUG
|
||||
|
||||
result = configure_logging(mock_config)
|
||||
|
||||
assert result == logger
|
||||
assert logger.level == logging.WARNING
|
||||
|
||||
def test_configure_logging_with_invalid_env_level(self):
|
||||
"""Test configure_logging with invalid environment log level"""
|
||||
with patch.dict(os.environ, {"AGENTOPS_LOG_LEVEL": "INVALID_LEVEL"}):
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.DEBUG
|
||||
|
||||
result = configure_logging(mock_config)
|
||||
|
||||
assert result == logger
|
||||
assert logger.level == logging.DEBUG # Falls back to config
|
||||
|
||||
def test_configure_logging_with_string_config_level(self):
|
||||
"""Test configure_logging with string log level in config"""
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = "ERROR"
|
||||
|
||||
result = configure_logging(mock_config)
|
||||
|
||||
assert result == logger
|
||||
assert logger.level == logging.ERROR
|
||||
|
||||
def test_configure_logging_with_invalid_string_config_level(self):
|
||||
"""Test configure_logging with invalid string log level in config"""
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = "INVALID_LEVEL"
|
||||
|
||||
result = configure_logging(mock_config)
|
||||
|
||||
assert result == logger
|
||||
assert logger.level == logging.INFO # Falls back to INFO
|
||||
|
||||
def test_configure_logging_with_non_string_int_config_level(self):
|
||||
"""Test configure_logging with non-string, non-int log level in config"""
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = None # Neither string nor int
|
||||
|
||||
result = configure_logging(mock_config)
|
||||
|
||||
assert result == logger
|
||||
assert logger.level == logging.INFO # Falls back to INFO
|
||||
|
||||
def test_configure_logging_removes_existing_handlers(self):
|
||||
"""Test that configure_logging removes existing handlers"""
|
||||
# Add a dummy handler
|
||||
dummy_handler = logging.StreamHandler()
|
||||
logger.addHandler(dummy_handler)
|
||||
assert len(logger.handlers) >= 1
|
||||
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.INFO
|
||||
|
||||
configure_logging(mock_config)
|
||||
|
||||
# Check that the dummy handler was removed
|
||||
assert dummy_handler not in logger.handlers
|
||||
|
||||
def test_configure_logging_creates_console_handler(self):
|
||||
"""Test that configure_logging creates a console handler"""
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.INFO
|
||||
|
||||
configure_logging(mock_config)
|
||||
|
||||
# Check that we have at least one StreamHandler
|
||||
stream_handlers = [h for h in logger.handlers if isinstance(h, logging.StreamHandler)]
|
||||
assert len(stream_handlers) >= 1
|
||||
|
||||
@patch("builtins.open", new_callable=mock_open)
|
||||
def test_configure_logging_with_file_logging_enabled(self, mock_file):
|
||||
"""Test configure_logging with file logging enabled"""
|
||||
with patch.dict(os.environ, {"AGENTOPS_LOGGING_TO_FILE": "true"}):
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.INFO
|
||||
|
||||
configure_logging(mock_config)
|
||||
|
||||
# Check that file handler was created
|
||||
file_handlers = [h for h in logger.handlers if isinstance(h, logging.FileHandler)]
|
||||
assert len(file_handlers) >= 1
|
||||
# Check that open was called with the correct filename (path may be absolute)
|
||||
mock_file.assert_called_once()
|
||||
call_args = mock_file.call_args
|
||||
assert call_args[0][0].endswith("agentops.log")
|
||||
assert call_args[0][1] == "w"
|
||||
|
||||
def test_configure_logging_with_file_logging_disabled(self):
|
||||
"""Test configure_logging with file logging disabled"""
|
||||
with patch.dict(os.environ, {"AGENTOPS_LOGGING_TO_FILE": "false"}):
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.INFO
|
||||
|
||||
configure_logging(mock_config)
|
||||
|
||||
# Check that no file handler was created
|
||||
file_handlers = [h for h in logger.handlers if isinstance(h, logging.FileHandler)]
|
||||
assert len(file_handlers) == 0
|
||||
|
||||
def test_configure_logging_with_file_logging_case_insensitive(self):
|
||||
"""Test configure_logging with file logging case insensitive"""
|
||||
with patch.dict(os.environ, {"AGENTOPS_LOGGING_TO_FILE": "TRUE"}):
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.INFO
|
||||
|
||||
configure_logging(mock_config)
|
||||
|
||||
# Check that file handler was created
|
||||
file_handlers = [h for h in logger.handlers if isinstance(h, logging.FileHandler)]
|
||||
assert len(file_handlers) >= 1
|
||||
|
||||
def test_configure_logging_with_file_logging_default(self):
|
||||
"""Test configure_logging with file logging default (no env var)"""
|
||||
# Remove the env var if it exists
|
||||
if "AGENTOPS_LOGGING_TO_FILE" in os.environ:
|
||||
del os.environ["AGENTOPS_LOGGING_TO_FILE"]
|
||||
|
||||
with patch("builtins.open", new_callable=mock_open):
|
||||
mock_config = MagicMock()
|
||||
mock_config.log_level = logging.INFO
|
||||
|
||||
configure_logging(mock_config)
|
||||
|
||||
# Check that file handler was created (default is True)
|
||||
file_handlers = [h for h in logger.handlers if isinstance(h, logging.FileHandler)]
|
||||
assert len(file_handlers) >= 1
|
||||
|
||||
|
||||
class TestInterceptOpenTelemetryLogging:
|
||||
"""Test the intercept_opentelemetry_logging function"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_and_teardown(self):
|
||||
"""Setup and teardown for each test"""
|
||||
# Store original opentelemetry logger state
|
||||
otel_logger = logging.getLogger("opentelemetry")
|
||||
original_handlers = otel_logger.handlers[:]
|
||||
original_level = otel_logger.level
|
||||
original_propagate = otel_logger.propagate
|
||||
|
||||
yield
|
||||
|
||||
# Restore original opentelemetry logger state
|
||||
for handler in otel_logger.handlers[:]:
|
||||
otel_logger.removeHandler(handler)
|
||||
for handler in original_handlers:
|
||||
otel_logger.addHandler(handler)
|
||||
otel_logger.setLevel(original_level)
|
||||
otel_logger.propagate = original_propagate
|
||||
|
||||
def test_intercept_opentelemetry_logging_configures_logger(self):
|
||||
"""Test that intercept_opentelemetry_logging configures the opentelemetry logger"""
|
||||
intercept_opentelemetry_logging()
|
||||
|
||||
otel_logger = logging.getLogger("opentelemetry")
|
||||
assert otel_logger.level == logging.DEBUG
|
||||
assert not otel_logger.propagate
|
||||
assert len(otel_logger.handlers) == 1
|
||||
|
||||
def test_intercept_opentelemetry_logging_removes_existing_handlers(self):
|
||||
"""Test that intercept_opentelemetry_logging removes existing handlers"""
|
||||
otel_logger = logging.getLogger("opentelemetry")
|
||||
dummy_handler = logging.StreamHandler()
|
||||
otel_logger.addHandler(dummy_handler)
|
||||
|
||||
intercept_opentelemetry_logging()
|
||||
|
||||
assert dummy_handler not in otel_logger.handlers
|
||||
|
||||
def test_intercept_opentelemetry_logging_creates_custom_handler(self):
|
||||
"""Test that intercept_opentelemetry_logging creates a custom handler"""
|
||||
intercept_opentelemetry_logging()
|
||||
|
||||
otel_logger = logging.getLogger("opentelemetry")
|
||||
assert len(otel_logger.handlers) == 1
|
||||
|
||||
handler = otel_logger.handlers[0]
|
||||
assert hasattr(handler, "emit")
|
||||
|
||||
def test_otel_log_handler_emit_with_opentelemetry_prefix(self):
|
||||
"""Test the OtelLogHandler.emit method with opentelemetry prefix"""
|
||||
intercept_opentelemetry_logging()
|
||||
|
||||
otel_logger = logging.getLogger("opentelemetry")
|
||||
handler = otel_logger.handlers[0]
|
||||
|
||||
# Create a mock record with opentelemetry prefix
|
||||
record = logging.LogRecord(
|
||||
name="opentelemetry.trace",
|
||||
level=logging.INFO,
|
||||
pathname="",
|
||||
lineno=0,
|
||||
msg="Test message",
|
||||
args=(),
|
||||
exc_info=None,
|
||||
)
|
||||
|
||||
with patch.object(logger, "debug") as mock_debug:
|
||||
handler.emit(record)
|
||||
mock_debug.assert_called_once_with("[opentelemetry.trace] Test message")
|
||||
|
||||
def test_otel_log_handler_emit_without_opentelemetry_prefix(self):
|
||||
"""Test the OtelLogHandler.emit method without opentelemetry prefix"""
|
||||
intercept_opentelemetry_logging()
|
||||
|
||||
otel_logger = logging.getLogger("opentelemetry")
|
||||
handler = otel_logger.handlers[0]
|
||||
|
||||
# Create a mock record without opentelemetry prefix
|
||||
record = logging.LogRecord(
|
||||
name="some.other.module",
|
||||
level=logging.INFO,
|
||||
pathname="",
|
||||
lineno=0,
|
||||
msg="Test message",
|
||||
args=(),
|
||||
exc_info=None,
|
||||
)
|
||||
|
||||
with patch.object(logger, "debug") as mock_debug:
|
||||
handler.emit(record)
|
||||
mock_debug.assert_called_once_with("[opentelemetry.some.other.module] Test message")
|
||||
|
||||
def test_otel_log_handler_emit_with_exact_opentelemetry_name(self):
|
||||
"""Test the OtelLogHandler.emit method with exact 'opentelemetry' name"""
|
||||
intercept_opentelemetry_logging()
|
||||
|
||||
otel_logger = logging.getLogger("opentelemetry")
|
||||
handler = otel_logger.handlers[0]
|
||||
|
||||
# Create a mock record with exact 'opentelemetry' name
|
||||
record = logging.LogRecord(
|
||||
name="opentelemetry", level=logging.INFO, pathname="", lineno=0, msg="Test message", args=(), exc_info=None
|
||||
)
|
||||
|
||||
with patch.object(logger, "debug") as mock_debug:
|
||||
handler.emit(record)
|
||||
mock_debug.assert_called_once_with("[opentelemetry.opentelemetry] Test message")
|
||||
|
||||
|
||||
class TestLoggerInitialization:
|
||||
"""Test the logger initialization at module level"""
|
||||
|
||||
def test_logger_initialization(self):
|
||||
"""Test that the logger is properly initialized"""
|
||||
assert logger.name == "agentops"
|
||||
assert not logger.propagate
|
||||
assert logger.level == logging.CRITICAL # Default level
|
||||
@@ -0,0 +1,64 @@
|
||||
import builtins
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from agentops.logging.instrument_logging import setup_print_logger, upload_logfile
|
||||
import logging
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reset_print():
|
||||
"""Fixture to reset the print function after tests"""
|
||||
original_print = builtins.print
|
||||
yield
|
||||
builtins.print = original_print
|
||||
|
||||
|
||||
def test_setup_print_logger_creates_buffer_logger_and_handler():
|
||||
"""Test that setup_print_logger creates a buffer logger with a StreamHandler."""
|
||||
setup_print_logger()
|
||||
buffer_logger = logging.getLogger("agentops_buffer_logger")
|
||||
assert buffer_logger.level == logging.DEBUG
|
||||
assert len(buffer_logger.handlers) == 1
|
||||
assert isinstance(buffer_logger.handlers[0], logging.StreamHandler)
|
||||
|
||||
|
||||
def test_print_logger_writes_message_to_stringio_buffer(reset_print):
|
||||
"""Test that the monkeypatched print function writes messages to the StringIO buffer."""
|
||||
setup_print_logger()
|
||||
test_message = "Test log message"
|
||||
print(test_message)
|
||||
buffer_logger = logging.getLogger("agentops_buffer_logger")
|
||||
log_content = buffer_logger.handlers[0].stream.getvalue()
|
||||
assert test_message in log_content
|
||||
|
||||
|
||||
def test_print_logger_replaces_and_restores_builtin_print(reset_print):
|
||||
"""Test that setup_print_logger replaces builtins.print and the fixture restores it after the test."""
|
||||
import agentops.logging.instrument_logging as il
|
||||
|
||||
builtins.print = il._original_print
|
||||
original_print = builtins.print
|
||||
setup_print_logger()
|
||||
assert builtins.print != original_print
|
||||
# The reset_print fixture will restore print after the test
|
||||
|
||||
|
||||
@patch("agentops.get_client")
|
||||
def test_upload_logfile_sends_buffer_content_and_clears_buffer(mock_get_client):
|
||||
"""Test that upload_logfile uploads the buffer content and clears the buffer after upload."""
|
||||
setup_print_logger()
|
||||
test_message = "Test upload message"
|
||||
print(test_message)
|
||||
mock_client = MagicMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
upload_logfile(trace_id=123)
|
||||
mock_client.api.v4.upload_logfile.assert_called_once()
|
||||
buffer_logger = logging.getLogger("agentops_buffer_logger")
|
||||
assert buffer_logger.handlers[0].stream.getvalue() == ""
|
||||
|
||||
|
||||
def test_upload_logfile_does_nothing_when_buffer_is_empty():
|
||||
"""Test that upload_logfile does nothing and does not call the client when the buffer is empty."""
|
||||
with patch("agentops.get_client") as mock_get_client:
|
||||
upload_logfile(trace_id=123)
|
||||
mock_get_client.assert_not_called()
|
||||
@@ -0,0 +1 @@
|
||||
# Test package for the SDK
|
||||
@@ -0,0 +1,206 @@
|
||||
from typing import Any, Dict, List, Protocol, Tuple, Union
|
||||
import importlib
|
||||
import unittest.mock as mock
|
||||
|
||||
from opentelemetry import trace as trace_api
|
||||
from opentelemetry.sdk.trace import ReadableSpan, Span, TracerProvider
|
||||
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
from opentelemetry.util.types import Attributes
|
||||
|
||||
from agentops.sdk.core import tracer
|
||||
|
||||
|
||||
def create_tracer_provider(
|
||||
**kwargs,
|
||||
) -> Tuple[TracerProvider, InMemorySpanExporter, SimpleSpanProcessor]:
|
||||
"""Helper to create a configured tracer provider.
|
||||
|
||||
Creates and configures a `TracerProvider` with a
|
||||
`SimpleSpanProcessor` and a `InMemorySpanExporter`.
|
||||
All the parameters passed are forwarded to the TracerProvider
|
||||
constructor.
|
||||
|
||||
Returns:
|
||||
A tuple with the tracer provider, memory exporter, and span processor.
|
||||
"""
|
||||
tracer_provider = TracerProvider(**kwargs)
|
||||
memory_exporter = InMemorySpanExporter()
|
||||
|
||||
# Use SimpleSpanProcessor instead of both processors to avoid duplication
|
||||
span_processor = SimpleSpanProcessor(memory_exporter)
|
||||
tracer_provider.add_span_processor(span_processor)
|
||||
|
||||
return tracer_provider, memory_exporter, span_processor
|
||||
|
||||
|
||||
def reset_trace_globals():
|
||||
"""Reset the global trace state to avoid conflicts."""
|
||||
# Reset tracer provider
|
||||
trace_api._TRACER_PROVIDER = None
|
||||
|
||||
# Reload the trace module to clear warning state
|
||||
importlib.reload(trace_api)
|
||||
|
||||
|
||||
class HasAttributesViaProperty(Protocol):
|
||||
@property
|
||||
def attributes(self) -> Attributes: ...
|
||||
|
||||
|
||||
class HasAttributesViaAttr(Protocol):
|
||||
attributes: Attributes
|
||||
|
||||
|
||||
HasAttributes = Union[HasAttributesViaProperty, HasAttributesViaAttr]
|
||||
|
||||
|
||||
class InstrumentationTester:
|
||||
"""
|
||||
A utility class for testing instrumentation in the AgentOps SDK.
|
||||
|
||||
This class provides methods for setting up a test environment with
|
||||
in-memory span exporters, and for asserting properties of spans.
|
||||
"""
|
||||
|
||||
tracer_provider: TracerProvider
|
||||
memory_exporter: InMemorySpanExporter
|
||||
span_processor: SimpleSpanProcessor
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize the instrumentation tester."""
|
||||
# Reset any global state first
|
||||
reset_trace_globals()
|
||||
|
||||
# Shut down any existing tracing core
|
||||
# self._shutdown_core()
|
||||
|
||||
# Create a new tracer provider and memory exporter
|
||||
(
|
||||
self.tracer_provider,
|
||||
self.memory_exporter,
|
||||
self.span_processor,
|
||||
) = create_tracer_provider()
|
||||
|
||||
# Set the tracer provider
|
||||
trace_api.set_tracer_provider(self.tracer_provider)
|
||||
|
||||
# Create a mock for the meter provider
|
||||
self.mock_meter_provider = mock.MagicMock()
|
||||
|
||||
# Patch the setup_telemetry function to return our test providers
|
||||
self.setup_telemetry_patcher = mock.patch(
|
||||
"agentops.sdk.core.setup_telemetry", return_value=(self.tracer_provider, self.mock_meter_provider)
|
||||
)
|
||||
self.mock_setup_telemetry = self.setup_telemetry_patcher.start()
|
||||
|
||||
# Reset the tracing core to force reinitialization
|
||||
core = tracer
|
||||
core._initialized = False
|
||||
core._provider = None
|
||||
|
||||
# Initialize the core, which will now use our mocked setup_telemetry
|
||||
core.initialize()
|
||||
|
||||
self.clear_spans()
|
||||
|
||||
def _shutdown_core(self):
|
||||
"""Safely shut down the tracing core."""
|
||||
try:
|
||||
tracer.shutdown()
|
||||
except Exception as e:
|
||||
print(f"Warning: Error shutting down tracing core: {e}")
|
||||
|
||||
def clear_spans(self):
|
||||
"""Clear all spans from the memory exporter."""
|
||||
# Force flush spans
|
||||
self.span_processor.force_flush()
|
||||
|
||||
# Then clear the memory
|
||||
self.memory_exporter.clear()
|
||||
print("Cleared all spans from memory exporter")
|
||||
|
||||
def reset(self):
|
||||
"""Reset the instrumentation tester."""
|
||||
# Force flush any pending spans
|
||||
self.span_processor.force_flush()
|
||||
|
||||
# Clear any existing spans
|
||||
self.clear_spans()
|
||||
|
||||
# Reset global trace state
|
||||
reset_trace_globals()
|
||||
|
||||
# Set our tracer provider again
|
||||
trace_api.set_tracer_provider(self.tracer_provider)
|
||||
|
||||
# Shut down and re-initialize the tracing core
|
||||
self._shutdown_core()
|
||||
|
||||
# Reset the mock setup_telemetry function
|
||||
self.mock_setup_telemetry.reset_mock()
|
||||
|
||||
# Reset the tracing core to force reinitialization
|
||||
core = tracer
|
||||
core._initialized = False
|
||||
core._provider = None
|
||||
|
||||
# Initialize the core, which will now use our mocked setup_telemetry
|
||||
core.initialize()
|
||||
|
||||
def __del__(self):
|
||||
"""Clean up resources when the tester is garbage collected."""
|
||||
try:
|
||||
# Stop the patcher when the tester is deleted
|
||||
self.setup_telemetry_patcher.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def get_finished_spans(self) -> List[ReadableSpan]:
|
||||
"""Get all finished spans."""
|
||||
# Force flush any pending spans
|
||||
self.span_processor.force_flush()
|
||||
|
||||
# Get the spans
|
||||
spans = list(self.memory_exporter.get_finished_spans())
|
||||
print(f"Instrumentation Tester: Found {len(spans)} finished spans")
|
||||
for i, span in enumerate(spans):
|
||||
print(f"Span {i}: name={span.name}, attributes={span.attributes}")
|
||||
return spans
|
||||
|
||||
def get_spans_by_name(self, name: str) -> List[ReadableSpan]:
|
||||
"""Get all spans with the given name."""
|
||||
return [span for span in self.get_finished_spans() if span.name == name]
|
||||
|
||||
def get_spans_by_kind(self, kind: str) -> List[ReadableSpan]:
|
||||
"""Get all spans with the given kind."""
|
||||
return [
|
||||
span for span in self.get_finished_spans() if span.attributes and span.attributes.get("span.kind") == kind
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def assert_has_attributes(obj: HasAttributes, attributes: Dict[str, Any]):
|
||||
"""Assert that an object has the given attributes."""
|
||||
import json
|
||||
|
||||
assert obj.attributes is not None
|
||||
for key, val in attributes.items():
|
||||
assert key in obj.attributes, f"Key {key!r} not found in attributes"
|
||||
|
||||
actual_val = obj.attributes[key]
|
||||
|
||||
# Try to handle JSON-serialized values
|
||||
if isinstance(actual_val, str) and isinstance(val, (list, dict)):
|
||||
try:
|
||||
actual_val = json.loads(actual_val)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
assert actual_val == val, f"Value for key {key!r} does not match: {actual_val} != {val}"
|
||||
|
||||
@staticmethod
|
||||
def assert_span_instrumented_for(span: Union[Span, ReadableSpan], module):
|
||||
"""Assert that a span is instrumented for the given module."""
|
||||
assert span.instrumentation_scope is not None
|
||||
assert span.instrumentation_scope.name == module.__name__
|
||||
assert span.instrumentation_scope.version == module.__version__
|
||||
@@ -0,0 +1,392 @@
|
||||
"""
|
||||
Tests for agentops.sdk.attributes module.
|
||||
|
||||
This module tests all attribute management functions for telemetry contexts.
|
||||
"""
|
||||
|
||||
import platform
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from agentops.sdk.attributes import (
|
||||
get_system_resource_attributes,
|
||||
get_global_resource_attributes,
|
||||
get_trace_attributes,
|
||||
get_span_attributes,
|
||||
get_session_end_attributes,
|
||||
)
|
||||
from agentops.semconv import ResourceAttributes, SpanAttributes, CoreAttributes
|
||||
|
||||
|
||||
class TestGetSystemResourceAttributes:
|
||||
"""Test get_system_resource_attributes function."""
|
||||
|
||||
def test_basic_system_attributes(self):
|
||||
"""Test that basic system attributes are included."""
|
||||
attributes = get_system_resource_attributes()
|
||||
|
||||
# Check that all basic platform attributes are present
|
||||
assert ResourceAttributes.HOST_MACHINE in attributes
|
||||
assert ResourceAttributes.HOST_NAME in attributes
|
||||
assert ResourceAttributes.HOST_NODE in attributes
|
||||
assert ResourceAttributes.HOST_PROCESSOR in attributes
|
||||
assert ResourceAttributes.HOST_SYSTEM in attributes
|
||||
assert ResourceAttributes.HOST_VERSION in attributes
|
||||
assert ResourceAttributes.HOST_OS_RELEASE in attributes
|
||||
|
||||
# Check that values match platform module
|
||||
assert attributes[ResourceAttributes.HOST_MACHINE] == platform.machine()
|
||||
assert attributes[ResourceAttributes.HOST_NAME] == platform.node()
|
||||
assert attributes[ResourceAttributes.HOST_NODE] == platform.node()
|
||||
assert attributes[ResourceAttributes.HOST_PROCESSOR] == platform.processor()
|
||||
assert attributes[ResourceAttributes.HOST_SYSTEM] == platform.system()
|
||||
assert attributes[ResourceAttributes.HOST_VERSION] == platform.version()
|
||||
assert attributes[ResourceAttributes.HOST_OS_RELEASE] == platform.release()
|
||||
|
||||
@patch("agentops.sdk.attributes.os.cpu_count")
|
||||
@patch("agentops.sdk.attributes.psutil.cpu_percent")
|
||||
def test_cpu_stats_success(self, mock_cpu_percent, mock_cpu_count):
|
||||
"""Test CPU stats when successfully retrieved."""
|
||||
mock_cpu_count.return_value = 8
|
||||
mock_cpu_percent.return_value = 25.5
|
||||
|
||||
attributes = get_system_resource_attributes()
|
||||
|
||||
assert ResourceAttributes.CPU_COUNT in attributes
|
||||
assert ResourceAttributes.CPU_PERCENT in attributes
|
||||
assert attributes[ResourceAttributes.CPU_COUNT] == 8
|
||||
assert attributes[ResourceAttributes.CPU_PERCENT] == 25.5
|
||||
|
||||
@patch("agentops.sdk.attributes.os.cpu_count")
|
||||
@patch("agentops.sdk.attributes.psutil.cpu_percent")
|
||||
def test_cpu_stats_cpu_count_none(self, mock_cpu_percent, mock_cpu_count):
|
||||
"""Test CPU stats when cpu_count returns None."""
|
||||
mock_cpu_count.return_value = None
|
||||
mock_cpu_percent.return_value = 25.5
|
||||
|
||||
attributes = get_system_resource_attributes()
|
||||
|
||||
assert ResourceAttributes.CPU_COUNT in attributes
|
||||
assert attributes[ResourceAttributes.CPU_COUNT] == 0
|
||||
|
||||
@patch("agentops.sdk.attributes.os.cpu_count")
|
||||
@patch("agentops.sdk.attributes.psutil.cpu_percent")
|
||||
def test_cpu_stats_exception(self, mock_cpu_percent, mock_cpu_count):
|
||||
"""Test CPU stats when exception occurs."""
|
||||
mock_cpu_count.side_effect = Exception("CPU count error")
|
||||
mock_cpu_percent.side_effect = Exception("CPU percent error")
|
||||
|
||||
attributes = get_system_resource_attributes()
|
||||
|
||||
# Should not include CPU attributes when exception occurs
|
||||
assert ResourceAttributes.CPU_COUNT not in attributes
|
||||
assert ResourceAttributes.CPU_PERCENT not in attributes
|
||||
|
||||
@patch("agentops.sdk.attributes.psutil.virtual_memory")
|
||||
def test_memory_stats_success(self, mock_virtual_memory):
|
||||
"""Test memory stats when successfully retrieved."""
|
||||
mock_memory = Mock()
|
||||
mock_memory.total = 8589934592 # 8GB
|
||||
mock_memory.available = 4294967296 # 4GB
|
||||
mock_memory.used = 4294967296 # 4GB
|
||||
mock_memory.percent = 50.0
|
||||
mock_virtual_memory.return_value = mock_memory
|
||||
|
||||
attributes = get_system_resource_attributes()
|
||||
|
||||
assert ResourceAttributes.MEMORY_TOTAL in attributes
|
||||
assert ResourceAttributes.MEMORY_AVAILABLE in attributes
|
||||
assert ResourceAttributes.MEMORY_USED in attributes
|
||||
assert ResourceAttributes.MEMORY_PERCENT in attributes
|
||||
assert attributes[ResourceAttributes.MEMORY_TOTAL] == 8589934592
|
||||
assert attributes[ResourceAttributes.MEMORY_AVAILABLE] == 4294967296
|
||||
assert attributes[ResourceAttributes.MEMORY_USED] == 4294967296
|
||||
assert attributes[ResourceAttributes.MEMORY_PERCENT] == 50.0
|
||||
|
||||
@patch("agentops.sdk.attributes.psutil.virtual_memory")
|
||||
def test_memory_stats_exception(self, mock_virtual_memory):
|
||||
"""Test memory stats when exception occurs."""
|
||||
mock_virtual_memory.side_effect = Exception("Memory error")
|
||||
|
||||
attributes = get_system_resource_attributes()
|
||||
|
||||
# Should not include memory attributes when exception occurs
|
||||
assert ResourceAttributes.MEMORY_TOTAL not in attributes
|
||||
assert ResourceAttributes.MEMORY_AVAILABLE not in attributes
|
||||
assert ResourceAttributes.MEMORY_USED not in attributes
|
||||
assert ResourceAttributes.MEMORY_PERCENT not in attributes
|
||||
|
||||
|
||||
class TestGetGlobalResourceAttributes:
|
||||
"""Test get_global_resource_attributes function."""
|
||||
|
||||
@patch("agentops.sdk.attributes.get_imported_libraries")
|
||||
def test_basic_attributes_with_project_id(self, mock_get_libs):
|
||||
"""Test basic attributes with project ID."""
|
||||
mock_get_libs.return_value = ["requests", "pandas"]
|
||||
|
||||
attributes = get_global_resource_attributes("test-service", project_id="test-project")
|
||||
|
||||
assert ResourceAttributes.SERVICE_NAME in attributes
|
||||
assert ResourceAttributes.PROJECT_ID in attributes
|
||||
assert ResourceAttributes.IMPORTED_LIBRARIES in attributes
|
||||
assert attributes[ResourceAttributes.SERVICE_NAME] == "test-service"
|
||||
assert attributes[ResourceAttributes.PROJECT_ID] == "test-project"
|
||||
assert attributes[ResourceAttributes.IMPORTED_LIBRARIES] == ["requests", "pandas"]
|
||||
|
||||
@patch("agentops.sdk.attributes.get_imported_libraries")
|
||||
def test_basic_attributes_without_project_id(self, mock_get_libs):
|
||||
"""Test basic attributes without project ID."""
|
||||
mock_get_libs.return_value = ["requests", "pandas"]
|
||||
|
||||
attributes = get_global_resource_attributes("test-service")
|
||||
|
||||
assert ResourceAttributes.SERVICE_NAME in attributes
|
||||
assert ResourceAttributes.PROJECT_ID not in attributes
|
||||
assert ResourceAttributes.IMPORTED_LIBRARIES in attributes
|
||||
assert attributes[ResourceAttributes.SERVICE_NAME] == "test-service"
|
||||
assert attributes[ResourceAttributes.IMPORTED_LIBRARIES] == ["requests", "pandas"]
|
||||
|
||||
@patch("agentops.sdk.attributes.get_imported_libraries")
|
||||
def test_no_imported_libraries(self, mock_get_libs):
|
||||
"""Test when no imported libraries are found."""
|
||||
mock_get_libs.return_value = None
|
||||
|
||||
attributes = get_global_resource_attributes("test-service", project_id="test-project")
|
||||
|
||||
assert ResourceAttributes.SERVICE_NAME in attributes
|
||||
assert ResourceAttributes.PROJECT_ID in attributes
|
||||
assert ResourceAttributes.IMPORTED_LIBRARIES not in attributes
|
||||
assert attributes[ResourceAttributes.SERVICE_NAME] == "test-service"
|
||||
assert attributes[ResourceAttributes.PROJECT_ID] == "test-project"
|
||||
|
||||
@patch("agentops.sdk.attributes.get_imported_libraries")
|
||||
def test_empty_imported_libraries(self, mock_get_libs):
|
||||
"""Test when imported libraries list is empty."""
|
||||
mock_get_libs.return_value = []
|
||||
|
||||
attributes = get_global_resource_attributes("test-service", project_id="test-project")
|
||||
|
||||
assert ResourceAttributes.SERVICE_NAME in attributes
|
||||
assert ResourceAttributes.PROJECT_ID in attributes
|
||||
assert ResourceAttributes.IMPORTED_LIBRARIES not in attributes
|
||||
assert attributes[ResourceAttributes.SERVICE_NAME] == "test-service"
|
||||
assert attributes[ResourceAttributes.PROJECT_ID] == "test-project"
|
||||
|
||||
|
||||
class TestGetTraceAttributes:
|
||||
"""Test get_trace_attributes function."""
|
||||
|
||||
def test_no_tags(self):
|
||||
"""Test when no tags are provided."""
|
||||
attributes = get_trace_attributes()
|
||||
|
||||
assert attributes == {}
|
||||
|
||||
def test_list_tags(self):
|
||||
"""Test with list of tags."""
|
||||
tags = ["tag1", "tag2", "tag3"]
|
||||
attributes = get_trace_attributes(tags)
|
||||
|
||||
assert CoreAttributes.TAGS in attributes
|
||||
assert attributes[CoreAttributes.TAGS] == ["tag1", "tag2", "tag3"]
|
||||
|
||||
def test_dict_tags(self):
|
||||
"""Test with dictionary of tags."""
|
||||
tags = {"key1": "value1", "key2": "value2"}
|
||||
attributes = get_trace_attributes(tags)
|
||||
|
||||
assert "key1" in attributes
|
||||
assert "key2" in attributes
|
||||
assert attributes["key1"] == "value1"
|
||||
assert attributes["key2"] == "value2"
|
||||
|
||||
def test_mixed_dict_tags(self):
|
||||
"""Test with dictionary containing various value types."""
|
||||
tags = {
|
||||
"string_key": "string_value",
|
||||
"int_key": 42,
|
||||
"float_key": 3.14,
|
||||
"bool_key": True,
|
||||
"list_key": [1, 2, 3],
|
||||
}
|
||||
attributes = get_trace_attributes(tags)
|
||||
|
||||
assert attributes["string_key"] == "string_value"
|
||||
assert attributes["int_key"] == 42
|
||||
assert attributes["float_key"] == 3.14
|
||||
assert attributes["bool_key"] is True
|
||||
assert attributes["list_key"] == [1, 2, 3]
|
||||
|
||||
def test_invalid_tags_type(self):
|
||||
"""Test with invalid tags type."""
|
||||
with patch("agentops.sdk.attributes.logger") as mock_logger:
|
||||
attributes = get_trace_attributes("invalid_tags")
|
||||
|
||||
assert attributes == {}
|
||||
mock_logger.warning.assert_called_once()
|
||||
|
||||
def test_none_tags(self):
|
||||
"""Test with None tags."""
|
||||
attributes = get_trace_attributes(None)
|
||||
|
||||
assert attributes == {}
|
||||
|
||||
|
||||
class TestGetSpanAttributes:
|
||||
"""Test get_span_attributes function."""
|
||||
|
||||
def test_basic_span_attributes(self):
|
||||
"""Test basic span attributes."""
|
||||
attributes = get_span_attributes("test-operation", "test-kind")
|
||||
|
||||
assert SpanAttributes.AGENTOPS_SPAN_KIND in attributes
|
||||
assert SpanAttributes.OPERATION_NAME in attributes
|
||||
assert attributes[SpanAttributes.AGENTOPS_SPAN_KIND] == "test-kind"
|
||||
assert attributes[SpanAttributes.OPERATION_NAME] == "test-operation"
|
||||
assert SpanAttributes.OPERATION_VERSION not in attributes
|
||||
|
||||
def test_span_attributes_with_version(self):
|
||||
"""Test span attributes with version."""
|
||||
attributes = get_span_attributes("test-operation", "test-kind", version=1)
|
||||
|
||||
assert SpanAttributes.AGENTOPS_SPAN_KIND in attributes
|
||||
assert SpanAttributes.OPERATION_NAME in attributes
|
||||
assert SpanAttributes.OPERATION_VERSION in attributes
|
||||
assert attributes[SpanAttributes.AGENTOPS_SPAN_KIND] == "test-kind"
|
||||
assert attributes[SpanAttributes.OPERATION_NAME] == "test-operation"
|
||||
assert attributes[SpanAttributes.OPERATION_VERSION] == 1
|
||||
|
||||
def test_span_attributes_with_version_zero(self):
|
||||
"""Test span attributes with version zero."""
|
||||
attributes = get_span_attributes("test-operation", "test-kind", version=0)
|
||||
|
||||
assert SpanAttributes.OPERATION_VERSION in attributes
|
||||
assert attributes[SpanAttributes.OPERATION_VERSION] == 0
|
||||
|
||||
def test_span_attributes_with_additional_kwargs(self):
|
||||
"""Test span attributes with additional keyword arguments."""
|
||||
attributes = get_span_attributes(
|
||||
"test-operation",
|
||||
"test-kind",
|
||||
version=1,
|
||||
custom_key="custom_value",
|
||||
another_key=42,
|
||||
)
|
||||
|
||||
assert SpanAttributes.AGENTOPS_SPAN_KIND in attributes
|
||||
assert SpanAttributes.OPERATION_NAME in attributes
|
||||
assert SpanAttributes.OPERATION_VERSION in attributes
|
||||
assert "custom_key" in attributes
|
||||
assert "another_key" in attributes
|
||||
assert attributes["custom_key"] == "custom_value"
|
||||
assert attributes["another_key"] == 42
|
||||
|
||||
def test_span_attributes_overwrite_kwargs(self):
|
||||
"""Test that kwargs can overwrite default attributes."""
|
||||
attributes = get_span_attributes(
|
||||
"test-operation",
|
||||
"test-kind",
|
||||
version=1,
|
||||
custom_operation_name="overwritten-name",
|
||||
custom_span_kind="overwritten-kind",
|
||||
)
|
||||
|
||||
# kwargs should overwrite the default values
|
||||
assert attributes["custom_operation_name"] == "overwritten-name"
|
||||
assert attributes["custom_span_kind"] == "overwritten-kind"
|
||||
# The original positional arguments should still be set
|
||||
assert attributes[SpanAttributes.OPERATION_NAME] == "test-operation"
|
||||
assert attributes[SpanAttributes.AGENTOPS_SPAN_KIND] == "test-kind"
|
||||
|
||||
|
||||
class TestGetSessionEndAttributes:
|
||||
"""Test get_session_end_attributes function."""
|
||||
|
||||
def test_session_end_attributes_success(self):
|
||||
"""Test session end attributes with success state."""
|
||||
attributes = get_session_end_attributes("Success")
|
||||
|
||||
assert SpanAttributes.AGENTOPS_SESSION_END_STATE in attributes
|
||||
assert attributes[SpanAttributes.AGENTOPS_SESSION_END_STATE] == "Success"
|
||||
|
||||
def test_session_end_attributes_failure(self):
|
||||
"""Test session end attributes with failure state."""
|
||||
attributes = get_session_end_attributes("Failure")
|
||||
|
||||
assert SpanAttributes.AGENTOPS_SESSION_END_STATE in attributes
|
||||
assert attributes[SpanAttributes.AGENTOPS_SESSION_END_STATE] == "Failure"
|
||||
|
||||
def test_session_end_attributes_custom_state(self):
|
||||
"""Test session end attributes with custom state."""
|
||||
attributes = get_session_end_attributes("CustomState")
|
||||
|
||||
assert SpanAttributes.AGENTOPS_SESSION_END_STATE in attributes
|
||||
assert attributes[SpanAttributes.AGENTOPS_SESSION_END_STATE] == "CustomState"
|
||||
|
||||
def test_session_end_attributes_empty_string(self):
|
||||
"""Test session end attributes with empty string."""
|
||||
attributes = get_session_end_attributes("")
|
||||
|
||||
assert SpanAttributes.AGENTOPS_SESSION_END_STATE in attributes
|
||||
assert attributes[SpanAttributes.AGENTOPS_SESSION_END_STATE] == ""
|
||||
|
||||
|
||||
class TestAttributesIntegration:
|
||||
"""Integration tests for attributes module."""
|
||||
|
||||
def test_all_functions_work_together(self):
|
||||
"""Test that all attribute functions work together without conflicts."""
|
||||
# Get system attributes
|
||||
system_attrs = get_system_resource_attributes()
|
||||
assert isinstance(system_attrs, dict)
|
||||
|
||||
# Get global attributes
|
||||
global_attrs = get_global_resource_attributes("test-service", project_id="test-project")
|
||||
assert isinstance(global_attrs, dict)
|
||||
|
||||
# Get trace attributes
|
||||
trace_attrs = get_trace_attributes(["tag1", "tag2"])
|
||||
assert isinstance(trace_attrs, dict)
|
||||
|
||||
# Get span attributes
|
||||
span_attrs = get_span_attributes("test-operation", "test-kind", version=1)
|
||||
assert isinstance(span_attrs, dict)
|
||||
|
||||
# Get session end attributes
|
||||
session_attrs = get_session_end_attributes("Success")
|
||||
assert isinstance(session_attrs, dict)
|
||||
|
||||
# Verify no key conflicts between different attribute types
|
||||
all_keys = (
|
||||
set(system_attrs.keys())
|
||||
| set(global_attrs.keys())
|
||||
| set(trace_attrs.keys())
|
||||
| set(span_attrs.keys())
|
||||
| set(session_attrs.keys())
|
||||
)
|
||||
assert len(all_keys) == len(system_attrs) + len(global_attrs) + len(trace_attrs) + len(span_attrs) + len(
|
||||
session_attrs
|
||||
)
|
||||
|
||||
def test_attribute_types_consistency(self):
|
||||
"""Test that all attributes return consistent types."""
|
||||
# All functions should return dictionaries
|
||||
assert isinstance(get_system_resource_attributes(), dict)
|
||||
assert isinstance(get_global_resource_attributes("test"), dict)
|
||||
assert isinstance(get_trace_attributes(), dict)
|
||||
assert isinstance(get_span_attributes("test", "test"), dict)
|
||||
assert isinstance(get_session_end_attributes("test"), dict)
|
||||
|
||||
# All dictionary values should be serializable
|
||||
import json
|
||||
|
||||
try:
|
||||
json.dumps(get_system_resource_attributes())
|
||||
json.dumps(get_global_resource_attributes("test"))
|
||||
json.dumps(get_trace_attributes())
|
||||
json.dumps(get_span_attributes("test", "test"))
|
||||
json.dumps(get_session_end_attributes("test"))
|
||||
except (TypeError, ValueError) as e:
|
||||
pytest.fail(f"Attributes are not JSON serializable: {e}")
|
||||
@@ -0,0 +1,468 @@
|
||||
"""
|
||||
Unit tests for concurrent instrumentation and context propagation.
|
||||
|
||||
This module tests the behavior of OpenTelemetry spans when using concurrent.futures.ThreadPoolExecutor,
|
||||
specifically testing context propagation across thread boundaries.
|
||||
"""
|
||||
|
||||
import concurrent.futures
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import threading
|
||||
|
||||
from opentelemetry import context, trace
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
|
||||
from agentops.sdk.processors import InternalSpanProcessor
|
||||
|
||||
|
||||
class IsolatedInstrumentationTester:
|
||||
"""
|
||||
A lighter-weight instrumentation tester that doesn't affect global state.
|
||||
|
||||
This version creates an isolated tracer provider and doesn't shut down
|
||||
the global tracing core, making it safer for use alongside other tests.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize with isolated tracer provider."""
|
||||
# Create isolated tracer provider and exporter
|
||||
self.tracer_provider = TracerProvider()
|
||||
self.memory_exporter = InMemorySpanExporter()
|
||||
self.span_processor = SimpleSpanProcessor(self.memory_exporter)
|
||||
self.tracer_provider.add_span_processor(self.span_processor)
|
||||
|
||||
# Don't set as global provider - keep isolated
|
||||
self.tracer = self.tracer_provider.get_tracer(__name__)
|
||||
|
||||
def get_tracer(self):
|
||||
"""Get the isolated tracer."""
|
||||
return self.tracer
|
||||
|
||||
def clear_spans(self):
|
||||
"""Clear all spans from the memory exporter."""
|
||||
self.span_processor.force_flush()
|
||||
self.memory_exporter.clear()
|
||||
|
||||
def get_finished_spans(self):
|
||||
"""Get all finished spans."""
|
||||
self.span_processor.force_flush()
|
||||
return list(self.memory_exporter.get_finished_spans())
|
||||
|
||||
|
||||
class TestConcurrentInstrumentation(unittest.TestCase):
|
||||
"""Tests for concurrent instrumentation and context propagation."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test environment with isolated instrumentation tester."""
|
||||
self.tester = IsolatedInstrumentationTester()
|
||||
self.tracer = self.tester.get_tracer()
|
||||
|
||||
def tearDown(self):
|
||||
"""Clean up test environment without affecting global state."""
|
||||
# Only clear our isolated spans
|
||||
self.tester.clear_spans()
|
||||
|
||||
def _create_simple_span(self, name: str, sleep_duration: float = 0.01) -> str:
|
||||
"""Helper to create a simple span and return its trace_id."""
|
||||
with self.tracer.start_as_current_span(name) as span:
|
||||
time.sleep(sleep_duration) # Simulate work
|
||||
return span.get_span_context().trace_id
|
||||
|
||||
def _create_nested_spans(self, parent_name: str, child_name: str) -> tuple:
|
||||
"""Helper to create nested spans and return their trace_ids."""
|
||||
with self.tracer.start_as_current_span(parent_name) as parent_span:
|
||||
parent_trace_id = parent_span.get_span_context().trace_id
|
||||
time.sleep(0.01)
|
||||
|
||||
with self.tracer.start_as_current_span(child_name) as child_span:
|
||||
child_trace_id = child_span.get_span_context().trace_id
|
||||
time.sleep(0.01)
|
||||
|
||||
return parent_trace_id, child_trace_id
|
||||
|
||||
def test_sequential_spans_same_trace(self):
|
||||
"""Test that sequential spans in the same thread share the same trace."""
|
||||
self._create_simple_span("span1")
|
||||
self._create_simple_span("span2")
|
||||
|
||||
# In sequential execution, spans should be independent (different traces)
|
||||
spans = self.tester.get_finished_spans()
|
||||
self.assertEqual(len(spans), 2)
|
||||
|
||||
# Each span should be a root span (no parent)
|
||||
for span in spans:
|
||||
self.assertIsNone(span.parent)
|
||||
|
||||
def test_nested_spans_same_trace(self):
|
||||
"""Test that nested spans share the same trace."""
|
||||
parent_trace_id, child_trace_id = self._create_nested_spans("parent", "child")
|
||||
|
||||
# Nested spans should share the same trace
|
||||
self.assertEqual(parent_trace_id, child_trace_id)
|
||||
|
||||
spans = self.tester.get_finished_spans()
|
||||
self.assertEqual(len(spans), 2)
|
||||
|
||||
# Find parent and child spans
|
||||
parent_spans = [s for s in spans if s.name == "parent"]
|
||||
child_spans = [s for s in spans if s.name == "child"]
|
||||
|
||||
self.assertEqual(len(parent_spans), 1)
|
||||
self.assertEqual(len(child_spans), 1)
|
||||
|
||||
parent_span = parent_spans[0]
|
||||
child_span = child_spans[0]
|
||||
|
||||
# Child should have parent as its parent
|
||||
self.assertEqual(child_span.parent.span_id, parent_span.context.span_id)
|
||||
|
||||
def test_threadpool_without_context_propagation_creates_separate_traces(self):
|
||||
"""Test that ThreadPoolExecutor without context propagation creates separate traces."""
|
||||
|
||||
def worker_task(task_id: str) -> dict:
|
||||
"""Worker task that creates a span without context propagation."""
|
||||
with self.tracer.start_as_current_span(f"worker_task_{task_id}") as span:
|
||||
time.sleep(0.01) # Simulate work
|
||||
return {
|
||||
"task_id": task_id,
|
||||
"trace_id": span.get_span_context().trace_id,
|
||||
"span_id": span.get_span_context().span_id,
|
||||
"thread_id": threading.get_ident(),
|
||||
}
|
||||
|
||||
# Create a parent span
|
||||
with self.tracer.start_as_current_span("main_task") as main_span:
|
||||
main_trace_id = main_span.get_span_context().trace_id
|
||||
|
||||
# Execute tasks in thread pool WITHOUT context propagation
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
||||
futures = [executor.submit(worker_task, f"task_{i}") for i in range(3)]
|
||||
results = [future.result() for future in concurrent.futures.as_completed(futures)]
|
||||
|
||||
spans = self.tester.get_finished_spans()
|
||||
self.assertEqual(len(spans), 4) # 1 main + 3 worker spans
|
||||
|
||||
# Extract trace IDs from results
|
||||
worker_trace_ids = [result["trace_id"] for result in results]
|
||||
|
||||
# Each worker should have a different trace ID from the main span
|
||||
for worker_trace_id in worker_trace_ids:
|
||||
self.assertNotEqual(
|
||||
worker_trace_id,
|
||||
main_trace_id,
|
||||
"Worker span should NOT share trace with main span (no context propagation)",
|
||||
)
|
||||
|
||||
# Worker spans should also be different from each other (separate traces)
|
||||
unique_trace_ids = set(worker_trace_ids)
|
||||
self.assertEqual(len(unique_trace_ids), 3, "Each worker should create a separate trace")
|
||||
|
||||
# Verify that worker spans have no parent (they are root spans)
|
||||
worker_spans = [s for s in spans if s.name.startswith("worker_task_")]
|
||||
for worker_span in worker_spans:
|
||||
self.assertIsNone(worker_span.parent, "Worker spans should be root spans without parent")
|
||||
|
||||
def test_threadpool_with_manual_context_propagation_shares_trace(self):
|
||||
"""Test that ThreadPoolExecutor with manual context propagation shares the same trace."""
|
||||
|
||||
def worker_task_with_context(task_info: tuple) -> dict:
|
||||
"""Worker task that restores context before creating spans."""
|
||||
task_id, ctx = task_info
|
||||
|
||||
# Restore the context in this thread
|
||||
token = context.attach(ctx)
|
||||
try:
|
||||
with self.tracer.start_as_current_span(f"worker_task_{task_id}") as span:
|
||||
time.sleep(0.01) # Simulate work
|
||||
return {
|
||||
"task_id": task_id,
|
||||
"trace_id": span.get_span_context().trace_id,
|
||||
"span_id": span.get_span_context().span_id,
|
||||
"thread_id": threading.get_ident(),
|
||||
"parent_span_id": span.parent.span_id if span.parent else None,
|
||||
}
|
||||
finally:
|
||||
context.detach(token)
|
||||
|
||||
# Create a parent span and capture its context
|
||||
with self.tracer.start_as_current_span("main_task") as main_span:
|
||||
main_trace_id = main_span.get_span_context().trace_id
|
||||
main_span_id = main_span.get_span_context().span_id
|
||||
current_context = context.get_current()
|
||||
|
||||
# Execute tasks in thread pool WITH manual context propagation
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
||||
futures = [executor.submit(worker_task_with_context, (f"task_{i}", current_context)) for i in range(3)]
|
||||
results = [future.result() for future in concurrent.futures.as_completed(futures)]
|
||||
|
||||
spans = self.tester.get_finished_spans()
|
||||
self.assertEqual(len(spans), 4) # 1 main + 3 worker spans
|
||||
|
||||
# Extract trace IDs from results
|
||||
worker_trace_ids = [result["trace_id"] for result in results]
|
||||
|
||||
# All workers should share the same trace ID as the main span
|
||||
for result in results:
|
||||
self.assertEqual(
|
||||
result["trace_id"], main_trace_id, f"Worker task {result['task_id']} should share trace with main span"
|
||||
)
|
||||
self.assertEqual(
|
||||
result["parent_span_id"],
|
||||
main_span_id,
|
||||
f"Worker task {result['task_id']} should have main span as parent",
|
||||
)
|
||||
|
||||
# All worker trace IDs should be the same
|
||||
unique_trace_ids = set(worker_trace_ids)
|
||||
self.assertEqual(len(unique_trace_ids), 1, "All workers should share the same trace")
|
||||
|
||||
def test_threadpool_with_contextvars_copy_context_shares_trace(self):
|
||||
"""Test ThreadPoolExecutor with proper context propagation using attach/detach."""
|
||||
|
||||
def worker_task_with_context_management(args) -> dict:
|
||||
"""Worker task that manages context properly."""
|
||||
task_id, ctx = args
|
||||
# Use attach/detach for better control over context
|
||||
token = context.attach(ctx)
|
||||
try:
|
||||
with self.tracer.start_as_current_span(f"worker_task_{task_id}") as span:
|
||||
time.sleep(0.01) # Simulate work
|
||||
return {
|
||||
"task_id": task_id,
|
||||
"trace_id": span.get_span_context().trace_id,
|
||||
"span_id": span.get_span_context().span_id,
|
||||
"thread_id": threading.get_ident(),
|
||||
"parent_span_id": span.parent.span_id if span.parent else None,
|
||||
}
|
||||
finally:
|
||||
context.detach(token)
|
||||
|
||||
# Create a parent span and capture context properly
|
||||
with self.tracer.start_as_current_span("main_task") as main_span:
|
||||
main_trace_id = main_span.get_span_context().trace_id
|
||||
main_span_id = main_span.get_span_context().span_id
|
||||
|
||||
# Get current context to propagate
|
||||
current_context = context.get_current()
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
||||
futures = [
|
||||
executor.submit(worker_task_with_context_management, (f"task_{i}", current_context))
|
||||
for i in range(3)
|
||||
]
|
||||
results = [future.result() for future in concurrent.futures.as_completed(futures)]
|
||||
|
||||
spans = self.tester.get_finished_spans()
|
||||
self.assertEqual(len(spans), 4) # 1 main + 3 worker spans
|
||||
|
||||
# All workers should share the same trace ID as the main span
|
||||
for result in results:
|
||||
self.assertEqual(
|
||||
result["trace_id"], main_trace_id, f"Worker task {result['task_id']} should share trace with main span"
|
||||
)
|
||||
self.assertEqual(
|
||||
result["parent_span_id"],
|
||||
main_span_id,
|
||||
f"Worker task {result['task_id']} should have main span as parent",
|
||||
)
|
||||
|
||||
def test_mixed_sequential_and_concurrent_spans(self):
|
||||
"""Test a complex scenario with both sequential and concurrent spans."""
|
||||
results = []
|
||||
|
||||
# Sequential span 1
|
||||
trace_id1 = self._create_simple_span("sequential_1")
|
||||
results.append(("sequential_1", trace_id1))
|
||||
|
||||
# Concurrent spans with context propagation
|
||||
with self.tracer.start_as_current_span("concurrent_parent") as parent_span:
|
||||
parent_trace_id = parent_span.get_span_context().trace_id
|
||||
results.append(("concurrent_parent", parent_trace_id))
|
||||
|
||||
def worker_task_with_context(args) -> tuple:
|
||||
task_id, ctx = args
|
||||
token = context.attach(ctx)
|
||||
try:
|
||||
with self.tracer.start_as_current_span(f"concurrent_{task_id}") as span:
|
||||
time.sleep(0.01)
|
||||
return (f"concurrent_{task_id}", span.get_span_context().trace_id)
|
||||
finally:
|
||||
context.detach(token)
|
||||
|
||||
current_context = context.get_current()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||
futures = [executor.submit(worker_task_with_context, (f"task_{i}", current_context)) for i in range(2)]
|
||||
concurrent_results = [future.result() for future in concurrent.futures.as_completed(futures)]
|
||||
results.extend(concurrent_results)
|
||||
|
||||
# Sequential span 2
|
||||
trace_id2 = self._create_simple_span("sequential_2")
|
||||
results.append(("sequential_2", trace_id2))
|
||||
|
||||
spans = self.tester.get_finished_spans()
|
||||
self.assertEqual(len(spans), 5) # 2 sequential + 1 parent + 2 concurrent
|
||||
|
||||
# Verify trace relationships
|
||||
sequential_spans = [r for r in results if r[0].startswith("sequential_")]
|
||||
concurrent_spans = [r for r in results if r[0].startswith("concurrent_")]
|
||||
|
||||
# Sequential spans should have different traces
|
||||
sequential_trace_ids = [r[1] for r in sequential_spans]
|
||||
self.assertEqual(len(set(sequential_trace_ids)), 2, "Sequential spans should have different traces")
|
||||
|
||||
# Concurrent spans should share the same trace
|
||||
concurrent_trace_ids = [r[1] for r in concurrent_spans]
|
||||
unique_concurrent_traces = set(concurrent_trace_ids)
|
||||
self.assertEqual(len(unique_concurrent_traces), 1, "All concurrent spans should share the same trace")
|
||||
|
||||
def test_error_handling_in_concurrent_spans(self):
|
||||
"""Test error handling and span status in concurrent execution."""
|
||||
|
||||
def worker_task_with_error_and_context(args) -> dict:
|
||||
"""Worker task that may raise an error."""
|
||||
task_id, ctx = args
|
||||
token = context.attach(ctx)
|
||||
try:
|
||||
with self.tracer.start_as_current_span(f"worker_task_{task_id}") as span:
|
||||
if task_id == "error_task":
|
||||
span.set_status(trace.Status(trace.StatusCode.ERROR, "Simulated error"))
|
||||
raise ValueError("Simulated error")
|
||||
|
||||
time.sleep(0.01)
|
||||
return {"task_id": task_id, "trace_id": span.get_span_context().trace_id, "status": "success"}
|
||||
finally:
|
||||
context.detach(token)
|
||||
|
||||
with self.tracer.start_as_current_span("main_task") as main_span:
|
||||
main_trace_id = main_span.get_span_context().trace_id
|
||||
current_context = context.get_current()
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
|
||||
futures = [
|
||||
executor.submit(worker_task_with_error_and_context, ("success_task_1", current_context)),
|
||||
executor.submit(worker_task_with_error_and_context, ("error_task", current_context)),
|
||||
executor.submit(worker_task_with_error_and_context, ("success_task_2", current_context)),
|
||||
]
|
||||
|
||||
results = []
|
||||
errors = []
|
||||
for future in concurrent.futures.as_completed(futures):
|
||||
try:
|
||||
results.append(future.result())
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
|
||||
spans = self.tester.get_finished_spans()
|
||||
self.assertEqual(len(spans), 4) # 1 main + 3 worker spans
|
||||
|
||||
# Should have 2 successful results and 1 error
|
||||
self.assertEqual(len(results), 2)
|
||||
self.assertEqual(len(errors), 1)
|
||||
self.assertIn("Simulated error", errors[0])
|
||||
|
||||
# All spans should share the same trace
|
||||
for result in results:
|
||||
self.assertEqual(result["trace_id"], main_trace_id)
|
||||
|
||||
# Find the error span and verify its status
|
||||
error_spans = [s for s in spans if s.name == "worker_task_error_task"]
|
||||
self.assertEqual(len(error_spans), 1)
|
||||
|
||||
error_span = error_spans[0]
|
||||
self.assertEqual(error_span.status.status_code, trace.StatusCode.ERROR)
|
||||
|
||||
@patch("agentops.sdk.processors.logger")
|
||||
def test_internal_span_processor_with_concurrent_spans(self, mock_logger):
|
||||
"""Test InternalSpanProcessor behavior with concurrent spans."""
|
||||
# Create an InternalSpanProcessor to test
|
||||
processor = InternalSpanProcessor()
|
||||
|
||||
# Add the processor to the tracer provider
|
||||
self.tester.tracer_provider.add_span_processor(processor)
|
||||
|
||||
try:
|
||||
|
||||
def worker_task_with_context(args) -> str:
|
||||
task_id, ctx = args
|
||||
token = context.attach(ctx)
|
||||
try:
|
||||
with self.tracer.start_as_current_span(f"openai.chat.completion_{task_id}"):
|
||||
time.sleep(0.01)
|
||||
return f"result_{task_id}"
|
||||
finally:
|
||||
context.detach(token)
|
||||
|
||||
# Execute concurrent tasks
|
||||
with self.tracer.start_as_current_span("main_session"):
|
||||
current_context = context.get_current()
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||
futures = [
|
||||
executor.submit(worker_task_with_context, (f"task_{i}", current_context)) for i in range(2)
|
||||
]
|
||||
results = [future.result() for future in concurrent.futures.as_completed(futures)]
|
||||
|
||||
# Verify results
|
||||
self.assertEqual(len(results), 2)
|
||||
|
||||
# Verify that debug logging would have been called
|
||||
# (The processor tracks root spans and logs when they end)
|
||||
self.assertTrue(mock_logger.debug.called)
|
||||
|
||||
finally:
|
||||
# Clean up the processor to avoid affecting other tests
|
||||
try:
|
||||
processor.shutdown()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def test_performance_impact_of_context_propagation(self):
|
||||
"""Test the performance impact of different context propagation methods."""
|
||||
import timeit
|
||||
|
||||
def without_context_propagation():
|
||||
def worker():
|
||||
with self.tracer.start_as_current_span("test_span"):
|
||||
time.sleep(0.001)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||
futures = [executor.submit(worker) for _ in range(4)]
|
||||
[f.result() for f in futures]
|
||||
|
||||
def with_context_propagation():
|
||||
def worker_with_context(ctx):
|
||||
token = context.attach(ctx)
|
||||
try:
|
||||
with self.tracer.start_as_current_span("test_span"):
|
||||
time.sleep(0.001)
|
||||
finally:
|
||||
context.detach(token)
|
||||
|
||||
current_context = context.get_current()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||
futures = [executor.submit(worker_with_context, current_context) for _ in range(4)]
|
||||
[f.result() for f in futures]
|
||||
|
||||
# Clear spans before performance test
|
||||
self.tester.clear_spans()
|
||||
|
||||
# Measure timing (just to ensure context propagation doesn't break anything)
|
||||
time_without = timeit.timeit(without_context_propagation, number=1)
|
||||
self.tester.clear_spans()
|
||||
|
||||
time_with = timeit.timeit(with_context_propagation, number=1)
|
||||
self.tester.clear_spans()
|
||||
|
||||
# Context propagation should not cause significant performance degradation
|
||||
# This is a sanity check rather than a strict performance requirement
|
||||
self.assertGreater(
|
||||
time_with * 10, time_without, "Context propagation should not cause extreme performance degradation"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,763 @@
|
||||
from typing import AsyncGenerator
|
||||
import asyncio
|
||||
import pytest
|
||||
|
||||
from agentops.sdk.decorators import agent, operation, session, workflow, task, tool
|
||||
from agentops.semconv import SpanKind
|
||||
from agentops.semconv.span_attributes import SpanAttributes
|
||||
from tests.unit.sdk.instrumentation_tester import InstrumentationTester
|
||||
from agentops.sdk.decorators.factory import create_entity_decorator
|
||||
|
||||
|
||||
class TestSpanNesting:
|
||||
"""Tests for proper nesting of spans in the tracing hierarchy."""
|
||||
|
||||
def test_operation_nests_under_agent(self, instrumentation: InstrumentationTester):
|
||||
"""Test that operation spans are properly nested under their agent spans."""
|
||||
|
||||
# Define the test agent with nested operations
|
||||
@agent
|
||||
class NestedAgent:
|
||||
def __init__(self):
|
||||
pass # No logic needed
|
||||
|
||||
@operation
|
||||
def nested_operation(self, message):
|
||||
"""Nested operation that should appear as a child of the agent"""
|
||||
return f"Processed: {message}"
|
||||
|
||||
@operation
|
||||
def main_operation(self):
|
||||
"""Main operation that calls the nested operation"""
|
||||
# Call the nested operation
|
||||
result = self.nested_operation("test message")
|
||||
return result
|
||||
|
||||
# Test session with the agent
|
||||
@session
|
||||
def test_session():
|
||||
agent = NestedAgent()
|
||||
return agent.main_operation()
|
||||
|
||||
# Run the test with our instrumentor
|
||||
result = test_session()
|
||||
|
||||
# Verify the result
|
||||
assert result == "Processed: test message"
|
||||
|
||||
# Get all spans captured during the test
|
||||
spans = instrumentation.get_finished_spans()
|
||||
|
||||
# Print detailed span information for debugging
|
||||
print("\nDetailed span information:")
|
||||
for i, span in enumerate(spans):
|
||||
parent_id = span.parent.span_id if span.parent else "None"
|
||||
span_id = span.context.span_id if span.context else "None"
|
||||
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
|
||||
|
||||
# We should have 4 spans: session, agent, and two operations
|
||||
assert len(spans) == 4
|
||||
|
||||
# Verify span kinds
|
||||
session_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
|
||||
]
|
||||
agent_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
|
||||
]
|
||||
operation_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
|
||||
]
|
||||
|
||||
assert len(session_spans) == 1
|
||||
assert len(agent_spans) == 1
|
||||
assert len(operation_spans) == 2
|
||||
|
||||
# Find the main_operation and nested_operation spans
|
||||
main_operation = None
|
||||
nested_operation = None
|
||||
|
||||
for span in operation_spans:
|
||||
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "main_operation":
|
||||
main_operation = span
|
||||
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "nested_operation":
|
||||
nested_operation = span
|
||||
|
||||
assert main_operation is not None, "main_operation span not found"
|
||||
assert nested_operation is not None, "nested_operation span not found"
|
||||
|
||||
# Verify the session span is the root
|
||||
session_span = session_spans[0]
|
||||
assert session_span.parent is None
|
||||
|
||||
# Verify the agent span is a child of the session span
|
||||
agent_span = agent_spans[0]
|
||||
assert agent_span.parent is not None
|
||||
assert session_span.context is not None
|
||||
assert agent_span.parent.span_id == session_span.context.span_id
|
||||
|
||||
# Verify main_operation is a child of the agent span
|
||||
assert main_operation.parent is not None
|
||||
assert agent_span.context is not None
|
||||
assert main_operation.parent.span_id == agent_span.context.span_id
|
||||
|
||||
# Verify nested_operation is a child of main_operation
|
||||
assert nested_operation.parent is not None
|
||||
assert main_operation.context is not None
|
||||
assert nested_operation.parent.span_id == main_operation.context.span_id
|
||||
|
||||
def test_async_operations(self, instrumentation: InstrumentationTester):
|
||||
"""Test that async operations are properly nested."""
|
||||
|
||||
# Define the test agent with async operations
|
||||
@agent
|
||||
class AsyncAgent:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@operation
|
||||
async def nested_async_operation(self, message):
|
||||
"""Async operation that should appear as a child of the main operation"""
|
||||
await asyncio.sleep(0.01) # Small delay to simulate async work
|
||||
return f"Processed async: {message}"
|
||||
|
||||
@operation
|
||||
async def main_async_operation(self):
|
||||
"""Main async operation that calls the nested async operation"""
|
||||
result = await self.nested_async_operation("test async")
|
||||
return result
|
||||
|
||||
# Test session with the async agent
|
||||
@session
|
||||
async def test_async_session():
|
||||
agent = AsyncAgent()
|
||||
return await agent.main_async_operation()
|
||||
|
||||
# Run the async test
|
||||
result = asyncio.run(test_async_session())
|
||||
|
||||
# Verify the result
|
||||
assert result == "Processed async: test async"
|
||||
|
||||
# Get all spans captured during the test
|
||||
spans = instrumentation.get_finished_spans()
|
||||
|
||||
# Print detailed span information for debugging
|
||||
print("\nDetailed span information for async test:")
|
||||
for i, span in enumerate(spans):
|
||||
parent_id = span.parent.span_id if span.parent else "None"
|
||||
span_id = span.context.span_id if span.context else "None"
|
||||
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
|
||||
|
||||
# We should have 4 spans: session, agent, and two operations
|
||||
assert len(spans) == 4
|
||||
|
||||
# Verify span kinds
|
||||
session_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
|
||||
]
|
||||
agent_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
|
||||
]
|
||||
operation_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
|
||||
]
|
||||
|
||||
assert len(session_spans) == 1
|
||||
assert len(agent_spans) == 1
|
||||
assert len(operation_spans) == 2
|
||||
|
||||
# Find the main_operation and nested_operation spans
|
||||
main_operation = None
|
||||
nested_operation = None
|
||||
|
||||
for span in operation_spans:
|
||||
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "main_async_operation":
|
||||
main_operation = span
|
||||
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "nested_async_operation":
|
||||
nested_operation = span
|
||||
|
||||
assert main_operation is not None, "main_async_operation span not found"
|
||||
assert nested_operation is not None, "nested_async_operation span not found"
|
||||
|
||||
# Verify the session span is the root
|
||||
session_span = session_spans[0]
|
||||
assert session_span.parent is None
|
||||
|
||||
# Verify the agent span is a child of the session span
|
||||
agent_span = agent_spans[0]
|
||||
assert agent_span.parent is not None
|
||||
assert session_span.context is not None
|
||||
assert agent_span.parent.span_id == session_span.context.span_id
|
||||
|
||||
# Verify main_operation is a child of the agent span
|
||||
assert main_operation.parent is not None
|
||||
assert agent_span.context is not None
|
||||
assert main_operation.parent.span_id == agent_span.context.span_id
|
||||
|
||||
# Verify nested_operation is a child of main_operation
|
||||
assert nested_operation.parent is not None
|
||||
assert main_operation.context is not None
|
||||
assert nested_operation.parent.span_id == main_operation.context.span_id
|
||||
|
||||
def test_generator_operations(self, instrumentation: InstrumentationTester):
|
||||
"""Test that generator operations are properly nested."""
|
||||
|
||||
# Define the test agent with generator operations
|
||||
@agent
|
||||
class GeneratorAgent:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@operation
|
||||
def nested_generator(self, count):
|
||||
"""Generator operation that should appear as a child of the main operation"""
|
||||
for i in range(count):
|
||||
yield f"Item {i}"
|
||||
|
||||
@operation
|
||||
def main_generator_operation(self, count):
|
||||
"""Main operation that calls the nested generator"""
|
||||
results = []
|
||||
for item in self.nested_generator(count):
|
||||
results.append(item)
|
||||
return results
|
||||
|
||||
# Test session with the generator agent
|
||||
@session
|
||||
def test_generator_session():
|
||||
agent = GeneratorAgent()
|
||||
return agent.main_generator_operation(3)
|
||||
|
||||
# Run the test
|
||||
result = test_generator_session()
|
||||
|
||||
# Verify the result
|
||||
assert result == ["Item 0", "Item 1", "Item 2"]
|
||||
|
||||
# Get all spans captured during the test
|
||||
spans = instrumentation.get_finished_spans()
|
||||
|
||||
# Print detailed span information for debugging
|
||||
print("\nDetailed span information for generator test:")
|
||||
for i, span in enumerate(spans):
|
||||
parent_id = span.parent.span_id if span.parent else "None"
|
||||
span_id = span.context.span_id if span.context else "None"
|
||||
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
|
||||
|
||||
# We should have 4 spans: session, agent, and two operations
|
||||
assert len(spans) == 4
|
||||
|
||||
# Verify span kinds
|
||||
session_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
|
||||
]
|
||||
agent_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
|
||||
]
|
||||
operation_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
|
||||
]
|
||||
|
||||
assert len(session_spans) == 1
|
||||
assert len(agent_spans) == 1
|
||||
assert len(operation_spans) == 2
|
||||
|
||||
# Find the main_operation and nested_operation spans
|
||||
main_operation = None
|
||||
nested_operation = None
|
||||
|
||||
for span in operation_spans:
|
||||
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "main_generator_operation":
|
||||
main_operation = span
|
||||
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "nested_generator":
|
||||
nested_operation = span
|
||||
|
||||
assert main_operation is not None, "main_generator_operation span not found"
|
||||
assert nested_operation is not None, "nested_generator span not found"
|
||||
|
||||
# Verify the session span is the root
|
||||
session_span = session_spans[0]
|
||||
assert session_span.parent is None
|
||||
|
||||
# Verify the agent span is a child of the session span
|
||||
agent_span = agent_spans[0]
|
||||
assert agent_span.parent is not None
|
||||
assert session_span.context is not None
|
||||
assert agent_span.parent.span_id == session_span.context.span_id
|
||||
|
||||
# Verify main_operation is a child of the agent span
|
||||
assert main_operation.parent is not None
|
||||
assert agent_span.context is not None
|
||||
assert main_operation.parent.span_id == agent_span.context.span_id
|
||||
|
||||
# Verify nested_operation is a child of main_operation
|
||||
assert nested_operation.parent is not None
|
||||
assert main_operation.context is not None
|
||||
assert nested_operation.parent.span_id == main_operation.context.span_id
|
||||
|
||||
def test_async_generator_operations(self, instrumentation: InstrumentationTester):
|
||||
"""Test that async generator operations are properly nested."""
|
||||
|
||||
# Define the test agent with async generator operations
|
||||
@agent
|
||||
class AsyncGeneratorAgent:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@operation
|
||||
async def nested_async_generator(self, count) -> AsyncGenerator[str, None]:
|
||||
"""Async generator operation that should appear as a child of the main operation"""
|
||||
for i in range(count):
|
||||
await asyncio.sleep(0.01) # Small delay to simulate async work
|
||||
yield f"Async Item {i}"
|
||||
|
||||
@operation
|
||||
async def main_async_generator_operation(self, count):
|
||||
"""Main async operation that calls the nested async generator"""
|
||||
results = []
|
||||
async for item in self.nested_async_generator(count):
|
||||
results.append(item)
|
||||
return results
|
||||
|
||||
# Test session with the async generator agent
|
||||
@session
|
||||
async def test_async_generator_session():
|
||||
agent = AsyncGeneratorAgent()
|
||||
return await agent.main_async_generator_operation(3)
|
||||
|
||||
# Run the async test
|
||||
result = asyncio.run(test_async_generator_session())
|
||||
|
||||
# Verify the result
|
||||
assert result == ["Async Item 0", "Async Item 1", "Async Item 2"]
|
||||
|
||||
# Get all spans captured during the test
|
||||
spans = instrumentation.get_finished_spans()
|
||||
|
||||
# Print detailed span information for debugging
|
||||
print("\nDetailed span information for async generator test:")
|
||||
for i, span in enumerate(spans):
|
||||
parent_id = span.parent.span_id if span.parent else "None"
|
||||
span_id = span.context.span_id if span.context else "None"
|
||||
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
|
||||
|
||||
# We should have 4 spans: session, agent, and two operations
|
||||
assert len(spans) == 4
|
||||
|
||||
# Verify span kinds
|
||||
session_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
|
||||
]
|
||||
agent_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
|
||||
]
|
||||
operation_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
|
||||
]
|
||||
|
||||
assert len(session_spans) == 1
|
||||
assert len(agent_spans) == 1
|
||||
assert len(operation_spans) == 2
|
||||
|
||||
# Find the main_operation and nested_operation spans
|
||||
main_operation = None
|
||||
nested_operation = None
|
||||
|
||||
for span in operation_spans:
|
||||
if (
|
||||
span.attributes
|
||||
and span.attributes.get(SpanAttributes.OPERATION_NAME) == "main_async_generator_operation"
|
||||
):
|
||||
main_operation = span
|
||||
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "nested_async_generator":
|
||||
nested_operation = span
|
||||
|
||||
assert main_operation is not None, "main_async_generator_operation span not found"
|
||||
assert nested_operation is not None, "nested_async_generator span not found"
|
||||
|
||||
# Verify the session span is the root
|
||||
session_span = session_spans[0]
|
||||
assert session_span.parent is None
|
||||
|
||||
# Verify the agent span is a child of the session span
|
||||
agent_span = agent_spans[0]
|
||||
assert agent_span.parent is not None
|
||||
assert session_span.context is not None
|
||||
assert agent_span.parent.span_id == session_span.context.span_id
|
||||
|
||||
# Verify main_operation is a child of the agent span
|
||||
assert main_operation.parent is not None
|
||||
assert agent_span.context is not None
|
||||
assert main_operation.parent.span_id == agent_span.context.span_id
|
||||
|
||||
# Verify nested_operation is a child of main_operation
|
||||
assert nested_operation.parent is not None
|
||||
assert main_operation.context is not None
|
||||
assert nested_operation.parent.span_id == main_operation.context.span_id
|
||||
|
||||
def test_complex_nesting(self, instrumentation: InstrumentationTester):
|
||||
"""Test complex nesting with multiple levels of operations."""
|
||||
|
||||
# Define the test agent with complex nesting
|
||||
@agent
|
||||
class ComplexAgent:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@operation
|
||||
def level3_operation(self, message):
|
||||
"""Level 3 operation (deepest)"""
|
||||
return f"Level 3: {message}"
|
||||
|
||||
@operation
|
||||
def level2_operation(self, message):
|
||||
"""Level 2 operation that calls level 3"""
|
||||
result = self.level3_operation(message)
|
||||
return f"Level 2: {result}"
|
||||
|
||||
@operation
|
||||
def level1_operation(self, message):
|
||||
"""Level 1 operation that calls level 2"""
|
||||
result = self.level2_operation(message)
|
||||
return f"Level 1: {result}"
|
||||
|
||||
# Test session with the complex agent
|
||||
@session
|
||||
def test_complex_session():
|
||||
agent = ComplexAgent()
|
||||
return agent.level1_operation("test message")
|
||||
|
||||
# Run the test
|
||||
result = test_complex_session()
|
||||
|
||||
# Verify the result
|
||||
assert result == "Level 1: Level 2: Level 3: test message"
|
||||
|
||||
# Get all spans captured during the test
|
||||
spans = instrumentation.get_finished_spans()
|
||||
|
||||
# Print detailed span information for debugging
|
||||
print("\nDetailed span information for complex nesting test:")
|
||||
for i, span in enumerate(spans):
|
||||
parent_id = span.parent.span_id if span.parent else "None"
|
||||
span_id = span.context.span_id if span.context else "None"
|
||||
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
|
||||
|
||||
# We should have 5 spans: session, agent, and three operations
|
||||
assert len(spans) == 5
|
||||
|
||||
# Verify span kinds
|
||||
session_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
|
||||
]
|
||||
agent_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.AGENT
|
||||
]
|
||||
operation_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
|
||||
]
|
||||
|
||||
assert len(session_spans) == 1
|
||||
assert len(agent_spans) == 1
|
||||
assert len(operation_spans) == 3
|
||||
|
||||
# Find the operation spans
|
||||
level1_operation = None
|
||||
level2_operation = None
|
||||
level3_operation = None
|
||||
|
||||
for span in operation_spans:
|
||||
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "level1_operation":
|
||||
level1_operation = span
|
||||
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "level2_operation":
|
||||
level2_operation = span
|
||||
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "level3_operation":
|
||||
level3_operation = span
|
||||
|
||||
assert level1_operation is not None, "level1_operation span not found"
|
||||
assert level2_operation is not None, "level2_operation span not found"
|
||||
assert level3_operation is not None, "level3_operation span not found"
|
||||
|
||||
# Verify the session span is the root
|
||||
session_span = session_spans[0]
|
||||
assert session_span.parent is None
|
||||
|
||||
# Verify the agent span is a child of the session span
|
||||
agent_span = agent_spans[0]
|
||||
assert agent_span.parent is not None
|
||||
assert session_span.context is not None
|
||||
assert agent_span.parent.span_id == session_span.context.span_id
|
||||
|
||||
# Verify level1_operation is a child of the agent span
|
||||
assert level1_operation.parent is not None
|
||||
assert agent_span.context is not None
|
||||
assert level1_operation.parent.span_id == agent_span.context.span_id
|
||||
|
||||
# Verify level2_operation is a child of level1_operation
|
||||
assert level2_operation.parent is not None
|
||||
assert level1_operation.context is not None
|
||||
assert level2_operation.parent.span_id == level1_operation.context.span_id
|
||||
|
||||
# Verify level3_operation is a child of level2_operation
|
||||
assert level3_operation.parent is not None
|
||||
assert level2_operation.context is not None
|
||||
assert level3_operation.parent.span_id == level2_operation.context.span_id
|
||||
|
||||
def test_workflow_and_task_nesting(self, instrumentation: InstrumentationTester):
|
||||
"""Test that workflow and task decorators create proper span nesting."""
|
||||
|
||||
# Define a workflow with tasks
|
||||
@workflow
|
||||
def data_processing_workflow(data):
|
||||
"""Main workflow that processes data through multiple tasks"""
|
||||
result = process_input(data)
|
||||
result = transform_data(result)
|
||||
return result
|
||||
|
||||
@task
|
||||
def process_input(data):
|
||||
"""Task to process input data"""
|
||||
return f"Processed: {data}"
|
||||
|
||||
@task
|
||||
def transform_data(data):
|
||||
"""Task to transform processed data"""
|
||||
return f"Transformed: {data}"
|
||||
|
||||
# Test session with the workflow
|
||||
@session
|
||||
def test_workflow_session():
|
||||
return data_processing_workflow("test data")
|
||||
|
||||
# Run the test
|
||||
result = test_workflow_session()
|
||||
|
||||
# Verify the result
|
||||
assert result == "Transformed: Processed: test data"
|
||||
|
||||
# Get all spans captured during the test
|
||||
spans = instrumentation.get_finished_spans()
|
||||
|
||||
# Print detailed span information for debugging
|
||||
print("\nDetailed span information for workflow and task test:")
|
||||
for i, span in enumerate(spans):
|
||||
parent_id = span.parent.span_id if span.parent else "None"
|
||||
span_id = span.context.span_id if span.context else "None"
|
||||
print(f"Span {i}: name={span.name}, span_id={span_id}, parent_id={parent_id}")
|
||||
|
||||
# We should have 4 spans: session, workflow, and two tasks
|
||||
assert len(spans) == 4
|
||||
|
||||
# Verify span kinds
|
||||
session_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.SESSION
|
||||
]
|
||||
workflow_spans = [
|
||||
s
|
||||
for s in spans
|
||||
if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.WORKFLOW
|
||||
]
|
||||
task_spans = [
|
||||
s for s in spans if s.attributes and s.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TASK
|
||||
]
|
||||
|
||||
assert len(session_spans) == 1
|
||||
assert len(workflow_spans) == 1
|
||||
assert len(task_spans) == 2
|
||||
|
||||
# Find the workflow and task spans
|
||||
workflow_span = None
|
||||
process_task = None
|
||||
transform_task = None
|
||||
|
||||
for span in spans:
|
||||
if span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "data_processing_workflow":
|
||||
workflow_span = span
|
||||
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "process_input":
|
||||
process_task = span
|
||||
elif span.attributes and span.attributes.get(SpanAttributes.OPERATION_NAME) == "transform_data":
|
||||
transform_task = span
|
||||
|
||||
assert workflow_span is not None, "workflow span not found"
|
||||
assert process_task is not None, "process_input task span not found"
|
||||
assert transform_task is not None, "transform_data task span not found"
|
||||
|
||||
# Verify the session span is the root
|
||||
session_span = session_spans[0]
|
||||
assert session_span.parent is None
|
||||
|
||||
# Verify the workflow span is a child of the session span
|
||||
assert workflow_span.parent is not None
|
||||
assert session_span.context is not None
|
||||
assert workflow_span.parent.span_id == session_span.context.span_id
|
||||
|
||||
# Verify process_task is a child of the workflow span
|
||||
assert process_task.parent is not None
|
||||
assert workflow_span.context is not None
|
||||
assert process_task.parent.span_id == workflow_span.context.span_id
|
||||
|
||||
# Verify transform_task is a child of the workflow span
|
||||
assert transform_task.parent is not None
|
||||
assert workflow_span.context is not None
|
||||
assert transform_task.parent.span_id == workflow_span.context.span_id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_context_manager():
|
||||
"""
|
||||
Tests async context manager functionality (__aenter__, __aexit__).
|
||||
"""
|
||||
|
||||
# Create a simple decorated class
|
||||
@create_entity_decorator("test")
|
||||
class TestClass:
|
||||
def __init__(self):
|
||||
self.value = 42
|
||||
|
||||
# Cover __aenter__ and __aexit__ (normal exit)
|
||||
async with TestClass() as instance:
|
||||
assert hasattr(instance, "_agentops_active_span")
|
||||
assert instance._agentops_active_span is not None
|
||||
|
||||
# Cover __aenter__ and __aexit__ (exceptional exit)
|
||||
with pytest.raises(ValueError):
|
||||
async with TestClass() as instance:
|
||||
raise ValueError("Trigger exception for __aexit__ coverage")
|
||||
|
||||
|
||||
class TestToolDecorator:
|
||||
"""Tests for the tool decorator functionality."""
|
||||
|
||||
@pytest.fixture
|
||||
def agent_class(self):
|
||||
@agent
|
||||
class TestAgent:
|
||||
@tool(cost=0.01)
|
||||
def process_item(self, item):
|
||||
return f"Processed {item}"
|
||||
|
||||
@tool(cost=0.02)
|
||||
async def async_process_item(self, item):
|
||||
await asyncio.sleep(0.1)
|
||||
return f"Async processed {item}"
|
||||
|
||||
@tool(cost=0.03)
|
||||
def generator_process_items(self, items):
|
||||
for item in items:
|
||||
yield self.process_item(item)
|
||||
|
||||
@tool(cost=0.04)
|
||||
async def async_generator_process_items(self, items):
|
||||
for item in items:
|
||||
await asyncio.sleep(0.1)
|
||||
yield await self.async_process_item(item)
|
||||
|
||||
return TestAgent()
|
||||
|
||||
def test_sync_tool_cost(self, agent_class, instrumentation: InstrumentationTester):
|
||||
"""Test synchronous tool with cost attribute."""
|
||||
result = agent_class.process_item("test")
|
||||
|
||||
assert result == "Processed test"
|
||||
|
||||
spans = instrumentation.get_finished_spans()
|
||||
tool_span = next(
|
||||
span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL
|
||||
)
|
||||
assert tool_span.attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.01
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_tool_cost(self, agent_class, instrumentation: InstrumentationTester):
|
||||
"""Test asynchronous tool with cost attribute."""
|
||||
result = await agent_class.async_process_item("test")
|
||||
|
||||
assert result == "Async processed test"
|
||||
|
||||
spans = instrumentation.get_finished_spans()
|
||||
tool_span = next(
|
||||
span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL
|
||||
)
|
||||
assert tool_span.attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.02
|
||||
|
||||
def test_generator_tool_cost(self, agent_class, instrumentation: InstrumentationTester):
|
||||
"""Test generator tool with cost attribute."""
|
||||
items = ["item1", "item2", "item3"]
|
||||
results = list(agent_class.generator_process_items(items))
|
||||
|
||||
assert len(results) == 3
|
||||
assert results[0] == "Processed item1"
|
||||
assert results[1] == "Processed item2"
|
||||
assert results[2] == "Processed item3"
|
||||
|
||||
spans = instrumentation.get_finished_spans()
|
||||
tool_spans = [span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL]
|
||||
assert len(tool_spans) == 4 # Only one span for the generator
|
||||
assert tool_spans[0].attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.01
|
||||
assert tool_spans[3].attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.03
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_generator_tool_cost(self, agent_class, instrumentation: InstrumentationTester):
|
||||
"""Test async generator tool with cost attribute."""
|
||||
items = ["item1", "item2", "item3"]
|
||||
results = [result async for result in agent_class.async_generator_process_items(items)]
|
||||
|
||||
assert len(results) == 3
|
||||
assert results[0] == "Async processed item1"
|
||||
assert results[1] == "Async processed item2"
|
||||
assert results[2] == "Async processed item3"
|
||||
|
||||
spans = instrumentation.get_finished_spans()
|
||||
tool_span = [span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL]
|
||||
assert len(tool_span) == 4 # Only one span for the generator
|
||||
assert tool_span[0].attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.02
|
||||
assert tool_span[3].attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.04
|
||||
|
||||
def test_multiple_tool_calls(self, agent_class, instrumentation: InstrumentationTester):
|
||||
"""Test multiple calls to the same tool."""
|
||||
for i in range(3):
|
||||
result = agent_class.process_item(f"item{i}")
|
||||
assert result == f"Processed item{i}"
|
||||
|
||||
spans = instrumentation.get_finished_spans()
|
||||
tool_spans = [span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL]
|
||||
assert len(tool_spans) == 3
|
||||
for span in tool_spans:
|
||||
assert span.attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.01
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_parallel_tool_calls(self, agent_class, instrumentation: InstrumentationTester):
|
||||
"""Test parallel execution of async tools."""
|
||||
results = await asyncio.gather(
|
||||
agent_class.async_process_item("item1"),
|
||||
agent_class.async_process_item("item2"),
|
||||
agent_class.async_process_item("item3"),
|
||||
)
|
||||
|
||||
assert len(results) == 3
|
||||
assert results[0] == "Async processed item1"
|
||||
assert results[1] == "Async processed item2"
|
||||
assert results[2] == "Async processed item3"
|
||||
|
||||
spans = instrumentation.get_finished_spans()
|
||||
tool_spans = [span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL]
|
||||
assert len(tool_spans) == 3
|
||||
for span in tool_spans:
|
||||
assert span.attributes.get(SpanAttributes.LLM_USAGE_TOOL_COST) == 0.02
|
||||
|
||||
def test_tool_without_cost(self, agent_class, instrumentation: InstrumentationTester):
|
||||
"""Test tool without cost parameter."""
|
||||
|
||||
@tool
|
||||
def no_cost_tool(self):
|
||||
return "No cost tool result"
|
||||
|
||||
result = no_cost_tool(agent_class)
|
||||
|
||||
assert result == "No cost tool result"
|
||||
|
||||
spans = instrumentation.get_finished_spans()
|
||||
tool_span = next(
|
||||
span for span in spans if span.attributes.get(SpanAttributes.AGENTOPS_SPAN_KIND) == SpanKind.TOOL
|
||||
)
|
||||
assert SpanAttributes.LLM_USAGE_TOOL_COST not in tool_span.attributes
|
||||
@@ -0,0 +1,260 @@
|
||||
"""
|
||||
Unit tests for AuthenticatedOTLPExporter.
|
||||
"""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import requests
|
||||
from opentelemetry.sdk.trace import ReadableSpan
|
||||
from opentelemetry.sdk.trace.export import SpanExportResult
|
||||
from opentelemetry.exporter.otlp.proto.http import Compression
|
||||
|
||||
from agentops.sdk.exporters import AuthenticatedOTLPExporter
|
||||
from agentops.exceptions import AgentOpsApiJwtExpiredException, ApiServerException
|
||||
|
||||
# these are simple tests on a simple file, basically just to get test coverage
|
||||
|
||||
|
||||
class TestAuthenticatedOTLPExporter(unittest.TestCase):
|
||||
"""Tests for AuthenticatedOTLPExporter class."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
self.endpoint = "https://api.agentops.ai/v1/traces"
|
||||
self.jwt = "test-jwt-token"
|
||||
self.timeout = 30
|
||||
self.compression = Compression.Gzip
|
||||
self.custom_headers = {"X-Custom-Header": "test-value"}
|
||||
|
||||
def test_initialization_with_required_params(self):
|
||||
"""Test exporter initialization with required parameters."""
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
# Verify the exporter was created successfully
|
||||
self.assertIsInstance(exporter, AuthenticatedOTLPExporter)
|
||||
self.assertEqual(exporter._endpoint, self.endpoint)
|
||||
|
||||
def test_initialization_with_all_params(self):
|
||||
"""Test exporter initialization with all parameters."""
|
||||
exporter = AuthenticatedOTLPExporter(
|
||||
endpoint=self.endpoint,
|
||||
jwt=self.jwt,
|
||||
headers=self.custom_headers,
|
||||
timeout=self.timeout,
|
||||
compression=self.compression,
|
||||
)
|
||||
|
||||
# Verify the exporter was created successfully
|
||||
self.assertIsInstance(exporter, AuthenticatedOTLPExporter)
|
||||
self.assertEqual(exporter._endpoint, self.endpoint)
|
||||
|
||||
def test_initialization_without_optional_params(self):
|
||||
"""Test exporter initialization without optional parameters."""
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
# Verify the exporter was created successfully
|
||||
self.assertIsInstance(exporter, AuthenticatedOTLPExporter)
|
||||
self.assertEqual(exporter._endpoint, self.endpoint)
|
||||
|
||||
def test_export_success(self):
|
||||
"""Test successful span export."""
|
||||
mock_spans = [Mock(spec=ReadableSpan), Mock(spec=ReadableSpan)]
|
||||
|
||||
with patch("opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter.export") as mock_export:
|
||||
mock_export.return_value = SpanExportResult.SUCCESS
|
||||
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
result = exporter.export(mock_spans)
|
||||
|
||||
# Verify the result
|
||||
self.assertEqual(result, SpanExportResult.SUCCESS)
|
||||
|
||||
def test_export_jwt_expired_exception(self):
|
||||
"""Test export handling of JWT expired exception."""
|
||||
mock_spans = [Mock(spec=ReadableSpan)]
|
||||
|
||||
with patch("opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter.export") as mock_export:
|
||||
mock_export.side_effect = AgentOpsApiJwtExpiredException("Token expired")
|
||||
|
||||
with patch("agentops.sdk.exporters.logger") as mock_logger:
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
result = exporter.export(mock_spans)
|
||||
|
||||
# Verify failure result and logging
|
||||
self.assertEqual(result, SpanExportResult.FAILURE)
|
||||
mock_logger.warning.assert_called_once()
|
||||
|
||||
def test_export_api_server_exception(self):
|
||||
"""Test export handling of API server exception."""
|
||||
mock_spans = [Mock(spec=ReadableSpan)]
|
||||
|
||||
with patch("opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter.export") as mock_export:
|
||||
mock_export.side_effect = ApiServerException("Server error")
|
||||
|
||||
with patch("agentops.sdk.exporters.logger") as mock_logger:
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
result = exporter.export(mock_spans)
|
||||
|
||||
# Verify failure result and logging
|
||||
self.assertEqual(result, SpanExportResult.FAILURE)
|
||||
mock_logger.error.assert_called_once()
|
||||
|
||||
def test_export_requests_exception(self):
|
||||
"""Test export handling of requests exception."""
|
||||
mock_spans = [Mock(spec=ReadableSpan)]
|
||||
|
||||
with patch("opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter.export") as mock_export:
|
||||
mock_export.side_effect = requests.RequestException("Network error")
|
||||
|
||||
with patch("agentops.sdk.exporters.logger") as mock_logger:
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
result = exporter.export(mock_spans)
|
||||
|
||||
# Verify failure result and logging
|
||||
self.assertEqual(result, SpanExportResult.FAILURE)
|
||||
mock_logger.error.assert_called_once()
|
||||
|
||||
def test_export_unexpected_exception(self):
|
||||
"""Test export handling of unexpected exception."""
|
||||
mock_spans = [Mock(spec=ReadableSpan)]
|
||||
|
||||
with patch("opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter.export") as mock_export:
|
||||
mock_export.side_effect = ValueError("Unexpected error")
|
||||
|
||||
with patch("agentops.sdk.exporters.logger") as mock_logger:
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
result = exporter.export(mock_spans)
|
||||
|
||||
# Verify failure result and logging
|
||||
self.assertEqual(result, SpanExportResult.FAILURE)
|
||||
mock_logger.error.assert_called_once()
|
||||
|
||||
def test_export_empty_spans_list(self):
|
||||
"""Test export with empty spans list."""
|
||||
mock_spans = []
|
||||
|
||||
with patch("opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter.export") as mock_export:
|
||||
mock_export.return_value = SpanExportResult.SUCCESS
|
||||
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
result = exporter.export(mock_spans)
|
||||
|
||||
# Verify the result
|
||||
self.assertEqual(result, SpanExportResult.SUCCESS)
|
||||
|
||||
def test_clear_method(self):
|
||||
"""Test clear method (should be a no-op)."""
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
# Clear method should not raise any exception
|
||||
exporter.clear()
|
||||
|
||||
def test_initialization_with_kwargs(self):
|
||||
"""Test exporter initialization with additional kwargs."""
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt, custom_param="test_value")
|
||||
|
||||
# Verify the exporter was created successfully
|
||||
self.assertIsInstance(exporter, AuthenticatedOTLPExporter)
|
||||
|
||||
def test_headers_merging(self):
|
||||
"""Test that custom headers are properly merged with authorization header."""
|
||||
custom_headers = {"X-Custom-Header": "test-value", "Content-Type": "application/json"}
|
||||
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt, headers=custom_headers)
|
||||
|
||||
# Verify the exporter was created successfully
|
||||
self.assertIsInstance(exporter, AuthenticatedOTLPExporter)
|
||||
|
||||
def test_headers_protected_from_override(self):
|
||||
"""Test that critical headers cannot be overridden by user-supplied headers."""
|
||||
# Attempt to override critical headers
|
||||
malicious_headers = {
|
||||
"Authorization": "Malicious-Auth malicious-token",
|
||||
"Content-Type": "text/plain",
|
||||
"User-Agent": "malicious-agent",
|
||||
"X-API-Key": "malicious-key",
|
||||
"X-Custom-Header": "test-value", # This should be allowed
|
||||
}
|
||||
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt, headers=malicious_headers)
|
||||
|
||||
# Test the _prepare_headers method directly to verify protection
|
||||
prepared_headers = exporter._prepare_headers(malicious_headers)
|
||||
|
||||
# Critical headers should not be overridden
|
||||
self.assertEqual(prepared_headers["Authorization"], f"Bearer {self.jwt}")
|
||||
self.assertNotEqual(prepared_headers.get("Content-Type"), "text/plain")
|
||||
self.assertNotEqual(prepared_headers.get("User-Agent"), "malicious-agent")
|
||||
self.assertNotIn("X-API-Key", prepared_headers) # Should be filtered out
|
||||
|
||||
# Non-critical headers should be allowed
|
||||
self.assertEqual(prepared_headers.get("X-Custom-Header"), "test-value")
|
||||
|
||||
# Verify the exporter was created successfully
|
||||
self.assertIsInstance(exporter, AuthenticatedOTLPExporter)
|
||||
|
||||
|
||||
class TestAuthenticatedOTLPExporterIntegration(unittest.TestCase):
|
||||
"""Integration-style tests for AuthenticatedOTLPExporter."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures."""
|
||||
self.endpoint = "https://api.agentops.ai/v1/traces"
|
||||
self.jwt = "test-jwt-token"
|
||||
|
||||
def test_full_export_cycle(self):
|
||||
"""Test a complete export cycle with multiple spans."""
|
||||
# Create mock spans
|
||||
mock_spans = [
|
||||
Mock(spec=ReadableSpan, name="span1"),
|
||||
Mock(spec=ReadableSpan, name="span2"),
|
||||
Mock(spec=ReadableSpan, name="span3"),
|
||||
]
|
||||
|
||||
with patch("opentelemetry.exporter.otlp.proto.http.trace_exporter.OTLPSpanExporter.export") as mock_export:
|
||||
mock_export.return_value = SpanExportResult.SUCCESS
|
||||
|
||||
# Create exporter
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt)
|
||||
|
||||
# Export spans
|
||||
result = exporter.export(mock_spans)
|
||||
|
||||
# Verify results
|
||||
self.assertEqual(result, SpanExportResult.SUCCESS)
|
||||
|
||||
# Test clear method
|
||||
exporter.clear() # Should not raise any exception
|
||||
|
||||
def test_export_with_different_compression_types(self):
|
||||
"""Test exporter with different compression types."""
|
||||
compression_types = [Compression.Gzip, Compression.Deflate, None]
|
||||
|
||||
for compression in compression_types:
|
||||
with self.subTest(compression=compression):
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt, compression=compression)
|
||||
|
||||
# Verify the exporter was created successfully
|
||||
self.assertIsInstance(exporter, AuthenticatedOTLPExporter)
|
||||
|
||||
def test_export_with_different_timeouts(self):
|
||||
"""Test exporter with different timeout values."""
|
||||
timeout_values = [10, 30, 60, None]
|
||||
|
||||
for timeout in timeout_values:
|
||||
with self.subTest(timeout=timeout):
|
||||
exporter = AuthenticatedOTLPExporter(endpoint=self.endpoint, jwt=self.jwt, timeout=timeout)
|
||||
|
||||
# Verify the exporter was created successfully
|
||||
self.assertIsInstance(exporter, AuthenticatedOTLPExporter)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,397 @@
|
||||
"""
|
||||
Unit tests for URL logging functionality and InternalSpanProcessor.
|
||||
"""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from opentelemetry.sdk.trace import Span, ReadableSpan
|
||||
|
||||
from agentops.sdk.processors import InternalSpanProcessor
|
||||
from agentops.sdk.core import TraceContext, tracer
|
||||
|
||||
|
||||
class TestURLLogging(unittest.TestCase):
|
||||
"""Tests for URL logging functionality in global tracer."""
|
||||
|
||||
def setUp(self):
|
||||
self.tracing_core = tracer
|
||||
# Mock the initialization to avoid actual setup
|
||||
self.tracing_core._initialized = True
|
||||
self.tracing_core._config = {"project_id": "test_project"}
|
||||
|
||||
@patch("agentops.sdk.core.log_trace_url")
|
||||
@patch("agentops.sdk.core.tracer.make_span")
|
||||
def test_start_trace_logs_url(self, mock_make_span, mock_log_trace_url):
|
||||
"""Test that start_trace logs the trace URL."""
|
||||
# Create a mock span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_context = MagicMock()
|
||||
mock_token = MagicMock()
|
||||
mock_span.get_span_context.return_value.span_id = 12345
|
||||
mock_make_span.return_value = (mock_span, mock_context, mock_token)
|
||||
|
||||
# Call start_trace
|
||||
trace_context = self.tracing_core.start_trace(trace_name="test_trace")
|
||||
|
||||
# Assert that log_trace_url was called with the span and title
|
||||
mock_log_trace_url.assert_called_once_with(mock_span, title="test_trace")
|
||||
self.assertIsInstance(trace_context, TraceContext)
|
||||
self.assertEqual(trace_context.span, mock_span)
|
||||
|
||||
@patch("agentops.sdk.core.log_trace_url")
|
||||
@patch("agentops.sdk.core.tracer.finalize_span")
|
||||
def test_end_trace_logs_url(self, mock_finalize_span, mock_log_trace_url):
|
||||
"""Test that end_trace logs the trace URL."""
|
||||
# Create a mock trace context
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_span.name = "test_trace"
|
||||
mock_span.get_span_context.return_value.span_id = 12345
|
||||
mock_token = MagicMock()
|
||||
trace_context = TraceContext(mock_span, mock_token)
|
||||
|
||||
# Call end_trace
|
||||
self.tracing_core.end_trace(trace_context, "Success")
|
||||
|
||||
# Assert that log_trace_url was called with the span and title
|
||||
mock_log_trace_url.assert_called_once_with(mock_span, title="test_trace")
|
||||
|
||||
@patch("agentops.sdk.core.log_trace_url")
|
||||
@patch("agentops.sdk.core.tracer.make_span")
|
||||
def test_start_trace_url_logging_failure_does_not_break_trace(self, mock_make_span, mock_log_trace_url):
|
||||
"""Test that URL logging failure doesn't break trace creation."""
|
||||
# Create a mock span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_context = MagicMock()
|
||||
mock_token = MagicMock()
|
||||
mock_span.get_span_context.return_value.span_id = 12345
|
||||
mock_make_span.return_value = (mock_span, mock_context, mock_token)
|
||||
|
||||
# Make log_trace_url raise an exception
|
||||
mock_log_trace_url.side_effect = Exception("URL logging failed")
|
||||
|
||||
# Call start_trace - should not raise exception
|
||||
trace_context = self.tracing_core.start_trace(trace_name="test_trace")
|
||||
|
||||
# Assert that trace was still created successfully
|
||||
self.assertIsInstance(trace_context, TraceContext)
|
||||
self.assertEqual(trace_context.span, mock_span)
|
||||
mock_log_trace_url.assert_called_once_with(mock_span, title="test_trace")
|
||||
|
||||
@patch("agentops.sdk.core.log_trace_url")
|
||||
@patch("agentops.sdk.core.tracer.finalize_span")
|
||||
def test_end_trace_url_logging_failure_does_not_break_trace(self, mock_finalize_span, mock_log_trace_url):
|
||||
"""Test that URL logging failure doesn't break trace ending."""
|
||||
# Create a mock trace context
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_span.name = "test_trace"
|
||||
mock_span.get_span_context.return_value.span_id = 12345
|
||||
mock_token = MagicMock()
|
||||
trace_context = TraceContext(mock_span, mock_token)
|
||||
|
||||
# Make log_trace_url raise an exception
|
||||
mock_log_trace_url.side_effect = Exception("URL logging failed")
|
||||
|
||||
# Call end_trace - should not raise exception
|
||||
self.tracing_core.end_trace(trace_context, "Success")
|
||||
|
||||
# Assert that finalize_span was still called
|
||||
mock_finalize_span.assert_called_once()
|
||||
mock_log_trace_url.assert_called_once_with(mock_span, title="test_trace")
|
||||
|
||||
@patch("agentops.sdk.core.log_trace_url")
|
||||
@patch("agentops.sdk.core.tracer.make_span")
|
||||
def test_start_trace_with_tags_logs_url(self, mock_make_span, mock_log_trace_url):
|
||||
"""Test that start_trace with tags logs the trace URL."""
|
||||
# Create a mock span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_context = MagicMock()
|
||||
mock_token = MagicMock()
|
||||
mock_span.get_span_context.return_value.span_id = 12345
|
||||
mock_make_span.return_value = (mock_span, mock_context, mock_token)
|
||||
|
||||
# Call start_trace with tags
|
||||
trace_context = self.tracing_core.start_trace(trace_name="tagged_trace", tags=["test", "integration"])
|
||||
|
||||
# Assert that log_trace_url was called with the span and title
|
||||
mock_log_trace_url.assert_called_once_with(mock_span, title="tagged_trace")
|
||||
self.assertIsInstance(trace_context, TraceContext)
|
||||
|
||||
|
||||
class TestSessionDecoratorURLLogging(unittest.TestCase):
|
||||
"""Tests for URL logging functionality in session decorators."""
|
||||
|
||||
def setUp(self):
|
||||
self.tracing_core = tracer
|
||||
# Mock the initialization to avoid actual setup
|
||||
self.tracing_core._initialized = True
|
||||
self.tracing_core._config = {"project_id": "test_project"}
|
||||
|
||||
@patch("agentops.sdk.core.log_trace_url")
|
||||
@patch("agentops.sdk.core.tracer.make_span")
|
||||
@patch("agentops.sdk.core.tracer.finalize_span")
|
||||
def test_session_decorator_logs_url_on_start_and_end(self, mock_finalize_span, mock_make_span, mock_log_trace_url):
|
||||
"""Test that session decorator logs URLs on both start and end."""
|
||||
from agentops.sdk.decorators import session
|
||||
|
||||
# Create a mock span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_span.name = "test_function"
|
||||
mock_context = MagicMock()
|
||||
mock_token = MagicMock()
|
||||
mock_span.get_span_context.return_value.span_id = 12345
|
||||
mock_make_span.return_value = (mock_span, mock_context, mock_token)
|
||||
|
||||
@session(name="test_session")
|
||||
def test_function():
|
||||
return "test_result"
|
||||
|
||||
# Call the decorated function
|
||||
result = test_function()
|
||||
|
||||
# Assert that log_trace_url was called (start and end)
|
||||
# Note: The actual number of calls may vary based on implementation details
|
||||
self.assertGreaterEqual(mock_log_trace_url.call_count, 2)
|
||||
# Verify that the calls include the expected session name
|
||||
call_args_list = [
|
||||
call_args[1]["title"] for call_args in mock_log_trace_url.call_args_list if "title" in call_args[1]
|
||||
]
|
||||
self.assertIn("test_session", call_args_list)
|
||||
self.assertEqual(result, "test_result")
|
||||
|
||||
@patch("agentops.sdk.core.log_trace_url")
|
||||
@patch("agentops.sdk.core.tracer.make_span")
|
||||
@patch("agentops.sdk.core.tracer.finalize_span")
|
||||
def test_session_decorator_with_default_name_logs_url(self, mock_finalize_span, mock_make_span, mock_log_trace_url):
|
||||
"""Test that session decorator with default name logs URLs."""
|
||||
from agentops.sdk.decorators import session
|
||||
|
||||
# Create a mock span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_span.name = "my_function"
|
||||
mock_context = MagicMock()
|
||||
mock_token = MagicMock()
|
||||
mock_span.get_span_context.return_value.span_id = 12345
|
||||
mock_make_span.return_value = (mock_span, mock_context, mock_token)
|
||||
|
||||
@session
|
||||
def my_function():
|
||||
return "result"
|
||||
|
||||
# Call the decorated function
|
||||
result = my_function()
|
||||
|
||||
# Assert that log_trace_url was called with function name as title
|
||||
self.assertGreaterEqual(mock_log_trace_url.call_count, 2)
|
||||
# Verify that the calls include the expected function name
|
||||
call_args_list = [
|
||||
call_args[1]["title"] for call_args in mock_log_trace_url.call_args_list if "title" in call_args[1]
|
||||
]
|
||||
self.assertIn("my_function", call_args_list)
|
||||
self.assertEqual(result, "result")
|
||||
|
||||
@patch("agentops.sdk.core.log_trace_url")
|
||||
@patch("agentops.sdk.core.tracer.make_span")
|
||||
@patch("agentops.sdk.core.tracer.finalize_span")
|
||||
def test_session_decorator_handles_url_logging_failure(
|
||||
self, mock_finalize_span, mock_make_span, mock_log_trace_url
|
||||
):
|
||||
"""Test that session decorator handles URL logging failures gracefully."""
|
||||
from agentops.sdk.decorators import session
|
||||
|
||||
# Create a mock span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_span.name = "test_function"
|
||||
mock_context = MagicMock()
|
||||
mock_token = MagicMock()
|
||||
mock_span.get_span_context.return_value.span_id = 12345
|
||||
mock_make_span.return_value = (mock_span, mock_context, mock_token)
|
||||
|
||||
# Make log_trace_url raise an exception
|
||||
mock_log_trace_url.side_effect = Exception("URL logging failed")
|
||||
|
||||
@session(name="failing_session")
|
||||
def test_function():
|
||||
return "test_result"
|
||||
|
||||
# Call the decorated function - should not raise exception
|
||||
result = test_function()
|
||||
|
||||
# Assert that function still executed successfully
|
||||
self.assertEqual(result, "test_result")
|
||||
# Assert that log_trace_url was called (even though it failed)
|
||||
self.assertGreaterEqual(mock_log_trace_url.call_count, 2)
|
||||
|
||||
|
||||
class TestInternalSpanProcessor(unittest.TestCase):
|
||||
"""Tests for InternalSpanProcessor functionality."""
|
||||
|
||||
def setUp(self):
|
||||
self.processor = InternalSpanProcessor()
|
||||
# Reset the root span ID before each test
|
||||
self.processor._root_span_id = None
|
||||
|
||||
def test_tracks_root_span_on_start(self):
|
||||
"""Test that the processor tracks the first span as root span."""
|
||||
# Create a mock span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_context = MagicMock()
|
||||
mock_context.trace_flags.sampled = True
|
||||
mock_context.span_id = 12345
|
||||
mock_span.context = mock_context
|
||||
|
||||
# Call on_start
|
||||
self.processor.on_start(mock_span)
|
||||
|
||||
# Assert that root span ID was set
|
||||
self.assertEqual(self.processor._root_span_id, 12345)
|
||||
|
||||
def test_ignores_unsampled_spans_on_start(self):
|
||||
"""Test that unsampled spans are ignored on start."""
|
||||
# Create a mock unsampled span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_context = MagicMock()
|
||||
mock_context.trace_flags.sampled = False
|
||||
mock_span.context = mock_context
|
||||
|
||||
# Call on_start
|
||||
self.processor.on_start(mock_span)
|
||||
|
||||
# Assert that root span ID was not set
|
||||
self.assertIsNone(self.processor._root_span_id)
|
||||
|
||||
def test_only_tracks_first_span_as_root(self):
|
||||
"""Test that only the first span is tracked as root span."""
|
||||
# First span
|
||||
mock_span1 = MagicMock(spec=Span)
|
||||
mock_context1 = MagicMock()
|
||||
mock_context1.trace_flags.sampled = True
|
||||
mock_context1.span_id = 12345
|
||||
mock_span1.context = mock_context1
|
||||
|
||||
# Second span
|
||||
mock_span2 = MagicMock(spec=Span)
|
||||
mock_context2 = MagicMock()
|
||||
mock_context2.trace_flags.sampled = True
|
||||
mock_context2.span_id = 67890
|
||||
mock_span2.context = mock_context2
|
||||
|
||||
# Start first span
|
||||
self.processor.on_start(mock_span1)
|
||||
self.assertEqual(self.processor._root_span_id, 12345)
|
||||
|
||||
# Start second span - should not change root span ID
|
||||
self.processor.on_start(mock_span2)
|
||||
self.assertEqual(self.processor._root_span_id, 12345)
|
||||
|
||||
@patch("agentops.sdk.processors.upload_logfile")
|
||||
def test_uploads_logfile_on_root_span_end(self, mock_upload_logfile):
|
||||
"""Test that logfile is uploaded when root span ends."""
|
||||
# Set up root span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_context = MagicMock()
|
||||
mock_context.trace_flags.sampled = True
|
||||
mock_context.span_id = 12345
|
||||
mock_context.trace_id = 98765
|
||||
mock_span.context = mock_context
|
||||
|
||||
# Start the span to set it as root
|
||||
self.processor.on_start(mock_span)
|
||||
|
||||
# Create readable span for end event
|
||||
mock_readable_span = MagicMock(spec=ReadableSpan)
|
||||
mock_readable_span.context = mock_context
|
||||
|
||||
# End the span
|
||||
self.processor.on_end(mock_readable_span)
|
||||
|
||||
# Assert that upload_logfile was called with trace_id
|
||||
mock_upload_logfile.assert_called_once_with(98765)
|
||||
|
||||
@patch("agentops.sdk.processors.upload_logfile")
|
||||
def test_does_not_upload_logfile_for_non_root_span(self, mock_upload_logfile):
|
||||
"""Test that logfile is not uploaded for non-root spans."""
|
||||
# Set up root span
|
||||
root_span = MagicMock(spec=Span)
|
||||
root_context = MagicMock()
|
||||
root_context.trace_flags.sampled = True
|
||||
root_context.span_id = 12345
|
||||
root_span.context = root_context
|
||||
|
||||
# Start root span
|
||||
self.processor.on_start(root_span)
|
||||
|
||||
# Create non-root span
|
||||
non_root_span = MagicMock(spec=ReadableSpan)
|
||||
non_root_context = MagicMock()
|
||||
non_root_context.trace_flags.sampled = True
|
||||
non_root_context.span_id = 67890 # Different from root
|
||||
non_root_span.context = non_root_context
|
||||
|
||||
# End non-root span
|
||||
self.processor.on_end(non_root_span)
|
||||
|
||||
# Assert that upload_logfile was not called
|
||||
mock_upload_logfile.assert_not_called()
|
||||
|
||||
@patch("agentops.sdk.processors.upload_logfile")
|
||||
def test_handles_upload_logfile_error(self, mock_upload_logfile):
|
||||
"""Test that processor handles upload_logfile errors gracefully."""
|
||||
# Set up root span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_context = MagicMock()
|
||||
mock_context.trace_flags.sampled = True
|
||||
mock_context.span_id = 12345
|
||||
mock_context.trace_id = 98765
|
||||
mock_span.context = mock_context
|
||||
|
||||
# Start the span to set it as root
|
||||
self.processor.on_start(mock_span)
|
||||
|
||||
# Make upload_logfile raise an exception
|
||||
mock_upload_logfile.side_effect = Exception("Upload failed")
|
||||
|
||||
# Create readable span for end event
|
||||
mock_readable_span = MagicMock(spec=ReadableSpan)
|
||||
mock_readable_span.context = mock_context
|
||||
|
||||
# End the span - should not raise exception
|
||||
self.processor.on_end(mock_readable_span)
|
||||
|
||||
# Assert that upload_logfile was called
|
||||
mock_upload_logfile.assert_called_once_with(98765)
|
||||
|
||||
def test_ignores_unsampled_spans_on_end(self):
|
||||
"""Test that unsampled spans are ignored on end."""
|
||||
# Create a mock unsampled span
|
||||
mock_span = MagicMock(spec=ReadableSpan)
|
||||
mock_context = MagicMock()
|
||||
mock_context.trace_flags.sampled = False
|
||||
mock_span.context = mock_context
|
||||
|
||||
# Call on_end - should not raise exception
|
||||
self.processor.on_end(mock_span)
|
||||
|
||||
def test_shutdown_resets_root_span_id(self):
|
||||
"""Test that shutdown resets the root span ID."""
|
||||
# Set up root span
|
||||
mock_span = MagicMock(spec=Span)
|
||||
mock_context = MagicMock()
|
||||
mock_context.trace_flags.sampled = True
|
||||
mock_context.span_id = 12345
|
||||
mock_span.context = mock_context
|
||||
|
||||
# Start span to set root span ID
|
||||
self.processor.on_start(mock_span)
|
||||
self.assertEqual(self.processor._root_span_id, 12345)
|
||||
|
||||
# Call shutdown
|
||||
self.processor.shutdown()
|
||||
|
||||
# Verify root span ID was reset
|
||||
self.assertIsNone(self.processor._root_span_id)
|
||||
|
||||
def test_force_flush_returns_true(self):
|
||||
"""Test that force_flush returns True."""
|
||||
result = self.processor.force_flush()
|
||||
self.assertTrue(result)
|
||||
@@ -0,0 +1,35 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
from agentops.sdk.core import tracer
|
||||
from agentops.sdk.attributes import get_global_resource_attributes
|
||||
from agentops.semconv.resource import ResourceAttributes
|
||||
|
||||
|
||||
@patch("agentops.sdk.attributes.get_imported_libraries", return_value=["agentops"])
|
||||
def test_global_resource_attributes_no_system(mock_libs):
|
||||
attrs = get_global_resource_attributes("svc", project_id="proj")
|
||||
assert attrs[ResourceAttributes.SERVICE_NAME] == "svc"
|
||||
assert attrs[ResourceAttributes.PROJECT_ID] == "proj"
|
||||
assert ResourceAttributes.IMPORTED_LIBRARIES in attrs
|
||||
assert ResourceAttributes.HOST_MACHINE not in attrs
|
||||
assert ResourceAttributes.CPU_COUNT not in attrs
|
||||
|
||||
|
||||
@patch("agentops.sdk.core.get_system_resource_attributes")
|
||||
def test_system_metadata_only_for_session(mock_sys_attrs, instrumentation):
|
||||
mock_sys_attrs.return_value = {ResourceAttributes.HOST_MACHINE: "test"}
|
||||
|
||||
ctx = tracer.start_trace("session")
|
||||
tracer.end_trace(ctx, end_state="Success")
|
||||
spans = instrumentation.get_finished_spans()
|
||||
assert len(spans) == 1
|
||||
assert spans[0].attributes.get(ResourceAttributes.HOST_MACHINE) == "test"
|
||||
|
||||
instrumentation.clear_spans()
|
||||
|
||||
ctx = tracer.start_trace("custom")
|
||||
tracer.end_trace(ctx, end_state="Success")
|
||||
spans = instrumentation.get_finished_spans()
|
||||
assert len(spans) == 1
|
||||
assert ResourceAttributes.HOST_MACHINE not in spans[0].attributes
|
||||
@@ -0,0 +1,82 @@
|
||||
import os
|
||||
from unittest import mock
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
|
||||
from agentops.config import Config
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_env():
|
||||
"""Fixture to mock environment variables"""
|
||||
with mock.patch.dict(os.environ, clear=True):
|
||||
# Set up test environment variables
|
||||
env_vars = {
|
||||
"AGENTOPS_API_KEY": "test-api-key",
|
||||
"AGENTOPS_API_ENDPOINT": "https://test.agentops.ai",
|
||||
"AGENTOPS_APP_URL": "https://test-app.agentops.ai",
|
||||
"AGENTOPS_MAX_WAIT_TIME": "1000",
|
||||
"AGENTOPS_MAX_QUEUE_SIZE": "256",
|
||||
"AGENTOPS_DEFAULT_TAGS": "tag1,tag2,tag3",
|
||||
"AGENTOPS_INSTRUMENT_LLM_CALLS": "false",
|
||||
"AGENTOPS_AUTO_START_SESSION": "false",
|
||||
"AGENTOPS_SKIP_AUTO_END_SESSION": "true",
|
||||
"AGENTOPS_ENV_DATA_OPT_OUT": "true",
|
||||
}
|
||||
for key, value in env_vars.items():
|
||||
os.environ[key] = value
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valid_uuid():
|
||||
"""Return a valid UUID string for testing"""
|
||||
return str(UUID("12345678-1234-5678-1234-567812345678"))
|
||||
|
||||
|
||||
def test_config_from_env(mock_env):
|
||||
"""Test configuration initialization from environment variables"""
|
||||
config = Config()
|
||||
|
||||
assert config.api_key == "test-api-key"
|
||||
assert config.endpoint == "https://test.agentops.ai"
|
||||
assert config.app_url == "https://test-app.agentops.ai"
|
||||
assert config.max_wait_time == 1000
|
||||
assert config.max_queue_size == 256
|
||||
assert config.default_tags == {"tag1", "tag2", "tag3"}
|
||||
assert config.instrument_llm_calls is False
|
||||
assert config.auto_start_session is False
|
||||
assert config.skip_auto_end_session is True
|
||||
assert config.env_data_opt_out is True
|
||||
|
||||
|
||||
def test_config_override_env(mock_env, valid_uuid):
|
||||
"""Test that kwargs override environment variables"""
|
||||
config = Config()
|
||||
|
||||
# Store the original value from environment
|
||||
original_max_queue_size = config.max_queue_size
|
||||
|
||||
config.configure(
|
||||
api_key=valid_uuid,
|
||||
endpoint="https://override.agentops.ai",
|
||||
app_url="https://override-app.agentops.ai",
|
||||
max_wait_time=2000,
|
||||
default_tags=["new-tag"],
|
||||
instrument_llm_calls=True,
|
||||
max_queue_size=original_max_queue_size, # Explicitly pass the original value
|
||||
)
|
||||
|
||||
assert config.api_key == valid_uuid
|
||||
assert config.endpoint == "https://override.agentops.ai"
|
||||
assert config.app_url == "https://override-app.agentops.ai"
|
||||
assert config.max_wait_time == 2000
|
||||
assert config.default_tags == {"new-tag"}
|
||||
assert config.instrument_llm_calls is True
|
||||
# Other values should remain from env
|
||||
assert config.max_queue_size == 256 # Use the value from mock_env
|
||||
|
||||
|
||||
def test_invalid_api_key():
|
||||
"""Test handling of invalid API key raises InvalidApiKeyException"""
|
||||
@@ -0,0 +1,777 @@
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
import threading
|
||||
import time
|
||||
import asyncio
|
||||
|
||||
from agentops import start_trace
|
||||
from agentops.sdk.core import TraceContext
|
||||
from opentelemetry.trace import StatusCode
|
||||
|
||||
|
||||
class TestContextManager(unittest.TestCase):
|
||||
"""Test the context manager functionality of TraceContext"""
|
||||
|
||||
def test_trace_context_has_context_manager_methods(self):
|
||||
"""Test that TraceContext has __enter__ and __exit__ methods"""
|
||||
# TraceContext should have context manager protocol methods
|
||||
assert hasattr(TraceContext, "__enter__")
|
||||
assert hasattr(TraceContext, "__exit__")
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
def test_trace_context_enter_returns_self(self, mock_tracer):
|
||||
"""Test that __enter__ returns the TraceContext instance"""
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# __enter__ should return self
|
||||
result = trace_context.__enter__()
|
||||
assert result is trace_context
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
def test_trace_context_exit_calls_end_trace(self, mock_tracer):
|
||||
"""Test that __exit__ calls end_trace with appropriate state"""
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# Test normal exit (no exception)
|
||||
trace_context.__exit__(None, None, None)
|
||||
mock_tracer.end_trace.assert_called_once_with(trace_context, StatusCode.OK)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
def test_trace_context_exit_with_exception_sets_error_state(self, mock_tracer):
|
||||
"""Test that __exit__ sets ERROR state when exception occurs"""
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# Test exit with exception
|
||||
mock_tracer.reset_mock()
|
||||
exc_type = ValueError
|
||||
exc_val = ValueError("test error")
|
||||
exc_tb = None
|
||||
|
||||
trace_context.__exit__(exc_type, exc_val, exc_tb)
|
||||
mock_tracer.end_trace.assert_called_once_with(trace_context, StatusCode.ERROR)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_usage_pattern(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test using start_trace as a context manager"""
|
||||
# Create a mock TraceContext
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
mock_trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# Mock the tracer's start_trace method to return our TraceContext
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Use as context manager
|
||||
with start_trace("test_trace") as trace:
|
||||
assert trace is mock_trace_context
|
||||
assert trace.span is mock_span
|
||||
assert trace.token is mock_token
|
||||
|
||||
# Verify start_trace was called
|
||||
mock_agentops_tracer.start_trace.assert_called_once_with(trace_name="test_trace", tags=None)
|
||||
# Verify end_trace was called
|
||||
mock_core_tracer.end_trace.assert_called_once_with(mock_trace_context, StatusCode.OK)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_with_exception(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test context manager handles exceptions properly"""
|
||||
# Create a mock TraceContext
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
mock_trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# Mock the tracer's start_trace method
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Test exception handling
|
||||
with self.assertRaises(ValueError):
|
||||
with start_trace("test_trace"):
|
||||
raise ValueError("Test exception")
|
||||
|
||||
# Verify end_trace was called with ERROR state
|
||||
mock_core_tracer.end_trace.assert_called_once_with(mock_trace_context, StatusCode.ERROR)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
@patch("agentops.init")
|
||||
def test_start_trace_auto_initializes_if_needed(self, mock_init, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that start_trace attempts to initialize SDK if not initialized"""
|
||||
# First call: SDK not initialized
|
||||
mock_agentops_tracer.initialized = False
|
||||
|
||||
# After init() is called, set initialized to True
|
||||
def set_initialized():
|
||||
mock_agentops_tracer.initialized = True
|
||||
|
||||
mock_init.side_effect = set_initialized
|
||||
|
||||
# Create a mock TraceContext for when start_trace is called after init
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
mock_trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Call start_trace
|
||||
result = start_trace("test_trace")
|
||||
|
||||
# Verify init was called
|
||||
mock_init.assert_called_once()
|
||||
# Verify start_trace was called on tracer
|
||||
mock_agentops_tracer.start_trace.assert_called_once_with(trace_name="test_trace", tags=None)
|
||||
assert result is mock_trace_context
|
||||
|
||||
def test_no_wrapper_classes_needed(self):
|
||||
"""Test that we don't need wrapper classes - TraceContext is the context manager"""
|
||||
# TraceContext itself implements the context manager protocol
|
||||
# No need for TraceContextManager wrapper
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# Can use directly as context manager
|
||||
assert hasattr(trace_context, "__enter__")
|
||||
assert hasattr(trace_context, "__exit__")
|
||||
assert callable(trace_context.__enter__)
|
||||
assert callable(trace_context.__exit__)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_parallel_traces_independence(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that multiple traces can run in parallel independently"""
|
||||
# Create mock TraceContexts
|
||||
mock_trace1 = TraceContext(span=Mock(), token=Mock())
|
||||
mock_trace2 = TraceContext(span=Mock(), token=Mock())
|
||||
|
||||
# Mock the tracer to return different traces
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.side_effect = [mock_trace1, mock_trace2]
|
||||
|
||||
# Start two traces
|
||||
trace1 = start_trace("trace1")
|
||||
trace2 = start_trace("trace2")
|
||||
|
||||
# They should be different instances
|
||||
assert trace1 is not trace2
|
||||
assert trace1 is mock_trace1
|
||||
assert trace2 is mock_trace2
|
||||
|
||||
# End them independently using context manager protocol
|
||||
trace1.__exit__(None, None, None)
|
||||
trace2.__exit__(None, None, None)
|
||||
|
||||
# Verify both were ended
|
||||
assert mock_core_tracer.end_trace.call_count == 2
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_nested_context_managers_create_parallel_traces(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that nested context managers create parallel traces, not parent-child"""
|
||||
# Create mock TraceContexts
|
||||
mock_outer = TraceContext(span=Mock(), token=Mock())
|
||||
mock_inner = TraceContext(span=Mock(), token=Mock())
|
||||
|
||||
# Mock the tracer
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.side_effect = [mock_outer, mock_inner]
|
||||
|
||||
# Use nested context managers
|
||||
with start_trace("outer_trace") as outer:
|
||||
assert outer is mock_outer
|
||||
with start_trace("inner_trace") as inner:
|
||||
assert inner is mock_inner
|
||||
assert inner is not outer
|
||||
# Both traces are active
|
||||
assert mock_agentops_tracer.start_trace.call_count == 2
|
||||
|
||||
# Verify both were ended
|
||||
assert mock_core_tracer.end_trace.call_count == 2
|
||||
# Inner trace ended first, then outer
|
||||
calls = mock_core_tracer.end_trace.call_args_list
|
||||
assert calls[0][0][0] is mock_inner
|
||||
assert calls[1][0][0] is mock_outer
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_exception_in_nested_traces(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test exception handling in nested traces"""
|
||||
# Create mock TraceContexts
|
||||
mock_outer = TraceContext(span=Mock(), token=Mock())
|
||||
mock_inner = TraceContext(span=Mock(), token=Mock())
|
||||
|
||||
# Mock the tracer
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.side_effect = [mock_outer, mock_inner]
|
||||
|
||||
# Test exception in inner trace
|
||||
with self.assertRaises(ValueError):
|
||||
with start_trace("outer_trace"):
|
||||
with start_trace("inner_trace"):
|
||||
raise ValueError("Inner exception")
|
||||
|
||||
# Both traces should be ended with ERROR state
|
||||
assert mock_core_tracer.end_trace.call_count == 2
|
||||
calls = mock_core_tracer.end_trace.call_args_list
|
||||
# Inner trace ended with ERROR
|
||||
assert calls[0][0][0] is mock_inner
|
||||
assert calls[0][0][1] == StatusCode.ERROR
|
||||
# Outer trace also ended with ERROR (exception propagated)
|
||||
assert calls[1][0][0] is mock_outer
|
||||
assert calls[1][0][1] == StatusCode.ERROR
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
def test_trace_context_attributes_access(self, mock_tracer):
|
||||
"""Test accessing span and token attributes of TraceContext"""
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# Direct attribute access
|
||||
assert trace_context.span is mock_span
|
||||
assert trace_context.token is mock_token
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_multiple_exceptions_in_sequence(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test handling multiple exceptions in sequence"""
|
||||
# Mock the tracer
|
||||
mock_agentops_tracer.initialized = True
|
||||
|
||||
# Create different mock traces for each attempt
|
||||
mock_traces = [TraceContext(span=Mock(), token=Mock()) for _ in range(3)]
|
||||
mock_agentops_tracer.start_trace.side_effect = mock_traces
|
||||
|
||||
# Multiple traces with exceptions
|
||||
for i in range(3):
|
||||
with self.assertRaises(RuntimeError):
|
||||
with start_trace(f"trace_{i}"):
|
||||
raise RuntimeError(f"Error {i}")
|
||||
|
||||
# All should be ended with ERROR state
|
||||
assert mock_core_tracer.end_trace.call_count == 3
|
||||
for i, call in enumerate(mock_core_tracer.end_trace.call_args_list):
|
||||
assert call[0][0] is mock_traces[i]
|
||||
assert call[0][1] == StatusCode.ERROR
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_trace_with_tags_dict(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test starting trace with tags as dictionary"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
tags = {"environment": "test", "version": "1.0"}
|
||||
with start_trace("tagged_trace", tags=tags) as trace:
|
||||
assert trace is mock_trace
|
||||
|
||||
# Verify tags were passed
|
||||
mock_agentops_tracer.start_trace.assert_called_once_with(trace_name="tagged_trace", tags=tags)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_trace_with_tags_list(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test starting trace with tags as list"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
tags = ["test", "v1.0", "experimental"]
|
||||
with start_trace("tagged_trace", tags=tags) as trace:
|
||||
assert trace is mock_trace
|
||||
|
||||
# Verify tags were passed
|
||||
mock_agentops_tracer.start_trace.assert_called_once_with(trace_name="tagged_trace", tags=tags)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_trace_context_manager_thread_safety(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that context managers work correctly in multi-threaded environment"""
|
||||
# Mock the tracer
|
||||
mock_agentops_tracer.initialized = True
|
||||
|
||||
# Create unique traces for each thread
|
||||
thread_traces = {}
|
||||
trace_lock = threading.Lock()
|
||||
|
||||
def create_trace(trace_name=None, tags=None, **kwargs):
|
||||
trace = TraceContext(span=Mock(), token=Mock())
|
||||
with trace_lock:
|
||||
thread_traces[threading.current_thread().ident] = trace
|
||||
return trace
|
||||
|
||||
mock_agentops_tracer.start_trace.side_effect = create_trace
|
||||
|
||||
results = []
|
||||
errors = []
|
||||
|
||||
def worker(thread_id):
|
||||
try:
|
||||
with start_trace(f"thread_{thread_id}_trace") as trace:
|
||||
# Each thread should get its own trace
|
||||
results.append((thread_id, trace))
|
||||
time.sleep(0.01) # Simulate some work
|
||||
except Exception as e:
|
||||
errors.append((thread_id, str(e)))
|
||||
|
||||
# Start multiple threads
|
||||
threads = []
|
||||
for i in range(5):
|
||||
t = threading.Thread(target=worker, args=(i,))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
|
||||
# Wait for all threads
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
# Check results
|
||||
assert len(errors) == 0, f"Errors in threads: {errors}"
|
||||
assert len(results) == 5
|
||||
|
||||
# Each thread should have gotten a unique trace
|
||||
traces = [r[1] for r in results]
|
||||
assert len(set(id(t) for t in traces)) == 5 # All unique
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_with_early_return(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that context manager properly cleans up with early return"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
def function_with_early_return():
|
||||
with start_trace("early_return_trace"):
|
||||
if True: # Early return condition
|
||||
return "early"
|
||||
return "normal"
|
||||
|
||||
result = function_with_early_return()
|
||||
assert result == "early"
|
||||
|
||||
# Verify trace was still ended properly
|
||||
mock_core_tracer.end_trace.assert_called_once_with(mock_trace, StatusCode.OK)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_with_finally_block(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test context manager with try-finally block"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
finally_executed = False
|
||||
|
||||
try:
|
||||
with start_trace("finally_trace"):
|
||||
try:
|
||||
raise ValueError("Test")
|
||||
finally:
|
||||
finally_executed = True
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
assert finally_executed
|
||||
# Trace should be ended with ERROR due to exception
|
||||
mock_core_tracer.end_trace.assert_called_once_with(mock_trace, StatusCode.ERROR)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_backwards_compatibility_existing_patterns(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that existing usage patterns continue to work"""
|
||||
# Create mock traces
|
||||
mock_traces = [TraceContext(span=Mock(), token=Mock()) for _ in range(3)]
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.side_effect = mock_traces
|
||||
|
||||
# Pattern 1: Basic context manager
|
||||
with start_trace("basic") as trace:
|
||||
assert trace is mock_traces[0]
|
||||
|
||||
# Pattern 2: Manual start/end using context manager protocol
|
||||
trace = start_trace("manual")
|
||||
assert trace is mock_traces[1]
|
||||
trace.__exit__(None, None, None) # Use context manager exit instead of end_trace
|
||||
|
||||
# Pattern 3: With tags
|
||||
with start_trace("tagged", tags=["production", "v2"]) as trace:
|
||||
assert trace is mock_traces[2]
|
||||
|
||||
# All patterns should work
|
||||
assert mock_agentops_tracer.start_trace.call_count == 3
|
||||
assert mock_core_tracer.end_trace.call_count == 3
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_edge_case_none_trace_context(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test handling when start_trace returns None"""
|
||||
# Mock SDK not initialized and init fails
|
||||
mock_agentops_tracer.initialized = False
|
||||
|
||||
# When start_trace is called on uninitialized tracer, it returns None
|
||||
with patch("agentops.init") as mock_init:
|
||||
mock_init.side_effect = Exception("Init failed")
|
||||
|
||||
result = start_trace("test_trace")
|
||||
assert result is None
|
||||
|
||||
# Verify start_trace was not called on tracer (since init failed)
|
||||
mock_agentops_tracer.start_trace.assert_not_called()
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_edge_case_tracing_core_not_initialized(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test behavior when global tracer is not initialized"""
|
||||
mock_agentops_tracer.initialized = False
|
||||
|
||||
# Mock init to succeed but tracer still not initialized
|
||||
with patch("agentops.init") as mock_init:
|
||||
mock_init.return_value = None # init succeeds but doesn't set initialized
|
||||
|
||||
result = start_trace("test")
|
||||
assert result is None
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_edge_case_exception_in_exit_method(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test handling when exception occurs in __exit__ method"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
# Make end_trace raise an exception
|
||||
mock_core_tracer.end_trace.side_effect = RuntimeError("End trace failed")
|
||||
|
||||
# The exception in __exit__ should be suppressed
|
||||
with start_trace("exception_in_exit"):
|
||||
pass # Should not raise
|
||||
|
||||
# Verify end_trace was attempted
|
||||
mock_core_tracer.end_trace.assert_called_once()
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_performance_many_sequential_traces(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test performance with many sequential traces"""
|
||||
# Mock the tracer
|
||||
mock_agentops_tracer.initialized = True
|
||||
|
||||
# Create traces on demand
|
||||
def create_trace(trace_name=None, tags=None, **kwargs):
|
||||
return TraceContext(span=Mock(), token=Mock())
|
||||
|
||||
mock_agentops_tracer.start_trace.side_effect = create_trace
|
||||
|
||||
# Create many traces sequentially
|
||||
start_time = time.time()
|
||||
for i in range(100):
|
||||
with start_trace(f"trace_{i}") as trace:
|
||||
assert trace is not None
|
||||
assert trace.span is not None
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
# Should complete reasonably quickly (< 1 second for 100 traces)
|
||||
assert elapsed < 1.0, f"Too slow: {elapsed:.2f}s for 100 traces"
|
||||
|
||||
# Verify all traces were started and ended
|
||||
assert mock_agentops_tracer.start_trace.call_count == 100
|
||||
assert mock_core_tracer.end_trace.call_count == 100
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
def test_trace_context_state_management(self, mock_tracer):
|
||||
"""Test that TraceContext properly manages its internal state"""
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# Initial state
|
||||
assert trace_context.span is mock_span
|
||||
assert trace_context.token is mock_token
|
||||
|
||||
# Enter context
|
||||
result = trace_context.__enter__()
|
||||
assert result is trace_context
|
||||
|
||||
# Exit context normally
|
||||
trace_context.__exit__(None, None, None)
|
||||
mock_tracer.end_trace.assert_called_once_with(trace_context, StatusCode.OK)
|
||||
|
||||
# State should remain accessible after exit
|
||||
assert trace_context.span is mock_span
|
||||
assert trace_context.token is mock_token
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_with_async_context(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test context manager works in async context"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
async def async_function():
|
||||
with start_trace("async_context") as trace:
|
||||
assert trace is mock_trace
|
||||
await asyncio.sleep(0.01)
|
||||
return "done"
|
||||
|
||||
# Run async function
|
||||
result = asyncio.run(async_function())
|
||||
assert result == "done"
|
||||
|
||||
# Verify trace was properly managed
|
||||
mock_agentops_tracer.start_trace.assert_called_once_with(trace_name="async_context", tags=None)
|
||||
mock_core_tracer.end_trace.assert_called_once_with(mock_trace, StatusCode.OK)
|
||||
|
||||
|
||||
class TestContextManagerBackwardCompatibility(unittest.TestCase):
|
||||
"""Test backward compatibility for context manager usage"""
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_existing_code_patterns_still_work(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that code using the old patterns still works"""
|
||||
# Create mock traces - need more than 3 for this test
|
||||
mock_traces = [TraceContext(span=Mock(), token=Mock()) for _ in range(5)]
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.side_effect = mock_traces
|
||||
|
||||
# Old pattern 1: Simple context manager
|
||||
with start_trace("basic") as trace:
|
||||
# Should work without changes
|
||||
assert trace.span is not None
|
||||
|
||||
# Old pattern 2: Context manager with exception handling
|
||||
try:
|
||||
with start_trace("with_error") as trace:
|
||||
raise ValueError("test")
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# Old pattern 3: Nested traces
|
||||
with start_trace("outer") as outer:
|
||||
with start_trace("inner") as inner:
|
||||
assert outer is not inner
|
||||
|
||||
# All should work - 4 calls total (basic, with_error, outer, inner)
|
||||
assert mock_agentops_tracer.start_trace.call_count == 4
|
||||
assert mock_core_tracer.end_trace.call_count == 4
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_api_compatibility(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that the API remains compatible"""
|
||||
# Create mock TraceContexts for each call
|
||||
mock_traces = [TraceContext(span=Mock(), token=Mock()) for _ in range(3)]
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.side_effect = mock_traces
|
||||
|
||||
# Test function signatures
|
||||
# start_trace(trace_name, tags=None)
|
||||
trace1 = start_trace("test1")
|
||||
assert trace1 is mock_traces[0]
|
||||
|
||||
trace2 = start_trace("test2", tags=["tag1", "tag2"])
|
||||
assert trace2 is mock_traces[1]
|
||||
|
||||
trace3 = start_trace("test3", tags={"key": "value"})
|
||||
assert trace3 is mock_traces[2]
|
||||
|
||||
# Use context manager protocol to end traces
|
||||
trace1.__exit__(None, None, None)
|
||||
trace2.__exit__(ValueError, ValueError("test"), None)
|
||||
trace3.__exit__(None, None, None)
|
||||
|
||||
# All calls should work
|
||||
assert mock_agentops_tracer.start_trace.call_count == 3
|
||||
assert mock_core_tracer.end_trace.call_count == 3
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_return_type_compatibility(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that return types are compatible with existing code"""
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
mock_trace = TraceContext(span=mock_span, token=mock_token)
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
# start_trace returns TraceContext (or None)
|
||||
trace = start_trace("test")
|
||||
assert isinstance(trace, TraceContext)
|
||||
assert hasattr(trace, "span")
|
||||
assert hasattr(trace, "token")
|
||||
assert hasattr(trace, "__enter__")
|
||||
assert hasattr(trace, "__exit__")
|
||||
|
||||
# Can be used as context manager
|
||||
with trace:
|
||||
pass
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_with_keyboard_interrupt(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test context manager handles KeyboardInterrupt properly"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
# Test KeyboardInterrupt handling
|
||||
with self.assertRaises(KeyboardInterrupt):
|
||||
with start_trace("keyboard_interrupt_trace"):
|
||||
raise KeyboardInterrupt()
|
||||
|
||||
# Verify end_trace was called with ERROR state
|
||||
mock_core_tracer.end_trace.assert_called_once_with(mock_trace, StatusCode.ERROR)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_with_system_exit(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test context manager handles SystemExit properly"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
# Test SystemExit handling
|
||||
with self.assertRaises(SystemExit):
|
||||
with start_trace("system_exit_trace"):
|
||||
raise SystemExit(1)
|
||||
|
||||
# Verify end_trace was called with ERROR state
|
||||
mock_core_tracer.end_trace.assert_called_once_with(mock_trace, StatusCode.ERROR)
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_in_generator_function(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test context manager works correctly in generator functions"""
|
||||
# Create mock traces
|
||||
mock_traces = [TraceContext(span=Mock(), token=Mock()) for _ in range(3)]
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.side_effect = mock_traces
|
||||
|
||||
def trace_generator():
|
||||
with start_trace("generator_trace"):
|
||||
yield 1
|
||||
yield 2
|
||||
yield 3
|
||||
|
||||
# Consume the generator
|
||||
results = list(trace_generator())
|
||||
assert results == [1, 2, 3]
|
||||
|
||||
# Verify trace was properly managed
|
||||
mock_agentops_tracer.start_trace.assert_called_once()
|
||||
mock_core_tracer.end_trace.assert_called_once()
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
def test_context_manager_exit_return_value(self, mock_tracer):
|
||||
"""Test that __exit__ returns None (doesn't suppress exceptions)"""
|
||||
mock_span = Mock()
|
||||
mock_token = Mock()
|
||||
trace_context = TraceContext(span=mock_span, token=mock_token)
|
||||
|
||||
# __exit__ should return None (or falsy) to not suppress exceptions
|
||||
result = trace_context.__exit__(None, None, None)
|
||||
assert result is None or not result
|
||||
|
||||
# Also with exception
|
||||
result = trace_context.__exit__(ValueError, ValueError("test"), None)
|
||||
assert result is None or not result
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_with_very_large_data(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test context manager with very large trace names and tags"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
# Very large trace name and tags
|
||||
large_trace_name = "x" * 10000
|
||||
large_tags = {f"key_{i}": f"value_{i}" * 100 for i in range(100)}
|
||||
|
||||
with start_trace(large_trace_name, tags=large_tags) as trace:
|
||||
assert trace is mock_trace
|
||||
|
||||
# Should handle large data without issues
|
||||
mock_agentops_tracer.start_trace.assert_called_once()
|
||||
args, kwargs = mock_agentops_tracer.start_trace.call_args
|
||||
assert kwargs["trace_name"] == large_trace_name
|
||||
assert kwargs["tags"] == large_tags
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_with_asyncio_tasks(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test context manager with multiple asyncio tasks"""
|
||||
# Mock the tracer
|
||||
mock_agentops_tracer.initialized = True
|
||||
|
||||
# Create traces for each task
|
||||
trace_count = 0
|
||||
|
||||
def create_trace(trace_name=None, tags=None, **kwargs):
|
||||
nonlocal trace_count
|
||||
trace_count += 1
|
||||
return TraceContext(span=Mock(name=f"span_{trace_count}"), token=Mock())
|
||||
|
||||
mock_agentops_tracer.start_trace.side_effect = create_trace
|
||||
|
||||
async def task_with_trace(task_id):
|
||||
with start_trace(f"async_task_{task_id}"):
|
||||
await asyncio.sleep(0.01)
|
||||
return task_id
|
||||
|
||||
async def run_concurrent_tasks():
|
||||
tasks = [task_with_trace(i) for i in range(5)]
|
||||
results = await asyncio.gather(*tasks)
|
||||
return results
|
||||
|
||||
# Run async tasks
|
||||
results = asyncio.run(run_concurrent_tasks())
|
||||
assert results == [0, 1, 2, 3, 4]
|
||||
|
||||
# All traces should be started and ended
|
||||
assert mock_agentops_tracer.start_trace.call_count == 5
|
||||
assert mock_core_tracer.end_trace.call_count == 5
|
||||
|
||||
@patch("agentops.sdk.core.tracer")
|
||||
@patch("agentops.tracer")
|
||||
def test_context_manager_resource_cleanup_on_exit_failure(self, mock_agentops_tracer, mock_core_tracer):
|
||||
"""Test that resources are cleaned up even if __exit__ fails"""
|
||||
# Create a mock TraceContext
|
||||
mock_trace = TraceContext(span=Mock(), token=Mock())
|
||||
mock_agentops_tracer.initialized = True
|
||||
mock_agentops_tracer.start_trace.return_value = mock_trace
|
||||
|
||||
# Make end_trace fail
|
||||
mock_core_tracer.end_trace.side_effect = Exception("Cleanup failed")
|
||||
|
||||
# Should not raise exception from __exit__
|
||||
with start_trace("cleanup_test") as trace:
|
||||
assert trace is mock_trace
|
||||
|
||||
# end_trace was attempted despite failure
|
||||
mock_core_tracer.end_trace.assert_called_once()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,27 @@
|
||||
import time
|
||||
|
||||
|
||||
import agentops
|
||||
from agentops import ActionEvent, ErrorEvent
|
||||
|
||||
|
||||
class TestEvents:
|
||||
def setup_method(self):
|
||||
self.api_key = "11111111-1111-4111-8111-111111111111"
|
||||
self.event_type = "test_event_type"
|
||||
|
||||
def test_record_timestamp(self, mock_req):
|
||||
agentops.init(api_key=self.api_key)
|
||||
|
||||
event = ActionEvent()
|
||||
time.sleep(0.15)
|
||||
agentops.record(event)
|
||||
|
||||
assert event.init_timestamp != event.end_timestamp
|
||||
|
||||
def test_record_error_event(self, mock_req):
|
||||
agentops.init(api_key=self.api_key)
|
||||
|
||||
event = ErrorEvent(logs=None)
|
||||
time.sleep(0.15)
|
||||
agentops.record(event)
|
||||
@@ -0,0 +1,54 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
# noinspection PyProtectedMember
|
||||
from psutil._common import sdiskpart, sdiskusage
|
||||
|
||||
import agentops.helpers.system as host_env
|
||||
|
||||
|
||||
def mock_partitions():
|
||||
# Try to create with new fields first, fall back to old format if it fails
|
||||
try:
|
||||
return [
|
||||
sdiskpart( # noqa: E501
|
||||
device="/dev/sda1",
|
||||
mountpoint="/",
|
||||
fstype="ext4",
|
||||
opts="rw,relatime",
|
||||
maxfile=255, # type: ignore
|
||||
maxpath=4096, # type: ignore
|
||||
)
|
||||
]
|
||||
except TypeError:
|
||||
# Fallback for older versions that don't have maxfile/maxpath
|
||||
return [sdiskpart(device="/dev/sda1", mountpoint="/", fstype="ext4", opts="rw,relatime")]
|
||||
|
||||
|
||||
def mock_disk_usage(partition):
|
||||
if partition == "/":
|
||||
return sdiskusage(total=(1024**3), used=0, free=(1024**3), percent=100)
|
||||
else:
|
||||
raise PermissionError("Device access exception should have been caught")
|
||||
|
||||
|
||||
class TestHostEnv:
|
||||
@patch("psutil.disk_partitions", new=lambda: [mock_partitions()[0]])
|
||||
@patch("psutil.disk_usage", new=mock_disk_usage)
|
||||
def test_disk_info(self):
|
||||
self.assert_disk_info()
|
||||
|
||||
@patch("psutil.disk_partitions", new=mock_partitions)
|
||||
@patch("psutil.disk_usage", new=mock_disk_usage)
|
||||
def test_disk_info_skips_oserror(self):
|
||||
self.assert_disk_info()
|
||||
|
||||
def assert_disk_info(self):
|
||||
disk_info = host_env.get_disk_details()
|
||||
assert list(disk_info.keys()) == ["/dev/sda1"]
|
||||
sda1 = disk_info["/dev/sda1"]
|
||||
assert sda1["Mountpoint"] == "/"
|
||||
assert sda1["Total"] == "1.00 GB"
|
||||
assert sda1["Used"] == "0.00 GB"
|
||||
assert sda1["Free"] == "1.00 GB"
|
||||
assert sda1["Percentage"] == "100%"
|
||||
@@ -0,0 +1,501 @@
|
||||
from unittest.mock import patch, MagicMock
|
||||
import agentops
|
||||
import threading
|
||||
|
||||
|
||||
def test_get_client_singleton():
|
||||
# Should always return the same instance
|
||||
c1 = agentops.get_client()
|
||||
c2 = agentops.get_client()
|
||||
assert c1 is c2
|
||||
|
||||
|
||||
def test_get_client_thread_safety():
|
||||
# Should not create multiple clients in threads
|
||||
results = []
|
||||
|
||||
def worker():
|
||||
results.append(agentops.get_client())
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(5)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
assert all(r is results[0] for r in results)
|
||||
|
||||
|
||||
def test_init_merges_tags(monkeypatch):
|
||||
with patch("agentops.get_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
agentops.init(tags=["a"], default_tags=["b"]) # Should merge
|
||||
assert {"a", "b"}.issubset(set(mock_client.init.call_args[1]["default_tags"]))
|
||||
|
||||
|
||||
def test_init_warns_on_deprecated_tags(monkeypatch):
|
||||
with patch("agentops.get_client") as mock_get_client, patch("agentops.warn_deprecated_param") as mock_warn:
|
||||
mock_client = MagicMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
agentops.init(tags=["a"])
|
||||
mock_warn.assert_called_once_with("tags", "default_tags")
|
||||
|
||||
|
||||
def test_init_jupyter_detection(monkeypatch):
|
||||
with patch("agentops.get_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
# Simulate Jupyter by patching get_ipython
|
||||
import builtins
|
||||
|
||||
builtins.get_ipython = lambda: type("Z", (), {"__name__": "ZMQInteractiveShell"})()
|
||||
agentops.init()
|
||||
del builtins.get_ipython
|
||||
|
||||
|
||||
def test_init_jupyter_detection_nameerror():
|
||||
with patch("agentops.get_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
# Simulate NameError when get_ipython() is called
|
||||
import builtins
|
||||
|
||||
original_get_ipython = getattr(builtins, "get_ipython", None)
|
||||
builtins.get_ipython = lambda: None # This will cause NameError
|
||||
try:
|
||||
agentops.init()
|
||||
except NameError:
|
||||
pass # Expected
|
||||
finally:
|
||||
if original_get_ipython:
|
||||
builtins.get_ipython = original_get_ipython
|
||||
else:
|
||||
delattr(builtins, "get_ipython")
|
||||
|
||||
|
||||
def test_configure_valid_and_invalid_params():
|
||||
with patch("agentops.get_client") as mock_get_client, patch("agentops.logger") as mock_logger:
|
||||
mock_client = MagicMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
# Valid param
|
||||
agentops.configure(api_key="foo")
|
||||
mock_client.configure.assert_called_with(api_key="foo")
|
||||
# Invalid param
|
||||
agentops.configure(bad_param=123)
|
||||
mock_logger.warning.assert_any_call("Invalid configuration parameters: {'bad_param'}")
|
||||
|
||||
|
||||
def test_record_sets_end_timestamp():
|
||||
class Dummy:
|
||||
end_timestamp = None
|
||||
|
||||
with patch("agentops.helpers.time.get_ISO_time", return_value="now"):
|
||||
d = Dummy()
|
||||
agentops.record(d)
|
||||
assert d.end_timestamp == "now"
|
||||
|
||||
|
||||
def test_record_no_end_timestamp():
|
||||
class Dummy:
|
||||
pass
|
||||
|
||||
d = Dummy()
|
||||
assert agentops.record(d) is d
|
||||
|
||||
|
||||
def test_update_trace_metadata_success():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
result = agentops.update_trace_metadata({"foo": "bar"})
|
||||
assert result is True
|
||||
mock_span.set_attribute.assert_called()
|
||||
|
||||
|
||||
def test_update_trace_metadata_no_active_span():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span", return_value=None):
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
assert not agentops.update_trace_metadata({"foo": "bar"})
|
||||
|
||||
|
||||
def test_update_trace_metadata_not_recording():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = False
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
assert not agentops.update_trace_metadata({"foo": "bar"})
|
||||
|
||||
|
||||
def test_update_trace_metadata_invalid_type():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
# Value is a dict, which is not allowed
|
||||
assert not agentops.update_trace_metadata({"foo": {"bar": 1}})
|
||||
|
||||
|
||||
def test_update_trace_metadata_list_type():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
# List of valid types
|
||||
assert agentops.update_trace_metadata({"foo": [1, 2, 3]})
|
||||
mock_span.set_attribute.assert_called()
|
||||
|
||||
|
||||
def test_update_trace_metadata_extract_key_single_part():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# Test with a semantic convention that has only one part (len < 2)
|
||||
with patch("agentops.AgentAttributes") as mock_attrs:
|
||||
mock_attrs.__dict__ = {"SINGLE": "single_value"}
|
||||
result = agentops.update_trace_metadata({"single_value": "test"})
|
||||
assert result is True
|
||||
|
||||
|
||||
def test_update_trace_metadata_skip_gen_ai_attributes():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# Test that gen_ai attributes are skipped
|
||||
with patch("agentops.AgentAttributes") as mock_attrs:
|
||||
mock_attrs.__dict__ = {"GEN_AI_ATTR": "gen_ai.something"}
|
||||
agentops.update_trace_metadata({"gen_ai.something": "test"})
|
||||
# Should still work but skip the gen_ai attribute
|
||||
|
||||
|
||||
def test_update_trace_metadata_trace_id_conversion_error():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "child_span" # Not a session span
|
||||
mock_span.get_span_context.return_value.trace_id = "invalid_hex"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {"trace1": MagicMock()}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# This should handle the ValueError from int("invalid_hex", 16)
|
||||
agentops.update_trace_metadata({"foo": "bar"})
|
||||
# The function should handle the error gracefully
|
||||
|
||||
|
||||
def test_update_trace_metadata_no_active_traces():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span", return_value=None),
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
result = agentops.update_trace_metadata({"foo": "bar"})
|
||||
assert result is False
|
||||
mock_logger.warning.assert_called_with("No active trace found. Cannot update metadata.")
|
||||
|
||||
|
||||
def test_update_trace_metadata_span_not_recording():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span") as mock_get_span,
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = False
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
result = agentops.update_trace_metadata({"foo": "bar"})
|
||||
assert result is False
|
||||
mock_logger.warning.assert_called_with("No active trace found. Cannot update metadata.")
|
||||
|
||||
|
||||
def test_update_trace_metadata_list_invalid_types():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span") as mock_get_span,
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# List with invalid types (dict)
|
||||
agentops.update_trace_metadata({"foo": [{"invalid": "type"}]})
|
||||
mock_logger.warning.assert_called_with("No valid metadata attributes were updated")
|
||||
|
||||
|
||||
def test_update_trace_metadata_invalid_value_type():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span") as mock_get_span,
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# Invalid value type (dict)
|
||||
agentops.update_trace_metadata({"foo": {"invalid": "type"}})
|
||||
mock_logger.warning.assert_called_with("No valid metadata attributes were updated")
|
||||
|
||||
|
||||
def test_update_trace_metadata_semantic_convention_mapping():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span") as mock_get_span,
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# Test semantic convention mapping
|
||||
with patch("agentops.AgentAttributes") as mock_attrs:
|
||||
mock_attrs.__dict__ = {"TEST_ATTR": "agent.test_attribute"}
|
||||
agentops.update_trace_metadata({"agent_test_attribute": "test"})
|
||||
mock_logger.debug.assert_called_with("Successfully updated 1 metadata attributes on trace")
|
||||
|
||||
|
||||
def test_update_trace_metadata_exception_handling():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span") as mock_get_span,
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_span.set_attribute.side_effect = Exception("Test error")
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
agentops.update_trace_metadata({"foo": "bar"})
|
||||
mock_logger.error.assert_called_with("Error updating trace metadata: Test error")
|
||||
|
||||
|
||||
def test_update_trace_metadata_no_valid_attributes():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span") as mock_get_span,
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# All values are None
|
||||
agentops.update_trace_metadata({"foo": None, "bar": None})
|
||||
mock_logger.warning.assert_called_with("No valid metadata attributes were updated")
|
||||
|
||||
|
||||
def test_start_trace_auto_init_failure():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.init") as mock_init,
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_tracer.initialized = False
|
||||
mock_init.side_effect = Exception("Init failed")
|
||||
|
||||
agentops.start_trace("test")
|
||||
mock_logger.error.assert_called_with(
|
||||
"SDK auto-initialization failed during start_trace: Init failed. Cannot start trace."
|
||||
)
|
||||
|
||||
|
||||
def test_start_trace_auto_init_still_not_initialized():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.init") as _,
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_tracer.initialized = False
|
||||
|
||||
agentops.start_trace("test")
|
||||
mock_logger.error.assert_called_with("SDK initialization failed. Cannot start trace.")
|
||||
|
||||
|
||||
def test_end_trace_not_initialized():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.logger") as mock_logger:
|
||||
mock_tracer.initialized = False
|
||||
agentops.end_trace()
|
||||
mock_logger.warning.assert_called_with("AgentOps SDK not initialized. Cannot end trace.")
|
||||
|
||||
|
||||
def test_update_trace_metadata_not_initialized():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.logger") as mock_logger:
|
||||
mock_tracer.initialized = False
|
||||
agentops.update_trace_metadata({"foo": "bar"})
|
||||
mock_logger.warning.assert_called_with("AgentOps SDK not initialized. Cannot update trace metadata.")
|
||||
|
||||
|
||||
def test_all_exports_importable():
|
||||
# Just import all symbols to ensure they're present
|
||||
from agentops import (
|
||||
init,
|
||||
configure,
|
||||
)
|
||||
|
||||
assert callable(init)
|
||||
assert callable(configure)
|
||||
|
||||
|
||||
def test_update_trace_metadata_use_current_span_when_no_parent_found():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "child_span" # Not a session span
|
||||
mock_span.get_span_context.return_value.trace_id = 12345
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {"trace1": MagicMock()}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# When no parent trace is found, should use current span
|
||||
agentops.update_trace_metadata({"foo": "bar"})
|
||||
# The function should work with current span
|
||||
|
||||
|
||||
def test_update_trace_metadata_use_current_span_when_no_active_traces():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "child_span" # Not a session span
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# When no active traces, should use current span
|
||||
agentops.update_trace_metadata({"foo": "bar"})
|
||||
# The function should work with current span
|
||||
|
||||
|
||||
def test_update_trace_metadata_use_most_recent_trace():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span", return_value=None),
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_trace_context = MagicMock()
|
||||
mock_trace_context.span = MagicMock()
|
||||
mock_trace_context.span.is_recording.return_value = True
|
||||
mock_tracer.get_active_traces.return_value = {"trace1": mock_trace_context}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
agentops.update_trace_metadata({"foo": "bar"})
|
||||
mock_logger.debug.assert_called_with("Successfully updated 1 metadata attributes on trace")
|
||||
|
||||
|
||||
def test_end_trace_with_trace_context():
|
||||
with patch("agentops.tracer") as mock_tracer:
|
||||
mock_tracer.initialized = True
|
||||
mock_trace_context = MagicMock()
|
||||
agentops.end_trace(mock_trace_context, "Error")
|
||||
mock_tracer.end_trace.assert_called_with(trace_context=mock_trace_context, end_state="Error")
|
||||
|
||||
|
||||
def test_init_jupyter_detection_actual_nameerror():
|
||||
with patch("agentops.get_client") as mock_get_client:
|
||||
mock_client = MagicMock()
|
||||
mock_get_client.return_value = mock_client
|
||||
# Actually remove get_ipython to trigger NameError
|
||||
import builtins
|
||||
|
||||
original_get_ipython = getattr(builtins, "get_ipython", None)
|
||||
if hasattr(builtins, "get_ipython"):
|
||||
delattr(builtins, "get_ipython")
|
||||
try:
|
||||
agentops.init()
|
||||
finally:
|
||||
if original_get_ipython:
|
||||
builtins.get_ipython = original_get_ipython
|
||||
|
||||
|
||||
def test_end_trace_with_default_state():
|
||||
with patch("agentops.tracer") as mock_tracer:
|
||||
mock_tracer.initialized = True
|
||||
from agentops import TraceState
|
||||
|
||||
agentops.end_trace() # Should use default TraceState.SUCCESS
|
||||
mock_tracer.end_trace.assert_called_with(trace_context=None, end_state=TraceState.SUCCESS)
|
||||
|
||||
|
||||
def test_update_trace_metadata_extract_key_single_part_actual():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# Test with a semantic convention that has only one part (len < 2)
|
||||
with patch("agentops.AgentAttributes") as mock_attrs:
|
||||
mock_attrs.__dict__ = {"SINGLE": "single"}
|
||||
agentops.update_trace_metadata({"single": "test"})
|
||||
# The function should handle single-part attributes
|
||||
|
||||
|
||||
def test_update_trace_metadata_skip_gen_ai_attributes_actual():
|
||||
with patch("agentops.tracer") as mock_tracer, patch("agentops.get_current_span") as mock_get_span:
|
||||
mock_span = MagicMock()
|
||||
mock_span.is_recording.return_value = True
|
||||
mock_span.name = "foo.SESSION"
|
||||
mock_get_span.return_value = mock_span
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# Test that gen_ai attributes are actually skipped in the mapping
|
||||
with patch("agentops.AgentAttributes") as mock_attrs:
|
||||
mock_attrs.__dict__ = {"GEN_AI_ATTR": "gen_ai.something"}
|
||||
agentops.update_trace_metadata({"gen_ai.something": "test"})
|
||||
# Should still work but the gen_ai attribute should be skipped in mapping
|
||||
|
||||
|
||||
def test_update_trace_metadata_no_active_traces_actual():
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.get_current_span", return_value=None),
|
||||
patch("agentops.logger") as mock_logger,
|
||||
):
|
||||
mock_tracer.get_active_traces.return_value = {}
|
||||
mock_tracer.initialized = True
|
||||
agentops.update_trace_metadata({"foo": "bar"})
|
||||
mock_logger.warning.assert_called_with("No active trace found. Cannot update metadata.")
|
||||
@@ -0,0 +1,433 @@
|
||||
"""Tests for serialization helpers."""
|
||||
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from typing import Dict
|
||||
|
||||
import pytest
|
||||
|
||||
from agentops.helpers.serialization import (
|
||||
filter_unjsonable,
|
||||
is_jsonable,
|
||||
model_to_dict,
|
||||
safe_serialize,
|
||||
serialize_uuid,
|
||||
)
|
||||
|
||||
|
||||
# Define test models and data structures
|
||||
class SampleEnum(Enum):
|
||||
ONE = 1
|
||||
TWO = 2
|
||||
THREE = "three"
|
||||
|
||||
|
||||
class SimpleModel:
|
||||
"""A simple class with __dict__ but no model_dump or dict method."""
|
||||
|
||||
def __init__(self, value: str):
|
||||
self.value = value
|
||||
|
||||
|
||||
class ModelWithToJson:
|
||||
"""A class that implements to_json method."""
|
||||
|
||||
def __init__(self, data: Dict):
|
||||
self.data = data
|
||||
|
||||
def to_json(self):
|
||||
return self.data
|
||||
|
||||
|
||||
class PydanticV1Model:
|
||||
"""Mock Pydantic v1 model with dict method."""
|
||||
|
||||
def __init__(self, **data):
|
||||
self.__dict__.update(data)
|
||||
|
||||
def dict(self):
|
||||
return self.__dict__
|
||||
|
||||
|
||||
class PydanticV2Model:
|
||||
"""Mock Pydantic v2 model with model_dump method."""
|
||||
|
||||
def __init__(self, **data):
|
||||
self.__dict__.update(data)
|
||||
|
||||
def model_dump(self):
|
||||
return self.__dict__
|
||||
|
||||
|
||||
class ModelWithParse:
|
||||
"""Mock model with parse method."""
|
||||
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
|
||||
def parse(self):
|
||||
return self.data
|
||||
|
||||
|
||||
class ModelWithoutDict:
|
||||
"""A class without __dict__ attribute."""
|
||||
|
||||
__slots__ = ["value"]
|
||||
|
||||
def __init__(self, value: str):
|
||||
self.value = value
|
||||
|
||||
|
||||
# Define test cases for is_jsonable
|
||||
class TestIsJsonable:
|
||||
def test_jsonable_types(self):
|
||||
"""Test that jsonable types return True."""
|
||||
jsonable_objects = [
|
||||
"string",
|
||||
"",
|
||||
123,
|
||||
123.45,
|
||||
True,
|
||||
False,
|
||||
None,
|
||||
[1, 2, 3],
|
||||
{"key": "value"},
|
||||
[],
|
||||
{},
|
||||
]
|
||||
|
||||
for obj in jsonable_objects:
|
||||
assert is_jsonable(obj) is True
|
||||
|
||||
def test_unjsonable_types(self):
|
||||
"""Test that unjsonable types return False."""
|
||||
unjsonable_objects = [
|
||||
datetime.now(),
|
||||
uuid.uuid4(),
|
||||
Decimal("123.45"),
|
||||
{1, 2, 3}, # set
|
||||
SampleEnum.ONE,
|
||||
lambda x: x, # function
|
||||
object(), # generic object
|
||||
]
|
||||
|
||||
for obj in unjsonable_objects:
|
||||
assert is_jsonable(obj) is False
|
||||
|
||||
def test_circular_reference(self):
|
||||
"""Test that circular references are not jsonable."""
|
||||
a = {}
|
||||
b = {}
|
||||
a["b"] = b
|
||||
b["a"] = a
|
||||
|
||||
# The current implementation doesn't handle ValueError from circular references
|
||||
# So this will raise an exception instead of returning False
|
||||
with pytest.raises(ValueError, match="Circular reference detected"):
|
||||
is_jsonable(a)
|
||||
|
||||
|
||||
# Define test cases for filter_unjsonable
|
||||
class TestFilterUnjsonable:
|
||||
def test_filter_simple_dict(self):
|
||||
"""Test filtering of simple dictionary."""
|
||||
input_dict = {
|
||||
"string": "value",
|
||||
"number": 42,
|
||||
"list": [1, 2, 3],
|
||||
"dict": {"nested": "value"},
|
||||
"uuid": uuid.uuid4(),
|
||||
"datetime": datetime.now(),
|
||||
"set": {1, 2, 3},
|
||||
}
|
||||
|
||||
result = filter_unjsonable(input_dict)
|
||||
|
||||
# Check that jsonable values are preserved
|
||||
assert result["string"] == "value"
|
||||
assert result["number"] == 42
|
||||
assert result["list"] == [1, 2, 3]
|
||||
assert result["dict"] == {"nested": "value"}
|
||||
|
||||
# Check that unjsonable values are converted to strings or empty strings
|
||||
assert isinstance(result["uuid"], str)
|
||||
assert result["datetime"] == ""
|
||||
assert result["set"] == ""
|
||||
|
||||
def test_filter_nested_dict(self):
|
||||
"""Test filtering of nested dictionaries."""
|
||||
input_dict = {
|
||||
"level1": {
|
||||
"level2": {
|
||||
"uuid": uuid.uuid4(),
|
||||
"string": "preserved",
|
||||
"datetime": datetime.now(),
|
||||
}
|
||||
},
|
||||
"list_with_unjsonable": [
|
||||
{"uuid": uuid.uuid4()},
|
||||
"string",
|
||||
datetime.now(),
|
||||
],
|
||||
}
|
||||
|
||||
result = filter_unjsonable(input_dict)
|
||||
|
||||
# Check nested structure is preserved
|
||||
assert result["level1"]["level2"]["string"] == "preserved"
|
||||
assert isinstance(result["level1"]["level2"]["uuid"], str)
|
||||
assert result["level1"]["level2"]["datetime"] == ""
|
||||
|
||||
# Check list filtering
|
||||
assert result["list_with_unjsonable"][1] == "string"
|
||||
assert isinstance(result["list_with_unjsonable"][0]["uuid"], str)
|
||||
assert result["list_with_unjsonable"][2] == ""
|
||||
|
||||
def test_filter_list(self):
|
||||
"""Test filtering of lists."""
|
||||
input_list = [
|
||||
"string",
|
||||
42,
|
||||
uuid.uuid4(),
|
||||
datetime.now(),
|
||||
[1, 2, uuid.uuid4()],
|
||||
{"uuid": uuid.uuid4()},
|
||||
]
|
||||
|
||||
result = filter_unjsonable(input_list)
|
||||
|
||||
assert result[0] == "string"
|
||||
assert result[1] == 42
|
||||
assert isinstance(result[2], str) # UUID converted to string
|
||||
assert result[3] == "" # datetime converted to empty string
|
||||
assert isinstance(result[4][2], str) # nested UUID converted to string
|
||||
assert isinstance(result[5]["uuid"], str) # nested UUID converted to string
|
||||
|
||||
def test_filter_empty_structures(self):
|
||||
"""Test filtering of empty structures."""
|
||||
assert filter_unjsonable({}) == {}
|
||||
assert filter_unjsonable([]) == []
|
||||
assert filter_unjsonable({"empty": {}}) == {"empty": {}}
|
||||
|
||||
|
||||
# Define test cases for serialize_uuid
|
||||
class TestSerializeUuid:
|
||||
def test_serialize_uuid(self):
|
||||
"""Test UUID serialization."""
|
||||
test_uuid = uuid.uuid4()
|
||||
result = serialize_uuid(test_uuid)
|
||||
|
||||
assert isinstance(result, str)
|
||||
assert result == str(test_uuid)
|
||||
|
||||
def test_serialize_uuid_string(self):
|
||||
"""Test that UUID string representation is correct."""
|
||||
test_uuid = uuid.UUID("00000000-0000-0000-0000-000000000001")
|
||||
result = serialize_uuid(test_uuid)
|
||||
|
||||
assert result == "00000000-0000-0000-0000-000000000001"
|
||||
|
||||
|
||||
# Define test cases for safe_serialize
|
||||
class TestSafeSerialize:
|
||||
def test_strings_returned_untouched(self):
|
||||
"""Test that strings are returned untouched."""
|
||||
test_strings = [
|
||||
"simple string",
|
||||
"",
|
||||
"special chars: !@#$%^&*()",
|
||||
'{"json": "string"}', # JSON as a string
|
||||
"[1, 2, 3]", # JSON array as a string
|
||||
"line 1\nline 2", # String with newlines
|
||||
]
|
||||
|
||||
for input_str in test_strings:
|
||||
# The string should be returned exactly as is
|
||||
assert safe_serialize(input_str) == input_str
|
||||
|
||||
def test_complex_objects_serialized(self):
|
||||
"""Test that complex objects are properly serialized."""
|
||||
test_cases = [
|
||||
# Test case, expected serialized form (or None for dict check)
|
||||
({"key": "value"}, '{"key": "value"}'),
|
||||
([1, 2, 3], "[1, 2, 3]"),
|
||||
(123, "123"),
|
||||
(123.45, "123.45"),
|
||||
(True, "true"),
|
||||
(False, "false"),
|
||||
(None, "null"),
|
||||
]
|
||||
|
||||
for input_obj, expected in test_cases:
|
||||
result = safe_serialize(input_obj)
|
||||
if expected is not None:
|
||||
# Check exact match for simple cases
|
||||
assert json.loads(result) == json.loads(expected)
|
||||
else:
|
||||
# For complex cases just verify it's valid JSON
|
||||
assert isinstance(result, str)
|
||||
assert json.loads(result) is not None
|
||||
|
||||
def test_pydantic_models(self):
|
||||
"""Test serialization of Pydantic-like models."""
|
||||
# V1 model with dict()
|
||||
v1_model = PydanticV1Model(name="test", value=42)
|
||||
v1_result = safe_serialize(v1_model)
|
||||
assert json.loads(v1_result) == {"name": "test", "value": 42}
|
||||
|
||||
# V2 model with model_dump()
|
||||
v2_model = PydanticV2Model(name="test", value=42)
|
||||
v2_result = safe_serialize(v2_model)
|
||||
assert json.loads(v2_result) == {"name": "test", "value": 42}
|
||||
|
||||
# Note: parse() method is currently not implemented due to recursion issues
|
||||
# See TODO in serialization.py
|
||||
|
||||
def test_special_types(self):
|
||||
"""Test serialization of special types using AgentOpsJSONEncoder."""
|
||||
test_cases = [
|
||||
# Datetime
|
||||
(datetime(2023, 1, 1, 12, 0, 0), '"2023-01-01T12:00:00"'),
|
||||
# UUID
|
||||
(uuid.UUID("00000000-0000-0000-0000-000000000001"), '"00000000-0000-0000-0000-000000000001"'),
|
||||
# Decimal
|
||||
(Decimal("123.45"), '"123.45"'),
|
||||
# Set
|
||||
({1, 2, 3}, "[1, 2, 3]"),
|
||||
# Enum
|
||||
(SampleEnum.ONE, "1"),
|
||||
(SampleEnum.THREE, '"three"'),
|
||||
# Class with to_json
|
||||
(ModelWithToJson({"key": "value"}), '{"key": "value"}'),
|
||||
]
|
||||
|
||||
for input_obj, expected in test_cases:
|
||||
result = safe_serialize(input_obj)
|
||||
|
||||
# Handle list comparison for sets where order might vary
|
||||
if isinstance(input_obj, set):
|
||||
assert sorted(json.loads(result)) == sorted(json.loads(expected))
|
||||
else:
|
||||
assert json.loads(result) == json.loads(expected)
|
||||
|
||||
def test_nested_objects(self):
|
||||
"""Test serialization of nested objects."""
|
||||
nested_obj = {
|
||||
"string": "value",
|
||||
"number": 42,
|
||||
"list": [1, 2, {"inner": "value"}],
|
||||
"dict": {"inner": {"deeper": [1, 2, 3]}},
|
||||
"model": PydanticV2Model(name="test"),
|
||||
}
|
||||
|
||||
result = safe_serialize(nested_obj)
|
||||
|
||||
# Verify it's valid JSON
|
||||
parsed = json.loads(result)
|
||||
assert parsed["string"] == "value"
|
||||
assert parsed["number"] == 42
|
||||
assert parsed["list"][2]["inner"] == "value"
|
||||
assert parsed["dict"]["inner"]["deeper"] == [1, 2, 3]
|
||||
|
||||
# Just verify we have the model in some form
|
||||
assert "model" in parsed
|
||||
# And verify it contains the expected data in some form
|
||||
assert "test" in str(parsed["model"])
|
||||
|
||||
def test_fallback_to_str(self):
|
||||
"""Test fallback to str() for unserializable objects."""
|
||||
|
||||
class Unserializable:
|
||||
def __str__(self):
|
||||
return "Unserializable object"
|
||||
|
||||
obj = Unserializable()
|
||||
result = safe_serialize(obj)
|
||||
# The string is wrapped in quotes because it's serialized as a JSON string
|
||||
assert result == '"Unserializable object"'
|
||||
|
||||
def test_serialization_error_handling(self):
|
||||
"""Test handling of serialization errors."""
|
||||
|
||||
# Create an object that causes JSON serialization to fail
|
||||
class BadObject:
|
||||
def __init__(self):
|
||||
self.recursive = None
|
||||
|
||||
def __getitem__(self, key):
|
||||
# This will cause infinite recursion during JSON serialization
|
||||
return self.recursive
|
||||
|
||||
def __str__(self):
|
||||
return "BadObject representation"
|
||||
|
||||
bad_obj = BadObject()
|
||||
bad_obj.recursive = bad_obj
|
||||
|
||||
result = safe_serialize(bad_obj)
|
||||
assert result == '"BadObject representation"'
|
||||
|
||||
def test_value_error_handling(self):
|
||||
"""Test handling of ValueError during JSON serialization."""
|
||||
|
||||
# Create an object that causes a ValueError during JSON serialization
|
||||
class ValueErrorObject:
|
||||
def to_json(self):
|
||||
raise ValueError("Cannot serialize this object")
|
||||
|
||||
def __str__(self):
|
||||
return "ValueErrorObject representation"
|
||||
|
||||
obj = ValueErrorObject()
|
||||
result = safe_serialize(obj)
|
||||
assert result == "ValueErrorObject representation"
|
||||
|
||||
|
||||
class TestModelToDict:
|
||||
def test_none_returns_empty_dict(self):
|
||||
"""Test that None returns an empty dict."""
|
||||
assert model_to_dict(None) == {}
|
||||
|
||||
def test_dict_returns_unchanged(self):
|
||||
"""Test that a dict is returned unchanged."""
|
||||
test_dict = {"key": "value"}
|
||||
assert model_to_dict(test_dict) is test_dict
|
||||
|
||||
def test_pydantic_models(self):
|
||||
"""Test conversion of Pydantic-like models to dicts."""
|
||||
# V1 model with dict()
|
||||
v1_model = PydanticV1Model(name="test", value=42)
|
||||
assert model_to_dict(v1_model) == {"name": "test", "value": 42}
|
||||
|
||||
# V2 model with model_dump()
|
||||
v2_model = PydanticV2Model(name="test", value=42)
|
||||
assert model_to_dict(v2_model) == {"name": "test", "value": 42}
|
||||
|
||||
@pytest.mark.skip(reason="parse() method handling is currently commented out in the implementation")
|
||||
def test_parse_method(self):
|
||||
"""Test models with parse method."""
|
||||
parse_model = ModelWithParse({"name": "test", "value": 42})
|
||||
assert model_to_dict(parse_model) == {"name": "test", "value": 42}
|
||||
|
||||
def test_dict_fallback(self):
|
||||
"""Test fallback to __dict__."""
|
||||
simple_model = SimpleModel("test value")
|
||||
assert model_to_dict(simple_model) == {"value": "test value"}
|
||||
|
||||
def test_dict_fallback_exception_handling(self):
|
||||
"""Test exception handling in dict fallback."""
|
||||
# Test with object that has no __dict__ attribute
|
||||
model_without_dict = ModelWithoutDict("test value")
|
||||
assert model_to_dict(model_without_dict) == {}
|
||||
|
||||
# Test with object that raises exception when accessing __dict__
|
||||
class BadModel:
|
||||
@property
|
||||
def __dict__(self):
|
||||
raise AttributeError("No dict for you!")
|
||||
|
||||
bad_model = BadModel()
|
||||
assert model_to_dict(bad_model) == {}
|
||||
@@ -0,0 +1,676 @@
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# Tests for the new session management functionality
|
||||
# These tests call the actual public API but mock the underlying implementation
|
||||
# to avoid making real API calls or initializing the full telemetry pipeline
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def mock_tracing_core():
|
||||
"""Mock the global tracer to avoid actual initialization"""
|
||||
# Patch both the main location and where it's imported in client
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.client.client.tracer", mock_tracer),
|
||||
patch("agentops.sdk.decorators.factory.tracer", mock_tracer),
|
||||
patch("agentops.legacy.tracer", mock_tracer),
|
||||
):
|
||||
# Create a mock instance
|
||||
mock_tracer.initialized = True
|
||||
|
||||
yield mock_tracer
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def mock_api_client():
|
||||
"""Mock the API client to avoid actual API calls"""
|
||||
with patch("agentops.client.api.ApiClient") as mock_api:
|
||||
# Configure the v3.fetch_auth_token method to return a valid response
|
||||
mock_v3 = MagicMock()
|
||||
mock_v3.fetch_auth_token.return_value = {"token": "mock-jwt-token", "project_id": "mock-project-id"}
|
||||
mock_api.return_value.v3 = mock_v3
|
||||
|
||||
yield mock_api
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def mock_trace_context():
|
||||
"""Mock the TraceContext creation"""
|
||||
mock_span = MagicMock()
|
||||
mock_token = MagicMock()
|
||||
mock_trace_context_instance = MagicMock()
|
||||
mock_trace_context_instance.span = mock_span
|
||||
mock_trace_context_instance.token = mock_token
|
||||
mock_trace_context_instance.is_init_trace = False
|
||||
|
||||
return mock_trace_context_instance
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def reset_client():
|
||||
"""Reset the AgentOps client before each test"""
|
||||
import agentops
|
||||
|
||||
# Create a fresh client instance for each test
|
||||
agentops._client = agentops.Client()
|
||||
# Reset all client state
|
||||
agentops._client._initialized = False
|
||||
agentops._client._init_trace_context = None
|
||||
agentops._client._legacy_session_for_init_trace = None
|
||||
yield
|
||||
# Clean up after test
|
||||
try:
|
||||
if hasattr(agentops._client, "_initialized"):
|
||||
agentops._client._initialized = False
|
||||
if hasattr(agentops._client, "_init_trace_context"):
|
||||
agentops._client._init_trace_context = None
|
||||
if hasattr(agentops._client, "_legacy_session_for_init_trace"):
|
||||
agentops._client._legacy_session_for_init_trace = None
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
def test_explicit_init_then_explicit_start_trace(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test explicitly initializing followed by explicitly starting a trace"""
|
||||
import agentops
|
||||
|
||||
# Explicitly initialize with auto_start_session=False
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Verify that no auto-trace was started
|
||||
mock_tracing_core.start_trace.assert_not_called()
|
||||
|
||||
# Mock the start_trace method to return our mock trace context
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Explicitly start a trace
|
||||
trace_context = agentops.start_trace(trace_name="test_trace", tags=["test"])
|
||||
|
||||
# Verify the trace was created
|
||||
mock_tracing_core.start_trace.assert_called_once_with(trace_name="test_trace", tags=["test"])
|
||||
assert trace_context == mock_trace_context
|
||||
|
||||
|
||||
def test_auto_start_session_true(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test initializing with auto_start_session=True"""
|
||||
import agentops
|
||||
from agentops.legacy import Session
|
||||
|
||||
# Mock the start_trace method to return our mock trace context
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Initialize with auto_start_session=True
|
||||
result = agentops.init(api_key="test-api-key", auto_start_session=True)
|
||||
|
||||
# Verify a trace was auto-started
|
||||
mock_tracing_core.start_trace.assert_called_once()
|
||||
# init() should return a Session object when auto-starting a session
|
||||
assert isinstance(result, Session)
|
||||
# Check that the session's trace_context has the expected properties
|
||||
assert result.trace_context is not None
|
||||
|
||||
|
||||
def test_auto_start_session_default(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test initializing with default auto_start_session behavior"""
|
||||
import agentops
|
||||
from agentops.legacy import Session
|
||||
|
||||
# Mock the start_trace method to return our mock trace context
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Initialize without explicitly setting auto_start_session (defaults to True)
|
||||
result = agentops.init(api_key="test-api-key")
|
||||
|
||||
# Verify that the client was initialized
|
||||
assert agentops._client.initialized
|
||||
# Since auto_start_session defaults to True, init() should return a Session object
|
||||
assert isinstance(result, Session)
|
||||
# Check that the session's trace_context has the expected properties
|
||||
assert result.trace_context is not None
|
||||
|
||||
|
||||
def test_start_trace_without_init():
|
||||
"""Test starting a trace without initialization triggers auto-init"""
|
||||
import agentops
|
||||
|
||||
# Reset client for test
|
||||
agentops._client = agentops.Client()
|
||||
|
||||
# Mock global tracer to be uninitialized initially, then initialized after init
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.client.client.tracer", mock_tracer),
|
||||
patch("agentops.sdk.decorators.factory.tracer", mock_tracer),
|
||||
patch("agentops.legacy.tracer", mock_tracer),
|
||||
):
|
||||
mock_tracer.initialized = False
|
||||
|
||||
# Mock the init function to simulate successful initialization
|
||||
with patch("agentops.init") as mock_init:
|
||||
|
||||
def side_effect():
|
||||
# After init is called, mark global tracer as initialized
|
||||
mock_tracer.initialized = True
|
||||
|
||||
mock_init.side_effect = side_effect
|
||||
mock_tracer.start_trace.return_value = None
|
||||
|
||||
# Try to start a trace without initialization
|
||||
result = agentops.start_trace(trace_name="test_trace")
|
||||
|
||||
# Verify that init was called automatically
|
||||
mock_init.assert_called_once()
|
||||
# Should return None since start_trace returned None
|
||||
assert result is None
|
||||
|
||||
|
||||
def test_end_trace(mock_tracing_core, mock_trace_context):
|
||||
"""Test ending a trace"""
|
||||
import agentops
|
||||
|
||||
# End the trace
|
||||
agentops.end_trace(mock_trace_context, end_state="Success")
|
||||
|
||||
# Verify end_trace was called on global tracer
|
||||
mock_tracing_core.end_trace.assert_called_once_with(trace_context=mock_trace_context, end_state="Success")
|
||||
|
||||
|
||||
def test_session_decorator_creates_trace(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test that the @session decorator creates a trace-level span"""
|
||||
import agentops
|
||||
from agentops.sdk.decorators import session
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Reset the call count to start fresh
|
||||
mock_tracing_core.reset_mock()
|
||||
# Mock the start_trace and end_trace methods
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
@session(name="test_session", tags=["decorator_test"])
|
||||
def test_function():
|
||||
return "test_result"
|
||||
|
||||
# Execute the decorated function
|
||||
result = test_function()
|
||||
|
||||
# Verify the function executed successfully
|
||||
assert result == "test_result"
|
||||
|
||||
# Verify that start_trace and end_trace were called
|
||||
# Note: The decorator might call start_trace multiple times due to initialization
|
||||
assert mock_tracing_core.start_trace.call_count >= 1
|
||||
assert mock_tracing_core.end_trace.call_count >= 1
|
||||
|
||||
|
||||
def test_session_decorator_with_exception(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test that the @session decorator handles exceptions properly"""
|
||||
import agentops
|
||||
from agentops.sdk.decorators import session
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Reset the call count to start fresh
|
||||
mock_tracing_core.reset_mock()
|
||||
# Mock the start_trace method
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
@session(name="failing_session")
|
||||
def failing_function():
|
||||
raise ValueError("Test exception")
|
||||
|
||||
# Execute the decorated function and expect an exception
|
||||
with pytest.raises(ValueError, match="Test exception"):
|
||||
failing_function()
|
||||
|
||||
# Verify that start_trace was called
|
||||
assert mock_tracing_core.start_trace.call_count >= 1
|
||||
# Verify that end_trace was called
|
||||
assert mock_tracing_core.end_trace.call_count >= 1
|
||||
|
||||
|
||||
def test_legacy_start_session_compatibility(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test that legacy start_session still works and calls tracer.start_trace"""
|
||||
import agentops
|
||||
from agentops.legacy import Session
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Reset the call count to start fresh
|
||||
mock_tracing_core.reset_mock()
|
||||
# Mock the start_trace method
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Start a legacy session
|
||||
session = agentops.start_session(tags=["legacy_test"])
|
||||
|
||||
# Verify the session was created
|
||||
assert isinstance(session, Session)
|
||||
# Check that the session's trace_context has the expected properties
|
||||
assert session.trace_context is not None
|
||||
|
||||
# Verify that tracer.start_trace was called
|
||||
# Note: May be called multiple times due to initialization
|
||||
assert mock_tracing_core.start_trace.call_count >= 1
|
||||
|
||||
|
||||
def test_legacy_end_session_compatibility(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test that legacy end_session still works and calls tracer.end_trace"""
|
||||
import agentops
|
||||
from agentops.legacy import Session
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Reset the call count to start fresh
|
||||
mock_tracing_core.reset_mock()
|
||||
|
||||
# Create a legacy session object
|
||||
session = Session(mock_trace_context)
|
||||
|
||||
# End the session
|
||||
agentops.end_session(session)
|
||||
|
||||
# Verify that tracer.end_trace was called
|
||||
mock_tracing_core.end_trace.assert_called_once_with(mock_trace_context, end_state="Success")
|
||||
|
||||
|
||||
def test_no_double_init(mock_tracing_core, mock_api_client, reset_client):
|
||||
"""Test that calling init multiple times doesn't reinitialize"""
|
||||
import agentops
|
||||
|
||||
# Initialize once
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Track the call count
|
||||
call_count = mock_api_client.call_count
|
||||
|
||||
# Call init again with the same API key
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Verify that API client wasn't constructed again
|
||||
assert mock_api_client.call_count == call_count
|
||||
|
||||
|
||||
def test_client_initialization_behavior(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test basic client initialization behavior"""
|
||||
import agentops
|
||||
|
||||
# Mock the start_trace method
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Test that initialization works
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Verify that the client was initialized
|
||||
assert agentops._client.initialized
|
||||
|
||||
# The API client might not be called if already mocked at a higher level
|
||||
# Just verify that the initialization completed successfully
|
||||
|
||||
# Test that calling init again doesn't cause issues
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Should still be initialized
|
||||
assert agentops._client.initialized
|
||||
|
||||
|
||||
def test_multiple_concurrent_traces(mock_tracing_core, mock_api_client, reset_client):
|
||||
"""Test that multiple traces can be started concurrently"""
|
||||
import agentops
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Create mock trace contexts for different traces
|
||||
mock_trace_context_1 = MagicMock()
|
||||
mock_trace_context_2 = MagicMock()
|
||||
|
||||
# Mock start_trace to return different contexts
|
||||
mock_tracing_core.start_trace.side_effect = [
|
||||
mock_trace_context_1,
|
||||
mock_trace_context_2,
|
||||
]
|
||||
|
||||
# Start multiple traces
|
||||
trace1 = agentops.start_trace(trace_name="trace1", tags=["test1"])
|
||||
trace2 = agentops.start_trace(trace_name="trace2", tags=["test2"])
|
||||
|
||||
# Verify both traces were created
|
||||
assert trace1 == mock_trace_context_1
|
||||
assert trace2 == mock_trace_context_2
|
||||
|
||||
# Verify start_trace was called twice
|
||||
assert mock_tracing_core.start_trace.call_count == 2
|
||||
|
||||
|
||||
def test_trace_context_properties(mock_trace_context):
|
||||
"""Test that TraceContext properties work correctly"""
|
||||
from agentops.legacy import Session
|
||||
|
||||
# Create a legacy session with the mock trace context
|
||||
session = Session(mock_trace_context)
|
||||
|
||||
# Test that properties are accessible
|
||||
assert session.span == mock_trace_context.span
|
||||
assert session.token == mock_trace_context.token
|
||||
assert session.trace_context == mock_trace_context
|
||||
|
||||
|
||||
def test_session_decorator_async_function(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test that the @session decorator works with async functions"""
|
||||
import agentops
|
||||
import asyncio
|
||||
from agentops.sdk.decorators import session
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Reset the call count to start fresh
|
||||
mock_tracing_core.reset_mock()
|
||||
# Mock the start_trace method
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
@session(name="async_test_session")
|
||||
async def async_test_function():
|
||||
await asyncio.sleep(0.01) # Simulate async work
|
||||
return "async_result"
|
||||
|
||||
# Execute the decorated async function
|
||||
result = asyncio.run(async_test_function())
|
||||
|
||||
# Verify the function executed successfully
|
||||
assert result == "async_result"
|
||||
|
||||
# Verify that start_trace and end_trace were called
|
||||
assert mock_tracing_core.start_trace.call_count >= 1
|
||||
assert mock_tracing_core.end_trace.call_count >= 1
|
||||
|
||||
|
||||
def test_trace_context_creation():
|
||||
"""Test that TraceContext can be created with proper attributes"""
|
||||
from agentops.sdk.core import TraceContext
|
||||
|
||||
mock_span = MagicMock()
|
||||
mock_token = MagicMock()
|
||||
|
||||
# Test creating a TraceContext
|
||||
trace_context = TraceContext(span=mock_span, token=mock_token, is_init_trace=False)
|
||||
|
||||
assert trace_context.span == mock_span
|
||||
assert trace_context.token == mock_token
|
||||
assert trace_context.is_init_trace == False
|
||||
|
||||
|
||||
def test_session_management_integration():
|
||||
"""Test the integration between new and legacy session management"""
|
||||
import agentops
|
||||
|
||||
# Reset client for test
|
||||
agentops._client = agentops.Client()
|
||||
|
||||
# Test that we can use both new and legacy APIs together
|
||||
with (
|
||||
patch("agentops.tracer") as mock_tracer,
|
||||
patch("agentops.client.client.tracer", mock_tracer),
|
||||
patch("agentops.sdk.decorators.factory.tracer", mock_tracer),
|
||||
patch("agentops.legacy.tracer", mock_tracer),
|
||||
):
|
||||
mock_tracer.initialized = True
|
||||
|
||||
# Mock API client
|
||||
with patch("agentops.client.api.ApiClient") as mock_api:
|
||||
mock_v3 = MagicMock()
|
||||
mock_v3.fetch_auth_token.return_value = {"token": "mock-jwt-token", "project_id": "mock-project-id"}
|
||||
mock_api.return_value.v3 = mock_v3
|
||||
|
||||
# Initialize AgentOps
|
||||
agentops.init(api_key="test-api-key", auto_start_session=False)
|
||||
|
||||
# Reset call counts after initialization
|
||||
mock_tracer.reset_mock()
|
||||
|
||||
# Create mock trace context
|
||||
mock_trace_context = MagicMock()
|
||||
mock_tracer.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Test new API
|
||||
trace_context = agentops.start_trace(trace_name="new_api_trace")
|
||||
assert trace_context == mock_trace_context
|
||||
|
||||
# Test legacy API
|
||||
session = agentops.start_session(tags=["legacy"])
|
||||
# Check that the session's trace_context has the expected properties
|
||||
assert session.trace_context is not None
|
||||
|
||||
# Test ending both
|
||||
agentops.end_trace(trace_context)
|
||||
agentops.end_session(session)
|
||||
|
||||
# Verify calls were made
|
||||
assert mock_tracer.start_trace.call_count >= 2
|
||||
assert mock_tracer.end_trace.call_count >= 2
|
||||
|
||||
|
||||
# CrewAI Backwards Compatibility Tests
|
||||
# These tests ensure CrewAI integration patterns continue to work
|
||||
|
||||
|
||||
def test_session_auto_start(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""Test auto-start session functionality for CrewAI compatibility"""
|
||||
import agentops
|
||||
from agentops.legacy import Session
|
||||
|
||||
# Configure mocks for session initialization
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Pass a dummy API key for the test
|
||||
session = agentops.init(api_key="test-api-key", auto_start_session=True)
|
||||
|
||||
assert isinstance(session, Session)
|
||||
|
||||
|
||||
def test_crewai_backwards_compatibility(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""
|
||||
CrewAI needs to access:
|
||||
|
||||
agentops.track_agent
|
||||
agentops.track_tool
|
||||
agentops.start_session
|
||||
agentops.end_session
|
||||
agentops.ActionEvent
|
||||
agentops.ToolEvent
|
||||
"""
|
||||
import agentops
|
||||
from agentops.legacy import Session
|
||||
|
||||
# Configure mocks
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Test initialization with API key
|
||||
agentops.init(api_key="test-api-key")
|
||||
|
||||
# Test session management functions
|
||||
session = agentops.start_session(tags=["test", "crewai"])
|
||||
assert isinstance(session, Session)
|
||||
|
||||
# Test that passing a string to end_session doesn't raise an error
|
||||
agentops.end_session("Success") # This pattern is used in CrewAI
|
||||
|
||||
# Test track_agent function exists and doesn't raise errors
|
||||
try:
|
||||
# Mock an agent object similar to what CrewAI would provide
|
||||
class MockAgent:
|
||||
def __init__(self):
|
||||
self.role = "Test Agent"
|
||||
self.goal = "Testing"
|
||||
self.id = "test-agent-id"
|
||||
|
||||
agent = MockAgent()
|
||||
agentops.track_agent(agent)
|
||||
except Exception as e:
|
||||
assert False, f"track_agent raised an exception: {e}"
|
||||
|
||||
# Test track_tool function exists and doesn't raise errors
|
||||
try:
|
||||
# Mock a tool object similar to what CrewAI would provide
|
||||
class MockTool:
|
||||
def __init__(self):
|
||||
self.name = "Test Tool"
|
||||
self.description = "A test tool"
|
||||
|
||||
tool = MockTool()
|
||||
agentops.track_tool(tool, "Test Agent")
|
||||
except Exception as e:
|
||||
assert False, f"track_tool raised an exception: {e}"
|
||||
|
||||
# Test events that CrewAI might use
|
||||
tool_event = agentops.ToolEvent(name="test_tool")
|
||||
action_event = agentops.ActionEvent(action_type="test_action")
|
||||
|
||||
# Verify that record function works with these events
|
||||
agentops.record(tool_event)
|
||||
agentops.record(action_event)
|
||||
|
||||
|
||||
def test_crewai_kwargs_pattern(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""
|
||||
Test the CrewAI < 0.105.0 pattern where end_session is called with only kwargs.
|
||||
|
||||
In versions < 0.105.0, CrewAI directly calls:
|
||||
agentops.end_session(
|
||||
end_state="Success",
|
||||
end_state_reason="Finished Execution",
|
||||
is_auto_end=True
|
||||
)
|
||||
"""
|
||||
import agentops
|
||||
from agentops.legacy import Session
|
||||
|
||||
# Configure mocks
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Initialize with test API key
|
||||
agentops.init(api_key="test-api-key")
|
||||
|
||||
# Create a session
|
||||
session = agentops.start_session(tags=["test", "crewai-kwargs"])
|
||||
assert isinstance(session, Session)
|
||||
|
||||
# Test the CrewAI < 0.105.0 pattern - calling end_session with only kwargs
|
||||
agentops.end_session(end_state="Success", end_state_reason="Finished Execution", is_auto_end=True)
|
||||
|
||||
# After calling end_session, creating a new session should work correctly
|
||||
# (this implicitly tests that the internal state is reset properly)
|
||||
new_session = agentops.start_session(tags=["test", "post-end"])
|
||||
assert isinstance(new_session, Session)
|
||||
|
||||
|
||||
def test_crewai_kwargs_pattern_no_session(mock_tracing_core, mock_api_client, reset_client):
|
||||
"""
|
||||
Test the CrewAI < 0.105.0 pattern where end_session is called with only kwargs,
|
||||
but no session has been created.
|
||||
|
||||
This should log a warning but not fail.
|
||||
"""
|
||||
import agentops
|
||||
|
||||
# Initialize with test API key
|
||||
agentops.init(api_key="test-api-key")
|
||||
|
||||
# We don't need to explicitly clear the session state
|
||||
# Just make sure we start with a clean state by calling init
|
||||
|
||||
# Test the CrewAI < 0.105.0 pattern - calling end_session with only kwargs
|
||||
# when no session exists. This should not raise an error.
|
||||
agentops.end_session(end_state="Success", end_state_reason="Finished Execution", is_auto_end=True)
|
||||
|
||||
|
||||
def test_crewai_kwargs_force_flush(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""
|
||||
Test that when using the CrewAI < 0.105.0 pattern (end_session with kwargs),
|
||||
the spans are properly exported to the backend with force_flush.
|
||||
|
||||
This is a more comprehensive test that ensures spans are actually sent
|
||||
to the backend when using the CrewAI integration pattern.
|
||||
"""
|
||||
import agentops
|
||||
import time
|
||||
|
||||
# Configure mocks
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Initialize AgentOps with API key
|
||||
agentops.init(api_key="test-api-key")
|
||||
|
||||
# Create a session
|
||||
agentops.start_session(tags=["test", "crewai-integration"])
|
||||
|
||||
# Simulate some work
|
||||
time.sleep(0.1)
|
||||
|
||||
# End session with kwargs (CrewAI < 0.105.0 pattern)
|
||||
agentops.end_session(end_state="Success", end_state_reason="Test Finished", is_auto_end=True)
|
||||
|
||||
# Explicitly ensure the core isn't already shut down for the test
|
||||
# Note: We're using mocks, so we check the mock's initialized state
|
||||
assert mock_tracing_core.initialized, "Mocked tracer should still be initialized"
|
||||
|
||||
|
||||
def test_crewai_task_instrumentation(mock_tracing_core, mock_api_client, mock_trace_context, reset_client):
|
||||
"""
|
||||
Test the CrewAI task instrumentation focusing on span attributes and tags.
|
||||
This test verifies that task spans are properly created with correct attributes
|
||||
and tags without requiring a session.
|
||||
"""
|
||||
import agentops
|
||||
from opentelemetry.trace import SpanKind
|
||||
from agentops.semconv import SpanAttributes, AgentOpsSpanKindValues
|
||||
from opentelemetry import trace
|
||||
from agentops.semconv.core import CoreAttributes
|
||||
|
||||
# Configure mocks
|
||||
mock_tracing_core.start_trace.return_value = mock_trace_context
|
||||
|
||||
# Initialize AgentOps with API key and default tags
|
||||
agentops.init(
|
||||
api_key="test-api-key",
|
||||
)
|
||||
agentops.start_session(tags=["test", "crewai-integration"])
|
||||
# Get the tracer
|
||||
tracer = trace.get_tracer(__name__)
|
||||
|
||||
# Create a mock task instance
|
||||
class MockTask:
|
||||
def __init__(self):
|
||||
self.description = "Test Task Description"
|
||||
self.agent = "Test Agent"
|
||||
self.tools = ["tool1", "tool2"]
|
||||
|
||||
task = MockTask()
|
||||
|
||||
# Start a span for the task
|
||||
with tracer.start_as_current_span(
|
||||
f"{task.description}.task",
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={
|
||||
SpanAttributes.AGENTOPS_SPAN_KIND: AgentOpsSpanKindValues.TASK.value,
|
||||
CoreAttributes.TAGS: ["crewai", "task-test"],
|
||||
},
|
||||
) as span:
|
||||
# Verify span attributes
|
||||
assert span.attributes[SpanAttributes.AGENTOPS_SPAN_KIND] == AgentOpsSpanKindValues.TASK.value
|
||||
assert "crewai" in span.attributes[CoreAttributes.TAGS]
|
||||
assert "task-test" in span.attributes[CoreAttributes.TAGS]
|
||||
|
||||
# Verify span name
|
||||
assert span.name == f"{task.description}.task"
|
||||
|
||||
# Verify span kind
|
||||
assert span.kind == SpanKind.CLIENT
|
||||
|
||||
agentops.end_session(end_state="Success", end_state_reason="Test Finished", is_auto_end=True)
|
||||
@@ -0,0 +1,34 @@
|
||||
import pytest
|
||||
import requests
|
||||
from unittest.mock import patch
|
||||
from agentops.client.http.http_client import HttpClient
|
||||
from agentops.helpers.version import get_agentops_version
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_http_client_session():
|
||||
# Reset the cached session before each test
|
||||
HttpClient._session = None
|
||||
|
||||
|
||||
def test_user_agent_header():
|
||||
with patch("requests.Session", wraps=requests.Session):
|
||||
session = HttpClient.get_session()
|
||||
expected_version = get_agentops_version() or "unknown"
|
||||
expected_user_agent = f"agentops-python/{expected_version}"
|
||||
# Check the session's headers directly
|
||||
assert "User-Agent" in session.headers
|
||||
assert session.headers["User-Agent"] == expected_user_agent
|
||||
|
||||
|
||||
def test_user_agent_header_content():
|
||||
with patch("requests.Session", wraps=requests.Session):
|
||||
session = HttpClient.get_session()
|
||||
# Check the session's headers directly
|
||||
assert "User-Agent" in session.headers
|
||||
assert "Connection" in session.headers
|
||||
assert "Keep-Alive" in session.headers
|
||||
assert "Content-Type" in session.headers
|
||||
assert session.headers["Connection"] == "keep-alive"
|
||||
assert session.headers["Keep-Alive"] == "timeout=10, max=1000"
|
||||
assert session.headers["Content-Type"] == "application/json"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user