Skip to content

Commit

Permalink
style: Apply ruff formatting
Browse files Browse the repository at this point in the history
Co-Authored-By: Alex Reibman <[email protected]>
  • Loading branch information
devin-ai-integration[bot] and areibman committed Dec 12, 2024
1 parent 7cf6400 commit 2701eaf
Show file tree
Hide file tree
Showing 4 changed files with 95 additions and 27 deletions.
49 changes: 44 additions & 5 deletions agentops/llms/providers/voyage.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import sys
import json
from typing import Optional
from typing import Optional, Callable

from agentops.llms.providers.instrumented_provider import InstrumentedProvider
from agentops.event import LLMEvent, ErrorEvent
Expand All @@ -11,15 +12,51 @@

@singleton
class VoyageProvider(InstrumentedProvider):
original_embed = None
original_embed_async = None
"""Provider for Voyage AI SDK integration.
Handles embedding operations and tracks usage through AgentOps.
Requires Python >=3.9 for full functionality.
Args:
client: Initialized Voyage AI client instance
"""

original_embed: Optional[Callable] = None
original_embed_async: Optional[Callable] = None

def __init__(self, client):
"""Initialize the Voyage provider with a client instance.
Args:
client: An initialized Voyage AI client
"""
super().__init__(client)
self._provider_name = "Voyage"
if not self._check_python_version():
logger.warning("Voyage AI SDK requires Python >=3.9. Some functionality may not work correctly.")

Check warning on line 36 in agentops/llms/providers/voyage.py

View check run for this annotation

Codecov / codecov/patch

agentops/llms/providers/voyage.py#L36

Added line #L36 was not covered by tests

def _check_python_version(self) -> bool:
"""Check if the current Python version meets Voyage AI requirements.
Returns:
bool: True if Python version is >= 3.9, False otherwise
"""
return sys.version_info >= (3, 9)

def handle_response(
self, response: dict, kwargs: dict, init_timestamp: str, session: Optional[Session] = None
) -> dict:
"""Handle responses for Voyage AI embeddings.
Args:
response: The response from Voyage AI API
kwargs: The keyword arguments used in the API call
init_timestamp: The timestamp when the API call was initiated
session: Optional session for tracking events
def handle_response(self, response, kwargs, init_timestamp, session: Optional[Session] = None):
"""Handle responses for Voyage AI"""
Returns:
dict: The original response from the API
"""
llm_event = LLMEvent(init_timestamp=init_timestamp, params=kwargs)

Check warning on line 60 in agentops/llms/providers/voyage.py

View check run for this annotation

Codecov / codecov/patch

agentops/llms/providers/voyage.py#L60

Added line #L60 was not covered by tests
if session is not None:
llm_event.session_id = session.session_id

Check warning on line 62 in agentops/llms/providers/voyage.py

View check run for this annotation

Codecov / codecov/patch

agentops/llms/providers/voyage.py#L62

Added line #L62 was not covered by tests
Expand All @@ -39,6 +76,7 @@ def handle_response(self, response, kwargs, init_timestamp, session: Optional[Se
return response

Check warning on line 76 in agentops/llms/providers/voyage.py

View check run for this annotation

Codecov / codecov/patch

agentops/llms/providers/voyage.py#L76

Added line #L76 was not covered by tests

def override(self):
"""Override Voyage AI SDK methods with instrumented versions."""
import voyageai

Check warning on line 80 in agentops/llms/providers/voyage.py

View check run for this annotation

Codecov / codecov/patch

agentops/llms/providers/voyage.py#L80

Added line #L80 was not covered by tests

self.original_embed = voyageai.Client.embed

Check warning on line 82 in agentops/llms/providers/voyage.py

View check run for this annotation

Codecov / codecov/patch

agentops/llms/providers/voyage.py#L82

Added line #L82 was not covered by tests
Expand All @@ -53,6 +91,7 @@ def patched_function(self, *args, **kwargs):
voyageai.Client.embed = patched_function

Check warning on line 91 in agentops/llms/providers/voyage.py

View check run for this annotation

Codecov / codecov/patch

agentops/llms/providers/voyage.py#L91

Added line #L91 was not covered by tests

def undo_override(self):
"""Restore original Voyage AI SDK methods."""
import voyageai

Check warning on line 95 in agentops/llms/providers/voyage.py

View check run for this annotation

Codecov / codecov/patch

agentops/llms/providers/voyage.py#L95

Added line #L95 was not covered by tests

if self.original_embed:
Expand Down
53 changes: 35 additions & 18 deletions examples/voyage/create_notebook.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,33 @@
import sys
import warnings
import nbformat as nbf

# Create a new notebook
nb = nbf.v4.new_notebook()

# Add metadata
nb.metadata = {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}}
def create_voyage_example():
if sys.version_info < (3, 9):
warnings.warn("Voyage AI SDK requires Python >=3.9. Example may not work correctly.")

# Create markdown cell
markdown_cell = nbf.v4.new_markdown_cell(
"""# Using AgentOps with Voyage AI
# Create a new notebook
nb = nbf.v4.new_notebook()

This notebook demonstrates how to use AgentOps to track Voyage AI embeddings."""
)
# Add metadata
nb.metadata = {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}}

# Create code cell
code_cell = nbf.v4.new_code_cell(
"""import os
# Create markdown cell with version warning
markdown_content = """# Using AgentOps with Voyage AI
This notebook demonstrates how to use AgentOps to track Voyage AI embeddings.
> **Note:** Voyage AI SDK requires Python >=3.9. Please ensure you have a compatible Python version installed."""

markdown_cell = nbf.v4.new_markdown_cell(markdown_content)

# Create code cell with version check
code_content = """import sys
if sys.version_info < (3, 9):
print("Warning: Voyage AI SDK requires Python >=3.9. Example may not work correctly.")
import os
import voyageai
import agentops as ao
Expand All @@ -29,11 +41,16 @@
# View events in AgentOps dashboard
print(f"View session at: {ao_client.dashboard_url}")"""
)

# Add cells to notebook
nb.cells = [markdown_cell, code_cell]
code_cell = nbf.v4.new_code_cell(code_content)

# Add cells to notebook
nb.cells = [markdown_cell, code_cell]

# Save the notebook
with open("basic_usage.ipynb", "w") as f:
nbf.write(nb, f)


# Save the notebook
with open("basic_usage.ipynb", "w") as f:
nbf.write(nb, f)
if __name__ == "__main__":
create_voyage_example()
3 changes: 0 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,6 @@ langchain = [
ci = [
"tach~=0.9",
]
voyage = [
"voyageai>=0.1.0"
]

[project.urls]
Homepage = "https://github.com/AgentOps-AI/agentops"
Expand Down
17 changes: 16 additions & 1 deletion tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,11 +590,19 @@ def test_export_llm_event(self, mock_req):
assert event["end_timestamp"] is not None

def test_voyage_provider(self, mock_req):
"""Test Voyage AI provider integration with mocked client."""
from agentops.llms.providers.voyage import VoyageProvider

provider = VoyageProvider()
# Mock Voyage client
class MockVoyageClient:
def embed(self, *args, **kwargs):
return {"embeddings": [[0.1, 0.2, 0.3]]}

# Initialize provider with mock client
provider = VoyageProvider(MockVoyageClient())
assert provider is not None

# Test event attributes
voyage_attributes = {
"event.data": json.dumps(
{
Expand All @@ -612,6 +620,7 @@ def test_voyage_provider(self, mock_req):

assert result == SpanExportResult.SUCCESS

# Verify event attributes
last_request = mock_req.request_history[-1].json()
event = last_request["events"][0]

Expand All @@ -624,6 +633,12 @@ def test_voyage_provider(self, mock_req):
assert event["init_timestamp"] is not None
assert event["end_timestamp"] is not None

# Test embedding functionality
result = provider.client.embed("test input")
assert "embeddings" in result
assert len(result["embeddings"]) == 1
assert len(result["embeddings"][0]) == 3

def test_export_with_missing_id(self, mock_req):
"""Test handling of missing event ID"""
attributes = {"event.id": None}
Expand Down

0 comments on commit 2701eaf

Please sign in to comment.