sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
vanna-ai/vanna:src/vanna/examples/anthropic_quickstart.py | """
Anthropic example using AnthropicLlmService.
Loads environment from .env (via python-dotenv), uses model 'claude-sonnet-4-20250514'
by default, and sends a simple message through a Agent.
Run:
PYTHONPATH=. python vanna/examples/anthropic_quickstart.py
"""
import asyncio
import importlib.util
import os
import sys
def ensure_env() -> None:
if importlib.util.find_spec("dotenv") is not None:
from dotenv import load_dotenv
# Load from local .env without overriding existing env
load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"), override=False)
else:
print(
"[warn] python-dotenv not installed; skipping .env load. Install with: pip install python-dotenv"
)
if not os.getenv("ANTHROPIC_API_KEY"):
print(
"[error] ANTHROPIC_API_KEY is not set. Add it to your environment or .env file."
)
sys.exit(1)
async def main() -> None:
ensure_env()
try:
from vanna.integrations.anthropic import AnthropicLlmService
except ImportError:
print(
"[error] anthropic extra not installed. Install with: pip install -e .[anthropic]"
)
raise
from vanna import AgentConfig, Agent, User
from vanna.core.registry import ToolRegistry
from vanna.tools import ListFilesTool
model = os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-20250514")
print(f"Using Anthropic model: {model}")
llm = AnthropicLlmService(model=model)
# Create tool registry and register the list_files tool
tool_registry = ToolRegistry()
list_files_tool = ListFilesTool()
tool_registry.register(list_files_tool)
agent = Agent(
llm_service=llm,
config=AgentConfig(stream_responses=False),
tool_registry=tool_registry,
)
user = User(id="demo-user", username="demo")
conversation_id = "anthropic-demo"
print("Sending: 'List the files in the current directory'\n")
async for component in agent.send_message(
user=user,
message="List the files in the current directory",
conversation_id=conversation_id,
):
if hasattr(component, "content") and component.content:
print("Assistant:", component.content)
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/anthropic_quickstart.py",
"license": "MIT License",
"lines": 61,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/examples/artifact_example.py | #!/usr/bin/env python3
"""
Example demonstrating the artifact system in Vanna Agents.
This script shows how agents can create interactive artifacts that can be
rendered externally by developers listening for the 'artifact-opened' event.
"""
import asyncio
from typing import AsyncGenerator, Optional
from vanna import Agent, UiComponent, User, AgentConfig
from vanna.core.rich_components import ArtifactComponent
from vanna.integrations.anthropic.mock import MockLlmService
from vanna.core.interfaces import Agent, LlmService
class ArtifactDemoAgent(Agent):
"""Demo agent that creates various types of artifacts."""
def __init__(self, llm_service: Optional[LlmService] = None) -> None:
if llm_service is None:
llm_service = MockLlmService(
"I'll help you create interactive artifacts! Try asking me to create a chart, dashboard, or interactive HTML widget."
)
super().__init__(
llm_service=llm_service,
config=AgentConfig(
stream_responses=True,
include_thinking_indicators=True,
),
)
async def send_message(
self, user: User, message: str, *, conversation_id: Optional[str] = None
) -> AsyncGenerator[UiComponent, None]:
"""Handle user messages and create appropriate artifacts."""
# First send the normal response
async for component in super().send_message(
user, message, conversation_id=conversation_id
):
yield component
# Then create artifacts based on message content
message_lower = message.lower()
if any(
word in message_lower for word in ["chart", "graph", "visualization", "d3"]
):
async for component in self.create_d3_visualization():
yield component
elif any(
word in message_lower for word in ["dashboard", "analytics", "metrics"]
):
async for component in self.create_dashboard_artifact():
yield component
elif any(
word in message_lower for word in ["html", "interactive", "widget", "demo"]
):
async for component in self.create_html_artifact():
yield component
async def create_html_artifact(self) -> AsyncGenerator[UiComponent, None]:
"""Create a simple HTML artifact."""
html_content = """
<div style="padding: 20px; font-family: Arial, sans-serif;">
<h2 style="color: #333;">Interactive HTML Artifact</h2>
<p>This is a simple HTML artifact that can be opened externally.</p>
<button onclick="alert('Hello from the artifact!')">Click me!</button>
<div style="margin-top: 20px;">
<input type="text" placeholder="Type something..." id="textInput">
<button onclick="document.getElementById('output').textContent = document.getElementById('textInput').value">
Update Text
</button>
</div>
<div id="output" style="margin-top: 10px; padding: 10px; background: #f0f0f0; border-radius: 4px;">
Output will appear here...
</div>
</div>
"""
artifact = ArtifactComponent.create_html(
content=html_content,
title="Interactive HTML Demo",
description="A simple HTML artifact with interactive elements",
)
yield UiComponent(rich_component=artifact)
async def create_d3_visualization(self) -> AsyncGenerator[UiComponent, None]:
"""Create a D3.js visualization artifact."""
d3_content = """
<div id="chart" style="width: 100%; height: 400px;"></div>
<script>
// Sample data
const data = [
{name: 'A', value: 30},
{name: 'B', value: 80},
{name: 'C', value: 45},
{name: 'D', value: 60},
{name: 'E', value: 20},
{name: 'F', value: 90}
];
// Set up dimensions
const margin = {top: 20, right: 30, bottom: 40, left: 40};
const width = 800 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
// Create SVG
const svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Create scales
const xScale = d3.scaleBand()
.domain(data.map(d => d.name))
.range([0, width])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([height, 0]);
// Create bars
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", d => xScale(d.name))
.attr("width", xScale.bandwidth())
.attr("y", d => yScale(d.value))
.attr("height", d => height - yScale(d.value))
.attr("fill", "#4CAF50")
.on("mouseover", function(event, d) {
d3.select(this).attr("fill", "#45a049");
})
.on("mouseout", function(event, d) {
d3.select(this).attr("fill", "#4CAF50");
});
// Add axes
svg.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale));
svg.append("g")
.call(d3.axisLeft(yScale));
</script>
"""
artifact = ArtifactComponent.create_d3(
content=d3_content,
title="D3.js Bar Chart",
description="An interactive bar chart built with D3.js",
)
yield UiComponent(rich_component=artifact)
async def create_dashboard_artifact(self) -> AsyncGenerator[UiComponent, None]:
"""Create a dashboard-style artifact."""
dashboard_content = """
<div style="padding: 20px; font-family: Arial, sans-serif; background: #f5f5f5; min-height: 100vh;">
<h1 style="color: #333; margin-bottom: 30px;">Analytics Dashboard</h1>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px;">
<div class="metric-card" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h3 style="margin: 0; color: #666;">Total Users</h3>
<p style="font-size: 2em; font-weight: bold; color: #333; margin: 10px 0;">12,456</p>
<span style="color: #4CAF50;">↗ +5.2%</span>
</div>
<div class="metric-card" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h3 style="margin: 0; color: #666;">Revenue</h3>
<p style="font-size: 2em; font-weight: bold; color: #333; margin: 10px 0;">$89,432</p>
<span style="color: #4CAF50;">↗ +12.3%</span>
</div>
<div class="metric-card" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h3 style="margin: 0; color: #666;">Conversion Rate</h3>
<p style="font-size: 2em; font-weight: bold; color: #333; margin: 10px 0;">3.4%</p>
<span style="color: #f44336;">↘ -0.8%</span>
</div>
</div>
<div style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h3 style="margin: 0 0 20px 0; color: #333;">Quick Actions</h3>
<div style="display: flex; gap: 10px; flex-wrap: wrap;">
<button onclick="alert('Export feature coming soon!')"
style="padding: 10px 20px; background: #2196F3; color: white; border: none; border-radius: 4px; cursor: pointer;">
Export Data
</button>
<button onclick="alert('Refresh complete!')"
style="padding: 10px 20px; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">
Refresh
</button>
<button onclick="alert('Settings panel opened!')"
style="padding: 10px 20px; background: #FF9800; color: white; border: none; border-radius: 4px; cursor: pointer;">
Settings
</button>
</div>
</div>
</div>
"""
artifact = ArtifactComponent(
content=dashboard_content,
artifact_type="dashboard",
title="Analytics Dashboard",
description="A sample analytics dashboard with metrics and controls",
external_renderable=True,
fullscreen_capable=True,
)
yield UiComponent(rich_component=artifact)
def create_demo_agent() -> ArtifactDemoAgent:
"""Create a demo agent for REPL and server usage.
Returns:
Configured ArtifactDemoAgent instance
"""
return ArtifactDemoAgent()
async def main() -> None:
"""Main demo function."""
print("🎨 Artifact Demo Agent")
print("This demo shows how to create different types of artifacts.")
print(
"In a real web application, developers can listen for 'artifact-opened' events."
)
print()
demo_agent = create_demo_agent()
user = User(id="demo_user", username="artifact_demo")
# Demo 1: HTML Artifact
print("1. Creating HTML Artifact...")
async for component in demo_agent.create_html_artifact():
artifact = component.rich_component
if isinstance(artifact, ArtifactComponent):
print(f" ✓ Created HTML artifact: {artifact.title}")
print(f" ✓ Artifact ID: {artifact.artifact_id}")
print(f" ✓ Type: {artifact.artifact_type}")
print(f" ✓ External renderable: {artifact.external_renderable}")
print()
# Demo 2: D3 Visualization
print("2. Creating D3.js Visualization...")
async for component in demo_agent.create_d3_visualization():
artifact = component.rich_component
if isinstance(artifact, ArtifactComponent):
print(f" ✓ Created D3 artifact: {artifact.title}")
print(f" ✓ Dependencies: {artifact.dependencies}")
print(f" ✓ Standalone HTML available via get_standalone_html()")
print()
# Demo 3: Dashboard
print("3. Creating Dashboard Artifact...")
async for component in demo_agent.create_dashboard_artifact():
artifact = component.rich_component
if isinstance(artifact, ArtifactComponent):
print(f" ✓ Created dashboard artifact: {artifact.title}")
print(f" ✓ Fullscreen capable: {artifact.fullscreen_capable}")
print()
print("🚀 Web Integration Example:")
print("""
In your web application, listen for the 'artifact-opened' event:
document.querySelector('vanna-chat').addEventListener('artifact-opened', (event) => {
const { artifactId, content, type, trigger } = event.detail;
if (trigger === 'created' && type === 'dashboard') {
// Auto-open dashboards in external window
const newWindow = window.open('', '_blank');
newWindow.document.write(event.detail.getStandaloneHTML());
newWindow.document.close();
// Prevent default rendering in chat
event.detail.preventDefault();
}
});
""")
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/artifact_example.py",
"license": "MIT License",
"lines": 249,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
vanna-ai/vanna:src/vanna/examples/claude_sqlite_example.py | """
Claude example using the SQL query tool with the Chinook database.
This example demonstrates using the RunSqlTool with SqliteRunner and Claude's AI
to intelligently query and analyze the Chinook database, with automatic visualization support.
Requirements:
- ANTHROPIC_API_KEY environment variable or .env file
- anthropic package: pip install -e .[anthropic]
- plotly package: pip install -e .[visualization]
Usage:
PYTHONPATH=. python vanna/examples/claude_sqlite_example.py
"""
import asyncio
import importlib.util
import os
import sys
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from vanna import Agent
def ensure_env() -> None:
if importlib.util.find_spec("dotenv") is not None:
from dotenv import load_dotenv
# Load from local .env without overriding existing env
load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"), override=False)
else:
print(
"[warn] python-dotenv not installed; skipping .env load. Install with: pip install python-dotenv"
)
if not os.getenv("ANTHROPIC_API_KEY"):
print(
"[error] ANTHROPIC_API_KEY is not set. Add it to your environment or .env file."
)
sys.exit(1)
async def main() -> None:
ensure_env()
try:
from vanna.integrations.anthropic import AnthropicLlmService
except ImportError:
print(
"[error] anthropic extra not installed. Install with: pip install -e .[anthropic]"
)
raise
from vanna import AgentConfig, Agent
from vanna.core.registry import ToolRegistry
from vanna.core.user import CookieEmailUserResolver, RequestContext
from vanna.integrations.sqlite import SqliteRunner
from vanna.tools import (
RunSqlTool,
VisualizeDataTool,
LocalFileSystem,
)
# Get the path to the Chinook database
database_path = os.path.join(
os.path.dirname(__file__), "..", "..", "Chinook.sqlite"
)
database_path = os.path.abspath(database_path)
if not os.path.exists(database_path):
print(f"[error] Chinook database not found at {database_path}")
print(
"Please download it with: curl -o Chinook.sqlite https://vanna.ai/Chinook.sqlite"
)
sys.exit(1)
model = os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-20250514")
print(f"Using Anthropic model: {model}")
print(f"Using database: {database_path}")
llm = AnthropicLlmService(model=model)
# Create shared FileSystem for both tools
file_system = LocalFileSystem(working_directory="./claude_data")
# Create tool registry and register the SQL tool with SQLite runner
tool_registry = ToolRegistry()
sqlite_runner = SqliteRunner(database_path=database_path)
sql_tool = RunSqlTool(sql_runner=sqlite_runner, file_system=file_system)
tool_registry.register(sql_tool)
# Register visualization tool
try:
viz_tool = VisualizeDataTool(file_system=file_system)
tool_registry.register(viz_tool)
print("Visualization tool enabled")
except ImportError:
print(
"[warn] Plotly not installed. Visualization tool disabled. Install with: pip install -e .[visualization]"
)
user_resolver = CookieEmailUserResolver()
agent = Agent(
llm_service=llm,
config=AgentConfig(stream_responses=False),
tool_registry=tool_registry,
user_resolver=user_resolver,
)
# Simulate a logged-in demo user via cookie-based resolver
request_context = RequestContext(
cookies={user_resolver.cookie_name: "demo-user@example.com"},
metadata={"demo": True},
remote_addr="127.0.0.1",
)
conversation_id = "claude-sqlite-demo"
# Sample queries to demonstrate different capabilities
sample_questions = [
"What tables are in this database?",
"Show me the first 5 customers with their names",
"What's the total number of tracks in the database?",
"Find the top 5 artists by number of albums",
"What's the average invoice total?",
"Get data on the top 10 longest tracks and then visualize it",
]
print("\n" + "=" * 60)
print("Claude SQLite Database Assistant Demo")
print("=" * 60)
print("This demo shows Claude querying the Chinook music database.")
print("Claude will intelligently construct SQL queries to answer questions")
print("and can create visualizations of the results.")
print()
for i, question in enumerate(sample_questions, 1):
print(f"\n--- Question {i}: {question} ---")
async for component in agent.send_message(
request_context=request_context,
message=question,
conversation_id=conversation_id,
):
# Handle different component types
if hasattr(component, "simple_component") and component.simple_component:
if hasattr(component.simple_component, "text"):
print("Assistant:", component.simple_component.text)
elif hasattr(component, "rich_component") and component.rich_component:
if (
hasattr(component.rich_component, "content")
and component.rich_component.content
):
print("Assistant:", component.rich_component.content)
elif hasattr(component, "content") and component.content:
print("Assistant:", component.content)
print() # Add spacing between questions
print("\n" + "=" * 60)
print("Demo complete! Claude successfully queried the database.")
print("=" * 60)
def create_demo_agent() -> "Agent":
"""Create a demo agent with Claude and SQLite query tool.
This function is called by the vanna server framework.
Returns:
Configured Agent with Claude LLM and SQLite tool
"""
ensure_env()
try:
from vanna.integrations.anthropic import AnthropicLlmService
except ImportError:
print(
"[error] anthropic extra not installed. Install with: pip install -e .[anthropic]"
)
raise
from vanna import AgentConfig, Agent
from vanna.core.registry import ToolRegistry
from vanna.core.user import CookieEmailUserResolver
from vanna.integrations.sqlite import SqliteRunner
from vanna.tools import (
RunSqlTool,
VisualizeDataTool,
LocalFileSystem,
)
# Get the path to the Chinook database
database_path = os.path.join(
os.path.dirname(__file__), "..", "..", "Chinook.sqlite"
)
database_path = os.path.abspath(database_path)
if not os.path.exists(database_path):
raise FileNotFoundError(
f"Chinook database not found at {database_path}. Please download it from https://vanna.ai/Chinook.sqlite"
)
model = os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-20250514")
llm = AnthropicLlmService(model=model)
# Create shared FileSystem for both tools
file_system = LocalFileSystem(working_directory="./claude_data")
# Create tool registry and register the SQL tool with SQLite runner
tool_registry = ToolRegistry()
sqlite_runner = SqliteRunner(database_path=database_path)
sql_tool = RunSqlTool(sql_runner=sqlite_runner, file_system=file_system)
tool_registry.register(sql_tool)
# Register visualization tool if available
try:
viz_tool = VisualizeDataTool(file_system=file_system)
tool_registry.register(viz_tool)
except ImportError:
pass # Visualization tool not available
user_resolver = CookieEmailUserResolver()
return Agent(
llm_service=llm,
config=AgentConfig(stream_responses=True), # Enable streaming for web interface
tool_registry=tool_registry,
user_resolver=user_resolver,
)
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/claude_sqlite_example.py",
"license": "MIT License",
"lines": 190,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/coding_agent_example.py | """
Example coding agent using the vanna-agents framework.
This example demonstrates building an agent that can edit code files,
following the concepts from the "How to Build an Agent" article.
The agent includes tools for file operations and uses an LLM service
that can understand and modify code.
Usage:
PYTHONPATH=. python vanna/examples/coding_agent_example.py
"""
import asyncio
import uuid
from typing import AsyncGenerator, List, Optional
from vanna import (
AgentConfig,
Agent,
ToolRegistry,
User,
)
from vanna.core.interfaces import LlmService
from vanna.core.models import (
LlmRequest,
LlmResponse,
LlmStreamChunk,
ToolCall,
ToolSchema,
)
from vanna.tools.file_system import create_file_system_tools
from vanna.tools.python import create_python_tools
class CodingLlmService(LlmService):
"""
LLM service that simulates a coding assistant.
This demonstrates the minimal implementation needed for an agent
as described in the article - just needs to understand tool calls
and respond appropriately.
"""
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Handle non-streaming requests."""
await asyncio.sleep(0.1) # Simulate thinking time
return self._build_response(request)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Handle streaming requests."""
await asyncio.sleep(0.1)
response = self._build_response(request)
if response.tool_calls:
yield LlmStreamChunk(tool_calls=response.tool_calls)
if response.content:
# Simulate streaming by chunking the response
words = response.content.split()
for i, word in enumerate(words):
chunk = word if i == 0 else f" {word}"
await asyncio.sleep(0.05) # Simulate streaming delay
yield LlmStreamChunk(content=chunk)
yield LlmStreamChunk(finish_reason=response.finish_reason)
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Validate tools - no errors for this simple implementation."""
return []
def _build_response(self, request: LlmRequest) -> LlmResponse:
"""Build a response based on the conversation context."""
last_message = request.messages[-1] if request.messages else None
# If we just got a tool result, respond to it
if last_message and last_message.role == "tool":
tool_result = last_message.content or "Tool executed"
return LlmResponse(
content=f"I've completed the operation. {tool_result}",
finish_reason="stop",
)
# If user is asking for file operations, use tools
if last_message and last_message.role == "user":
user_message = last_message.content.lower()
if "list files" in user_message or "show files" in user_message:
return LlmResponse(
content="I'll list the files for you.",
tool_calls=[
ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="list_files",
arguments={},
)
],
finish_reason="tool_calls",
)
elif "read" in user_message and (
"file" in user_message
or ".py" in user_message
or ".txt" in user_message
):
filename = _extract_filename(user_message)
if filename:
return LlmResponse(
content=f"I'll read the file '{filename}' for you.",
tool_calls=[
ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="read_file",
arguments={"filename": filename},
)
],
finish_reason="tool_calls",
)
elif "create" in user_message or "write" in user_message:
# Suggest creating a simple example file
return LlmResponse(
content="I'll create an example Python file for you.",
tool_calls=[
ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="write_file",
arguments={
"filename": "example.py",
"content": "# Example Python file\nprint('Hello from the coding agent!')\n\ndef greet(name):\n return f'Hello, {name}!'\n\nif __name__ == '__main__':\n print(greet('World'))\n",
"overwrite": True,
},
)
],
finish_reason="tool_calls",
)
elif (
"run" in user_message or "execute" in user_message
) and ".py" in user_message:
filename = _extract_filename(user_message)
if filename:
return LlmResponse(
content=f"I'll run the Python file '{filename}'.",
tool_calls=[
ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="run_python_file",
arguments={
"filename": filename,
"arguments": [],
},
)
],
finish_reason="tool_calls",
)
elif (
"edit" in user_message
or "update" in user_message
or "modify" in user_message
):
return LlmResponse(
content="I'll update the greet function to make it more descriptive.",
tool_calls=[
ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="edit_file",
arguments={
"filename": "example.py",
"edits": [
{
"start_line": 4,
"end_line": 5,
"new_content": (
"def greet(name):\n"
' """Return a friendly greeting."""\n'
' return f"Hello, {name}! Welcome to the coding agent."\n'
),
}
],
},
)
],
finish_reason="tool_calls",
)
# Default response
return LlmResponse(
content=(
"I'm a coding assistant. I can help you list, read, write, edit, and run Python files. "
"Try asking me to 'list files', 'read example.py', 'create a Python file', 'run example.py', or 'update example.py'."
),
finish_reason="stop",
)
def create_demo_agent() -> Agent:
"""
Create a coding agent with file operation tools.
This follows the pattern from the article - minimal code
to create a powerful code-editing agent. Uses dependency injection
for file system operations with LocalFileSystem as default.
"""
# Create tool registry and register file system tools
tool_registry = ToolRegistry()
# Use the convenience function to create tools with default LocalFileSystem
for tool in create_file_system_tools():
tool_registry.register(tool)
for tool in create_python_tools():
tool_registry.register(tool)
# Create LLM service
llm_service = CodingLlmService()
# Create agent with configuration
return Agent(
llm_service=llm_service,
tool_registry=tool_registry,
config=AgentConfig(
stream_responses=True,
include_thinking_indicators=True,
max_tool_iterations=3,
),
)
async def main() -> None:
"""
Demonstrate the coding agent in action.
As the article mentions: "300 lines of code and three tools and now
you're able to talk to an alien intelligence that edits your code."
"""
print("🤖 Starting Coding Agent Demo")
print("This demonstrates the concepts from 'How to Build an Agent'")
print("-" * 50)
# Create the agent
agent = create_demo_agent()
# Create a test user
user = User(id="coder123", username="developer", permissions=[])
# Show available tools
tools = await agent.get_available_tools(user)
print(f"Available tools: {[tool.name for tool in tools]}")
print()
# Demo conversation
conversation_id = "coding-session"
demos = [
"Hello! Can you list the files in this directory?",
"Can you create a simple Python file for me?",
"Now read the example.py file you just created",
"Please update the greet function to include a docstring and a friendlier message.",
"Run example.py so I can see its output.",
"Great, read example.py again to confirm the changes.",
]
for i, message in enumerate(demos, 1):
print(f"Demo {i}: {message}")
print("Agent response:")
async for component in agent.send_message(
user=user, message=message, conversation_id=conversation_id
):
if (
hasattr(component.rich_component, "content")
and component.rich_component.content
):
print(f" 📝 {component.rich_component.content}")
elif hasattr(component.rich_component, "message"):
print(f" 💬 {component.rich_component.message}")
elif component.simple_component and hasattr(
component.simple_component, "text"
):
print(f" 📄 {component.simple_component.text}")
print("-" * 30)
def _extract_filename(message: str) -> Optional[str]:
"""Extract a likely filename token from a user message."""
for token in message.replace("\n", " ").split():
cleaned = token.strip("'\".,;!?")
if "." in cleaned and not cleaned.startswith("."):
return cleaned
return None
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/coding_agent_example.py",
"license": "MIT License",
"lines": 254,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/custom_system_prompt_example.py | """
Example demonstrating custom system prompt builder with dependency injection.
This example shows how to create a custom SystemPromptBuilder that dynamically
generates system prompts based on user context and available tools.
Usage:
python -m vanna.examples.custom_system_prompt_example
"""
from typing import List, Optional
from vanna.core.interfaces import SystemPromptBuilder
from vanna.core.models import ToolSchema, User
class CustomSystemPromptBuilder(SystemPromptBuilder):
"""Custom system prompt builder that personalizes prompts based on user."""
async def build_system_prompt(
self, user: User, tools: List[ToolSchema]
) -> Optional[str]:
"""Build a personalized system prompt.
Args:
user: The user making the request
tools: List of tools available to the user
Returns:
Personalized system prompt
"""
# Build personalized greeting
username = user.username or user.id
greeting = f"Hello {username}! I'm your AI assistant."
# Add role-specific instructions based on user permissions
role_instructions = []
if "admin" in user.permissions:
role_instructions.append(
"As an admin user, you have access to all tools and capabilities."
)
elif "analyst" in user.permissions:
role_instructions.append(
"You're working as an analyst. I'll help you query and visualize data."
)
else:
role_instructions.append("I'm here to help you with your tasks.")
# List available tools
tool_info = []
if tools:
tool_info.append("\nAvailable tools:")
for tool in tools:
tool_info.append(f"- {tool.name}: {tool.description}")
# Combine all parts
parts = [greeting] + role_instructions + tool_info
return "\n".join(parts)
class SQLAssistantSystemPromptBuilder(SystemPromptBuilder):
"""System prompt builder specifically for SQL database assistants."""
def __init__(self, database_name: str = "database"):
"""Initialize with database context.
Args:
database_name: Name of the database being queried
"""
self.database_name = database_name
async def build_system_prompt(
self, user: User, tools: List[ToolSchema]
) -> Optional[str]:
"""Build a SQL-focused system prompt.
Args:
user: The user making the request
tools: List of tools available to the user
Returns:
SQL-focused system prompt
"""
prompt = f"""You are an expert SQL database assistant for the {self.database_name} database.
Your primary responsibilities:
1. Write efficient, correct SQL queries
2. Explain query results clearly
3. Suggest optimizations when relevant
4. Visualize data when appropriate
Guidelines:
- Always validate SQL syntax before execution
- Use appropriate JOINs and avoid Cartesian products
- Limit result sets to reasonable sizes by default
- Format numbers and dates for readability
"""
# Add tool-specific instructions
has_viz_tool = any(tool.name == "visualize_data" for tool in tools)
if has_viz_tool:
prompt += "\n- Create visualizations for numerical data when it helps understanding"
return prompt
async def demo() -> None:
"""Demonstrate custom system prompt builders."""
from vanna import Agent, User
from vanna.core.registry import ToolRegistry
from vanna.integrations.anthropic.mock import MockLlmService
# Example 1: Custom personalized system prompt
print("=" * 60)
print("Example 1: Custom Personalized System Prompt")
print("=" * 60)
custom_builder = CustomSystemPromptBuilder()
admin_user = User(id="user-1", username="Alice", permissions=["admin"])
# Simulate some tools
mock_tools = [
ToolSchema(
name="query_database", description="Query the SQL database", parameters={}
),
ToolSchema(
name="visualize_data",
description="Create data visualizations",
parameters={},
),
]
prompt = await custom_builder.build_system_prompt(admin_user, mock_tools)
print("\nGenerated system prompt for admin user:")
print("-" * 60)
print(prompt)
print("-" * 60)
# Example 2: SQL-specific system prompt
print("\n" + "=" * 60)
print("Example 2: SQL Assistant System Prompt")
print("=" * 60)
sql_builder = SQLAssistantSystemPromptBuilder(database_name="Chinook")
analyst_user = User(id="user-2", username="Bob", permissions=["analyst"])
prompt = await sql_builder.build_system_prompt(analyst_user, mock_tools)
print("\nGenerated system prompt for SQL assistant:")
print("-" * 60)
print(prompt)
print("-" * 60)
# Example 3: Using custom builder with Agent
print("\n" + "=" * 60)
print("Example 3: Using Custom Builder with Agent")
print("=" * 60)
mock_llm = MockLlmService()
tool_registry = ToolRegistry()
agent = Agent(
llm_service=mock_llm,
tool_registry=tool_registry,
system_prompt_builder=sql_builder, # Inject custom builder here
)
print("\nAgent created with custom SQL system prompt builder!")
print("The agent will now use the SQL-focused system prompt for all interactions.")
if __name__ == "__main__":
import asyncio
asyncio.run(demo())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/custom_system_prompt_example.py",
"license": "MIT License",
"lines": 135,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/default_workflow_handler_example.py | """
Example demonstrating the DefaultWorkflowHandler with setup health checking.
This example shows how the DefaultWorkflowHandler provides intelligent starter UI
that adapts based on available tools and helps users understand their setup status.
Run:
PYTHONPATH=. python vanna/examples/default_workflow_handler_example.py
"""
import asyncio
from vanna import (
AgentConfig,
Agent,
MemoryConversationStore,
MockLlmService,
User,
DefaultWorkflowHandler,
)
from vanna.core.registry import ToolRegistry
from vanna.core.user.resolver import SimpleUserResolver
from vanna.tools import ListFilesTool
async def demonstrate_setup_scenarios():
"""Demonstrate different setup scenarios with DefaultWorkflowHandler."""
print("🚀 Starting DefaultWorkflowHandler Setup Health Check Demo\n")
# Create basic components
llm_service = MockLlmService(response_content="I'm ready to help!")
conversation_store = MemoryConversationStore()
user_resolver = SimpleUserResolver()
# Create test user
user = User(
id="user1",
username="alice",
email="alice@example.com",
group_memberships=["user"],
)
print("=" * 60)
print("SCENARIO 1: Empty Setup (No Tools)")
print("=" * 60)
# Empty tool registry
empty_registry = ToolRegistry()
agent_empty = Agent(
llm_service=llm_service,
tool_registry=empty_registry,
user_resolver=user_resolver,
conversation_store=conversation_store,
config=AgentConfig(stream_responses=False),
workflow_handler=DefaultWorkflowHandler(),
)
print("📋 Starter UI for empty setup:")
async for component in agent_empty.send_message(
request_context=user_resolver.create_request_context(
metadata={"starter_ui_request": True}
),
message="",
conversation_id="empty-setup",
):
if hasattr(component, "simple_component") and component.simple_component:
print(f" 📄 {component.simple_component.text[:100]}...")
elif hasattr(component, "rich_component"):
comp = component.rich_component
if hasattr(comp, "title"):
print(f" 📊 {comp.title}: {comp.status} - {comp.description}")
elif hasattr(comp, "content"):
print(f" 📝 {comp.content[:100]}...")
print("\n" + "=" * 60)
print("SCENARIO 2: Functional Setup (SQL + Basic Tools)")
print("=" * 60)
# Tool registry with SQL tool (simulated)
functional_registry = ToolRegistry()
# Register a mock SQL tool (we'll simulate by tool name)
list_tool = ListFilesTool()
list_tool.name = "run_sql" # Simulate SQL tool
functional_registry.register(list_tool)
agent_functional = Agent(
llm_service=llm_service,
tool_registry=functional_registry,
user_resolver=user_resolver,
conversation_store=conversation_store,
config=AgentConfig(stream_responses=False),
workflow_handler=DefaultWorkflowHandler(),
)
print("📋 Starter UI for functional setup:")
async for component in agent_functional.send_message(
request_context=user_resolver.create_request_context(
metadata={"starter_ui_request": True}
),
message="",
conversation_id="functional-setup",
):
if hasattr(component, "simple_component") and component.simple_component:
print(f" 📄 {component.simple_component.text[:100]}...")
elif hasattr(component, "rich_component"):
comp = component.rich_component
if hasattr(comp, "title"):
print(f" 📊 {comp.title}: {comp.status} - {comp.description}")
elif hasattr(comp, "content"):
print(f" 📝 {comp.content[:100]}...")
print("\n" + "=" * 60)
print("SCENARIO 3: Complete Setup (SQL + Memory + Visualization)")
print("=" * 60)
# Complete tool registry
complete_registry = ToolRegistry()
# Mock SQL tool
sql_tool = ListFilesTool()
sql_tool.name = "run_sql"
complete_registry.register(sql_tool)
# Mock memory tools
search_tool = ListFilesTool()
search_tool.name = "search_saved_correct_tool_uses"
complete_registry.register(search_tool)
save_tool = ListFilesTool()
save_tool.name = "save_question_tool_args"
complete_registry.register(save_tool)
# Mock visualization tool
viz_tool = ListFilesTool()
viz_tool.name = "visualize_data"
complete_registry.register(viz_tool)
agent_complete = Agent(
llm_service=llm_service,
tool_registry=complete_registry,
user_resolver=user_resolver,
conversation_store=conversation_store,
config=AgentConfig(stream_responses=False),
workflow_handler=DefaultWorkflowHandler(),
)
print("📋 Starter UI for complete setup:")
async for component in agent_complete.send_message(
request_context=user_resolver.create_request_context(
metadata={"starter_ui_request": True}
),
message="",
conversation_id="complete-setup",
):
if hasattr(component, "simple_component") and component.simple_component:
print(f" 📄 {component.simple_component.text[:100]}...")
elif hasattr(component, "rich_component"):
comp = component.rich_component
if hasattr(comp, "title"):
print(f" 📊 {comp.title}: {comp.status} - {comp.description}")
elif hasattr(comp, "content"):
print(f" 📝 {comp.content[:100]}...")
print("\n" + "=" * 60)
print("SCENARIO 4: Testing Commands")
print("=" * 60)
print("📋 Testing /help command:")
async for component in agent_complete.send_message(
request_context=user_resolver.create_request_context(),
message="/help",
conversation_id="help-test",
):
if hasattr(component, "rich_component") and hasattr(
component.rich_component, "content"
):
print(f" 📝 Help: {component.rich_component.content[:200]}...")
print("\n📋 Testing /status command:")
async for component in agent_complete.send_message(
request_context=user_resolver.create_request_context(),
message="/status",
conversation_id="status-test",
):
if hasattr(component, "rich_component"):
comp = component.rich_component
if hasattr(comp, "title"):
print(f" 📊 {comp.title}: {comp.status}")
elif hasattr(comp, "content"):
print(f" 📝 Status: {comp.content[:150]}...")
print("\n✅ Demo complete! The DefaultWorkflowHandler provides:")
print(" • Smart setup health checking")
print(" • Contextual starter UI based on available tools")
print(" • Helpful error messages and setup guidance")
print(" • Built-in command handling (/help, /status)")
print(" • Automatic tool analysis and recommendations")
async def main():
"""Run the DefaultWorkflowHandler demonstration."""
await demonstrate_setup_scenarios()
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/default_workflow_handler_example.py",
"license": "MIT License",
"lines": 175,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/email_auth_example.py | """
Email authentication example for the Vanna Agents framework.
This example demonstrates how to create an agent with email-based authentication
where users are prompted for their email address in chat and the system creates
a user profile based on that email.
## What This Example Shows
1. **UserService Implementation**: A demo `DemoEmailUserService` that:
- Stores users in memory
- Authenticates users by email validation
- Creates user profiles automatically
- Manages user permissions
2. **Authentication Tool**: An `AuthTool` that:
- Takes an email address as input
- Uses the UserService to authenticate/create users
- Returns rich UI components for success/error feedback
- Provides structured results for the LLM
3. **In-Chat Authentication Flow**: Shows how:
- Users can provide their email in natural conversation
- The agent can prompt for authentication when needed
- Authentication results are displayed with rich UI components
- The system maintains user context across conversations
## Key Components
- `DemoEmailUserService`: Implements the `UserService` interface
- `AuthTool`: Implements the `Tool` interface for authentication
- Rich UI components for authentication feedback
- Integration with the agent's tool registry and conversation store
## Usage
Interactive: python -m vanna.examples.email_auth_example
## Note
This example uses a simplified mock LLM that doesn't actually call tools.
In a real implementation with OpenAI or Anthropic, the LLM would automatically
detect email addresses in user messages and call the authenticate_user tool.
For production use, you would:
- Replace DemoEmailUserService with a database-backed implementation
- Add proper email validation and security measures
- Implement session management in the server layer
- Add proper error handling and rate limiting
"""
import asyncio
from typing import Any, Dict, Optional, Type
from pydantic import BaseModel, Field
from vanna import (
AgentConfig,
Agent,
MemoryConversationStore,
MockLlmService,
User,
)
from vanna.core import Tool, UserService
from vanna.core import ToolContext, ToolResult
from vanna.core.registry import ToolRegistry
from vanna.core.components import UiComponent
from vanna.core import RichComponent
# Demo User Service Implementation
class DemoEmailUserService(UserService):
"""Demo user service that authenticates users by email."""
def __init__(self):
"""Initialize with in-memory user store."""
self._users: Dict[str, User] = {} # user_id -> User
self._email_to_id: Dict[str, str] = {} # email -> user_id
async def get_user(self, user_id: str) -> Optional[User]:
"""Get user by ID."""
return self._users.get(user_id)
async def authenticate(self, credentials: Dict[str, Any]) -> Optional[User]:
"""Authenticate user by email."""
email = credentials.get("email")
if not email or not self._is_valid_email(email):
return None
# Check if user exists
user_id = self._email_to_id.get(email)
if user_id:
return self._users[user_id]
# Create new user
user_id = f"user_{len(self._users) + 1}"
username = email.split("@")[0]
user = User(
id=user_id,
username=username,
email=email,
permissions=["basic_user"],
metadata={"auth_method": "email"},
)
self._users[user_id] = user
self._email_to_id[email] = user_id
return user
async def has_permission(self, user: User, permission: str) -> bool:
"""Check if user has permission."""
return permission in user.permissions
def _is_valid_email(self, email: str) -> bool:
"""Simple email validation."""
return "@" in email and "." in email.split("@")[1]
# Authentication Tool
class AuthArgs(BaseModel):
"""Arguments for authentication."""
email: str = Field(description="User's email address")
class AuthTool(Tool[AuthArgs]):
"""Tool to authenticate users by email."""
def __init__(self, user_service: DemoEmailUserService):
self.user_service = user_service
@property
def name(self) -> str:
return "authenticate_user"
@property
def description(self) -> str:
return "Authenticate a user by their email address. Use this when the user provides an email."
def get_args_schema(self) -> Type[AuthArgs]:
return AuthArgs
async def execute(self, context: ToolContext, args: AuthArgs) -> ToolResult:
"""Execute authentication."""
user = await self.user_service.authenticate({"email": args.email})
if user:
success_msg = (
f"✅ Welcome {user.username}! You're now authenticated as {user.email}"
)
auth_component = RichComponent(
type="status_card",
data={
"title": "Authentication Success",
"status": "success",
"description": success_msg,
"icon": "✅",
"metadata": {
"user_id": user.id,
"username": user.username,
"email": user.email,
},
},
)
return ToolResult(
success=True,
result_for_llm=f"User successfully authenticated as {user.username} ({user.email}). They can now access personalized features.",
ui_component=UiComponent(rich_component=auth_component),
)
else:
error_msg = f"❌ Invalid email format: {args.email}"
error_component = RichComponent(
type="status_card",
data={
"title": "Authentication Failed",
"status": "error",
"description": error_msg,
"icon": "❌",
"metadata": {"email": args.email},
},
)
return ToolResult(
success=False,
result_for_llm=f"Authentication failed for {args.email}. Please provide a valid email address.",
ui_component=UiComponent(rich_component=error_component),
error=error_msg,
)
def create_demo_agent() -> Agent:
"""Create a demo agent for REPL and server usage.
Returns:
Configured Agent instance with email authentication
"""
return create_auth_agent()
def create_auth_agent() -> Agent:
"""Create agent with email authentication."""
# Create user service
user_service = DemoEmailUserService()
# Use simple mock LLM - the system prompt will guide behavior
llm_service = MockLlmService(
response_content="Hello! I'm your AI assistant. To provide you with personalized help, I'll need your email address for authentication. Please share your email with me, and I'll use the authenticate_user tool to set up your profile."
)
# Create tool registry with auth tool
tool_registry = ToolRegistry()
auth_tool = AuthTool(user_service)
tool_registry.register(auth_tool)
# Create agent with authentication system prompt
agent = Agent(
llm_service=llm_service,
config=AgentConfig(
stream_responses=True,
include_thinking_indicators=False, # Cleaner output for demo
system_prompt="""You are a helpful AI assistant with an email-based authentication system.
AUTHENTICATION BEHAVIOR:
1. When a user provides an email address in their message, immediately use the 'authenticate_user' tool
2. Look for emails in patterns like "my email is...", "I'm john@example.com", or any text with @ symbols
3. If user isn't authenticated, politely ask for their email address to get started
4. After successful authentication, welcome them by name and offer personalized assistance
5. Be friendly and helpful throughout the process
Remember: Authentication is required for personalized features!""",
),
tool_registry=tool_registry,
conversation_store=MemoryConversationStore(),
)
return agent
async def demo_auth_flow():
"""Demonstrate the authentication flow with simple output."""
agent = create_auth_agent()
# Start with anonymous user
user = User(id="anonymous", username="guest", email=None, permissions=[])
conversation_id = "auth_demo_conv"
print("=== Email Authentication Demo ===")
print("This example shows how an agent can authenticate users via email in chat.")
print("Note: This uses a simple mock LLM for demonstration purposes.\n")
# Demo conversation
print("🔹 Step 1: Initial greeting")
print("User: Hello!")
print("Agent: ", end="")
async for component in agent.send_message(
user=user, message="Hello!", conversation_id=conversation_id
):
if (
hasattr(component, "rich_component")
and component.rich_component.type.value == "text"
):
content = component.rich_component.data.get("content") or getattr(
component.rich_component, "content", ""
)
if content:
print(content)
break
print("\n" + "=" * 60)
print("\n🔹 Step 2: User provides email for authentication")
print("User: My email is alice@example.com")
print("Agent: ", end="")
# This should trigger the auth tool
auth_shown = False
async for component in agent.send_message(
user=user,
message="My email is alice@example.com",
conversation_id=conversation_id,
):
if hasattr(component, "rich_component"):
rich_comp = component.rich_component
if rich_comp.type.value == "status_card" and not auth_shown:
status = rich_comp.data.get("status", "")
desc = rich_comp.data.get("description", "")
if status == "success":
auth_shown = True
print(f"🔐 {desc}")
break
print("\n" + "=" * 60)
print("\n🔹 Step 3: Post-authentication interaction")
print("User: What can you help me with now?")
print("Agent: ", end="")
async for component in agent.send_message(
user=user,
message="What can you help me with now?",
conversation_id=conversation_id,
):
if (
hasattr(component, "rich_component")
and component.rich_component.type.value == "text"
):
content = component.rich_component.data.get("content") or getattr(
component.rich_component, "content", ""
)
if content:
print(content)
break
print("\n" + "=" * 60)
print("\n✅ Authentication demo complete!")
print("\nKey Features Demonstrated:")
print("• Email-based user authentication")
print("• Tool-based authentication flow")
print("• In-memory user storage and management")
print("• Rich UI components for auth feedback")
async def main():
"""Run the authentication example."""
await demo_auth_flow()
def run_interactive():
"""Entry point for interactive usage."""
print("Starting email authentication example...")
asyncio.run(main())
if __name__ == "__main__":
run_interactive()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/email_auth_example.py",
"license": "MIT License",
"lines": 269,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/evaluation_example.py | """
Evaluation System Example
This example demonstrates how to use the evaluation framework to test
and compare agents. Shows:
- Creating test cases programmatically
- Running evaluations with multiple evaluators
- Comparing agent variants (e.g., different LLMs)
- Generating reports
Usage:
PYTHONPATH=. python vanna/examples/evaluation_example.py
"""
import asyncio
from vanna import Agent, MockLlmService, MemoryConversationStore, User
from vanna.core.evaluation import (
EvaluationRunner,
EvaluationDataset,
TestCase,
ExpectedOutcome,
AgentVariant,
TrajectoryEvaluator,
OutputEvaluator,
EfficiencyEvaluator,
)
from vanna.core.registry import ToolRegistry
def create_sample_dataset() -> EvaluationDataset:
"""Create a sample dataset for demonstration."""
eval_user = User(
id="eval_user", username="evaluator", email="eval@example.com", permissions=[]
)
test_cases = [
TestCase(
id="test_001",
user=eval_user,
message="Hello, how are you?",
expected_outcome=ExpectedOutcome(
final_answer_contains=["hello", "hi"],
max_execution_time_ms=3000,
),
metadata={"category": "greeting", "difficulty": "easy"},
),
TestCase(
id="test_002",
user=eval_user,
message="What can you help me with?",
expected_outcome=ExpectedOutcome(
final_answer_contains=["help", "assist"],
max_execution_time_ms=3000,
),
metadata={"category": "capabilities", "difficulty": "easy"},
),
TestCase(
id="test_003",
user=eval_user,
message="Explain quantum computing",
expected_outcome=ExpectedOutcome(
final_answer_contains=["quantum", "computing"],
min_components=1,
max_execution_time_ms=5000,
),
metadata={"category": "explanation", "difficulty": "medium"},
),
]
return EvaluationDataset(
name="Demo Test Cases",
test_cases=test_cases,
description="Sample test cases for evaluation demo",
)
def create_test_agent(name: str, response_content: str) -> Agent:
"""Create a test agent with mock LLM."""
return Agent(
llm_service=MockLlmService(response_content=response_content),
tool_registry=ToolRegistry(),
conversation_store=MemoryConversationStore(),
)
async def demo_single_agent_evaluation():
"""Demonstrate evaluating a single agent."""
print("\n" + "=" * 80)
print("DEMO 1: Single Agent Evaluation")
print("=" * 80 + "\n")
# Create dataset
dataset = create_sample_dataset()
print(f"Loaded dataset: {dataset.name}")
print(f"Test cases: {len(dataset.test_cases)}\n")
# Create agent
agent = create_test_agent(
"test-agent",
"Hello! I'm here to help you with various tasks including answering questions about topics like quantum computing.",
)
# Create evaluators
evaluators = [
TrajectoryEvaluator(),
OutputEvaluator(),
EfficiencyEvaluator(max_execution_time_ms=5000),
]
# Run evaluation
runner = EvaluationRunner(evaluators=evaluators, max_concurrency=5)
print("Running evaluation...")
report = await runner.run_evaluation(agent, dataset.test_cases)
# Print results
report.print_summary()
# Show failures
failures = report.get_failures()
if failures:
print("\nFailed test cases:")
for result in failures:
print(f" - {result.test_case.id}: {result.test_case.message}")
async def demo_agent_comparison():
"""Demonstrate comparing multiple agent variants."""
print("\n" + "=" * 80)
print("DEMO 2: Agent Comparison (LLM Comparison Use Case)")
print("=" * 80 + "\n")
# Create dataset
dataset = create_sample_dataset()
print(f"Loaded dataset: {dataset.name}")
print(f"Test cases: {len(dataset.test_cases)}\n")
# Create agent variants
variants = [
AgentVariant(
name="agent-v1",
agent=create_test_agent(
"v1",
"Hi there! I can help you with many things including explaining complex topics like quantum computing.",
),
metadata={"version": "1.0", "model": "mock-v1"},
),
AgentVariant(
name="agent-v2",
agent=create_test_agent(
"v2",
"Hello! I'm your helpful assistant. I can assist with various tasks and explain topics like quantum computing in detail.",
),
metadata={"version": "2.0", "model": "mock-v2"},
),
AgentVariant(
name="agent-v3",
agent=create_test_agent(
"v3",
"Greetings! I'm designed to help you with a wide range of tasks, from simple questions to complex explanations about quantum computing and more.",
),
metadata={"version": "3.0", "model": "mock-v3"},
),
]
print(f"Created {len(variants)} agent variants:")
for v in variants:
print(f" - {v.name}")
print()
# Create evaluators
evaluators = [
OutputEvaluator(),
EfficiencyEvaluator(max_execution_time_ms=5000),
]
# Run comparison
runner = EvaluationRunner(evaluators=evaluators, max_concurrency=10)
print(
f"Running comparison ({len(variants)} variants × {len(dataset.test_cases)} test cases)..."
)
print("All variants running in parallel for maximum efficiency...\n")
comparison = await runner.compare_agents(variants, dataset.test_cases)
# Print results
comparison.print_summary()
# Show best variants
print("Best Performing Variants:")
print(f" 🏆 Best score: {comparison.get_best_variant('score')}")
print(f" ⚡ Fastest: {comparison.get_best_variant('speed')}")
print(f" ✅ Best pass rate: {comparison.get_best_variant('pass_rate')}")
async def demo_dataset_operations():
"""Demonstrate dataset creation and manipulation."""
print("\n" + "=" * 80)
print("DEMO 3: Dataset Operations")
print("=" * 80 + "\n")
# Create dataset
dataset = create_sample_dataset()
# Show dataset info
print(f"Dataset: {dataset.name}")
print(f"Description: {dataset.description}")
print(f"Total test cases: {len(dataset)}\n")
# Filter by metadata
easy_tests = dataset.filter_by_metadata(difficulty="easy")
medium_tests = dataset.filter_by_metadata(difficulty="medium")
print(f"Easy test cases: {len(easy_tests)}")
print(f"Medium test cases: {len(medium_tests)}\n")
# Save to file (for demonstration)
import tempfile
import os
with tempfile.TemporaryDirectory() as tmpdir:
yaml_path = os.path.join(tmpdir, "dataset.yaml")
json_path = os.path.join(tmpdir, "dataset.json")
dataset.save_yaml(yaml_path)
dataset.save_json(json_path)
print("Dataset saved to temporary files:")
print(f" - YAML: {yaml_path}")
print(f" - JSON: {json_path}\n")
# Load back
loaded_yaml = EvaluationDataset.from_yaml(yaml_path)
loaded_json = EvaluationDataset.from_json(json_path)
print("Loaded datasets:")
print(f" - From YAML: {len(loaded_yaml)} test cases")
print(f" - From JSON: {len(loaded_json)} test cases")
async def main():
"""Run all evaluation demos."""
print("\n🚀 Vanna Agents Evaluation System Demo")
print("=" * 80)
# Demo 1: Single agent evaluation
await demo_single_agent_evaluation()
# Demo 2: Agent comparison (main use case)
await demo_agent_comparison()
# Demo 3: Dataset operations
await demo_dataset_operations()
print("\n" + "=" * 80)
print("✅ All demos completed!")
print("=" * 80)
print("\nKey Takeaways:")
print(" 1. Evaluations are integral to the Vanna package")
print(" 2. Parallel execution handles I/O-bound LLM calls efficiently")
print(" 3. Agent comparison is a first-class use case")
print(" 4. Multiple evaluators can be composed for comprehensive testing")
print(" 5. Reports can be exported to HTML, CSV, or printed to console")
print("\nFor LLM comparison, see: evals/benchmarks/llm_comparison.py")
print()
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/evaluation_example.py",
"license": "MIT License",
"lines": 221,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/extensibility_example.py | """
Comprehensive example demonstrating all extensibility interfaces.
This example shows how to use:
- LlmMiddleware for caching
- ErrorRecoveryStrategy for retry logic
- ToolContextEnricher for adding user preferences
- ConversationFilter for context window management
- ObservabilityProvider for monitoring
"""
import asyncio
import time
from typing import Any, Dict, List, Optional
from vanna.core import (
Agent,
LlmMiddleware,
ErrorRecoveryStrategy,
ToolContextEnricher,
ConversationFilter,
ObservabilityProvider,
User,
ToolContext,
Conversation,
Message,
LlmRequest,
LlmResponse,
Span,
Metric,
)
from vanna.core.recovery import RecoveryAction, RecoveryActionType
from vanna.core.registry import ToolRegistry
# 1. LlmMiddleware Example: Simple Caching
class CachingMiddleware(LlmMiddleware):
"""Cache LLM responses to reduce costs and latency."""
def __init__(self) -> None:
self.cache: Dict[str, LlmResponse] = {}
self.hits = 0
self.misses = 0
def _compute_cache_key(self, request: LlmRequest) -> str:
"""Create cache key from request."""
messages_str = str([(m.role, m.content) for m in request.messages])
return f"{messages_str}:{request.temperature}"
async def before_llm_request(self, request: LlmRequest) -> LlmRequest:
"""Check cache before sending request."""
cache_key = self._compute_cache_key(request)
if cache_key in self.cache:
self.hits += 1
print(f"[CACHE HIT] Cache stats: {self.hits} hits, {self.misses} misses")
return request
async def after_llm_response(
self, request: LlmRequest, response: LlmResponse
) -> LlmResponse:
"""Cache the response."""
cache_key = self._compute_cache_key(request)
if cache_key not in self.cache:
self.cache[cache_key] = response
self.misses += 1
print(f"[CACHE MISS] Caching response")
return response
# 2. ErrorRecoveryStrategy Example: Exponential Backoff
class ExponentialBackoffStrategy(ErrorRecoveryStrategy):
"""Retry failed operations with exponential backoff."""
def __init__(self, max_retries: int = 3) -> None:
self.max_retries = max_retries
async def handle_tool_error(
self, error: Exception, context: ToolContext, attempt: int = 1
) -> RecoveryAction:
"""Retry tool errors with exponential backoff."""
if attempt < self.max_retries:
delay_ms = (2 ** (attempt - 1)) * 1000
print(
f"[RETRY] Tool failed, retrying in {delay_ms}ms (attempt {attempt}/{self.max_retries})"
)
return RecoveryAction(
action=RecoveryActionType.RETRY,
retry_delay_ms=delay_ms,
message=f"Retrying after {delay_ms}ms",
)
print(f"[FAIL] Max retries exceeded for tool error: {error}")
return RecoveryAction(
action=RecoveryActionType.FAIL,
message=f"Tool error after {self.max_retries} attempts: {str(error)}",
)
async def handle_llm_error(
self, error: Exception, request: LlmRequest, attempt: int = 1
) -> RecoveryAction:
"""Retry LLM errors with backoff."""
if attempt < self.max_retries:
delay_ms = (2 ** (attempt - 1)) * 1000
print(
f"[RETRY] LLM failed, retrying in {delay_ms}ms (attempt {attempt}/{self.max_retries})"
)
return RecoveryAction(
action=RecoveryActionType.RETRY,
retry_delay_ms=delay_ms,
message=f"Retrying LLM after {delay_ms}ms",
)
print(f"[FAIL] Max retries exceeded for LLM error: {error}")
return RecoveryAction(
action=RecoveryActionType.FAIL,
message=f"LLM error after {self.max_retries} attempts: {str(error)}",
)
# 3. ToolContextEnricher Example: Add User Preferences
class UserPreferencesEnricher(ToolContextEnricher):
"""Enrich context with user preferences."""
def __init__(self) -> None:
# Mock user preferences database
self.preferences: Dict[str, Dict[str, Any]] = {
"user123": {
"timezone": "America/New_York",
"language": "en",
"theme": "dark",
}
}
async def enrich_context(self, context: ToolContext) -> ToolContext:
"""Add user preferences to context."""
prefs = self.preferences.get(context.user.id, {})
context.metadata["user_preferences"] = prefs
context.metadata["timezone"] = prefs.get("timezone", "UTC")
print(f"[ENRICH] Added preferences for user {context.user.id}: {prefs}")
return context
# 4. ConversationFilter Example: Context Window Management
class ContextWindowFilter(ConversationFilter):
"""Limit conversation to fit within context window."""
def __init__(self, max_messages: int = 20) -> None:
self.max_messages = max_messages
async def filter_messages(self, messages: List[Message]) -> List[Message]:
"""Keep only recent messages within limit."""
if len(messages) <= self.max_messages:
return messages
# Keep system messages and recent messages
system_messages = [m for m in messages if m.role == "system"]
other_messages = [m for m in messages if m.role != "system"]
# Take the most recent messages
recent_messages = other_messages[-self.max_messages :]
filtered = system_messages + recent_messages
print(f"[FILTER] Reduced {len(messages)} messages to {len(filtered)}")
return filtered
# 5. ObservabilityProvider Example: Simple Logging
class LoggingObservabilityProvider(ObservabilityProvider):
"""Log metrics and spans for monitoring."""
def __init__(self) -> None:
self.metrics: List[Metric] = []
self.spans: List[Span] = []
async def record_metric(
self,
name: str,
value: float,
unit: str = "",
tags: Optional[Dict[str, str]] = None,
) -> None:
"""Record and log a metric."""
metric = Metric(name=name, value=value, unit=unit, tags=tags or {})
self.metrics.append(metric)
tags_str = ", ".join(f"{k}={v}" for k, v in (tags or {}).items())
print(f"[METRIC] {name}: {value}{unit} {tags_str}")
async def create_span(
self, name: str, attributes: Optional[Dict[str, Any]] = None
) -> Span:
"""Create a span for tracing."""
span = Span(name=name, attributes=attributes or {})
print(f"[SPAN START] {name}")
return span
async def end_span(self, span: Span) -> None:
"""End and record a span."""
span.end()
self.spans.append(span)
duration = span.duration_ms() or 0
print(f"[SPAN END] {span.name}: {duration:.2f}ms")
async def run_example() -> None:
"""
Example showing all extensibility interfaces working together.
"""
from vanna.integrations.anthropic import AnthropicLlmService
# Create all extensibility components
caching_middleware = CachingMiddleware()
retry_strategy = ExponentialBackoffStrategy(max_retries=3)
preferences_enricher = UserPreferencesEnricher()
context_filter = ContextWindowFilter(max_messages=20)
observability = LoggingObservabilityProvider()
# Mock conversation store
class MockStore:
async def get_conversation(self, cid: str, uid: str) -> Optional[Conversation]:
return None
async def create_conversation(
self, cid: str, uid: str, title: str
) -> Conversation:
return Conversation(
id=cid, user_id=uid, messages=[Message(role="user", content=title)]
)
async def update_conversation(self, conv: Conversation) -> None:
pass
async def delete_conversation(self, cid: str, uid: str) -> bool:
return False
async def list_conversations(
self, uid: str, limit: int = 50, offset: int = 0
) -> List[Conversation]:
return []
# Create agent with all extensibility components
agent = Agent(
llm_service=AnthropicLlmService(api_key="test-key"),
tool_registry=ToolRegistry(),
conversation_store=MockStore(), # type: ignore
llm_middlewares=[caching_middleware],
error_recovery_strategy=retry_strategy,
context_enrichers=[preferences_enricher],
conversation_filters=[context_filter],
observability_provider=observability,
)
print("✓ Agent created with all extensibility components:")
print(f" - LLM Middleware: {len(agent.llm_middlewares)} middlewares")
print(f" - Error Recovery: {type(agent.error_recovery_strategy).__name__}")
print(f" - Context Enrichers: {len(agent.context_enrichers)} enrichers")
print(f" - Conversation Filters: {len(agent.conversation_filters)} filters")
print(f" - Observability: {type(agent.observability_provider).__name__}")
print("\n🎉 All extensibility interfaces integrated successfully!")
if __name__ == "__main__":
asyncio.run(run_example())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/extensibility_example.py",
"license": "MIT License",
"lines": 217,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/minimal_example.py | """Minimal Claude + SQLite example ready for FastAPI."""
from __future__ import annotations
import os
from pathlib import Path
from vanna import AgentConfig, Agent
from vanna.core.registry import ToolRegistry
from vanna.integrations.anthropic import AnthropicLlmService
from vanna.integrations.sqlite import SqliteRunner
from vanna.integrations.local import LocalFileSystem
from vanna.tools import (
RunSqlTool,
# Visualization
VisualizeDataTool,
# Python execution
RunPythonFileTool,
PipInstallTool,
# File system (for coding agents)
SearchFilesTool,
ListFilesTool,
ReadFileTool,
WriteFileTool,
)
_DB = Path(__file__).resolve().parents[2] / "Chinook.sqlite"
def create_demo_agent() -> Agent:
# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()
llm = AnthropicLlmService(model=os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-5"))
# Shared file system for all tools
file_system = LocalFileSystem("./claude_data")
tools = ToolRegistry()
# 1. Basic SQL agent - query databases
tools.register(
RunSqlTool(
sql_runner=SqliteRunner(database_path=str(_DB)),
file_system=file_system,
)
)
# 2. Add visualization - create charts from data
tools.register(VisualizeDataTool(file_system=file_system))
# 3. Add Python execution - build dashboards with artifacts
# tools.register(RunPythonFileTool(file_system=file_system))
# tools.register(PipInstallTool(file_system=file_system))
# 4. Full coding agent - read, write, search files
# tools.register(SearchFilesTool(file_system=file_system))
# tools.register(ListFilesTool(file_system=file_system))
# tools.register(ReadFileTool(file_system=file_system))
# tools.register(WriteFileTool(file_system=file_system))
return Agent(
llm_service=llm,
tool_registry=tools,
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/minimal_example.py",
"license": "MIT License",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/examples/mock_auth_example.py | """
Mock authentication example to verify user resolution is working.
This example demonstrates the new UserResolver architecture where:
1. UserResolver is a required parameter of Agent
2. Agent.send_message() accepts RequestContext (not User directly)
3. The Agent resolves the user internally using the UserResolver
The agent uses an LLM middleware to inject user info into the response,
so we can verify the authentication is working correctly.
Usage:
python -m vanna.examples.mock_auth_example
"""
from __future__ import annotations
import asyncio
from vanna import AgentConfig, Agent
from vanna.core.registry import ToolRegistry
from vanna.core.llm import LlmRequest, LlmResponse
from vanna.core.middleware import LlmMiddleware
from vanna.integrations.mock import MockLlmService
from vanna.core.user import CookieEmailUserResolver, RequestContext
class UserEchoMiddleware(LlmMiddleware):
"""Middleware that injects user email into LLM responses."""
async def after_llm_response(
self, request: LlmRequest, response: LlmResponse
) -> LlmResponse:
"""Inject user email into response."""
# Extract user email from request user_id (which is set to user.id in the agent)
user_id = request.user_id
# Create a new response with user info
new_content = f"Hello! You are authenticated as: {user_id}"
return LlmResponse(
content=new_content,
finish_reason=response.finish_reason,
usage=response.usage,
)
def create_demo_agent() -> Agent:
"""Create a demo agent for server usage.
Returns:
Configured Agent instance with cookie-based authentication
"""
# Create a mock LLM
llm_service = MockLlmService(response_content="Mock response")
# Empty tool registry
tool_registry = ToolRegistry()
# Cookie-based user resolver
user_resolver = CookieEmailUserResolver(cookie_name="vanna_email")
# User echo middleware
middleware = UserEchoMiddleware()
# Create agent with user resolver and middleware
agent = Agent(
llm_service=llm_service,
tool_registry=tool_registry,
user_resolver=user_resolver,
llm_middlewares=[middleware],
config=AgentConfig(
stream_responses=True,
include_thinking_indicators=False,
),
)
return agent
async def demo_authentication():
"""Demonstrate authentication with different request contexts."""
agent = create_demo_agent()
print("=== Mock Authentication Demo ===")
print("This example verifies that user resolution is working correctly.\n")
# Test 1: Request with email cookie
print("🔹 Test 1: Authenticated user (alice@example.com)")
request_context = RequestContext(
cookies={"vanna_email": "alice@example.com"},
headers={},
remote_addr="127.0.0.1",
)
print(
"Request context:",
{
"cookies": request_context.cookies,
"headers": request_context.headers,
"remote_addr": request_context.remote_addr,
},
)
# Send message - Agent will resolve user internally
agent_response = ""
async for component in agent.send_message(
request_context=request_context,
message="Who am I?",
conversation_id="test_conv_1",
):
# Extract and display user info from the resolved user
if hasattr(component, "rich_component"):
rich = component.rich_component
# Check if it's a text component
if rich.type.value == "text":
# Access content directly from the component (before serialization)
if hasattr(rich, "content"):
agent_response = rich.content
print(f"Agent response: {agent_response}")
# Verify user was resolved by checking the conversation store
user_resolver = agent.user_resolver
resolved_user = await user_resolver.resolve_user(request_context)
print(
f"✅ Resolved user: {resolved_user.email} (username: {resolved_user.username}, id: {resolved_user.id})"
)
print(f" Permissions: {resolved_user.permissions}")
print(f" Metadata: {resolved_user.metadata}")
print("\n" + "=" * 60 + "\n")
# Test 2: Request without email cookie (anonymous)
print("🔹 Test 2: Anonymous user (no cookie)")
anonymous_context = RequestContext(cookies={}, headers={}, remote_addr="127.0.0.1")
print(
"Request context:",
{
"cookies": anonymous_context.cookies,
"headers": anonymous_context.headers,
"remote_addr": anonymous_context.remote_addr,
},
)
agent_response = ""
async for component in agent.send_message(
request_context=anonymous_context,
message="Who am I?",
conversation_id="test_conv_2",
):
if hasattr(component, "rich_component"):
rich = component.rich_component
if rich.type.value == "text" and hasattr(rich, "content"):
agent_response = rich.content
print(f"Agent response: {agent_response}")
resolved_user = await user_resolver.resolve_user(anonymous_context)
print(
f"✅ Resolved user: {resolved_user.email or 'None'} (username: {resolved_user.username}, id: {resolved_user.id})"
)
print(f" Permissions: {resolved_user.permissions}")
print(f" Metadata: {resolved_user.metadata}")
print("\n" + "=" * 60 + "\n")
# Test 3: Different user
print("🔹 Test 3: Different authenticated user (bob@company.com)")
bob_context = RequestContext(
cookies={"vanna_email": "bob@company.com"},
headers={"User-Agent": "Mozilla/5.0"},
remote_addr="192.168.1.100",
)
print(
"Request context:",
{
"cookies": bob_context.cookies,
"headers": bob_context.headers,
"remote_addr": bob_context.remote_addr,
},
)
agent_response = ""
async for component in agent.send_message(
request_context=bob_context, message="Who am I?", conversation_id="test_conv_3"
):
if hasattr(component, "rich_component"):
rich = component.rich_component
if rich.type.value == "text" and hasattr(rich, "content"):
agent_response = rich.content
print(f"Agent response: {agent_response}")
resolved_user = await user_resolver.resolve_user(bob_context)
print(
f"✅ Resolved user: {resolved_user.email} (username: {resolved_user.username}, id: {resolved_user.id})"
)
print(f" Permissions: {resolved_user.permissions}")
print(f" Metadata: {resolved_user.metadata}")
print("\n" + "=" * 60)
print("\n✅ Authentication demo complete!")
print("\nKey Features Verified:")
print("• UserResolver is part of Agent")
print("• Agent.send_message() accepts RequestContext")
print("• User resolution happens internally in Agent")
print("• CookieEmailUserResolver extracts email from vanna_email cookie")
print("• Anonymous users are created when no cookie is present")
print("• Different users can be resolved from different request contexts")
async def main():
"""Run the authentication example."""
await demo_authentication()
def run_interactive():
"""Entry point for interactive usage."""
print("Starting mock authentication example...")
asyncio.run(main())
if __name__ == "__main__":
run_interactive()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/mock_auth_example.py",
"license": "MIT License",
"lines": 181,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/mock_custom_tool.py | """
Mock example showing how to create and use custom tools.
This example demonstrates creating a simple calculator tool
and registering it with an agent that uses a mock LLM service.
It now includes a `MockCalculatorLlmService` that automatically
invokes the calculator tool with random numbers before echoing
back the computed answer.
Usage:
Template: Copy this file and modify for your custom tools
Interactive: python -m vanna.examples.mock_custom_tool
REPL: from vanna.examples.mock_custom_tool import create_demo_agent
Server: python -m vanna.servers --example mock_custom_tool
"""
import asyncio
import random
import uuid
from typing import AsyncGenerator, Dict, List, Optional, Tuple, Type
from pydantic import BaseModel, Field
from vanna import (
AgentConfig,
Agent,
Tool,
ToolContext,
ToolRegistry,
ToolResult,
User,
UiComponent,
)
from vanna.core.interfaces import LlmService
from vanna.core.models import (
LlmRequest,
LlmResponse,
LlmStreamChunk,
ToolCall,
ToolSchema,
)
from vanna.core.rich_components import (
CardComponent,
NotificationComponent,
ComponentType,
)
from vanna.core.simple_components import (
SimpleTextComponent,
)
class CalculatorArgs(BaseModel):
"""Arguments for the calculator tool."""
operation: str = Field(
description="The operation to perform: add, subtract, multiply, divide"
)
a: float = Field(description="First number")
b: float = Field(description="Second number")
class CalculatorTool(Tool[CalculatorArgs]):
"""A simple calculator tool."""
@property
def name(self) -> str:
return "calculator"
@property
def description(self) -> str:
return "Perform basic arithmetic operations (add, subtract, multiply, divide)"
def get_args_schema(self) -> Type[CalculatorArgs]:
return CalculatorArgs
async def execute(self, context: ToolContext, args: CalculatorArgs) -> ToolResult:
"""Execute the calculator operation."""
symbol_map = {"add": "+", "subtract": "-", "multiply": "×", "divide": "÷"}
try:
if args.operation == "add":
result = args.a + args.b
elif args.operation == "subtract":
result = args.a - args.b
elif args.operation == "multiply":
result = args.a * args.b
elif args.operation == "divide":
if args.b == 0:
message = "Cannot divide by zero"
await asyncio.sleep(3)
return ToolResult(
success=False,
result_for_llm=message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=message,
),
simple_component=SimpleTextComponent(text=message),
),
error=message,
)
result = args.a / args.b
else:
message = f"Unknown operation: {args.operation}"
await asyncio.sleep(3)
return ToolResult(
success=False,
result_for_llm=message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="warning",
message=message,
),
simple_component=SimpleTextComponent(text=message),
),
error=message,
)
await asyncio.sleep(3)
symbol = symbol_map.get(args.operation, args.operation)
expression = f"{args.a:g} {symbol} {args.b:g} = {result:g}"
return ToolResult(
success=True,
result_for_llm=str(result),
ui_component=UiComponent(
rich_component=CardComponent(
type=ComponentType.CARD,
title="Calculator Result",
content=expression,
),
simple_component=SimpleTextComponent(text=expression),
),
error=None,
)
except Exception as e:
message = str(e)
await asyncio.sleep(3)
return ToolResult(
success=False,
result_for_llm=message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=message,
),
simple_component=SimpleTextComponent(text=message),
),
error=message,
)
class MockCalculatorLlmService(LlmService):
"""LLM service that exercises the calculator tool before echoing the result."""
def __init__(self, seed: Optional[int] = None):
self._random = random.Random(seed)
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Handle non-streaming calculator interactions."""
await asyncio.sleep(0.05)
return self._build_response(request)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Provide streaming compatibility by yielding a single chunk."""
await asyncio.sleep(0.05)
response = self._build_response(request)
if response.tool_calls:
yield LlmStreamChunk(tool_calls=response.tool_calls)
if response.content is not None:
yield LlmStreamChunk(
content=response.content, finish_reason=response.finish_reason
)
else:
yield LlmStreamChunk(finish_reason=response.finish_reason)
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Mock validation - no errors."""
return []
def _build_response(self, request: LlmRequest) -> LlmResponse:
"""Create a response that either calls the tool or echoes its result."""
last_message = request.messages[-1] if request.messages else None
if last_message and last_message.role == "tool":
answer = last_message.content or "No result provided"
return LlmResponse(
content=answer,
finish_reason="stop",
usage={
"prompt_tokens": 30,
"completion_tokens": 10,
"total_tokens": 40,
},
)
operation, a, b = self._random_operands()
tool_call = ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="calculator",
arguments={"operation": operation, "a": a, "b": b},
)
return LlmResponse(
content="Let me ask my calculator friend for help...",
tool_calls=[tool_call],
finish_reason="tool_calls",
usage={"prompt_tokens": 30, "completion_tokens": 5, "total_tokens": 35},
)
def _random_operands(self) -> Tuple[str, float, float]:
"""Generate operation and operands suited for the calculator tool."""
operation = self._random.choice(["add", "subtract", "multiply", "divide"])
if operation == "divide":
b = float(self._random.randint(1, 10))
multiplier = self._random.randint(1, 10)
a = float(b * multiplier)
elif operation == "subtract":
b = float(self._random.randint(1, 10))
a = b + float(self._random.randint(0, 10))
else:
a = float(self._random.randint(1, 12))
b = float(self._random.randint(1, 12))
return operation, a, b
def create_demo_agent() -> Agent:
"""Create a demo agent with custom calculator tool.
Returns:
Configured Agent with calculator tool and mock calculator LLM
"""
tool_registry = ToolRegistry()
calculator_tool = CalculatorTool()
tool_registry.register(calculator_tool)
llm_service = MockCalculatorLlmService()
return Agent(
llm_service=llm_service,
tool_registry=tool_registry,
config=AgentConfig(
stream_responses=False,
include_thinking_indicators=False,
),
)
async def main() -> None:
"""Run the mock custom tool example."""
# Create agent using factory function
agent = create_demo_agent()
tool_registry = agent.tool_registry
# Create a test user
user = User(id="user123", username="testuser", permissions=[])
# Test the tool directly
print("Testing calculator tool directly:")
tool_call = ToolCall(
id="test123", name="calculator", arguments={"operation": "add", "a": 5, "b": 3}
)
context = ToolContext(user=user, conversation_id="test", request_id="test")
result = await tool_registry.execute(tool_call, context)
print(f"5 + 3 = {result.result_for_llm if result.success else result.error}")
# Show available tools
schemas = await tool_registry.get_schemas(user)
print(f"\nAvailable tools for user: {[schema.name for schema in schemas]}")
# Demonstrate the mock LLM triggering a tool call
print("\nAgent conversation demo:")
conversation_id = "calc-demo"
async for component in agent.send_message(
user=user,
message="Can you compute something for me?",
conversation_id=conversation_id,
):
print(f"- Component type: {component.rich_component.type}")
if (
hasattr(component.rich_component, "content")
and component.rich_component.content
):
print(f"Assistant: {component.rich_component.content}")
elif component.simple_component and hasattr(component.simple_component, "text"):
print(f"Assistant: {component.simple_component.text}")
else:
print(f"- Component data: {component.rich_component.data}")
def run_interactive() -> None:
"""Entry point for interactive usage."""
print("Starting mock custom tool example...")
asyncio.run(main())
if __name__ == "__main__":
run_interactive()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/mock_custom_tool.py",
"license": "MIT License",
"lines": 261,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/mock_quickstart.py | """
Mock quickstart example for the Vanna Agents framework.
This example shows how to create a basic agent with a mock LLM service
and have a simple conversation.
Usage:
Template: Copy this file and modify for your needs
Interactive: python -m vanna.examples.mock_quickstart
REPL: from vanna.examples.mock_quickstart import create_demo_agent
Server: python -m vanna.servers --example mock_quickstart
"""
import asyncio
from vanna import (
AgentConfig,
Agent,
MemoryConversationStore,
MockLlmService,
User,
)
def create_demo_agent() -> Agent:
"""Create a demo agent for REPL and server usage.
Returns:
Configured Agent instance
"""
llm_service = MockLlmService(
response_content="Hello! I'm a helpful AI assistant created using the Vanna Agents framework."
)
return Agent(
llm_service=llm_service,
config=AgentConfig(
stream_responses=True, # Enable streaming for better server experience
include_thinking_indicators=True,
),
)
async def main() -> None:
"""Run the mock quickstart example."""
# Create agent using factory function
agent = create_demo_agent()
# Create a test user
user = User(
id="user123", username="testuser", email="test@example.com", permissions=[]
)
# Start a conversation
conversation_id = "conversation123"
user_message = "Hello! Can you introduce yourself?"
print(f"User: {user_message}")
print("Agent: ", end="")
# Send message and collect response
async for component in agent.send_message(
user=user, message=user_message, conversation_id=conversation_id
):
if hasattr(component, "content"):
print(component.content, end="")
print()
def run_interactive() -> None:
"""Entry point for interactive usage."""
print("Starting Vanna Agents mock quickstart demo...")
asyncio.run(main())
if __name__ == "__main__":
run_interactive()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/mock_quickstart.py",
"license": "MIT License",
"lines": 59,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/examples/mock_quota_example.py | """
Mock quota-based agent example using Mock LLM service.
This example demonstrates how to create a custom agent runner that
enforces user-based message quotas. It shows:
- Custom agent runner subclass
- Quota management and enforcement
- Error handling for quota exceeded cases
- Multiple users with different quotas
Run:
PYTHONPATH=. python vanna/examples/mock_quota_example.py
"""
import asyncio
from vanna import (
AgentConfig,
MemoryConversationStore,
MockLlmService,
User,
)
from vanna.core.registry import ToolRegistry
from vanna.tools import ListFilesTool
from vanna.examples.quota_agent import QuotaAgentRunner, QuotaExceededError
async def demonstrate_quota_system() -> None:
"""Demonstrate the quota-based agent system."""
print("🚀 Starting Mock Quota-based Agent Example\n")
# Create a mock LLM service
llm_service = MockLlmService(
response_content="Hello! I'm here to help you with your questions."
)
# Create tool registry with list_files tool
tool_registry = ToolRegistry()
list_files_tool = ListFilesTool()
tool_registry.register(list_files_tool)
# Create conversation store
conversation_store = MemoryConversationStore()
# Create the quota-based agent
agent = QuotaAgentRunner(
llm_service=llm_service,
tool_registry=tool_registry,
conversation_store=conversation_store,
config=AgentConfig(
stream_responses=False,
include_thinking_indicators=False,
),
)
# Create users with different quota settings
regular_user = User(
id="user1", username="alice", email="alice@example.com", permissions=[]
)
premium_user = User(
id="user2", username="bob", email="bob@example.com", permissions=["premium"]
)
# Set custom quotas
agent.set_user_quota(regular_user.id, 3) # Alice gets 3 messages
agent.set_user_quota(premium_user.id, 5) # Bob gets 5 messages (premium)
print("📋 User Quotas:")
print(
f" • {regular_user.username}: {agent.get_user_quota(regular_user.id)} messages"
)
print(
f" • {premium_user.username}: {agent.get_user_quota(premium_user.id)} messages"
)
print()
# Test regular user within quota
print("💬 Testing regular user (Alice) within quota:")
for i in range(1, 4): # Send 3 messages (within quota)
print(f" Message {i}/3:")
async for component in agent.send_message(
user=regular_user,
message=f"Hello, this is message {i}",
conversation_id="alice-conv",
):
if hasattr(component, "content") and component.content:
print(f" Agent: {component.content}")
print()
# Test regular user exceeding quota
print("⚠️ Testing regular user (Alice) exceeding quota:")
async for component in agent.send_message(
user=regular_user,
message="This message should be blocked",
conversation_id="alice-conv",
):
if hasattr(component, "content") and component.content:
print(f" Agent: {component.content}")
print()
# Test premium user with higher quota
print("⭐ Testing premium user (Bob) with higher quota:")
for i in range(1, 4): # Send 3 messages
print(f" Message {i}/5:")
async for component in agent.send_message(
user=premium_user,
message=f"Premium user message {i}",
conversation_id="bob-conv",
):
if hasattr(component, "content") and component.content:
print(f" Agent: {component.content}")
print()
# Demonstrate quota reset
print("🔄 Resetting Alice's usage:")
agent.reset_user_usage(regular_user.id)
print(f" Alice's remaining messages: {agent.get_user_remaining(regular_user.id)}")
print()
print("✅ After reset, Alice can send messages again:")
async for component in agent.send_message(
user=regular_user,
message="This should work after reset",
conversation_id="alice-conv2",
):
if hasattr(component, "content") and component.content:
print(f" Agent: {component.content}")
print("\n📊 Final Usage Summary:")
print(
f" • Alice: {agent.get_user_usage(regular_user.id)}/{agent.get_user_quota(regular_user.id)} used"
)
print(
f" • Bob: {agent.get_user_usage(premium_user.id)}/{agent.get_user_quota(premium_user.id)} used"
)
async def main() -> None:
"""Run the mock quota example."""
await demonstrate_quota_system()
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/mock_quota_example.py",
"license": "MIT License",
"lines": 121,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/mock_rich_components_demo.py | """
Mock rich components demonstration example.
This example shows how to create an agent that emits rich, stateful components
including cards, task lists, and tool execution displays using a mock LLM service.
Usage:
PYTHONPATH=. python vanna/examples/mock_rich_components_demo.py
"""
import asyncio
import time
from datetime import datetime
from typing import AsyncGenerator, Optional
from vanna import (
AgentConfig,
Agent,
MemoryConversationStore,
MockLlmService,
User,
)
from vanna.core.components import UiComponent
from vanna.core.rich_components import (
StatusCardComponent,
ProgressDisplayComponent,
LogViewerComponent,
BadgeComponent,
IconTextComponent,
RichTextComponent,
Task,
)
class RichComponentsAgent(Agent):
"""Agent that demonstrates rich component capabilities."""
async def send_message(
self,
user: User,
message: str,
*,
conversation_id: Optional[str] = None,
) -> AsyncGenerator[UiComponent, None]:
"""Send message and yield UiComponent(rich_component=rich) components."""
# Welcome message using IconText
yield UiComponent(
rich_component=IconTextComponent(
id="welcome-message",
icon="👋",
text=f"Hello {user.username}! I'll demonstrate primitive components.",
variant="primary",
size="large",
)
)
# Status card showing we're processing
status_card = StatusCardComponent(
id="processing-status",
title="Processing Request",
status="running",
description="Processing your request...",
icon="⚙️",
)
yield UiComponent(rich_component=status_card)
# Simulate some processing time
await asyncio.sleep(1)
# Update status to success
yield UiComponent(
rich_component=status_card.set_status(
"success", "Request processed successfully!"
)
)
# Create a status card for overall demo progress
demo_card = StatusCardComponent(
id="demo-progress",
title="Demo Progress",
status="running",
description="Starting primitive components demonstration...",
icon="🎯",
)
yield UiComponent(rich_component=demo_card)
# Create badges for different stages
stages = [
("Initialize", "success", "✅"),
("Components", "running", "⚙️"),
("Progress", "pending", "⏳"),
("Logs", "pending", "📋"),
("Complete", "pending", "🎉"),
]
for stage_name, stage_status, stage_icon in stages:
yield UiComponent(
rich_component=BadgeComponent(
id=f"stage-{stage_name.lower()}",
text=stage_name,
variant=stage_status if stage_status != "pending" else "default",
icon=stage_icon,
size="md",
)
)
# Progress display
progress_display = ProgressDisplayComponent(
id="demo-progress-bar",
label="Overall Progress",
value=0.2,
description="Initializing demonstration...",
status="info",
animated=True,
)
yield UiComponent(rich_component=progress_display)
# Create log viewer for detailed progress
log_viewer = LogViewerComponent(id="demo-logs", title="Demo Activity Log")
yield UiComponent(rich_component=log_viewer)
# Simulate work with updates
for i in range(3):
await asyncio.sleep(1)
# Update progress
progress_value = 0.2 + (i + 1) * 0.2
step_name = ["Creating components", "Updating progress", "Finalizing demo"][
i
]
yield UiComponent(
rich_component=progress_display.update_progress(
progress_value, f"Step {i + 2} of 5: {step_name}..."
)
)
# Update demo card
yield UiComponent(
rich_component=demo_card.set_status(
"running",
f"Step {i + 2} of 5 completed. Progress: {int(progress_value * 100)}%",
)
)
# Add log entry
yield UiComponent(
rich_component=log_viewer.add_entry(
f"Completed step: {step_name}", "info"
)
)
# Update stage badges
if i == 0:
yield UiComponent(
rich_component=BadgeComponent(
id="stage-components",
text="Components",
variant="success",
icon="✅",
size="md",
)
)
elif i == 1:
yield UiComponent(
rich_component=BadgeComponent(
id="stage-progress",
text="Progress",
variant="success",
icon="✅",
size="md",
)
)
yield UiComponent(
rich_component=BadgeComponent(
id="stage-logs",
text="Logs",
variant="running",
icon="📋",
size="md",
)
)
# Tool execution using primitive components
tool_status = StatusCardComponent(
id="demo-tool",
title="Analyze Data Tool",
status="running",
description="Running regression analysis on user_data.csv",
icon="🔬",
)
yield UiComponent(rich_component=tool_status)
# Tool progress
tool_progress = ProgressDisplayComponent(
id="tool-progress",
label="Tool Execution",
value=0.0,
description="Initializing tool...",
animated=True,
)
yield UiComponent(rich_component=tool_progress)
# Tool logs
tool_logs = LogViewerComponent(id="tool-logs", title="Tool Execution Log")
yield UiComponent(rich_component=tool_logs)
# Simulate tool execution steps
tool_steps = [
(0.2, "Loading dataset...", "info"),
(0.4, "Dataset loaded: 1000 rows, 5 columns", "info"),
(0.6, "Preprocessing data...", "info"),
(0.8, "Running regression analysis...", "info"),
(1.0, "Analysis complete!", "info"),
]
for progress_val, log_message, log_level in tool_steps:
await asyncio.sleep(0.5)
yield UiComponent(
rich_component=tool_progress.update_progress(
progress_val, f"Progress: {int(progress_val * 100)}%"
)
)
yield UiComponent(
rich_component=tool_logs.add_entry(log_message, log_level)
)
# Complete tool execution
yield UiComponent(
rich_component=tool_status.set_status(
"success",
"Tool completed successfully. R² = 0.85, strong correlation found.",
)
)
# Show results using IconText
yield UiComponent(
rich_component=IconTextComponent(
id="tool-results",
icon="📊",
text="Analysis Results: R² = 0.85 (Strong correlation)",
variant="success",
size="medium",
)
)
# Update final stage badge
yield UiComponent(
rich_component=BadgeComponent(
id="stage-logs", text="Logs", variant="success", icon="✅", size="md"
)
)
yield UiComponent(
rich_component=BadgeComponent(
id="stage-complete",
text="Complete",
variant="success",
icon="🎉",
size="md",
)
)
# Final updates
yield UiComponent(
rich_component=progress_display.update_progress(
1.0, "Demo completed successfully!"
)
)
yield UiComponent(
rich_component=demo_card.set_status(
"success", "Primitive components demonstration finished successfully!"
)
)
# Add final log entry
yield UiComponent(
rich_component=tool_logs.add_entry("Demo completed successfully!", "info")
)
# Add final text response
yield UiComponent(
rich_component=RichTextComponent(
content=f"""## Primitive Components Demo Complete!
I've demonstrated the new primitive component system:
- **Status Cards**: Domain-agnostic status displays that work for any process
- **Progress Displays**: Reusable progress indicators with animations
- **Log Viewers**: Structured log display for any activity
- **Badges**: Flexible status and category indicators
- **Icon Text**: Composable icon+text combinations
### Key Benefits of Primitive Components:
- **Separation of Concerns**: UI components are purely presentational
- **Reusability**: Components work across different domains and tools
- **Composability**: Tools build exactly the UI they need from primitives
- **Maintainability**: Business logic changes don't affect UI components
- **Extensibility**: New tools don't require new component types
**Primitive Components**: Compose UI from domain-agnostic building blocks
**After**: Tools compose UI from primitive `StatusCard` + `ProgressDisplay` + `LogViewer`
Your message was: "{message}"
""",
markdown=True,
)
)
# CLI compatibility alias
create_demo_agent = lambda: create_rich_demo_agent()
def create_rich_demo_agent() -> RichComponentsAgent:
"""Create a primitive components demo agent.
Returns:
Configured RichComponentsAgent instance
"""
llm_service = MockLlmService(response_content="Primitive components demo response")
return RichComponentsAgent(
llm_service=llm_service,
config=AgentConfig(
stream_responses=True,
include_thinking_indicators=False, # We'll use custom status cards
),
)
async def main() -> None:
"""Run the primitive components demo."""
# Create agent
agent = create_rich_demo_agent()
# Create a test user
user = User(
id="user123", username="demo_user", email="demo@example.com", permissions=[]
)
# Start a conversation
conversation_id = "primitive_demo_123"
user_message = "Show me the primitive components demo!"
print(f"User: {user_message}")
print("Agent response (primitive components):")
print("=" * 50)
# Send message and display components
component_count = 0
async for component in agent.send_message(
user=user, message=user_message, conversation_id=conversation_id
):
component_count += 1
rich_comp = component.rich_component
component_type = getattr(rich_comp, "type", rich_comp.__class__.__name__)
component_id = getattr(rich_comp, "id", "N/A")
lifecycle = getattr(rich_comp, "lifecycle", "N/A")
print(
f"[{component_count:2d}] {component_type} (id: {component_id[:8]}, lifecycle: {lifecycle})"
)
# Show some component details
if hasattr(rich_comp, "title"):
print(f" Title: {rich_comp.title}")
if hasattr(rich_comp, "content") and len(str(rich_comp.content)) < 100:
print(f" Content: {rich_comp.content}")
if hasattr(rich_comp, "status"):
print(f" Status: {rich_comp.status}")
if (
hasattr(rich_comp, "value")
and hasattr(rich_comp.type, "value")
and rich_comp.type.value == "progress_bar"
):
print(f" Progress: {rich_comp.value:.1%}")
print()
print("=" * 50)
print(f"Total components emitted: {component_count}")
def run_interactive() -> None:
"""Entry point for interactive usage."""
print("Starting Primitive Components Demo...")
asyncio.run(main())
if __name__ == "__main__":
run_interactive()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/mock_rich_components_demo.py",
"license": "MIT License",
"lines": 334,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/mock_sqlite_example.py | """
Mock example showing how to use the SQL query tool with the Chinook database.
This example demonstrates using the RunSqlTool with SqliteRunner and a mock LLM service
that automatically executes sample SQL queries against the Chinook database.
Usage:
Template: Copy this file and modify for your custom database
Interactive: python -m vanna.examples.mock_sqlite_example
REPL: from vanna.examples.mock_sqlite_example import create_demo_agent
Server: python -m vanna.servers --example mock_sqlite_example
"""
import asyncio
import os
import random
import uuid
from typing import AsyncGenerator, Dict, List, Optional, Type
from pydantic import BaseModel, Field
from vanna import (
AgentConfig,
Agent,
Tool,
ToolContext,
ToolRegistry,
ToolResult,
User,
UiComponent,
)
from vanna.core.interfaces import LlmService
from vanna.core.models import (
LlmRequest,
LlmResponse,
LlmStreamChunk,
ToolCall,
ToolSchema,
)
from vanna.core.rich_components import (
CardComponent,
NotificationComponent,
ComponentType,
)
from vanna.core.simple_components import (
SimpleTextComponent,
)
from vanna.tools import RunSqlTool
from vanna.integrations.sqlite import SqliteRunner
class MockSqliteLlmService(LlmService):
"""LLM service that exercises the SQLite query tool with sample queries."""
def __init__(self, seed: Optional[int] = None):
self._random = random.Random(seed)
self._sample_queries = [
"SELECT name FROM sqlite_master WHERE type='table'",
"SELECT COUNT(*) as total_customers FROM Customer",
"SELECT FirstName, LastName FROM Customer LIMIT 5",
"SELECT Name, Composer FROM Track WHERE Composer IS NOT NULL LIMIT 5",
"SELECT COUNT(*) as album_count FROM Album",
"SELECT Name FROM Artist LIMIT 10",
"SELECT AVG(Total) as avg_invoice_total FROM Invoice",
"SELECT GenreId, COUNT(*) as track_count FROM Track GROUP BY GenreId LIMIT 5",
]
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Handle non-streaming SQLite interactions."""
await asyncio.sleep(0.1)
return self._build_response(request)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Provide streaming compatibility by yielding a single chunk."""
await asyncio.sleep(0.1)
response = self._build_response(request)
if response.tool_calls:
yield LlmStreamChunk(tool_calls=response.tool_calls)
if response.content is not None:
yield LlmStreamChunk(
content=response.content, finish_reason=response.finish_reason
)
else:
yield LlmStreamChunk(finish_reason=response.finish_reason)
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Mock validation - no errors."""
return []
def _build_response(self, request: LlmRequest) -> LlmResponse:
"""Create a response that either calls the tool or explains its result."""
last_message = request.messages[-1] if request.messages else None
if last_message and last_message.role == "tool":
# Respond to tool result
result = last_message.content or "No result provided"
return LlmResponse(
content=f"Here's what I found in the database:\n\n{result}",
finish_reason="stop",
usage={
"prompt_tokens": 40,
"completion_tokens": 20,
"total_tokens": 60,
},
)
# Generate a random SQL query
sql_query = self._random.choice(self._sample_queries)
tool_call = ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="run_sql",
arguments={"sql": sql_query},
)
return LlmResponse(
content="Let me query the Chinook database for you...",
tool_calls=[tool_call],
finish_reason="tool_calls",
usage={"prompt_tokens": 30, "completion_tokens": 10, "total_tokens": 40},
)
def create_demo_agent() -> Agent:
"""Create a demo agent with SQLite query tool.
Returns:
Configured Agent with SQLite tool and mock LLM
"""
# Get the path to the Chinook database
database_path = os.path.join(
os.path.dirname(__file__), "..", "..", "Chinook.sqlite"
)
database_path = os.path.abspath(database_path)
if not os.path.exists(database_path):
raise FileNotFoundError(
f"Chinook database not found at {database_path}. Please download it from https://vanna.ai/Chinook.sqlite"
)
tool_registry = ToolRegistry()
sqlite_runner = SqliteRunner(database_path=database_path)
sql_tool = RunSqlTool(sql_runner=sqlite_runner)
tool_registry.register(sql_tool)
llm_service = MockSqliteLlmService()
return Agent(
llm_service=llm_service,
tool_registry=tool_registry,
config=AgentConfig(
stream_responses=False,
include_thinking_indicators=False,
),
)
async def main() -> None:
"""Run the mock SQLite example."""
# Create agent using factory function
agent = create_demo_agent()
tool_registry = agent.tool_registry
# Create a test user
user = User(id="user123", username="testuser", permissions=[])
# Test the tool directly
print("Testing SQL tool directly:")
tool_call = ToolCall(
id="test123",
name="run_sql",
arguments={"sql": "SELECT name FROM sqlite_master WHERE type='table'"},
)
context = ToolContext(user=user, conversation_id="test", request_id="test")
result = await tool_registry.execute(tool_call, context)
print(
f"Tables in database:\n{result.result_for_llm if result.success else result.error}"
)
# Show available tools
schemas = await tool_registry.get_schemas(user)
print(f"\nAvailable tools for user: {[schema.name for schema in schemas]}")
# Demonstrate the mock LLM triggering SQL queries
print("\n" + "=" * 50)
print("Agent conversation demo:")
print("=" * 50)
conversation_id = "sqlite-demo"
# Run multiple queries to show different results
for i in range(3):
print(f"\n--- Query {i + 1} ---")
async for component in agent.send_message(
user=user,
message=f"Show me some data from the database (query {i + 1})",
conversation_id=conversation_id,
):
if (
hasattr(component.rich_component, "content")
and component.rich_component.content
):
print(f"Assistant: {component.rich_component.content}")
elif component.simple_component and hasattr(
component.simple_component, "text"
):
print(f"Assistant: {component.simple_component.text}")
def run_interactive() -> None:
"""Entry point for interactive usage."""
print("Starting mock SQLite example...")
print("This example uses the Chinook database to demonstrate SQL queries.")
asyncio.run(main())
if __name__ == "__main__":
run_interactive()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/mock_sqlite_example.py",
"license": "MIT License",
"lines": 185,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/openai_quickstart.py | """
OpenAI example using OpenAILlmService.
Loads environment from .env (via python-dotenv), uses model 'gpt-5' by default,
and sends a simple message through a Agent.
Run:
PYTHONPATH=. python vanna/examples/openai_quickstart.py
"""
import asyncio
import importlib.util
import os
import sys
def ensure_env() -> None:
if importlib.util.find_spec("dotenv") is not None:
from dotenv import load_dotenv
# Load from local .env without overriding existing env
load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".env"), override=False)
else:
print(
"[warn] python-dotenv not installed; skipping .env load. Install with: pip install python-dotenv"
)
if not os.getenv("OPENAI_API_KEY"):
print(
"[error] OPENAI_API_KEY is not set. Add it to your environment or .env file."
)
sys.exit(1)
async def main() -> None:
ensure_env()
# Lazy import after env load to allow custom base_url/org via env
try:
from vanna.integrations.anthropic import OpenAILlmService
except ImportError as e:
print(
"[error] openai extra not installed. Install with: pip install -e .[openai]"
)
raise
from vanna import AgentConfig, Agent, User
from vanna.core.registry import ToolRegistry
from vanna.tools import ListFilesTool
# Default to 'gpt-5' for this demo; override via $OPENAI_MODEL if desired
model = os.getenv("OPENAI_MODEL", "gpt-5")
print(f"Using OpenAI model: {model}")
llm = OpenAILlmService(model=model)
# Create tool registry and register the list_files tool
tool_registry = ToolRegistry()
list_files_tool = ListFilesTool()
tool_registry.register(list_files_tool)
# Some models (e.g., reasoning/gpt-5) only support the default temperature=1.0
agent = Agent(
llm_service=llm,
config=AgentConfig(stream_responses=False, temperature=1.0),
tool_registry=tool_registry,
)
user = User(id="demo-user", username="demo")
conversation_id = "openai-demo"
print("Sending: 'List the files in the current directory'\n")
async for component in agent.send_message(
user=user,
message="List the files in the current directory",
conversation_id=conversation_id,
):
if hasattr(component, "content") and component.content:
print("Assistant:", component.content)
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/openai_quickstart.py",
"license": "MIT License",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/examples/primitive_components_demo.py | """
Demonstration of the new primitive component system.
This example shows how tools compose UI from primitive, domain-agnostic
components like StatusCardComponent, ProgressDisplayComponent, etc.
Usage:
PYTHONPATH=. python vanna/examples/primitive_components_demo.py
"""
import asyncio
import uuid
from datetime import datetime
from typing import AsyncGenerator, Optional
from vanna import (
AgentConfig,
Agent,
MemoryConversationStore,
MockLlmService,
User,
)
from vanna.core.components import UiComponent
from vanna.core.rich_components import (
StatusCardComponent,
ProgressDisplayComponent,
LogViewerComponent,
BadgeComponent,
IconTextComponent,
RichTextComponent,
)
class PrimitiveComponentsAgent(Agent):
"""Agent that demonstrates the new primitive component system."""
async def send_message(
self,
user: User,
message: str,
*,
conversation_id: Optional[str] = None,
) -> AsyncGenerator[UiComponent, None]:
"""Send message and demonstrate primitive component composition."""
session_id = str(uuid.uuid4())[:8]
# Demo 1: Tool execution using primitive components
yield UiComponent(
rich_component=RichTextComponent(
content="## Primitive Components Demo\n\nShowing how tools now compose UI from primitive components:",
markdown=True,
)
)
# Status card for overall operation
operation_status = StatusCardComponent(
id=f"operation-{session_id}",
title="Data Analysis Pipeline",
status="running",
description="Processing user data through multiple analysis stages",
icon="⚙️",
)
yield UiComponent(rich_component=operation_status)
# Progress display for overall progress
overall_progress = ProgressDisplayComponent(
id=f"progress-{session_id}",
label="Overall Progress",
value=0.0,
description="Starting analysis...",
animated=True,
)
yield UiComponent(rich_component=overall_progress)
# Log viewer for detailed output
log_viewer = LogViewerComponent(
id=f"logs-{session_id}",
title="Analysis Log",
entries=[],
show_timestamps=True,
auto_scroll=True,
)
yield UiComponent(rich_component=log_viewer)
# Simulate analysis stages
stages = [
("Data Loading", "📊", 0.2),
("Data Validation", "✅", 0.4),
("Statistical Analysis", "🧮", 0.6),
("Report Generation", "📄", 0.8),
("Finalization", "🎯", 1.0),
]
for i, (stage_name, stage_icon, progress_value) in enumerate(stages):
await asyncio.sleep(0.8)
# Update overall status
status = "success" if progress_value == 1.0 else "running"
yield UiComponent(
rich_component=operation_status.set_status(
status, f"Executing: {stage_name}"
)
)
# Update progress
yield UiComponent(
rich_component=overall_progress.update_progress(
progress_value, f"Executing {stage_name}..."
)
)
# Add log entry
yield UiComponent(
rich_component=log_viewer.add_entry(f"Starting {stage_name}", "info")
)
# Create a status card for this specific stage
stage_status = StatusCardComponent(
id=f"stage-{i}-{session_id}",
title=stage_name,
status="running" if progress_value < 1.0 else "success",
description=f"Processing stage {i + 1} of {len(stages)}",
icon=stage_icon,
)
yield UiComponent(rich_component=stage_status)
await asyncio.sleep(0.5)
# Complete the stage
final_stage_status = "success" if progress_value < 1.0 else "completed"
yield UiComponent(
rich_component=stage_status.set_status(
final_stage_status, f"{stage_name} completed successfully"
)
)
yield UiComponent(
rich_component=log_viewer.add_entry(f"Completed {stage_name}", "info")
)
# Demo 2: Badge and IconText primitives
yield UiComponent(
rich_component=RichTextComponent(
content="\n### Primitive Component Examples\n\nShowing individual primitive components:",
markdown=True,
)
)
# Various badge examples
badges = [
BadgeComponent(text="Processing", variant="primary", size="small"),
BadgeComponent(text="Complete", variant="success", size="medium"),
BadgeComponent(text="Warning", variant="warning", size="large", icon="⚠️"),
BadgeComponent(text="Error", variant="error", size="medium", icon="❌"),
]
for badge in badges:
yield UiComponent(rich_component=badge)
# IconText examples
icon_texts = [
IconTextComponent(
icon="📊",
text="Data Analysis Complete",
variant="primary",
size="large",
),
IconTextComponent(
icon="✅", text="All tests passed", variant="default", size="medium"
),
IconTextComponent(
icon="⏱️",
text="Processing time: 2.3s",
variant="secondary",
size="small",
),
]
for icon_text in icon_texts:
yield UiComponent(rich_component=icon_text)
# Demo 3: Comparison with old approach
yield UiComponent(
rich_component=RichTextComponent(
content=f"""
## Key Benefits of Primitive Components
**Primitive Component Approach:**
```python
# Tool composes UI from primitives
status_card = StatusCardComponent(
title="Data Analysis",
status="running", # Pure UI state
icon="📊"
)
progress = ProgressDisplayComponent(
label="Analysis Progress",
value=0.5
)
logs = LogViewerComponent(
title="Analysis Log",
entries=log_entries
)
```
### Benefits:
- **Separation of Concerns**: UI components are purely presentational
- **Reusability**: Status cards work for any process, not just tools
- **Composability**: Tools build exactly the UI they need
- **Maintainability**: Changes to business logic don't affect UI components
- **Extensibility**: New tools don't require new component types
Your message was: "{message}"
""",
markdown=True,
)
)
def create_primitive_demo_agent() -> PrimitiveComponentsAgent:
"""Create a primitive components demo agent.
Returns:
Configured PrimitiveComponentsAgent instance
"""
llm_service = MockLlmService(response_content="Primitive components demo response")
return PrimitiveComponentsAgent(
llm_service=llm_service,
config=AgentConfig(
stream_responses=True,
include_thinking_indicators=False,
),
)
async def main() -> None:
"""Run the primitive components demo."""
# Create agent
agent = create_primitive_demo_agent()
# Create a test user
user = User(
id="user123", username="demo_user", email="demo@example.com", permissions=[]
)
# Start a conversation
conversation_id = "primitive_demo_123"
user_message = "Show me how the new primitive component system works!"
print(f"User: {user_message}")
print("Agent response (primitive components):")
print("=" * 60)
# Send message and display components
component_count = 0
async for component in agent.send_message(
user=user, message=user_message, conversation_id=conversation_id
):
component_count += 1
component_type = getattr(component, "type", component.__class__.__name__)
component_id = getattr(component, "id", "N/A")
print(
f"[{component_count:2d}] {component_type.value if hasattr(component_type, 'value') else component_type} (id: {component_id[:12] if len(str(component_id)) > 12 else component_id})"
)
rich_comp = component.rich_component
# Show component details
if hasattr(rich_comp, "title"):
print(f" Title: {rich_comp.title}")
if hasattr(rich_comp, "status"):
print(f" Status: {rich_comp.status}")
if hasattr(rich_comp, "description") and rich_comp.description:
desc = (
rich_comp.description[:60] + "..."
if len(rich_comp.description) > 60
else rich_comp.description
)
print(f" Description: {desc}")
if (
hasattr(rich_comp, "value")
and hasattr(rich_comp.type, "value")
and rich_comp.type.value == "progress_display"
):
print(f" Progress: {rich_comp.value:.1%}")
print()
print("=" * 60)
print(f"Total components emitted: {component_count}")
print("\nThis demonstrates how tools can now compose rich UIs")
print("from primitive, reusable components without semantic coupling!")
def run_interactive() -> None:
"""Entry point for interactive usage."""
print("Starting Primitive Components Demo...")
asyncio.run(main())
if __name__ == "__main__":
run_interactive()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/primitive_components_demo.py",
"license": "MIT License",
"lines": 256,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/quota_lifecycle_example.py | """
Example demonstrating lifecycle hooks for user quota management.
This example shows how to use lifecycle hooks to add custom functionality
like quota management without creating custom agent runner subclasses.
"""
from typing import Any, Dict, Optional
from vanna.core import Agent, LifecycleHook, User
from vanna.core.errors import AgentError
class QuotaExceededError(AgentError):
"""Raised when a user exceeds their message quota."""
pass
class QuotaCheckHook(LifecycleHook):
"""Lifecycle hook that enforces user-based message quotas."""
def __init__(self, default_quota: int = 10) -> None:
"""Initialize quota hook.
Args:
default_quota: Default quota per user if not specifically set
"""
self._user_quotas: Dict[str, int] = {}
self._user_usage: Dict[str, int] = {}
self._default_quota = default_quota
def set_user_quota(self, user_id: str, quota: int) -> None:
"""Set a specific quota for a user."""
self._user_quotas[user_id] = quota
def get_user_quota(self, user_id: str) -> int:
"""Get the quota for a user."""
return self._user_quotas.get(user_id, self._default_quota)
def get_user_usage(self, user_id: str) -> int:
"""Get current usage count for a user."""
return self._user_usage.get(user_id, 0)
def get_user_remaining(self, user_id: str) -> int:
"""Get remaining messages for a user."""
return self.get_user_quota(user_id) - self.get_user_usage(user_id)
def reset_user_usage(self, user_id: str) -> None:
"""Reset usage count for a user."""
self._user_usage[user_id] = 0
async def before_message(self, user: User, message: str) -> Optional[str]:
"""Check quota before processing message.
Raises:
QuotaExceededError: If user has exceeded their quota
"""
usage = self.get_user_usage(user.id)
quota = self.get_user_quota(user.id)
if usage >= quota:
raise QuotaExceededError(
f"User {user.username} has exceeded their quota of {quota} messages. "
f"Current usage: {usage}"
)
# Increment usage count
current_usage = self._user_usage.get(user.id, 0)
self._user_usage[user.id] = current_usage + 1
# Don't modify the message
return None
class LoggingHook(LifecycleHook):
"""Example logging hook for demonstration."""
async def before_message(self, user: User, message: str) -> Optional[str]:
"""Log incoming messages."""
print(f"[LOG] User {user.username} ({user.id}) sent message: {message[:50]}...")
return None
async def after_message(self, result: Any) -> None:
"""Log message completion."""
print(f"[LOG] Message processing completed")
async def run_example() -> None:
"""
Example showing how to use lifecycle hooks with Agent.
Instead of creating a custom subclass, we compose
the behavior using lifecycle hooks.
"""
from vanna.core.registry import ToolRegistry
from vanna.integrations.anthropic import AnthropicLlmService
from vanna.integrations.local import MemoryConversationStore
# Create quota hook
quota_hook = QuotaCheckHook(default_quota=10)
quota_hook.set_user_quota("user123", 5) # Set custom quota for specific user
# Create logging hook
logging_hook = LoggingHook()
# Create agent with multiple hooks
agent = Agent(
llm_service=AnthropicLlmService(api_key="your-api-key"),
tool_registry=ToolRegistry(),
conversation_store=MemoryConversationStore(),
lifecycle_hooks=[
logging_hook, # Logs will happen first
quota_hook, # Then quota check
],
)
# Create a test user
user = User(
id="user123", username="test_user", email="test@example.com", permissions=[]
)
# Send messages - will track quota
try:
async for component in agent.send_message(user=user, message="Hello, agent!"):
# Process UI components
pass
# Check remaining quota
remaining = quota_hook.get_user_remaining(user.id)
print(f"Remaining messages: {remaining}/{quota_hook.get_user_quota(user.id)}")
except QuotaExceededError as e:
print(f"Quota exceeded: {e}")
if __name__ == "__main__":
import asyncio
asyncio.run(run_example())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/quota_lifecycle_example.py",
"license": "MIT License",
"lines": 103,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/examples/visualization_example.py | """
Example demonstrating SQL query execution with automatic visualization.
This example shows the integration of RunSqlTool and VisualizeDataTool,
demonstrating how SQL results are saved to CSV files and can be visualized
using the visualization tool with dependency injection.
Usage:
PYTHONPATH=. python vanna/examples/visualization_example.py
"""
import asyncio
import os
import sys
import uuid
from typing import AsyncGenerator, List, Optional
from vanna import (
AgentConfig,
Agent,
ToolRegistry,
User,
)
from vanna.core import LlmService
from vanna.core import (
LlmRequest,
LlmResponse,
LlmStreamChunk,
ToolCall,
ToolSchema,
)
from vanna.integrations.sqlite import SqliteRunner
from vanna.tools import (
RunSqlTool,
VisualizeDataTool,
LocalFileSystem,
)
class VisualizationDemoLlmService(LlmService):
"""Mock LLM that demonstrates SQL query and visualization workflow."""
def __init__(self) -> None:
self.step = 0
self.csv_filename: Optional[str] = None
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Handle non-streaming requests."""
await asyncio.sleep(0.1)
return self._build_response(request)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Handle streaming requests."""
await asyncio.sleep(0.1)
response = self._build_response(request)
if response.tool_calls:
yield LlmStreamChunk(tool_calls=response.tool_calls)
if response.content:
yield LlmStreamChunk(
content=response.content, finish_reason=response.finish_reason
)
else:
yield LlmStreamChunk(finish_reason=response.finish_reason)
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Validate tools - no errors."""
return []
def _build_response(self, request: LlmRequest) -> LlmResponse:
"""Build response based on conversation state."""
last_message = request.messages[-1] if request.messages else None
# If we got a tool result, process it
if last_message and last_message.role == "tool":
tool_result = last_message.content or ""
# Check if this was a SQL query result with a CSV file
if "Results saved to" in tool_result and ".csv" in tool_result:
# Extract filename from result
import re
match = re.search(r"'([^']*\.csv)'", tool_result)
if match:
self.csv_filename = match.group(1)
# Now visualize the data
return LlmResponse(
content=f"Great! I've saved the query results. Now let me create a visualization of the data.",
tool_calls=[
ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="visualize_data",
arguments={"filename": self.csv_filename},
)
],
finish_reason="tool_calls",
)
# If this was a visualization result, acknowledge it
if "Created visualization" in tool_result:
return LlmResponse(
content=f"Perfect! I've created a visualization of the data. {tool_result}",
finish_reason="stop",
)
# Default acknowledgment
return LlmResponse(
content=f"I've completed the operation. {tool_result}",
finish_reason="stop",
)
# Initial request - run SQL query
if self.step == 0:
self.step += 1
return LlmResponse(
content="I'll query the database for you and then create a visualization.",
tool_calls=[
ToolCall(
id=f"call_{uuid.uuid4().hex[:8]}",
name="run_sql",
arguments={
"sql": "SELECT Name, Milliseconds, Bytes FROM Track LIMIT 20"
},
)
],
finish_reason="tool_calls",
)
# Default response
return LlmResponse(
content="I can help you query databases and visualize the results.",
finish_reason="stop",
)
def create_demo_agent() -> Agent:
"""
Create a demo agent with SQL and visualization tools.
This function is called by the vanna server framework.
Returns:
Configured Agent with SQL and visualization tools
"""
# Check for Chinook database
database_path = os.path.join(
os.path.dirname(__file__), "..", "..", "Chinook.sqlite"
)
database_path = os.path.abspath(database_path)
if not os.path.exists(database_path):
raise FileNotFoundError(
f"Chinook database not found at {database_path}. "
"Please download it from https://vanna.ai/Chinook.sqlite"
)
# Create shared FileSystem for both tools
file_system = LocalFileSystem(working_directory="./data_storage")
# Create SQL tool with FileSystem
sqlite_runner = SqliteRunner(database_path=database_path)
sql_tool = RunSqlTool(sql_runner=sqlite_runner, file_system=file_system)
# Create visualization tool with same FileSystem
viz_tool = VisualizeDataTool(file_system=file_system)
# Create tool registry
tool_registry = ToolRegistry()
tool_registry.register(sql_tool)
tool_registry.register(viz_tool)
# Create LLM service
llm_service = VisualizationDemoLlmService()
# Create agent with streaming enabled for web interface
return Agent(
llm_service=llm_service,
tool_registry=tool_registry,
config=AgentConfig(
stream_responses=True,
include_thinking_indicators=False,
),
)
async def main() -> None:
"""Demonstrate SQL query execution with automatic visualization."""
print("🎨 SQL + Visualization Demo")
print("=" * 60)
print("This example demonstrates:")
print("1. Running SQL queries that save results to CSV files")
print("2. Automatically visualizing the CSV data")
print("3. User isolation for file storage")
print("=" * 60)
print()
# Create agent using factory function
agent = create_demo_agent()
# Create test user
user = User(id="demo-user", username="demo")
# Show available tools
tools = await agent.get_available_tools(user)
print(f"Available tools: {[tool.name for tool in tools]}")
print()
# Run conversation
conversation_id = "viz-demo"
print("User: Show me some track data and visualize it")
print()
async for component in agent.send_message(
user=user,
message="Show me some track data and visualize it",
conversation_id=conversation_id,
):
if (
component.simple_component
and hasattr(component.simple_component, "text")
and component.simple_component.text
):
print(f"Agent: {component.simple_component.text}")
elif component.simple_component and hasattr(component.simple_component, "text"):
print(f"Agent: {component.simple_component.text}")
elif hasattr(component.rich_component, "content"):
if isinstance(component.rich_component.content, dict):
# This is the chart
print(
f"Agent: [Chart Generated - Plotly figure with {len(str(component.rich_component.content))} chars]"
)
else:
print(f"Agent: {component.rich_component.content}")
print()
print("=" * 60)
print("Demo complete!")
print()
print("Key features demonstrated:")
print("✅ SQL queries save results to user-isolated CSV files")
print("✅ Visualization tool reads CSV files using FileSystem")
print("✅ Automatic chart type selection based on data shape")
print("✅ Dependency injection allows customization")
print()
if __name__ == "__main__":
asyncio.run(main())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/examples/visualization_example.py",
"license": "MIT License",
"lines": 210,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/anthropic/llm.py | """
Anthropic LLM service implementation.
Implements the LlmService interface using Anthropic's Messages API
(anthropic>=0.8.0). Supports non-streaming and streaming text output.
Tool-calls (tool_use blocks) are surfaced at the end of a stream or after a
non-streaming call as ToolCall entries.
"""
from __future__ import annotations
import logging
import os
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
from vanna.core.llm import (
LlmService,
LlmRequest,
LlmResponse,
LlmStreamChunk,
)
from vanna.core.tool import ToolCall, ToolSchema
class AnthropicLlmService(LlmService):
"""Anthropic Messages-backed LLM service.
Args:
model: Anthropic model name (e.g., "claude-sonnet-4-5", "claude-opus-4").
Defaults to "claude-sonnet-4-5". Can also be set via ANTHROPIC_MODEL env var.
api_key: API key; falls back to env `ANTHROPIC_API_KEY`.
base_url: Optional custom base URL; env `ANTHROPIC_BASE_URL` if unset.
extra_client_kwargs: Extra kwargs forwarded to `anthropic.Anthropic()`.
"""
def __init__(
self,
model: Optional[str] = None,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
**extra_client_kwargs: Any,
) -> None:
try:
import anthropic
except Exception as e: # pragma: no cover
raise ImportError(
"anthropic package is required. Install with: pip install 'vanna[anthropic]'"
) from e
# Model selection - use environment variable or default
self.model = model or os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-5")
api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
base_url = base_url or os.getenv("ANTHROPIC_BASE_URL")
client_kwargs: Dict[str, Any] = {**extra_client_kwargs}
if api_key:
client_kwargs["api_key"] = api_key
if base_url:
client_kwargs["base_url"] = base_url
self._client = anthropic.Anthropic(**client_kwargs)
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Send a non-streaming request to Anthropic and return the response."""
payload = self._build_payload(request)
resp = self._client.messages.create(**payload)
logger.info(f"Anthropic response: {resp}")
text_content, tool_calls = self._parse_message_content(resp)
usage: Dict[str, int] = {}
if getattr(resp, "usage", None):
try:
usage = {
"input_tokens": int(resp.usage.input_tokens),
"output_tokens": int(resp.usage.output_tokens),
}
except Exception:
pass
return LlmResponse(
content=text_content or None,
tool_calls=tool_calls or None,
finish_reason=getattr(resp, "stop_reason", None),
usage=usage or None,
)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Stream a request to Anthropic.
Yields text chunks as they arrive. Emits tool-calls at the end by
inspecting the final message.
"""
payload = self._build_payload(request)
logger.info(f"Anthropic streaming payload: {payload}")
# SDK provides a streaming context manager with a text_stream iterator.
with self._client.messages.stream(**payload) as stream:
for text in stream.text_stream:
if text:
yield LlmStreamChunk(content=text)
final = stream.get_final_message()
logger.info(f"Anthropic stream response: {final}")
_, tool_calls = self._parse_message_content(final)
if tool_calls:
yield LlmStreamChunk(
tool_calls=tool_calls,
finish_reason=getattr(final, "stop_reason", None),
)
else:
yield LlmStreamChunk(
finish_reason=getattr(final, "stop_reason", None) or "stop"
)
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Basic validation of tool schemas for Anthropic."""
errors: List[str] = []
for t in tools:
if not t.name:
errors.append("Tool name is required")
return errors
# Internal helpers
def _build_payload(self, request: LlmRequest) -> Dict[str, Any]:
# Anthropic requires messages content as list of content blocks per message
# We need to group consecutive tool messages into single user messages
messages: List[Dict[str, Any]] = []
i = 0
while i < len(request.messages):
m = request.messages[i]
if m.role == "tool":
# Group consecutive tool messages into one user message
tool_content_blocks = []
while i < len(request.messages) and request.messages[i].role == "tool":
tool_msg = request.messages[i]
if tool_msg.tool_call_id:
tool_content_blocks.append(
{
"type": "tool_result",
"tool_use_id": tool_msg.tool_call_id,
"content": tool_msg.content,
}
)
i += 1
if tool_content_blocks:
messages.append(
{
"role": "user",
"content": tool_content_blocks,
}
)
else:
# Handle non-tool messages normally
content_blocks = []
# Handle text content - only add if not empty
if m.content and m.content.strip():
content_blocks.append({"type": "text", "text": m.content})
# Handle tool_calls for assistant messages (convert to tool_use blocks)
if m.role == "assistant" and m.tool_calls:
for tc in m.tool_calls:
content_blocks.append(
{
"type": "tool_use",
"id": tc.id,
"name": tc.name,
"input": tc.arguments, # type: ignore[dict-item]
}
)
# Ensure we have at least one content block for text messages
if not content_blocks and m.role in {"user", "assistant"}:
content_blocks.append({"type": "text", "text": m.content or ""})
if content_blocks:
role = m.role if m.role in {"user", "assistant"} else "user"
messages.append(
{
"role": role,
"content": content_blocks,
}
)
i += 1
tools_payload: Optional[List[Dict[str, Any]]] = None
if request.tools:
tools_payload = [
{
"name": t.name,
"description": t.description,
"input_schema": t.parameters,
}
for t in request.tools
]
payload: Dict[str, Any] = {
"model": self.model,
"messages": messages,
# Anthropic requires max_tokens; default if not provided
"max_tokens": request.max_tokens if request.max_tokens is not None else 512,
"temperature": request.temperature,
}
if tools_payload:
payload["tools"] = tools_payload
payload["tool_choice"] = {"type": "auto"}
# Add system prompt if provided
if request.system_prompt:
payload["system"] = request.system_prompt
return payload
def _parse_message_content(self, msg: Any) -> Tuple[str, List[ToolCall]]:
text_parts: List[str] = []
tool_calls: List[ToolCall] = []
content_list = getattr(msg, "content", []) or []
for block in content_list:
btype = getattr(block, "type", None) or (
block.get("type") if isinstance(block, dict) else None
)
if btype == "text":
# SDK returns block.text for typed object; dict uses {"text": ...}
text = getattr(block, "text", None)
if text is None and isinstance(block, dict):
text = block.get("text")
if text:
text_parts.append(str(text))
elif btype == "tool_use":
# Tool call with name and input
name = getattr(block, "name", None) or (
block.get("name") if isinstance(block, dict) else None
)
tc_id = getattr(block, "id", None) or (
block.get("id") if isinstance(block, dict) else None
)
input_data = getattr(block, "input", None) or (
block.get("input") if isinstance(block, dict) else None
)
if name:
try:
# input_data should be a dict already
args = (
input_data
if isinstance(input_data, dict)
else {"_raw": input_data}
)
except Exception:
args = {"_raw": str(input_data)}
tool_calls.append(
ToolCall(
id=str(tc_id or "tool_call"), name=str(name), arguments=args
)
)
text_content = "".join(text_parts)
return text_content, tool_calls
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/anthropic/llm.py",
"license": "MIT License",
"lines": 230,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/azureopenai/llm.py | """
Azure OpenAI LLM service implementation.
Provides an `LlmService` backed by Azure OpenAI Chat Completions (openai>=1.0.0)
with support for streaming, deployment-scoped models, and Azure-specific
authentication flows.
"""
from __future__ import annotations
import json
import os
from typing import Any, AsyncGenerator, Dict, List, Optional, Set
from vanna.core.llm import (
LlmService,
LlmRequest,
LlmResponse,
LlmStreamChunk,
)
from vanna.core.tool import ToolCall, ToolSchema
# Models that don't support temperature and other sampling parameters
REASONING_MODELS: Set[str] = {
"o1",
"o1-mini",
"o1-preview",
"o3-mini",
"gpt-5",
"gpt-5-mini",
"gpt-5-nano",
"gpt-5-pro",
"gpt-5-codex",
}
def _is_reasoning_model(model: str) -> bool:
"""Return True when the deployment targets a reasoning-only model."""
model_lower = model.lower()
return any(reasoning_model in model_lower for reasoning_model in REASONING_MODELS)
class AzureOpenAILlmService(LlmService):
"""Azure OpenAI Chat Completions-backed LLM service.
Wraps `openai.AzureOpenAI` so Vanna can talk to deployment-scoped models
and either API key or Microsoft Entra ID authentication.
Args:
model: Deployment name in Azure OpenAI (required).
api_key: API key; falls back to `AZURE_OPENAI_API_KEY`.
azure_endpoint: Azure OpenAI endpoint URL; falls back to
`AZURE_OPENAI_ENDPOINT`.
api_version: API version; defaults to "2024-10-21" or
`AZURE_OPENAI_API_VERSION`.
azure_ad_token_provider: Optional bearer token provider for Entra ID.
**extra_client_kwargs: Additional keyword arguments forwarded to the
underlying client.
"""
def __init__(
self,
model: Optional[str] = None,
api_key: Optional[str] = None,
azure_endpoint: Optional[str] = None,
api_version: Optional[str] = None,
azure_ad_token_provider: Optional[Any] = None,
**extra_client_kwargs: Any,
) -> None:
try:
from openai import AzureOpenAI
except Exception as e: # pragma: no cover
raise ImportError(
"openai package is required. Install with: pip install 'vanna[azureopenai]' "
"or 'pip install openai'"
) from e
# Model/deployment name is required for Azure OpenAI
self.model = model or os.getenv("AZURE_OPENAI_MODEL")
if not self.model:
raise ValueError(
"model parameter (deployment name) is required for Azure OpenAI. "
"Provide it as argument or set AZURE_OPENAI_MODEL environment variable."
)
# Azure endpoint is required
azure_endpoint = azure_endpoint or os.getenv("AZURE_OPENAI_ENDPOINT")
if not azure_endpoint:
raise ValueError(
"azure_endpoint is required for Azure OpenAI. "
"Provide it as argument or set AZURE_OPENAI_ENDPOINT environment variable."
)
# API version - use latest stable GA version by default
api_version = api_version or os.getenv("AZURE_OPENAI_API_VERSION", "2024-10-21")
# Build client kwargs
client_kwargs: Dict[str, Any] = {
"azure_endpoint": azure_endpoint,
"api_version": api_version,
**extra_client_kwargs,
}
# Authentication: prefer Azure AD token provider, fallback to API key
if azure_ad_token_provider is not None:
client_kwargs["azure_ad_token_provider"] = azure_ad_token_provider
else:
api_key = api_key or os.getenv("AZURE_OPENAI_API_KEY")
if not api_key:
raise ValueError(
"Authentication required: provide either api_key or azure_ad_token_provider. "
"API key can also be set via AZURE_OPENAI_API_KEY environment variable."
)
client_kwargs["api_key"] = api_key
self._client = AzureOpenAI(**client_kwargs)
self._is_reasoning_model = _is_reasoning_model(self.model)
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Send a non-streaming request to Azure OpenAI and return the response."""
payload = self._build_payload(request)
# Call the API synchronously; this function is async but we can block here.
resp = self._client.chat.completions.create(**payload, stream=False)
if not resp.choices:
return LlmResponse(content=None, tool_calls=None, finish_reason=None)
choice = resp.choices[0]
content: Optional[str] = getattr(choice.message, "content", None)
tool_calls = self._extract_tool_calls_from_message(choice.message)
usage: Dict[str, int] = {}
if getattr(resp, "usage", None):
usage = {
k: int(v)
for k, v in {
"prompt_tokens": getattr(resp.usage, "prompt_tokens", 0),
"completion_tokens": getattr(resp.usage, "completion_tokens", 0),
"total_tokens": getattr(resp.usage, "total_tokens", 0),
}.items()
}
return LlmResponse(
content=content,
tool_calls=tool_calls or None,
finish_reason=getattr(choice, "finish_reason", None),
usage=usage or None,
)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""
Stream a request to Azure OpenAI.
Emits `LlmStreamChunk` for textual deltas as they arrive. Tool-calls are
accumulated and emitted in a final chunk when the stream ends.
"""
payload = self._build_payload(request)
# Synchronous streaming iterator; iterate within async context.
stream = self._client.chat.completions.create(**payload, stream=True)
# Builders for streamed tool-calls (index -> partial)
tc_builders: Dict[int, Dict[str, Optional[str]]] = {}
last_finish: Optional[str] = None
for event in stream:
if not getattr(event, "choices", None):
continue
choice = event.choices[0]
delta = getattr(choice, "delta", None)
if delta is None:
# Some SDK versions use `event.choices[0].message` on the final packet
last_finish = getattr(choice, "finish_reason", last_finish)
continue
# Text content
content_piece: Optional[str] = getattr(delta, "content", None)
if content_piece:
yield LlmStreamChunk(content=content_piece)
# Tool calls (streamed)
streamed_tool_calls = getattr(delta, "tool_calls", None)
if streamed_tool_calls:
for tc in streamed_tool_calls:
idx = getattr(tc, "index", 0) or 0
b = tc_builders.setdefault(
idx, {"id": None, "name": None, "arguments": ""}
)
if getattr(tc, "id", None):
b["id"] = tc.id
fn = getattr(tc, "function", None)
if fn is not None:
if getattr(fn, "name", None):
b["name"] = fn.name
if getattr(fn, "arguments", None):
b["arguments"] = (b["arguments"] or "") + fn.arguments
last_finish = getattr(choice, "finish_reason", last_finish)
# Emit final tool-calls chunk if any
final_tool_calls: List[ToolCall] = []
for b in tc_builders.values():
if not b.get("name"):
continue
args_raw = b.get("arguments") or "{}"
try:
loaded = json.loads(args_raw)
if isinstance(loaded, dict):
args_dict: Dict[str, Any] = loaded
else:
args_dict = {"args": loaded}
except Exception:
args_dict = {"_raw": args_raw}
final_tool_calls.append(
ToolCall(
id=b.get("id") or "tool_call",
name=b["name"] or "tool",
arguments=args_dict,
)
)
if final_tool_calls:
yield LlmStreamChunk(tool_calls=final_tool_calls, finish_reason=last_finish)
else:
# Still emit a terminal chunk to signal completion
yield LlmStreamChunk(finish_reason=last_finish or "stop")
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Validate tool schemas. Returns a list of error messages."""
errors: List[str] = []
# Basic checks; Azure OpenAI will enforce further validation server-side.
for t in tools:
if not t.name or len(t.name) > 64:
errors.append(f"Invalid tool name: {t.name!r}")
return errors
# Internal helpers
def _build_payload(self, request: LlmRequest) -> Dict[str, Any]:
"""Build the API payload from LlmRequest."""
messages: List[Dict[str, Any]] = []
# Add system prompt as first message if provided
if request.system_prompt:
messages.append({"role": "system", "content": request.system_prompt})
for m in request.messages:
msg: Dict[str, Any] = {"role": m.role, "content": m.content}
if m.role == "tool" and m.tool_call_id:
msg["tool_call_id"] = m.tool_call_id
elif m.role == "assistant" and m.tool_calls:
# Convert tool calls to OpenAI format
tool_calls_payload = []
for tc in m.tool_calls:
tool_calls_payload.append(
{
"id": tc.id,
"type": "function",
"function": {
"name": tc.name,
"arguments": json.dumps(tc.arguments),
},
}
)
msg["tool_calls"] = tool_calls_payload
messages.append(msg)
tools_payload: Optional[List[Dict[str, Any]]] = None
if request.tools:
tools_payload = [
{
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.parameters,
},
}
for t in request.tools
]
payload: Dict[str, Any] = {
"model": self.model,
"messages": messages,
}
# Add temperature only for non-reasoning models
# Reasoning models (GPT-5, o1, o3-mini) don't support temperature parameter
if not self._is_reasoning_model:
payload["temperature"] = request.temperature
if request.max_tokens is not None:
payload["max_tokens"] = request.max_tokens
if tools_payload:
payload["tools"] = tools_payload
payload["tool_choice"] = "auto"
return payload
def _extract_tool_calls_from_message(self, message: Any) -> List[ToolCall]:
"""Extract tool calls from OpenAI message object."""
tool_calls: List[ToolCall] = []
raw_tool_calls = getattr(message, "tool_calls", None) or []
for tc in raw_tool_calls:
fn = getattr(tc, "function", None)
if not fn:
continue
args_raw = getattr(fn, "arguments", "{}")
try:
loaded = json.loads(args_raw)
if isinstance(loaded, dict):
args_dict: Dict[str, Any] = loaded
else:
args_dict = {"args": loaded}
except Exception:
args_dict = {"_raw": args_raw}
tool_calls.append(
ToolCall(
id=getattr(tc, "id", "tool_call"),
name=getattr(fn, "name", "tool"),
arguments=args_dict,
)
)
return tool_calls
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/azureopenai/llm.py",
"license": "MIT License",
"lines": 282,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/azuresearch/agent_memory.py | """
Azure AI Search implementation of AgentMemory.
This implementation uses Azure Cognitive Search for vector storage of tool usage patterns.
"""
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
from azure.search.documents import SearchClient
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
SearchIndex,
SearchField,
SearchFieldDataType,
VectorSearch,
VectorSearchAlgorithmConfiguration,
)
from azure.core.credentials import AzureKeyCredential
AZURE_SEARCH_AVAILABLE = True
except ImportError:
AZURE_SEARCH_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class AzureAISearchAgentMemory(AgentMemory):
"""Azure AI Search-based implementation of AgentMemory."""
def __init__(
self,
endpoint: str,
api_key: str,
index_name: str = "tool-memories",
dimension: int = 384,
):
if not AZURE_SEARCH_AVAILABLE:
raise ImportError(
"Azure Search is required for AzureAISearchAgentMemory. "
"Install with: pip install azure-search-documents"
)
self.endpoint = endpoint
self.api_key = api_key
self.index_name = index_name
self.dimension = dimension
self._credential = AzureKeyCredential(api_key)
self._search_client = None
self._index_client = None
self._executor = ThreadPoolExecutor(max_workers=2)
def _get_index_client(self):
"""Get or create index client."""
if self._index_client is None:
self._index_client = SearchIndexClient(
endpoint=self.endpoint, credential=self._credential
)
self._ensure_index_exists()
return self._index_client
def _get_search_client(self):
"""Get or create search client."""
if self._search_client is None:
self._get_index_client() # Ensure index exists
self._search_client = SearchClient(
endpoint=self.endpoint,
index_name=self.index_name,
credential=self._credential,
)
return self._search_client
def _ensure_index_exists(self):
"""Create index if it doesn't exist."""
try:
self._index_client.get_index(self.index_name)
except Exception:
# Create index with vector search configuration
fields = [
SearchField(
name="memory_id", type=SearchFieldDataType.String, key=True
),
SearchField(
name="question", type=SearchFieldDataType.String, searchable=True
),
SearchField(
name="tool_name", type=SearchFieldDataType.String, filterable=True
),
SearchField(name="args_json", type=SearchFieldDataType.String),
SearchField(
name="timestamp",
type=SearchFieldDataType.String,
sortable=True,
filterable=True,
),
SearchField(
name="success", type=SearchFieldDataType.Boolean, filterable=True
),
SearchField(name="metadata_json", type=SearchFieldDataType.String),
SearchField(
name="embedding",
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
searchable=True,
vector_search_dimensions=self.dimension,
vector_search_configuration="vector-config",
),
]
vector_search = VectorSearch(
algorithm_configurations=[
VectorSearchAlgorithmConfiguration(name="vector-config")
]
)
index = SearchIndex(
name=self.index_name, fields=fields, vector_search=vector_search
)
self._index_client.create_index(index)
def _create_embedding(self, text: str) -> List[float]:
"""Create a simple embedding from text (placeholder)."""
import hashlib
hash_val = int(hashlib.md5(text.encode()).hexdigest(), 16)
return [(hash_val >> i) % 100 / 100.0 for i in range(self.dimension)]
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
client = self._get_search_client()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(question)
document = {
"memory_id": memory_id,
"question": question,
"tool_name": tool_name,
"args_json": json.dumps(args),
"timestamp": timestamp,
"success": success,
"metadata_json": json.dumps(metadata or {}),
"embedding": embedding,
}
client.upload_documents(documents=[document])
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
client = self._get_search_client()
embedding = self._create_embedding(question)
# Build filter
filter_expr = "success eq true"
if tool_name_filter:
filter_expr += f" and tool_name eq '{tool_name_filter}'"
results = client.search(
search_text=None, vector=embedding, top_k=limit, filter=filter_expr
)
search_results = []
for i, doc in enumerate(results):
# Azure returns similarity score in @search.score
similarity_score = doc.get("@search.score", 0)
if similarity_score >= similarity_threshold:
args = json.loads(doc.get("args_json", "{}"))
metadata_dict = json.loads(doc.get("metadata_json", "{}"))
memory = ToolMemory(
memory_id=doc["memory_id"],
question=doc["question"],
tool_name=doc["tool_name"],
args=args,
timestamp=doc.get("timestamp"),
success=doc.get("success", True),
metadata=metadata_dict,
)
search_results.append(
ToolMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories."""
def _get_recent():
client = self._get_search_client()
results = client.search(
search_text="*", top=limit, order_by=["timestamp desc"]
)
memories = []
for doc in results:
args = json.loads(doc.get("args_json", "{}"))
metadata_dict = json.loads(doc.get("metadata_json", "{}"))
memory = ToolMemory(
memory_id=doc["memory_id"],
question=doc["question"],
tool_name=doc["tool_name"],
args=args,
timestamp=doc.get("timestamp"),
success=doc.get("success", True),
metadata=metadata_dict,
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID."""
def _delete():
client = self._get_search_client()
try:
client.delete_documents(documents=[{"memory_id": memory_id}])
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
client = self._get_search_client()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(content)
document = {
"memory_id": memory_id,
"content": content,
"timestamp": timestamp,
"embedding": embedding,
}
client.upload_documents(documents=[document])
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
client = self._get_search_client()
embedding = self._create_embedding(query)
results = client.search(search_text=None, vector=embedding, top_k=limit)
search_results = []
for i, doc in enumerate(results):
similarity_score = doc.get("@search.score", 0)
if similarity_score >= similarity_threshold:
memory = TextMemory(
memory_id=doc["memory_id"],
content=doc.get("content", ""),
timestamp=doc.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
client = self._get_search_client()
results = client.search(
search_text="*", top=limit, order_by=["timestamp desc"]
)
memories = []
for doc in results:
# Skip if this is a tool memory (has tool_name field)
if "tool_name" in doc:
continue
memory = TextMemory(
memory_id=doc["memory_id"],
content=doc.get("content", ""),
timestamp=doc.get("timestamp"),
)
memories.append(memory)
return memories[:limit]
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
client = self._get_search_client()
try:
client.delete_documents(documents=[{"memory_id": memory_id}])
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
client = self._get_search_client()
# Build filter
filter_parts = []
if tool_name:
filter_parts.append(f"tool_name eq '{tool_name}'")
if before_date:
filter_parts.append(f"timestamp lt '{before_date}'")
filter_expr = " and ".join(filter_parts) if filter_parts else None
# Search for documents to delete
results = client.search(
search_text="*", filter=filter_expr, select=["memory_id"]
)
docs_to_delete = [{"memory_id": doc["memory_id"]} for doc in results]
if docs_to_delete:
client.delete_documents(documents=docs_to_delete)
return len(docs_to_delete)
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/azuresearch/agent_memory.py",
"license": "MIT License",
"lines": 332,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/bigquery/sql_runner.py | """BigQuery implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class BigQueryRunner(SqlRunner):
"""BigQuery implementation of the SqlRunner interface."""
def __init__(self, project_id: str, cred_file_path: Optional[str] = None, **kwargs):
"""Initialize with BigQuery connection parameters.
Args:
project_id: Google Cloud Project ID
cred_file_path: Path to Google Cloud credentials JSON file (optional)
**kwargs: Additional google.cloud.bigquery.Client parameters
"""
try:
from google.cloud import bigquery
from google.oauth2 import service_account
self.bigquery = bigquery
self.service_account = service_account
except ImportError as e:
raise ImportError(
"google-cloud-bigquery package is required. "
"Install with: pip install 'vanna[bigquery]'"
) from e
self.project_id = project_id
self.cred_file_path = cred_file_path
self.kwargs = kwargs
self._client = None
def _get_client(self):
"""Get or create BigQuery client."""
if self._client is not None:
return self._client
if self.cred_file_path:
import json
with open(self.cred_file_path, "r") as f:
credentials = (
self.service_account.Credentials.from_service_account_info(
json.loads(f.read()),
scopes=["https://www.googleapis.com/auth/cloud-platform"],
)
)
self._client = self.bigquery.Client(
project=self.project_id, credentials=credentials, **self.kwargs
)
else:
# Use default credentials
self._client = self.bigquery.Client(project=self.project_id, **self.kwargs)
return self._client
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against BigQuery database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
google.api_core.exceptions.GoogleAPIError: If query execution fails
"""
client = self._get_client()
# Execute the query
job = client.query(args.sql)
df = job.result().to_dataframe()
return df
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/bigquery/sql_runner.py",
"license": "MIT License",
"lines": 63,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/chromadb/agent_memory.py | """
Local vector database implementation of AgentMemory.
This implementation uses ChromaDB for local vector storage of tool usage patterns.
"""
import json
import hashlib
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
import chromadb
from chromadb.config import Settings
from chromadb.utils import embedding_functions
try:
from chromadb.errors import NotFoundError
except ImportError:
# Fallback for older ChromaDB versions that don't have chromadb.errors
class NotFoundError(Exception):
"""Fallback NotFoundError for older ChromaDB versions."""
pass
CHROMADB_AVAILABLE = True
except ImportError:
CHROMADB_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class ChromaAgentMemory(AgentMemory):
"""ChromaDB-based implementation of AgentMemory.
This implementation uses ChromaDB's PersistentClient to store agent memories
on disk, ensuring they persist across application restarts.
Key Features:
- Persistent storage: All memories are automatically saved to disk
- Efficient retrieval: Existing collections are loaded without re-initializing
embedding functions, avoiding unnecessary model downloads
- Flexible embedding: Supports custom embedding functions or uses ChromaDB's
default embedding function
Args:
persist_directory: Directory where ChromaDB will store its data.
Defaults to "./chroma_memory". Use an absolute path
for production deployments to ensure consistent location
across restarts.
collection_name: Name of the ChromaDB collection to use. Multiple agents
can share the same persist_directory with different
collection names.
embedding_function: Optional custom embedding function. If not provided,
ChromaDB's DefaultEmbeddingFunction is used (requires
internet connection on first use to download the model).
Once a collection is created, subsequent application
restarts will retrieve the existing collection without
re-downloading the model.
Example:
>>> from vanna.integrations.chromadb import ChromaAgentMemory
>>> # Basic usage with defaults
>>> memory = ChromaAgentMemory(
... persist_directory="/app/data/chroma",
... collection_name="my_agent_memory"
... )
>>>
>>> # With custom embedding function (e.g., for offline use)
>>> from chromadb.utils import embedding_functions
>>> ef = embedding_functions.SentenceTransformerEmbeddingFunction()
>>> memory = ChromaAgentMemory(
... persist_directory="/app/data/chroma",
... embedding_function=ef
... )
Note:
The default embedding function downloads an ONNX model (~80MB) on first use.
For air-gapped or offline environments, pre-download the model or provide
a custom embedding function.
Limitation:
This class does not validate that an existing Chroma collection was created
with the same embedding function as the one configured for the current
``ChromaAgentMemory`` instance. If you reuse a collection (same
``persist_directory`` and ``collection_name``) with a different embedding
function than was originally used, queries may fail or produce incorrect
similarity results. It is your responsibility to ensure that a given
collection is always accessed with a consistent embedding function, or to
implement your own validation around collection creation and reuse.
"""
def __init__(
self,
persist_directory: str = "./chroma_memory",
collection_name: str = "tool_memories",
embedding_function=None,
):
if not CHROMADB_AVAILABLE:
raise ImportError(
"ChromaDB is required for ChromaAgentMemory. Install with: pip install chromadb"
)
self.persist_directory = persist_directory
self.collection_name = collection_name
self._client = None
self._collection = None
self._executor = ThreadPoolExecutor(max_workers=2)
self._embedding_function = embedding_function
def _get_client(self):
"""Get or create ChromaDB client."""
if self._client is None:
self._client = chromadb.PersistentClient(
path=self.persist_directory,
settings=Settings(anonymized_telemetry=False, allow_reset=True),
)
return self._client
def _get_embedding_function(self):
"""Get or create the embedding function.
If no embedding function was provided during initialization,
uses ChromaDB's default embedding function.
"""
if self._embedding_function is None:
# Use ChromaDB's default embedding function
# This avoids requiring sentence-transformers as a hard dependency
self._embedding_function = embedding_functions.DefaultEmbeddingFunction()
return self._embedding_function
def _get_collection(self):
"""Get or create ChromaDB collection."""
if self._collection is None:
client = self._get_client()
try:
# Try to get existing collection first
# Don't pass embedding_function here to avoid re-instantiating/downloading it
# For existing collections, ChromaDB uses the stored embedding function configuration
self._collection = client.get_collection(name=self.collection_name)
except NotFoundError:
# Collection doesn't exist, create it with embedding function
embedding_func = self._get_embedding_function()
self._collection = client.create_collection(
name=self.collection_name,
embedding_function=embedding_func,
metadata={"description": "Tool usage memories for learning"},
)
return self._collection
def _create_memory_id(self) -> str:
"""Create a unique ID for a memory."""
import uuid
return str(uuid.uuid4())
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
collection = self._get_collection()
memory_id = self._create_memory_id()
timestamp = datetime.now().isoformat()
# ChromaDB only accepts primitive types in metadata
# Serialize complex objects to JSON strings
memory_data = {
"question": question,
"tool_name": tool_name,
"args_json": json.dumps(args), # Serialize to JSON string
"timestamp": timestamp,
"success": success,
"metadata_json": json.dumps(metadata or {}), # Serialize metadata too
}
# Use question as document text for embedding
collection.upsert(
ids=[memory_id], documents=[question], metadatas=[memory_data]
)
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
collection = self._get_collection()
# Prepare where filter - ChromaDB requires $and for multiple conditions
if tool_name_filter:
where_filter = {
"$and": [{"success": True}, {"tool_name": tool_name_filter}]
}
else:
where_filter = {"success": True}
results = collection.query(
query_texts=[question], n_results=limit, where=where_filter
)
search_results = []
if results["ids"] and len(results["ids"][0]) > 0:
for i, (id_, distance, metadata) in enumerate(
zip(
results["ids"][0],
results["distances"][0],
results["metadatas"][0],
)
):
# Convert distance to similarity score (ChromaDB uses L2 distance)
similarity_score = max(0, 1 - distance)
if similarity_score >= similarity_threshold:
# Deserialize JSON fields
args = json.loads(metadata.get("args_json", "{}"))
metadata_dict = json.loads(metadata.get("metadata_json", "{}"))
# Use the ChromaDB document ID as the memory ID
memory = ToolMemory(
memory_id=id_,
question=metadata["question"],
tool_name=metadata["tool_name"],
args=args,
timestamp=metadata.get("timestamp"),
success=metadata.get("success", True),
metadata=metadata_dict,
)
search_results.append(
ToolMemorySearchResult(
memory=memory,
similarity_score=similarity_score,
rank=i + 1,
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories. Returns most recent memories first."""
def _get_recent():
collection = self._get_collection()
# Get all memories and sort by timestamp
results = collection.get()
if not results["metadatas"] or not results["ids"]:
return []
# Parse and sort by timestamp
memories_with_time = []
for i, (doc_id, metadata) in enumerate(
zip(results["ids"], results["metadatas"])
):
# Skip text memories - they have is_text_memory flag
if metadata.get("is_text_memory"):
continue
args = json.loads(metadata.get("args_json", "{}"))
metadata_dict = json.loads(metadata.get("metadata_json", "{}"))
# Use the ChromaDB document ID as the memory ID
memory = ToolMemory(
memory_id=doc_id,
question=metadata["question"],
tool_name=metadata["tool_name"],
args=args,
timestamp=metadata.get("timestamp"),
success=metadata.get("success", True),
metadata=metadata_dict,
)
memories_with_time.append((memory, metadata.get("timestamp", "")))
# Sort by timestamp descending (most recent first)
memories_with_time.sort(key=lambda x: x[1], reverse=True)
# Return only the memory objects, limited to the requested amount
return [m[0] for m in memories_with_time[:limit]]
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID. Returns True if deleted, False if not found."""
def _delete():
collection = self._get_collection()
# Check if the ID exists
try:
results = collection.get(ids=[memory_id])
if results["ids"] and len(results["ids"]) > 0:
collection.delete(ids=[memory_id])
return True
return False
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
collection = self._get_collection()
memory_id = self._create_memory_id()
timestamp = datetime.now().isoformat()
memory_data = {
"content": content,
"timestamp": timestamp,
"is_text_memory": True,
}
collection.upsert(
ids=[memory_id], documents=[content], metadatas=[memory_data]
)
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
collection = self._get_collection()
where_filter = {"is_text_memory": True}
results = collection.query(
query_texts=[query], n_results=limit, where=where_filter
)
search_results = []
if results["ids"] and len(results["ids"][0]) > 0:
for i, (id_, distance, metadata) in enumerate(
zip(
results["ids"][0],
results["distances"][0],
results["metadatas"][0],
)
):
similarity_score = max(0, 1 - distance)
if similarity_score >= similarity_threshold:
memory = TextMemory(
memory_id=id_,
content=metadata.get("content", ""),
timestamp=metadata.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory,
similarity_score=similarity_score,
rank=i + 1,
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
collection = self._get_collection()
results = collection.get(where={"is_text_memory": True})
if not results["metadatas"] or not results["ids"]:
return []
memories_with_time = []
for doc_id, metadata in zip(results["ids"], results["metadatas"]):
memory = TextMemory(
memory_id=doc_id,
content=metadata.get("content", ""),
timestamp=metadata.get("timestamp"),
)
memories_with_time.append((memory, metadata.get("timestamp", "")))
memories_with_time.sort(key=lambda x: x[1], reverse=True)
return [m[0] for m in memories_with_time[:limit]]
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
collection = self._get_collection()
try:
results = collection.get(ids=[memory_id])
if results["ids"] and len(results["ids"]) > 0:
collection.delete(ids=[memory_id])
return True
return False
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
collection = self._get_collection()
# Build where filter
where_filter = {}
if tool_name:
where_filter["tool_name"] = tool_name
# Get memories to delete
results = collection.get(where=where_filter if where_filter else None)
if not results["ids"]:
return 0
ids_to_delete = []
for i, metadata in enumerate(results["metadatas"]):
if before_date:
memory_date = metadata.get("timestamp", "")
if memory_date and memory_date < before_date:
ids_to_delete.append(results["ids"][i])
else:
ids_to_delete.append(results["ids"][i])
if ids_to_delete:
collection.delete(ids=ids_to_delete)
return len(ids_to_delete)
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/chromadb/agent_memory.py",
"license": "MIT License",
"lines": 398,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/clickhouse/sql_runner.py | """ClickHouse implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class ClickHouseRunner(SqlRunner):
"""ClickHouse implementation of the SqlRunner interface."""
def __init__(
self,
host: str,
database: str,
user: str,
password: str,
port: int = 8123,
**kwargs,
):
"""Initialize with ClickHouse connection parameters.
Args:
host: Database host address
database: Database name
user: Database user
password: Database password
port: Database port (default: 8123)
**kwargs: Additional clickhouse_connect connection parameters
"""
try:
import clickhouse_connect
self.clickhouse_connect = clickhouse_connect
except ImportError as e:
raise ImportError(
"clickhouse-connect package is required. "
"Install with: pip install 'vanna[clickhouse]'"
) from e
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self.kwargs = kwargs
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against ClickHouse database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
Exception: If query execution fails
"""
# Connect to the database
client = self.clickhouse_connect.get_client(
host=self.host,
port=self.port,
username=self.user,
password=self.password,
database=self.database,
**self.kwargs,
)
try:
# Execute the query
result = client.query(args.sql)
results = result.result_rows
# Create a pandas dataframe from the results
df = pd.DataFrame(results, columns=result.column_names)
return df
finally:
client.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/clickhouse/sql_runner.py",
"license": "MIT License",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/duckdb/sql_runner.py | """DuckDB implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class DuckDBRunner(SqlRunner):
"""DuckDB implementation of the SqlRunner interface."""
def __init__(
self, database_path: str = ":memory:", init_sql: Optional[str] = None, **kwargs
):
"""Initialize with DuckDB connection parameters.
Args:
database_path: Path to the DuckDB database file.
Use ":memory:" for in-memory database (default).
Use "md:" or "motherduck:" for MotherDuck database.
init_sql: Optional SQL to run when connecting to the database
**kwargs: Additional duckdb connection parameters
"""
try:
import duckdb
self.duckdb = duckdb
except ImportError as e:
raise ImportError(
"duckdb package is required. Install with: pip install 'vanna[duckdb]'"
) from e
self.database_path = database_path
self.init_sql = init_sql
self.kwargs = kwargs
self._conn = None
def _get_connection(self):
"""Get or create DuckDB connection."""
if self._conn is None:
self._conn = self.duckdb.connect(self.database_path, **self.kwargs)
if self.init_sql:
self._conn.query(self.init_sql)
return self._conn
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against DuckDB database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
duckdb.Error: If query execution fails
"""
conn = self._get_connection()
# Execute the query and convert to DataFrame
df = conn.query(args.sql).to_df()
return df
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/duckdb/sql_runner.py",
"license": "MIT License",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/faiss/agent_memory.py | """
FAISS vector database implementation of AgentMemory.
This implementation uses FAISS for local vector storage of tool usage patterns.
"""
import json
import uuid
import pickle
import os
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
import numpy as np
try:
import faiss
FAISS_AVAILABLE = True
except ImportError:
FAISS_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class FAISSAgentMemory(AgentMemory):
"""FAISS-based implementation of AgentMemory."""
def __init__(
self,
index_path: Optional[str] = None,
persist_path: Optional[str] = None,
dimension: int = 384,
metric: str = "cosine",
):
if not FAISS_AVAILABLE:
raise ImportError(
"FAISS is required for FAISSAgentMemory. Install with: pip install faiss-cpu"
)
# Accept either index_path or persist_path for backward compatibility
self.index_path = persist_path or index_path or "./faiss_index"
self.dimension = dimension
self.metric = metric
self._index = None
self._metadata = {}
self._executor = ThreadPoolExecutor(max_workers=2)
self._load_index()
def _load_index(self):
"""Load or create FAISS index."""
index_file = os.path.join(self.index_path, "index.faiss")
metadata_file = os.path.join(self.index_path, "metadata.pkl")
if os.path.exists(index_file) and os.path.exists(metadata_file):
# Load existing index
self._index = faiss.read_index(index_file)
with open(metadata_file, "rb") as f:
self._metadata = pickle.load(f)
else:
# Create new index
os.makedirs(self.index_path, exist_ok=True)
if self.metric == "cosine":
self._index = faiss.IndexFlatIP(self.dimension)
else:
self._index = faiss.IndexFlatL2(self.dimension)
self._metadata = {}
def _save_index(self):
"""Save FAISS index to disk."""
index_file = os.path.join(self.index_path, "index.faiss")
metadata_file = os.path.join(self.index_path, "metadata.pkl")
faiss.write_index(self._index, index_file)
with open(metadata_file, "wb") as f:
pickle.dump(self._metadata, f)
def _create_embedding(self, text: str) -> np.ndarray:
"""Create a simple embedding from text (placeholder)."""
import hashlib
hash_val = int(hashlib.md5(text.encode()).hexdigest(), 16)
embedding = np.array(
[(hash_val >> i) % 100 / 100.0 for i in range(self.dimension)],
dtype=np.float32,
)
# Normalize for cosine similarity
if self.metric == "cosine":
norm = np.linalg.norm(embedding)
if norm > 0:
embedding = embedding / norm
return embedding
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(question)
# Add to FAISS index
self._index.add(np.array([embedding]))
# Store metadata
idx = self._index.ntotal - 1
self._metadata[idx] = {
"memory_id": memory_id,
"question": question,
"tool_name": tool_name,
"args": args,
"timestamp": timestamp,
"success": success,
"metadata": metadata or {},
}
self._save_index()
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
embedding = self._create_embedding(question)
# Search in FAISS
k = min(limit * 3, self._index.ntotal) if self._index.ntotal > 0 else 1
if k == 0:
return []
distances, indices = self._index.search(np.array([embedding]), k)
search_results = []
rank = 1
for i, (dist, idx) in enumerate(zip(distances[0], indices[0])):
if idx == -1 or idx not in self._metadata:
continue
metadata = self._metadata[idx]
# Filter by success
if not metadata.get("success", True):
continue
# Filter by tool name
if tool_name_filter and metadata.get("tool_name") != tool_name_filter:
continue
# Convert distance to similarity score
if self.metric == "cosine":
similarity_score = float(dist)
else:
similarity_score = 1.0 / (1.0 + float(dist))
if similarity_score >= similarity_threshold:
memory = ToolMemory(
memory_id=metadata["memory_id"],
question=metadata["question"],
tool_name=metadata["tool_name"],
args=metadata["args"],
timestamp=metadata.get("timestamp"),
success=metadata.get("success", True),
metadata=metadata.get("metadata", {}),
)
search_results.append(
ToolMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=rank
)
)
rank += 1
if len(search_results) >= limit:
break
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories."""
def _get_recent():
# Get all metadata entries and sort by timestamp
all_entries = list(self._metadata.values())
sorted_entries = sorted(
all_entries, key=lambda m: m.get("timestamp", ""), reverse=True
)
memories = []
for entry in sorted_entries[:limit]:
# Skip text memories - they have is_text_memory flag
if entry.get("is_text_memory"):
continue
memory = ToolMemory(
memory_id=entry["memory_id"],
question=entry["question"],
tool_name=entry["tool_name"],
args=entry["args"],
timestamp=entry.get("timestamp"),
success=entry.get("success", True),
metadata=entry.get("metadata", {}),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID."""
def _delete():
# Find and remove from metadata
idx_to_remove = None
for idx, metadata in self._metadata.items():
if metadata["memory_id"] == memory_id:
idx_to_remove = idx
break
if idx_to_remove is not None:
del self._metadata[idx_to_remove]
self._save_index()
return True
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(content)
# Add to FAISS index
self._index.add(np.array([embedding]))
# Store metadata
idx = self._index.ntotal - 1
self._metadata[idx] = {
"memory_id": memory_id,
"content": content,
"timestamp": timestamp,
"is_text_memory": True,
}
self._save_index()
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
embedding = self._create_embedding(query)
k = min(limit * 3, self._index.ntotal) if self._index.ntotal > 0 else 1
if k == 0:
return []
distances, indices = self._index.search(np.array([embedding]), k)
search_results = []
rank = 1
for dist, idx in zip(distances[0], indices[0]):
if idx == -1 or idx not in self._metadata:
continue
metadata = self._metadata[idx]
# Filter for text memories only
if not metadata.get("is_text_memory", False):
continue
# Convert distance to similarity score
if self.metric == "cosine":
similarity_score = float(dist)
else:
similarity_score = 1.0 / (1.0 + float(dist))
if similarity_score >= similarity_threshold:
memory = TextMemory(
memory_id=metadata["memory_id"],
content=metadata["content"],
timestamp=metadata.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=rank
)
)
rank += 1
if len(search_results) >= limit:
break
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
# Get all text memory entries and sort by timestamp
text_entries = [
entry
for entry in self._metadata.values()
if entry.get("is_text_memory", False)
]
sorted_entries = sorted(
text_entries, key=lambda m: m.get("timestamp", ""), reverse=True
)
memories = []
for entry in sorted_entries[:limit]:
memory = TextMemory(
memory_id=entry["memory_id"],
content=entry["content"],
timestamp=entry.get("timestamp"),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
# Find and remove from metadata
idx_to_remove = None
for idx, metadata in self._metadata.items():
if metadata["memory_id"] == memory_id:
idx_to_remove = idx
break
if idx_to_remove is not None:
del self._metadata[idx_to_remove]
self._save_index()
return True
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
indices_to_remove = []
for idx, metadata in self._metadata.items():
should_remove = True
if tool_name and metadata.get("tool_name") != tool_name:
should_remove = False
if before_date and metadata.get("timestamp", "") >= before_date:
should_remove = False
if should_remove:
indices_to_remove.append(idx)
# Remove from metadata
for idx in indices_to_remove:
del self._metadata[idx]
# If clearing all, recreate index
if not tool_name and not before_date:
if self.metric == "cosine":
self._index = faiss.IndexFlatIP(self.dimension)
else:
self._index = faiss.IndexFlatL2(self.dimension)
self._metadata = {}
self._save_index()
return len(indices_to_remove)
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/faiss/agent_memory.py",
"license": "MIT License",
"lines": 347,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/google/gemini.py | """
Google Gemini LLM service implementation.
Implements the LlmService interface using Google's Gen AI SDK
(google-genai). Supports non-streaming and streaming text output,
as well as function calling (tool use).
"""
from __future__ import annotations
import json
import logging
import os
from typing import Any, AsyncGenerator, Dict, List, Optional
logger = logging.getLogger(__name__)
from vanna.core.llm import (
LlmService,
LlmRequest,
LlmResponse,
LlmStreamChunk,
)
from vanna.core.tool import ToolCall, ToolSchema
class GeminiLlmService(LlmService):
"""Google Gemini-backed LLM service.
Args:
model: Gemini model name (e.g., "gemini-2.5-pro", "gemini-2.5-flash").
Defaults to "gemini-2.5-pro". Can also be set via GEMINI_MODEL env var.
api_key: API key; falls back to env `GOOGLE_API_KEY` or `GEMINI_API_KEY`.
GOOGLE_API_KEY takes precedence if both are set.
temperature: Temperature for generation (0.0-2.0). Default 0.7.
extra_config: Extra kwargs forwarded to GenerateContentConfig.
"""
def __init__(
self,
model: Optional[str] = None,
api_key: Optional[str] = None,
temperature: float = 0.7,
**extra_config: Any,
) -> None:
try:
from google import genai
from google.genai import types
except Exception as e: # pragma: no cover
raise ImportError(
"google-genai package is required. "
"Install with: pip install 'vanna[gemini]'"
) from e
self.model_name = model or os.getenv("GEMINI_MODEL", "gemini-2.5-pro")
# Check GOOGLE_API_KEY first (takes precedence), then GEMINI_API_KEY
api_key = api_key or os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY")
if not api_key:
raise ValueError(
"Google API key is required. Set GOOGLE_API_KEY or GEMINI_API_KEY "
"environment variable, or pass api_key parameter."
)
# Store modules for use in methods
self._genai = genai
self._types = types
# Create client
self._client = genai.Client(api_key=api_key)
# Store generation config
self.temperature = temperature
self.extra_config = extra_config
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Send a non-streaming request to Gemini and return the response."""
contents, config = self._build_payload(request)
try:
# Generate content
response = self._client.models.generate_content(
model=self.model_name,
contents=contents,
config=config,
)
logger.info(f"Gemini response: {response}")
# Parse response
text_content, tool_calls = self._parse_response(response)
# Extract usage information
usage: Dict[str, int] = {}
if hasattr(response, "usage_metadata"):
try:
usage = {
"prompt_tokens": int(
response.usage_metadata.prompt_token_count
),
"completion_tokens": int(
response.usage_metadata.candidates_token_count
),
"total_tokens": int(response.usage_metadata.total_token_count),
}
except Exception:
pass
# Get finish reason
finish_reason = None
if response.candidates:
finish_reason = str(response.candidates[0].finish_reason).lower()
return LlmResponse(
content=text_content or None,
tool_calls=tool_calls or None,
finish_reason=finish_reason,
usage=usage or None,
)
except Exception as e:
logger.error(f"Error calling Gemini API: {e}")
raise
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Stream a request to Gemini.
Yields text chunks as they arrive. Emits tool calls at the end.
"""
contents, config = self._build_payload(request)
logger.info(f"Gemini streaming request with model: {self.model_name}")
try:
# Stream content
stream = self._client.models.generate_content_stream(
model=self.model_name,
contents=contents,
config=config,
)
# Accumulate chunks for tool calls
accumulated_chunks = []
for chunk in stream:
accumulated_chunks.append(chunk)
# Yield text content as it arrives
if hasattr(chunk, "text") and chunk.text:
yield LlmStreamChunk(content=chunk.text)
# After stream completes, check for tool calls in accumulated response
if accumulated_chunks:
final_chunk = accumulated_chunks[-1]
_, tool_calls = self._parse_response_chunk(final_chunk)
finish_reason = None
if final_chunk.candidates:
finish_reason = str(final_chunk.candidates[0].finish_reason).lower()
if tool_calls:
yield LlmStreamChunk(
tool_calls=tool_calls,
finish_reason=finish_reason,
)
else:
yield LlmStreamChunk(finish_reason=finish_reason or "stop")
except Exception as e:
logger.error(f"Error streaming from Gemini API: {e}")
raise
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Basic validation of tool schemas for Gemini."""
errors: List[str] = []
for t in tools:
if not t.name:
errors.append("Tool name is required")
if not t.description:
errors.append(f"Tool {t.name}: description is required")
return errors
# Internal helpers
def _build_payload(self, request: LlmRequest) -> tuple[List[Any], Any]:
"""Build the payload for Gemini API.
Returns:
Tuple of (contents, config)
"""
# Build contents (messages) for Gemini
contents = []
# System prompt handling - Gemini supports system instructions in config
system_instruction = None
if request.system_prompt:
system_instruction = request.system_prompt
for m in request.messages:
# Map roles: user -> user, assistant -> model, tool -> function
if m.role == "user":
contents.append(
self._types.Content(
role="user", parts=[self._types.Part(text=m.content)]
)
)
elif m.role == "assistant":
parts = []
# Add text content if present
if m.content and m.content.strip():
parts.append(self._types.Part(text=m.content))
# Add tool calls if present
if m.tool_calls:
for tc in m.tool_calls:
parts.append(
self._types.Part(
function_call=self._types.FunctionCall(
name=tc.name, args=tc.arguments
)
)
)
if parts:
contents.append(self._types.Content(role="model", parts=parts))
elif m.role == "tool":
# Tool results in Gemini format
if m.tool_call_id:
# Parse the content as JSON if possible
try:
response_content = json.loads(m.content)
except (json.JSONDecodeError, TypeError):
response_content = {"result": m.content}
# Extract function name from tool_call_id or use a default
function_name = m.tool_call_id.replace("call_", "")
contents.append(
self._types.Content(
role="function",
parts=[
self._types.Part(
function_response=self._types.FunctionResponse(
name=function_name, response=response_content
)
)
],
)
)
# Build tools configuration if tools are provided
tools = None
if request.tools:
function_declarations = []
for tool in request.tools:
# Clean schema to remove unsupported fields
cleaned_parameters = self._clean_schema_for_gemini(tool.parameters)
function_declarations.append(
{
"name": tool.name,
"description": tool.description,
"parameters": cleaned_parameters,
}
)
if function_declarations:
tools = [self._types.Tool(function_declarations=function_declarations)]
# Build generation config
config_dict = {
"temperature": request.temperature,
**self.extra_config,
}
if request.max_tokens is not None:
config_dict["max_output_tokens"] = request.max_tokens
if tools:
config_dict["tools"] = tools
if system_instruction:
config_dict["system_instruction"] = system_instruction
config = self._types.GenerateContentConfig(**config_dict)
return contents, config
def _parse_response(self, response: Any) -> tuple[str, List[ToolCall]]:
"""Parse a Gemini response into text and tool calls."""
text_parts: List[str] = []
tool_calls: List[ToolCall] = []
if not response.candidates:
return "", []
candidate = response.candidates[0]
if (
hasattr(candidate, "content")
and candidate.content
and hasattr(candidate.content, "parts")
and candidate.content.parts
):
for part in candidate.content.parts:
# Check for text content
if hasattr(part, "text") and part.text:
text_parts.append(part.text)
# Check for function calls
if hasattr(part, "function_call") and part.function_call:
fc = part.function_call
# Convert function call to ToolCall
tool_calls.append(
ToolCall(
id=f"call_{fc.name}", # Generate an ID
name=fc.name,
arguments=dict(fc.args) if hasattr(fc, "args") else {},
)
)
text_content = "".join(text_parts)
return text_content, tool_calls
def _parse_response_chunk(self, chunk: Any) -> tuple[str, List[ToolCall]]:
"""Parse a streaming chunk (same logic as _parse_response)."""
return self._parse_response(chunk)
def _clean_schema_for_gemini(self, schema: Dict[str, Any]) -> Dict[str, Any]:
"""Clean JSON Schema to only include fields supported by Gemini.
Gemini only supports a subset of OpenAPI schema. This removes unsupported
fields like 'title', 'default', '$schema', etc.
Supported fields:
- type, description, enum
- properties, required, items (for objects/arrays)
"""
if not isinstance(schema, dict):
return schema
# Fields that Gemini supports
allowed_fields = {
"type",
"description",
"enum",
"properties",
"required",
"items",
"format",
}
cleaned = {}
for key, value in schema.items():
if key in allowed_fields:
# Recursively clean nested schemas
if key == "properties" and isinstance(value, dict):
cleaned[key] = {
prop_name: self._clean_schema_for_gemini(prop_schema)
for prop_name, prop_schema in value.items()
}
elif key == "items" and isinstance(value, dict):
cleaned[key] = self._clean_schema_for_gemini(value)
else:
cleaned[key] = value
return cleaned
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/google/gemini.py",
"license": "MIT License",
"lines": 304,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/hive/sql_runner.py | """Hive implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class HiveRunner(SqlRunner):
"""Hive implementation of the SqlRunner interface."""
def __init__(
self,
host: str,
database: str = "default",
user: Optional[str] = None,
password: Optional[str] = None,
port: int = 10000,
auth: str = "CUSTOM",
**kwargs,
):
"""Initialize with Hive connection parameters.
Args:
host: The host of the Hive database
database: The name of the database to connect to (default: 'default')
user: The username to use for authentication
password: The password to use for authentication
port: The port to use for the connection (default: 10000)
auth: The authentication method to use (default: 'CUSTOM')
**kwargs: Additional pyhive connection parameters
"""
try:
from pyhive import hive
self.hive = hive
except ImportError as e:
raise ImportError(
"pyhive package is required. Install with: pip install pyhive"
) from e
self.host = host
self.database = database
self.user = user
self.password = password
self.port = port
self.auth = auth
self.kwargs = kwargs
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against Hive database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
hive.Error: If query execution fails
"""
# Connect to the database
conn = self.hive.Connection(
host=self.host,
username=self.user,
password=self.password,
database=self.database,
port=self.port,
auth=self.auth,
**self.kwargs,
)
try:
cursor = conn.cursor()
cursor.execute(args.sql)
results = cursor.fetchall()
# Create a pandas dataframe from the results
df = pd.DataFrame(results, columns=[desc[0] for desc in cursor.description])
cursor.close()
return df
finally:
conn.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/hive/sql_runner.py",
"license": "MIT License",
"lines": 71,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/local/agent_memory/in_memory.py | """
Demo in-memory implementation of AgentMemory.
This implementation provides a zero-dependency, minimal storage solution that
keeps all memories in RAM. It uses simple similarity algorithms (Jaccard and
difflib) instead of vector embeddings. Perfect for demos and testing.
"""
from __future__ import annotations
import asyncio
import difflib
import time
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class DemoAgentMemory(AgentMemory):
"""
Minimal, dependency-free in-memory storage for demos and testing.
- O(n) search over an in-memory list
- Simple similarity: max(Jaccard(token sets), difflib ratio)
- Optional FIFO eviction via max_items
- Async-safe with an asyncio.Lock
"""
def __init__(self, *, max_items: int = 10_000):
"""
Initialize the in-memory storage.
Args:
max_items: Maximum number of memories to keep. Oldest memories are
evicted when this limit is reached (FIFO).
"""
self._memories: List[ToolMemory] = []
self._text_memories: List[TextMemory] = []
self._lock = asyncio.Lock()
self._max_items = max_items
@staticmethod
def _now_iso() -> str:
"""Get current timestamp in ISO format."""
return datetime.now().isoformat()
@staticmethod
def _normalize(text: str) -> str:
"""Normalize text by lowercasing and collapsing whitespace."""
return " ".join(text.lower().split())
@staticmethod
def _tokenize(text: str) -> set[str]:
"""Simple tokenizer that splits on whitespace."""
return set(text.lower().split())
@classmethod
def _similarity(cls, a: str, b: str) -> float:
"""
Calculate similarity between two strings using multiple methods.
Returns the maximum of Jaccard similarity and difflib ratio.
"""
a_norm, b_norm = cls._normalize(a), cls._normalize(b)
# Jaccard over whitespace tokens
ta, tb = cls._tokenize(a_norm), cls._tokenize(b_norm)
if not ta and not tb:
jaccard = 1.0
elif not ta or not tb:
jaccard = 0.0
else:
jaccard = len(ta & tb) / max(1, len(ta | tb))
# difflib ratio
ratio = difflib.SequenceMatcher(None, a_norm, b_norm).ratio()
# Take the better of the two cheap measures
return max(jaccard, ratio)
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern for future reference."""
tm = ToolMemory(
memory_id=str(uuid.uuid4()),
question=question,
tool_name=tool_name,
args=args,
timestamp=self._now_iso(),
success=success,
metadata=metadata or {},
)
async with self._lock:
self._memories.append(tm)
# Optional FIFO eviction
if len(self._memories) > self._max_items:
overflow = len(self._memories) - self._max_items
del self._memories[:overflow]
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Store a text memory in RAM."""
tm = TextMemory(
memory_id=str(uuid.uuid4()), content=content, timestamp=self._now_iso()
)
async with self._lock:
self._text_memories.append(tm)
if len(self._text_memories) > self._max_items:
overflow = len(self._text_memories) - self._max_items
del self._text_memories[:overflow]
return tm
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns based on a question."""
q = self._normalize(question)
async with self._lock:
# Filter candidates by tool name and success status
candidates = [
m
for m in self._memories
if m.success
and (tool_name_filter is None or m.tool_name == tool_name_filter)
]
# Score each candidate by question similarity
results: List[tuple[ToolMemory, float]] = []
for m in candidates:
score = self._similarity(q, m.question)
results.append((m, min(score, 1.0)))
# Filter by threshold and sort by score
results = [(m, s) for (m, s) in results if s >= similarity_threshold]
results.sort(key=lambda x: x[1], reverse=True)
# Build ranked response
out: List[ToolMemorySearchResult] = []
for idx, (m, s) in enumerate(results[:limit], start=1):
out.append(
ToolMemorySearchResult(memory=m, similarity_score=s, rank=idx)
)
return out
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search free-form text memories using the demo similarity metric."""
normalized_query = self._normalize(query)
async with self._lock:
scored: List[tuple[TextMemory, float]] = []
for memory in self._text_memories:
score = self._similarity(normalized_query, memory.content)
scored.append((memory, min(score, 1.0)))
scored = [
(memory, score)
for memory, score in scored
if score >= similarity_threshold
]
scored.sort(key=lambda item: item[1], reverse=True)
results: List[TextMemorySearchResult] = []
for idx, (memory, score) in enumerate(scored[:limit], start=1):
results.append(
TextMemorySearchResult(
memory=memory, similarity_score=score, rank=idx
)
)
return results
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories. Returns most recent memories first."""
async with self._lock:
# Return memories in reverse order (most recent first)
return list(reversed(self._memories[-limit:]))
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Return recently added text memories."""
async with self._lock:
return list(reversed(self._text_memories[-limit:]))
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a stored text memory by ID."""
async with self._lock:
for index, memory in enumerate(self._text_memories):
if memory.memory_id == memory_id:
del self._text_memories[index]
return True
return False
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID. Returns True if deleted, False if not found."""
async with self._lock:
for i, m in enumerate(self._memories):
if m.memory_id == memory_id:
del self._memories[i]
return True
return False
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories. Returns number of memories deleted."""
async with self._lock:
original_tool_count = len(self._memories)
original_text_count = len(self._text_memories)
# Filter memories to keep
kept_memories = []
for m in self._memories:
should_delete = True
# Check tool name filter
if tool_name and m.tool_name != tool_name:
should_delete = False
# Check date filter
if should_delete and before_date and m.timestamp:
if m.timestamp >= before_date:
should_delete = False
# If no filters specified, delete all
if tool_name is None and before_date is None:
should_delete = True
# Keep if should not delete
if not should_delete:
kept_memories.append(m)
self._memories = kept_memories
deleted_tool_count = original_tool_count - len(self._memories)
# Apply filters to text memories (tool filter ignored)
kept_text_memories = []
for memory in self._text_memories:
should_delete = (
tool_name is None
) # only delete text when not targeting a tool
if before_date and memory.timestamp:
if memory.timestamp >= before_date:
should_delete = False
if not should_delete:
kept_text_memories.append(memory)
self._text_memories = kept_text_memories
deleted_text_count = original_text_count - len(self._text_memories)
return deleted_tool_count + deleted_text_count
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/local/agent_memory/in_memory.py",
"license": "MIT License",
"lines": 242,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/local/audit.py | """
Local audit logger implementation using Python logging.
This module provides a simple audit logger that writes events using
the standard Python logging module, useful for development and testing.
"""
import json
import logging
from typing import Optional
from vanna.core.audit import AuditEvent, AuditLogger
logger = logging.getLogger(__name__)
class LoggingAuditLogger(AuditLogger):
"""Audit logger that writes events to Python logger as structured JSON.
This implementation uses logger.info() to emit audit events as JSON,
making them easy to parse and route to log aggregation systems.
Example:
audit_logger = LoggingAuditLogger()
agent = Agent(
llm_service=...,
audit_logger=audit_logger
)
"""
def __init__(self, log_level: int = logging.INFO):
"""Initialize the logging audit logger.
Args:
log_level: Log level to use for audit events (default: INFO)
"""
self.log_level = log_level
async def log_event(self, event: AuditEvent) -> None:
"""Log an audit event as structured JSON.
Args:
event: The audit event to log
"""
try:
# Convert event to dict for JSON serialization
event_dict = event.model_dump(mode="json", exclude_none=True)
# Format as single-line JSON for easy parsing
event_json = json.dumps(event_dict, separators=(",", ":"))
# Log with structured prefix for easy filtering
logger.log(
self.log_level,
f"[AUDIT] {event.event_type.value} | {event_json}",
)
except Exception as e:
# Don't fail the operation if audit logging fails
logger.error(f"Failed to log audit event: {e}", exc_info=True)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/local/audit.py",
"license": "MIT License",
"lines": 45,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
vanna-ai/vanna:src/vanna/integrations/local/file_system.py | """
Local file system implementation.
This module provides a local file system implementation with per-user isolation.
"""
import asyncio
import hashlib
from pathlib import Path
from typing import List, Optional
from vanna.capabilities.file_system import CommandResult, FileSearchMatch, FileSystem
from vanna.core.tool import ToolContext
MAX_SEARCH_FILE_BYTES = 1_000_000
class LocalFileSystem(FileSystem):
"""Local file system implementation with per-user isolation."""
def __init__(self, working_directory: str = "."):
"""Initialize with a working directory.
Args:
working_directory: Base directory where user-specific folders will be created
"""
self.working_directory = Path(working_directory)
def _get_user_directory(self, context: ToolContext) -> Path:
"""Get the user-specific directory by hashing the user ID.
Args:
context: Tool context containing user information
Returns:
Path to the user-specific directory
"""
# Hash the user ID to create a directory name
user_hash = hashlib.sha256(context.user.id.encode()).hexdigest()[:16]
user_dir = self.working_directory / user_hash
# Create the directory if it doesn't exist
user_dir.mkdir(parents=True, exist_ok=True)
return user_dir
def _resolve_path(self, path: str, context: ToolContext) -> Path:
"""Resolve a path relative to the user's directory.
Args:
path: Path relative to user directory
context: Tool context containing user information
Returns:
Absolute path within user's directory
"""
user_dir = self._get_user_directory(context)
resolved = user_dir / path
# Ensure the path is within the user's directory (prevent directory traversal)
try:
resolved.resolve().relative_to(user_dir.resolve())
except ValueError:
raise PermissionError(
f"Access denied: path '{path}' is outside user directory"
)
return resolved
async def list_files(self, directory: str, context: ToolContext) -> List[str]:
"""List files in a directory within the user's isolated space."""
directory_path = self._resolve_path(directory, context)
if not directory_path.exists():
raise FileNotFoundError(f"Directory '{directory}' does not exist")
if not directory_path.is_dir():
raise NotADirectoryError(f"'{directory}' is not a directory")
files = []
for item in directory_path.iterdir():
if item.is_file():
files.append(item.name)
return sorted(files)
async def read_file(self, filename: str, context: ToolContext) -> str:
"""Read the contents of a file within the user's isolated space."""
file_path = self._resolve_path(filename, context)
if not file_path.exists():
raise FileNotFoundError(f"File '{filename}' does not exist")
if not file_path.is_file():
raise IsADirectoryError(f"'{filename}' is a directory, not a file")
return file_path.read_text(encoding="utf-8")
async def write_file(
self, filename: str, content: str, context: ToolContext, overwrite: bool = False
) -> None:
"""Write content to a file within the user's isolated space."""
file_path = self._resolve_path(filename, context)
# Create parent directories if they don't exist
file_path.parent.mkdir(parents=True, exist_ok=True)
if file_path.exists() and not overwrite:
raise FileExistsError(
f"File '{filename}' already exists. Use overwrite=True to replace it."
)
file_path.write_text(content, encoding="utf-8")
async def exists(self, path: str, context: ToolContext) -> bool:
"""Check if a file or directory exists within the user's isolated space."""
try:
resolved_path = self._resolve_path(path, context)
return resolved_path.exists()
except PermissionError:
return False
async def is_directory(self, path: str, context: ToolContext) -> bool:
"""Check if a path is a directory within the user's isolated space."""
try:
resolved_path = self._resolve_path(path, context)
return resolved_path.exists() and resolved_path.is_dir()
except PermissionError:
return False
async def search_files(
self,
query: str,
context: ToolContext,
*,
max_results: int = 20,
include_content: bool = False,
) -> List[FileSearchMatch]:
"""Search for files within the user's isolated space."""
trimmed_query = query.strip()
if not trimmed_query:
raise ValueError("Search query must not be empty")
user_dir = self._get_user_directory(context)
matches: List[FileSearchMatch] = []
query_lower = trimmed_query.lower()
for path in user_dir.rglob("*"):
if len(matches) >= max_results:
break
if not path.is_file():
continue
relative_path = path.relative_to(user_dir).as_posix()
include_entry = False
snippet: Optional[str] = None
if query_lower in path.name.lower():
include_entry = True
snippet = "[filename match]"
content: Optional[str] = None
if include_content:
try:
size = path.stat().st_size
except OSError:
if include_entry:
matches.append(
FileSearchMatch(path=relative_path, snippet=snippet)
)
continue
if size <= MAX_SEARCH_FILE_BYTES:
try:
content = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
content = None
elif not include_entry:
# Skip oversized files if they do not match by name
continue
if include_content and content is not None:
if query_lower in content.lower():
# Create snippet
lowered = content.lower()
index = lowered.find(query_lower)
if index != -1:
context_window = 60
start = max(0, index - context_window)
end = min(len(content), index + len(query) + context_window)
snippet = content[start:end].replace("\n", " ").strip()
if start > 0:
snippet = f"…{snippet}"
if end < len(content):
snippet = f"{snippet}…"
include_entry = True
elif not include_entry:
continue
if include_entry:
matches.append(FileSearchMatch(path=relative_path, snippet=snippet))
return matches
async def run_bash(
self,
command: str,
context: ToolContext,
*,
timeout: Optional[float] = None,
) -> CommandResult:
"""Execute a bash command within the user's isolated space."""
if not command.strip():
raise ValueError("Command must not be empty")
user_dir = self._get_user_directory(context)
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=str(user_dir),
)
try:
stdout_bytes, stderr_bytes = await asyncio.wait_for(
process.communicate(), timeout=timeout
)
except asyncio.TimeoutError as exc:
process.kill()
await process.wait()
raise TimeoutError(f"Command timed out after {timeout} seconds") from exc
stdout = stdout_bytes.decode("utf-8", errors="replace")
stderr = stderr_bytes.decode("utf-8", errors="replace")
return CommandResult(
stdout=stdout, stderr=stderr, returncode=process.returncode or 0
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/local/file_system.py",
"license": "MIT License",
"lines": 190,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/local/file_system_conversation_store.py | """
File system conversation store implementation.
This module provides a file-based implementation of the ConversationStore
interface that persists conversations to disk as a directory structure.
"""
import json
import os
from pathlib import Path
from typing import Dict, List, Optional
from datetime import datetime
import time
from vanna.core.storage import ConversationStore, Conversation, Message
from vanna.core.user import User
class FileSystemConversationStore(ConversationStore):
"""File system-based conversation store.
Stores conversations as directories with individual message files:
conversations/{conversation_id}/
metadata.json - conversation metadata (id, user info, timestamps)
messages/
{timestamp}_{index}.json - individual message files
"""
def __init__(self, base_dir: str = "conversations") -> None:
"""Initialize the file system conversation store.
Args:
base_dir: Base directory for storing conversations
"""
self.base_dir = Path(base_dir)
self.base_dir.mkdir(parents=True, exist_ok=True)
def _get_conversation_dir(self, conversation_id: str) -> Path:
"""Get the directory path for a conversation."""
return self.base_dir / conversation_id
def _get_metadata_path(self, conversation_id: str) -> Path:
"""Get the metadata file path for a conversation."""
return self._get_conversation_dir(conversation_id) / "metadata.json"
def _get_messages_dir(self, conversation_id: str) -> Path:
"""Get the messages directory for a conversation."""
return self._get_conversation_dir(conversation_id) / "messages"
def _save_metadata(self, conversation: Conversation) -> None:
"""Save conversation metadata to disk."""
conv_dir = self._get_conversation_dir(conversation.id)
conv_dir.mkdir(parents=True, exist_ok=True)
metadata = {
"id": conversation.id,
"user": conversation.user.model_dump(mode="json"),
"created_at": conversation.created_at.isoformat(),
"updated_at": conversation.updated_at.isoformat(),
}
metadata_path = self._get_metadata_path(conversation.id)
with open(metadata_path, "w") as f:
json.dump(metadata, f, indent=2)
def _load_messages(self, conversation_id: str) -> List[Message]:
"""Load all messages for a conversation."""
messages_dir = self._get_messages_dir(conversation_id)
if not messages_dir.exists():
return []
messages = []
# Sort message files by name (timestamp_index ensures correct order)
message_files = sorted(messages_dir.glob("*.json"))
for file_path in message_files:
try:
with open(file_path, "r") as f:
data = json.load(f)
message = Message.model_validate(data)
messages.append(message)
except (json.JSONDecodeError, ValueError) as e:
print(f"Failed to load message from {file_path}: {e}")
continue
return messages
def _append_message(
self, conversation_id: str, message: Message, index: int
) -> None:
"""Append a message to the conversation."""
messages_dir = self._get_messages_dir(conversation_id)
messages_dir.mkdir(parents=True, exist_ok=True)
# Use timestamp + index to ensure unique, ordered filenames
timestamp = int(time.time() * 1000000) # microseconds
filename = f"{timestamp}_{index:06d}.json"
file_path = messages_dir / filename
with open(file_path, "w") as f:
json.dump(message.model_dump(mode="json"), f, indent=2)
async def create_conversation(
self, conversation_id: str, user: User, initial_message: str
) -> Conversation:
"""Create a new conversation with the specified ID."""
conversation = Conversation(
id=conversation_id,
user=user,
messages=[Message(role="user", content=initial_message)],
)
# Save metadata
self._save_metadata(conversation)
# Save initial message
self._append_message(conversation_id, conversation.messages[0], 0)
return conversation
async def get_conversation(
self, conversation_id: str, user: User
) -> Optional[Conversation]:
"""Get conversation by ID, scoped to user."""
metadata_path = self._get_metadata_path(conversation_id)
if not metadata_path.exists():
return None
try:
# Load metadata
with open(metadata_path, "r") as f:
metadata = json.load(f)
# Verify ownership
if metadata["user"]["id"] != user.id:
return None
# Load all messages
messages = self._load_messages(conversation_id)
# Reconstruct conversation
conversation = Conversation(
id=metadata["id"],
user=User.model_validate(metadata["user"]),
messages=messages,
created_at=datetime.fromisoformat(metadata["created_at"]),
updated_at=datetime.fromisoformat(metadata["updated_at"]),
)
return conversation
except (json.JSONDecodeError, ValueError, KeyError) as e:
print(f"Failed to load conversation {conversation_id}: {e}")
return None
async def update_conversation(self, conversation: Conversation) -> None:
"""Update conversation with new messages."""
# Update the updated_at timestamp
conversation.updated_at = datetime.now()
# Save updated metadata
self._save_metadata(conversation)
# Get existing messages count to determine new message indices
existing_messages = self._load_messages(conversation.id)
existing_count = len(existing_messages)
# Only append new messages (ones not already saved)
for i, message in enumerate(
conversation.messages[existing_count:], start=existing_count
):
self._append_message(conversation.id, message, i)
async def delete_conversation(self, conversation_id: str, user: User) -> bool:
"""Delete conversation."""
conv_dir = self._get_conversation_dir(conversation_id)
if not conv_dir.exists():
return False
# Verify ownership before deleting
conversation = await self.get_conversation(conversation_id, user)
if not conversation:
return False
try:
# Delete all message files
messages_dir = self._get_messages_dir(conversation_id)
if messages_dir.exists():
for file_path in messages_dir.glob("*.json"):
file_path.unlink()
messages_dir.rmdir()
# Delete metadata
metadata_path = self._get_metadata_path(conversation_id)
if metadata_path.exists():
metadata_path.unlink()
# Delete conversation directory
conv_dir.rmdir()
return True
except OSError as e:
print(f"Failed to delete conversation {conversation_id}: {e}")
return False
async def list_conversations(
self, user: User, limit: int = 50, offset: int = 0
) -> List[Conversation]:
"""List conversations for user."""
if not self.base_dir.exists():
return []
conversations = []
# Iterate through all conversation directories
for conv_dir in self.base_dir.iterdir():
if not conv_dir.is_dir():
continue
metadata_path = conv_dir / "metadata.json"
if not metadata_path.exists():
continue
try:
# Load metadata
with open(metadata_path, "r") as f:
metadata = json.load(f)
# Skip conversations not owned by this user
if metadata["user"]["id"] != user.id:
continue
# Load messages
messages = self._load_messages(conv_dir.name)
# Reconstruct conversation
conversation = Conversation(
id=metadata["id"],
user=User.model_validate(metadata["user"]),
messages=messages,
created_at=datetime.fromisoformat(metadata["created_at"]),
updated_at=datetime.fromisoformat(metadata["updated_at"]),
)
conversations.append(conversation)
except (json.JSONDecodeError, ValueError, KeyError) as e:
print(f"Failed to load conversation from {conv_dir}: {e}")
continue
# Sort by updated_at desc
conversations.sort(key=lambda x: x.updated_at, reverse=True)
# Apply pagination
return conversations[offset : offset + limit]
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/local/file_system_conversation_store.py",
"license": "MIT License",
"lines": 201,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/local/storage.py | """
In-memory conversation store implementation.
This module provides a simple in-memory implementation of the ConversationStore
interface, useful for testing and development.
"""
from typing import Dict, List, Optional
from vanna.core.storage import ConversationStore, Conversation, Message
from vanna.core.user import User
class MemoryConversationStore(ConversationStore):
"""In-memory conversation store."""
def __init__(self) -> None:
self._conversations: Dict[str, Conversation] = {}
async def create_conversation(
self, conversation_id: str, user: User, initial_message: str
) -> Conversation:
"""Create a new conversation with the specified ID."""
conversation = Conversation(
id=conversation_id,
user=user,
messages=[Message(role="user", content=initial_message)],
)
self._conversations[conversation_id] = conversation
return conversation
async def get_conversation(
self, conversation_id: str, user: User
) -> Optional[Conversation]:
"""Get conversation by ID, scoped to user."""
conversation = self._conversations.get(conversation_id)
if conversation and conversation.user.id == user.id:
return conversation
return None
async def update_conversation(self, conversation: Conversation) -> None:
"""Update conversation with new messages."""
self._conversations[conversation.id] = conversation
async def delete_conversation(self, conversation_id: str, user: User) -> bool:
"""Delete conversation."""
conversation = await self.get_conversation(conversation_id, user)
if conversation:
del self._conversations[conversation_id]
return True
return False
async def list_conversations(
self, user: User, limit: int = 50, offset: int = 0
) -> List[Conversation]:
"""List conversations for user."""
user_conversations = [
conv for conv in self._conversations.values() if conv.user.id == user.id
]
# Sort by updated_at desc
user_conversations.sort(key=lambda x: x.updated_at, reverse=True)
return user_conversations[offset : offset + limit]
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/local/storage.py",
"license": "MIT License",
"lines": 51,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/marqo/agent_memory.py | """
Marqo vector database implementation of AgentMemory.
This implementation uses Marqo for vector storage of tool usage patterns.
"""
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
import marqo
MARQO_AVAILABLE = True
except ImportError:
MARQO_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class MarqoAgentMemory(AgentMemory):
"""Marqo-based implementation of AgentMemory."""
def __init__(
self,
url: str = "http://localhost:8882",
index_name: str = "tool-memories",
api_key: Optional[str] = None,
):
if not MARQO_AVAILABLE:
raise ImportError(
"Marqo is required for MarqoAgentMemory. Install with: pip install marqo"
)
self.url = url
self.index_name = index_name
self.api_key = api_key
self._client = None
self._executor = ThreadPoolExecutor(max_workers=2)
def _get_client(self):
"""Get or create Marqo client."""
if self._client is None:
self._client = marqo.Client(url=self.url, api_key=self.api_key)
# Create index if it doesn't exist
try:
self._client.get_index(self.index_name)
except Exception:
self._client.create_index(self.index_name)
return self._client
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
client = self._get_client()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
document = {
"_id": memory_id,
"question": question,
"tool_name": tool_name,
"args": json.dumps(args),
"timestamp": timestamp,
"success": success,
"metadata": json.dumps(metadata or {}),
}
client.index(self.index_name).add_documents(
[document], tensor_fields=["question"]
)
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
client = self._get_client()
# Build filter
filter_string = "success:true"
if tool_name_filter:
filter_string += f" AND tool_name:{tool_name_filter}"
results = client.index(self.index_name).search(
q=question, limit=limit, filter_string=filter_string
)
search_results = []
for i, hit in enumerate(results["hits"]):
# Marqo returns score
similarity_score = hit.get("_score", 0)
if similarity_score >= similarity_threshold:
args = json.loads(hit.get("args", "{}"))
metadata_dict = json.loads(hit.get("metadata", "{}"))
memory = ToolMemory(
memory_id=hit["_id"],
question=hit["question"],
tool_name=hit["tool_name"],
args=args,
timestamp=hit.get("timestamp"),
success=hit.get("success", True),
metadata=metadata_dict,
)
search_results.append(
ToolMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories."""
def _get_recent():
client = self._get_client()
# Search with wildcard and sort by timestamp
results = client.index(self.index_name).search(
q="*", limit=limit, sort="timestamp:desc"
)
memories = []
for hit in results.get("hits", []):
args = json.loads(hit.get("args", "{}"))
metadata_dict = json.loads(hit.get("metadata", "{}"))
memory = ToolMemory(
memory_id=hit["_id"],
question=hit["question"],
tool_name=hit["tool_name"],
args=args,
timestamp=hit.get("timestamp"),
success=hit.get("success", True),
metadata=metadata_dict,
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID."""
def _delete():
client = self._get_client()
try:
client.index(self.index_name).delete_documents(ids=[memory_id])
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
client = self._get_client()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
document = {
"_id": memory_id,
"content": content,
"timestamp": timestamp,
"is_text_memory": True,
}
client.index(self.index_name).add_documents(
[document], tensor_fields=["content"]
)
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
client = self._get_client()
filter_string = "is_text_memory:true"
results = client.index(self.index_name).search(
q=query, limit=limit, filter_string=filter_string
)
search_results = []
for i, hit in enumerate(results["hits"]):
similarity_score = hit.get("_score", 0)
if similarity_score >= similarity_threshold:
memory = TextMemory(
memory_id=hit["_id"],
content=hit.get("content", ""),
timestamp=hit.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
client = self._get_client()
results = client.index(self.index_name).search(
q="*",
limit=limit,
filter_string="is_text_memory:true",
sort="timestamp:desc",
)
memories = []
for hit in results.get("hits", []):
memory = TextMemory(
memory_id=hit["_id"],
content=hit.get("content", ""),
timestamp=hit.get("timestamp"),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
client = self._get_client()
try:
client.index(self.index_name).delete_documents(ids=[memory_id])
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
client = self._get_client()
# Build filter for search
filter_parts = []
if tool_name:
filter_parts.append(f"tool_name:{tool_name}")
if before_date:
filter_parts.append(f"timestamp:[* TO {before_date}]")
if filter_parts or (tool_name is None and before_date is None):
filter_string = " AND ".join(filter_parts) if filter_parts else None
if filter_string:
# Search for documents to delete
results = client.index(self.index_name).search(
q="*",
limit=1000, # Max results
filter_string=filter_string,
)
ids_to_delete = [hit["_id"] for hit in results.get("hits", [])]
if ids_to_delete:
client.index(self.index_name).delete_documents(
ids=ids_to_delete
)
return len(ids_to_delete)
else:
# Delete entire index and recreate
try:
client.delete_index(self.index_name)
client.create_index(self.index_name)
except Exception:
pass
return 0
return 0
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/marqo/agent_memory.py",
"license": "MIT License",
"lines": 279,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/milvus/agent_memory.py | """
Milvus vector database implementation of AgentMemory.
This implementation uses Milvus for distributed vector storage of tool usage patterns.
"""
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
from pymilvus import (
connections,
Collection,
CollectionSchema,
FieldSchema,
DataType,
utility,
)
MILVUS_AVAILABLE = True
except ImportError:
MILVUS_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class MilvusAgentMemory(AgentMemory):
"""Milvus-based implementation of AgentMemory."""
def __init__(
self,
collection_name: str = "tool_memories",
host: str = "localhost",
port: int = 19530,
alias: str = "default",
dimension: int = 384,
):
if not MILVUS_AVAILABLE:
raise ImportError(
"Milvus is required for MilvusAgentMemory. Install with: pip install pymilvus"
)
self.collection_name = collection_name
self.host = host
self.port = port
self.alias = alias
self.dimension = dimension
self._collection = None
self._executor = ThreadPoolExecutor(max_workers=2)
def _get_collection(self):
"""Get or create Milvus collection."""
if self._collection is None:
# Connect to Milvus
connections.connect(alias=self.alias, host=self.host, port=self.port)
# Create collection if it doesn't exist
if not utility.has_collection(self.collection_name):
fields = [
FieldSchema(
name="id",
dtype=DataType.VARCHAR,
is_primary=True,
max_length=100,
),
FieldSchema(
name="embedding",
dtype=DataType.FLOAT_VECTOR,
dim=self.dimension,
),
FieldSchema(
name="question", dtype=DataType.VARCHAR, max_length=2000
),
FieldSchema(
name="tool_name", dtype=DataType.VARCHAR, max_length=200
),
FieldSchema(
name="args_json", dtype=DataType.VARCHAR, max_length=5000
),
FieldSchema(
name="timestamp", dtype=DataType.VARCHAR, max_length=50
),
FieldSchema(name="success", dtype=DataType.BOOL),
FieldSchema(
name="metadata_json", dtype=DataType.VARCHAR, max_length=5000
),
]
schema = CollectionSchema(
fields=fields, description="Tool usage memories"
)
collection = Collection(name=self.collection_name, schema=schema)
# Create index for vector field
index_params = {
"index_type": "IVF_FLAT",
"metric_type": "IP",
"params": {"nlist": 128},
}
collection.create_index(
field_name="embedding", index_params=index_params
)
self._collection = Collection(self.collection_name)
self._collection.load()
return self._collection
def _create_embedding(self, text: str) -> List[float]:
"""Create a simple embedding from text (placeholder)."""
import hashlib
hash_val = int(hashlib.md5(text.encode()).hexdigest(), 16)
return [(hash_val >> i) % 100 / 100.0 for i in range(self.dimension)]
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
collection = self._get_collection()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(question)
entities = [
[memory_id],
[embedding],
[question],
[tool_name],
[json.dumps(args)],
[timestamp],
[success],
[json.dumps(metadata or {})],
]
collection.insert(entities)
collection.flush()
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
collection = self._get_collection()
embedding = self._create_embedding(question)
# Build filter expression
expr = "success == true"
if tool_name_filter:
expr += f' && tool_name == "{tool_name_filter}"'
search_params = {"metric_type": "IP", "params": {"nprobe": 10}}
results = collection.search(
data=[embedding],
anns_field="embedding",
param=search_params,
limit=limit,
expr=expr,
output_fields=[
"id",
"question",
"tool_name",
"args_json",
"timestamp",
"success",
"metadata_json",
],
)
search_results = []
for i, hits in enumerate(results):
for j, hit in enumerate(hits):
similarity_score = hit.distance
if similarity_score >= similarity_threshold:
args = json.loads(hit.entity.get("args_json", "{}"))
metadata_dict = json.loads(
hit.entity.get("metadata_json", "{}")
)
memory = ToolMemory(
memory_id=hit.entity.get("id"),
question=hit.entity.get("question"),
tool_name=hit.entity.get("tool_name"),
args=args,
timestamp=hit.entity.get("timestamp"),
success=hit.entity.get("success", True),
metadata=metadata_dict,
)
search_results.append(
ToolMemorySearchResult(
memory=memory,
similarity_score=similarity_score,
rank=j + 1,
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories."""
def _get_recent():
collection = self._get_collection()
# Query all entries and sort by timestamp
results = collection.query(
expr="id != ''",
output_fields=[
"id",
"question",
"tool_name",
"args_json",
"timestamp",
"success",
"metadata_json",
],
limit=1000,
)
# Sort by timestamp
sorted_results = sorted(
results, key=lambda r: r.get("timestamp", ""), reverse=True
)
memories = []
for result in sorted_results[:limit]:
args = json.loads(result.get("args_json", "{}"))
metadata_dict = json.loads(result.get("metadata_json", "{}"))
memory = ToolMemory(
memory_id=result.get("id"),
question=result.get("question"),
tool_name=result.get("tool_name"),
args=args,
timestamp=result.get("timestamp"),
success=result.get("success", True),
metadata=metadata_dict,
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID."""
def _delete():
collection = self._get_collection()
try:
expr = f'id == "{memory_id}"'
collection.delete(expr)
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
collection = self._get_collection()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(content)
entities = [
[memory_id],
[embedding],
[content],
[""], # tool_name (empty for text memories)
[""], # args_json (empty for text memories)
[timestamp],
[True], # success (always true for text memories)
[json.dumps({"is_text_memory": True})], # metadata_json
]
collection.insert(entities)
collection.flush()
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
collection = self._get_collection()
embedding = self._create_embedding(query)
# Build filter expression for text memories
expr = 'tool_name == ""'
search_params = {"metric_type": "IP", "params": {"nprobe": 10}}
results = collection.search(
data=[embedding],
anns_field="embedding",
param=search_params,
limit=limit,
expr=expr,
output_fields=["id", "question", "timestamp", "metadata_json"],
)
search_results = []
for i, hits in enumerate(results):
for j, hit in enumerate(hits):
similarity_score = hit.distance
if similarity_score >= similarity_threshold:
content = hit.entity.get("question", "")
memory = TextMemory(
memory_id=hit.entity.get("id"),
content=content,
timestamp=hit.entity.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory,
similarity_score=similarity_score,
rank=j + 1,
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
collection = self._get_collection()
# Query text memory entries
results = collection.query(
expr='tool_name == ""',
output_fields=["id", "question", "timestamp"],
limit=1000,
)
# Sort by timestamp
sorted_results = sorted(
results, key=lambda r: r.get("timestamp", ""), reverse=True
)
memories = []
for result in sorted_results[:limit]:
memory = TextMemory(
memory_id=result.get("id"),
content=result.get("question", ""),
timestamp=result.get("timestamp"),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
collection = self._get_collection()
try:
expr = f'id == "{memory_id}"'
collection.delete(expr)
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
collection = self._get_collection()
# Build filter expression
expr_parts = []
if tool_name:
expr_parts.append(f'tool_name == "{tool_name}"')
if before_date:
expr_parts.append(f'timestamp < "{before_date}"')
if expr_parts:
expr = " && ".join(expr_parts)
else:
expr = "id != ''"
collection.delete(expr)
return 0
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/milvus/agent_memory.py",
"license": "MIT License",
"lines": 375,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/mock/llm.py | """
Mock LLM service implementation for testing.
This module provides a simple mock implementation of the LlmService interface,
useful for testing and development without requiring actual LLM API calls.
"""
import asyncio
from typing import AsyncGenerator, List
from vanna.core.llm import LlmService, LlmRequest, LlmResponse, LlmStreamChunk
from vanna.core.tool import ToolSchema
class MockLlmService(LlmService):
"""Mock LLM service that returns predefined responses."""
def __init__(self, response_content: str = "Hello! This is a mock response."):
self.response_content = response_content
self.call_count = 0
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Send a request to the mock LLM."""
self.call_count += 1
# Simulate processing delay
await asyncio.sleep(0.1)
# Return a simple response
return LlmResponse(
content=f"{self.response_content} (Request #{self.call_count})",
finish_reason="stop",
usage={"prompt_tokens": 50, "completion_tokens": 20, "total_tokens": 70},
)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Stream a request to the mock LLM."""
self.call_count += 1
# Split response into chunks
words = f"{self.response_content} (Streamed #{self.call_count})".split()
for i, word in enumerate(words):
await asyncio.sleep(0.05) # Simulate streaming delay
chunk_content = word + (" " if i < len(words) - 1 else "")
yield LlmStreamChunk(
content=chunk_content,
finish_reason="stop" if i == len(words) - 1 else None,
)
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Validate tool schemas and return any errors."""
# Mock validation - no errors
return []
def set_response(self, content: str) -> None:
"""Set the response content for testing."""
self.response_content = content
def reset_call_count(self) -> None:
"""Reset the call counter."""
self.call_count = 0
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/mock/llm.py",
"license": "MIT License",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/mssql/sql_runner.py | """Microsoft SQL Server implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class MSSQLRunner(SqlRunner):
"""Microsoft SQL Server implementation of the SqlRunner interface."""
def __init__(self, odbc_conn_str: str, **kwargs):
"""Initialize with MSSQL connection parameters.
Args:
odbc_conn_str: The ODBC connection string for SQL Server
**kwargs: Additional SQLAlchemy engine parameters
"""
try:
import pyodbc
self.pyodbc = pyodbc
except ImportError as e:
raise ImportError(
"pyodbc package is required. Install with: pip install pyodbc"
) from e
try:
import sqlalchemy as sa
from sqlalchemy.engine import URL
from sqlalchemy import create_engine
self.sa = sa
self.URL = URL
self.create_engine = create_engine
except ImportError as e:
raise ImportError(
"sqlalchemy package is required. Install with: pip install sqlalchemy"
) from e
# Create the connection URL
connection_url = self.URL.create(
"mssql+pyodbc", query={"odbc_connect": odbc_conn_str}
)
# Create the engine
self.engine = self.create_engine(connection_url, **kwargs)
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against MSSQL database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
sqlalchemy.exc.SQLAlchemyError: If query execution fails
"""
# Execute the SQL statement and return the result as a pandas DataFrame
with self.engine.begin() as conn:
df = pd.read_sql_query(self.sa.text(args.sql), conn)
return df
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/mssql/sql_runner.py",
"license": "MIT License",
"lines": 51,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/mysql/sql_runner.py | """MySQL implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class MySQLRunner(SqlRunner):
"""MySQL implementation of the SqlRunner interface."""
def __init__(
self,
host: str,
database: str,
user: str,
password: str,
port: int = 3306,
**kwargs,
):
"""Initialize with MySQL connection parameters.
Args:
host: Database host address
database: Database name
user: Database user
password: Database password
port: Database port (default: 3306)
**kwargs: Additional PyMySQL connection parameters
"""
try:
import pymysql.cursors
self.pymysql = pymysql
except ImportError as e:
raise ImportError(
"PyMySQL package is required. Install with: pip install 'vanna[mysql]'"
) from e
self.host = host
self.database = database
self.user = user
self.password = password
self.port = port
self.kwargs = kwargs
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against MySQL database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
pymysql.Error: If query execution fails
"""
# Connect to the database
conn = self.pymysql.connect(
host=self.host,
user=self.user,
password=self.password,
database=self.database,
port=self.port,
cursorclass=self.pymysql.cursors.DictCursor,
**self.kwargs,
)
try:
# Ping to ensure connection is alive
conn.ping(reconnect=True)
cursor = conn.cursor()
cursor.execute(args.sql)
results = cursor.fetchall()
# Create a pandas dataframe from the results
df = pd.DataFrame(
results,
columns=[desc[0] for desc in cursor.description]
if cursor.description
else [],
)
cursor.close()
return df
finally:
conn.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/mysql/sql_runner.py",
"license": "MIT License",
"lines": 75,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/ollama/llm.py | """
Ollama LLM service implementation.
This module provides an implementation of the LlmService interface backed by
Ollama's local LLM API. It supports non-streaming responses and streaming
of text content. Tool calling support depends on the Ollama model being used.
"""
from __future__ import annotations
import json
import os
from typing import Any, AsyncGenerator, Dict, List, Optional
from vanna.core.llm import (
LlmService,
LlmRequest,
LlmResponse,
LlmStreamChunk,
)
from vanna.core.tool import ToolCall, ToolSchema
class OllamaLlmService(LlmService):
"""Ollama-backed LLM service for local model inference.
Args:
model: Ollama model name (e.g., "gpt-oss:20b").
host: Ollama server URL; defaults to "http://localhost:11434" or env `OLLAMA_HOST`.
timeout: Request timeout in seconds; defaults to 240.
num_ctx: Context window size; defaults to 8192.
temperature: Sampling temperature; defaults to 0.7.
extra_options: Additional options passed to Ollama (e.g., num_predict, top_k, top_p).
"""
def __init__(
self,
model: str,
host: Optional[str] = None,
timeout: float = 240.0,
num_ctx: int = 8192,
temperature: float = 0.7,
**extra_options: Any,
) -> None:
try:
import ollama
except ImportError as e:
raise ImportError(
"ollama package is required. Install with: pip install 'vanna[ollama]' or pip install ollama"
) from e
if not model:
raise ValueError("model parameter is required for Ollama")
self.model = model
self.host = host or os.getenv("OLLAMA_HOST", "http://localhost:11434")
self.timeout = timeout
self.num_ctx = num_ctx
self.temperature = temperature
self.extra_options = extra_options
# Create Ollama client
self._client = ollama.Client(host=self.host, timeout=timeout)
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Send a non-streaming request to Ollama and return the response."""
payload = self._build_payload(request)
# Call the Ollama API
try:
resp = self._client.chat(**payload)
except Exception as e:
raise RuntimeError(f"Ollama request failed: {str(e)}") from e
# Extract message from response
message = resp.get("message", {})
content = message.get("content")
tool_calls = self._extract_tool_calls_from_message(message)
# Extract usage information if available
usage: Dict[str, int] = {}
if "prompt_eval_count" in resp or "eval_count" in resp:
usage = {
"prompt_tokens": resp.get("prompt_eval_count", 0),
"completion_tokens": resp.get("eval_count", 0),
"total_tokens": resp.get("prompt_eval_count", 0)
+ resp.get("eval_count", 0),
}
return LlmResponse(
content=content,
tool_calls=tool_calls or None,
finish_reason=resp.get("done_reason")
or ("stop" if resp.get("done") else None),
usage=usage or None,
)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Stream a request to Ollama.
Emits `LlmStreamChunk` for textual deltas as they arrive. Tool calls are
accumulated and emitted in a final chunk when the stream ends.
"""
payload = self._build_payload(request)
# Ollama streaming
try:
stream = self._client.chat(**payload, stream=True)
except Exception as e:
raise RuntimeError(f"Ollama streaming request failed: {str(e)}") from e
# Accumulate tool calls if present
accumulated_tool_calls: List[ToolCall] = []
last_finish: Optional[str] = None
for chunk in stream:
message = chunk.get("message", {})
# Yield text content
content = message.get("content")
if content:
yield LlmStreamChunk(content=content)
# Accumulate tool calls
tool_calls = self._extract_tool_calls_from_message(message)
if tool_calls:
accumulated_tool_calls.extend(tool_calls)
# Track finish reason
if chunk.get("done"):
last_finish = chunk.get("done_reason", "stop")
# Emit final chunk with tool calls if any
if accumulated_tool_calls:
yield LlmStreamChunk(
tool_calls=accumulated_tool_calls, finish_reason=last_finish or "stop"
)
else:
# Emit terminal chunk to signal completion
yield LlmStreamChunk(finish_reason=last_finish or "stop")
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Validate tool schemas. Returns a list of error messages."""
errors: List[str] = []
# Basic validation; Ollama model support for tools varies
for t in tools:
if not t.name:
errors.append(f"Tool must have a name")
if not t.description:
errors.append(f"Tool '{t.name}' should have a description")
return errors
# Internal helpers
def _build_payload(self, request: LlmRequest) -> Dict[str, Any]:
"""Build the Ollama chat payload from LlmRequest."""
messages: List[Dict[str, Any]] = []
# Add system prompt as first message if provided
if request.system_prompt:
messages.append({"role": "system", "content": request.system_prompt})
# Convert messages to Ollama format
for m in request.messages:
msg: Dict[str, Any] = {"role": m.role, "content": m.content or ""}
# Handle tool calls in assistant messages
if m.role == "assistant" and m.tool_calls:
# Some Ollama models support tool_calls in message
tool_calls_payload = []
for tc in m.tool_calls:
tool_calls_payload.append(
{"function": {"name": tc.name, "arguments": tc.arguments}}
)
msg["tool_calls"] = tool_calls_payload
messages.append(msg)
# Build tools array if tools are provided
tools_payload: Optional[List[Dict[str, Any]]] = None
if request.tools:
tools_payload = []
for t in request.tools:
tools_payload.append(
{
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.parameters,
},
}
)
# Build options
options: Dict[str, Any] = {
"num_ctx": self.num_ctx,
"temperature": self.temperature,
**self.extra_options,
}
# Build final payload
payload: Dict[str, Any] = {
"model": self.model,
"messages": messages,
"options": options,
}
# Add tools if provided (note: not all Ollama models support tools)
if tools_payload:
payload["tools"] = tools_payload
return payload
def _extract_tool_calls_from_message(
self, message: Dict[str, Any]
) -> List[ToolCall]:
"""Extract tool calls from Ollama message."""
tool_calls: List[ToolCall] = []
# Check for tool_calls in message
raw_tool_calls = message.get("tool_calls", [])
if not raw_tool_calls:
return tool_calls
for idx, tc in enumerate(raw_tool_calls):
fn = tc.get("function", {})
name = fn.get("name")
if not name:
continue
# Parse arguments
arguments = fn.get("arguments", {})
if isinstance(arguments, str):
try:
arguments = json.loads(arguments)
except Exception:
arguments = {"_raw": arguments}
if not isinstance(arguments, dict):
arguments = {"args": arguments}
tool_calls.append(
ToolCall(
id=tc.get("id", f"tool_call_{idx}"),
name=name,
arguments=arguments,
)
)
return tool_calls
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/ollama/llm.py",
"license": "MIT License",
"lines": 209,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/openai/llm.py | """
OpenAI LLM service implementation.
This module provides an implementation of the LlmService interface backed by
OpenAI's Chat Completions API (openai>=1.0.0). It supports non-streaming
responses and best-effort streaming of text content. Tool/function calling is
passed through when tools are provided, but full tool-call conversation
round-tripping may require adding assistant tool-call messages to the
conversation upstream.
"""
from __future__ import annotations
import json
import os
from typing import Any, AsyncGenerator, Dict, List, Optional, cast
from vanna.core.llm import (
LlmService,
LlmRequest,
LlmResponse,
LlmStreamChunk,
)
from vanna.core.tool import ToolCall, ToolSchema
class OpenAILlmService(LlmService):
"""OpenAI Chat Completions-backed LLM service.
Args:
model: OpenAI model name (e.g., "gpt-5").
api_key: API key; falls back to env `OPENAI_API_KEY`.
organization: Optional org; env `OPENAI_ORG` if unset.
base_url: Optional custom base URL; env `OPENAI_BASE_URL` if unset.
extra_client_kwargs: Extra kwargs forwarded to `openai.OpenAI()`.
"""
def __init__(
self,
model: Optional[str] = None,
api_key: Optional[str] = None,
organization: Optional[str] = None,
base_url: Optional[str] = None,
**extra_client_kwargs: Any,
) -> None:
try:
from openai import OpenAI
except Exception as e: # pragma: no cover - import-time error surface
raise ImportError(
"openai package is required. Install with: pip install 'vanna[openai]'"
) from e
self.model = model or os.getenv("OPENAI_MODEL", "gpt-5")
api_key = api_key or os.getenv("OPENAI_API_KEY")
organization = organization or os.getenv("OPENAI_ORG")
base_url = base_url or os.getenv("OPENAI_BASE_URL")
client_kwargs: Dict[str, Any] = {**extra_client_kwargs}
if api_key:
client_kwargs["api_key"] = api_key
if organization:
client_kwargs["organization"] = organization
if base_url:
client_kwargs["base_url"] = base_url
self._client = OpenAI(**client_kwargs)
async def send_request(self, request: LlmRequest) -> LlmResponse:
"""Send a non-streaming request to OpenAI and return the response."""
payload = self._build_payload(request)
# Call the API synchronously; this function is async but we can block here.
resp = self._client.chat.completions.create(**payload, stream=False)
if not resp.choices:
return LlmResponse(content=None, tool_calls=None, finish_reason=None)
choice = resp.choices[0]
content: Optional[str] = getattr(choice.message, "content", None)
tool_calls = self._extract_tool_calls_from_message(choice.message)
usage: Dict[str, int] = {}
if getattr(resp, "usage", None):
usage = {
k: int(v)
for k, v in {
"prompt_tokens": getattr(resp.usage, "prompt_tokens", 0),
"completion_tokens": getattr(resp.usage, "completion_tokens", 0),
"total_tokens": getattr(resp.usage, "total_tokens", 0),
}.items()
}
return LlmResponse(
content=content,
tool_calls=tool_calls or None,
finish_reason=getattr(choice, "finish_reason", None),
usage=usage or None,
)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
"""Stream a request to OpenAI.
Emits `LlmStreamChunk` for textual deltas as they arrive. Tool-calls are
accumulated and emitted in a final chunk when the stream ends.
"""
payload = self._build_payload(request)
# Synchronous streaming iterator; iterate within async context.
stream = self._client.chat.completions.create(**payload, stream=True)
# Builders for streamed tool-calls (index -> partial)
tc_builders: Dict[int, Dict[str, Optional[str]]] = {}
last_finish: Optional[str] = None
for event in stream:
if not getattr(event, "choices", None):
continue
choice = event.choices[0]
delta = getattr(choice, "delta", None)
if delta is None:
# Some SDK versions use `event.choices[0].message` on the final packet
last_finish = getattr(choice, "finish_reason", last_finish)
continue
# Text content
content_piece: Optional[str] = getattr(delta, "content", None)
if content_piece:
yield LlmStreamChunk(content=content_piece)
# Tool calls (streamed)
streamed_tool_calls = getattr(delta, "tool_calls", None)
if streamed_tool_calls:
for tc in streamed_tool_calls:
idx = getattr(tc, "index", 0) or 0
b = tc_builders.setdefault(
idx, {"id": None, "name": None, "arguments": ""}
)
if getattr(tc, "id", None):
b["id"] = tc.id
fn = getattr(tc, "function", None)
if fn is not None:
if getattr(fn, "name", None):
b["name"] = fn.name
if getattr(fn, "arguments", None):
b["arguments"] = (b["arguments"] or "") + fn.arguments
last_finish = getattr(choice, "finish_reason", last_finish)
# Emit final tool-calls chunk if any
final_tool_calls: List[ToolCall] = []
for b in tc_builders.values():
if not b.get("name"):
continue
args_raw = b.get("arguments") or "{}"
try:
loaded = json.loads(args_raw)
if isinstance(loaded, dict):
args_dict: Dict[str, Any] = loaded
else:
args_dict = {"args": loaded}
except Exception:
args_dict = {"_raw": args_raw}
final_tool_calls.append(
ToolCall(
id=b.get("id") or "tool_call",
name=b["name"] or "tool",
arguments=args_dict,
)
)
if final_tool_calls:
yield LlmStreamChunk(tool_calls=final_tool_calls, finish_reason=last_finish)
else:
# Still emit a terminal chunk to signal completion
yield LlmStreamChunk(finish_reason=last_finish or "stop")
async def validate_tools(self, tools: List[ToolSchema]) -> List[str]:
"""Validate tool schemas. Returns a list of error messages."""
errors: List[str] = []
# Basic checks; OpenAI will enforce further validation server-side.
for t in tools:
if not t.name or len(t.name) > 64:
errors.append(f"Invalid tool name: {t.name!r}")
return errors
# Internal helpers
def _build_payload(self, request: LlmRequest) -> Dict[str, Any]:
messages: List[Dict[str, Any]] = []
# Add system prompt as first message if provided
if request.system_prompt:
messages.append({"role": "system", "content": request.system_prompt})
for m in request.messages:
msg: Dict[str, Any] = {"role": m.role, "content": m.content}
if m.role == "tool" and m.tool_call_id:
msg["tool_call_id"] = m.tool_call_id
elif m.role == "assistant" and m.tool_calls:
# Convert tool calls to OpenAI format
tool_calls_payload = []
for tc in m.tool_calls:
tool_calls_payload.append(
{
"id": tc.id,
"type": "function",
"function": {
"name": tc.name,
"arguments": json.dumps(tc.arguments),
},
}
)
msg["tool_calls"] = tool_calls_payload
messages.append(msg)
tools_payload: Optional[List[Dict[str, Any]]] = None
if request.tools:
tools_payload = [
{
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.parameters,
},
}
for t in request.tools
]
payload: Dict[str, Any] = {
"model": self.model,
"messages": messages,
}
if request.max_tokens is not None:
payload["max_tokens"] = request.max_tokens
if tools_payload:
payload["tools"] = tools_payload
payload["tool_choice"] = "auto"
return payload
def _extract_tool_calls_from_message(self, message: Any) -> List[ToolCall]:
tool_calls: List[ToolCall] = []
raw_tool_calls = getattr(message, "tool_calls", None) or []
for tc in raw_tool_calls:
fn = getattr(tc, "function", None)
if not fn:
continue
args_raw = getattr(fn, "arguments", "{}")
try:
loaded = json.loads(args_raw)
if isinstance(loaded, dict):
args_dict: Dict[str, Any] = loaded
else:
args_dict = {"args": loaded}
except Exception:
args_dict = {"_raw": args_raw}
tool_calls.append(
ToolCall(
id=getattr(tc, "id", "tool_call"),
name=getattr(fn, "name", "tool"),
arguments=args_dict,
)
)
return tool_calls
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/openai/llm.py",
"license": "MIT License",
"lines": 231,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/openai/responses.py | from __future__ import annotations
import json
import os
from typing import Any, AsyncGenerator, Dict, List, Optional, Tuple, TYPE_CHECKING
from vanna.core.llm import LlmService, LlmRequest, LlmResponse, LlmStreamChunk
from vanna.core.tool import ToolCall, ToolSchema
if TYPE_CHECKING:
from openai.types.responses import Response
class OpenAIResponsesService(LlmService):
def __init__(
self, api_key: Optional[str] = None, model: Optional[str] = None
) -> None:
try:
from openai import AsyncOpenAI
from openai.types.responses import Response
except Exception as e: # pragma: no cover
raise ImportError(
"openai package is required. Install with: pip install 'vanna[openai]'"
) from e
self.client = AsyncOpenAI(api_key=api_key or os.getenv("OPENAI_API_KEY"))
self.model = model or os.getenv("OPENAI_MODEL", "gpt-5")
async def send_request(self, request: LlmRequest) -> LlmResponse:
payload = self._payload(request)
resp: Response = await self.client.responses.create(**payload)
self._debug_print("response", resp)
text, tools, status, usage = self._extract(resp)
return LlmResponse(
content=text,
tool_calls=tools or None,
finish_reason=status,
usage=usage or None,
metadata={"request_id": getattr(resp, "id", None)},
)
async def stream_request(
self, request: LlmRequest
) -> AsyncGenerator[LlmStreamChunk, None]:
payload = self._payload(request)
async with self.client.responses.stream(**payload) as stream:
async for event in stream:
self._debug_print("stream_event", event)
event_type = getattr(event, "type", None)
if event_type == "response.output_text.delta":
delta = getattr(event, "delta", None)
if delta:
yield LlmStreamChunk(content=delta)
final: Response = await stream.get_final_response()
self._debug_print("final_response", final)
_text, tools, status, _usage = self._extract(final)
yield LlmStreamChunk(tool_calls=tools or None, finish_reason=status)
async def validate_tools(self, tools: List[Any]) -> List[str]:
return [] # minimal: accept whatever's passed through
# ---- helpers ----
def _payload(self, request: LlmRequest) -> Dict[str, Any]:
msgs = [{"role": m.role, "content": m.content} for m in request.messages]
p: Dict[str, Any] = {"model": self.model, "input": msgs}
if request.system_prompt:
p["instructions"] = request.system_prompt
if request.max_tokens:
p["max_output_tokens"] = request.max_tokens
if request.tools:
p["tools"] = [self._serialize_tool(t) for t in request.tools]
return p
def _debug_print(self, label: str, obj: Any) -> None:
try:
payload = obj.model_dump()
except AttributeError:
try:
payload = obj.dict()
except AttributeError:
payload = obj
print(f"[OpenAIResponsesService] {label}: {payload}")
def _extract(
self, resp: Response
) -> Tuple[
Optional[str], Optional[List[ToolCall]], Optional[str], Optional[Dict[str, int]]
]:
text = getattr(resp, "output_text", None)
tool_calls: List[ToolCall] = []
for oc in getattr(resp, "output", []) or []:
for item in getattr(oc, "content", []) or []:
if getattr(item, "type", None) == "tool_call":
tc = getattr(item, "tool_call", None)
if tc and getattr(tc, "type", None) == "function":
fn = getattr(tc, "function", None)
if fn:
name = getattr(fn, "name", None)
args = getattr(fn, "arguments", None)
if not isinstance(args, (dict, list)):
try:
args = json.loads(args) if args else {}
except Exception:
args = {"_raw": args}
tool_calls.append(ToolCall(name=name, arguments=args))
usage = None
if getattr(resp, "usage", None):
usage = {
"input_tokens": getattr(resp.usage, "input_tokens", 0) or 0,
"output_tokens": getattr(resp.usage, "output_tokens", 0) or 0,
"total_tokens": getattr(resp.usage, "total_tokens", None)
or (
(getattr(resp.usage, "input_tokens", 0) or 0)
+ (getattr(resp.usage, "output_tokens", 0) or 0)
),
}
status = getattr(resp, "status", None) # e.g. "completed"
return text, (tool_calls or None), status, usage
def _serialize_tool(self, tool: Any) -> Dict[str, Any]:
"""Convert a tool schema into the dict format expected by OpenAI Responses."""
if isinstance(tool, ToolSchema):
return {
"type": "function",
"name": tool.name,
"description": tool.description,
"parameters": tool.parameters,
"strict": False,
}
# Support generic pydantic/BaseModel style objects without importing pydantic here.
if hasattr(tool, "model_dump"):
data = tool.model_dump()
if all(key in data for key in ("name", "description", "parameters")):
return {
"type": "function",
"name": data["name"],
"description": data["description"],
"parameters": data["parameters"],
"strict": data.get("strict", False),
}
return data
if isinstance(tool, dict):
if "type" in tool:
return tool
if all(k in tool for k in ("name", "description", "parameters")):
return {
"type": "function",
"name": tool["name"],
"description": tool["description"],
"parameters": tool["parameters"],
"strict": tool.get("strict", False),
}
return tool
raise TypeError(f"Unsupported tool schema type: {type(tool)!r}")
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/openai/responses.py",
"license": "MIT License",
"lines": 141,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/opensearch/agent_memory.py | """
OpenSearch vector database implementation of AgentMemory.
This implementation uses OpenSearch for distributed search and storage of tool usage patterns.
"""
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
from opensearchpy import OpenSearch, helpers
OPENSEARCH_AVAILABLE = True
except ImportError:
OPENSEARCH_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class OpenSearchAgentMemory(AgentMemory):
"""OpenSearch-based implementation of AgentMemory."""
def __init__(
self,
index_name: str = "tool_memories",
hosts: Optional[List[str]] = None,
http_auth: Optional[tuple] = None,
use_ssl: bool = False,
verify_certs: bool = False,
dimension: int = 384,
):
if not OPENSEARCH_AVAILABLE:
raise ImportError(
"OpenSearch is required for OpenSearchAgentMemory. Install with: pip install opensearch-py"
)
self.index_name = index_name
self.hosts = hosts or ["localhost:9200"]
self.http_auth = http_auth
self.use_ssl = use_ssl
self.verify_certs = verify_certs
self.dimension = dimension
self._client = None
self._executor = ThreadPoolExecutor(max_workers=2)
def _get_client(self):
"""Get or create OpenSearch client."""
if self._client is None:
self._client = OpenSearch(
hosts=self.hosts,
http_auth=self.http_auth,
use_ssl=self.use_ssl,
verify_certs=self.verify_certs,
ssl_show_warn=False,
)
# Create index if it doesn't exist
if not self._client.indices.exists(index=self.index_name):
index_body = {
"settings": {
"index": {"knn": True, "knn.algo_param.ef_search": 100}
},
"mappings": {
"properties": {
"memory_id": {"type": "keyword"},
"question": {"type": "text"},
"tool_name": {"type": "keyword"},
"args": {"type": "object", "enabled": False},
"timestamp": {"type": "date"},
"success": {"type": "boolean"},
"metadata": {"type": "object", "enabled": False},
"embedding": {
"type": "knn_vector",
"dimension": self.dimension,
"method": {
"name": "hnsw",
"space_type": "cosinesimil",
"engine": "nmslib",
},
},
}
},
}
self._client.indices.create(index=self.index_name, body=index_body)
return self._client
def _create_embedding(self, text: str) -> List[float]:
"""Create a simple embedding from text (placeholder)."""
import hashlib
hash_val = int(hashlib.md5(text.encode()).hexdigest(), 16)
return [(hash_val >> i) % 100 / 100.0 for i in range(self.dimension)]
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
client = self._get_client()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(question)
document = {
"memory_id": memory_id,
"question": question,
"tool_name": tool_name,
"args": args,
"timestamp": timestamp,
"success": success,
"metadata": metadata or {},
"embedding": embedding,
}
client.index(
index=self.index_name, body=document, id=memory_id, refresh=True
)
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
client = self._get_client()
embedding = self._create_embedding(question)
# Build query
must_conditions = [{"term": {"success": True}}]
if tool_name_filter:
must_conditions.append({"term": {"tool_name": tool_name_filter}})
query = {
"size": limit,
"query": {
"bool": {
"must": must_conditions,
"filter": {
"knn": {"embedding": {"vector": embedding, "k": limit}}
},
}
},
}
response = client.search(index=self.index_name, body=query)
search_results = []
for i, hit in enumerate(response["hits"]["hits"]):
source = hit["_source"]
score = hit["_score"]
# Normalize score to 0-1 range (OpenSearch scores can vary)
similarity_score = min(score / 10.0, 1.0)
if similarity_score >= similarity_threshold:
memory = ToolMemory(
memory_id=source["memory_id"],
question=source["question"],
tool_name=source["tool_name"],
args=source["args"],
timestamp=source.get("timestamp"),
success=source.get("success", True),
metadata=source.get("metadata", {}),
)
search_results.append(
ToolMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories."""
def _get_recent():
client = self._get_client()
query = {
"size": limit,
"query": {"match_all": {}},
"sort": [{"timestamp": {"order": "desc"}}],
}
response = client.search(index=self.index_name, body=query)
memories = []
for hit in response["hits"]["hits"]:
source = hit["_source"]
memory = ToolMemory(
memory_id=source["memory_id"],
question=source["question"],
tool_name=source["tool_name"],
args=source["args"],
timestamp=source.get("timestamp"),
success=source.get("success", True),
metadata=source.get("metadata", {}),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID."""
def _delete():
client = self._get_client()
try:
client.delete(index=self.index_name, id=memory_id, refresh=True)
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
client = self._get_client()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(content)
document = {
"memory_id": memory_id,
"content": content,
"timestamp": timestamp,
"is_text_memory": True,
"embedding": embedding,
}
client.index(
index=self.index_name, body=document, id=memory_id, refresh=True
)
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
client = self._get_client()
embedding = self._create_embedding(query)
query_body = {
"size": limit,
"query": {
"bool": {
"must": [{"term": {"is_text_memory": True}}],
"filter": {
"knn": {"embedding": {"vector": embedding, "k": limit}}
},
}
},
}
response = client.search(index=self.index_name, body=query_body)
search_results = []
for i, hit in enumerate(response["hits"]["hits"]):
source = hit["_source"]
score = hit["_score"]
similarity_score = min(score / 10.0, 1.0)
if similarity_score >= similarity_threshold:
memory = TextMemory(
memory_id=source["memory_id"],
content=source.get("content", ""),
timestamp=source.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
client = self._get_client()
query = {
"size": limit,
"query": {"term": {"is_text_memory": True}},
"sort": [{"timestamp": {"order": "desc"}}],
}
response = client.search(index=self.index_name, body=query)
memories = []
for hit in response["hits"]["hits"]:
source = hit["_source"]
memory = TextMemory(
memory_id=source["memory_id"],
content=source.get("content", ""),
timestamp=source.get("timestamp"),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
client = self._get_client()
try:
client.delete(index=self.index_name, id=memory_id, refresh=True)
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
client = self._get_client()
# Build query
must_conditions = []
if tool_name:
must_conditions.append({"term": {"tool_name": tool_name}})
if before_date:
must_conditions.append({"range": {"timestamp": {"lt": before_date}}})
if must_conditions:
query = {"query": {"bool": {"must": must_conditions}}}
else:
query = {"query": {"match_all": {}}}
response = client.delete_by_query(
index=self.index_name, body=query, refresh=True
)
return response.get("deleted", 0)
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/opensearch/agent_memory.py",
"license": "MIT License",
"lines": 330,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/oracle/sql_runner.py | """Oracle implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class OracleRunner(SqlRunner):
"""Oracle implementation of the SqlRunner interface."""
def __init__(self, user: str, password: str, dsn: str, **kwargs):
"""Initialize with Oracle connection parameters.
Args:
user: Oracle database user name
password: Oracle database user password
dsn: Oracle database host - format: host:port/sid
**kwargs: Additional oracledb connection parameters
"""
try:
import oracledb
self.oracledb = oracledb
except ImportError as e:
raise ImportError(
"oracledb package is required. Install with: pip install 'vanna[oracle]'"
) from e
self.user = user
self.password = password
self.dsn = dsn
self.kwargs = kwargs
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against Oracle database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
oracledb.Error: If query execution fails
"""
# Connect to the database
conn = self.oracledb.connect(
user=self.user, password=self.password, dsn=self.dsn, **self.kwargs
)
cursor = conn.cursor()
try:
# Strip and remove trailing semicolons (Oracle doesn't like them)
sql = args.sql.rstrip()
if sql.endswith(";"):
sql = sql[:-1]
# Execute the query
cursor.execute(sql)
results = cursor.fetchall()
# Create a pandas dataframe from the results
df = pd.DataFrame(results, columns=[desc[0] for desc in cursor.description])
return df
except self.oracledb.Error:
conn.rollback()
raise
finally:
cursor.close()
conn.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/oracle/sql_runner.py",
"license": "MIT License",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/pinecone/agent_memory.py | """
Pinecone vector database implementation of AgentMemory.
This implementation uses Pinecone for cloud-based vector storage of tool usage patterns.
"""
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
from pinecone import Pinecone, ServerlessSpec
PINECONE_AVAILABLE = True
except ImportError:
PINECONE_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class PineconeAgentMemory(AgentMemory):
"""Pinecone-based implementation of AgentMemory."""
def __init__(
self,
api_key: str,
index_name: str = "tool-memories",
environment: str = "us-east-1",
dimension: int = 384,
metric: str = "cosine",
):
if not PINECONE_AVAILABLE:
raise ImportError(
"Pinecone is required for PineconeAgentMemory. Install with: pip install pinecone-client"
)
self.api_key = api_key
self.index_name = index_name
self.environment = environment
self.dimension = dimension
self.metric = metric
self._client = None
self._index = None
self._executor = ThreadPoolExecutor(max_workers=2)
def _get_client(self):
"""Get or create Pinecone client."""
if self._client is None:
self._client = Pinecone(api_key=self.api_key)
return self._client
def _get_index(self):
"""Get or create Pinecone index."""
if self._index is None:
client = self._get_client()
# Create index if it doesn't exist
if self.index_name not in client.list_indexes().names():
client.create_index(
name=self.index_name,
dimension=self.dimension,
metric=self.metric,
spec=ServerlessSpec(cloud="aws", region=self.environment),
)
self._index = client.Index(self.index_name)
return self._index
def _create_embedding(self, text: str) -> List[float]:
"""Create a simple embedding from text (placeholder - should use actual embedding model)."""
# TODO: Replace with actual embedding model
import hashlib
hash_val = int(hashlib.md5(text.encode()).hexdigest(), 16)
return [(hash_val >> i) % 100 / 100.0 for i in range(self.dimension)]
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
index = self._get_index()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(question)
# Pinecone metadata must be simple types
memory_metadata = {
"question": question,
"tool_name": tool_name,
"args_json": json.dumps(args),
"timestamp": timestamp,
"success": success,
"metadata_json": json.dumps(metadata or {}),
}
index.upsert(vectors=[(memory_id, embedding, memory_metadata)])
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
index = self._get_index()
embedding = self._create_embedding(question)
# Build filter
filter_dict = {"success": True}
if tool_name_filter:
filter_dict["tool_name"] = tool_name_filter
results = index.query(
vector=embedding, top_k=limit, filter=filter_dict, include_metadata=True
)
search_results = []
for i, match in enumerate(results.matches):
# Pinecone returns similarity score directly
similarity_score = match.score
if similarity_score >= similarity_threshold:
metadata = match.metadata
args = json.loads(metadata.get("args_json", "{}"))
metadata_dict = json.loads(metadata.get("metadata_json", "{}"))
memory = ToolMemory(
memory_id=match.id,
question=metadata["question"],
tool_name=metadata["tool_name"],
args=args,
timestamp=metadata.get("timestamp"),
success=metadata.get("success", True),
metadata=metadata_dict,
)
search_results.append(
ToolMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories."""
def _get_recent():
index = self._get_index()
# Pinecone doesn't have a native "get all" - we need to query with a dummy vector
# or use the list operation with metadata filtering
# This is a limitation - we'll return empty for now
# In production, you'd maintain a separate timestamp index or use Pinecone's metadata filtering
return []
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID."""
def _delete():
index = self._get_index()
try:
index.delete(ids=[memory_id])
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
index = self._get_index()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(content)
memory_metadata = {
"content": content,
"timestamp": timestamp,
"is_text_memory": True,
}
index.upsert(vectors=[(memory_id, embedding, memory_metadata)])
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
index = self._get_index()
embedding = self._create_embedding(query)
filter_dict = {"is_text_memory": True}
results = index.query(
vector=embedding, top_k=limit, filter=filter_dict, include_metadata=True
)
search_results = []
for i, match in enumerate(results.matches):
similarity_score = match.score
if similarity_score >= similarity_threshold:
metadata = match.metadata
memory = TextMemory(
memory_id=match.id,
content=metadata.get("content", ""),
timestamp=metadata.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
# Pinecone doesn't have a native "get all sorted by timestamp" operation
# This is a limitation - returning empty list
# In production, you'd need to maintain a separate index or use metadata filtering
return []
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
index = self._get_index()
try:
index.delete(ids=[memory_id])
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
index = self._get_index()
# Build filter
filter_dict = {}
if tool_name:
filter_dict["tool_name"] = tool_name
if before_date:
filter_dict["timestamp"] = {"$lt": before_date}
if filter_dict:
# Delete with filter
index.delete(filter=filter_dict)
else:
# Delete all
index.delete(delete_all=True)
# Pinecone doesn't return count of deleted items
return 0
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/pinecone/agent_memory.py",
"license": "MIT License",
"lines": 258,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/plotly/chart_generator.py | """Plotly-based chart generator with automatic chart type selection."""
from typing import Dict, Any, List, cast
import json
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
class PlotlyChartGenerator:
"""Generate Plotly charts using heuristics based on DataFrame characteristics."""
# Vanna brand colors from landing page
THEME_COLORS = {
"navy": "#023d60",
"cream": "#e7e1cf",
"teal": "#15a8a8",
"orange": "#fe5d26",
"magenta": "#bf1363",
}
# Color palette for charts (excluding cream as it's too light for data)
COLOR_PALETTE = ["#15a8a8", "#fe5d26", "#bf1363", "#023d60"]
def generate_chart(self, df: pd.DataFrame, title: str = "Chart") -> Dict[str, Any]:
"""Generate a Plotly chart based on DataFrame shape and types.
Heuristics:
- 4+ columns: table
- 1 numeric column: histogram
- 2 columns (1 categorical, 1 numeric): bar chart
- 2 numeric columns: scatter plot
- 3+ numeric columns: correlation heatmap or multi-line chart
- Time series data: line chart
- Multiple categorical: grouped bar chart
Args:
df: DataFrame to visualize
title: Title for the chart
Returns:
Plotly figure as dictionary
Raises:
ValueError: If DataFrame is empty or cannot be visualized
"""
if df.empty:
raise ValueError("Cannot visualize empty DataFrame")
# Heuristic: If 4 or more columns, render as a table
if len(df.columns) >= 4:
fig = self._create_table(df, title)
result: Dict[str, Any] = json.loads(pio.to_json(fig))
return result
# Identify column types
numeric_cols = df.select_dtypes(include=["number"]).columns.tolist()
categorical_cols = df.select_dtypes(
include=["object", "category"]
).columns.tolist()
datetime_cols = df.select_dtypes(include=["datetime64"]).columns.tolist()
# Check for time series
is_timeseries = len(datetime_cols) > 0
# Apply heuristics
if is_timeseries and len(numeric_cols) > 0:
# Time series line chart
fig = self._create_time_series_chart(
df, datetime_cols[0], numeric_cols, title
)
elif len(numeric_cols) == 1 and len(categorical_cols) == 0:
# Single numeric column: histogram
fig = self._create_histogram(df, numeric_cols[0], title)
elif len(numeric_cols) == 1 and len(categorical_cols) == 1:
# One categorical, one numeric: bar chart
fig = self._create_bar_chart(
df, categorical_cols[0], numeric_cols[0], title
)
elif len(numeric_cols) == 2:
# Two numeric columns: scatter plot
fig = self._create_scatter_plot(df, numeric_cols[0], numeric_cols[1], title)
elif len(numeric_cols) >= 3:
# Multiple numeric columns: correlation heatmap
fig = self._create_correlation_heatmap(df, numeric_cols, title)
elif len(categorical_cols) >= 2:
# Multiple categorical: grouped bar chart
fig = self._create_grouped_bar_chart(df, categorical_cols, title)
else:
# Fallback: show first two columns as scatter/bar
if len(df.columns) >= 2:
fig = self._create_generic_chart(
df, df.columns[0], df.columns[1], title
)
else:
raise ValueError(
"Cannot determine appropriate visualization for this DataFrame"
)
# Convert to JSON-serializable dict using plotly's JSON encoder
result = json.loads(pio.to_json(fig))
return result
def _apply_standard_layout(self, fig: go.Figure) -> go.Figure:
"""Apply consistent Vanna brand styling to all charts.
Uses Vanna brand colors from the landing page for a cohesive look.
Args:
fig: Plotly figure to update
Returns:
Updated figure with Vanna brand styling
"""
fig.update_layout(
# paper_bgcolor='white',
# plot_bgcolor='white',
font={"color": self.THEME_COLORS["navy"]}, # Navy for text
autosize=True, # Allow chart to resize responsively
colorway=self.COLOR_PALETTE, # Use Vanna brand colors for data
# Don't set width/height - let frontend handle sizing
)
return fig
def _create_histogram(self, df: pd.DataFrame, column: str, title: str) -> go.Figure:
"""Create a histogram for a single numeric column."""
fig = px.histogram(
df,
x=column,
title=title,
color_discrete_sequence=[self.THEME_COLORS["teal"]],
)
fig.update_layout(xaxis_title=column, yaxis_title="Count", showlegend=False)
self._apply_standard_layout(fig)
return fig
def _create_bar_chart(
self, df: pd.DataFrame, x_col: str, y_col: str, title: str
) -> go.Figure:
"""Create a bar chart for categorical vs numeric data."""
# Aggregate if needed
agg_df = df.groupby(x_col)[y_col].sum().reset_index()
fig = px.bar(
agg_df,
x=x_col,
y=y_col,
title=title,
color_discrete_sequence=[self.THEME_COLORS["orange"]],
)
fig.update_layout(xaxis_title=x_col, yaxis_title=y_col)
self._apply_standard_layout(fig)
return fig
def _create_scatter_plot(
self, df: pd.DataFrame, x_col: str, y_col: str, title: str
) -> go.Figure:
"""Create a scatter plot for two numeric columns."""
fig = px.scatter(
df,
x=x_col,
y=y_col,
title=title,
color_discrete_sequence=[self.THEME_COLORS["magenta"]],
)
fig.update_layout(xaxis_title=x_col, yaxis_title=y_col)
self._apply_standard_layout(fig)
return fig
def _create_correlation_heatmap(
self, df: pd.DataFrame, columns: List[str], title: str
) -> go.Figure:
"""Create a correlation heatmap for multiple numeric columns."""
corr_matrix = df[columns].corr()
# Custom Vanna color scale: navy (negative) -> cream (neutral) -> teal (positive)
vanna_colorscale = [
[0.0, self.THEME_COLORS["navy"]],
[0.5, self.THEME_COLORS["cream"]],
[1.0, self.THEME_COLORS["teal"]],
]
fig = cast(
go.Figure,
px.imshow(
corr_matrix,
title=title,
labels=dict(color="Correlation"),
x=columns,
y=columns,
color_continuous_scale=vanna_colorscale,
zmin=-1,
zmax=1,
),
)
self._apply_standard_layout(fig)
return fig
def _create_time_series_chart(
self, df: pd.DataFrame, time_col: str, value_cols: List[str], title: str
) -> go.Figure:
"""Create a time series line chart."""
fig = go.Figure()
for i, col in enumerate(value_cols[:5]): # Limit to 5 lines for readability
color = self.COLOR_PALETTE[i % len(self.COLOR_PALETTE)]
fig.add_trace(
go.Scatter(
x=df[time_col],
y=df[col],
mode="lines",
name=col,
line=dict(color=color),
)
)
fig.update_layout(
title=title,
xaxis_title=time_col,
yaxis_title="Value",
hovermode="x unified",
)
self._apply_standard_layout(fig)
return fig
def _create_grouped_bar_chart(
self, df: pd.DataFrame, categorical_cols: List[str], title: str
) -> go.Figure:
"""Create a grouped bar chart for multiple categorical columns."""
# Use first two categorical columns
if len(categorical_cols) >= 2:
# Count occurrences
grouped = df.groupby(categorical_cols[:2]).size().reset_index(name="count")
fig = px.bar(
grouped,
x=categorical_cols[0],
y="count",
color=categorical_cols[1],
title=title,
barmode="group",
color_discrete_sequence=self.COLOR_PALETTE,
)
self._apply_standard_layout(fig)
return fig
else:
# Single categorical: value counts
counts = df[categorical_cols[0]].value_counts().reset_index()
counts.columns = [categorical_cols[0], "count"]
fig = px.bar(
counts,
x=categorical_cols[0],
y="count",
title=title,
color_discrete_sequence=[self.THEME_COLORS["teal"]],
)
self._apply_standard_layout(fig)
return fig
def _create_generic_chart(
self, df: pd.DataFrame, col1: str, col2: str, title: str
) -> go.Figure:
"""Create a generic chart for any two columns."""
# Try to determine the best representation
if pd.api.types.is_numeric_dtype(df[col1]) and pd.api.types.is_numeric_dtype(
df[col2]
):
return self._create_scatter_plot(df, col1, col2, title)
else:
# Treat first as categorical, second as value
fig = px.bar(
df,
x=col1,
y=col2,
title=title,
color_discrete_sequence=[self.THEME_COLORS["orange"]],
)
self._apply_standard_layout(fig)
return fig
def _create_table(self, df: pd.DataFrame, title: str) -> go.Figure:
"""Create a Plotly table for DataFrames with 4 or more columns."""
# Prepare header
header_values = list(df.columns)
# Prepare cell values (transpose to get columns)
cell_values = [df[col].tolist() for col in df.columns]
# Create the table
fig = go.Figure(
data=[
go.Table(
header=dict(
values=header_values,
fill_color=self.THEME_COLORS["navy"],
font=dict(color="white", size=12),
align="left",
),
cells=dict(
values=cell_values,
fill_color=[
[
self.THEME_COLORS["cream"] if i % 2 == 0 else "white"
for i in range(len(df))
]
],
font=dict(color=self.THEME_COLORS["navy"], size=11),
align="left",
),
)
]
)
fig.update_layout(title=title, font={"color": self.THEME_COLORS["navy"]})
return fig
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/plotly/chart_generator.py",
"license": "MIT License",
"lines": 280,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/postgres/sql_runner.py | """PostgreSQL implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class PostgresRunner(SqlRunner):
"""PostgreSQL implementation of the SqlRunner interface."""
def __init__(
self,
connection_string: Optional[str] = None,
host: Optional[str] = None,
port: Optional[int] = 5432,
database: Optional[str] = None,
user: Optional[str] = None,
password: Optional[str] = None,
**kwargs,
):
"""Initialize with PostgreSQL connection parameters.
You can either provide a connection_string OR individual parameters (host, database, etc.).
If connection_string is provided, it takes precedence.
Args:
connection_string: PostgreSQL connection string (e.g., "postgresql://user:password@host:port/database")
host: Database host address
port: Database port (default: 5432)
database: Database name
user: Database user
password: Database password
**kwargs: Additional psycopg2 connection parameters (sslmode, connect_timeout, etc.)
"""
try:
import psycopg2
import psycopg2.extras
self.psycopg2 = psycopg2
except Exception as e:
raise ImportError(
"psycopg2 package is required. Install with: pip install 'vanna[postgres]'"
) from e
if connection_string:
self.connection_string = connection_string
self.connection_params = None
elif host and database and user:
self.connection_string = None
self.connection_params = {
"host": host,
"port": port,
"database": database,
"user": user,
"password": password,
**kwargs,
}
else:
raise ValueError(
"Either provide connection_string OR (host, database, and user) parameters"
)
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against PostgreSQL database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
psycopg2.Error: If query execution fails
"""
# Connect to the database using either connection string or parameters
if self.connection_string:
conn = self.psycopg2.connect(self.connection_string)
else:
conn = self.psycopg2.connect(**self.connection_params)
cursor = conn.cursor(cursor_factory=self.psycopg2.extras.RealDictCursor)
try:
# Execute the query
cursor.execute(args.sql)
# Determine if this is a SELECT query or modification query
query_type = args.sql.strip().upper().split()[0]
if query_type == "SELECT":
# Fetch results for SELECT queries
rows = cursor.fetchall()
if not rows:
# Return empty DataFrame
return pd.DataFrame()
# Convert rows to list of dictionaries
results_data = [dict(row) for row in rows]
return pd.DataFrame(results_data)
else:
# For non-SELECT queries (INSERT, UPDATE, DELETE, etc.)
conn.commit()
rows_affected = cursor.rowcount
# Return a DataFrame indicating rows affected
return pd.DataFrame({"rows_affected": [rows_affected]})
finally:
cursor.close()
conn.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/postgres/sql_runner.py",
"license": "MIT License",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/premium/agent_memory/premium.py | """
Cloud-based implementation of AgentMemory.
This implementation uses Vanna's premium cloud service for storing and searching
tool usage patterns with advanced similarity search and analytics.
"""
import json
from datetime import datetime
from typing import Any, Dict, List, Optional
import httpx
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class CloudAgentMemory(AgentMemory):
"""Cloud-based implementation of AgentMemory."""
def __init__(
self,
api_base_url: str = "https://api.vanna.ai",
api_key: Optional[str] = None,
organization_id: Optional[str] = None,
):
self.api_base_url = api_base_url.rstrip("/")
self.api_key = api_key
self.organization_id = organization_id
self._client = httpx.AsyncClient(base_url=self.api_base_url, timeout=30.0)
def _get_headers(self) -> Dict[str, str]:
"""Get request headers with authentication."""
headers = {"Content-Type": "application/json"}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
if self.organization_id:
headers["X-Organization-ID"] = self.organization_id
return headers
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern to premium cloud storage."""
import uuid
payload = {
"id": str(uuid.uuid4()),
"question": question,
"tool_name": tool_name,
"args": args,
"success": success,
"metadata": metadata or {},
"timestamp": datetime.now().isoformat(),
}
response = await self._client.post(
"/memory/tool-usage", json=payload, headers=self._get_headers()
)
response.raise_for_status()
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns in premium cloud storage."""
params = {
"question": question,
"limit": limit,
"similarity_threshold": similarity_threshold,
}
if tool_name_filter:
params["tool_name_filter"] = tool_name_filter
response = await self._client.get(
"/memory/search-similar", params=params, headers=self._get_headers()
)
response.raise_for_status()
data = response.json()
results = []
for item in data.get("results", []):
memory = ToolMemory(**item["memory"])
result = ToolMemorySearchResult(
memory=memory,
similarity_score=item["similarity_score"],
rank=item["rank"],
)
results.append(result)
return results
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories from premium cloud storage."""
params = {"limit": limit}
response = await self._client.get(
"/memory/recent", params=params, headers=self._get_headers()
)
response.raise_for_status()
data = response.json()
memories = []
for item in data.get("memories", []):
memory = ToolMemory(**item)
memories.append(memory)
return memories
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID from premium cloud storage."""
response = await self._client.delete(
f"/memory/{memory_id}", headers=self._get_headers()
)
if response.status_code == 404:
return False
response.raise_for_status()
return True
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Cloud implementation does not yet support text memories."""
raise NotImplementedError("CloudAgentMemory does not support text memories.")
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Cloud implementation does not yet support text memories."""
return []
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Cloud implementation does not yet support text memories."""
return []
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Cloud implementation does not yet support text memories."""
return False
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories from premium cloud storage."""
payload = {}
if tool_name:
payload["tool_name"] = tool_name
if before_date:
payload["before_date"] = before_date
response = await self._client.delete(
"/memory/clear", json=payload, headers=self._get_headers()
)
response.raise_for_status()
data = response.json()
return data.get("deleted_count", 0)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/premium/agent_memory/premium.py",
"license": "MIT License",
"lines": 156,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/presto/sql_runner.py | """Presto implementation of SqlRunner interface."""
from typing import Optional
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class PrestoRunner(SqlRunner):
"""Presto implementation of the SqlRunner interface."""
def __init__(
self,
host: str,
catalog: str = "hive",
schema: str = "default",
user: Optional[str] = None,
password: Optional[str] = None,
port: int = 443,
combined_pem_path: Optional[str] = None,
protocol: str = "https",
requests_kwargs: Optional[dict] = None,
**kwargs,
):
"""Initialize with Presto connection parameters.
Args:
host: The host address of the Presto database
catalog: The catalog to use in the Presto environment (default: 'hive')
schema: The schema to use in the Presto environment (default: 'default')
user: The username for authentication
password: The password for authentication
port: The port number for the Presto connection (default: 443)
combined_pem_path: The path to the combined pem file for SSL connection
protocol: The protocol to use for the connection (default: 'https')
requests_kwargs: Additional keyword arguments for requests
**kwargs: Additional pyhive connection parameters
"""
try:
from pyhive import presto
self.presto = presto
except ImportError as e:
raise ImportError(
"pyhive package is required. Install with: pip install pyhive"
) from e
self.host = host
self.catalog = catalog
self.schema = schema
self.user = user
self.password = password
self.port = port
self.protocol = protocol
self.kwargs = kwargs
# Set up requests_kwargs for SSL if combined_pem_path is provided
if requests_kwargs is None and combined_pem_path is not None:
self.requests_kwargs = {"verify": combined_pem_path}
else:
self.requests_kwargs = requests_kwargs
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against Presto database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
presto.Error: If query execution fails
"""
# Connect to the database
conn = self.presto.Connection(
host=self.host,
username=self.user,
password=self.password,
catalog=self.catalog,
schema=self.schema,
port=self.port,
protocol=self.protocol,
requests_kwargs=self.requests_kwargs,
**self.kwargs,
)
try:
# Strip and remove trailing semicolons (Presto doesn't like them)
sql = args.sql.rstrip()
if sql.endswith(";"):
sql = sql[:-1]
cursor = conn.cursor()
cursor.execute(sql)
results = cursor.fetchall()
# Create a pandas dataframe from the results
df = pd.DataFrame(results, columns=[desc[0] for desc in cursor.description])
cursor.close()
return df
finally:
conn.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/presto/sql_runner.py",
"license": "MIT License",
"lines": 89,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/qdrant/agent_memory.py | """
Qdrant vector database implementation of AgentMemory.
This implementation uses Qdrant for vector storage of tool usage patterns.
"""
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
from qdrant_client import QdrantClient
from qdrant_client.models import (
Distance,
VectorParams,
PointStruct,
Filter,
FieldCondition,
MatchValue,
)
QDRANT_AVAILABLE = True
except ImportError:
QDRANT_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class QdrantAgentMemory(AgentMemory):
"""Qdrant-based implementation of AgentMemory."""
def __init__(
self,
collection_name: str = "tool_memories",
url: Optional[str] = None,
path: Optional[str] = None,
api_key: Optional[str] = None,
dimension: int = 384,
):
if not QDRANT_AVAILABLE:
raise ImportError(
"Qdrant is required for QdrantAgentMemory. Install with: pip install qdrant-client"
)
self.collection_name = collection_name
self.url = url
self.path = path
self.api_key = api_key
self.dimension = dimension
self._client = None
self._executor = ThreadPoolExecutor(max_workers=2)
def _get_client(self):
"""Get or create Qdrant client."""
if self._client is None:
if self.url:
self._client = QdrantClient(url=self.url, api_key=self.api_key)
else:
self._client = QdrantClient(path=self.path or ":memory:")
# Create collection if it doesn't exist
collections = self._client.get_collections().collections
if not any(c.name == self.collection_name for c in collections):
self._client.create_collection(
collection_name=self.collection_name,
vectors_config=VectorParams(
size=self.dimension, distance=Distance.COSINE
),
)
return self._client
def _create_embedding(self, text: str) -> List[float]:
"""Create a simple embedding from text (placeholder)."""
import hashlib
hash_val = int(hashlib.md5(text.encode()).hexdigest(), 16)
return [(hash_val >> i) % 100 / 100.0 for i in range(self.dimension)]
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
client = self._get_client()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(question)
payload = {
"question": question,
"tool_name": tool_name,
"args": args,
"timestamp": timestamp,
"success": success,
"metadata": metadata or {},
}
point = PointStruct(id=memory_id, vector=embedding, payload=payload)
client.upsert(collection_name=self.collection_name, points=[point])
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
client = self._get_client()
embedding = self._create_embedding(question)
# Build filter
query_filter = None
conditions = [FieldCondition(key="success", match=MatchValue(value=True))]
if tool_name_filter:
conditions.append(
FieldCondition(
key="tool_name", match=MatchValue(value=tool_name_filter)
)
)
if conditions:
query_filter = Filter(must=conditions)
# Use query_points for newer qdrant-client (1.8.0+) or search for older versions
if hasattr(client, "query_points"):
results = client.query_points(
collection_name=self.collection_name,
query=embedding,
limit=limit,
query_filter=query_filter,
score_threshold=similarity_threshold,
).points
else:
# Fallback to search method for older qdrant-client versions
results = client.search(
collection_name=self.collection_name,
query_vector=embedding,
limit=limit,
query_filter=query_filter,
score_threshold=similarity_threshold,
)
search_results = []
for i, hit in enumerate(results):
payload = hit.payload
memory = ToolMemory(
memory_id=str(hit.id),
question=payload["question"],
tool_name=payload["tool_name"],
args=payload["args"],
timestamp=payload.get("timestamp"),
success=payload.get("success", True),
metadata=payload.get("metadata", {}),
)
search_results.append(
ToolMemorySearchResult(
memory=memory, similarity_score=hit.score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories."""
def _get_recent():
client = self._get_client()
# Scroll through all points and sort by timestamp
points, _ = client.scroll(
collection_name=self.collection_name,
limit=1000, # Get more than we need to sort
with_payload=True,
with_vectors=False,
)
# Sort by timestamp
sorted_points = sorted(
points, key=lambda p: p.payload.get("timestamp", ""), reverse=True
)
memories = []
for point in sorted_points[:limit]:
payload = point.payload
# Skip text memories - they have is_text_memory flag
if payload.get("is_text_memory"):
continue
memory = ToolMemory(
memory_id=str(point.id),
question=payload["question"],
tool_name=payload["tool_name"],
args=payload["args"],
timestamp=payload.get("timestamp"),
success=payload.get("success", True),
metadata=payload.get("metadata", {}),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID. Returns True if deleted, False if not found."""
def _delete():
client = self._get_client()
try:
# Check if the point exists before attempting to delete
points = client.retrieve(
collection_name=self.collection_name,
ids=[memory_id],
with_payload=False,
with_vectors=False,
)
if points and len(points) > 0:
client.delete(
collection_name=self.collection_name,
points_selector=[memory_id],
)
return True
return False
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
client = self._get_client()
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(content)
payload = {
"content": content,
"timestamp": timestamp,
"is_text_memory": True,
}
point = PointStruct(id=memory_id, vector=embedding, payload=payload)
client.upsert(collection_name=self.collection_name, points=[point])
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
client = self._get_client()
embedding = self._create_embedding(query)
query_filter = Filter(
must=[
FieldCondition(key="is_text_memory", match=MatchValue(value=True))
]
)
# Use query_points for newer qdrant-client (1.8.0+) or search for older versions
if hasattr(client, "query_points"):
results = client.query_points(
collection_name=self.collection_name,
query=embedding,
limit=limit,
query_filter=query_filter,
score_threshold=similarity_threshold,
).points
else:
# Fallback to search method for older qdrant-client versions
results = client.search(
collection_name=self.collection_name,
query_vector=embedding,
limit=limit,
query_filter=query_filter,
score_threshold=similarity_threshold,
)
search_results = []
for i, hit in enumerate(results):
payload = hit.payload
memory = TextMemory(
memory_id=str(hit.id),
content=payload.get("content", ""),
timestamp=payload.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory, similarity_score=hit.score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
client = self._get_client()
# Scroll through text memory points and sort by timestamp
points, _ = client.scroll(
collection_name=self.collection_name,
scroll_filter=Filter(
must=[
FieldCondition(
key="is_text_memory", match=MatchValue(value=True)
)
]
),
limit=1000,
with_payload=True,
with_vectors=False,
)
# Sort by timestamp
sorted_points = sorted(
points, key=lambda p: p.payload.get("timestamp", ""), reverse=True
)
memories = []
for point in sorted_points[:limit]:
payload = point.payload
memory = TextMemory(
memory_id=str(point.id),
content=payload.get("content", ""),
timestamp=payload.get("timestamp"),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
client = self._get_client()
try:
# Check if the point exists before attempting to delete
points = client.retrieve(
collection_name=self.collection_name,
ids=[memory_id],
with_payload=False,
with_vectors=False,
)
if points and len(points) > 0:
client.delete(
collection_name=self.collection_name,
points_selector=[memory_id],
)
return True
return False
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
client = self._get_client()
# Build filter
conditions = []
if tool_name:
conditions.append(
FieldCondition(key="tool_name", match=MatchValue(value=tool_name))
)
if before_date:
conditions.append(
FieldCondition(key="timestamp", match=MatchValue(value=before_date))
)
if conditions or (tool_name is None and before_date is None):
# Delete with filter or delete all
query_filter = Filter(must=conditions) if conditions else None
if query_filter:
client.delete(
collection_name=self.collection_name,
points_selector=query_filter,
)
else:
# Delete all points
client.delete_collection(collection_name=self.collection_name)
# Recreate empty collection
client.create_collection(
collection_name=self.collection_name,
vectors_config=VectorParams(
size=self.dimension, distance=Distance.COSINE
),
)
return 0 # Qdrant doesn't return count
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/qdrant/agent_memory.py",
"license": "MIT License",
"lines": 384,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/snowflake/sql_runner.py | """Snowflake implementation of SqlRunner interface."""
from typing import Optional, Union
import os
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class SnowflakeRunner(SqlRunner):
"""Snowflake implementation of the SqlRunner interface."""
def __init__(
self,
account: str,
username: str,
password: Optional[str] = None,
database: str = "",
role: Optional[str] = None,
warehouse: Optional[str] = None,
private_key_path: Optional[str] = None,
private_key_passphrase: Optional[str] = None,
private_key_content: Optional[bytes] = None,
**kwargs,
):
"""Initialize with Snowflake connection parameters.
Args:
account: Snowflake account identifier
username: Database user
password: Database password (optional if using key-pair auth)
database: Database name
role: Snowflake role to use (optional)
warehouse: Snowflake warehouse to use (optional)
private_key_path: Path to private key file for RSA key-pair authentication (optional)
private_key_passphrase: Passphrase for encrypted private key (optional)
private_key_content: Private key content as bytes (optional, alternative to private_key_path)
**kwargs: Additional snowflake.connector connection parameters
Note:
Either password OR private_key_path/private_key_content must be provided.
RSA key-pair authentication is recommended for production systems as Snowflake
is deprecating user/password authentication.
"""
try:
import snowflake.connector
self.snowflake = snowflake.connector
except ImportError as e:
raise ImportError(
"snowflake-connector-python package is required. "
"Install with: pip install 'vanna[snowflake]'"
) from e
# Validate that at least one authentication method is provided
if not password and not private_key_path and not private_key_content:
raise ValueError(
"Either password or private_key_path/private_key_content must be provided for authentication"
)
# Validate private key path exists if provided
if private_key_path and not os.path.isfile(private_key_path):
raise FileNotFoundError(f"Private key file not found: {private_key_path}")
self.account = account
self.username = username
self.password = password
self.database = database
self.role = role
self.warehouse = warehouse
self.private_key_path = private_key_path
self.private_key_passphrase = private_key_passphrase
self.private_key_content = private_key_content
self.kwargs = kwargs
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against Snowflake database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
snowflake.connector.Error: If query execution fails
"""
# Build connection parameters
conn_params = {
"user": self.username,
"account": self.account,
"client_session_keep_alive": True,
}
# Add database if specified
if self.database:
conn_params["database"] = self.database
# Configure authentication method
if self.private_key_path or self.private_key_content:
# Use RSA key-pair authentication
if self.private_key_path:
conn_params["private_key_path"] = self.private_key_path
else:
conn_params["private_key_content"] = self.private_key_content
# Add passphrase if provided
if self.private_key_passphrase:
conn_params["private_key_passphrase"] = self.private_key_passphrase
else:
# Use password authentication (fallback)
conn_params["password"] = self.password
# Add any additional kwargs
conn_params.update(self.kwargs)
# Connect to the database
conn = self.snowflake.connect(**conn_params)
cursor = conn.cursor()
try:
# Set role if specified
if self.role:
cursor.execute(f"USE ROLE {self.role}")
# Set warehouse if specified
if self.warehouse:
cursor.execute(f"USE WAREHOUSE {self.warehouse}")
# Use the specified database if provided
if self.database:
cursor.execute(f"USE DATABASE {self.database}")
# Execute the query
cursor.execute(args.sql)
results = cursor.fetchall()
# Create a pandas dataframe from the results
df = pd.DataFrame(results, columns=[desc[0] for desc in cursor.description])
return df
finally:
cursor.close()
conn.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/snowflake/sql_runner.py",
"license": "MIT License",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/integrations/sqlite/sql_runner.py | """SQLite implementation of SqlRunner interface."""
import sqlite3
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class SqliteRunner(SqlRunner):
"""SQLite implementation of the SqlRunner interface."""
def __init__(self, database_path: str):
"""Initialize with a SQLite database path.
Args:
database_path: Path to the SQLite database file
"""
self.database_path = database_path
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query against SQLite database and return results as DataFrame.
Args:
args: SQL query arguments
context: Tool execution context
Returns:
DataFrame with query results
Raises:
sqlite3.Error: If query execution fails
"""
# Connect to the database
conn = sqlite3.connect(self.database_path)
conn.row_factory = sqlite3.Row # Enable column access by name
cursor = conn.cursor()
try:
# Execute the query
cursor.execute(args.sql)
# Determine if this is a SELECT query or modification query
query_type = args.sql.strip().upper().split()[0]
if query_type == "SELECT":
# Fetch results for SELECT queries
rows = cursor.fetchall()
if not rows:
# Return empty DataFrame
return pd.DataFrame()
# Convert rows to list of dictionaries
results_data = [dict(row) for row in rows]
return pd.DataFrame(results_data)
else:
# For non-SELECT queries (INSERT, UPDATE, DELETE, etc.)
conn.commit()
rows_affected = cursor.rowcount
# Return a DataFrame indicating rows affected
return pd.DataFrame({"rows_affected": [rows_affected]})
finally:
cursor.close()
conn.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/sqlite/sql_runner.py",
"license": "MIT License",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/integrations/weaviate/agent_memory.py | """
Weaviate vector database implementation of AgentMemory.
This implementation uses Weaviate for semantic search and storage of tool usage patterns.
"""
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
import weaviate
from weaviate.classes.config import (
Configure,
Property,
DataType as WeaviateDataType,
)
WEAVIATE_AVAILABLE = True
except ImportError:
WEAVIATE_AVAILABLE = False
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class WeaviateAgentMemory(AgentMemory):
"""Weaviate-based implementation of AgentMemory."""
def __init__(
self,
collection_name: str = "ToolMemory",
url: str = "http://localhost:8080",
api_key: Optional[str] = None,
dimension: int = 384,
):
if not WEAVIATE_AVAILABLE:
raise ImportError(
"Weaviate is required for WeaviateAgentMemory. Install with: pip install weaviate-client"
)
self.collection_name = collection_name
self.url = url
self.api_key = api_key
self.dimension = dimension
self._client = None
self._executor = ThreadPoolExecutor(max_workers=2)
def _get_client(self):
"""Get or create Weaviate client."""
if self._client is None:
if self.api_key:
self._client = weaviate.connect_to_weaviate_cloud(
cluster_url=self.url,
auth_credentials=weaviate.auth.AuthApiKey(self.api_key),
)
else:
self._client = weaviate.connect_to_local(
host=self.url.replace("http://", "").replace("https://", "")
)
# Create collection if it doesn't exist
if not self._client.collections.exists(self.collection_name):
self._client.collections.create(
name=self.collection_name,
vectorizer_config=Configure.Vectorizer.none(),
properties=[
Property(name="question", data_type=WeaviateDataType.TEXT),
Property(name="tool_name", data_type=WeaviateDataType.TEXT),
Property(name="args_json", data_type=WeaviateDataType.TEXT),
Property(name="timestamp", data_type=WeaviateDataType.TEXT),
Property(name="success", data_type=WeaviateDataType.BOOL),
Property(name="metadata_json", data_type=WeaviateDataType.TEXT),
],
)
return self._client
def _create_embedding(self, text: str) -> List[float]:
"""Create a simple embedding from text (placeholder)."""
import hashlib
hash_val = int(hashlib.md5(text.encode()).hexdigest(), 16)
return [(hash_val >> i) % 100 / 100.0 for i in range(self.dimension)]
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern."""
def _save():
client = self._get_client()
collection = client.collections.get(self.collection_name)
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(question)
properties = {
"question": question,
"tool_name": tool_name,
"args_json": json.dumps(args),
"timestamp": timestamp,
"success": success,
"metadata_json": json.dumps(metadata or {}),
}
collection.data.insert(
properties=properties, vector=embedding, uuid=memory_id
)
await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns."""
def _search():
client = self._get_client()
collection = client.collections.get(self.collection_name)
embedding = self._create_embedding(question)
# Build filter
filters = weaviate.classes.query.Filter.by_property("success").equal(True)
if tool_name_filter:
filters = filters & weaviate.classes.query.Filter.by_property(
"tool_name"
).equal(tool_name_filter)
response = collection.query.near_vector(
near_vector=embedding,
limit=limit,
filters=filters,
return_metadata=weaviate.classes.query.MetadataQuery(distance=True),
)
search_results = []
for i, obj in enumerate(response.objects):
# Weaviate returns distance, convert to similarity
distance = obj.metadata.distance if obj.metadata else 1.0
similarity_score = 1 - distance
if similarity_score >= similarity_threshold:
properties = obj.properties
args = json.loads(properties.get("args_json", "{}"))
metadata_dict = json.loads(properties.get("metadata_json", "{}"))
memory = ToolMemory(
memory_id=str(obj.uuid),
question=properties.get("question"),
tool_name=properties.get("tool_name"),
args=args,
timestamp=properties.get("timestamp"),
success=properties.get("success", True),
metadata=metadata_dict,
)
search_results.append(
ToolMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories."""
def _get_recent():
client = self._get_client()
collection = client.collections.get(self.collection_name)
# Query and sort by timestamp
response = collection.query.fetch_objects(limit=1000)
# Convert to list and sort
objects_list = list(response.objects)
sorted_objects = sorted(
objects_list,
key=lambda o: o.properties.get("timestamp", ""),
reverse=True,
)
memories = []
for obj in sorted_objects[:limit]:
properties = obj.properties
args = json.loads(properties.get("args_json", "{}"))
metadata_dict = json.loads(properties.get("metadata_json", "{}"))
memory = ToolMemory(
memory_id=str(obj.uuid),
question=properties.get("question"),
tool_name=properties.get("tool_name"),
args=args,
timestamp=properties.get("timestamp"),
success=properties.get("success", True),
metadata=metadata_dict,
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID."""
def _delete():
client = self._get_client()
collection = client.collections.get(self.collection_name)
try:
collection.data.delete_by_id(uuid=memory_id)
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save a text memory."""
def _save():
client = self._get_client()
collection = client.collections.get(self.collection_name)
memory_id = str(uuid.uuid4())
timestamp = datetime.now().isoformat()
embedding = self._create_embedding(content)
properties = {
"question": content, # Using question field for content
"tool_name": "", # Empty for text memories
"args_json": "",
"timestamp": timestamp,
"success": True,
"metadata_json": json.dumps({"is_text_memory": True}),
}
collection.data.insert(
properties=properties, vector=embedding, uuid=memory_id
)
return TextMemory(memory_id=memory_id, content=content, timestamp=timestamp)
return await asyncio.get_event_loop().run_in_executor(self._executor, _save)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search for similar text memories."""
def _search():
client = self._get_client()
collection = client.collections.get(self.collection_name)
embedding = self._create_embedding(query)
# Build filter for text memories (empty tool_name)
filters = weaviate.classes.query.Filter.by_property("tool_name").equal("")
response = collection.query.near_vector(
near_vector=embedding,
limit=limit,
filters=filters,
return_metadata=weaviate.classes.query.MetadataQuery(distance=True),
)
search_results = []
for i, obj in enumerate(response.objects):
distance = obj.metadata.distance if obj.metadata else 1.0
similarity_score = 1 - distance
if similarity_score >= similarity_threshold:
properties = obj.properties
content = properties.get("question", "")
memory = TextMemory(
memory_id=str(obj.uuid),
content=content,
timestamp=properties.get("timestamp"),
)
search_results.append(
TextMemorySearchResult(
memory=memory, similarity_score=similarity_score, rank=i + 1
)
)
return search_results
return await asyncio.get_event_loop().run_in_executor(self._executor, _search)
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Get recently added text memories."""
def _get_recent():
client = self._get_client()
collection = client.collections.get(self.collection_name)
# Query text memories (empty tool_name) and sort by timestamp
response = collection.query.fetch_objects(
filters=weaviate.classes.query.Filter.by_property("tool_name").equal(
""
),
limit=1000,
)
# Convert to list and sort
objects_list = list(response.objects)
sorted_objects = sorted(
objects_list,
key=lambda o: o.properties.get("timestamp", ""),
reverse=True,
)
memories = []
for obj in sorted_objects[:limit]:
properties = obj.properties
content = properties.get("question", "")
memory = TextMemory(
memory_id=str(obj.uuid),
content=content,
timestamp=properties.get("timestamp"),
)
memories.append(memory)
return memories
return await asyncio.get_event_loop().run_in_executor(
self._executor, _get_recent
)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID."""
def _delete():
client = self._get_client()
collection = client.collections.get(self.collection_name)
try:
collection.data.delete_by_id(uuid=memory_id)
return True
except Exception:
return False
return await asyncio.get_event_loop().run_in_executor(self._executor, _delete)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories."""
def _clear():
client = self._get_client()
collection = client.collections.get(self.collection_name)
# Build filter
if tool_name and before_date:
filters = weaviate.classes.query.Filter.by_property("tool_name").equal(
tool_name
) & weaviate.classes.query.Filter.by_property("timestamp").less_than(
before_date
)
elif tool_name:
filters = weaviate.classes.query.Filter.by_property("tool_name").equal(
tool_name
)
elif before_date:
filters = weaviate.classes.query.Filter.by_property(
"timestamp"
).less_than(before_date)
else:
filters = None
if filters:
collection.data.delete_many(where=filters)
else:
# Delete all
collection.data.delete_many(
where=weaviate.classes.query.Filter.by_property(
"success"
).contains_any([True, False])
)
return 0
return await asyncio.get_event_loop().run_in_executor(self._executor, _clear)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/integrations/weaviate/agent_memory.py",
"license": "MIT License",
"lines": 349,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/legacy/adapter.py | """
Legacy VannaBase adapter for the Vanna Agents framework.
This module provides a LegacyVannaAdapter that bridges legacy VannaBase objects
with the new ToolRegistry system by auto-registering legacy methods as tools
with appropriate group-based access control.
"""
from typing import Any, Dict, List, Optional
import pandas as pd
from ..capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from ..capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from ..core.registry import ToolRegistry
from ..core.tool import Tool, ToolContext, ToolResult
from ..core.user import User
from ..tools.agent_memory import (
SaveQuestionToolArgsTool,
SearchSavedCorrectToolUsesTool,
)
from ..tools.run_sql import RunSqlTool
from .base.base import VannaBase
class LegacySqlRunner(SqlRunner):
"""SqlRunner implementation that wraps a legacy VannaBase instance.
This class bridges the new SqlRunner interface with legacy VannaBase
run_sql methods, allowing legacy database connections to work with
the new tool-based architecture.
"""
def __init__(self, vn: VannaBase):
"""Initialize with a legacy VannaBase instance.
Args:
vn: The legacy VannaBase instance with an initialized run_sql method
"""
self.vn = vn
async def run_sql(self, args: RunSqlToolArgs, context: ToolContext) -> pd.DataFrame:
"""Execute SQL query using the legacy VannaBase run_sql method.
Args:
args: SQL query arguments containing the SQL string
context: Tool execution context (not used by legacy implementation)
Returns:
DataFrame with query results
Raises:
Exception: If query execution fails
"""
# Call the legacy VannaBase run_sql method
# The legacy method is synchronous, so we call it directly
return self.vn.run_sql(args.sql)
class LegacyVannaAdapter(ToolRegistry, AgentMemory):
"""Adapter that wraps a legacy VannaBase object and exposes its methods as tools.
This adapter automatically registers specific VannaBase methods as tools in the
registry with configurable group-based access control. This allows legacy Vanna
instances to work seamlessly with the new Agents framework.
Features:
- Auto-registers legacy methods as tools
- Configurable group-based permissions ('user', 'admin', etc.)
- Seamless integration with ToolRegistry
- Implements AgentMemory interface
- Preserves legacy VannaBase functionality
Example:
```python
from vanna.legacy.base import VannaBase
from vanna.legacy.adapter import LegacyVannaAdapter
# Initialize your legacy Vanna instance
vn = VannaBase(config={"model": "gpt-4"})
vn.connect_to_postgres(...)
# Create adapter and auto-register tools
adapter = LegacyVannaAdapter(vn)
# Tools are now available through the registry
schemas = await adapter.get_schemas(user)
```
"""
def __init__(
self,
vn: VannaBase,
audit_logger: Optional[Any] = None,
audit_config: Optional[Any] = None,
) -> None:
"""Initialize the adapter with a legacy VannaBase instance.
Args:
vanna: The legacy VannaBase instance to wrap
audit_logger: Optional audit logger for tool execution tracking
audit_config: Optional audit configuration
"""
ToolRegistry.__init__(
self, audit_logger=audit_logger, audit_config=audit_config
)
self.vn = vn
self._register_tools()
def _register_tools(self) -> None:
"""Register legacy VannaBase methods as tools with appropriate permissions.
Registers the following tools:
- RunSqlTool: Wraps the legacy run_sql method via LegacySqlRunner
- SaveQuestionToolArgsTool: Wraps add_question_sql via LegacyAgentMemory
- SearchSavedCorrectToolUsesTool: Wraps get_similar_question_sql via LegacyAgentMemory
"""
# Create a LegacySqlRunner to wrap the VannaBase run_sql method
sql_runner = LegacySqlRunner(self.vn)
# Register the RunSqlTool with user and admin access
run_sql_tool = RunSqlTool(sql_runner)
self.register_local_tool(run_sql_tool, access_groups=["user", "admin"])
# Register memory tools using the internal _agent_memory instance
# SaveQuestionToolArgsTool - for saving question-tool-args patterns (admin only)
save_memory_tool = SaveQuestionToolArgsTool()
self.register_local_tool(save_memory_tool, access_groups=["admin"])
# SearchSavedCorrectToolUsesTool - for searching similar patterns (user and admin)
search_memory_tool = SearchSavedCorrectToolUsesTool()
self.register_local_tool(search_memory_tool, access_groups=["user", "admin"])
# AgentMemory interface implementation
async def save_tool_usage(
self,
question: str,
tool_name: str,
args: Dict[str, Any],
context: ToolContext,
success: bool = True,
metadata: Optional[Dict[str, Any]] = None,
) -> None:
"""Save a tool usage pattern by storing it as a question-sql pair.
Args:
question: The user question
tool_name: Name of the tool that was used
args: Arguments passed to the tool
context: Tool execution context (not used by legacy implementation)
success: Whether the tool execution was successful
metadata: Additional metadata (not used by legacy implementation)
"""
# For legacy compatibility, we primarily care about SQL queries
# Extract SQL from args if this was a run_sql tool
if tool_name == "run_sql" and "sql" in args:
sql = args["sql"]
# Call the legacy add_question_sql method
# The legacy method is synchronous, so we call it directly
self.vn.add_question_sql(question=question, sql=sql)
async def search_similar_usage(
self,
question: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
tool_name_filter: Optional[str] = None,
) -> List[ToolMemorySearchResult]:
"""Search for similar tool usage patterns using legacy question-sql lookup.
Args:
question: The question to search for
context: Tool execution context (not used by legacy implementation)
limit: Maximum number of results (not directly supported by legacy)
similarity_threshold: Minimum similarity score (not directly supported by legacy)
tool_name_filter: Filter by tool name (not directly supported by legacy)
Returns:
List of memory search results with similar question-sql pairs
"""
# Call the legacy get_similar_question_sql method
similar_results = self.vn.get_similar_question_sql(question=question)
# Convert legacy results to ToolMemorySearchResult format
memory_results = []
for idx, result in enumerate(similar_results):
# Legacy results are typically dicts with 'question' and 'sql' keys
if isinstance(result, dict) and "question" in result and "sql" in result:
tool_memory = ToolMemory(
memory_id=None, # Legacy doesn't provide IDs
question=result["question"],
tool_name="run_sql",
args={"sql": result["sql"]},
success=True,
)
# Assign a simple rank-based similarity score
# Legacy system doesn't provide actual similarity scores
similarity_score = 1.0 - (idx * 0.1) # Decreasing score by rank
similarity_score = max(similarity_score, 0.0)
memory_results.append(
ToolMemorySearchResult(
memory=tool_memory,
similarity_score=similarity_score,
rank=idx + 1,
)
)
return memory_results[:limit]
async def save_text_memory(self, content: str, context: ToolContext) -> TextMemory:
"""Save text memory using legacy add_documentation method.
Args:
content: The documentation content to save
context: Tool execution context (not used by legacy implementation)
Returns:
TextMemory object with the saved content
"""
# Call the legacy add_documentation method
# The legacy method is synchronous, so we call it directly
doc_id = self.vn.add_documentation(documentation=content)
return TextMemory(
memory_id=doc_id,
content=content,
timestamp=None, # Legacy doesn't provide timestamps
)
async def search_text_memories(
self,
query: str,
context: ToolContext,
*,
limit: int = 10,
similarity_threshold: float = 0.7,
) -> List[TextMemorySearchResult]:
"""Search text memories using legacy get_related_documentation method.
Args:
query: The query to search for
context: Tool execution context (not used by legacy implementation)
limit: Maximum number of results (not directly supported by legacy)
similarity_threshold: Minimum similarity score (not directly supported by legacy)
Returns:
List of text memory search results
"""
# Call the legacy get_related_documentation method
related_docs = self.vn.get_related_documentation(question=query)
# Convert legacy results to TextMemorySearchResult format
memory_results = []
for idx, doc in enumerate(related_docs):
# Legacy results are typically strings or dicts
if isinstance(doc, str):
content = doc
doc_id = None
elif isinstance(doc, dict):
content = str(doc.get("documentation", doc.get("content", str(doc))))
doc_id = doc.get("id")
else:
content = str(doc)
doc_id = None
# Create TextMemory object
text_memory = TextMemory(
memory_id=doc_id,
content=content,
timestamp=None, # Legacy doesn't provide timestamps
)
# Assign a simple rank-based similarity score
# Legacy system doesn't provide actual similarity scores
similarity_score = 1.0 - (idx * 0.1) # Decreasing score by rank
similarity_score = max(similarity_score, 0.0)
if similarity_score >= similarity_threshold:
memory_results.append(
TextMemorySearchResult(
memory=text_memory,
similarity_score=similarity_score,
rank=idx + 1,
)
)
return memory_results[:limit]
async def get_recent_memories(
self, context: ToolContext, limit: int = 10
) -> List[ToolMemory]:
"""Get recently added memories.
Note: Legacy VannaBase does not provide a direct way to get recent memories,
so we retrieve using a blank string which typically returns the most relevant
or recent items from the vector store.
Args:
context: Tool execution context
limit: Maximum number of memories to return
Returns:
List of recently added tool memories
"""
# Use blank string retrieval to get recent/relevant memories
similar_results = self.vn.get_similar_question_sql(question="")
# Convert legacy results to ToolMemory format
memories = []
for idx, result in enumerate(similar_results[:limit]):
# Legacy results are typically dicts with 'question' and 'sql' keys
if isinstance(result, dict) and "question" in result and "sql" in result:
tool_memory = ToolMemory(
memory_id=None, # Legacy doesn't provide IDs
question=result["question"],
tool_name="run_sql",
args={"sql": result["sql"]},
success=True,
)
memories.append(tool_memory)
return memories
async def get_recent_text_memories(
self, context: ToolContext, limit: int = 10
) -> List[TextMemory]:
"""Fetch recently stored text memories.
Note: Legacy VannaBase does not provide a direct way to get recent text memories,
so we retrieve using a blank string which typically returns the most relevant
or recent items from the vector store.
Args:
context: Tool execution context
limit: Maximum number of memories to return
Returns:
List of recently added text memories
"""
# Use blank string retrieval to get recent/relevant documentation
related_docs = self.vn.get_related_documentation(question="")
# Convert legacy results to TextMemory format
memories = []
for doc in related_docs[:limit]:
# Legacy results are typically strings or dicts
if isinstance(doc, str):
content = doc
doc_id = None
elif isinstance(doc, dict):
content = str(doc.get("documentation", doc.get("content", str(doc))))
doc_id = doc.get("id")
else:
content = str(doc)
doc_id = None
# Create TextMemory object
text_memory = TextMemory(
memory_id=doc_id,
content=content,
timestamp=None, # Legacy doesn't provide timestamps
)
memories.append(text_memory)
return memories
async def delete_by_id(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a memory by its ID using legacy remove_training_data method.
Args:
context: Tool execution context
memory_id: ID of the memory to delete
Returns:
True if the memory was deleted, False otherwise
"""
# Call the legacy remove_training_data method
# The legacy method is synchronous, so we call it directly
return self.vn.remove_training_data(id=memory_id)
async def delete_text_memory(self, context: ToolContext, memory_id: str) -> bool:
"""Delete a text memory by its ID using legacy remove_training_data method.
Args:
context: Tool execution context
memory_id: ID of the text memory to delete
Returns:
True if the text memory was deleted, False otherwise
"""
# Call the legacy remove_training_data method
# The legacy method is synchronous, so we call it directly
return self.vn.remove_training_data(id=memory_id)
async def clear_memories(
self,
context: ToolContext,
tool_name: Optional[str] = None,
before_date: Optional[str] = None,
) -> int:
"""Clear stored memories.
Note: Legacy VannaBase does not provide a direct clear method,
so this operation is not supported.
Args:
context: Tool execution context
tool_name: Optional tool name filter
before_date: Optional date filter
Returns:
0 (operation not supported by legacy)
"""
return 0
# Example stub for a tool wrapper (to be expanded)
# You can copy and customize this pattern for each tool you want to expose
"""
class ExampleTool(Tool[ExampleToolArgs]):
def __init__(self, vanna: VannaBase):
self.vanna = vanna
@property
def name(self) -> str:
return "example_tool"
@property
def description(self) -> str:
return "Example tool description"
@property
def access_groups(self) -> List[str]:
# This is optional - will be overridden by register_local_tool
return []
def get_args_schema(self) -> type[ExampleToolArgs]:
return ExampleToolArgs
async def execute(
self,
context: ToolContext,
args: ExampleToolArgs
) -> ToolResult:
# Call the legacy VannaBase method
result = self.vanna.example_method(args.param1, args.param2)
return ToolResult(
success=True,
result_for_llm=result,
ui_component=None,
)
"""
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/adapter.py",
"license": "MIT License",
"lines": 383,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
vanna-ai/vanna:src/vanna/legacy/mock/vectordb.py | import pandas as pd
from ..base import VannaBase
class MockVectorDB(VannaBase):
def __init__(self, config=None):
pass
def _get_id(self, value: str, **kwargs) -> str:
# Hash the value and return the ID
return str(hash(value))
def add_ddl(self, ddl: str, **kwargs) -> str:
return self._get_id(ddl)
def add_documentation(self, doc: str, **kwargs) -> str:
return self._get_id(doc)
def add_question_sql(self, question: str, sql: str, **kwargs) -> str:
return self._get_id(question)
def get_related_ddl(self, question: str, **kwargs) -> list:
return []
def get_related_documentation(self, question: str, **kwargs) -> list:
return []
def get_similar_question_sql(self, question: str, **kwargs) -> list:
return []
def get_training_data(self, **kwargs) -> pd.DataFrame:
return pd.DataFrame(
{
"id": {
0: "19546-ddl",
1: "91597-sql",
2: "133976-sql",
3: "59851-doc",
4: "73046-sql",
},
"training_data_type": {
0: "ddl",
1: "sql",
2: "sql",
3: "documentation",
4: "sql",
},
"question": {
0: None,
1: "What are the top selling genres?",
2: "What are the low 7 artists by sales?",
3: None,
4: "What is the total sales for each customer?",
},
"content": {
0: "CREATE TABLE [Invoice]\n(\n [InvoiceId] INTEGER NOT NULL,\n [CustomerId] INTEGER NOT NULL,\n [InvoiceDate] DATETIME NOT NULL,\n [BillingAddress] NVARCHAR(70),\n [BillingCity] NVARCHAR(40),\n [BillingState] NVARCHAR(40),\n [BillingCountry] NVARCHAR(40),\n [BillingPostalCode] NVARCHAR(10),\n [Total] NUMERIC(10,2) NOT NULL,\n CONSTRAINT [PK_Invoice] PRIMARY KEY ([InvoiceId]),\n FOREIGN KEY ([CustomerId]) REFERENCES [Customer] ([CustomerId]) \n\t\tON DELETE NO ACTION ON UPDATE NO ACTION\n)",
1: "SELECT g.Name AS Genre, SUM(il.Quantity) AS TotalSales\nFROM Genre g\nJOIN Track t ON g.GenreId = t.GenreId\nJOIN InvoiceLine il ON t.TrackId = il.TrackId\nGROUP BY g.GenreId, g.Name\nORDER BY TotalSales DESC;",
2: "SELECT a.ArtistId, a.Name, SUM(il.Quantity) AS TotalSales\nFROM Artist a\nINNER JOIN Album al ON a.ArtistId = al.ArtistId\nINNER JOIN Track t ON al.AlbumId = t.AlbumId\nINNER JOIN InvoiceLine il ON t.TrackId = il.TrackId\nGROUP BY a.ArtistId, a.Name\nORDER BY TotalSales ASC\nLIMIT 7;",
3: "This is a SQLite database. For dates rememeber to use SQLite syntax.",
4: "SELECT c.CustomerId, c.FirstName, c.LastName, SUM(i.Total) AS TotalSales\nFROM Customer c\nJOIN Invoice i ON c.CustomerId = i.CustomerId\nGROUP BY c.CustomerId, c.FirstName, c.LastName;",
},
}
)
def remove_training_data(id: str, **kwargs) -> bool:
return True
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/mock/vectordb.py",
"license": "MIT License",
"lines": 55,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/legacy/ollama/ollama.py | import json
import re
from httpx import Timeout
from ..base import VannaBase
from ..exceptions import DependencyError
class Ollama(VannaBase):
def __init__(self, config=None):
try:
ollama = __import__("ollama")
except ImportError:
raise DependencyError(
"You need to install required dependencies to execute this method, run command:"
" \npip install ollama"
)
if not config:
raise ValueError("config must contain at least Ollama model")
if "model" not in config.keys():
raise ValueError("config must contain at least Ollama model")
self.host = config.get("ollama_host", "http://localhost:11434")
self.model = config["model"]
if ":" not in self.model:
self.model += ":latest"
self.ollama_timeout = config.get("ollama_timeout", 240.0)
self.ollama_client = ollama.Client(
self.host, timeout=Timeout(self.ollama_timeout)
)
self.keep_alive = config.get("keep_alive", None)
self.ollama_options = config.get("options", {})
self.num_ctx = self.ollama_options.get("num_ctx", 2048)
self.__pull_model_if_ne(self.ollama_client, self.model)
@staticmethod
def __pull_model_if_ne(ollama_client, model):
model_response = ollama_client.list()
model_lists = [
model_element["model"] for model_element in model_response.get("models", [])
]
if model not in model_lists:
ollama_client.pull(model)
def system_message(self, message: str) -> any:
return {"role": "system", "content": message}
def user_message(self, message: str) -> any:
return {"role": "user", "content": message}
def assistant_message(self, message: str) -> any:
return {"role": "assistant", "content": message}
def extract_sql(self, llm_response):
"""
Extracts the first SQL statement after the word 'select', ignoring case,
matches until the first semicolon, three backticks, or the end of the string,
and removes three backticks if they exist in the extracted string.
Args:
- llm_response (str): The string to search within for an SQL statement.
Returns:
- str: The first SQL statement found, with three backticks removed, or an empty string if no match is found.
"""
# Remove ollama-generated extra characters
llm_response = llm_response.replace("\\_", "_")
llm_response = llm_response.replace("\\", "")
# Regular expression to find ```sql' and capture until '```'
sql = re.search(r"```sql\n((.|\n)*?)(?=;|\[|```)", llm_response, re.DOTALL)
# Regular expression to find 'select, with (ignoring case) and capture until ';', [ (this happens in case of mistral) or end of string
select_with = re.search(
r"(select|(with.*?as \())(.*?)(?=;|\[|```)",
llm_response,
re.IGNORECASE | re.DOTALL,
)
if sql:
self.log(f"Output from LLM: {llm_response} \nExtracted SQL: {sql.group(1)}")
return sql.group(1).replace("```", "")
elif select_with:
self.log(
f"Output from LLM: {llm_response} \nExtracted SQL: {select_with.group(0)}"
)
return select_with.group(0)
else:
return llm_response
def submit_prompt(self, prompt, **kwargs) -> str:
self.log(
f"Ollama parameters:\n"
f"model={self.model},\n"
f"options={self.ollama_options},\n"
f"keep_alive={self.keep_alive}"
)
self.log(f"Prompt Content:\n{json.dumps(prompt, ensure_ascii=False)}")
response_dict = self.ollama_client.chat(
model=self.model,
messages=prompt,
stream=False,
options=self.ollama_options,
keep_alive=self.keep_alive,
)
self.log(f"Ollama Response:\n{str(response_dict)}")
return response_dict["message"]["content"]
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/ollama/ollama.py",
"license": "MIT License",
"lines": 92,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/legacy/opensearch/opensearch_vector.py | import base64
import uuid
from typing import List
import pandas as pd
from opensearchpy import OpenSearch
from ..base import VannaBase
class OpenSearch_VectorStore(VannaBase):
def __init__(self, config=None):
VannaBase.__init__(self, config=config)
document_index = "vanna_document_index"
ddl_index = "vanna_ddl_index"
question_sql_index = "vanna_questions_sql_index"
if config is not None and "es_document_index" in config:
document_index = config["es_document_index"]
if config is not None and "es_ddl_index" in config:
ddl_index = config["es_ddl_index"]
if config is not None and "es_question_sql_index" in config:
question_sql_index = config["es_question_sql_index"]
self.document_index = document_index
self.ddl_index = ddl_index
self.question_sql_index = question_sql_index
print(
"OpenSearch_VectorStore initialized with document_index: ",
document_index,
" ddl_index: ",
ddl_index,
" question_sql_index: ",
question_sql_index,
)
document_index_settings = {
"settings": {"index": {"number_of_shards": 6, "number_of_replicas": 2}},
"mappings": {
"properties": {
"question": {
"type": "text",
},
"doc": {
"type": "text",
},
}
},
}
ddl_index_settings = {
"settings": {"index": {"number_of_shards": 6, "number_of_replicas": 2}},
"mappings": {
"properties": {
"ddl": {
"type": "text",
},
"doc": {
"type": "text",
},
}
},
}
question_sql_index_settings = {
"settings": {"index": {"number_of_shards": 6, "number_of_replicas": 2}},
"mappings": {
"properties": {
"question": {
"type": "text",
},
"sql": {
"type": "text",
},
}
},
}
if config is not None and "es_document_index_settings" in config:
document_index_settings = config["es_document_index_settings"]
if config is not None and "es_ddl_index_settings" in config:
ddl_index_settings = config["es_ddl_index_settings"]
if config is not None and "es_question_sql_index_settings" in config:
question_sql_index_settings = config["es_question_sql_index_settings"]
self.document_index_settings = document_index_settings
self.ddl_index_settings = ddl_index_settings
self.question_sql_index_settings = question_sql_index_settings
es_urls = None
if config is not None and "es_urls" in config:
es_urls = config["es_urls"]
# Host and port
if config is not None and "es_host" in config:
host = config["es_host"]
else:
host = "localhost"
if config is not None and "es_port" in config:
port = config["es_port"]
else:
port = 9200
if config is not None and "es_ssl" in config:
ssl = config["es_ssl"]
else:
ssl = False
if config is not None and "es_verify_certs" in config:
verify_certs = config["es_verify_certs"]
else:
verify_certs = False
# Authentication
if config is not None and "es_user" in config:
auth = (config["es_user"], config["es_password"])
else:
# Default to admin:admin
auth = None
headers = None
# base64 authentication
if (
config is not None
and "es_encoded_base64" in config
and "es_user" in config
and "es_password" in config
):
if config["es_encoded_base64"]:
encoded_credentials = base64.b64encode(
(config["es_user"] + ":" + config["es_password"]).encode("utf-8")
).decode("utf-8")
headers = {"Authorization": "Basic " + encoded_credentials}
# remove auth from config
auth = None
# custom headers
if config is not None and "es_headers" in config:
headers = config["es_headers"]
if config is not None and "es_timeout" in config:
timeout = config["es_timeout"]
else:
timeout = 60
if config is not None and "es_max_retries" in config:
max_retries = config["es_max_retries"]
else:
max_retries = 10
if config is not None and "es_http_compress" in config:
es_http_compress = config["es_http_compress"]
else:
es_http_compress = False
print(
"OpenSearch_VectorStore initialized with es_urls: ",
es_urls,
" host: ",
host,
" port: ",
port,
" ssl: ",
ssl,
" verify_certs: ",
verify_certs,
" timeout: ",
timeout,
" max_retries: ",
max_retries,
)
if es_urls is not None:
# Initialize the OpenSearch client by passing a list of URLs
self.client = OpenSearch(
hosts=[es_urls],
http_compress=es_http_compress,
use_ssl=ssl,
verify_certs=verify_certs,
timeout=timeout,
max_retries=max_retries,
retry_on_timeout=True,
http_auth=auth,
headers=headers,
)
else:
# Initialize the OpenSearch client by passing a host and port
self.client = OpenSearch(
hosts=[{"host": host, "port": port}],
http_compress=es_http_compress,
use_ssl=ssl,
verify_certs=verify_certs,
timeout=timeout,
max_retries=max_retries,
retry_on_timeout=True,
http_auth=auth,
headers=headers,
)
print("OpenSearch_VectorStore initialized with client over ")
# 执行一个简单的查询来检查连接
try:
print("Connected to OpenSearch cluster:")
info = self.client.info()
print("OpenSearch cluster info:", info)
except Exception as e:
print("Error connecting to OpenSearch cluster:", e)
# Create the indices if they don't exist
self.create_index_if_not_exists(
self.document_index, self.document_index_settings
)
self.create_index_if_not_exists(self.ddl_index, self.ddl_index_settings)
self.create_index_if_not_exists(
self.question_sql_index, self.question_sql_index_settings
)
def create_index(self):
for index in [self.document_index, self.ddl_index, self.question_sql_index]:
try:
self.client.indices.create(index)
except Exception as e:
print("Error creating index: ", e)
print(f"opensearch index {index} already exists")
pass
def create_index_if_not_exists(self, index_name: str, index_settings: dict) -> bool:
try:
if not self.client.indices.exists(index_name):
print(f"Index {index_name} does not exist. Creating...")
self.client.indices.create(index=index_name, body=index_settings)
return True
else:
print(f"Index {index_name} already exists.")
return False
except Exception as e:
print(f"Error creating index: {index_name} ", e)
return False
def add_ddl(self, ddl: str, **kwargs) -> str:
# Assuming that you have a DDL index in your OpenSearch
id = str(uuid.uuid4()) + "-ddl"
ddl_dict = {"ddl": ddl}
response = self.client.index(
index=self.ddl_index, body=ddl_dict, id=id, **kwargs
)
return response["_id"]
def add_documentation(self, doc: str, **kwargs) -> str:
# Assuming you have a documentation index in your OpenSearch
id = str(uuid.uuid4()) + "-doc"
doc_dict = {"doc": doc}
response = self.client.index(
index=self.document_index, id=id, body=doc_dict, **kwargs
)
return response["_id"]
def add_question_sql(self, question: str, sql: str, **kwargs) -> str:
# Assuming you have a Questions and SQL index in your OpenSearch
id = str(uuid.uuid4()) + "-sql"
question_sql_dict = {"question": question, "sql": sql}
response = self.client.index(
index=self.question_sql_index, body=question_sql_dict, id=id, **kwargs
)
return response["_id"]
def get_related_ddl(self, question: str, **kwargs) -> List[str]:
# Assume you have some vector search mechanism associated with your data
query = {"query": {"match": {"ddl": question}}}
print(query)
response = self.client.search(index=self.ddl_index, body=query, **kwargs)
return [hit["_source"]["ddl"] for hit in response["hits"]["hits"]]
def get_related_documentation(self, question: str, **kwargs) -> List[str]:
query = {"query": {"match": {"doc": question}}}
print(query)
response = self.client.search(index=self.document_index, body=query, **kwargs)
return [hit["_source"]["doc"] for hit in response["hits"]["hits"]]
def get_similar_question_sql(self, question: str, **kwargs) -> List[str]:
query = {"query": {"match": {"question": question}}}
print(query)
response = self.client.search(
index=self.question_sql_index, body=query, **kwargs
)
return [
(hit["_source"]["question"], hit["_source"]["sql"])
for hit in response["hits"]["hits"]
]
def get_training_data(self, **kwargs) -> pd.DataFrame:
# This will be a simple example pulling all data from an index
# WARNING: Do not use this approach in production for large indices!
data = []
response = self.client.search(
index=self.document_index, body={"query": {"match_all": {}}}, size=1000
)
print(response)
# records = [hit['_source'] for hit in response['hits']['hits']]
for hit in response["hits"]["hits"]:
data.append(
{
"id": hit["_id"],
"training_data_type": "documentation",
"question": "",
"content": hit["_source"]["doc"],
}
)
response = self.client.search(
index=self.question_sql_index, body={"query": {"match_all": {}}}, size=1000
)
# records = [hit['_source'] for hit in response['hits']['hits']]
for hit in response["hits"]["hits"]:
data.append(
{
"id": hit["_id"],
"training_data_type": "sql",
"question": hit.get("_source", {}).get("question", ""),
"content": hit.get("_source", {}).get("sql", ""),
}
)
response = self.client.search(
index=self.ddl_index, body={"query": {"match_all": {}}}, size=1000
)
# records = [hit['_source'] for hit in response['hits']['hits']]
for hit in response["hits"]["hits"]:
data.append(
{
"id": hit["_id"],
"training_data_type": "ddl",
"question": "",
"content": hit["_source"]["ddl"],
}
)
return pd.DataFrame(data)
def remove_training_data(self, id: str, **kwargs) -> bool:
try:
if id.endswith("-sql"):
self.client.delete(index=self.question_sql_index, id=id)
return True
elif id.endswith("-ddl"):
self.client.delete(index=self.ddl_index, id=id, **kwargs)
return True
elif id.endswith("-doc"):
self.client.delete(index=self.document_index, id=id, **kwargs)
return True
else:
return False
except Exception as e:
print("Error deleting training dataError deleting training data: ", e)
return False
def generate_embedding(self, data: str, **kwargs) -> list[float]:
# opensearch doesn't need to generate embeddings
pass
# OpenSearch_VectorStore.__init__(self, config={'es_urls':
# "https://opensearch-node.test.com:9200", 'es_encoded_base64': True, 'es_user':
# "admin", 'es_password': "admin", 'es_verify_certs': True})
# OpenSearch_VectorStore.__init__(self, config={'es_host':
# "https://opensearch-node.test.com", 'es_port': 9200, 'es_user': "admin",
# 'es_password': "admin", 'es_verify_certs': True})
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/opensearch/opensearch_vector.py",
"license": "MIT License",
"lines": 326,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/legacy/opensearch/opensearch_vector_semantic.py | import json
import pandas as pd
from langchain_community.vectorstores import OpenSearchVectorSearch
from ..base import VannaBase
from ..utils import deterministic_uuid
class OpenSearch_Semantic_VectorStore(VannaBase):
def __init__(self, config=None):
VannaBase.__init__(self, config=config)
if config is None:
config = {}
if "embedding_function" in config:
self.embedding_function = config.get("embedding_function")
else:
from langchain_huggingface import HuggingFaceEmbeddings
self.embedding_function = HuggingFaceEmbeddings(
model_name="all-MiniLM-L6-v2"
)
self.n_results_sql = config.get("n_results_sql", config.get("n_results", 10))
self.n_results_documentation = config.get(
"n_results_documentation", config.get("n_results", 10)
)
self.n_results_ddl = config.get("n_results_ddl", config.get("n_results", 10))
self.document_index = config.get("es_document_index", "vanna_document_index")
self.ddl_index = config.get("es_ddl_index", "vanna_ddl_index")
self.question_sql_index = config.get(
"es_question_sql_index", "vanna_questions_sql_index"
)
self.log(
f"OpenSearch_Semantic_VectorStore initialized with document_index: {self.document_index}, ddl_index: {self.ddl_index}, question_sql_index: {self.question_sql_index}"
)
es_urls = config.get("es_urls", "https://localhost:9200")
ssl = config.get("es_ssl", True)
verify_certs = config.get("es_verify_certs", True)
if "es_user" in config:
auth = (config["es_user"], config["es_password"])
else:
auth = None
headers = config.get("es_headers", None)
timeout = config.get("es_timeout", 60)
max_retries = config.get("es_max_retries", 10)
common_args = {
"opensearch_url": es_urls,
"embedding_function": self.embedding_function,
"engine": "faiss",
"http_auth": auth,
"use_ssl": ssl,
"verify_certs": verify_certs,
"timeout": timeout,
"max_retries": max_retries,
"retry_on_timeout": True,
"headers": headers,
}
self.documentation_store = OpenSearchVectorSearch(
index_name=self.document_index, **common_args
)
self.ddl_store = OpenSearchVectorSearch(
index_name=self.ddl_index, **common_args
)
self.sql_store = OpenSearchVectorSearch(
index_name=self.question_sql_index, **common_args
)
def add_ddl(self, ddl: str, **kwargs) -> str:
_id = deterministic_uuid(ddl) + "-ddl"
self.ddl_store.add_texts(texts=[ddl], ids=[_id], **kwargs)
return _id
def add_documentation(self, documentation: str, **kwargs) -> str:
_id = deterministic_uuid(documentation) + "-doc"
self.documentation_store.add_texts(texts=[documentation], ids=[_id], **kwargs)
return _id
def add_question_sql(self, question: str, sql: str, **kwargs) -> str:
question_sql_json = json.dumps(
{
"question": question,
"sql": sql,
},
ensure_ascii=False,
)
_id = deterministic_uuid(question_sql_json) + "-sql"
self.sql_store.add_texts(texts=[question_sql_json], ids=[_id], **kwargs)
return _id
def get_related_ddl(self, question: str, **kwargs) -> list:
documents = self.ddl_store.similarity_search(
query=question, k=self.n_results_ddl
)
return [document.page_content for document in documents]
def get_related_documentation(self, question: str, **kwargs) -> list:
documents = self.documentation_store.similarity_search(
query=question, k=self.n_results_documentation
)
return [document.page_content for document in documents]
def get_similar_question_sql(self, question: str, **kwargs) -> list:
documents = self.sql_store.similarity_search(
query=question, k=self.n_results_sql
)
return [json.loads(document.page_content) for document in documents]
def get_training_data(self, **kwargs) -> pd.DataFrame:
data = []
query = {"query": {"match_all": {}}}
indices = [
{"index": self.document_index, "type": "documentation"},
{"index": self.question_sql_index, "type": "sql"},
{"index": self.ddl_index, "type": "ddl"},
]
# Use documentation_store.client consistently for search on all indices
opensearch_client = self.documentation_store.client
for index_info in indices:
index_name = index_info["index"]
training_data_type = index_info["type"]
scroll = "1m" # keep scroll context for 1 minute
response = opensearch_client.search(
index=index_name,
ignore_unavailable=True,
body=query,
scroll=scroll,
size=1000,
)
scroll_id = response.get("_scroll_id")
while scroll_id:
hits = response["hits"]["hits"]
if not hits:
break # No more hits, exit loop
for hit in hits:
source = hit["_source"]
if training_data_type == "sql":
try:
doc_dict = json.loads(source["text"])
content = doc_dict.get("sql")
question = doc_dict.get("question")
except json.JSONDecodeError as e:
self.log(
f"Skipping row with custom_id {hit['_id']} due to JSON parsing error: {e}",
"Error",
)
continue
else: # documentation or ddl
content = source["text"]
question = None
data.append(
{
"id": hit["_id"],
"training_data_type": training_data_type,
"question": question,
"content": content,
}
)
# Get next batch of results, using documentation_store.client.scroll
response = opensearch_client.scroll(scroll_id=scroll_id, scroll=scroll)
scroll_id = response.get("_scroll_id")
return pd.DataFrame(data)
def remove_training_data(self, id: str, **kwargs) -> bool:
try:
if id.endswith("-sql"):
return self.sql_store.delete(ids=[id], **kwargs)
elif id.endswith("-ddl"):
return self.ddl_store.delete(ids=[id], **kwargs)
elif id.endswith("-doc"):
return self.documentation_store.delete(ids=[id], **kwargs)
else:
return False
except Exception as e:
self.log(
f"Error deleting training dataError deleting training data: {e}",
"Error",
)
return False
def generate_embedding(self, data: str, **kwargs) -> list[float]:
pass
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/opensearch/opensearch_vector_semantic.py",
"license": "MIT License",
"lines": 167,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/legacy/oracle/oracle_vector.py | import json
import uuid
from typing import List, Optional, Tuple
import oracledb
import pandas as pd
from chromadb.utils import embedding_functions
from ..base import VannaBase
default_ef = embedding_functions.DefaultEmbeddingFunction()
class Oracle_VectorStore(VannaBase):
def __init__(self, config=None):
VannaBase.__init__(self, config=config)
if config is not None:
self.embedding_function = config.get("embedding_function", default_ef)
self.pre_delete_collection = config.get("pre_delete_collection", False)
self.cmetadata = config.get("cmetadata", {"created_by": "oracle"})
else:
self.embedding_function = default_ef
self.pre_delete_collection = False
self.cmetadata = {"created_by": "oracle"}
self.oracle_conn = oracledb.connect(dsn=config.get("dsn"))
self.oracle_conn.call_timeout = 30000
self.documentation_collection = "documentation"
self.ddl_collection = "ddl"
self.sql_collection = "sql"
self.n_results = config.get("n_results", 10)
self.n_results_ddl = config.get("n_results_ddl", self.n_results)
self.n_results_sql = config.get("n_results_sql", self.n_results)
self.n_results_documentation = config.get(
"n_results_documentation", self.n_results
)
self.create_tables_if_not_exists()
self.create_collections_if_not_exists(self.documentation_collection)
self.create_collections_if_not_exists(self.ddl_collection)
self.create_collections_if_not_exists(self.sql_collection)
def generate_embedding(self, data: str, **kwargs) -> List[float]:
embeddings = self.embedding_function([data])
if len(embeddings) == 1:
return list(embeddings[0].astype(float))
return list(embeddings.astype(float))
def add_question_sql(self, question: str, sql: str, **kwargs) -> str:
cmetadata = self.cmetadata.copy()
collection = self.get_collection(self.sql_collection)
question_sql_json = json.dumps(
{
"question": question,
"sql": sql,
},
ensure_ascii=False,
)
id = str(uuid.uuid4())
embeddings = self.generate_embedding(question)
custom_id = id + "-sql"
cursor = self.oracle_conn.cursor()
cursor.setinputsizes(None, oracledb.DB_TYPE_VECTOR)
cursor.execute(
"""
INSERT INTO oracle_embedding (
collection_id,
embedding,
document,
cmetadata,
custom_id,
uuid
) VALUES (
:1,
TO_VECTOR(:2),
:3,
:4,
:5,
:6
)
""",
[
collection["uuid"],
embeddings,
question_sql_json,
json.dumps(cmetadata),
custom_id,
id,
],
)
self.oracle_conn.commit()
cursor.close()
return id
def add_ddl(self, ddl: str, **kwargs) -> str:
collection = self.get_collection(self.ddl_collection)
question_ddl_json = json.dumps(
{
"question": None,
"ddl": ddl,
},
ensure_ascii=False,
)
id = str(uuid.uuid4())
custom_id = id + "-ddl"
cursor = self.oracle_conn.cursor()
cursor.setinputsizes(None, oracledb.DB_TYPE_VECTOR)
cursor.execute(
"""
INSERT INTO oracle_embedding (
collection_id,
embedding,
document,
cmetadata,
custom_id,
uuid
) VALUES (
:1,
TO_VECTOR(:2),
:3,
:4,
:5,
:6
)
""",
[
collection["uuid"],
self.generate_embedding(ddl),
question_ddl_json,
json.dumps(self.cmetadata),
custom_id,
id,
],
)
self.oracle_conn.commit()
cursor.close()
return id
def add_documentation(self, documentation: str, **kwargs) -> str:
collection = self.get_collection(self.documentation_collection)
question_documentation_json = json.dumps(
{
"question": None,
"documentation": documentation,
},
ensure_ascii=False,
)
id = str(uuid.uuid4())
custom_id = id + "-doc"
cursor = self.oracle_conn.cursor()
cursor.setinputsizes(None, oracledb.DB_TYPE_VECTOR)
cursor.execute(
"""
INSERT INTO oracle_embedding (
collection_id,
embedding,
document,
cmetadata,
custom_id,
uuid
) VALUES (
:1,
TO_VECTOR(:2),
:3,
:4,
:5,
:6
)
""",
[
collection["uuid"],
self.generate_embedding(documentation),
question_documentation_json,
json.dumps(self.cmetadata),
custom_id,
id,
],
)
self.oracle_conn.commit()
cursor.close()
return id
def get_training_data(self, **kwargs) -> pd.DataFrame:
df = pd.DataFrame()
cursor = self.oracle_conn.cursor()
sql_collection = self.get_collection(self.sql_collection)
cursor.execute(
"""
SELECT
document,
uuid
FROM oracle_embedding
WHERE
collection_id = :1
""",
[sql_collection["uuid"]],
)
sql_data = cursor.fetchall()
if sql_data is not None:
# Extract the documents and ids
documents = [row_data[0] for row_data in sql_data]
ids = [row_data[1] for row_data in sql_data]
# Create a DataFrame
df_sql = pd.DataFrame(
{
"id": ids,
"question": [
json.loads(doc)["question"]
if isinstance(doc, str)
else doc["question"]
for doc in documents
],
"content": [
json.loads(doc)["sql"] if isinstance(doc, str) else doc["sql"]
for doc in documents
],
}
)
df_sql["training_data_type"] = "sql"
df = pd.concat([df, df_sql])
ddl_collection = self.get_collection(self.ddl_collection)
cursor.execute(
"""
SELECT
document,
uuid
FROM oracle_embedding
WHERE
collection_id = :1
""",
[ddl_collection["uuid"]],
)
ddl_data = cursor.fetchall()
if ddl_data is not None:
# Extract the documents and ids
documents = [row_data[0] for row_data in ddl_data]
ids = [row_data[1] for row_data in ddl_data]
# Create a DataFrame
df_ddl = pd.DataFrame(
{
"id": ids,
"question": [None for _ in documents],
"content": [
json.loads(doc)["ddl"] if isinstance(doc, str) else doc["ddl"]
for doc in documents
],
}
)
df_ddl["training_data_type"] = "ddl"
df = pd.concat([df, df_ddl])
doc_collection = self.get_collection(self.documentation_collection)
cursor.execute(
"""
SELECT
document,
uuid
FROM oracle_embedding
WHERE
collection_id = :1
""",
[doc_collection["uuid"]],
)
doc_data = cursor.fetchall()
if doc_data is not None:
# Extract the documents and ids
documents = [row_data[0] for row_data in doc_data]
ids = [row_data[1] for row_data in doc_data]
# Create a DataFrame
df_doc = pd.DataFrame(
{
"id": ids,
"question": [None for _ in documents],
"content": [
json.loads(doc)["documentation"]
if isinstance(doc, str)
else doc["documentation"]
for doc in documents
],
}
)
df_doc["training_data_type"] = "documentation"
df = pd.concat([df, df_doc])
self.oracle_conn.commit()
cursor.close()
return df
def remove_training_data(self, id: str, **kwargs) -> bool:
cursor = self.oracle_conn.cursor()
cursor.execute(
"""
DELETE
FROM
oracle_embedding
WHERE
uuid = :1
""",
[id],
)
self.oracle_conn.commit()
cursor.close()
return True
def update_training_data(
self, id: str, train_type: str, question: str, **kwargs
) -> bool:
print(f"{train_type=}")
update_content = kwargs["content"]
if train_type == "sql":
update_json = json.dumps(
{
"question": question,
"sql": update_content,
}
)
elif train_type == "ddl":
update_json = json.dumps(
{
"question": None,
"ddl": update_content,
}
)
elif train_type == "documentation":
update_json = json.dumps(
{
"question": None,
"documentation": update_content,
}
)
else:
update_json = json.dumps(
{
"question": question,
"sql": update_content,
}
)
cursor = self.oracle_conn.cursor()
cursor.setinputsizes(oracledb.DB_TYPE_VECTOR, oracledb.DB_TYPE_JSON)
cursor.execute(
"""
UPDATE
oracle_embedding
SET
embedding = TO_VECTOR(:1),
document = JSON_MERGEPATCH(document, :2)
WHERE
uuid = :3
""",
[self.generate_embedding(update_content), update_json, id],
)
self.oracle_conn.commit()
cursor.close()
return True
@staticmethod
def _extract_documents(query_results) -> list:
"""
Static method to extract the documents from the results of a query.
Args:
query_results (pd.DataFrame): The dataframe to use.
Returns:
List[str] or None: The extracted documents, or an empty list or single document if an error occurred.
"""
if query_results is None or len(query_results) == 0:
return []
documents = [
json.loads(row_data[0]) if isinstance(row_data[0], str) else row_data[0]
for row_data in query_results
]
return documents
def get_similar_question_sql(self, question: str, **kwargs) -> list:
embeddings = self.generate_embedding(question)
collection = self.get_collection(self.sql_collection)
cursor = self.oracle_conn.cursor()
cursor.setinputsizes(None, oracledb.DB_TYPE_VECTOR, oracledb.DB_TYPE_VECTOR)
cursor.execute(
"""
SELECT document
FROM oracle_embedding
WHERE collection_id = :1
ORDER BY VECTOR_DISTANCE(embedding, TO_VECTOR(:2), COSINE)
FETCH FIRST :3 ROWS ONLY
""",
[collection["uuid"], embeddings, self.n_results_sql],
)
results = cursor.fetchall()
cursor.close()
return self._extract_documents(results)
def get_related_ddl(self, question: str, **kwargs) -> list:
collection = self.get_collection(self.ddl_collection)
cursor = self.oracle_conn.cursor()
cursor.setinputsizes(None, oracledb.DB_TYPE_VECTOR)
cursor.execute(
"""
SELECT
document
FROM oracle_embedding
WHERE
collection_id = :1
ORDER BY VECTOR_DISTANCE(embedding, TO_VECTOR(:2), COSINE)
FETCH FIRST :top_k ROWS ONLY
""",
[collection["uuid"], self.generate_embedding(question), 100],
)
results = cursor.fetchall()
self.oracle_conn.commit()
cursor.close()
return Oracle_VectorStore._extract_documents(results)
def search_tables_metadata(
self,
engine: str = None,
catalog: str = None,
schema: str = None,
table_name: str = None,
ddl: str = None,
size: int = 10,
**kwargs,
) -> list:
pass
def get_related_documentation(self, question: str, **kwargs) -> list:
collection = self.get_collection(self.documentation_collection)
cursor = self.oracle_conn.cursor()
cursor.setinputsizes(None, oracledb.DB_TYPE_VECTOR)
cursor.execute(
"""
SELECT
document
FROM oracle_embedding
WHERE
collection_id = :1
ORDER BY VECTOR_DISTANCE(embedding, TO_VECTOR(:2), DOT)
FETCH FIRST :top_k ROWS ONLY
""",
[collection["uuid"], self.generate_embedding(question), 100],
)
results = cursor.fetchall()
self.oracle_conn.commit()
cursor.close()
return Oracle_VectorStore._extract_documents(results)
def create_tables_if_not_exists(self) -> None:
cursor = self.oracle_conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS oracle_collection (
name VARCHAR2(200) NOT NULL,
cmetadata json NOT NULL,
uuid VARCHAR2(200) NOT NULL,
CONSTRAINT oc_key_uuid PRIMARY KEY ( uuid )
)
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS oracle_embedding (
collection_id VARCHAR2(200) NOT NULL,
embedding vector NOT NULL,
document json NOT NULL,
cmetadata json NOT NULL,
custom_id VARCHAR2(200) NOT NULL,
uuid VARCHAR2(200) NOT NULL,
CONSTRAINT oe_key_uuid PRIMARY KEY ( uuid )
)
"""
)
self.oracle_conn.commit()
cursor.close()
def create_collections_if_not_exists(
self,
name: str,
cmetadata: Optional[dict] = None,
) -> Tuple[dict, bool]:
"""
Get or create a collection.
Returns [Collection, bool] where the bool is True if the collection was created.
"""
if self.pre_delete_collection:
self.delete_collection(name)
created = False
collection = self.get_collection(name)
if collection:
return collection, created
cmetadata = (
json.dumps(self.cmetadata) if cmetadata is None else json.dumps(cmetadata)
)
collection_id = str(uuid.uuid4())
cursor = self.oracle_conn.cursor()
cursor.execute(
"""
INSERT INTO oracle_collection(name, cmetadata, uuid)
VALUES (:1, :2, :3)
""",
[name, cmetadata, str(collection_id)],
)
self.oracle_conn.commit()
cursor.close()
collection = {"name": name, "cmetadata": cmetadata, "uuid": collection_id}
created = True
return collection, created
def get_collection(self, name) -> Optional[dict]:
return self.get_by_name(name)
def get_by_name(self, name: str) -> Optional[dict]:
cursor = self.oracle_conn.cursor()
cursor.execute(
"""
SELECT
name,
cmetadata,
uuid
FROM
oracle_collection
WHERE
name = :1
FETCH FIRST 1 ROWS ONLY
""",
[name],
)
for row in cursor:
return {"name": row[0], "cmetadata": row[1], "uuid": row[2]}
return # type: ignore
def delete_collection(self, name) -> None:
collection = self.get_collection(name)
if not collection:
return
cursor = self.oracle_conn.cursor()
cursor.execute(
"""
DELETE
FROM
oracle_embedding
WHERE
collection_id = ( SELECT uuid FROM oracle_collection WHERE name = :1 )
""",
[name],
)
cursor.execute(
"""
DELETE
FROM
oracle_collection
WHERE
name = :1
""",
[name],
)
self.oracle_conn.commit()
cursor.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/oracle/oracle_vector.py",
"license": "MIT License",
"lines": 530,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/legacy/qianfan/Qianfan_Chat.py | import qianfan
from ..base import VannaBase
class Qianfan_Chat(VannaBase):
def __init__(self, client=None, config=None):
VannaBase.__init__(self, config=config)
if "api_key" not in config:
raise Exception("Missing api_key in config")
self.api_key = config["api_key"]
if "secret_key" not in config:
raise Exception("Missing secret_key in config")
self.secret_key = config["secret_key"]
# default parameters - can be overrided using config
self.temperature = 0.9
self.max_tokens = 1024
if "temperature" in config:
self.temperature = config["temperature"]
if "max_tokens" in config:
self.max_tokens = config["max_tokens"]
self.model = config["model"] if "model" in config else "ERNIE-Speed"
if client is not None:
self.client = client
return
self.client = qianfan.ChatCompletion(ak=self.api_key, sk=self.secret_key)
def system_message(self, message: str) -> any:
return {"role": "system", "content": message}
def user_message(self, message: str) -> any:
return {"role": "user", "content": message}
def assistant_message(self, message: str) -> any:
return {"role": "assistant", "content": message}
def get_sql_prompt(
self,
initial_prompt: str,
question: str,
question_sql_list: list,
ddl_list: list,
doc_list: list,
**kwargs,
):
"""
Example:
```python
vn.get_sql_prompt(
question="What are the top 10 customers by sales?",
question_sql_list=[{"question": "What are the top 10 customers by sales?", "sql": "SELECT * FROM customers ORDER BY sales DESC LIMIT 10"}],
ddl_list=["CREATE TABLE customers (id INT, name TEXT, sales DECIMAL)"],
doc_list=["The customers table contains information about customers and their sales."],
)
```
This method is used to generate a prompt for the LLM to generate SQL.
Args:
question (str): The question to generate SQL for.
question_sql_list (list): A list of questions and their corresponding SQL statements.
ddl_list (list): A list of DDL statements.
doc_list (list): A list of documentation.
Returns:
any: The prompt for the LLM to generate SQL.
"""
if initial_prompt is None:
initial_prompt = (
f"You are a {self.dialect} expert. "
+ "Please help to generate a SQL to answer the question based on some context.Please don't give any explanation for your answer. Just only generate a SQL \n"
)
initial_prompt = self.add_ddl_to_prompt(
initial_prompt, ddl_list, max_tokens=self.max_tokens
)
if self.static_documentation != "":
doc_list.append(self.static_documentation)
initial_prompt = self.add_documentation_to_prompt(
initial_prompt, doc_list, max_tokens=self.max_tokens
)
message_log = []
if question_sql_list is None or len(question_sql_list) == 0:
initial_prompt = initial_prompt + f"question: {question}"
message_log.append(self.user_message(initial_prompt))
else:
for i, example in question_sql_list:
if example is None:
print("example is None")
else:
if (
example is not None
and "question" in example
and "sql" in example
):
if i == 0:
initial_prompt = (
initial_prompt + f"question: {example['question']}"
)
message_log.append(self.user_message(initial_prompt))
else:
message_log.append(self.user_message(example["question"]))
message_log.append(self.assistant_message(example["sql"]))
message_log.append(self.user_message(question))
return message_log
def submit_prompt(self, prompt, **kwargs) -> str:
if prompt is None:
raise Exception("Prompt is None")
if len(prompt) == 0:
raise Exception("Prompt is empty")
# Count the number of tokens in the message log
# Use 4 as an approximation for the number of characters per token
num_tokens = 0
for message in prompt:
num_tokens += len(message["content"]) / 4
if kwargs.get("model", None) is not None:
model = kwargs.get("model", None)
print(f"Using model {model} for {num_tokens} tokens (approx)")
response = self.client.do(
model=self.model,
messages=prompt,
max_output_tokens=self.max_tokens,
stop=None,
temperature=self.temperature,
)
elif self.config is not None and "model" in self.config:
print(
f"Using model {self.config['model']} for {num_tokens} tokens (approx)"
)
response = self.client.do(
model=self.config.get("model"),
messages=prompt,
max_output_tokens=self.max_tokens,
stop=None,
temperature=self.temperature,
)
else:
if num_tokens > 3500:
model = "ERNIE-Speed-128K"
else:
model = "ERNIE-Speed-8K"
print(f"Using model {model} for {num_tokens} tokens (approx)")
response = self.client.do(
model=model,
messages=prompt,
max_output_tokens=self.max_tokens,
stop=None,
temperature=self.temperature,
)
return response.body.get("result")
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/qianfan/Qianfan_Chat.py",
"license": "MIT License",
"lines": 139,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/legacy/qianfan/Qianfan_embeddings.py | import qianfan
from ..base import VannaBase
class Qianfan_Embeddings(VannaBase):
def __init__(self, client=None, config=None):
VannaBase.__init__(self, config=config)
if client is not None:
self.client = client
return
if "api_key" not in config:
raise Exception("Missing api_key in config")
self.api_key = config["api_key"]
if "secret_key" not in config:
raise Exception("Missing secret_key in config")
self.secret_key = config["secret_key"]
self.client = qianfan.Embedding(ak=self.api_key, sk=self.secret_key)
def generate_embedding(self, data: str, **kwargs) -> list[float]:
if self.config is not None and "model" in self.config:
embedding = self.client.do(
model=self.config["model"],
input=[data],
)
else:
embedding = self.client.do(
model="bge-large-zh",
input=[data],
)
return embedding.get("data")[0]["embedding"]
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/qianfan/Qianfan_embeddings.py",
"license": "MIT License",
"lines": 27,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/legacy/qianwen/QianwenAI_chat.py | import os
from openai import OpenAI
from ..base import VannaBase
class QianWenAI_Chat(VannaBase):
def __init__(self, client=None, config=None):
VannaBase.__init__(self, config=config)
# default parameters - can be overrided using config
self.temperature = 0.7
if "temperature" in config:
self.temperature = config["temperature"]
if "api_type" in config:
raise Exception(
"Passing api_type is now deprecated. Please pass an OpenAI client instead."
)
if "api_base" in config:
raise Exception(
"Passing api_base is now deprecated. Please pass an OpenAI client instead."
)
if "api_version" in config:
raise Exception(
"Passing api_version is now deprecated. Please pass an OpenAI client instead."
)
if client is not None:
self.client = client
return
if config is None and client is None:
self.client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
return
if "api_key" in config:
if "base_url" not in config:
self.client = OpenAI(
api_key=config["api_key"],
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
else:
self.client = OpenAI(
api_key=config["api_key"], base_url=config["base_url"]
)
def system_message(self, message: str) -> any:
return {"role": "system", "content": message}
def user_message(self, message: str) -> any:
return {"role": "user", "content": message}
def assistant_message(self, message: str) -> any:
return {"role": "assistant", "content": message}
def submit_prompt(self, prompt, **kwargs) -> str:
if prompt is None:
raise Exception("Prompt is None")
if len(prompt) == 0:
raise Exception("Prompt is empty")
# Count the number of tokens in the message log
# Use 4 as an approximation for the number of characters per token
num_tokens = 0
for message in prompt:
num_tokens += len(message["content"]) / 4
if kwargs.get("model", None) is not None:
model = kwargs.get("model", None)
print(f"Using model {model} for {num_tokens} tokens (approx)")
response = self.client.chat.completions.create(
model=model,
messages=prompt,
stop=None,
temperature=self.temperature,
)
elif kwargs.get("engine", None) is not None:
engine = kwargs.get("engine", None)
print(f"Using model {engine} for {num_tokens} tokens (approx)")
response = self.client.chat.completions.create(
engine=engine,
messages=prompt,
stop=None,
temperature=self.temperature,
)
elif self.config is not None and "engine" in self.config:
print(
f"Using engine {self.config['engine']} for {num_tokens} tokens (approx)"
)
response = self.client.chat.completions.create(
engine=self.config["engine"],
messages=prompt,
stop=None,
temperature=self.temperature,
)
elif self.config is not None and "model" in self.config:
print(
f"Using model {self.config['model']} for {num_tokens} tokens (approx)"
)
response = self.client.chat.completions.create(
model=self.config["model"],
messages=prompt,
stop=None,
temperature=self.temperature,
)
else:
if num_tokens > 3500:
model = "qwen-long"
else:
model = "qwen-plus"
print(f"Using model {model} for {num_tokens} tokens (approx)")
response = self.client.chat.completions.create(
model=model,
messages=prompt,
stop=None,
temperature=self.temperature,
)
# Find the first response from the chatbot that has text in it (some responses may not have text)
for choice in response.choices:
if "text" in choice:
return choice.text
# If no response with text is found, return the first response's content (which may be empty)
return response.choices[0].message.content
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/legacy/qianwen/QianwenAI_chat.py",
"license": "MIT License",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/servers/__main__.py | """
Entry point for running Vanna Agents servers.
"""
from .cli.server_runner import main
if __name__ == "__main__":
main()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/__main__.py",
"license": "MIT License",
"lines": 6,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
vanna-ai/vanna:src/vanna/servers/base/chat_handler.py | """
Framework-agnostic chat handling logic.
"""
import uuid
from typing import AsyncGenerator, List
from ...core import Agent
from .models import ChatRequest, ChatResponse, ChatStreamChunk
class ChatHandler:
"""Core chat handling logic - framework agnostic."""
def __init__(
self,
agent: Agent,
):
"""Initialize chat handler.
Args:
agent: The agent to handle chat requests
"""
self.agent = agent
async def handle_stream(
self, request: ChatRequest
) -> AsyncGenerator[ChatStreamChunk, None]:
"""Stream chat responses.
Args:
request: Chat request
Yields:
Chat stream chunks
"""
conversation_id = request.conversation_id or self._generate_conversation_id()
# Use request_id from client for tracking, or use the one generated internally
request_id = request.request_id or str(uuid.uuid4())
async for component in self.agent.send_message(
request_context=request.request_context,
message=request.message,
conversation_id=conversation_id,
):
yield ChatStreamChunk.from_component(component, conversation_id, request_id)
async def handle_poll(self, request: ChatRequest) -> ChatResponse:
"""Handle polling-based chat.
Args:
request: Chat request
Returns:
Complete chat response
"""
chunks = []
async for chunk in self.handle_stream(request):
chunks.append(chunk)
return ChatResponse.from_chunks(chunks)
def _generate_conversation_id(self) -> str:
"""Generate new conversation ID."""
return f"conv_{uuid.uuid4().hex[:8]}"
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/base/chat_handler.py",
"license": "MIT License",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
vanna-ai/vanna:src/vanna/servers/base/models.py | """
Request and response models for server endpoints.
"""
import time
import uuid
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field
from ...components import UiComponent, RichComponent
from ...core.component_manager import ComponentUpdate
from ...core.user.request_context import RequestContext
class ChatRequest(BaseModel):
"""Request model for chat endpoints."""
message: str = Field(description="User message")
conversation_id: Optional[str] = Field(default=None, description="Conversation ID")
request_id: Optional[str] = Field(
default=None, description="Request ID for tracing"
)
request_context: RequestContext = Field(
default_factory=RequestContext,
description="Request context for user resolution",
)
metadata: Dict[str, Any] = Field(
default_factory=dict, description="Additional metadata"
)
class ChatStreamChunk(BaseModel):
"""Single chunk in a streaming chat response."""
rich: Dict[str, Any] = Field(description="Rich component data for advanced UIs")
simple: Optional[Dict[str, Any]] = Field(
default=None, description="Simple component data for basic UIs"
)
# Stream metadata
conversation_id: str = Field(description="Conversation ID")
request_id: str = Field(description="Request ID")
timestamp: float = Field(default_factory=time.time, description="Timestamp")
@classmethod
def from_component(
cls,
component: Union[UiComponent, RichComponent],
conversation_id: str,
request_id: str,
) -> "ChatStreamChunk":
"""Create chunk from UI component or rich component."""
if isinstance(component, UiComponent):
# Full UiComponent with both rich and simple
rich_data = component.rich_component.serialize_for_frontend()
simple_data = None
if component.simple_component:
simple_data = component.simple_component.serialize_for_frontend()
return cls(
rich=rich_data,
simple=simple_data,
conversation_id=conversation_id,
request_id=request_id,
)
# Rich component only (no simple fallback)
rich_data = component.serialize_for_frontend()
return cls(
rich=rich_data,
simple=None,
conversation_id=conversation_id,
request_id=request_id,
)
@classmethod
def from_component_update(
cls, update: ComponentUpdate, conversation_id: str, request_id: str
) -> "ChatStreamChunk":
"""Create chunk from component update."""
update_payload = update.serialize_for_frontend()
return cls(
rich=update_payload,
simple=None, # Component updates don't have simple representations
conversation_id=conversation_id,
request_id=request_id,
)
class ChatResponse(BaseModel):
"""Complete chat response for polling endpoints."""
chunks: List[ChatStreamChunk] = Field(description="Response chunks")
conversation_id: str = Field(description="Conversation ID")
request_id: str = Field(description="Request ID")
total_chunks: int = Field(description="Total number of chunks")
@classmethod
def from_chunks(cls, chunks: List[ChatStreamChunk]) -> "ChatResponse":
"""Create response from chunks."""
if not chunks:
return cls(chunks=[], conversation_id="", request_id="", total_chunks=0)
return cls(
chunks=chunks,
conversation_id=chunks[0].conversation_id,
request_id=chunks[0].request_id,
total_chunks=len(chunks),
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/base/models.py",
"license": "MIT License",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
vanna-ai/vanna:src/vanna/servers/base/rich_chat_handler.py | # """
# Rich component-aware chat handling logic.
# """
# import uuid
# from typing import AsyncGenerator, Callable, List, Optional, Union
# from ...core import Agent, User
# from ...core.rich_components import RichComponent
# from ...core.component_manager import ComponentManager, ComponentUpdate
# from .models import ChatRequest, ChatResponse, ChatStreamChunk
# class RichChatHandler:
# """Rich component-aware chat handling logic."""
# def __init__(
# self,
# agent: Agent,
# default_user_factory: Optional[Callable[[Optional[str]], User]] = None,
# ):
# """Initialize rich chat handler.
# Args:
# agent: The agent to handle chat requests
# default_user_factory: Function to create default user from user_id
# """
# self.agent = agent
# self.default_user_factory = default_user_factory or self._create_default_user
# self.component_managers: dict[str, ComponentManager] = {} # Per conversation
# async def handle_stream(
# self, request: ChatRequest
# ) -> AsyncGenerator[ChatStreamChunk, None]:
# """Stream chat responses with rich component support.
# Args:
# request: Chat request
# Yields:
# Chat stream chunks including rich component updates
# """
# user = self._resolve_user(request.user_id)
# conversation_id = request.conversation_id or self._generate_conversation_id()
# request_id = request.request_id or str(uuid.uuid4())
# # Get or create component manager for this conversation
# if conversation_id not in self.component_managers:
# self.component_managers[conversation_id] = ComponentManager()
# component_manager = self.component_managers[conversation_id]
# async for component in self.agent.send_message(
# conversation_id=conversation_id,
# user=user,
# message=request.message,
# request_id=request_id,
# ):
# if isinstance(component, RichComponent):
# # Handle rich component through manager
# update = component_manager.emit(component)
# yield ChatStreamChunk.from_component_update(update, conversation_id, request_id)
# else:
# # Handle legacy components
# yield ChatStreamChunk.from_component(component, conversation_id, request_id)
# async def handle_poll(self, request: ChatRequest) -> ChatResponse:
# """Handle polling request with rich component support.
# Args:
# request: Chat request
# Returns:
# Complete chat response with all components
# """
# chunks: List[ChatStreamChunk] = []
# async for chunk in self.handle_stream(request):
# chunks.append(chunk)
# return ChatResponse.from_chunks(chunks)
# def get_component_manager(self, conversation_id: str) -> Optional[ComponentManager]:
# """Get the component manager for a conversation."""
# return self.component_managers.get(conversation_id)
# def get_component(self, conversation_id: str, component_id: str) -> Optional[RichComponent]:
# """Get a specific component from a conversation."""
# manager = self.get_component_manager(conversation_id)
# return manager.get_component(component_id) if manager else None
# def get_all_components(self, conversation_id: str) -> List[RichComponent]:
# """Get all components in a conversation."""
# manager = self.get_component_manager(conversation_id)
# return manager.get_all_components() if manager else []
# def update_component(
# self,
# conversation_id: str,
# component_id: str,
# **updates
# ) -> Optional[ComponentUpdate]:
# """Update a component in a conversation."""
# manager = self.get_component_manager(conversation_id)
# return manager.update_component(component_id, **updates) if manager else None
# def remove_component(
# self,
# conversation_id: str,
# component_id: str
# ) -> Optional[ComponentUpdate]:
# """Remove a component from a conversation."""
# manager = self.get_component_manager(conversation_id)
# return manager.remove_component(component_id) if manager else None
# def clear_conversation_components(self, conversation_id: str):
# """Clear all components for a conversation."""
# if conversation_id in self.component_managers:
# del self.component_managers[conversation_id]
# def _resolve_user(self, user_id: Optional[str]) -> User:
# """Resolve user from ID or create default."""
# if user_id:
# # In a real implementation, you'd fetch from a user store
# return User(id=user_id, username=f"user_{user_id}", email="", permissions=[])
# return self.default_user_factory(user_id)
# def _create_default_user(self, user_id: Optional[str]) -> User:
# """Create a default user."""
# user_id = user_id or "anonymous"
# return User(
# id=user_id,
# username=f"user_{user_id}",
# email="",
# permissions=[]
# )
# def _generate_conversation_id(self) -> str:
# """Generate a new conversation ID."""
# return str(uuid.uuid4())
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/base/rich_chat_handler.py",
"license": "MIT License",
"lines": 114,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/servers/base/templates.py | """
HTML templates for Vanna Agents servers.
"""
from typing import Optional
def get_vanna_component_script(
dev_mode: bool = False,
static_path: str = "/static",
cdn_url: str = "https://img.vanna.ai/vanna-components.js",
) -> str:
"""Get the script tag for loading Vanna web components.
Args:
dev_mode: If True, load from local static files
static_path: Path to static assets in dev mode
cdn_url: CDN URL for production
Returns:
HTML script tag for loading components
"""
if dev_mode:
return (
f'<script type="module" src="{static_path}/vanna-components.js"></script>'
)
else:
return f'<script type="module" src="{cdn_url}"></script>'
def get_index_html(
dev_mode: bool = False,
static_path: str = "/static",
cdn_url: str = "https://img.vanna.ai/vanna-components.js",
api_base_url: str = "",
) -> str:
"""Generate index HTML with configurable component loading.
Args:
dev_mode: If True, load components from local static files
static_path: Path to static assets in dev mode
cdn_url: CDN URL for production components
api_base_url: Base URL for API endpoints
Returns:
Complete HTML page as string
"""
component_script = get_vanna_component_script(dev_mode, static_path, cdn_url)
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vanna Agents Chat</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@400;500;600;700&family=Space+Grotesk:wght@300;400;500;600;700&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet">
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {{
theme: {{
extend: {{
colors: {{
'vanna-navy': '#023d60',
'vanna-cream': '#e7e1cf',
'vanna-teal': '#15a8a8',
'vanna-orange': '#fe5d26',
'vanna-magenta': '#bf1363',
}},
fontFamily: {{
'sans': ['Space Grotesk', 'ui-sans-serif', 'system-ui'],
'serif': ['Roboto Slab', 'ui-serif', 'Georgia'],
'mono': ['Space Mono', 'ui-monospace', 'monospace'],
}}
}}
}}
}}
</script>
<style>
body {{
background: linear-gradient(to bottom, #e7e1cf, #ffffff, #e7e1cf);
min-height: 100vh;
position: relative;
overflow-x: hidden;
}}
/* Background decorations matching landing page */
body::before {{
content: '';
position: fixed;
inset: 0;
pointer-events: none;
z-index: 0;
/* Radial gradients with brand colors */
background:
radial-gradient(circle at top left, rgba(21, 168, 168, 0.12), transparent 60%),
radial-gradient(circle at bottom right, rgba(254, 93, 38, 0.08), transparent 65%);
}}
body::after {{
content: '';
position: fixed;
inset: 0;
pointer-events: none;
z-index: 0;
/* Dot pattern with retro computing aesthetic */
background-image: radial-gradient(circle at 2px 2px, rgba(2, 61, 96, 0.3) 1px, transparent 0);
background-size: 32px 32px;
/* Grid overlay */
background-image:
radial-gradient(circle at 2px 2px, rgba(2, 61, 96, 0.3) 1px, transparent 0),
linear-gradient(rgba(2, 61, 96, 0.1) 1px, transparent 1px),
linear-gradient(90deg, rgba(2, 61, 96, 0.1) 1px, transparent 1px);
background-size: 32px 32px, 100px 100px, 100px 100px;
}}
/* Ensure content is above background */
body > * {{
position: relative;
z-index: 1;
}}
vanna-chat {{
width: 100%;
height: 100%;
display: block;
}}
</style>
{component_script}
</head>
<body>
<div class="max-w-6xl mx-auto p-5">
<!-- Header -->
<div class="text-center mb-8">
<h1 class="text-4xl font-bold text-vanna-navy mb-2 font-serif">Vanna Agents</h1>
<p class="text-lg font-mono font-bold text-vanna-teal mb-4">DATA-FIRST AGENTS</p>
<p class="text-slate-600 mb-4">Interactive AI Assistant powered by Vanna Agents Framework</p>
<a href="javascript:window.location='view-source:'+window.location.href" class="inline-flex items-center gap-2 px-4 py-2 bg-vanna-teal text-white text-sm font-medium rounded-lg hover:bg-vanna-navy transition">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/>
</svg>
View Page Source
</a>
</div>
{(' <div class="bg-vanna-orange/10 border border-vanna-orange/30 rounded-lg p-3 mb-5 text-vanna-orange text-sm font-medium">📦 Development Mode: Loading components from local assets</div>' if dev_mode else "")}
<!-- Login Form -->
<div id="loginContainer" class="max-w-md mx-auto mb-10 bg-white p-8 rounded-xl shadow-lg border border-vanna-teal/30">
<div class="text-center mb-6">
<h2 class="text-2xl font-semibold text-vanna-navy mb-2 font-serif">Login to Continue</h2>
<p class="text-sm text-slate-600">Select your email to access the chat</p>
</div>
<div class="mb-5">
<label for="emailInput" class="block mb-2 text-sm font-medium text-vanna-navy">Email Address</label>
<select
id="emailInput"
class="w-full px-4 py-3 text-sm border border-vanna-teal/30 rounded-lg focus:outline-none focus:ring-2 focus:ring-vanna-teal focus:border-transparent bg-white"
>
<option value="">Select an email...</option>
<option value="admin@example.com">admin@example.com</option>
<option value="user@example.com">user@example.com</option>
</select>
</div>
<button id="loginButton" class="w-full px-4 py-3 bg-vanna-teal text-white text-sm font-medium rounded-lg hover:bg-vanna-navy focus:outline-none focus:ring-2 focus:ring-vanna-teal focus:ring-offset-2 transition disabled:bg-gray-400 disabled:cursor-not-allowed">
Continue
</button>
<div class="mt-5 p-3 bg-vanna-teal/10 border-l-4 border-vanna-teal rounded text-xs text-vanna-navy leading-relaxed">
<strong>Demo Mode:</strong> This is a frontend-only authentication demo.
Your email will be stored as a cookie and automatically sent with all API requests.
</div>
</div>
<!-- Logged In Status (hidden by default) -->
<div id="loggedInStatus" class="hidden text-center p-4 bg-vanna-teal/10 border border-vanna-teal/30 rounded-lg mb-5">
Logged in as <span id="loggedInEmail" class="font-semibold text-vanna-navy"></span>
<br>
<button id="logoutButton" class="mt-2 px-3 py-1.5 bg-vanna-navy text-white text-xs rounded hover:bg-vanna-teal transition">
Logout
</button>
</div>
<!-- Chat Container (hidden by default) -->
<div id="chatSections" class="hidden">
<div class="bg-white rounded-xl shadow-lg h-[600px] overflow-hidden border border-vanna-teal/30">
<vanna-chat
api-base="{api_base_url}"
sse-endpoint="{api_base_url}/api/vanna/v2/chat_sse"
ws-endpoint="{api_base_url}/api/vanna/v2/chat_websocket"
poll-endpoint="{api_base_url}/api/vanna/v2/chat_poll">
</vanna-chat>
</div>
<div class="mt-8 p-5 bg-white rounded-lg shadow border border-vanna-teal/30">
<h3 class="text-lg font-semibold text-vanna-navy mb-3 font-serif">API Endpoints</h3>
<ul class="space-y-2">
<li class="p-2 bg-vanna-cream/50 rounded font-mono text-sm">
<span class="font-bold text-vanna-teal mr-2">POST</span>{api_base_url}/api/vanna/v2/chat_sse - Server-Sent Events streaming
</li>
<li class="p-2 bg-vanna-cream/50 rounded font-mono text-sm">
<span class="font-bold text-vanna-teal mr-2">WS</span>{api_base_url}/api/vanna/v2/chat_websocket - WebSocket real-time chat
</li>
<li class="p-2 bg-vanna-cream/50 rounded font-mono text-sm">
<span class="font-bold text-vanna-teal mr-2">POST</span>{api_base_url}/api/vanna/v2/chat_poll - Request/response polling
</li>
<li class="p-2 bg-vanna-cream/50 rounded font-mono text-sm">
<span class="font-bold text-vanna-teal mr-2">GET</span>{api_base_url}/health - Health check
</li>
</ul>
</div>
</div>
</div>
<script>
// Cookie helpers
const getCookie = (name) => {{
const value = `; ${{document.cookie}}`;
const parts = value.split(`; ${{name}}=`);
return parts.length === 2 ? parts.pop().split(';').shift() : null;
}};
const setCookie = (name, value) => {{
const expires = new Date(Date.now() + 365 * 864e5).toUTCString();
document.cookie = `${{name}}=${{value}}; expires=${{expires}}; path=/; SameSite=Lax`;
}};
const deleteCookie = (name) => {{
document.cookie = `${{name}}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}};
// Login/Logout
document.addEventListener('DOMContentLoaded', () => {{
const email = getCookie('vanna_email');
// Check if already logged in
if (email) {{
loginContainer.classList.add('hidden');
loggedInStatus.classList.remove('hidden');
chatSections.classList.remove('hidden');
loggedInEmail.textContent = email;
}}
// Login button
loginButton.addEventListener('click', () => {{
const email = emailInput.value.trim();
if (!email) {{
alert('Please select an email address');
return;
}}
setCookie('vanna_email', email);
loginContainer.classList.add('hidden');
loggedInStatus.classList.remove('hidden');
chatSections.classList.remove('hidden');
loggedInEmail.textContent = email;
}});
// Logout button
logoutButton.addEventListener('click', () => {{
deleteCookie('vanna_email');
loginContainer.classList.remove('hidden');
loggedInStatus.classList.add('hidden');
chatSections.classList.add('hidden');
emailInput.value = '';
}});
// Enter key
emailInput.addEventListener('keypress', (e) => {{
if (e.key === 'Enter') loginButton.click();
}});
}});
</script>
<script>
// Artifact demo event listener
document.addEventListener('DOMContentLoaded', () => {{
const vannaChat = document.querySelector('vanna-chat');
if (vannaChat) {{
// Add artifact event listener to demonstrate external rendering
vannaChat.addEventListener('artifact-opened', (event) => {{
const {{ artifactId, type, title, trigger }} = event.detail;
console.log('🎨 Artifact Event:', {{ artifactId, type, title, trigger }});
// For demo: open all artifacts externally
setTimeout(() => {{
const newWindow = window.open('', '_blank', 'width=900,height=700');
if (newWindow) {{
newWindow.document.write(event.detail.getStandaloneHTML());
newWindow.document.close();
newWindow.document.title = title || 'Vanna Artifact';
console.log(`📱 Opened ${{title}} in new window`);
}}
}}, 100);
// Prevent default in-chat rendering
event.detail.preventDefault();
console.log('✋ Showing placeholder in chat instead of full artifact');
}});
console.log('🎯 Artifact demo mode: All artifacts will open externally');
}}
}});
// Fallback if web component doesn't load
if (!customElements.get('vanna-chat')) {{
setTimeout(() => {{
if (!customElements.get('vanna-chat')) {{
document.querySelector('vanna-chat').innerHTML = `
<div class="p-10 text-center text-gray-600">
<h3 class="text-xl font-semibold mb-2">Vanna Chat Component</h3>
<p class="mb-2">Web component failed to load. Please check your connection.</p>
<p class="text-sm text-gray-400">
{("Loading from: local static assets" if dev_mode else f"Loading from: {cdn_url}")}
</p>
</div>
`;
}}
}}, 2000);
}}
</script>
</body>
</html>"""
# Backward compatibility - default production HTML
INDEX_HTML = get_index_html()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/base/templates.py",
"license": "MIT License",
"lines": 292,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
vanna-ai/vanna:src/vanna/servers/cli/server_runner.py | """
CLI for running Vanna Agents servers with example agents.
"""
import importlib
import json
from typing import Dict, Optional, Any, cast, TextIO, Union
import click
from ...core import Agent
class ExampleAgentLoader:
"""Loads example agents for the CLI."""
@staticmethod
def list_available_examples() -> Dict[str, str]:
"""Return available examples with descriptions."""
return {
"mock_quickstart": "Basic agent with mock LLM service",
"anthropic_quickstart": "Agent configured for Anthropic's Claude API",
"openai_quickstart": "Agent configured for OpenAI's GPT models",
"mock_custom_tool": "Agent with custom tool demonstration (mock LLM)",
"mock_quota_example": "Agent with usage quota management (mock LLM)",
"mock_rich_components_demo": "Rich components demonstration with cards, tasks, and progress (mock LLM)",
"coding_agent_example": "Coding agent with file system tools (list, read, write files)",
"email_auth_example": "Email-based authentication demonstration (mock LLM)",
"claude_sqlite_example": "Claude agent with SQLite database querying capabilities",
"mock_sqlite_example": "Mock agent with SQLite database demonstration",
}
@staticmethod
def load_example_agent(example_name: str) -> Agent:
"""Load an example agent by name.
Args:
example_name: Name of the example to load
Returns:
Configured agent instance
Raises:
ValueError: If example not found or failed to load
"""
try:
# Import the example module
module = importlib.import_module(f"vanna.examples.{example_name}")
# Look for standard factory functions
factory_functions = [
"create_demo_agent",
"create_agent",
"create_basic_demo",
]
for func_name in factory_functions:
if hasattr(module, func_name):
factory = getattr(module, func_name)
return cast(Agent, factory())
# Look for module-level agent instances
if hasattr(module, "main_agent"):
return cast(Agent, module.main_agent)
raise AttributeError(f"No agent factory found in {example_name}")
except ImportError as e:
raise ValueError(f"Example '{example_name}' not found: {e}")
except Exception as e:
raise ValueError(f"Failed to load example '{example_name}': {e}")
@click.command()
@click.option(
"--framework",
type=click.Choice(["flask", "fastapi"]),
default="fastapi",
help="Web framework to use",
)
@click.option("--port", default=8000, help="Port to run server on")
@click.option("--host", default="0.0.0.0", help="Host to bind server to")
@click.option(
"--example", help="Example agent to use (use --list-examples to see options)"
)
@click.option("--list-examples", is_flag=True, help="List available example agents")
@click.option(
"--config", type=click.File("r"), help="JSON config file for server settings"
)
@click.option("--debug", is_flag=True, help="Enable debug mode")
@click.option(
"--dev",
is_flag=True,
help="Enable development mode (load components from local assets)",
)
@click.option(
"--static-folder", default=None, help="Static folder path for development mode"
)
@click.option(
"--cdn-url",
default="https://img.vanna.ai/vanna-components.js",
help="CDN URL for web components",
)
def main(
framework: str,
port: int,
host: str,
example: Optional[str],
list_examples: bool,
config: Optional[click.File],
debug: bool,
dev: bool,
static_folder: Optional[str],
cdn_url: str,
) -> None:
"""Run Vanna Agents server with optional example agent."""
if list_examples:
click.echo("Available example agents:")
examples = ExampleAgentLoader.list_available_examples()
for name, description in examples.items():
click.echo(f" {name:20} - {description}")
return
# Load configuration
server_config = {}
if config:
server_config = json.load(cast(TextIO, config))
# Set default static folder based on dev mode
if static_folder is None:
static_folder = "frontend/webcomponent/static" if dev else "static"
# Add CLI options to config
server_config.update(
{
"dev_mode": dev,
"static_folder": static_folder,
"cdn_url": cdn_url,
"api_base_url": "", # Can be overridden in config file
}
)
# Create agent
if example:
try:
agent = ExampleAgentLoader.load_example_agent(example)
click.echo(f"✓ Loaded example agent: {example}")
except ValueError as e:
click.echo(f"Error: {e}", err=True)
return
else:
# Fallback to basic agent
try:
from ...agents import create_basic_agent
from ...integrations.mock import MockLlmService
llm_service = MockLlmService(
response_content="Hello! I'm a Vanna Agents demo server. How can I help you?"
)
agent = create_basic_agent(llm_service)
click.echo(
"✓ Using basic demo agent (use --example to specify different agent)"
)
except ImportError as e:
click.echo(f"Error: Could not create basic agent: {e}", err=True)
return
from ..flask.app import VannaFlaskServer
from ..fastapi.app import VannaFastAPIServer
# Create and run server
server: Union[VannaFlaskServer, VannaFastAPIServer]
if framework == "flask":
server = VannaFlaskServer(agent, config=server_config)
click.echo(f"🚀 Starting Flask server on http://{host}:{port}")
if dev:
click.echo(
f"📦 Development mode: loading web components from ./{static_folder}/"
)
else:
click.echo(f"🌍 Production mode: loading web components from CDN")
try:
server.run(host=host, port=port, debug=debug)
except KeyboardInterrupt:
click.echo("\n👋 Server stopped")
else:
server = VannaFastAPIServer(agent, config=server_config)
click.echo(f"🚀 Starting FastAPI server on http://{host}:{port}")
click.echo(f"📖 API docs available at http://{host}:{port}/docs")
if dev:
click.echo(
f"📦 Development mode: loading web components from ./{static_folder}/"
)
else:
click.echo(f"🌍 Production mode: loading web components from CDN")
try:
server.run(host=host, port=port)
except KeyboardInterrupt:
click.echo("\n👋 Server stopped")
if __name__ == "__main__":
main()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/cli/server_runner.py",
"license": "MIT License",
"lines": 177,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/servers/fastapi/app.py | """
FastAPI server factory for Vanna Agents.
"""
from typing import Any, Dict, Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from ...core import Agent
from ..base import ChatHandler
from .routes import register_chat_routes
class VannaFastAPIServer:
"""FastAPI server factory for Vanna Agents."""
def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None):
"""Initialize FastAPI server.
Args:
agent: The agent to serve (must have user_resolver configured)
config: Optional server configuration
"""
self.agent = agent
self.config = config or {}
self.chat_handler = ChatHandler(agent)
def create_app(self) -> FastAPI:
"""Create configured FastAPI app.
Returns:
Configured FastAPI application
"""
# Create FastAPI app
app_config = self.config.get("fastapi", {})
app = FastAPI(
title="Vanna Agents API",
description="API server for Vanna Agents framework",
version="0.1.0",
**app_config,
)
# Configure CORS if enabled
cors_config = self.config.get("cors", {})
if cors_config.get("enabled", True):
cors_params = {k: v for k, v in cors_config.items() if k != "enabled"}
# Set sensible defaults
cors_params.setdefault("allow_origins", ["*"])
cors_params.setdefault("allow_credentials", True)
cors_params.setdefault("allow_methods", ["*"])
cors_params.setdefault("allow_headers", ["*"])
app.add_middleware(CORSMiddleware, **cors_params)
# Add static file serving in dev mode
dev_mode = self.config.get("dev_mode", False)
if dev_mode:
static_folder = self.config.get("static_folder", "static")
try:
import os
if os.path.exists(static_folder):
app.mount(
"/static", StaticFiles(directory=static_folder), name="static"
)
except Exception:
pass # Static files not available
# Register routes
register_chat_routes(app, self.chat_handler, self.config)
# Add health check
@app.get("/health")
async def health_check() -> Dict[str, str]:
return {"status": "healthy", "service": "vanna"}
return app
def run(self, **kwargs: Any) -> None:
"""Run the FastAPI server.
This method automatically detects if running in an async environment
(Jupyter, Colab, IPython, etc.) and:
- Uses appropriate async handling for existing event loops
- Sets up port forwarding if in Google Colab
- Displays the correct URL for accessing the app
Args:
**kwargs: Arguments passed to uvicorn configuration
"""
import sys
import asyncio
import uvicorn
# Check if we're in an environment with a running event loop FIRST
in_async_env = False
try:
asyncio.get_running_loop()
in_async_env = True
except RuntimeError:
in_async_env = False
# If in async environment, apply nest_asyncio BEFORE creating the app
if in_async_env:
try:
import nest_asyncio
nest_asyncio.apply()
except ImportError:
print("Warning: nest_asyncio not installed. Installing...")
import subprocess
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "nest_asyncio"]
)
import nest_asyncio
nest_asyncio.apply()
# Now create the app after nest_asyncio is applied
app = self.create_app()
# Set defaults
run_kwargs = {"host": "0.0.0.0", "port": 8000, "log_level": "info", **kwargs}
# Get the port and other config from run_kwargs
port = run_kwargs.get("port", 8000)
host = run_kwargs.get("host", "0.0.0.0")
log_level = run_kwargs.get("log_level", "info")
# Check if we're specifically in Google Colab for port forwarding
in_colab = "google.colab" in sys.modules
if in_colab:
try:
from google.colab import output
output.serve_kernel_port_as_window(port)
from google.colab.output import eval_js
print("Your app is running at:")
print(eval_js(f"google.colab.kernel.proxyPort({port})"))
except Exception as e:
print(f"Warning: Could not set up Colab port forwarding: {e}")
print(f"Your app is running at: http://localhost:{port}")
else:
print("Your app is running at:")
print(f"http://localhost:{port}")
if in_async_env:
# In Jupyter/Colab, create config with loop="asyncio" and use asyncio.run()
# This matches the working pattern from Colab
config = uvicorn.Config(
app, host=host, port=port, log_level=log_level, loop="asyncio"
)
server = uvicorn.Server(config)
asyncio.run(server.serve())
else:
# Normal execution outside of Jupyter/Colab
uvicorn.run(app, **run_kwargs)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/fastapi/app.py",
"license": "MIT License",
"lines": 130,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/servers/fastapi/routes.py | """
FastAPI route implementations for Vanna Agents.
"""
import json
import traceback
from typing import Any, AsyncGenerator, Dict, Optional
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import StreamingResponse, HTMLResponse
from ..base import ChatHandler, ChatRequest, ChatResponse
from ..base.templates import get_index_html
from ...core.user.request_context import RequestContext
def register_chat_routes(
app: FastAPI, chat_handler: ChatHandler, config: Optional[Dict[str, Any]] = None
) -> None:
"""Register chat routes on FastAPI app.
Args:
app: FastAPI application
chat_handler: Chat handler instance
config: Server configuration
"""
config = config or {}
@app.get("/", response_class=HTMLResponse)
async def index() -> str:
"""Serve the main chat interface."""
dev_mode = config.get("dev_mode", False)
cdn_url = config.get("cdn_url", "https://img.vanna.ai/vanna-components.js")
api_base_url = config.get("api_base_url", "")
return get_index_html(
dev_mode=dev_mode, cdn_url=cdn_url, api_base_url=api_base_url
)
@app.post("/api/vanna/v2/chat_sse")
async def chat_sse(
chat_request: ChatRequest, http_request: Request
) -> StreamingResponse:
"""Server-Sent Events endpoint for streaming chat."""
# Extract request context for user resolution
chat_request.request_context = RequestContext(
cookies=dict(http_request.cookies),
headers=dict(http_request.headers),
remote_addr=http_request.client.host if http_request.client else None,
query_params=dict(http_request.query_params),
metadata=chat_request.metadata,
)
async def generate() -> AsyncGenerator[str, None]:
"""Generate SSE stream."""
try:
async for chunk in chat_handler.handle_stream(chat_request):
chunk_json = chunk.model_dump_json()
yield f"data: {chunk_json}\n\n"
yield "data: [DONE]\n\n"
except Exception as e:
traceback.print_stack()
traceback.print_exc()
error_data = {
"type": "error",
"data": {"message": str(e)},
"conversation_id": chat_request.conversation_id or "",
"request_id": chat_request.request_id or "",
}
yield f"data: {json.dumps(error_data)}\n\n"
return StreamingResponse(
generate(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no", # Disable nginx buffering
},
)
@app.websocket("/api/vanna/v2/chat_websocket")
async def chat_websocket(websocket: WebSocket) -> None:
"""WebSocket endpoint for real-time chat."""
await websocket.accept()
try:
while True:
# Receive message
try:
data = await websocket.receive_json()
# Extract request context for user resolution
metadata = data.get("metadata", {})
data["request_context"] = RequestContext(
cookies=dict(websocket.cookies),
headers=dict(websocket.headers),
remote_addr=websocket.client.host if websocket.client else None,
query_params=dict(websocket.query_params),
metadata=metadata,
)
chat_request = ChatRequest(**data)
except Exception as e:
traceback.print_stack()
traceback.print_exc()
await websocket.send_json(
{
"type": "error",
"data": {"message": f"Invalid request: {str(e)}"},
}
)
continue
# Stream response
try:
async for chunk in chat_handler.handle_stream(chat_request):
await websocket.send_json(chunk.model_dump())
# Send completion signal
await websocket.send_json(
{
"type": "completion",
"data": {"status": "done"},
"conversation_id": chunk.conversation_id
if "chunk" in locals()
else "",
"request_id": chunk.request_id
if "chunk" in locals()
else "",
}
)
except Exception as e:
traceback.print_stack()
traceback.print_exc()
await websocket.send_json(
{
"type": "error",
"data": {"message": str(e)},
"conversation_id": chat_request.conversation_id or "",
"request_id": chat_request.request_id or "",
}
)
except WebSocketDisconnect:
pass
except Exception as e:
traceback.print_stack()
traceback.print_exc()
try:
await websocket.send_json(
{
"type": "error",
"data": {"message": f"WebSocket error: {str(e)}"},
}
)
except Exception:
pass
finally:
await websocket.close()
@app.post("/api/vanna/v2/chat_poll")
async def chat_poll(
chat_request: ChatRequest, http_request: Request
) -> ChatResponse:
"""Polling endpoint for chat."""
# Extract request context for user resolution
chat_request.request_context = RequestContext(
cookies=dict(http_request.cookies),
headers=dict(http_request.headers),
remote_addr=http_request.client.host if http_request.client else None,
query_params=dict(http_request.query_params),
metadata=chat_request.metadata,
)
try:
result = await chat_handler.handle_poll(chat_request)
return result
except Exception as e:
traceback.print_stack()
traceback.print_exc()
raise HTTPException(status_code=500, detail=f"Chat failed: {str(e)}")
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/fastapi/routes.py",
"license": "MIT License",
"lines": 162,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/servers/flask/app.py | """
Flask server factory for Vanna Agents.
"""
import asyncio
from typing import Any, Dict, Optional
from flask import Flask
from flask_cors import CORS
from ...core import Agent
from ..base import ChatHandler
from .routes import register_chat_routes
class VannaFlaskServer:
"""Flask server factory for Vanna Agents."""
def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None):
"""Initialize Flask server.
Args:
agent: The agent to serve (must have user_resolver configured)
config: Optional server configuration
"""
self.agent = agent
self.config = config or {}
self.chat_handler = ChatHandler(agent)
def create_app(self) -> Flask:
"""Create configured Flask app.
Returns:
Configured Flask application
"""
# Check if dev mode is enabled
dev_mode = self.config.get("dev_mode", False)
static_folder = self.config.get("static_folder", "static") if dev_mode else None
app = Flask(__name__, static_folder=static_folder, static_url_path="/static")
# Apply configuration
app.config.update(self.config.get("flask", {}))
# Enable CORS if configured
cors_config = self.config.get("cors", {})
if cors_config.get("enabled", True):
CORS(app, **{k: v for k, v in cors_config.items() if k != "enabled"})
# Register routes
register_chat_routes(app, self.chat_handler, self.config)
# Add health check
@app.route("/health")
def health_check() -> Dict[str, str]:
return {"status": "healthy", "service": "vanna"}
return app
def run(self, **kwargs: Any) -> None:
"""Run the Flask server.
This method automatically detects if running in an async environment
(Jupyter, Colab, IPython, etc.) and:
- Installs and applies nest_asyncio to handle existing event loops
- Sets up port forwarding if in Google Colab
- Displays the correct URL for accessing the app
Args:
**kwargs: Arguments passed to Flask.run()
"""
import sys
app = self.create_app()
# Set defaults
run_kwargs = {"host": "0.0.0.0", "port": 5000, "debug": False, **kwargs}
# Get the port from run_kwargs
port = run_kwargs.get("port", 5000)
# Check if we're in an environment with a running event loop
# (Jupyter, Colab, IPython, VS Code notebooks, etc.)
in_async_env = False
try:
import asyncio
try:
asyncio.get_running_loop()
in_async_env = True
except RuntimeError:
in_async_env = False
except Exception:
pass
if in_async_env:
# Apply nest_asyncio to allow nested event loops
try:
import nest_asyncio
nest_asyncio.apply()
except ImportError:
print("Warning: nest_asyncio not installed. Installing...")
import subprocess
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "nest_asyncio"]
)
import nest_asyncio
nest_asyncio.apply()
# Check if we're specifically in Google Colab for port forwarding
in_colab = "google.colab" in sys.modules
if in_colab:
try:
from google.colab import output
output.serve_kernel_port_as_window(port)
from google.colab.output import eval_js
print("Your app is running at:")
print(eval_js(f"google.colab.kernel.proxyPort({port})"))
except Exception as e:
print(f"Warning: Could not set up Colab port forwarding: {e}")
print(f"Your app is running at: http://localhost:{port}")
else:
print("Your app is running at:")
print(f"http://localhost:{port}")
app.run(**run_kwargs)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/flask/app.py",
"license": "MIT License",
"lines": 100,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/servers/flask/routes.py | """
Flask route implementations for Vanna Agents.
"""
import asyncio
import json
import traceback
from typing import Any, AsyncGenerator, Dict, Generator, Optional, Union
from flask import Flask, Response, jsonify, request
from ..base import ChatHandler, ChatRequest
from ..base.templates import get_index_html
from ...core.user.request_context import RequestContext
def register_chat_routes(
app: Flask, chat_handler: ChatHandler, config: Optional[Dict[str, Any]] = None
) -> None:
"""Register chat routes on Flask app.
Args:
app: Flask application
chat_handler: Chat handler instance
config: Server configuration
"""
config = config or {}
@app.route("/")
def index() -> str:
"""Serve the main chat interface."""
dev_mode = config.get("dev_mode", False)
cdn_url = config.get("cdn_url", "https://img.vanna.ai/vanna-components.js")
api_base_url = config.get("api_base_url", "")
return get_index_html(
dev_mode=dev_mode, cdn_url=cdn_url, api_base_url=api_base_url
)
@app.route("/api/vanna/v2/chat_sse", methods=["POST"])
def chat_sse() -> Union[Response, tuple[Response, int]]:
"""Server-Sent Events endpoint for streaming chat."""
try:
data = request.get_json()
if not data:
return jsonify({"error": "JSON body required"}), 400
# Extract request context for user resolution
data["request_context"] = RequestContext(
cookies=dict(request.cookies),
headers=dict(request.headers),
remote_addr=request.remote_addr,
query_params=dict(request.args),
)
chat_request = ChatRequest(**data)
except Exception as e:
traceback.print_stack()
traceback.print_exc()
return jsonify({"error": f"Invalid request: {str(e)}"}), 400
def generate() -> Generator[str, None, None]:
"""Generate SSE stream."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
async def async_generate() -> AsyncGenerator[str, None]:
async for chunk in chat_handler.handle_stream(chat_request):
chunk_json = chunk.model_dump_json()
yield f"data: {chunk_json}\n\n"
gen = async_generate()
try:
while True:
chunk = loop.run_until_complete(gen.__anext__())
yield chunk
except StopAsyncIteration:
yield "data: [DONE]\n\n"
finally:
loop.close()
return Response(
generate(),
mimetype="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no", # Disable nginx buffering
},
)
@app.route("/api/vanna/v2/chat_websocket")
def chat_websocket() -> tuple[Response, int]:
"""WebSocket endpoint placeholder."""
return jsonify(
{
"error": "WebSocket endpoint not implemented in basic Flask example",
"suggestion": "Use Flask-SocketIO for WebSocket support",
}
), 501
@app.route("/api/vanna/v2/chat_poll", methods=["POST"])
def chat_poll() -> Union[Response, tuple[Response, int]]:
"""Polling endpoint for chat."""
try:
data = request.get_json()
if not data:
return jsonify({"error": "JSON body required"}), 400
# Extract request context for user resolution
data["request_context"] = RequestContext(
cookies=dict(request.cookies),
headers=dict(request.headers),
remote_addr=request.remote_addr,
query_params=dict(request.args),
)
chat_request = ChatRequest(**data)
except Exception as e:
traceback.print_stack()
traceback.print_exc()
return jsonify({"error": f"Invalid request: {str(e)}"}), 400
# Run async handler in new event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(chat_handler.handle_poll(chat_request))
return jsonify(result.model_dump())
except Exception as e:
traceback.print_stack()
traceback.print_exc()
return jsonify({"error": f"Chat failed: {str(e)}"}), 500
finally:
loop.close()
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/servers/flask/routes.py",
"license": "MIT License",
"lines": 116,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/tools/agent_memory.py | """
Agent memory tools.
This module provides agent memory operations through an abstract AgentMemory interface,
allowing for different implementations (local vector DB, remote cloud service, etc.).
The tools access AgentMemory via ToolContext, which is populated by the Agent.
"""
import logging
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Field
logger = logging.getLogger(__name__)
from vanna.core.tool import Tool, ToolContext, ToolResult
from vanna.core.agent.config import UiFeature
from vanna.capabilities.agent_memory import AgentMemory
from vanna.components import (
UiComponent,
StatusBarUpdateComponent,
CardComponent,
)
class SaveQuestionToolArgsParams(BaseModel):
"""Parameters for saving question-tool-argument combinations."""
question: str = Field(description="The original question that was asked")
tool_name: str = Field(
description="The name of the tool that was used successfully"
)
args: Dict[str, Any] = Field(
description="The arguments that were passed to the tool"
)
class SearchSavedCorrectToolUsesParams(BaseModel):
"""Parameters for searching saved tool usage patterns."""
question: str = Field(
description="The question to find similar tool usage patterns for"
)
limit: Optional[int] = Field(
default=10, description="Maximum number of results to return"
)
similarity_threshold: Optional[float] = Field(
default=0.7, description="Minimum similarity score for results (0.0-1.0)"
)
tool_name_filter: Optional[str] = Field(
default=None, description="Filter results to specific tool name"
)
class SaveTextMemoryParams(BaseModel):
"""Parameters for saving free-form text memories."""
content: str = Field(description="The text content to save as a memory")
class SaveQuestionToolArgsTool(Tool[SaveQuestionToolArgsParams]):
"""Tool for saving successful question-tool-argument combinations."""
@property
def name(self) -> str:
return "save_question_tool_args"
@property
def description(self) -> str:
return (
"Save a successful question-tool-argument combination for future reference"
)
def get_args_schema(self) -> Type[SaveQuestionToolArgsParams]:
return SaveQuestionToolArgsParams
async def execute(
self, context: ToolContext, args: SaveQuestionToolArgsParams
) -> ToolResult:
"""Save the tool usage pattern to agent memory."""
try:
await context.agent_memory.save_tool_usage(
question=args.question,
tool_name=args.tool_name,
args=args.args,
context=context,
success=True,
)
success_msg = (
f"Successfully saved usage pattern for '{args.tool_name}' tool"
)
return ToolResult(
success=True,
result_for_llm=success_msg,
ui_component=UiComponent(
rich_component=StatusBarUpdateComponent(
status="success",
message="Saved to memory",
detail=f"Saved pattern for '{args.tool_name}'",
),
simple_component=None,
),
)
except Exception as e:
error_message = f"Failed to save memory: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_message,
ui_component=UiComponent(
rich_component=StatusBarUpdateComponent(
status="error", message="Failed to save memory", detail=str(e)
),
simple_component=None,
),
error=str(e),
)
class SearchSavedCorrectToolUsesTool(Tool[SearchSavedCorrectToolUsesParams]):
"""Tool for searching saved tool usage patterns."""
@property
def name(self) -> str:
return "search_saved_correct_tool_uses"
@property
def description(self) -> str:
return "Search for similar tool usage patterns based on a question"
def get_args_schema(self) -> Type[SearchSavedCorrectToolUsesParams]:
return SearchSavedCorrectToolUsesParams
async def execute(
self, context: ToolContext, args: SearchSavedCorrectToolUsesParams
) -> ToolResult:
"""Search for similar tool usage patterns."""
try:
results = await context.agent_memory.search_similar_usage(
question=args.question,
context=context,
limit=args.limit or 10,
similarity_threshold=args.similarity_threshold or 0.7,
tool_name_filter=args.tool_name_filter,
)
if not results:
no_results_msg = (
"No similar tool usage patterns found for this question."
)
# Check if user has access to detailed memory results
ui_features_available = context.metadata.get(
"ui_features_available", []
)
show_detailed_results = (
UiFeature.UI_FEATURE_SHOW_MEMORY_DETAILED_RESULTS
in ui_features_available
)
# Create UI component based on access level
if show_detailed_results:
# Admin view: Show card indicating 0 results
ui_component = UiComponent(
rich_component=CardComponent(
title="🧠 Memory Search: 0 Results",
content="No similar tool usage patterns found for this question.\n\nSearched agent memory with no matches.",
icon="🔍",
status="info",
collapsible=True,
collapsed=True,
markdown=True,
),
simple_component=None,
)
else:
# Non-admin view: Simple status message
ui_component = UiComponent(
rich_component=StatusBarUpdateComponent(
status="idle",
message="No similar patterns found",
detail="Searched agent memory",
),
simple_component=None,
)
return ToolResult(
success=True,
result_for_llm=no_results_msg,
ui_component=ui_component,
)
# Format results for LLM
results_text = f"Found {len(results)} similar tool usage pattern(s):\n\n"
for i, result in enumerate(results, 1):
memory = result.memory
results_text += f"{i}. {memory.tool_name} (similarity: {result.similarity_score:.2f})\n"
results_text += f" Question: {memory.question}\n"
results_text += f" Args: {memory.args}\n\n"
logger.info(f"Agent memory search results: {results_text.strip()}")
# Check if user has access to detailed memory results
ui_features_available = context.metadata.get("ui_features_available", [])
show_detailed_results = (
UiFeature.UI_FEATURE_SHOW_MEMORY_DETAILED_RESULTS
in ui_features_available
)
# Create UI component based on access level
if show_detailed_results:
# Admin view: Show detailed results in collapsible card
detailed_content = "**Retrieved memories passed to LLM:**\n\n"
for i, result in enumerate(results, 1):
memory = result.memory
detailed_content += f"**{i}. {memory.tool_name}** (similarity: {result.similarity_score:.2f})\n"
detailed_content += f"- **Question:** {memory.question}\n"
detailed_content += f"- **Arguments:** `{memory.args}`\n"
if memory.timestamp:
detailed_content += f"- **Timestamp:** {memory.timestamp}\n"
if memory.memory_id:
detailed_content += f"- **ID:** `{memory.memory_id}`\n"
detailed_content += "\n"
ui_component = UiComponent(
rich_component=CardComponent(
title=f"🧠 Memory Search: {len(results)} Result(s)",
content=detailed_content.strip(),
icon="🔍",
status="info",
collapsible=True,
collapsed=True, # Start collapsed to avoid clutter
markdown=True, # Render content as markdown
),
simple_component=None,
)
else:
# Non-admin view: Simple status message
ui_component = UiComponent(
rich_component=StatusBarUpdateComponent(
status="success",
message=f"Found {len(results)} similar pattern(s)",
detail="Retrieved from agent memory",
),
simple_component=None,
)
return ToolResult(
success=True,
result_for_llm=results_text.strip(),
ui_component=ui_component,
)
except Exception as e:
error_message = f"Failed to search memories: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_message,
ui_component=UiComponent(
rich_component=StatusBarUpdateComponent(
status="error", message="Failed to search memory", detail=str(e)
),
simple_component=None,
),
error=str(e),
)
class SaveTextMemoryTool(Tool[SaveTextMemoryParams]):
"""Tool for saving free-form text memories."""
@property
def name(self) -> str:
return "save_text_memory"
@property
def description(self) -> str:
return "Save free-form text memory for important insights, observations, or context"
def get_args_schema(self) -> Type[SaveTextMemoryParams]:
return SaveTextMemoryParams
async def execute(
self, context: ToolContext, args: SaveTextMemoryParams
) -> ToolResult:
"""Save a text memory to agent memory."""
try:
text_memory = await context.agent_memory.save_text_memory(
content=args.content, context=context
)
success_msg = (
f"Successfully saved text memory with ID: {text_memory.memory_id}"
)
return ToolResult(
success=True,
result_for_llm=success_msg,
ui_component=UiComponent(
rich_component=StatusBarUpdateComponent(
status="success",
message="Saved text memory",
detail=f"ID: {text_memory.memory_id}",
),
simple_component=None,
),
)
except Exception as e:
error_message = f"Failed to save text memory: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_message,
ui_component=UiComponent(
rich_component=StatusBarUpdateComponent(
status="error",
message="Failed to save text memory",
detail=str(e),
),
simple_component=None,
),
error=str(e),
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/tools/agent_memory.py",
"license": "MIT License",
"lines": 276,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/tools/file_system.py | """
File system tools with dependency injection support.
This module provides file system operations through an abstract FileSystem interface,
allowing for different implementations (local, remote, sandboxed, etc.).
The tools accept a FileSystem instance via dependency injection.
"""
import asyncio
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import Any, List, Optional, Type
import difflib
import hashlib
from pydantic import BaseModel, Field, model_validator
from vanna.core.tool import Tool, ToolContext, ToolResult
from vanna.components import (
UiComponent,
CardComponent,
NotificationComponent,
ComponentType,
SimpleTextComponent,
)
MAX_SEARCH_FILE_BYTES = 1_000_000
FILENAME_MATCH_SNIPPET = "[filename match]"
@dataclass
class FileSearchMatch:
"""Represents a single search result within a file system."""
path: str
snippet: Optional[str] = None
@dataclass
class CommandResult:
"""Represents the result of executing a shell command."""
stdout: str
stderr: str
returncode: int
def _make_snippet(text: str, query: str, context_window: int = 60) -> Optional[str]:
"""Return a short snippet around the first occurrence of query in text."""
lowered = text.lower()
index = lowered.find(query.lower())
if index == -1:
return None
start = max(0, index - context_window)
end = min(len(text), index + len(query) + context_window)
snippet = text[start:end].replace("\n", " ").strip()
if start > 0:
snippet = f"…{snippet}"
if end < len(text):
snippet = f"{snippet}…"
return snippet
class FileSystem(ABC):
"""Abstract base class for file system operations."""
@abstractmethod
async def list_files(self, directory: str, context: ToolContext) -> List[str]:
"""List files in a directory."""
pass
@abstractmethod
async def read_file(self, filename: str, context: ToolContext) -> str:
"""Read the contents of a file."""
pass
@abstractmethod
async def write_file(
self, filename: str, content: str, context: ToolContext, overwrite: bool = False
) -> None:
"""Write content to a file."""
pass
@abstractmethod
async def exists(self, path: str, context: ToolContext) -> bool:
"""Check if a file or directory exists."""
pass
@abstractmethod
async def is_directory(self, path: str, context: ToolContext) -> bool:
"""Check if a path is a directory."""
pass
@abstractmethod
async def search_files(
self,
query: str,
context: ToolContext,
*,
max_results: int = 20,
include_content: bool = False,
) -> List[FileSearchMatch]:
"""Search for files matching a query within the accessible namespace."""
pass
@abstractmethod
async def run_bash(
self,
command: str,
context: ToolContext,
*,
timeout: Optional[float] = None,
) -> CommandResult:
"""Execute a bash command within the accessible namespace."""
pass
class LocalFileSystem(FileSystem):
"""Local file system implementation with per-user isolation."""
def __init__(self, working_directory: str = "."):
"""Initialize with a working directory.
Args:
working_directory: Base directory where user-specific folders will be created
"""
self.working_directory = Path(working_directory)
def _get_user_directory(self, context: ToolContext) -> Path:
"""Get the user-specific directory by hashing the user ID.
Args:
context: Tool context containing user information
Returns:
Path to the user-specific directory
"""
# Hash the user ID to create a directory name
user_hash = hashlib.sha256(context.user.id.encode()).hexdigest()[:16]
user_dir = self.working_directory / user_hash
# Create the directory if it doesn't exist
user_dir.mkdir(parents=True, exist_ok=True)
return user_dir
def _resolve_path(self, path: str, context: ToolContext) -> Path:
"""Resolve a path relative to the user's directory.
Args:
path: Path relative to user directory
context: Tool context containing user information
Returns:
Absolute path within user's directory
"""
user_dir = self._get_user_directory(context)
resolved = user_dir / path
# Ensure the path is within the user's directory (prevent directory traversal)
try:
resolved.resolve().relative_to(user_dir.resolve())
except ValueError:
raise PermissionError(
f"Access denied: path '{path}' is outside user directory"
)
return resolved
async def list_files(self, directory: str, context: ToolContext) -> List[str]:
"""List files in a directory within the user's isolated space."""
directory_path = self._resolve_path(directory, context)
if not directory_path.exists():
raise FileNotFoundError(f"Directory '{directory}' does not exist")
if not directory_path.is_dir():
raise NotADirectoryError(f"'{directory}' is not a directory")
files = []
for item in directory_path.iterdir():
if item.is_file():
files.append(item.name)
return sorted(files)
async def read_file(self, filename: str, context: ToolContext) -> str:
"""Read the contents of a file within the user's isolated space."""
file_path = self._resolve_path(filename, context)
if not file_path.exists():
raise FileNotFoundError(f"File '{filename}' does not exist")
if not file_path.is_file():
raise IsADirectoryError(f"'{filename}' is a directory, not a file")
return file_path.read_text(encoding="utf-8")
async def write_file(
self, filename: str, content: str, context: ToolContext, overwrite: bool = False
) -> None:
"""Write content to a file within the user's isolated space."""
file_path = self._resolve_path(filename, context)
# Create parent directories if they don't exist
file_path.parent.mkdir(parents=True, exist_ok=True)
if file_path.exists() and not overwrite:
raise FileExistsError(
f"File '{filename}' already exists. Use overwrite=True to replace it."
)
file_path.write_text(content, encoding="utf-8")
async def exists(self, path: str, context: ToolContext) -> bool:
"""Check if a file or directory exists within the user's isolated space."""
try:
resolved_path = self._resolve_path(path, context)
return resolved_path.exists()
except PermissionError:
return False
async def is_directory(self, path: str, context: ToolContext) -> bool:
"""Check if a path is a directory within the user's isolated space."""
try:
resolved_path = self._resolve_path(path, context)
return resolved_path.exists() and resolved_path.is_dir()
except PermissionError:
return False
async def search_files(
self,
query: str,
context: ToolContext,
*,
max_results: int = 20,
include_content: bool = False,
) -> List[FileSearchMatch]:
"""Search for files within the user's isolated space."""
trimmed_query = query.strip()
if not trimmed_query:
raise ValueError("Search query must not be empty")
user_dir = self._get_user_directory(context)
matches: List[FileSearchMatch] = []
query_lower = trimmed_query.lower()
for path in user_dir.rglob("*"):
if len(matches) >= max_results:
break
if not path.is_file():
continue
relative_path = path.relative_to(user_dir).as_posix()
include_entry = False
snippet: Optional[str] = None
if query_lower in path.name.lower():
include_entry = True
snippet = FILENAME_MATCH_SNIPPET
content: Optional[str] = None
if include_content:
try:
size = path.stat().st_size
except OSError:
if include_entry:
matches.append(
FileSearchMatch(path=relative_path, snippet=snippet)
)
continue
if size <= MAX_SEARCH_FILE_BYTES:
try:
content = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
content = None
elif not include_entry:
# Skip oversized files if they do not match by name
continue
if include_content and content is not None:
if query_lower in content.lower():
snippet = _make_snippet(content, trimmed_query) or snippet
include_entry = True
elif not include_entry:
continue
if include_entry:
matches.append(FileSearchMatch(path=relative_path, snippet=snippet))
return matches
async def run_bash(
self,
command: str,
context: ToolContext,
*,
timeout: Optional[float] = None,
) -> CommandResult:
"""Execute a bash command within the user's isolated space."""
if not command.strip():
raise ValueError("Command must not be empty")
user_dir = self._get_user_directory(context)
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=str(user_dir),
)
try:
stdout_bytes, stderr_bytes = await asyncio.wait_for(
process.communicate(), timeout=timeout
)
except asyncio.TimeoutError as exc:
process.kill()
await process.wait()
raise TimeoutError(f"Command timed out after {timeout} seconds") from exc
stdout = stdout_bytes.decode("utf-8", errors="replace")
stderr = stderr_bytes.decode("utf-8", errors="replace")
return CommandResult(
stdout=stdout, stderr=stderr, returncode=process.returncode or 0
)
class SearchFilesArgs(BaseModel):
"""Arguments for searching files."""
query: str = Field(description="Text to search for in file names or contents")
include_content: bool = Field(
default=True,
description="Whether to search within file contents in addition to file names",
)
max_results: int = Field(
default=20,
ge=1,
le=100,
description="Maximum number of matches to return",
)
class SearchFilesTool(Tool[SearchFilesArgs]):
"""Tool to search for files using the injected file system implementation."""
def __init__(self, file_system: Optional[FileSystem] = None):
self.file_system = file_system or LocalFileSystem()
@property
def name(self) -> str:
return "search_files"
@property
def description(self) -> str:
return "Search for files by name or content"
def get_args_schema(self) -> Type[SearchFilesArgs]:
return SearchFilesArgs
async def execute(self, context: ToolContext, args: SearchFilesArgs) -> ToolResult:
try:
matches = await self.file_system.search_files(
args.query,
context,
max_results=args.max_results,
include_content=args.include_content,
)
except Exception as exc:
error_msg = f"Error searching files: {exc}"
return ToolResult(
success=False,
result_for_llm=error_msg,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_msg,
),
simple_component=SimpleTextComponent(text=error_msg),
),
error=str(exc),
)
if not matches:
message = f"No matches found for '{args.query}'."
return ToolResult(
success=True,
result_for_llm=message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="info",
message=message,
),
simple_component=SimpleTextComponent(text=message),
),
)
lines: List[str] = []
for match in matches:
snippet = match.snippet
if snippet == FILENAME_MATCH_SNIPPET:
snippet_text = "(matched filename)"
elif snippet:
snippet_text = snippet
else:
snippet_text = ""
if snippet_text and len(snippet_text) > 200:
snippet_text = f"{snippet_text[:197]}…"
if snippet_text:
lines.append(f"- {match.path}: {snippet_text}")
else:
lines.append(f"- {match.path}")
summary = f"Found {len(matches)} match(es) for '{args.query}' (max {args.max_results})."
content = "\n".join(lines)
return ToolResult(
success=True,
result_for_llm=f"{summary}\n{content}",
ui_component=UiComponent(
rich_component=CardComponent(
type=ComponentType.CARD,
title=f"Search results for '{args.query}'",
content=content,
),
simple_component=SimpleTextComponent(text=summary),
),
)
class ListFilesArgs(BaseModel):
"""Arguments for listing files."""
directory: str = Field(
default=".", description="Directory to list (defaults to current)"
)
class ListFilesTool(Tool[ListFilesArgs]):
"""Tool to list files in a directory using dependency injection for file system access."""
def __init__(self, file_system: Optional[FileSystem] = None):
"""Initialize with optional file system dependency."""
self.file_system = file_system or LocalFileSystem()
@property
def name(self) -> str:
return "list_files"
@property
def description(self) -> str:
return "List files in a directory"
def get_args_schema(self) -> Type[ListFilesArgs]:
return ListFilesArgs
async def execute(self, context: ToolContext, args: ListFilesArgs) -> ToolResult:
try:
files = await self.file_system.list_files(args.directory, context)
if not files:
result = f"No files found in directory '{args.directory}'"
files_list = "No files found"
else:
files_list = "\n".join(f"- {f}" for f in files)
result = f"Files in '{args.directory}':\n{files_list}"
return ToolResult(
success=True,
result_for_llm=result,
ui_component=UiComponent(
rich_component=CardComponent(
type=ComponentType.CARD,
title=f"Files in {args.directory}",
content=files_list,
),
simple_component=SimpleTextComponent(text=result),
),
)
except Exception as e:
error_msg = f"Error listing files: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_msg,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_msg,
),
simple_component=SimpleTextComponent(text=error_msg),
),
error=str(e),
)
class ReadFileArgs(BaseModel):
"""Arguments for reading a file."""
filename: str = Field(description="Name of the file to read")
class ReadFileTool(Tool[ReadFileArgs]):
"""Tool to read file contents using dependency injection for file system access."""
def __init__(self, file_system: Optional[FileSystem] = None):
"""Initialize with optional file system dependency."""
self.file_system = file_system or LocalFileSystem()
@property
def name(self) -> str:
return "read_file"
@property
def description(self) -> str:
return "Read the contents of a file"
def get_args_schema(self) -> Type[ReadFileArgs]:
return ReadFileArgs
async def execute(self, context: ToolContext, args: ReadFileArgs) -> ToolResult:
try:
content = await self.file_system.read_file(args.filename, context)
result = f"Content of '{args.filename}':\n\n{content}"
return ToolResult(
success=True,
result_for_llm=result,
ui_component=UiComponent(
rich_component=CardComponent(
type=ComponentType.CARD,
title=f"Contents of {args.filename}",
content=content,
),
simple_component=SimpleTextComponent(
text=f"File content:\n{content}"
),
),
)
except Exception as e:
error_msg = f"Error reading file: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_msg,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_msg,
),
simple_component=SimpleTextComponent(text=error_msg),
),
error=str(e),
)
class WriteFileArgs(BaseModel):
"""Arguments for writing a file."""
filename: str = Field(description="Name of the file to write")
content: str = Field(description="Content to write to the file")
overwrite: bool = Field(
default=False, description="Whether to overwrite existing files"
)
class WriteFileTool(Tool[WriteFileArgs]):
"""Tool to write content to a file using dependency injection for file system access."""
def __init__(self, file_system: Optional[FileSystem] = None):
"""Initialize with optional file system dependency."""
self.file_system = file_system or LocalFileSystem()
@property
def name(self) -> str:
return "write_file"
@property
def description(self) -> str:
return "Write content to a file"
def get_args_schema(self) -> Type[WriteFileArgs]:
return WriteFileArgs
async def execute(self, context: ToolContext, args: WriteFileArgs) -> ToolResult:
try:
await self.file_system.write_file(
args.filename, args.content, context, args.overwrite
)
success_msg = f"Successfully wrote {len(args.content)} characters to '{args.filename}'"
return ToolResult(
success=True,
result_for_llm=success_msg,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="success",
message=f"File '{args.filename}' written successfully",
),
simple_component=SimpleTextComponent(
text=f"Wrote to {args.filename}"
),
),
)
except Exception as e:
error_msg = f"Error writing file: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_msg,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_msg,
),
simple_component=SimpleTextComponent(text=error_msg),
),
error=str(e),
)
class LineEdit(BaseModel):
"""Definition of a single line-based edit operation."""
start_line: int = Field(
ge=1, description="First line (1-based) affected by this edit"
)
end_line: Optional[int] = Field(
default=None,
description=(
"Last line (1-based, inclusive) to replace. Set to start_line - 1 to insert before start_line. "
"Defaults to start_line, replacing a single line."
),
)
new_content: str = Field(
default="", description="Replacement text (preserves provided newlines)"
)
@model_validator(mode="after")
def validate_line_range(self) -> "LineEdit":
effective_end = self.start_line if self.end_line is None else self.end_line
if effective_end < self.start_line - 1:
raise ValueError("end_line must be >= start_line - 1")
return self
class EditFileArgs(BaseModel):
"""Arguments for editing one or more sections within a file."""
filename: str = Field(description="Path to the file to edit")
edits: List[LineEdit] = Field(
description="List of edits to apply. Later entries should reference higher line numbers.",
min_length=1,
)
class EditFileTool(Tool[EditFileArgs]):
"""Tool to apply line-based edits to an existing file."""
def __init__(self, file_system: Optional[FileSystem] = None):
self.file_system = file_system or LocalFileSystem()
@property
def name(self) -> str:
return "edit_file"
@property
def description(self) -> str:
return "Modify specific lines within a file"
def get_args_schema(self) -> Type[EditFileArgs]:
return EditFileArgs
async def execute(self, context: ToolContext, args: EditFileArgs) -> ToolResult:
try:
original_content = await self.file_system.read_file(args.filename, context)
except Exception as exc:
error_msg = f"Error loading file '{args.filename}': {exc}"
return ToolResult(
success=False,
result_for_llm=error_msg,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_msg,
),
simple_component=SimpleTextComponent(text=error_msg),
),
error=str(exc),
)
lines = original_content.splitlines(keepends=True)
applied_edits: List[str] = []
# Apply edits starting from the bottom so line numbers remain valid for each operation
for edit in sorted(args.edits, key=lambda e: e.start_line, reverse=True):
start_line = edit.start_line
end_line = edit.end_line if edit.end_line is not None else edit.start_line
if start_line < 1:
return self._range_error(
args.filename, start_line, end_line, "start_line must be >= 1"
)
if end_line < start_line - 1:
return self._range_error(
args.filename,
start_line,
end_line,
"end_line must be >= start_line - 1",
)
is_insertion = end_line == start_line - 1
if not is_insertion and start_line > len(lines):
return self._range_error(
args.filename,
start_line,
end_line,
f"start_line {start_line} is beyond the end of the file (len={len(lines)})",
)
if is_insertion:
if start_line > len(lines) + 1:
return self._range_error(
args.filename,
start_line,
end_line,
"Cannot insert beyond one line past the end of the file",
)
start_index = min(start_line - 1, len(lines))
end_index = start_index
else:
if end_line > len(lines):
return self._range_error(
args.filename,
start_line,
end_line,
f"end_line {end_line} is beyond the end of the file (len={len(lines)})",
)
start_index = start_line - 1
end_index = end_line
replacement_lines = edit.new_content.splitlines(keepends=True)
lines[start_index:end_index] = replacement_lines
if is_insertion:
inserted_count = len(replacement_lines)
applied_edits.append(
f"Inserted {inserted_count} line(s) at line {start_line}"
)
else:
removed_count = end_line - start_line + 1
applied_edits.append(
f"Replaced lines {start_line}-{end_line} (removed {removed_count} line(s))"
)
new_content = "".join(lines)
if new_content == original_content:
message = (
f"No changes applied to '{args.filename}' (content already up to date)."
)
return ToolResult(
success=True,
result_for_llm=message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="info",
message=message,
),
simple_component=SimpleTextComponent(text=message),
),
)
try:
await self.file_system.write_file(
args.filename, new_content, context, overwrite=True
)
except Exception as exc:
error_msg = f"Error writing updated contents to '{args.filename}': {exc}"
return ToolResult(
success=False,
result_for_llm=error_msg,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_msg,
),
simple_component=SimpleTextComponent(text=error_msg),
),
error=str(exc),
)
diff_lines = list(
difflib.unified_diff(
original_content.splitlines(),
new_content.splitlines(),
fromfile=f"a/{args.filename}",
tofile=f"b/{args.filename}",
lineterm="",
)
)
diff_text = (
"\n".join(diff_lines) if diff_lines else "(No textual diff available)"
)
summary = (
f"Updated '{args.filename}' with {len(args.edits)} edit(s).\n"
+ "\n".join(reversed(applied_edits))
)
return ToolResult(
success=True,
result_for_llm=f"{summary}\n\n{diff_text}",
ui_component=UiComponent(
rich_component=CardComponent(
type=ComponentType.CARD,
title=f"Edited {args.filename}",
content=diff_text,
),
simple_component=SimpleTextComponent(text=summary),
),
)
def _range_error(
self, filename: str, start_line: int, end_line: int, message: str
) -> ToolResult:
error_msg = f"Invalid edit range for '{filename}': start_line={start_line}, end_line={end_line}. {message}"
return ToolResult(
success=False,
result_for_llm=error_msg,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_msg,
),
simple_component=SimpleTextComponent(text=error_msg),
),
error=message,
)
# Convenience function for creating tools with default local file system
def create_file_system_tools(
file_system: Optional[FileSystem] = None,
) -> List[Tool[Any]]:
"""Create a set of file system tools with optional dependency injection."""
fs = file_system or LocalFileSystem()
return [
ListFilesTool(fs),
SearchFilesTool(fs),
ReadFileTool(fs),
WriteFileTool(fs),
EditFileTool(fs),
]
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/tools/file_system.py",
"license": "MIT License",
"lines": 720,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/tools/python.py | """Python-specific tooling built on top of the file system service."""
from __future__ import annotations
import shlex
import sys
from typing import Any, List, Optional, Sequence, Type
from pydantic import BaseModel, Field
from vanna.components import (
UiComponent,
CardComponent,
ComponentType,
NotificationComponent,
SimpleTextComponent,
)
from vanna.core.tool import Tool, ToolContext, ToolResult
from .file_system import CommandResult, FileSystem, LocalFileSystem
MAX_OUTPUT_LENGTH = 4000
class RunPythonFileArgs(BaseModel):
"""Arguments required to execute a Python file."""
filename: str = Field(
description="Python file to execute (relative to the workspace root)"
)
arguments: Sequence[str] = Field(
default_factory=list,
description="Optional arguments to pass to the Python script",
)
timeout_seconds: Optional[float] = Field(
default=None,
ge=0,
description="Optional timeout for the command in seconds",
)
class RunPythonFileTool(Tool[RunPythonFileArgs]):
"""Execute a Python file using the provided file system service."""
def __init__(self, file_system: Optional[FileSystem] = None):
self.file_system = file_system or LocalFileSystem()
@property
def name(self) -> str:
return "run_python_file"
@property
def description(self) -> str:
return "Execute a Python file using the workspace interpreter"
def get_args_schema(self) -> Type[RunPythonFileArgs]:
return RunPythonFileArgs
async def execute(
self, context: ToolContext, args: RunPythonFileArgs
) -> ToolResult:
exists = await self.file_system.exists(args.filename, context)
if not exists:
message = f"Cannot execute '{args.filename}' because it does not exist."
return _error_result(message)
command_parts = [sys.executable, args.filename]
command_parts.extend(args.arguments)
command = _quote_command(command_parts)
try:
result = await self.file_system.run_bash(
command,
context,
timeout=args.timeout_seconds,
)
except TimeoutError as exc:
message = str(exc)
return _error_result(message)
summary = f"Executed python {args.filename} (exit code {result.returncode})."
success = result.returncode == 0
return _result_from_command(summary, command, result, success=success)
class PipInstallArgs(BaseModel):
"""Arguments required to run pip install."""
packages: List[str] = Field(
description="Packages (with optional specifiers) to install", min_length=1
)
upgrade: bool = Field(
default=False,
description="Whether to include --upgrade in the pip invocation",
)
extra_args: Sequence[str] = Field(
default_factory=list,
description="Additional arguments to pass to pip install",
)
timeout_seconds: Optional[float] = Field(
default=None,
ge=0,
description="Optional timeout for the command in seconds",
)
class PipInstallTool(Tool[PipInstallArgs]):
"""Install Python packages using pip inside the workspace environment."""
def __init__(self, file_system: Optional[FileSystem] = None):
self.file_system = file_system or LocalFileSystem()
@property
def name(self) -> str:
return "pip_install"
@property
def description(self) -> str:
return "Install Python packages using pip"
def get_args_schema(self) -> Type[PipInstallArgs]:
return PipInstallArgs
async def execute(self, context: ToolContext, args: PipInstallArgs) -> ToolResult:
command_parts = [sys.executable, "-m", "pip", "install"]
if args.upgrade:
command_parts.append("--upgrade")
command_parts.extend(args.packages)
command_parts.extend(args.extra_args)
command = _quote_command(command_parts)
try:
result = await self.file_system.run_bash(
command,
context,
timeout=args.timeout_seconds,
)
except TimeoutError as exc:
return _error_result(str(exc))
success = result.returncode == 0
summary = (
"pip install completed successfully"
if success
else f"pip install failed (exit code {result.returncode})."
)
return _result_from_command(summary, command, result, success=success)
def create_python_tools(file_system: Optional[FileSystem] = None) -> List[Tool[Any]]:
"""Create Python-specific tools backed by a shared file system service."""
fs = file_system or LocalFileSystem()
return [
RunPythonFileTool(fs),
PipInstallTool(fs),
]
def _quote_command(parts: Sequence[str]) -> str:
return " ".join(shlex.quote(part) for part in parts)
def _truncate(text: str, limit: int = MAX_OUTPUT_LENGTH) -> str:
if len(text) <= limit:
return text
return f"{text[: limit - 1]}…"
def _result_from_command(
summary: str,
command: str,
result: CommandResult,
*,
success: bool = True,
) -> ToolResult:
stdout = result.stdout.strip()
stderr = result.stderr.strip()
blocks: List[str] = [f"$ {command}"]
if stdout:
blocks.append("STDOUT:\n" + _truncate(stdout))
if stderr:
blocks.append("STDERR:\n" + _truncate(stderr))
if not stdout and not stderr:
blocks.append("(no output)")
content = "\n\n".join(blocks)
card_status = "success" if success else "error"
component = CardComponent(
type=ComponentType.CARD,
title="Command Result",
content=content,
status=card_status,
)
return ToolResult(
success=success,
result_for_llm=f"{summary}\n\n{content}",
ui_component=UiComponent(
rich_component=component,
simple_component=SimpleTextComponent(text=summary),
),
error=None if success else content,
)
def _error_result(message: str) -> ToolResult:
return ToolResult(
success=False,
result_for_llm=message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=message,
),
simple_component=SimpleTextComponent(text=message),
),
error=message,
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/tools/python.py",
"license": "MIT License",
"lines": 176,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/tools/run_sql.py | """Generic SQL query execution tool with dependency injection."""
from typing import Any, Dict, List, Optional, Type, cast
import uuid
from vanna.core.tool import Tool, ToolContext, ToolResult
from vanna.components import (
UiComponent,
DataFrameComponent,
NotificationComponent,
ComponentType,
SimpleTextComponent,
)
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.capabilities.file_system import FileSystem
from vanna.integrations.local import LocalFileSystem
class RunSqlTool(Tool[RunSqlToolArgs]):
"""Tool that executes SQL queries using an injected SqlRunner implementation."""
def __init__(
self,
sql_runner: SqlRunner,
file_system: Optional[FileSystem] = None,
custom_tool_name: Optional[str] = None,
custom_tool_description: Optional[str] = None,
):
"""Initialize the tool with a SqlRunner implementation.
Args:
sql_runner: SqlRunner implementation that handles actual query execution
file_system: FileSystem implementation for saving results (defaults to LocalFileSystem)
custom_tool_name: Optional custom name for the tool (overrides default "run_sql")
custom_tool_description: Optional custom description for the tool (overrides default description)
"""
self.sql_runner = sql_runner
self.file_system = file_system or LocalFileSystem()
self._custom_name = custom_tool_name
self._custom_description = custom_tool_description
@property
def name(self) -> str:
return self._custom_name if self._custom_name else "run_sql"
@property
def description(self) -> str:
return (
self._custom_description
if self._custom_description
else "Execute SQL queries against the configured database"
)
def get_args_schema(self) -> Type[RunSqlToolArgs]:
return RunSqlToolArgs
async def execute(self, context: ToolContext, args: RunSqlToolArgs) -> ToolResult:
"""Execute a SQL query using the injected SqlRunner."""
try:
# Use the injected SqlRunner to execute the query
df = await self.sql_runner.run_sql(args, context)
# Determine query type
query_type = args.sql.strip().upper().split()[0]
if query_type == "SELECT":
# Handle SELECT queries with results
if df.empty:
result = "Query executed successfully. No rows returned."
ui_component = UiComponent(
rich_component=DataFrameComponent(
rows=[],
columns=[],
title="Query Results",
description="No rows returned",
),
simple_component=SimpleTextComponent(text=result),
)
metadata = {
"row_count": 0,
"columns": [],
"query_type": query_type,
"results": [],
}
else:
# Convert DataFrame to records
results_data = df.to_dict("records")
columns = df.columns.tolist()
row_count = len(df)
# Write DataFrame to CSV file for downstream tools
file_id = str(uuid.uuid4())[:8]
filename = f"query_results_{file_id}.csv"
csv_content = df.to_csv(index=False)
await self.file_system.write_file(
filename, csv_content, context, overwrite=True
)
# Create result text for LLM with truncated results
results_preview = csv_content
if len(results_preview) > 1000:
results_preview = (
results_preview[:1000]
+ "\n(Results truncated to 1000 characters. FOR LARGE RESULTS YOU DO NOT NEED TO SUMMARIZE THESE RESULTS OR PROVIDE OBSERVATIONS. THE NEXT STEP SHOULD BE A VISUALIZE_DATA CALL)"
)
result = f"{results_preview}\n\nResults saved to file: {filename}\n\n**IMPORTANT: FOR VISUALIZE_DATA USE FILENAME: {filename}**"
# Create DataFrame component for UI
dataframe_component = DataFrameComponent.from_records(
records=cast(List[Dict[str, Any]], results_data),
title="Query Results",
description=f"SQL query returned {row_count} rows with {len(columns)} columns",
)
ui_component = UiComponent(
rich_component=dataframe_component,
simple_component=SimpleTextComponent(text=result),
)
metadata = {
"row_count": row_count,
"columns": columns,
"query_type": query_type,
"results": results_data,
"output_file": filename,
}
else:
# For non-SELECT queries (INSERT, UPDATE, DELETE, etc.)
# The SqlRunner should return a DataFrame with affected row count
rows_affected = len(df) if not df.empty else 0
result = (
f"Query executed successfully. {rows_affected} row(s) affected."
)
metadata = {"rows_affected": rows_affected, "query_type": query_type}
ui_component = UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION, level="success", message=result
),
simple_component=SimpleTextComponent(text=result),
)
return ToolResult(
success=True,
result_for_llm=result,
ui_component=ui_component,
metadata=metadata,
)
except Exception as e:
error_message = f"Error executing query: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_message,
),
simple_component=SimpleTextComponent(text=error_message),
),
error=str(e),
metadata={"error_type": "sql_error"},
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/tools/run_sql.py",
"license": "MIT License",
"lines": 145,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:src/vanna/tools/visualize_data.py | """Tool for visualizing DataFrame data from CSV files."""
from typing import Optional, Type
import logging
import pandas as pd
from pydantic import BaseModel, Field
from vanna.core.tool import Tool, ToolContext, ToolResult
from vanna.components import (
UiComponent,
ChartComponent,
NotificationComponent,
ComponentType,
SimpleTextComponent,
)
from .file_system import FileSystem, LocalFileSystem
from vanna.integrations.plotly import PlotlyChartGenerator
logger = logging.getLogger(__name__)
class VisualizeDataArgs(BaseModel):
"""Arguments for visualize_data tool."""
filename: str = Field(description="Name of the CSV file to visualize")
title: Optional[str] = Field(
default=None, description="Optional title for the chart"
)
class VisualizeDataTool(Tool[VisualizeDataArgs]):
"""Tool that reads CSV files and generates visualizations using dependency injection."""
def __init__(
self,
file_system: Optional[FileSystem] = None,
plotly_generator: Optional[PlotlyChartGenerator] = None,
):
"""Initialize the tool with FileSystem and PlotlyChartGenerator.
Args:
file_system: FileSystem implementation for reading CSV files (defaults to LocalFileSystem)
plotly_generator: PlotlyChartGenerator for creating Plotly charts (defaults to PlotlyChartGenerator())
"""
self.file_system = file_system or LocalFileSystem()
self.plotly_generator = plotly_generator or PlotlyChartGenerator()
@property
def name(self) -> str:
return "visualize_data"
@property
def description(self) -> str:
return "Create a visualization from a CSV file. The tool automatically selects an appropriate chart type based on the data."
def get_args_schema(self) -> Type[VisualizeDataArgs]:
return VisualizeDataArgs
async def execute(
self, context: ToolContext, args: VisualizeDataArgs
) -> ToolResult:
"""Read CSV file and generate visualization."""
try:
logger.info(f"Starting visualization for file: {args.filename}")
# Read the CSV file using FileSystem
csv_content = await self.file_system.read_file(args.filename, context)
logger.info(f"Read {len(csv_content)} bytes from CSV file")
# Parse CSV into DataFrame
import io
df = pd.read_csv(io.StringIO(csv_content))
logger.info(
f"Parsed DataFrame with shape {df.shape}, columns: {df.columns.tolist()}, dtypes: {df.dtypes.to_dict()}"
)
# Generate title
title = args.title or f"Visualization of {args.filename}"
# Generate chart using PlotlyChartGenerator
logger.info("Generating chart...")
chart_dict = self.plotly_generator.generate_chart(df, title)
logger.info(
f"Chart generated, type: {type(chart_dict)}, keys: {list(chart_dict.keys()) if isinstance(chart_dict, dict) else 'N/A'}"
)
# Create result message
row_count = len(df)
col_count = len(df.columns)
result = f"Created visualization from '{args.filename}' ({row_count} rows, {col_count} columns)."
# Create ChartComponent
logger.info("Creating ChartComponent...")
chart_component = ChartComponent(
chart_type="plotly",
data=chart_dict,
title=title,
config={
"data_shape": {"rows": row_count, "columns": col_count},
"source_file": args.filename,
},
)
logger.info("ChartComponent created successfully")
logger.info("Creating ToolResult...")
tool_result = ToolResult(
success=True,
result_for_llm=result,
ui_component=UiComponent(
rich_component=chart_component,
simple_component=SimpleTextComponent(text=result),
),
metadata={
"filename": args.filename,
"rows": row_count,
"columns": col_count,
"chart": chart_dict,
},
)
logger.info("ToolResult created successfully")
return tool_result
except FileNotFoundError as e:
logger.error(f"File not found: {args.filename}", exc_info=True)
error_message = f"File not found: {args.filename}"
return ToolResult(
success=False,
result_for_llm=error_message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_message,
),
simple_component=SimpleTextComponent(text=error_message),
),
error=str(e),
metadata={"error_type": "file_not_found"},
)
except pd.errors.ParserError as e:
logger.error(f"CSV parse error for {args.filename}", exc_info=True)
error_message = f"Failed to parse CSV file '{args.filename}': {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_message,
),
simple_component=SimpleTextComponent(text=error_message),
),
error=str(e),
metadata={"error_type": "csv_parse_error"},
)
except ValueError as e:
logger.error(f"Visualization error for {args.filename}", exc_info=True)
error_message = f"Cannot visualize data: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_message,
),
simple_component=SimpleTextComponent(text=error_message),
),
error=str(e),
metadata={"error_type": "visualization_error"},
)
except Exception as e:
logger.error(
f"Unexpected error creating visualization for {args.filename}",
exc_info=True,
)
error_message = f"Error creating visualization: {str(e)}"
return ToolResult(
success=False,
result_for_llm=error_message,
ui_component=UiComponent(
rich_component=NotificationComponent(
type=ComponentType.NOTIFICATION,
level="error",
message=error_message,
),
simple_component=SimpleTextComponent(text=error_message),
),
error=str(e),
metadata={"error_type": "general_error"},
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "src/vanna/tools/visualize_data.py",
"license": "MIT License",
"lines": 171,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
vanna-ai/vanna:tests/test_agent_memory.py | """
Integration tests for AgentMemory implementations.
These tests verify actual functionality against running services.
Tests are marked by implementation and skip if dependencies are unavailable.
"""
import pytest
import asyncio
import tempfile
import shutil
import os
from vanna.core.user import User
from vanna.core.tool import ToolContext
from vanna.integrations.local.agent_memory import DemoAgentMemory
@pytest.fixture
def test_user():
"""Test user for context."""
return User(
id="test_user",
username="test",
email="test@example.com",
group_memberships=["user"],
)
def create_test_context(test_user, agent_memory):
"""Helper to create test context with specific agent memory."""
return ToolContext(
user=test_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
metadata={},
)
@pytest.fixture
def chromadb_memory():
"""Create ChromaDB memory instance."""
try:
from vanna.integrations.chromadb import ChromaAgentMemory
temp_dir = tempfile.mkdtemp()
memory = ChromaAgentMemory(
persist_directory=temp_dir, collection_name="test_memories"
)
yield memory
shutil.rmtree(temp_dir, ignore_errors=True)
except ImportError:
pytest.skip("ChromaDB not installed")
@pytest.fixture
def qdrant_memory():
"""Create Qdrant memory instance."""
try:
from vanna.integrations.qdrant import QdrantAgentMemory
temp_dir = tempfile.mkdtemp()
memory = QdrantAgentMemory(path=temp_dir)
yield memory
shutil.rmtree(temp_dir, ignore_errors=True)
except ImportError:
pytest.skip("Qdrant not installed")
@pytest.fixture
def faiss_memory():
"""Create FAISS memory instance."""
try:
from vanna.integrations.faiss import FAISSAgentMemory
temp_dir = tempfile.mkdtemp()
memory = FAISSAgentMemory(persist_path=temp_dir)
yield memory
shutil.rmtree(temp_dir, ignore_errors=True)
except ImportError:
pytest.skip("FAISS not installed")
# Parametrized tests for local implementations
@pytest.mark.parametrize(
"memory_fixture", ["chromadb_memory", "qdrant_memory", "faiss_memory"]
)
class TestLocalAgentMemory:
"""Tests for local AgentMemory implementations (ChromaDB, Qdrant, FAISS)."""
@pytest.mark.asyncio
async def test_save_and_search(self, memory_fixture, test_user, request):
"""Test saving and searching tool usage patterns."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
await memory.save_tool_usage(
question="Show me top customers",
tool_name="run_sql",
args={"sql": "SELECT * FROM customers ORDER BY total_spent DESC LIMIT 10"},
context=test_context,
success=True,
)
results = await memory.search_similar_usage(
question="Show me best customers",
context=test_context,
limit=5,
similarity_threshold=0.5,
)
assert len(results) > 0
assert results[0].memory.question == "Show me top customers"
assert results[0].memory.tool_name == "run_sql"
assert results[0].similarity_score > 0.5
@pytest.mark.asyncio
async def test_multiple_memories(self, memory_fixture, test_user, request):
"""Test storing and searching multiple memories."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
patterns = [
("Show me sales data", "run_sql", {"sql": "SELECT * FROM sales"}),
("Get customer list", "run_sql", {"sql": "SELECT * FROM customers"}),
(
"Generate sales report",
"run_sql",
{"sql": "SELECT date, SUM(amount) FROM sales GROUP BY date"},
),
]
for question, tool_name, args in patterns:
await memory.save_tool_usage(
question=question,
tool_name=tool_name,
args=args,
context=test_context,
success=True,
)
results = await memory.search_similar_usage(
question="Show me sales information",
context=test_context,
limit=10,
similarity_threshold=0.3,
)
assert len(results) >= 2
@pytest.mark.asyncio
async def test_tool_filter(self, memory_fixture, test_user, request):
"""Test filtering by tool name."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
await memory.save_tool_usage(
question="Query database",
tool_name="run_sql",
args={"sql": "SELECT 1"},
context=test_context,
)
await memory.save_tool_usage(
question="Search files",
tool_name="search_files",
args={"pattern": "*.py"},
context=test_context,
)
results = await memory.search_similar_usage(
question="Query data",
context=test_context,
tool_name_filter="run_sql",
similarity_threshold=0.0,
)
assert len(results) > 0
assert all(r.memory.tool_name == "run_sql" for r in results)
@pytest.mark.asyncio
async def test_clear_memories(self, memory_fixture, test_user, request):
"""Test clearing memories."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
await memory.save_tool_usage("Q1", "run_sql", {}, test_context)
await memory.save_tool_usage("Q2", "run_sql", {}, test_context)
await memory.save_tool_usage("Q3", "visualize_data", {}, test_context)
deleted = await memory.clear_memories(context=test_context, tool_name="run_sql")
assert deleted >= 0
@pytest.mark.asyncio
async def test_get_recent_memories(self, memory_fixture, test_user, request):
"""Test getting recent memories."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
await memory.save_tool_usage("Q1", "run_sql", {"sql": "SELECT 1"}, test_context)
await asyncio.sleep(0.01)
await memory.save_tool_usage("Q2", "run_sql", {"sql": "SELECT 2"}, test_context)
await asyncio.sleep(0.01)
await memory.save_tool_usage(
"Q3", "visualize_data", {"file": "data.csv"}, test_context
)
await asyncio.sleep(0.01)
await memory.save_tool_usage("Q4", "run_sql", {"sql": "SELECT 3"}, test_context)
await asyncio.sleep(0.01)
await memory.save_tool_usage(
"Q5", "search_files", {"pattern": "*.py"}, test_context
)
recent = await memory.get_recent_memories(context=test_context, limit=3)
assert isinstance(recent, list)
assert len(recent) <= 3
if recent:
assert all(hasattr(m, "memory_id") for m in recent)
@pytest.mark.asyncio
async def test_delete_by_id(self, memory_fixture, test_user, request):
"""Test deleting memories by ID."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
await memory.save_tool_usage("Q1", "run_sql", {"sql": "SELECT 1"}, test_context)
await memory.save_tool_usage("Q2", "run_sql", {"sql": "SELECT 2"}, test_context)
await memory.save_tool_usage(
"Q3", "visualize_data", {"file": "data.csv"}, test_context
)
recent = await memory.get_recent_memories(context=test_context, limit=10)
if not recent:
pytest.skip("Implementation doesn't support get_recent_memories")
assert all(m.memory_id is not None for m in recent)
memory_to_delete = recent[0]
deleted = await memory.delete_by_id(
context=test_context, memory_id=memory_to_delete.memory_id
)
assert deleted is True
remaining = await memory.get_recent_memories(context=test_context, limit=10)
assert all(m.memory_id != memory_to_delete.memory_id for m in remaining)
fake_deleted = await memory.delete_by_id(
context=test_context, memory_id="fake-id-12345"
)
assert fake_deleted is False
@pytest.mark.asyncio
async def test_save_and_search_text_memories(
self, memory_fixture, test_user, request
):
"""Test saving and searching text memories."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
# Save a text memory
text_memory = await memory.save_text_memory(
content="The status column uses 1 for active, 0 for inactive",
context=test_context,
)
assert text_memory.memory_id is not None
assert (
text_memory.content == "The status column uses 1 for active, 0 for inactive"
)
# Search for similar text memories
results = await memory.search_text_memories(
query="status column meaning",
context=test_context,
limit=5,
similarity_threshold=0.3,
)
assert len(results) > 0
assert (
results[0].memory.content
== "The status column uses 1 for active, 0 for inactive"
)
assert results[0].similarity_score > 0.3
@pytest.mark.asyncio
async def test_multiple_text_memories(self, memory_fixture, test_user, request):
"""Test storing and searching multiple text memories."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
text_contents = [
"The fiscal year starts in April",
"MRR means Monthly Recurring Revenue",
"Always exclude test accounts where email contains 'test'",
]
for content in text_contents:
await memory.save_text_memory(content=content, context=test_context)
# Search for fiscal year info
results = await memory.search_text_memories(
query="When does the fiscal year start?",
context=test_context,
limit=10,
similarity_threshold=0.2,
)
assert len(results) >= 1
assert any("fiscal year" in r.memory.content.lower() for r in results)
@pytest.mark.asyncio
async def test_get_recent_text_memories(self, memory_fixture, test_user, request):
"""Test getting recent text memories."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
await memory.save_text_memory("First text memory", test_context)
await asyncio.sleep(0.01)
await memory.save_text_memory("Second text memory", test_context)
await asyncio.sleep(0.01)
await memory.save_text_memory("Third text memory", test_context)
recent = await memory.get_recent_text_memories(context=test_context, limit=2)
assert isinstance(recent, list)
assert len(recent) <= 2
if recent:
assert all(hasattr(m, "memory_id") for m in recent)
assert all(hasattr(m, "content") for m in recent)
@pytest.mark.asyncio
async def test_delete_text_memory(self, memory_fixture, test_user, request):
"""Test deleting text memories by ID."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
text_memory = await memory.save_text_memory(
"Test memory to delete", test_context
)
assert text_memory.memory_id is not None
deleted = await memory.delete_text_memory(
context=test_context, memory_id=text_memory.memory_id
)
assert deleted is True
# Verify it's gone
recent = await memory.get_recent_text_memories(context=test_context, limit=10)
assert all(m.memory_id != text_memory.memory_id for m in recent)
# Try deleting non-existent memory
fake_deleted = await memory.delete_text_memory(
context=test_context, memory_id="fake-text-id-12345"
)
assert fake_deleted is False
@pytest.mark.asyncio
async def test_mixed_tool_and_text_memories(
self, memory_fixture, test_user, request
):
"""Test that tool memories and text memories can coexist without errors."""
memory = request.getfixturevalue(memory_fixture)
test_context = create_test_context(test_user, memory)
await memory.clear_memories(context=test_context)
# Save some tool memories
await memory.save_tool_usage(
question="Show me top customers",
tool_name="run_sql",
args={"sql": "SELECT * FROM customers"},
context=test_context,
)
# Save some text memories
await memory.save_text_memory(
content="The fiscal year starts in April",
context=test_context,
)
await memory.save_tool_usage(
question="Get sales data",
tool_name="run_sql",
args={"sql": "SELECT * FROM sales"},
context=test_context,
)
await memory.save_text_memory(
content="MRR means Monthly Recurring Revenue",
context=test_context,
)
# This should only return tool memories, not text memories
tool_memories = await memory.get_recent_memories(context=test_context, limit=10)
assert isinstance(tool_memories, list)
assert len(tool_memories) == 2 # Should only have the 2 tool memories
assert all(hasattr(m, "question") for m in tool_memories)
assert all(hasattr(m, "tool_name") for m in tool_memories)
# This should only return text memories, not tool memories
text_memories = await memory.get_recent_text_memories(
context=test_context, limit=10
)
assert isinstance(text_memories, list)
assert len(text_memories) == 2 # Should only have the 2 text memories
assert all(hasattr(m, "content") for m in text_memories)
assert all(
"fiscal year" in m.content or "MRR" in m.content for m in text_memories
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_agent_memory.py",
"license": "MIT License",
"lines": 349,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_agent_memory_sanity.py | """
Sanity tests for AgentMemory implementations.
These tests verify that:
1. Each AgentMemory implementation correctly implements the AgentMemory interface
2. Imports are working correctly for all vector store modules
3. Basic class instantiation works (without requiring actual service connections)
Note: These tests do NOT execute actual vector operations against services.
They are lightweight sanity checks for the implementation structure.
"""
import pytest
from inspect import signature, iscoroutinefunction
from abc import ABC
class TestAgentMemoryInterface:
"""Test that the AgentMemory interface is properly defined."""
def test_agent_memory_import(self):
"""Test that AgentMemory can be imported."""
from vanna.capabilities.agent_memory import AgentMemory
assert AgentMemory is not None
def test_agent_memory_is_abstract(self):
"""Test that AgentMemory is an abstract base class."""
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(AgentMemory, ABC)
def test_agent_memory_has_required_methods(self):
"""Test that AgentMemory defines all required abstract methods."""
from vanna.capabilities.agent_memory import AgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(AgentMemory, method_name)
method = getattr(AgentMemory, method_name)
assert getattr(method, "__isabstractmethod__", False), (
f"{method_name} should be abstract"
)
def test_all_methods_are_async(self):
"""Test that all AgentMemory methods are async."""
from vanna.capabilities.agent_memory import AgentMemory
methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in methods:
method = getattr(AgentMemory, method_name)
assert iscoroutinefunction(method), f"{method_name} should be async"
class TestToolMemoryModel:
"""Test the ToolMemory model."""
def test_tool_memory_import(self):
"""Test that ToolMemory can be imported."""
from vanna.capabilities.agent_memory import ToolMemory
assert ToolMemory is not None
def test_tool_memory_is_pydantic_model(self):
"""Test that ToolMemory is a Pydantic model."""
from vanna.capabilities.agent_memory import ToolMemory
from pydantic import BaseModel
assert issubclass(ToolMemory, BaseModel)
def test_tool_memory_has_required_fields(self):
"""Test that ToolMemory has all required fields."""
from vanna.capabilities.agent_memory import ToolMemory
required_fields = ["question", "tool_name", "args"]
optional_fields = ["memory_id", "timestamp", "success", "metadata"]
model_fields = list(ToolMemory.model_fields.keys())
for field in required_fields:
assert field in model_fields, f"Required field '{field}' missing"
for field in optional_fields:
assert field in model_fields, f"Optional field '{field}' missing"
def test_tool_memory_instantiation(self):
"""Test that ToolMemory can be instantiated."""
from vanna.capabilities.agent_memory import ToolMemory
memory = ToolMemory(
memory_id="test-123",
question="What is the total sales?",
tool_name="run_sql",
args={"sql": "SELECT SUM(amount) FROM sales"},
)
assert memory.memory_id == "test-123"
assert memory.question == "What is the total sales?"
assert memory.tool_name == "run_sql"
assert memory.args == {"sql": "SELECT SUM(amount) FROM sales"}
assert memory.success is True # Default value
class TestToolMemorySearchResultModel:
"""Test the ToolMemorySearchResult model."""
def test_memory_search_result_import(self):
"""Test that ToolMemorySearchResult can be imported."""
from vanna.capabilities.agent_memory import ToolMemorySearchResult
assert ToolMemorySearchResult is not None
def test_memory_search_result_instantiation(self):
"""Test that ToolMemorySearchResult can be instantiated."""
from vanna.capabilities.agent_memory import ToolMemorySearchResult, ToolMemory
memory = ToolMemory(question="test", tool_name="test_tool", args={})
result = ToolMemorySearchResult(memory=memory, similarity_score=0.95, rank=1)
assert result.memory == memory
assert result.similarity_score == 0.95
assert result.rank == 1
class TestTextMemoryModel:
"""Test the TextMemory model."""
def test_text_memory_import(self):
"""Test that TextMemory can be imported."""
from vanna.capabilities.agent_memory import TextMemory
assert TextMemory is not None
def test_text_memory_is_pydantic_model(self):
"""Test that TextMemory is a Pydantic model."""
from vanna.capabilities.agent_memory import TextMemory
from pydantic import BaseModel
assert issubclass(TextMemory, BaseModel)
def test_text_memory_has_required_fields(self):
"""Test that TextMemory has all required fields."""
from vanna.capabilities.agent_memory import TextMemory
required_fields = ["content"]
optional_fields = ["memory_id", "timestamp"]
model_fields = list(TextMemory.model_fields.keys())
for field in required_fields:
assert field in model_fields, f"Required field '{field}' missing"
for field in optional_fields:
assert field in model_fields, f"Optional field '{field}' missing"
def test_text_memory_instantiation(self):
"""Test that TextMemory can be instantiated."""
from vanna.capabilities.agent_memory import TextMemory
memory = TextMemory(
memory_id="text-123", content="Remember to handle edge cases"
)
assert memory.memory_id == "text-123"
assert memory.content == "Remember to handle edge cases"
class TestTextMemorySearchResultModel:
"""Test the TextMemorySearchResult model."""
def test_text_memory_search_result_import(self):
"""Test that TextMemorySearchResult can be imported."""
from vanna.capabilities.agent_memory import TextMemorySearchResult
assert TextMemorySearchResult is not None
def test_text_memory_search_result_instantiation(self):
"""Test that TextMemorySearchResult can be instantiated."""
from vanna.capabilities.agent_memory import TextMemorySearchResult, TextMemory
memory = TextMemory(content="Example memory")
result = TextMemorySearchResult(memory=memory, similarity_score=0.88, rank=2)
assert result.memory == memory
assert result.similarity_score == 0.88
assert result.rank == 2
class TestChromaDBAgentMemory:
"""Sanity tests for ChromaDB AgentMemory implementation."""
def test_chromadb_import(self):
"""Test that ChromaAgentMemory can be imported."""
try:
from vanna.integrations.chromadb import ChromaAgentMemory
assert ChromaAgentMemory is not None
except ImportError:
pytest.skip("ChromaDB not installed")
def test_chromadb_implements_agent_memory(self):
"""Test that ChromaAgentMemory implements AgentMemory."""
try:
from vanna.integrations.chromadb import ChromaAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(ChromaAgentMemory, AgentMemory)
except ImportError:
pytest.skip("ChromaDB not installed")
def test_chromadb_has_all_methods(self):
"""Test that ChromaAgentMemory implements all required methods."""
try:
from vanna.integrations.chromadb import ChromaAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(ChromaAgentMemory, method_name)
method = getattr(ChromaAgentMemory, method_name)
assert not getattr(method, "__isabstractmethod__", False), (
f"{method_name} should be implemented (not abstract)"
)
except ImportError:
pytest.skip("ChromaDB not installed")
def test_chromadb_instantiation(self):
"""Test that ChromaAgentMemory can be instantiated."""
try:
from vanna.integrations.chromadb import ChromaAgentMemory
import tempfile
temp_dir = tempfile.mkdtemp()
memory = ChromaAgentMemory(
persist_directory=temp_dir, collection_name="test"
)
assert memory is not None
assert memory.persist_directory == temp_dir
assert memory.collection_name == "test"
except ImportError:
pytest.skip("ChromaDB not installed")
class TestQdrantAgentMemory:
"""Sanity tests for Qdrant AgentMemory implementation."""
def test_qdrant_import(self):
"""Test that QdrantAgentMemory can be imported."""
try:
from vanna.integrations.qdrant import QdrantAgentMemory
assert QdrantAgentMemory is not None
except ImportError:
pytest.skip("Qdrant not installed")
def test_qdrant_implements_agent_memory(self):
"""Test that QdrantAgentMemory implements AgentMemory."""
try:
from vanna.integrations.qdrant import QdrantAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(QdrantAgentMemory, AgentMemory)
except ImportError:
pytest.skip("Qdrant not installed")
def test_qdrant_has_all_methods(self):
"""Test that QdrantAgentMemory implements all required methods."""
try:
from vanna.integrations.qdrant import QdrantAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(QdrantAgentMemory, method_name)
except ImportError:
pytest.skip("Qdrant not installed")
def test_qdrant_instantiation(self):
"""Test that QdrantAgentMemory can be instantiated."""
try:
from vanna.integrations.qdrant import QdrantAgentMemory
# In-memory mode doesn't require actual service
memory = QdrantAgentMemory(path=":memory:")
assert memory is not None
except ImportError:
pytest.skip("Qdrant not installed")
class TestPineconeAgentMemory:
"""Sanity tests for Pinecone AgentMemory implementation."""
def test_pinecone_import(self):
"""Test that PineconeAgentMemory can be imported."""
try:
from vanna.integrations.pinecone import PineconeAgentMemory
assert PineconeAgentMemory is not None
except ImportError:
pytest.skip("Pinecone not installed")
def test_pinecone_implements_agent_memory(self):
"""Test that PineconeAgentMemory implements AgentMemory."""
try:
from vanna.integrations.pinecone import PineconeAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(PineconeAgentMemory, AgentMemory)
except ImportError:
pytest.skip("Pinecone not installed")
def test_pinecone_has_all_methods(self):
"""Test that PineconeAgentMemory implements all required methods."""
try:
from vanna.integrations.pinecone import PineconeAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(PineconeAgentMemory, method_name)
except ImportError:
pytest.skip("Pinecone not installed")
class TestMilvusAgentMemory:
"""Sanity tests for Milvus AgentMemory implementation."""
def test_milvus_import(self):
"""Test that MilvusAgentMemory can be imported."""
try:
from vanna.integrations.milvus import MilvusAgentMemory
assert MilvusAgentMemory is not None
except ImportError:
pytest.skip("Milvus not installed")
def test_milvus_implements_agent_memory(self):
"""Test that MilvusAgentMemory implements AgentMemory."""
try:
from vanna.integrations.milvus import MilvusAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(MilvusAgentMemory, AgentMemory)
except ImportError:
pytest.skip("Milvus not installed")
def test_milvus_has_all_methods(self):
"""Test that MilvusAgentMemory implements all required methods."""
try:
from vanna.integrations.milvus import MilvusAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(MilvusAgentMemory, method_name)
except ImportError:
pytest.skip("Milvus not installed")
class TestWeaviateAgentMemory:
"""Sanity tests for Weaviate AgentMemory implementation."""
def test_weaviate_import(self):
"""Test that WeaviateAgentMemory can be imported."""
try:
from vanna.integrations.weaviate import WeaviateAgentMemory
assert WeaviateAgentMemory is not None
except ImportError:
pytest.skip("Weaviate not installed")
def test_weaviate_implements_agent_memory(self):
"""Test that WeaviateAgentMemory implements AgentMemory."""
try:
from vanna.integrations.weaviate import WeaviateAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(WeaviateAgentMemory, AgentMemory)
except ImportError:
pytest.skip("Weaviate not installed")
def test_weaviate_has_all_methods(self):
"""Test that WeaviateAgentMemory implements all required methods."""
try:
from vanna.integrations.weaviate import WeaviateAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(WeaviateAgentMemory, method_name)
except ImportError:
pytest.skip("Weaviate not installed")
class TestFAISSAgentMemory:
"""Sanity tests for FAISS AgentMemory implementation."""
def test_faiss_import(self):
"""Test that FAISSAgentMemory can be imported."""
try:
from vanna.integrations.faiss import FAISSAgentMemory
assert FAISSAgentMemory is not None
except ImportError:
pytest.skip("FAISS not installed")
def test_faiss_implements_agent_memory(self):
"""Test that FAISSAgentMemory implements AgentMemory."""
try:
from vanna.integrations.faiss import FAISSAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(FAISSAgentMemory, AgentMemory)
except ImportError:
pytest.skip("FAISS not installed")
def test_faiss_has_all_methods(self):
"""Test that FAISSAgentMemory implements all required methods."""
try:
from vanna.integrations.faiss import FAISSAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(FAISSAgentMemory, method_name)
except ImportError:
pytest.skip("FAISS not installed")
def test_faiss_instantiation(self):
"""Test that FAISSAgentMemory can be instantiated."""
try:
from vanna.integrations.faiss import FAISSAgentMemory
import tempfile
temp_dir = tempfile.mkdtemp()
memory = FAISSAgentMemory(persist_path=temp_dir)
assert memory is not None
assert memory.persist_path == temp_dir
except ImportError:
pytest.skip("FAISS not installed")
class TestOpenSearchAgentMemory:
"""Sanity tests for OpenSearch AgentMemory implementation."""
def test_opensearch_import(self):
"""Test that OpenSearchAgentMemory can be imported."""
try:
from vanna.integrations.opensearch import OpenSearchAgentMemory
assert OpenSearchAgentMemory is not None
except ImportError:
pytest.skip("OpenSearch not installed")
def test_opensearch_implements_agent_memory(self):
"""Test that OpenSearchAgentMemory implements AgentMemory."""
try:
from vanna.integrations.opensearch import OpenSearchAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(OpenSearchAgentMemory, AgentMemory)
except ImportError:
pytest.skip("OpenSearch not installed")
def test_opensearch_has_all_methods(self):
"""Test that OpenSearchAgentMemory implements all required methods."""
try:
from vanna.integrations.opensearch import OpenSearchAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(OpenSearchAgentMemory, method_name)
except ImportError:
pytest.skip("OpenSearch not installed")
class TestAzureAISearchAgentMemory:
"""Sanity tests for Azure AI Search AgentMemory implementation."""
def test_azuresearch_import(self):
"""Test that AzureAISearchAgentMemory can be imported."""
try:
from vanna.integrations.azuresearch import AzureAISearchAgentMemory
assert AzureAISearchAgentMemory is not None
except ImportError:
pytest.skip("Azure Search not installed")
def test_azuresearch_implements_agent_memory(self):
"""Test that AzureAISearchAgentMemory implements AgentMemory."""
try:
from vanna.integrations.azuresearch import AzureAISearchAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(AzureAISearchAgentMemory, AgentMemory)
except ImportError:
pytest.skip("Azure Search not installed")
def test_azuresearch_has_all_methods(self):
"""Test that AzureAISearchAgentMemory implements all required methods."""
try:
from vanna.integrations.azuresearch import AzureAISearchAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(AzureAISearchAgentMemory, method_name)
except ImportError:
pytest.skip("Azure Search not installed")
class TestMarqoAgentMemory:
"""Sanity tests for Marqo AgentMemory implementation."""
def test_marqo_import(self):
"""Test that MarqoAgentMemory can be imported."""
try:
from vanna.integrations.marqo import MarqoAgentMemory
assert MarqoAgentMemory is not None
except ImportError:
pytest.skip("Marqo not installed")
def test_marqo_implements_agent_memory(self):
"""Test that MarqoAgentMemory implements AgentMemory."""
try:
from vanna.integrations.marqo import MarqoAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(MarqoAgentMemory, AgentMemory)
except ImportError:
pytest.skip("Marqo not installed")
def test_marqo_has_all_methods(self):
"""Test that MarqoAgentMemory implements all required methods."""
try:
from vanna.integrations.marqo import MarqoAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(MarqoAgentMemory, method_name)
except ImportError:
pytest.skip("Marqo not installed")
class TestDemoAgentMemory:
"""Sanity tests for DemoAgentMemory (in-memory) implementation."""
def test_demo_import(self):
"""Test that DemoAgentMemory can be imported."""
from vanna.integrations.local.agent_memory import DemoAgentMemory
assert DemoAgentMemory is not None
def test_demo_implements_agent_memory(self):
"""Test that DemoAgentMemory implements AgentMemory."""
from vanna.integrations.local.agent_memory import DemoAgentMemory
from vanna.capabilities.agent_memory import AgentMemory
assert issubclass(DemoAgentMemory, AgentMemory)
def test_demo_has_all_methods(self):
"""Test that DemoAgentMemory implements all required methods."""
from vanna.integrations.local.agent_memory import DemoAgentMemory
required_methods = [
"save_tool_usage",
"save_text_memory",
"search_similar_usage",
"search_text_memories",
"get_recent_memories",
"get_recent_text_memories",
"delete_by_id",
"delete_text_memory",
"clear_memories",
]
for method_name in required_methods:
assert hasattr(DemoAgentMemory, method_name)
def test_demo_instantiation(self):
"""Test that DemoAgentMemory can be instantiated."""
from vanna.integrations.local.agent_memory import DemoAgentMemory
memory = DemoAgentMemory(max_items=100)
assert memory is not None
assert memory._max_items == 100
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_agent_memory_sanity.py",
"license": "MIT License",
"lines": 546,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_agents.py | """
Simple end-to-end tests for Vanna agents.
Tests use agent.send_message and validate the response components.
"""
import os
import pytest
from vanna.core.user import User
from vanna.core.user.resolver import UserResolver
from vanna.core.user.request_context import RequestContext
class SimpleUserResolver(UserResolver):
"""Simple user resolver for tests - always returns the same test user."""
async def resolve_user(self, request_context: RequestContext) -> User:
return User(
id="test_user", email="test@example.com", group_memberships=["user"]
)
def create_agent(llm_service, sql_runner):
"""Helper to create a configured agent."""
from vanna import Agent, AgentConfig
from vanna.core.registry import ToolRegistry
from vanna.tools import RunSqlTool
from vanna.integrations.local.file_system import LocalFileSystem
from vanna.integrations.local.agent_memory import DemoAgentMemory
from vanna.tools.agent_memory import (
SaveQuestionToolArgsTool,
SearchSavedCorrectToolUsesTool,
)
tools = ToolRegistry()
# Add SQL tool
db_tool = RunSqlTool(sql_runner=sql_runner, file_system=LocalFileSystem())
tools.register_local_tool(db_tool, access_groups=["user"])
# Add memory tools (they access agent_memory via ToolContext)
agent_memory = DemoAgentMemory(max_items=1000)
tools.register_local_tool(SaveQuestionToolArgsTool(), access_groups=["user"])
tools.register_local_tool(SearchSavedCorrectToolUsesTool(), access_groups=["user"])
return Agent(
llm_service=llm_service,
tool_registry=tools,
user_resolver=SimpleUserResolver(),
agent_memory=agent_memory,
config=AgentConfig(),
)
async def test_agent_top_artist(agent, expected_artist="Iron Maiden"):
"""Common test logic for testing agent responses about top artist by sales."""
# Create a simple request context
request_context = RequestContext(cookies={}, headers={})
# Collect all components from the async generator
components = []
async for component in agent.send_message(
request_context, "Who is the top artist by sales?"
):
components.append(component)
# Validate we got components
assert len(components) > 0, "Should receive at least one component"
# Print all components for debugging
print(f"\n\n=== Received {len(components)} components ===")
for i, component in enumerate(components):
print(f"\nComponent {i + 1}:")
print(f" Type: {component.type if hasattr(component, 'type') else 'no type'}")
if hasattr(component, "text"):
print(
f" Text: {component.text[:200]}..."
if len(component.text) > 200
else f" Text: {component.text}"
)
if hasattr(component, "content"):
print(f" Content: {str(component.content)[:200]}...")
print(f" Full: {component}")
# Look for the expected artist in any component
found_artist = False
for component in components:
# Check rich_component.content
if hasattr(component, "rich_component") and hasattr(
component.rich_component, "content"
):
if expected_artist in component.rich_component.content:
found_artist = True
break
# Check simple_component.text
if hasattr(component, "simple_component") and hasattr(
component.simple_component, "text"
):
if expected_artist in component.simple_component.text:
found_artist = True
break
assert found_artist, (
f"Response should mention '{expected_artist}' as the top artist. Got {len(components)} components."
)
@pytest.mark.anthropic
@pytest.mark.asyncio
async def test_anthropic_top_artist(chinook_db):
"""Test Anthropic agent finding the top artist by sales."""
from vanna.integrations.anthropic import AnthropicLlmService
api_key = os.getenv("ANTHROPIC_API_KEY")
llm = AnthropicLlmService(api_key=api_key, model="claude-sonnet-4-5")
agent = create_agent(llm, chinook_db)
await test_agent_top_artist(agent)
@pytest.mark.openai
@pytest.mark.asyncio
async def test_openai_top_artist(chinook_db):
"""Test OpenAI agent finding the top artist by sales."""
from vanna.integrations.openai import OpenAILlmService
api_key = os.getenv("OPENAI_API_KEY")
llm = OpenAILlmService(api_key=api_key, model="gpt-5")
agent = create_agent(llm, chinook_db)
await test_agent_top_artist(agent)
@pytest.mark.azureopenai
@pytest.mark.asyncio
async def test_azure_openai_top_artist(chinook_db):
"""Test Azure OpenAI agent finding the top artist by sales."""
from vanna.integrations.azureopenai import AzureOpenAILlmService
# Get Azure OpenAI credentials from environment
api_key = os.getenv("AZURE_OPENAI_API_KEY")
model = os.getenv("AZURE_OPENAI_MODEL")
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT")
api_version = os.getenv("AZURE_OPENAI_API_VERSION")
llm = AzureOpenAILlmService(
model=model,
api_key=api_key,
azure_endpoint=azure_endpoint,
api_version=api_version,
)
agent = create_agent(llm, chinook_db)
await test_agent_top_artist(agent)
# @pytest.mark.openai
# @pytest.mark.asyncio
# async def test_openai_responses_top_artist(chinook_db):
# """Test OpenAI Responses API agent finding the top artist by sales."""
# from vanna.integrations.openai import OpenAIResponsesService
# api_key = os.getenv("OPENAI_API_KEY")
# llm = OpenAIResponsesService(api_key=api_key, model="gpt-5")
# agent = create_agent(llm, chinook_db)
# await test_agent_top_artist(agent)
@pytest.mark.ollama
@pytest.mark.asyncio
async def test_ollama_top_artist(chinook_db):
"""Test Ollama agent finding the top artist by sales."""
from vanna.integrations.ollama import OllamaLlmService
llm = OllamaLlmService(
model="gpt-oss:20b-cloud",
host=os.getenv("OLLAMA_HOST", "http://localhost:11434"),
)
agent = create_agent(llm, chinook_db)
await test_agent_top_artist(agent)
@pytest.mark.gemini
@pytest.mark.asyncio
async def test_gemini_top_artist(chinook_db):
"""Test Gemini agent finding the top artist by sales."""
from vanna.integrations.google import GeminiLlmService
# API key will be picked up from GOOGLE_API_KEY or GEMINI_API_KEY env var
llm = GeminiLlmService(model="gemini-2.5-pro", temperature=0.0)
agent = create_agent(llm, chinook_db)
await test_agent_top_artist(agent)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_agents.py",
"license": "MIT License",
"lines": 152,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_azureopenai_llm.py | """
Unit tests for Azure OpenAI LLM service integration.
These tests validate the Azure OpenAI integration without making actual API calls.
"""
import pytest
from unittest.mock import Mock, patch, AsyncMock
from vanna.integrations.azureopenai import AzureOpenAILlmService
from vanna.integrations.azureopenai.llm import _is_reasoning_model
class TestReasoningModelDetection:
"""Test reasoning model detection logic."""
def test_is_reasoning_model_o1(self):
"""Test that o1 models are detected as reasoning models."""
assert _is_reasoning_model("o1")
assert _is_reasoning_model("o1-mini")
assert _is_reasoning_model("o1-preview")
def test_is_reasoning_model_o3(self):
"""Test that o3 models are detected as reasoning models."""
assert _is_reasoning_model("o3-mini")
def test_is_reasoning_model_gpt5(self):
"""Test that GPT-5 series models are detected as reasoning models."""
assert _is_reasoning_model("gpt-5")
assert _is_reasoning_model("gpt-5-mini")
assert _is_reasoning_model("gpt-5-nano")
assert _is_reasoning_model("gpt-5-pro")
assert _is_reasoning_model("gpt-5-codex")
def test_is_not_reasoning_model(self):
"""Test that standard models are not detected as reasoning models."""
assert not _is_reasoning_model("gpt-4")
assert not _is_reasoning_model("gpt-4o")
assert not _is_reasoning_model("gpt-4-turbo")
assert not _is_reasoning_model("gpt-3.5-turbo")
def test_case_insensitive_detection(self):
"""Test that model detection is case insensitive."""
assert _is_reasoning_model("GPT-5")
assert _is_reasoning_model("O1-MINI")
assert not _is_reasoning_model("GPT-4O")
class TestAzureOpenAILlmServiceInitialization:
"""Test Azure OpenAI service initialization."""
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_init_with_all_params(self, mock_azure_openai):
"""Test initialization with all parameters provided."""
service = AzureOpenAILlmService(
model="gpt-4o",
api_key="test-key",
azure_endpoint="https://test.openai.azure.com",
api_version="2024-10-21",
)
assert service.model == "gpt-4o"
assert not service._is_reasoning_model
# Verify AzureOpenAI was called with correct params
mock_azure_openai.assert_called_once()
call_kwargs = mock_azure_openai.call_args[1]
assert call_kwargs["azure_endpoint"] == "https://test.openai.azure.com"
assert call_kwargs["api_version"] == "2024-10-21"
assert call_kwargs["api_key"] == "test-key"
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_init_with_reasoning_model(self, mock_azure_openai):
"""Test initialization with a reasoning model."""
service = AzureOpenAILlmService(
model="gpt-5",
api_key="test-key",
azure_endpoint="https://test.openai.azure.com",
)
assert service.model == "gpt-5"
assert service._is_reasoning_model
@patch.dict(
"os.environ",
{
"AZURE_OPENAI_MODEL": "gpt-4o-deployment",
"AZURE_OPENAI_API_KEY": "env-key",
"AZURE_OPENAI_ENDPOINT": "https://env.openai.azure.com",
"AZURE_OPENAI_API_VERSION": "2024-06-01",
},
)
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_init_from_environment(self, mock_azure_openai):
"""Test initialization from environment variables."""
service = AzureOpenAILlmService()
assert service.model == "gpt-4o-deployment"
# Verify AzureOpenAI was called with env values
call_kwargs = mock_azure_openai.call_args[1]
assert call_kwargs["azure_endpoint"] == "https://env.openai.azure.com"
assert call_kwargs["api_version"] == "2024-06-01"
assert call_kwargs["api_key"] == "env-key"
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_init_missing_model_raises(self, mock_azure_openai):
"""Test that missing model parameter raises ValueError."""
with pytest.raises(ValueError, match="model parameter.*is required"):
AzureOpenAILlmService(
api_key="test-key",
azure_endpoint="https://test.openai.azure.com",
)
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_init_missing_endpoint_raises(self, mock_azure_openai):
"""Test that missing azure_endpoint raises ValueError."""
with pytest.raises(ValueError, match="azure_endpoint is required"):
AzureOpenAILlmService(
model="gpt-4o",
api_key="test-key",
)
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_init_missing_auth_raises(self, mock_azure_openai):
"""Test that missing authentication raises ValueError."""
with pytest.raises(ValueError, match="Authentication required"):
AzureOpenAILlmService(
model="gpt-4o",
azure_endpoint="https://test.openai.azure.com",
)
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_init_with_azure_ad_token_provider(self, mock_azure_openai):
"""Test initialization with Azure AD token provider."""
mock_token_provider = Mock()
service = AzureOpenAILlmService(
model="gpt-4o",
azure_endpoint="https://test.openai.azure.com",
azure_ad_token_provider=mock_token_provider,
)
# Verify token provider was used instead of API key
call_kwargs = mock_azure_openai.call_args[1]
assert call_kwargs["azure_ad_token_provider"] == mock_token_provider
assert "api_key" not in call_kwargs
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_init_default_api_version(self, mock_azure_openai):
"""Test that default API version is used when not specified."""
service = AzureOpenAILlmService(
model="gpt-4o",
api_key="test-key",
azure_endpoint="https://test.openai.azure.com",
)
# Verify default API version (2024-10-21)
call_kwargs = mock_azure_openai.call_args[1]
assert call_kwargs["api_version"] == "2024-10-21"
class TestAzureOpenAILlmServicePayloadBuilding:
"""Test payload building for API requests."""
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_build_payload_includes_temperature_for_standard_model(
self, mock_azure_openai
):
"""Test that temperature is included for standard models."""
from vanna.core.llm import LlmRequest, LlmMessage
from vanna.core.user import User
service = AzureOpenAILlmService(
model="gpt-4o",
api_key="test-key",
azure_endpoint="https://test.openai.azure.com",
)
request = LlmRequest(
messages=[LlmMessage(role="user", content="test")],
user=User(id="test", email="test@example.com", group_memberships=[]),
temperature=0.8,
)
payload = service._build_payload(request)
assert "temperature" in payload
assert payload["temperature"] == 0.8
assert payload["model"] == "gpt-4o"
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_build_payload_excludes_temperature_for_reasoning_model(
self, mock_azure_openai
):
"""Test that temperature is excluded for reasoning models."""
from vanna.core.llm import LlmRequest, LlmMessage
from vanna.core.user import User
service = AzureOpenAILlmService(
model="gpt-5",
api_key="test-key",
azure_endpoint="https://test.openai.azure.com",
)
request = LlmRequest(
messages=[LlmMessage(role="user", content="test")],
user=User(id="test", email="test@example.com", group_memberships=[]),
temperature=0.8,
)
payload = service._build_payload(request)
assert "temperature" not in payload
assert payload["model"] == "gpt-5"
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_build_payload_with_system_prompt(self, mock_azure_openai):
"""Test that system prompt is added to messages."""
from vanna.core.llm import LlmRequest, LlmMessage
from vanna.core.user import User
service = AzureOpenAILlmService(
model="gpt-4o",
api_key="test-key",
azure_endpoint="https://test.openai.azure.com",
)
request = LlmRequest(
messages=[LlmMessage(role="user", content="test")],
user=User(id="test", email="test@example.com", group_memberships=[]),
system_prompt="You are a helpful assistant.",
)
payload = service._build_payload(request)
assert len(payload["messages"]) == 2
assert payload["messages"][0]["role"] == "system"
assert payload["messages"][0]["content"] == "You are a helpful assistant."
@patch("vanna.integrations.azureopenai.llm.AzureOpenAI")
def test_build_payload_with_tools(self, mock_azure_openai):
"""Test that tools are properly formatted in payload."""
from vanna.core.llm import LlmRequest, LlmMessage
from vanna.core.user import User
from vanna.core.tool import ToolSchema
service = AzureOpenAILlmService(
model="gpt-4o",
api_key="test-key",
azure_endpoint="https://test.openai.azure.com",
)
tool = ToolSchema(
name="test_tool",
description="A test tool",
parameters={
"type": "object",
"properties": {"param1": {"type": "string"}},
},
)
request = LlmRequest(
messages=[LlmMessage(role="user", content="test")],
user=User(id="test", email="test@example.com", group_memberships=[]),
tools=[tool],
)
payload = service._build_payload(request)
assert "tools" in payload
assert len(payload["tools"]) == 1
assert payload["tools"][0]["type"] == "function"
assert payload["tools"][0]["function"]["name"] == "test_tool"
assert payload["tool_choice"] == "auto"
class TestImportError:
"""Test import error handling."""
def test_import_error_message(self):
"""Test that helpful error message is shown when openai is not installed."""
with patch.dict("sys.modules", {"openai": None}):
# Force module reload to trigger import error
import sys
if "vanna.integrations.azureopenai.llm" in sys.modules:
del sys.modules["vanna.integrations.azureopenai.llm"]
with pytest.raises(
ImportError, match="pip install 'vanna\\[azureopenai\\]'"
):
from vanna.integrations.azureopenai import AzureOpenAILlmService
AzureOpenAILlmService(
model="gpt-4o",
api_key="test",
azure_endpoint="https://test.openai.azure.com",
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_azureopenai_llm.py",
"license": "MIT License",
"lines": 242,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_database_sanity.py | """
Sanity tests for database implementations.
These tests verify that:
1. Each database implementation correctly implements the SqlRunner interface
2. Imports are working correctly for all database modules
3. Basic class instantiation works (without requiring actual database connections)
Note: These tests do NOT execute actual queries against databases.
They are lightweight sanity checks for the implementation structure.
"""
import pytest
from abc import abstractmethod
from inspect import signature, iscoroutinefunction
import pandas as pd
class TestSqlRunnerInterface:
"""Test that the SqlRunner interface is properly defined."""
def test_sql_runner_import(self):
"""Test that SqlRunner can be imported."""
from vanna.capabilities.sql_runner import SqlRunner
assert SqlRunner is not None
def test_sql_runner_is_abstract(self):
"""Test that SqlRunner is an abstract base class."""
from vanna.capabilities.sql_runner import SqlRunner
from abc import ABC
assert issubclass(SqlRunner, ABC)
def test_sql_runner_has_run_sql_method(self):
"""Test that SqlRunner defines the run_sql abstract method."""
from vanna.capabilities.sql_runner import SqlRunner
assert hasattr(SqlRunner, "run_sql")
assert getattr(SqlRunner.run_sql, "__isabstractmethod__", False)
def test_run_sql_method_signature(self):
"""Test that run_sql has the correct method signature."""
from vanna.capabilities.sql_runner import SqlRunner
sig = signature(SqlRunner.run_sql)
params = list(sig.parameters.keys())
# Should have: self, args, context
assert len(params) == 3
assert params[0] == "self"
assert params[1] == "args"
assert params[2] == "context"
def test_run_sql_is_async(self):
"""Test that run_sql is defined as an async method."""
from vanna.capabilities.sql_runner import SqlRunner
# Abstract methods are wrapped, so we check if it's meant to be async
# by looking at the method definition
assert iscoroutinefunction(SqlRunner.run_sql)
class TestRunSqlToolArgsModel:
"""Test the RunSqlToolArgs model."""
def test_run_sql_tool_args_import(self):
"""Test that RunSqlToolArgs can be imported."""
from vanna.capabilities.sql_runner import RunSqlToolArgs
assert RunSqlToolArgs is not None
def test_run_sql_tool_args_has_sql_field(self):
"""Test that RunSqlToolArgs has a 'sql' field."""
from vanna.capabilities.sql_runner import RunSqlToolArgs
# Create an instance
args = RunSqlToolArgs(sql="SELECT 1")
assert hasattr(args, "sql")
assert args.sql == "SELECT 1"
def test_run_sql_tool_args_is_pydantic_model(self):
"""Test that RunSqlToolArgs is a Pydantic model."""
from vanna.capabilities.sql_runner import RunSqlToolArgs
from pydantic import BaseModel
assert issubclass(RunSqlToolArgs, BaseModel)
class TestPostgresRunner:
"""Sanity tests for PostgresRunner implementation."""
def test_postgres_runner_import(self):
"""Test that PostgresRunner can be imported."""
from vanna.integrations.postgres import PostgresRunner
assert PostgresRunner is not None
def test_postgres_runner_implements_sql_runner(self):
"""Test that PostgresRunner implements SqlRunner interface."""
from vanna.integrations.postgres import PostgresRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(PostgresRunner, SqlRunner)
def test_postgres_runner_has_run_sql_method(self):
"""Test that PostgresRunner implements run_sql method."""
from vanna.integrations.postgres import PostgresRunner
assert hasattr(PostgresRunner, "run_sql")
# Should not be abstract anymore
assert not getattr(PostgresRunner.run_sql, "__isabstractmethod__", False)
def test_postgres_runner_instantiation_with_connection_string(self):
"""Test that PostgresRunner can be instantiated with connection string."""
from vanna.integrations.postgres import PostgresRunner
# This should not raise an error (no actual connection is made in __init__)
runner = PostgresRunner(connection_string="postgresql://user:pass@localhost/db")
assert runner is not None
assert runner.connection_string == "postgresql://user:pass@localhost/db"
assert runner.connection_params is None
def test_postgres_runner_instantiation_with_params(self):
"""Test that PostgresRunner can be instantiated with individual parameters."""
from vanna.integrations.postgres import PostgresRunner
runner = PostgresRunner(
host="localhost",
port=5432,
database="testdb",
user="testuser",
password="testpass",
)
assert runner is not None
assert runner.connection_string is None
assert runner.connection_params is not None
assert runner.connection_params["host"] == "localhost"
assert runner.connection_params["database"] == "testdb"
def test_postgres_runner_requires_valid_params(self):
"""Test that PostgresRunner raises error with invalid parameters."""
from vanna.integrations.postgres import PostgresRunner
with pytest.raises(ValueError, match="Either provide connection_string OR"):
PostgresRunner() # No parameters provided
def test_postgres_runner_checks_psycopg2_import(self):
"""Test that PostgresRunner checks for psycopg2 package."""
from vanna.integrations.postgres import PostgresRunner
# If psycopg2 is not installed, this should raise ImportError
# If it is installed, this should work fine
try:
runner = PostgresRunner(connection_string="postgresql://test")
assert runner.psycopg2 is not None
except ImportError as e:
assert "psycopg2" in str(e)
class TestSqliteRunner:
"""Sanity tests for SqliteRunner implementation."""
def test_sqlite_runner_import(self):
"""Test that SqliteRunner can be imported."""
from vanna.integrations.sqlite import SqliteRunner
assert SqliteRunner is not None
def test_sqlite_runner_implements_sql_runner(self):
"""Test that SqliteRunner implements SqlRunner interface."""
from vanna.integrations.sqlite import SqliteRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(SqliteRunner, SqlRunner)
def test_sqlite_runner_has_run_sql_method(self):
"""Test that SqliteRunner implements run_sql method."""
from vanna.integrations.sqlite import SqliteRunner
assert hasattr(SqliteRunner, "run_sql")
# Should not be abstract anymore
assert not getattr(SqliteRunner.run_sql, "__isabstractmethod__", False)
def test_sqlite_runner_instantiation(self):
"""Test that SqliteRunner can be instantiated with a database path."""
from vanna.integrations.sqlite import SqliteRunner
runner = SqliteRunner(database_path="/tmp/test.db")
assert runner is not None
assert runner.database_path == "/tmp/test.db"
def test_sqlite_uses_builtin_sqlite3(self):
"""Test that SqliteRunner uses Python's built-in sqlite3 module."""
import sqlite3
from vanna.integrations.sqlite import SqliteRunner
# sqlite3 should be importable (it's part of Python standard library)
assert sqlite3 is not None
class TestLegacySqlRunner:
"""Sanity tests for LegacySqlRunner adapter."""
def test_legacy_sql_runner_import(self):
"""Test that LegacySqlRunner can be imported."""
from vanna.legacy.adapter import LegacySqlRunner
assert LegacySqlRunner is not None
def test_legacy_sql_runner_implements_sql_runner(self):
"""Test that LegacySqlRunner implements SqlRunner interface."""
from vanna.legacy.adapter import LegacySqlRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(LegacySqlRunner, SqlRunner)
def test_legacy_sql_runner_has_run_sql_method(self):
"""Test that LegacySqlRunner implements run_sql method."""
from vanna.legacy.adapter import LegacySqlRunner
assert hasattr(LegacySqlRunner, "run_sql")
# Should not be abstract anymore
assert not getattr(LegacySqlRunner.run_sql, "__isabstractmethod__", False)
def test_legacy_sql_runner_instantiation(self):
"""Test that LegacySqlRunner can be instantiated with a VannaBase instance."""
from vanna.legacy.adapter import LegacySqlRunner
from unittest.mock import Mock
# Create a mock VannaBase instance
mock_vn = Mock()
runner = LegacySqlRunner(vn=mock_vn)
assert runner is not None
assert runner.vn is mock_vn
class TestDatabaseIntegrationModules:
"""Test that database integration modules can be imported."""
def test_postgres_module_import(self):
"""Test that the postgres integration module can be imported."""
try:
import vanna.integrations.postgres
assert vanna.integrations.postgres is not None
except ImportError as e:
pytest.fail(f"Failed to import postgres module: {e}")
def test_sqlite_module_import(self):
"""Test that the sqlite integration module can be imported."""
try:
import vanna.integrations.sqlite
assert vanna.integrations.sqlite is not None
except ImportError as e:
pytest.fail(f"Failed to import sqlite module: {e}")
def test_postgres_module_exports_runner(self):
"""Test that postgres module exports PostgresRunner."""
from vanna.integrations.postgres import PostgresRunner
assert PostgresRunner is not None
def test_sqlite_module_exports_runner(self):
"""Test that sqlite module exports SqliteRunner."""
from vanna.integrations.sqlite import SqliteRunner
assert SqliteRunner is not None
class TestLegacyVannaBaseConnections:
"""Test that legacy VannaBase connection methods exist."""
def test_vanna_base_import(self):
"""Test that VannaBase can be imported."""
from vanna.legacy.base.base import VannaBase
assert VannaBase is not None
def test_vanna_base_has_connection_methods(self):
"""Test that VannaBase has various database connection methods."""
from vanna.legacy.base.base import VannaBase
connection_methods = [
"connect_to_snowflake",
"connect_to_sqlite",
"connect_to_postgres",
"connect_to_mysql",
"connect_to_clickhouse",
"connect_to_oracle",
"connect_to_bigquery",
"connect_to_duckdb",
"connect_to_mssql",
"connect_to_presto",
"connect_to_hive",
]
for method_name in connection_methods:
assert hasattr(VannaBase, method_name), f"VannaBase missing {method_name}"
def test_vanna_base_has_run_sql_method(self):
"""Test that VannaBase has a run_sql method."""
from vanna.legacy.base.base import VannaBase
assert hasattr(VannaBase, "run_sql")
class TestLegacyVannaAdapter:
"""Test the LegacyVannaAdapter."""
def test_legacy_vanna_adapter_import(self):
"""Test that LegacyVannaAdapter can be imported."""
from vanna.legacy.adapter import LegacyVannaAdapter
assert LegacyVannaAdapter is not None
def test_legacy_vanna_adapter_is_tool_registry(self):
"""Test that LegacyVannaAdapter extends ToolRegistry."""
from vanna.legacy.adapter import LegacyVannaAdapter
from vanna.core.registry import ToolRegistry
assert issubclass(LegacyVannaAdapter, ToolRegistry)
class TestSnowflakeRunner:
"""Sanity tests for SnowflakeRunner implementation."""
def test_snowflake_runner_import(self):
"""Test that SnowflakeRunner can be imported."""
from vanna.integrations.snowflake import SnowflakeRunner
assert SnowflakeRunner is not None
def test_snowflake_runner_implements_sql_runner(self):
"""Test that SnowflakeRunner implements SqlRunner interface."""
from vanna.integrations.snowflake import SnowflakeRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(SnowflakeRunner, SqlRunner)
def test_snowflake_runner_has_run_sql_method(self):
"""Test that SnowflakeRunner implements run_sql method."""
from vanna.integrations.snowflake import SnowflakeRunner
assert hasattr(SnowflakeRunner, "run_sql")
assert not getattr(SnowflakeRunner.run_sql, "__isabstractmethod__", False)
def test_snowflake_runner_instantiation(self):
"""Test that SnowflakeRunner can be instantiated with required parameters."""
from vanna.integrations.snowflake import SnowflakeRunner
runner = SnowflakeRunner(
account="test-account",
username="test-user",
password="test-pass",
database="test-db",
)
assert runner is not None
assert runner.account == "test-account"
def test_snowflake_runner_key_pair_auth_with_path(self, tmp_path):
"""Test that SnowflakeRunner can be instantiated with RSA key-pair authentication using path."""
from vanna.integrations.snowflake import SnowflakeRunner
# Create a temporary private key file
private_key_file = tmp_path / "test_private_key.p8"
private_key_file.write_text(
"-----BEGIN PRIVATE KEY-----\ntest_key_content\n-----END PRIVATE KEY-----"
)
runner = SnowflakeRunner(
account="test-account",
username="test-user",
private_key_path=str(private_key_file),
private_key_passphrase="test-passphrase",
database="test-db",
)
assert runner is not None
assert runner.account == "test-account"
assert runner.username == "test-user"
assert runner.password is None
assert runner.private_key_path == str(private_key_file)
assert runner.private_key_passphrase == "test-passphrase"
def test_snowflake_runner_key_pair_auth_with_content(self):
"""Test that SnowflakeRunner can be instantiated with RSA key-pair authentication using content."""
from vanna.integrations.snowflake import SnowflakeRunner
private_key_content = (
b"-----BEGIN PRIVATE KEY-----\ntest_key_content\n-----END PRIVATE KEY-----"
)
runner = SnowflakeRunner(
account="test-account",
username="test-user",
private_key_content=private_key_content,
database="test-db",
)
assert runner is not None
assert runner.account == "test-account"
assert runner.username == "test-user"
assert runner.password is None
assert runner.private_key_content == private_key_content
def test_snowflake_runner_key_pair_auth_without_passphrase(self, tmp_path):
"""Test that SnowflakeRunner works with unencrypted private key (no passphrase)."""
from vanna.integrations.snowflake import SnowflakeRunner
# Create a temporary private key file
private_key_file = tmp_path / "test_private_key_unencrypted.p8"
private_key_file.write_text(
"-----BEGIN PRIVATE KEY-----\ntest_key_content\n-----END PRIVATE KEY-----"
)
runner = SnowflakeRunner(
account="test-account",
username="test-user",
private_key_path=str(private_key_file),
database="test-db",
)
assert runner is not None
assert runner.private_key_passphrase is None
def test_snowflake_runner_missing_auth_raises_error(self):
"""Test that SnowflakeRunner raises error when no authentication method is provided."""
from vanna.integrations.snowflake import SnowflakeRunner
import pytest
with pytest.raises(
ValueError,
match="Either password or private_key_path/private_key_content must be provided",
):
SnowflakeRunner(
account="test-account", username="test-user", database="test-db"
)
def test_snowflake_runner_invalid_key_path_raises_error(self):
"""Test that SnowflakeRunner raises error when private key file doesn't exist."""
from vanna.integrations.snowflake import SnowflakeRunner
import pytest
with pytest.raises(FileNotFoundError, match="Private key file not found"):
SnowflakeRunner(
account="test-account",
username="test-user",
private_key_path="/nonexistent/path/to/key.p8",
database="test-db",
)
def test_snowflake_runner_password_auth_backwards_compatible(self):
"""Test that SnowflakeRunner maintains backward compatibility with password auth."""
from vanna.integrations.snowflake import SnowflakeRunner
runner = SnowflakeRunner(
account="test-account",
username="test-user",
password="test-password",
database="test-db",
role="test-role",
warehouse="test-warehouse",
)
assert runner is not None
assert runner.password == "test-password"
assert runner.private_key_path is None
assert runner.private_key_content is None
class TestMySQLRunner:
"""Sanity tests for MySQLRunner implementation."""
def test_mysql_runner_import(self):
"""Test that MySQLRunner can be imported."""
from vanna.integrations.mysql import MySQLRunner
assert MySQLRunner is not None
def test_mysql_runner_implements_sql_runner(self):
"""Test that MySQLRunner implements SqlRunner interface."""
from vanna.integrations.mysql import MySQLRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(MySQLRunner, SqlRunner)
def test_mysql_runner_has_run_sql_method(self):
"""Test that MySQLRunner implements run_sql method."""
from vanna.integrations.mysql import MySQLRunner
assert hasattr(MySQLRunner, "run_sql")
assert not getattr(MySQLRunner.run_sql, "__isabstractmethod__", False)
def test_mysql_runner_instantiation(self):
"""Test that MySQLRunner can be instantiated with required parameters."""
from vanna.integrations.mysql import MySQLRunner
runner = MySQLRunner(
host="localhost", database="test-db", user="test-user", password="test-pass"
)
assert runner is not None
assert runner.host == "localhost"
class TestClickHouseRunner:
"""Sanity tests for ClickHouseRunner implementation."""
def test_clickhouse_runner_import(self):
"""Test that ClickHouseRunner can be imported."""
from vanna.integrations.clickhouse import ClickHouseRunner
assert ClickHouseRunner is not None
def test_clickhouse_runner_implements_sql_runner(self):
"""Test that ClickHouseRunner implements SqlRunner interface."""
from vanna.integrations.clickhouse import ClickHouseRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(ClickHouseRunner, SqlRunner)
def test_clickhouse_runner_has_run_sql_method(self):
"""Test that ClickHouseRunner implements run_sql method."""
from vanna.integrations.clickhouse import ClickHouseRunner
assert hasattr(ClickHouseRunner, "run_sql")
assert not getattr(ClickHouseRunner.run_sql, "__isabstractmethod__", False)
def test_clickhouse_runner_instantiation(self):
"""Test that ClickHouseRunner can be instantiated with required parameters."""
from vanna.integrations.clickhouse import ClickHouseRunner
runner = ClickHouseRunner(
host="localhost", database="test-db", user="test-user", password="test-pass"
)
assert runner is not None
assert runner.host == "localhost"
class TestOracleRunner:
"""Sanity tests for OracleRunner implementation."""
def test_oracle_runner_import(self):
"""Test that OracleRunner can be imported."""
from vanna.integrations.oracle import OracleRunner
assert OracleRunner is not None
def test_oracle_runner_implements_sql_runner(self):
"""Test that OracleRunner implements SqlRunner interface."""
from vanna.integrations.oracle import OracleRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(OracleRunner, SqlRunner)
def test_oracle_runner_has_run_sql_method(self):
"""Test that OracleRunner implements run_sql method."""
from vanna.integrations.oracle import OracleRunner
assert hasattr(OracleRunner, "run_sql")
assert not getattr(OracleRunner.run_sql, "__isabstractmethod__", False)
def test_oracle_runner_instantiation(self):
"""Test that OracleRunner can be instantiated with required parameters."""
from vanna.integrations.oracle import OracleRunner
runner = OracleRunner(
user="test-user", password="test-pass", dsn="localhost:1521/ORCL"
)
assert runner is not None
assert runner.user == "test-user"
class TestBigQueryRunner:
"""Sanity tests for BigQueryRunner implementation."""
def test_bigquery_runner_import(self):
"""Test that BigQueryRunner can be imported."""
from vanna.integrations.bigquery import BigQueryRunner
assert BigQueryRunner is not None
def test_bigquery_runner_implements_sql_runner(self):
"""Test that BigQueryRunner implements SqlRunner interface."""
from vanna.integrations.bigquery import BigQueryRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(BigQueryRunner, SqlRunner)
def test_bigquery_runner_has_run_sql_method(self):
"""Test that BigQueryRunner implements run_sql method."""
from vanna.integrations.bigquery import BigQueryRunner
assert hasattr(BigQueryRunner, "run_sql")
assert not getattr(BigQueryRunner.run_sql, "__isabstractmethod__", False)
def test_bigquery_runner_instantiation(self):
"""Test that BigQueryRunner can be instantiated with required parameters."""
from vanna.integrations.bigquery import BigQueryRunner
runner = BigQueryRunner(project_id="test-project")
assert runner is not None
assert runner.project_id == "test-project"
class TestDuckDBRunner:
"""Sanity tests for DuckDBRunner implementation."""
def test_duckdb_runner_import(self):
"""Test that DuckDBRunner can be imported."""
from vanna.integrations.duckdb import DuckDBRunner
assert DuckDBRunner is not None
def test_duckdb_runner_implements_sql_runner(self):
"""Test that DuckDBRunner implements SqlRunner interface."""
from vanna.integrations.duckdb import DuckDBRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(DuckDBRunner, SqlRunner)
def test_duckdb_runner_has_run_sql_method(self):
"""Test that DuckDBRunner implements run_sql method."""
from vanna.integrations.duckdb import DuckDBRunner
assert hasattr(DuckDBRunner, "run_sql")
assert not getattr(DuckDBRunner.run_sql, "__isabstractmethod__", False)
def test_duckdb_runner_instantiation_memory(self):
"""Test that DuckDBRunner can be instantiated for in-memory database."""
from vanna.integrations.duckdb import DuckDBRunner
runner = DuckDBRunner(database_path=":memory:")
assert runner is not None
assert runner.database_path == ":memory:"
def test_duckdb_runner_instantiation_file(self):
"""Test that DuckDBRunner can be instantiated with file path."""
from vanna.integrations.duckdb import DuckDBRunner
runner = DuckDBRunner(database_path="/tmp/test.duckdb")
assert runner is not None
assert runner.database_path == "/tmp/test.duckdb"
class TestMSSQLRunner:
"""Sanity tests for MSSQLRunner implementation."""
def test_mssql_runner_import(self):
"""Test that MSSQLRunner can be imported."""
from vanna.integrations.mssql import MSSQLRunner
assert MSSQLRunner is not None
def test_mssql_runner_implements_sql_runner(self):
"""Test that MSSQLRunner implements SqlRunner interface."""
from vanna.integrations.mssql import MSSQLRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(MSSQLRunner, SqlRunner)
def test_mssql_runner_has_run_sql_method(self):
"""Test that MSSQLRunner implements run_sql method."""
from vanna.integrations.mssql import MSSQLRunner
assert hasattr(MSSQLRunner, "run_sql")
assert not getattr(MSSQLRunner.run_sql, "__isabstractmethod__", False)
def test_mssql_runner_instantiation(self):
"""Test that MSSQLRunner can be instantiated with ODBC connection string."""
from vanna.integrations.mssql import MSSQLRunner
runner = MSSQLRunner(
odbc_conn_str="Driver={SQL Server};Server=localhost;Database=test;Trusted_Connection=yes;"
)
assert runner is not None
class TestPrestoRunner:
"""Sanity tests for PrestoRunner implementation."""
def test_presto_runner_import(self):
"""Test that PrestoRunner can be imported."""
from vanna.integrations.presto import PrestoRunner
assert PrestoRunner is not None
def test_presto_runner_implements_sql_runner(self):
"""Test that PrestoRunner implements SqlRunner interface."""
from vanna.integrations.presto import PrestoRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(PrestoRunner, SqlRunner)
def test_presto_runner_has_run_sql_method(self):
"""Test that PrestoRunner implements run_sql method."""
from vanna.integrations.presto import PrestoRunner
assert hasattr(PrestoRunner, "run_sql")
assert not getattr(PrestoRunner.run_sql, "__isabstractmethod__", False)
def test_presto_runner_instantiation(self):
"""Test that PrestoRunner can be instantiated with required parameters."""
from vanna.integrations.presto import PrestoRunner
runner = PrestoRunner(host="localhost", user="test-user", password="test-pass")
assert runner is not None
assert runner.host == "localhost"
class TestHiveRunner:
"""Sanity tests for HiveRunner implementation."""
def test_hive_runner_import(self):
"""Test that HiveRunner can be imported."""
from vanna.integrations.hive import HiveRunner
assert HiveRunner is not None
def test_hive_runner_implements_sql_runner(self):
"""Test that HiveRunner implements SqlRunner interface."""
from vanna.integrations.hive import HiveRunner
from vanna.capabilities.sql_runner import SqlRunner
assert issubclass(HiveRunner, SqlRunner)
def test_hive_runner_has_run_sql_method(self):
"""Test that HiveRunner implements run_sql method."""
from vanna.integrations.hive import HiveRunner
assert hasattr(HiveRunner, "run_sql")
assert not getattr(HiveRunner.run_sql, "__isabstractmethod__", False)
def test_hive_runner_instantiation(self):
"""Test that HiveRunner can be instantiated with required parameters."""
from vanna.integrations.hive import HiveRunner
runner = HiveRunner(host="localhost", user="test-user", password="test-pass")
assert runner is not None
assert runner.host == "localhost"
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_database_sanity.py",
"license": "MIT License",
"lines": 543,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_gemini_integration.py | """
Google Gemini integration tests.
Basic unit tests for the Gemini LLM service integration.
End-to-end tests are in test_agents.py.
Note: Tests requiring API calls need GOOGLE_API_KEY environment variable.
"""
import os
import pytest
from vanna.core.llm import LlmRequest, LlmMessage
from vanna.core.tool import ToolSchema
from vanna.core.user import User
@pytest.fixture
def test_user():
"""Test user for LLM requests."""
return User(
id="test_user",
username="test",
email="test@example.com",
group_memberships=["user"],
)
@pytest.mark.gemini
@pytest.mark.asyncio
async def test_gemini_import():
"""Test that Gemini integration can be imported."""
from vanna.integrations.google import GeminiLlmService
print("✓ GeminiLlmService imported successfully")
assert GeminiLlmService is not None
@pytest.mark.gemini
@pytest.mark.asyncio
async def test_gemini_initialization_without_key():
"""Test that Gemini service raises error without API key."""
from vanna.integrations.google import GeminiLlmService
# Clear both env vars if they exist
old_google_key = os.environ.pop("GOOGLE_API_KEY", None)
old_gemini_key = os.environ.pop("GEMINI_API_KEY", None)
try:
with pytest.raises(ValueError, match="Google API key is required"):
llm = GeminiLlmService(model="gemini-2.5-pro")
finally:
# Restore the keys if they existed
if old_google_key:
os.environ["GOOGLE_API_KEY"] = old_google_key
if old_gemini_key:
os.environ["GEMINI_API_KEY"] = old_gemini_key
@pytest.mark.gemini
@pytest.mark.asyncio
async def test_gemini_initialization():
"""Test that Gemini service can be initialized with API key."""
from vanna.integrations.google import GeminiLlmService
# This test will be skipped by conftest.py if GOOGLE_API_KEY is not set
llm = GeminiLlmService(
model="gemini-2.5-pro",
temperature=0.7,
)
print(f"✓ GeminiLlmService initialized")
print(f" Model: {llm.model_name}")
print(f" Temperature: {llm.temperature}")
assert llm.model_name == "gemini-2.5-pro"
assert llm.temperature == 0.7
@pytest.mark.gemini
@pytest.mark.asyncio
async def test_gemini_basic_request(test_user):
"""Test a basic request without tools."""
from vanna.integrations.google import GeminiLlmService
llm = GeminiLlmService(model="gemini-2.5-pro", temperature=0.0)
request = LlmRequest(
user=test_user,
messages=[
LlmMessage(role="user", content="What is 2+2? Answer with just the number.")
],
)
print(f"\n=== Basic Request Test ===")
print(f"Sending request to Gemini...")
response = await llm.send_request(request)
print(f"✓ Response received")
print(f" Content type: {type(response.content)}")
print(f" Content: {response.content}")
print(f" Finish reason: {response.finish_reason}")
print(f" Tool calls: {response.tool_calls}")
print(f" Usage: {response.usage}")
# Verify response structure
assert response is not None
assert response.content is not None
assert isinstance(response.content, str)
assert "4" in response.content
@pytest.mark.gemini
@pytest.mark.asyncio
async def test_gemini_streaming_request(test_user):
"""Test streaming request."""
from vanna.integrations.google import GeminiLlmService
llm = GeminiLlmService(model="gemini-2.5-pro", temperature=0.0)
request = LlmRequest(
user=test_user,
messages=[
LlmMessage(role="user", content="Count from 1 to 5, one number per line.")
],
stream=True,
)
print(f"\n=== Streaming Request Test ===")
print(f"Streaming from Gemini...")
chunks = []
async for chunk in llm.stream_request(request):
chunks.append(chunk)
if chunk.content:
print(f" Chunk: {chunk.content}")
print(f"✓ Streaming completed")
print(f" Total chunks: {len(chunks)}")
# Verify we got chunks
assert len(chunks) > 0
# At least one chunk should have content
assert any(c.content for c in chunks)
@pytest.mark.gemini
@pytest.mark.asyncio
async def test_gemini_validate_tools():
"""Test tool validation (does not require API key for actual calls)."""
from vanna.integrations.google import GeminiLlmService
# For validation testing, we need to initialize but won't make API calls
llm = GeminiLlmService(model="gemini-2.5-pro")
# Valid tool
valid_tool = ToolSchema(
name="test_tool",
description="A test tool",
parameters={"type": "object", "properties": {}},
)
# Invalid tool (no name)
invalid_tool = ToolSchema(
name="",
description="Invalid tool",
parameters={"type": "object", "properties": {}},
)
# Invalid tool (no description)
invalid_tool2 = ToolSchema(
name="test_tool_2",
description="",
parameters={"type": "object", "properties": {}},
)
errors = await llm.validate_tools([valid_tool])
assert len(errors) == 0, "Valid tool should have no errors"
errors = await llm.validate_tools([invalid_tool])
assert len(errors) > 0, "Tool with empty name should have errors"
assert any("name" in e.lower() for e in errors)
errors = await llm.validate_tools([invalid_tool2])
assert len(errors) > 0, "Tool with empty description should have errors"
assert any("description" in e.lower() for e in errors)
print("✓ Tool validation working correctly")
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_gemini_integration.py",
"license": "MIT License",
"lines": 145,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_legacy_adapter.py | """
Test for LegacyVannaAdapter retrofit functionality.
This test validates that a legacy VannaBase instance can be wrapped
with LegacyVannaAdapter and used with the new Agents framework.
"""
import os
import pytest
from vanna.core.user import User
from vanna.core.user.resolver import UserResolver
from vanna.core.user.request_context import RequestContext
class SimpleUserResolver(UserResolver):
"""Simple user resolver for tests - returns test user or admin."""
async def resolve_user(self, request_context: RequestContext) -> User:
user_email = request_context.cookies.get("vanna_email", "test@example.com")
if user_email == "admin@example.com":
return User(id="admin_user", email=user_email, group_memberships=["admin"])
return User(id=user_email, email=user_email, group_memberships=["user"])
@pytest.mark.legacy
@pytest.mark.asyncio
async def test_legacy_adapter_with_anthropic():
"""Test LegacyVannaAdapter wrapping a legacy VannaBase instance with Anthropic LLM."""
from vanna import Agent, AgentConfig
from vanna.legacy.adapter import LegacyVannaAdapter
from vanna.legacy.mock import MockLLM
from vanna.legacy.chromadb import ChromaDB_VectorStore
from vanna.integrations.anthropic import AnthropicLlmService
# Create a legacy VannaBase instance (using multiple inheritance like v0.x)
class MyVanna(ChromaDB_VectorStore, MockLLM):
def __init__(self, config=None):
ChromaDB_VectorStore.__init__(self, config=config)
MockLLM.__init__(self, config=config)
vn = MyVanna()
# Connect to the Chinook database using legacy method
vn.connect_to_sqlite("https://vanna.ai/Chinook.sqlite")
# Add some training data
vn.add_question_sql(
question="Who is the top artist by sales?",
sql="SELECT a.Name, SUM(il.UnitPrice * il.Quantity) as total FROM Artist a JOIN Album al ON a.ArtistId = al.ArtistId JOIN Track t ON al.AlbumId = t.AlbumId JOIN InvoiceLine il ON t.TrackId = il.TrackId GROUP BY a.ArtistId ORDER BY total DESC LIMIT 1",
)
# Wrap legacy VannaBase with LegacyVannaAdapter
legacy_adapter = LegacyVannaAdapter(vn)
# Create agent with new LLM service
api_key = os.getenv("ANTHROPIC_API_KEY")
llm = AnthropicLlmService(api_key=api_key, model="claude-haiku-4-5")
agent = Agent(
llm_service=llm,
tool_registry=legacy_adapter, # LegacyVannaAdapter is a ToolRegistry
agent_memory=legacy_adapter, # LegacyVannaAdapter implements AgentMemory
user_resolver=SimpleUserResolver(),
config=AgentConfig(),
)
# Test that the agent can answer a question
request_context = RequestContext(cookies={}, headers={})
components = []
async for component in agent.send_message(
request_context, "Who is the top artist by sales?"
):
components.append(component)
# Validate we got components
assert len(components) > 0, "Should receive at least one component"
# Look for a successful response (either table or text mentioning an artist)
has_response = False
for component in components:
if hasattr(component, "rich_component") and component.rich_component:
has_response = True
break
if hasattr(component, "simple_component") and component.simple_component:
if (
hasattr(component.simple_component, "text")
and component.simple_component.text
):
has_response = True
break
assert has_response, "Should receive at least one response component"
@pytest.mark.legacy
@pytest.mark.asyncio
async def test_legacy_adapter_memory_operations():
"""Test that LegacyVannaAdapter properly implements AgentMemory interface."""
from vanna.legacy.adapter import LegacyVannaAdapter
from vanna.legacy.mock import MockLLM
from vanna.legacy.chromadb import ChromaDB_VectorStore
from vanna.core.tool import ToolContext
from vanna.core.user import User
# Create a legacy VannaBase instance
class MyVanna(ChromaDB_VectorStore, MockLLM):
def __init__(self, config=None):
ChromaDB_VectorStore.__init__(self, config=config)
MockLLM.__init__(self, config=config)
vn = MyVanna()
adapter = LegacyVannaAdapter(vn)
# Create a properly constructed tool context
user = User(id="test_user", email="test@example.com", group_memberships=["user"])
context = ToolContext(
user=user,
conversation_id="test-conversation",
request_id="test-request",
agent_memory=adapter, # Use the adapter itself as the agent_memory
)
# Test save_tool_usage
await adapter.save_tool_usage(
question="What are the total sales?",
tool_name="run_sql",
args={"sql": "SELECT SUM(Total) FROM Invoice"},
context=context,
success=True,
)
# Test search_similar_usage
results = await adapter.search_similar_usage(
question="What are sales?", context=context, limit=5
)
# Should find the saved usage
assert len(results) > 0, "Should find similar tool usage"
assert results[0].memory.question == "What are the total sales?"
assert results[0].memory.args["sql"] == "SELECT SUM(Total) FROM Invoice"
# Test save_text_memory
text_memory = await adapter.save_text_memory(
content="The Invoice table contains all sales transactions.", context=context
)
assert text_memory.content == "The Invoice table contains all sales transactions."
# Test search_text_memories
text_results = await adapter.search_text_memories(
query="sales", context=context, limit=5
)
assert len(text_results) > 0, "Should find similar text memories"
# Test get_recent_memories (uses blank string retrieval)
recent = await adapter.get_recent_memories(context=context, limit=5)
assert isinstance(recent, list), "Should return a list of memories"
# Test get_recent_text_memories
recent_text = await adapter.get_recent_text_memories(context=context, limit=5)
assert isinstance(recent_text, list), "Should return a list of text memories"
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_legacy_adapter.py",
"license": "MIT License",
"lines": 130,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_llm_context_enhancer.py | """
Unit tests for LlmContextEnhancer functionality.
These tests validate that the Agent properly calls the LlmContextEnhancer methods
to enhance system prompts and user messages.
"""
import pytest
from typing import List
from vanna.core.enhancer.base import LlmContextEnhancer
from vanna.core.enhancer.default import DefaultLlmContextEnhancer
from vanna.core.user import User
from vanna.core.user.resolver import UserResolver
from vanna.core.user.request_context import RequestContext
from vanna.core.llm.models import LlmMessage
from vanna.core.llm.base import LlmService
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
)
from vanna.core.tool import ToolContext
class MockAgentMemory(AgentMemory):
"""Mock AgentMemory for testing."""
def __init__(self):
self.text_memories: List[TextMemory] = []
async def save_tool_usage(
self, question, tool_name, args, context, success=True, metadata=None
):
pass
async def save_text_memory(self, content, context):
memory = TextMemory(
memory_id=f"mem-{len(self.text_memories)}", content=content, timestamp=None
)
self.text_memories.append(memory)
return memory
async def search_similar_usage(
self,
question,
context,
*,
limit=10,
similarity_threshold=0.7,
tool_name_filter=None,
):
return []
async def search_text_memories(
self, query, context, *, limit=10, similarity_threshold=0.7
):
"""Return mock search results based on stored memories."""
results = []
for idx, memory in enumerate(self.text_memories[:limit]):
results.append(
TextMemorySearchResult(
memory=memory, similarity_score=0.9 - (idx * 0.1), rank=idx + 1
)
)
return results
async def get_recent_memories(self, context, limit=10):
return []
async def get_recent_text_memories(self, context, limit=10):
return self.text_memories[:limit]
async def delete_by_id(self, context, memory_id):
return False
async def delete_text_memory(self, context, memory_id):
return False
async def clear_memories(self, context, tool_name=None, before_date=None):
return 0
class MockLlmService(LlmService):
"""Mock LLM service that records calls."""
def __init__(self):
self.requests = [] # Store full request objects
self.next_response = "Mock response"
async def send_request(self, request):
"""Record the call and return a mock response."""
from vanna.core.llm.models import LlmResponse, LlmResponseMessage
# Store the full request object
self.requests.append(request)
# Return a simple text response
return LlmResponse(
message=LlmResponseMessage(role="assistant", content=self.next_response),
finish_reason="end_turn",
)
async def stream_request(self, request):
"""Mock streaming - just yield a single chunk."""
from vanna.core.llm.models import LlmStreamChunk
# Store the full request object
self.requests.append(request)
yield LlmStreamChunk(delta=self.next_response, finish_reason="end_turn")
async def validate_tools(self, tools):
"""Mock validation - no errors."""
return []
class SimpleUserResolver(UserResolver):
"""Simple user resolver for tests."""
async def resolve_user(self, request_context: RequestContext) -> User:
return User(
id="test_user", email="test@example.com", group_memberships=["user"]
)
class TrackingEnhancer(LlmContextEnhancer):
"""Custom enhancer that tracks when methods are called."""
def __init__(self):
self.enhance_system_prompt_calls = []
self.enhance_user_messages_calls = []
async def enhance_system_prompt(
self, system_prompt: str, user_message: str, user: User
) -> str:
"""Track call and add a marker to the system prompt."""
self.enhance_system_prompt_calls.append(
{
"system_prompt": system_prompt,
"user_message": user_message,
"user_id": user.id,
}
)
return system_prompt + "\n\n[ENHANCED_SYSTEM_PROMPT]"
async def enhance_user_messages(
self, messages: List[LlmMessage], user: User
) -> List[LlmMessage]:
"""Track call and add a marker to messages."""
self.enhance_user_messages_calls.append(
{"message_count": len(messages), "user_id": user.id}
)
# Add a marker to the last user message
if messages and messages[-1].role == "user":
enhanced_messages = messages[:-1] + [
LlmMessage(
role="user",
content=messages[-1].content + " [ENHANCED_USER_MESSAGE]",
)
]
return enhanced_messages
return messages
@pytest.mark.asyncio
async def test_custom_enhancer_system_prompt_is_called():
"""Test that a custom LlmContextEnhancer.enhance_system_prompt is called by the Agent."""
from vanna import Agent, AgentConfig
from vanna.core.registry import ToolRegistry
# Create mock components
llm = MockLlmService()
tools = ToolRegistry()
enhancer = TrackingEnhancer()
agent_memory = MockAgentMemory()
# Create agent with the tracking enhancer
agent = Agent(
llm_service=llm,
tool_registry=tools,
user_resolver=SimpleUserResolver(),
agent_memory=agent_memory,
llm_context_enhancer=enhancer,
config=AgentConfig(),
)
# Send a message
request_context = RequestContext(cookies={}, headers={})
components = []
async for component in agent.send_message(request_context, "Hello, world!"):
components.append(component)
# Verify enhance_system_prompt was called
assert len(enhancer.enhance_system_prompt_calls) == 1, (
"enhance_system_prompt should be called exactly once"
)
call = enhancer.enhance_system_prompt_calls[0]
assert call["user_message"] == "Hello, world!", (
"Should pass the user message to enhancer"
)
assert call["user_id"] == "test_user", "Should pass the correct user"
assert "system_prompt" in call, "Should pass the system prompt"
# Verify the enhanced system prompt was sent to the LLM
assert len(llm.requests) >= 1, "LLM should be called at least once"
first_request = llm.requests[0]
assert first_request.system_prompt is not None, "Should have a system prompt"
assert "[ENHANCED_SYSTEM_PROMPT]" in first_request.system_prompt, (
f"System prompt should contain enhancement marker. Got: {first_request.system_prompt}"
)
@pytest.mark.asyncio
async def test_custom_enhancer_user_messages_is_called():
"""Test that a custom LlmContextEnhancer.enhance_user_messages is called by the Agent."""
from vanna import Agent, AgentConfig
from vanna.core.registry import ToolRegistry
# Create mock components
llm = MockLlmService()
tools = ToolRegistry()
enhancer = TrackingEnhancer()
agent_memory = MockAgentMemory()
# Create agent with the tracking enhancer
agent = Agent(
llm_service=llm,
tool_registry=tools,
user_resolver=SimpleUserResolver(),
agent_memory=agent_memory,
llm_context_enhancer=enhancer,
config=AgentConfig(),
)
# Send a message
request_context = RequestContext(cookies={}, headers={})
components = []
async for component in agent.send_message(request_context, "Test message"):
components.append(component)
# Verify enhance_user_messages was called
assert len(enhancer.enhance_user_messages_calls) >= 1
call = enhancer.enhance_user_messages_calls[0]
assert call["user_id"] == "test_user"
assert call["message_count"] > 0
# Verify the enhanced user message was sent to the LLM
assert len(llm.requests) >= 1
first_request = llm.requests[0]
user_messages = [m for m in first_request.messages if m.role == "user"]
assert len(user_messages) >= 1, "Should have at least one user message"
assert "[ENHANCED_USER_MESSAGE]" in user_messages[0].content, (
f"User message should be enhanced. Got: {user_messages[0].content}"
)
@pytest.mark.asyncio
async def test_default_enhancer_with_agent_memory():
"""Test that DefaultLlmContextEnhancer properly enhances system prompt with memories."""
from vanna import Agent, AgentConfig
from vanna.core.registry import ToolRegistry
# Create mock components
llm = MockLlmService()
tools = ToolRegistry()
agent_memory = MockAgentMemory()
# Add some test memories
user = User(id="test_user", email="test@example.com", group_memberships=["user"])
context = ToolContext(
user=user, conversation_id="test", request_id="test", agent_memory=agent_memory
)
await agent_memory.save_text_memory(
"The database has a users table with columns: id, name, email", context
)
await agent_memory.save_text_memory(
"The products table contains: product_id, name, price, category", context
)
# Create default enhancer with agent memory
enhancer = DefaultLlmContextEnhancer(agent_memory=agent_memory)
# Create agent
agent = Agent(
llm_service=llm,
tool_registry=tools,
user_resolver=SimpleUserResolver(),
agent_memory=agent_memory,
llm_context_enhancer=enhancer,
config=AgentConfig(),
)
# Send a message that should trigger memory retrieval
request_context = RequestContext(cookies={}, headers={})
components = []
async for component in agent.send_message(
request_context, "Show me the database schema"
):
components.append(component)
# Verify that the DefaultLlmContextEnhancer added memory context to the system prompt
assert len(llm.requests) >= 1, "LLM should be called"
first_request = llm.requests[0]
# The DefaultLlmContextEnhancer should add "Relevant Context from Memory" to system prompt
assert first_request.system_prompt is not None, "Should have a system prompt"
assert "Relevant Context from Memory" in first_request.system_prompt, (
f"System prompt should include memory context. Got: {first_request.system_prompt}"
)
# Should contain one or both of the memories we added
assert (
"users table" in first_request.system_prompt
or "products table" in first_request.system_prompt
), (
f"System prompt should contain our test memories. Got: {first_request.system_prompt}"
)
@pytest.mark.asyncio
async def test_default_enhancer_without_agent_memory():
"""Test that DefaultLlmContextEnhancer works without agent memory (no enhancement)."""
from vanna import Agent, AgentConfig
from vanna.core.registry import ToolRegistry
# Create mock components
llm = MockLlmService()
tools = ToolRegistry()
# Create default enhancer without agent memory
enhancer = DefaultLlmContextEnhancer(agent_memory=None)
agent_memory = MockAgentMemory()
# Create agent
agent = Agent(
llm_service=llm,
tool_registry=tools,
user_resolver=SimpleUserResolver(),
agent_memory=agent_memory,
llm_context_enhancer=enhancer,
config=AgentConfig(),
)
# Send a message
request_context = RequestContext(cookies={}, headers={})
components = []
async for component in agent.send_message(request_context, "Hello"):
components.append(component)
# Verify the system prompt does NOT include memory context (since enhancer has no agent_memory)
assert len(llm.requests) >= 1, "LLM should be called"
first_request = llm.requests[0]
# The system prompt should exist but NOT contain memory context
if first_request.system_prompt:
assert "Relevant Context from Memory" not in first_request.system_prompt, (
"Should not add memory context when enhancer has no agent_memory"
)
@pytest.mark.asyncio
async def test_no_enhancer_means_no_enhancement():
"""Test that when no enhancer is provided, no enhancement occurs."""
from vanna import Agent, AgentConfig
from vanna.core.registry import ToolRegistry
# Create mock components
llm = MockLlmService()
tools = ToolRegistry()
agent_memory = MockAgentMemory()
# Create agent WITHOUT an enhancer (should use default no-op behavior)
agent = Agent(
llm_service=llm,
tool_registry=tools,
user_resolver=SimpleUserResolver(),
agent_memory=agent_memory,
config=AgentConfig(),
)
# Send a message
request_context = RequestContext(cookies={}, headers={})
components = []
async for component in agent.send_message(request_context, "Hello"):
components.append(component)
# Verify basic system prompt exists but has no enhancements
assert len(llm.requests) >= 1, "LLM should be called"
first_request = llm.requests[0]
# Should be the basic system prompt with no enhancements
if first_request.system_prompt:
assert "Relevant Context from Memory" not in first_request.system_prompt, (
"Should not add memory context when no enhancer is provided"
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_llm_context_enhancer.py",
"license": "MIT License",
"lines": 324,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_memory_tools.py | """
Tests for agent memory tools, including UI feature access control.
"""
import pytest
import uuid
from vanna.tools.agent_memory import (
SearchSavedCorrectToolUsesTool,
SearchSavedCorrectToolUsesParams,
)
from vanna.core.tool import ToolContext
from vanna.core.user import User
from vanna.core.agent.config import UiFeature
from vanna.integrations.local.agent_memory import DemoAgentMemory
from vanna.core.rich_component import ComponentType
@pytest.fixture
def demo_agent_memory():
"""Create a demo agent memory instance."""
return DemoAgentMemory(max_items=100)
@pytest.fixture
def admin_user():
"""Create an admin user."""
return User(id="admin", email="admin@example.com", group_memberships=["admin"])
@pytest.fixture
def regular_user():
"""Create a regular user."""
return User(id="user", email="user@example.com", group_memberships=["user"])
@pytest.fixture
def search_tool():
"""Create a search tool instance."""
return SearchSavedCorrectToolUsesTool()
class TestMemoryToolDetailedResults:
"""Test memory tool detailed results feature."""
@pytest.mark.asyncio
async def test_admin_sees_detailed_results(
self, search_tool, demo_agent_memory, admin_user
):
"""Test that admin users see detailed memory results in a collapsible card."""
# Create context with admin user and feature enabled
context = ToolContext(
user=admin_user,
conversation_id=str(uuid.uuid4()),
request_id=str(uuid.uuid4()),
agent_memory=demo_agent_memory,
metadata={
"ui_features_available": [
UiFeature.UI_FEATURE_SHOW_MEMORY_DETAILED_RESULTS
]
},
)
# Save some memories
await demo_agent_memory.save_tool_usage(
question="What is the total sales?",
tool_name="run_sql",
args={"query": "SELECT SUM(total) FROM invoices"},
context=context,
success=True,
)
# Search for similar patterns
search_params = SearchSavedCorrectToolUsesParams(
question="What are the total sales?", limit=10, similarity_threshold=0.5
)
result = await search_tool.execute(context, search_params)
# Verify result
assert result.success is True
assert result.ui_component is not None
assert result.ui_component.rich_component is not None
# Check that it's a CardComponent (detailed view)
assert result.ui_component.rich_component.type == ComponentType.CARD
# Check collapsible properties
card = result.ui_component.rich_component
assert card.collapsible is True
assert card.collapsed is True # Should start collapsed
# Verify content includes detailed information
assert "Retrieved memories passed to LLM" in card.content
assert "run_sql" in card.content
assert "similarity:" in card.content.lower()
assert "Question:" in card.content
assert "Arguments:" in card.content
@pytest.mark.asyncio
async def test_non_admin_sees_simple_status(
self, search_tool, demo_agent_memory, regular_user
):
"""Test that non-admin users see simple status message."""
# Create context with regular user (no detailed results feature)
context = ToolContext(
user=regular_user,
conversation_id=str(uuid.uuid4()),
request_id=str(uuid.uuid4()),
agent_memory=demo_agent_memory,
metadata={"ui_features_available": []}, # No detailed results feature
)
# Save some memories
await demo_agent_memory.save_tool_usage(
question="What is the total sales?",
tool_name="run_sql",
args={"query": "SELECT SUM(total) FROM invoices"},
context=context,
success=True,
)
# Search for similar patterns
search_params = SearchSavedCorrectToolUsesParams(
question="What are the total sales?", limit=10, similarity_threshold=0.5
)
result = await search_tool.execute(context, search_params)
# Verify result
assert result.success is True
assert result.ui_component is not None
assert result.ui_component.rich_component is not None
# Check that it's a StatusBarUpdateComponent (simple view)
assert (
result.ui_component.rich_component.type == ComponentType.STATUS_BAR_UPDATE
)
# Verify it shows success message
status = result.ui_component.rich_component
assert status.status == "success"
assert "similar pattern" in status.message.lower()
@pytest.mark.asyncio
async def test_detailed_results_include_all_memory_fields(
self, search_tool, demo_agent_memory, admin_user
):
"""Test that detailed results include all relevant memory fields."""
# Create context with admin user and feature enabled
context = ToolContext(
user=admin_user,
conversation_id=str(uuid.uuid4()),
request_id=str(uuid.uuid4()),
agent_memory=demo_agent_memory,
metadata={
"ui_features_available": [
UiFeature.UI_FEATURE_SHOW_MEMORY_DETAILED_RESULTS
]
},
)
# Save a memory
await demo_agent_memory.save_tool_usage(
question="Show me customer names",
tool_name="run_sql",
args={"query": "SELECT name FROM customers"},
context=context,
success=True,
)
# Search for it
search_params = SearchSavedCorrectToolUsesParams(
question="Show customer names", limit=10, similarity_threshold=0.3
)
result = await search_tool.execute(context, search_params)
# Verify detailed content
card = result.ui_component.rich_component
content = card.content
# Check for all expected fields
assert "Question:" in content
assert "Show me customer names" in content
assert "Arguments:" in content
assert "run_sql" in content
assert "similarity:" in content.lower()
# Timestamp and ID should be included if available
# (DemoAgentMemory might not set these, but the code should handle them)
@pytest.mark.asyncio
async def test_no_results_works_for_both_admin_and_user(
self, search_tool, demo_agent_memory, admin_user, regular_user
):
"""Test that admin sees card with 0 results while regular user sees status bar."""
# Test with admin
admin_context = ToolContext(
user=admin_user,
conversation_id=str(uuid.uuid4()),
request_id=str(uuid.uuid4()),
agent_memory=demo_agent_memory,
metadata={
"ui_features_available": [
UiFeature.UI_FEATURE_SHOW_MEMORY_DETAILED_RESULTS
]
},
)
search_params = SearchSavedCorrectToolUsesParams(
question="This query will not match anything",
limit=10,
similarity_threshold=0.99,
)
admin_result = await search_tool.execute(admin_context, search_params)
assert admin_result.success is True
assert "No similar tool usage patterns found" in admin_result.result_for_llm
# Admin should see a card showing 0 results
assert admin_result.ui_component.rich_component.type == ComponentType.CARD
assert "0 Results" in admin_result.ui_component.rich_component.title
assert admin_result.ui_component.rich_component.collapsible is True
# Test with regular user
user_context = ToolContext(
user=regular_user,
conversation_id=str(uuid.uuid4()),
request_id=str(uuid.uuid4()),
agent_memory=demo_agent_memory,
metadata={"ui_features_available": []},
)
user_result = await search_tool.execute(user_context, search_params)
assert user_result.success is True
assert "No similar tool usage patterns found" in user_result.result_for_llm
# Regular user should see a status bar update
assert (
user_result.ui_component.rich_component.type
== ComponentType.STATUS_BAR_UPDATE
)
@pytest.mark.asyncio
async def test_llm_result_same_for_admin_and_user(
self, search_tool, demo_agent_memory, admin_user, regular_user
):
"""Test that the LLM receives the same information regardless of UI feature access."""
# Save a memory
admin_context = ToolContext(
user=admin_user,
conversation_id=str(uuid.uuid4()),
request_id=str(uuid.uuid4()),
agent_memory=demo_agent_memory,
metadata={
"ui_features_available": [
UiFeature.UI_FEATURE_SHOW_MEMORY_DETAILED_RESULTS
]
},
)
await demo_agent_memory.save_tool_usage(
question="Count all records",
tool_name="run_sql",
args={"query": "SELECT COUNT(*) FROM table"},
context=admin_context,
success=True,
)
search_params = SearchSavedCorrectToolUsesParams(
question="Count records", limit=10, similarity_threshold=0.3
)
# Get admin result
admin_result = await search_tool.execute(admin_context, search_params)
# Get regular user result
user_context = ToolContext(
user=regular_user,
conversation_id=str(uuid.uuid4()),
request_id=str(uuid.uuid4()),
agent_memory=demo_agent_memory,
metadata={"ui_features_available": []},
)
user_result = await search_tool.execute(user_context, search_params)
# Both should have the same result_for_llm
assert admin_result.result_for_llm == user_result.result_for_llm
assert "Found" in admin_result.result_for_llm
assert "similar tool usage pattern" in admin_result.result_for_llm
if __name__ == "__main__":
pytest.main([__file__, "-v"])
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_memory_tools.py",
"license": "MIT License",
"lines": 246,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_ollama_direct.py | """
Direct Ollama integration tests to diagnose and verify the integration.
These tests check each aspect of the Ollama integration separately.
"""
import pytest
from vanna.core.llm import LlmRequest, LlmMessage
from vanna.core.tool import ToolSchema
from vanna.core.user import User
@pytest.fixture
def test_user():
"""Test user for LLM requests."""
return User(
id="test_user",
username="test",
email="test@example.com",
group_memberships=["user"],
)
@pytest.mark.ollama
@pytest.mark.asyncio
async def test_ollama_import():
"""Test that Ollama integration can be imported."""
try:
from vanna.integrations.ollama import OllamaLlmService
print("✓ OllamaLlmService imported successfully")
assert OllamaLlmService is not None
except ImportError as e:
pytest.fail(f"Failed to import OllamaLlmService: {e}")
@pytest.mark.ollama
@pytest.mark.asyncio
async def test_ollama_initialization():
"""Test that Ollama service can be initialized."""
from vanna.integrations.ollama import OllamaLlmService
try:
llm = OllamaLlmService(
model="llama3.2", host="http://localhost:11434", temperature=0.0
)
print(f"✓ OllamaLlmService initialized")
print(f" Model: {llm.model}")
print(f" Host: {llm.host}")
print(f" Temperature: {llm.temperature}")
print(f" Context window: {llm.num_ctx}")
assert llm.model == "llama3.2"
assert llm.host == "http://localhost:11434"
except Exception as e:
pytest.fail(f"Failed to initialize OllamaLlmService: {e}")
@pytest.mark.ollama
@pytest.mark.asyncio
async def test_ollama_basic_request(test_user):
"""Test a basic request without tools."""
from vanna.integrations.ollama import OllamaLlmService
llm = OllamaLlmService(model="llama3.2", temperature=0.0)
request = LlmRequest(
user=test_user,
messages=[
LlmMessage(role="user", content="What is 2+2? Answer with just the number.")
],
)
print(f"\n=== Basic Request Test ===")
print(f"Sending request to Ollama...")
try:
response = await llm.send_request(request)
print(f"✓ Response received")
print(f" Content type: {type(response.content)}")
print(f" Content: {response.content}")
print(f" Finish reason: {response.finish_reason}")
print(f" Tool calls: {response.tool_calls}")
print(f" Usage: {response.usage}")
# Verify response structure
assert response is not None
assert response.content is not None
assert isinstance(response.content, str)
except Exception as e:
print(f"❌ Error during request: {e}")
import traceback
traceback.print_exc()
raise
@pytest.mark.ollama
@pytest.mark.asyncio
async def test_ollama_pydantic_response(test_user):
"""Test that the response is a valid Pydantic model."""
from vanna.integrations.ollama import OllamaLlmService
from vanna.core.llm import LlmResponse
llm = OllamaLlmService(model="llama3.2", temperature=0.0)
request = LlmRequest(
user=test_user, messages=[LlmMessage(role="user", content="Say 'hello'")]
)
print(f"\n=== Pydantic Validation Test ===")
try:
response = await llm.send_request(request)
# Verify it's a Pydantic model
assert isinstance(response, LlmResponse)
print(f"✓ Response is LlmResponse instance")
# Test model_dump
dumped = response.model_dump()
print(f"✓ model_dump() works: {dumped}")
# Test model_dump_json
json_str = response.model_dump_json()
print(f"✓ model_dump_json() works: {json_str[:100]}...")
# Test reconstruction
reconstructed = LlmResponse(**dumped)
print(f"✓ Reconstruction works")
assert reconstructed.content == response.content
except Exception as e:
print(f"❌ Pydantic error: {e}")
import traceback
traceback.print_exc()
raise
@pytest.mark.ollama
@pytest.mark.asyncio
async def test_ollama_streaming(test_user):
"""Test streaming responses."""
from vanna.integrations.ollama import OllamaLlmService
from vanna.core.llm import LlmStreamChunk
llm = OllamaLlmService(model="llama3.2", temperature=0.0)
request = LlmRequest(
user=test_user, messages=[LlmMessage(role="user", content="Count from 1 to 3.")]
)
print(f"\n=== Streaming Test ===")
try:
chunks = []
content_parts = []
async for chunk in llm.stream_request(request):
chunks.append(chunk)
# Verify chunk is correct type
assert isinstance(chunk, LlmStreamChunk)
if chunk.content:
content_parts.append(chunk.content)
print(f" Chunk {len(chunks)}: {chunk.content!r}")
full_content = "".join(content_parts)
print(f"✓ Streaming completed")
print(f" Total chunks: {len(chunks)}")
print(f" Full content: {full_content}")
print(f" Final finish_reason: {chunks[-1].finish_reason}")
assert len(chunks) > 0
assert chunks[-1].finish_reason is not None
except Exception as e:
print(f"❌ Streaming error: {e}")
import traceback
traceback.print_exc()
raise
@pytest.mark.ollama
@pytest.mark.asyncio
async def test_ollama_tool_calling_attempt(test_user):
"""Test tool calling with Ollama (may not work with all models)."""
from vanna.integrations.ollama import OllamaLlmService
llm = OllamaLlmService(model="llama3.2", temperature=0.0)
tools = [
ToolSchema(
name="get_weather",
description="Get the current weather for a location",
parameters={
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"],
},
)
]
request = LlmRequest(
user=test_user,
system_prompt="You are a helpful assistant. When asked about weather, use the get_weather tool.",
messages=[
LlmMessage(role="user", content="What's the weather in San Francisco?")
],
tools=tools,
)
print(f"\n=== Tool Calling Test ===")
print(f"Model: {llm.model}")
print(f"Tools provided: {[t.name for t in tools]}")
try:
response = await llm.send_request(request)
print(f"\nResponse:")
print(f" Content: {response.content}")
print(f" Tool calls: {response.tool_calls}")
print(f" Finish reason: {response.finish_reason}")
if response.tool_calls:
print(f"\n✓ Tool calling works!")
print(f" Number of tool calls: {len(response.tool_calls)}")
for i, tc in enumerate(response.tool_calls):
print(f" Tool call {i + 1}:")
print(f" ID: {tc.id}")
print(f" Name: {tc.name}")
print(f" Arguments: {tc.arguments}")
print(f" Arguments type: {type(tc.arguments)}")
else:
print(f"\n⚠️ Model returned text instead of tool calls")
print(f" This is expected for models without tool calling support")
print(f" Try using llama3.1:8b or mistral for better tool calling")
# Test passes either way - we're just diagnosing
assert response is not None
except Exception as e:
print(f"❌ Tool calling error: {e}")
import traceback
traceback.print_exc()
raise
@pytest.mark.ollama
@pytest.mark.asyncio
async def test_ollama_payload_building(test_user):
"""Test that the payload is built correctly."""
from vanna.integrations.ollama import OllamaLlmService
llm = OllamaLlmService(model="llama3.2", temperature=0.5, num_ctx=4096)
tools = [
ToolSchema(
name="test_tool",
description="A test tool",
parameters={"type": "object", "properties": {}},
)
]
request = LlmRequest(
user=test_user,
system_prompt="You are a test assistant.",
messages=[LlmMessage(role="user", content="Hello")],
tools=tools,
)
print(f"\n=== Payload Building Test ===")
try:
# Access the internal method to inspect payload
payload = llm._build_payload(request)
print(f"Built payload:")
print(f" Model: {payload.get('model')}")
print(f" Messages count: {len(payload.get('messages', []))}")
print(f" First message: {payload.get('messages', [{}])[0]}")
print(f" Options: {payload.get('options')}")
print(f" Tools: {payload.get('tools')}")
# Verify payload structure
assert payload["model"] == "llama3.2"
assert len(payload["messages"]) == 2 # system + user
assert payload["messages"][0]["role"] == "system"
assert payload["messages"][1]["role"] == "user"
assert payload["options"]["temperature"] == 0.5
assert payload["options"]["num_ctx"] == 4096
assert "tools" in payload
assert len(payload["tools"]) == 1
print(f"✓ Payload structure is correct")
except Exception as e:
print(f"❌ Payload building error: {e}")
import traceback
traceback.print_exc()
raise
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_ollama_direct.py",
"license": "MIT License",
"lines": 240,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_tool_permissions.py | """
Tests for tool access control and permissions.
"""
import pytest
from pydantic import BaseModel, Field
from typing import Type, TypeVar, Union
from vanna.core.tool import (
Tool,
ToolContext,
ToolResult,
ToolCall,
ToolRejection,
ToolSchema,
)
from vanna.core.user import User
from vanna.core.registry import ToolRegistry
from vanna.components import UiComponent, SimpleTextComponent
from vanna.integrations.local.agent_memory import DemoAgentMemory
T = TypeVar("T")
class SimpleToolArgs(BaseModel):
"""Simple args for testing."""
message: str = Field(description="A message")
class MockTool(Tool[SimpleToolArgs]):
"""Mock tool for testing."""
def __init__(self, tool_name: str = "mock_tool"):
self._tool_name = tool_name
@property
def name(self) -> str:
return self._tool_name
@property
def description(self) -> str:
return f"A mock tool for testing: {self._tool_name}"
def get_args_schema(self) -> Type[SimpleToolArgs]:
return SimpleToolArgs
async def execute(self, context: ToolContext, args: SimpleToolArgs) -> ToolResult:
return ToolResult(
success=True, result_for_llm=f"Mock tool executed: {args.message}"
)
@pytest.fixture
def agent_memory():
"""Agent memory for testing."""
return DemoAgentMemory(max_items=100)
@pytest.fixture
def admin_user():
"""Admin user with admin group."""
return User(
id="admin_1",
username="admin",
email="admin@example.com",
group_memberships=["admin", "user"],
)
@pytest.fixture
def regular_user():
"""Regular user with user group."""
return User(
id="user_1",
username="user",
email="user@example.com",
group_memberships=["user"],
)
@pytest.fixture
def analyst_user():
"""Analyst user with analyst group."""
return User(
id="analyst_1",
username="analyst",
email="analyst@example.com",
group_memberships=["analyst", "user"],
)
@pytest.fixture
def guest_user():
"""Guest user with no groups."""
return User(
id="guest_1", username="guest", email="guest@example.com", group_memberships=[]
)
@pytest.mark.asyncio
async def test_tool_access_empty_groups_allows_all(regular_user, agent_memory):
"""Test that empty access_groups allows all users."""
print("\n=== Empty Access Groups Test ===")
registry = ToolRegistry()
tool = MockTool("public_tool")
# Register with empty access groups
registry.register_local_tool(tool, access_groups=[])
# Create context
context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
# Execute tool
tool_call = ToolCall(
id="call_1", name="public_tool", arguments={"message": "hello"}
)
result = await registry.execute(tool_call, context)
print(f"✓ Tool executed with empty access groups")
print(f" Success: {result.success}")
assert result.success is True
assert "Mock tool executed" in result.result_for_llm
@pytest.mark.asyncio
async def test_tool_access_granted_matching_group(admin_user, agent_memory):
"""Test that user with matching group can access tool."""
print("\n=== Access Granted Test ===")
registry = ToolRegistry()
tool = MockTool("admin_tool")
# Register with admin-only access
registry.register_local_tool(tool, access_groups=["admin"])
context = ToolContext(
user=admin_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
tool_call = ToolCall(
id="call_1", name="admin_tool", arguments={"message": "admin action"}
)
result = await registry.execute(tool_call, context)
print(f"✓ Admin user accessed admin-only tool")
print(f" User groups: {admin_user.group_memberships}")
print(f" Tool access groups: ['admin']")
print(f" Success: {result.success}")
assert result.success is True
@pytest.mark.asyncio
async def test_tool_access_denied_no_matching_group(regular_user, agent_memory):
"""Test that user without matching group cannot access tool."""
print("\n=== Access Denied Test ===")
registry = ToolRegistry()
tool = MockTool("admin_tool")
# Register with admin-only access
registry.register_local_tool(tool, access_groups=["admin"])
context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
tool_call = ToolCall(
id="call_1", name="admin_tool", arguments={"message": "should fail"}
)
result = await registry.execute(tool_call, context)
print(f"✓ Regular user denied access to admin-only tool")
print(f" User groups: {regular_user.group_memberships}")
print(f" Tool access groups: ['admin']")
print(f" Success: {result.success}")
print(f" Error: {result.error}")
assert result.success is False
assert "Insufficient group access" in result.result_for_llm
assert "admin_tool" in result.result_for_llm
@pytest.mark.asyncio
async def test_tool_access_multiple_allowed_groups(
analyst_user, admin_user, regular_user, agent_memory
):
"""Test tool with multiple allowed groups."""
print("\n=== Multiple Allowed Groups Test ===")
registry = ToolRegistry()
tool = MockTool("data_tool")
# Allow both admin and analyst groups
registry.register_local_tool(tool, access_groups=["admin", "analyst"])
# Test analyst can access
analyst_context = ToolContext(
user=analyst_user,
conversation_id="test_conv",
request_id="test_req_1",
agent_memory=agent_memory,
)
tool_call = ToolCall(id="call_1", name="data_tool", arguments={"message": "test"})
result = await registry.execute(tool_call, analyst_context)
print(f"✓ Analyst accessed tool")
assert result.success is True
# Test admin can access
admin_context = ToolContext(
user=admin_user,
conversation_id="test_conv",
request_id="test_req_2",
agent_memory=agent_memory,
)
result = await registry.execute(tool_call, admin_context)
print(f"✓ Admin accessed tool")
assert result.success is True
# Test regular user cannot access
user_context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req_3",
agent_memory=agent_memory,
)
result = await registry.execute(tool_call, user_context)
print(f"✓ Regular user denied access")
assert result.success is False
@pytest.mark.asyncio
async def test_tool_access_guest_user_denied(guest_user, agent_memory):
"""Test that guest user with no groups cannot access restricted tools."""
print("\n=== Guest User Denied Test ===")
registry = ToolRegistry()
tool = MockTool("restricted_tool")
registry.register_local_tool(tool, access_groups=["user"])
context = ToolContext(
user=guest_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
tool_call = ToolCall(
id="call_1", name="restricted_tool", arguments={"message": "test"}
)
result = await registry.execute(tool_call, context)
print(f"✓ Guest user with no groups denied access")
print(f" User groups: {guest_user.group_memberships}")
print(f" Tool access groups: ['user']")
assert result.success is False
assert "Insufficient group access" in result.result_for_llm
@pytest.mark.asyncio
async def test_get_schemas_filters_by_user(admin_user, regular_user):
"""Test that get_schemas only returns tools accessible to user."""
print("\n=== Schema Filtering Test ===")
registry = ToolRegistry()
# Register tools with different access levels
registry.register_local_tool(MockTool("public_tool"), access_groups=[])
registry.register_local_tool(MockTool("admin_tool"), access_groups=["admin"])
registry.register_local_tool(MockTool("user_tool"), access_groups=["user"])
# Admin user should see all tools
admin_schemas = await registry.get_schemas(admin_user)
admin_tool_names = [s.name for s in admin_schemas]
print(f"✓ Admin user schemas: {admin_tool_names}")
assert "public_tool" in admin_tool_names
assert "admin_tool" in admin_tool_names
assert "user_tool" in admin_tool_names
assert len(admin_tool_names) == 3
# Regular user should only see public and user tools
user_schemas = await registry.get_schemas(regular_user)
user_tool_names = [s.name for s in user_schemas]
print(f"✓ Regular user schemas: {user_tool_names}")
assert "public_tool" in user_tool_names
assert "user_tool" in user_tool_names
assert "admin_tool" not in user_tool_names
assert len(user_tool_names) == 2
@pytest.mark.asyncio
async def test_tool_not_found(agent_memory):
"""Test execution of non-existent tool."""
print("\n=== Tool Not Found Test ===")
registry = ToolRegistry()
user = User(id="user", username="user", group_memberships=["user"])
context = ToolContext(
user=user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
tool_call = ToolCall(
id="call_1", name="nonexistent_tool", arguments={"message": "test"}
)
result = await registry.execute(tool_call, context)
print(f"✓ Non-existent tool handled gracefully")
print(f" Error: {result.error}")
assert result.success is False
assert "not found" in result.result_for_llm.lower()
@pytest.mark.asyncio
async def test_duplicate_tool_registration():
"""Test that registering the same tool twice raises error."""
print("\n=== Duplicate Registration Test ===")
registry = ToolRegistry()
tool = MockTool("duplicate_tool")
# First registration should succeed
registry.register_local_tool(tool, access_groups=[])
print(f"✓ First registration succeeded")
# Second registration should fail
with pytest.raises(ValueError, match="already registered"):
registry.register_local_tool(tool, access_groups=[])
print(f"✓ Duplicate registration properly rejected")
@pytest.mark.asyncio
async def test_tool_access_group_intersection(admin_user, agent_memory):
"""Test that access is granted on ANY matching group (not all groups)."""
print("\n=== Group Intersection Test ===")
registry = ToolRegistry()
tool = MockTool("multi_group_tool")
# Tool requires either admin OR analyst
registry.register_local_tool(tool, access_groups=["admin", "analyst"])
# User has admin (but not analyst) - should still have access
context = ToolContext(
user=admin_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
tool_call = ToolCall(
id="call_1", name="multi_group_tool", arguments={"message": "test"}
)
result = await registry.execute(tool_call, context)
print(f"✓ User with ONE matching group granted access")
print(f" User groups: {admin_user.group_memberships}")
print(f" Tool requires: ['admin', 'analyst']")
print(f" Intersection: {set(admin_user.group_memberships) & {'admin', 'analyst'}}")
assert result.success is True
@pytest.mark.asyncio
async def test_list_tools():
"""Test listing all registered tools."""
print("\n=== List Tools Test ===")
registry = ToolRegistry()
registry.register_local_tool(MockTool("tool1"), access_groups=[])
registry.register_local_tool(MockTool("tool2"), access_groups=["admin"])
registry.register_local_tool(MockTool("tool3"), access_groups=["user"])
tools = await registry.list_tools()
print(f"✓ Listed {len(tools)} tools")
print(f" Tools: {tools}")
assert len(tools) == 3
assert "tool1" in tools
assert "tool2" in tools
assert "tool3" in tools
# ============================================================================
# transform_args Tests
# ============================================================================
@pytest.mark.asyncio
async def test_transform_args_default_no_transformation(regular_user, agent_memory):
"""Test that default transform_args implementation returns args unchanged."""
print("\n=== Default transform_args (NoOp) Test ===")
registry = ToolRegistry()
tool = MockTool("test_tool")
registry.register_local_tool(tool, access_groups=[])
context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
# Test the transform_args method directly
original_args = SimpleToolArgs(message="original message")
transformed_args = await registry.transform_args(
tool=tool,
args=original_args,
user=regular_user,
context=context,
)
print(f"✓ Default transform_args returns args unchanged")
print(f" Original: {original_args.message}")
print(f" Transformed: {transformed_args.message}")
assert transformed_args == original_args
assert transformed_args.message == "original message"
assert not isinstance(transformed_args, ToolRejection)
class CustomTransformRegistry(ToolRegistry):
"""Custom registry that modifies arguments."""
async def transform_args(
self,
tool: Tool[T],
args: T,
user: User,
context: ToolContext,
) -> Union[T, ToolRejection]:
"""Custom transform that appends user info to message."""
if isinstance(args, SimpleToolArgs):
# Modify the args by appending user info
modified_args = SimpleToolArgs(
message=f"{args.message} [user: {user.username}]"
)
return modified_args
return args
@pytest.mark.asyncio
async def test_transform_args_custom_modification(regular_user, agent_memory):
"""Test custom transform_args that modifies arguments."""
print("\n=== Custom transform_args Modification Test ===")
registry = CustomTransformRegistry()
tool = MockTool("test_tool")
registry.register_local_tool(tool, access_groups=[])
context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
# Execute tool - args should be transformed
tool_call = ToolCall(
id="call_1",
name="test_tool",
arguments={"message": "hello"},
)
result = await registry.execute(tool_call, context)
print(f"✓ Tool executed with transformed args")
print(f" Result: {result.result_for_llm}")
assert result.success is True
assert "hello [user: user]" in result.result_for_llm
assert "Mock tool executed" in result.result_for_llm
class RejectionRegistry(ToolRegistry):
"""Custom registry that rejects certain arguments."""
async def transform_args(
self,
tool: Tool[T],
args: T,
user: User,
context: ToolContext,
) -> Union[T, ToolRejection]:
"""Reject args containing 'forbidden' keyword."""
if isinstance(args, SimpleToolArgs):
if "forbidden" in args.message.lower():
return ToolRejection(
reason=f"Message contains forbidden keyword. User '{user.username}' is not allowed to use this word."
)
return args
@pytest.mark.asyncio
async def test_transform_args_rejection(regular_user, agent_memory):
"""Test transform_args returning ToolRejection."""
print("\n=== transform_args Rejection Test ===")
registry = RejectionRegistry()
tool = MockTool("test_tool")
registry.register_local_tool(tool, access_groups=[])
context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
# Execute tool with forbidden word
tool_call = ToolCall(
id="call_1",
name="test_tool",
arguments={"message": "this is forbidden"},
)
result = await registry.execute(tool_call, context)
print(f"✓ Tool execution rejected by transform_args")
print(f" Error: {result.error}")
assert result.success is False
assert "forbidden keyword" in result.result_for_llm
assert "not allowed" in result.result_for_llm
assert "user" in result.result_for_llm
@pytest.mark.asyncio
async def test_transform_args_allows_approved_content(regular_user, agent_memory):
"""Test that transform_args allows approved content."""
print("\n=== transform_args Allows Approved Content Test ===")
registry = RejectionRegistry()
tool = MockTool("test_tool")
registry.register_local_tool(tool, access_groups=[])
context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
# Execute tool with approved message
tool_call = ToolCall(
id="call_1",
name="test_tool",
arguments={"message": "this is allowed"},
)
result = await registry.execute(tool_call, context)
print(f"✓ Tool execution allowed for approved content")
print(f" Result: {result.result_for_llm}")
assert result.success is True
assert "Mock tool executed" in result.result_for_llm
assert "this is allowed" in result.result_for_llm
class RowLevelSecurityRegistry(ToolRegistry):
"""Custom registry that applies row-level security transformations."""
async def transform_args(
self,
tool: Tool[T],
args: T,
user: User,
context: ToolContext,
) -> Union[T, ToolRejection]:
"""Apply RLS by modifying SQL queries based on user groups."""
if isinstance(args, SimpleToolArgs):
# Simulate SQL query transformation for RLS
if "SELECT" in args.message.upper():
# Add WHERE clause based on user groups
if "admin" in user.group_memberships:
# Admins see everything - no modification needed
return args
elif "analyst" in user.group_memberships:
# Analysts see filtered data
modified_message = args.message + " WHERE department='analytics'"
return SimpleToolArgs(message=modified_message)
else:
# Regular users see even more restricted data
modified_message = args.message + f" WHERE user_id='{user.id}'"
return SimpleToolArgs(message=modified_message)
return args
@pytest.mark.asyncio
async def test_transform_args_row_level_security(
admin_user, analyst_user, regular_user, agent_memory
):
"""Test transform_args implementing row-level security."""
print("\n=== Row-Level Security Test ===")
registry = RowLevelSecurityRegistry()
tool = MockTool("sql_tool")
registry.register_local_tool(tool, access_groups=[])
base_query = "SELECT * FROM users"
# Test admin user - no modification
admin_context = ToolContext(
user=admin_user,
conversation_id="test_conv",
request_id="test_req_1",
agent_memory=agent_memory,
)
tool_call = ToolCall(
id="call_1",
name="sql_tool",
arguments={"message": base_query},
)
result = await registry.execute(tool_call, admin_context)
print(f"✓ Admin query: {result.result_for_llm}")
assert result.success is True
assert "WHERE" not in result.result_for_llm
# Test analyst user - department filter
analyst_context = ToolContext(
user=analyst_user,
conversation_id="test_conv",
request_id="test_req_2",
agent_memory=agent_memory,
)
result = await registry.execute(tool_call, analyst_context)
print(f"✓ Analyst query: {result.result_for_llm}")
assert result.success is True
assert "WHERE department='analytics'" in result.result_for_llm
# Test regular user - user_id filter
regular_context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req_3",
agent_memory=agent_memory,
)
result = await registry.execute(tool_call, regular_context)
print(f"✓ Regular user query: {result.result_for_llm}")
assert result.success is True
assert f"WHERE user_id='{regular_user.id}'" in result.result_for_llm
@pytest.mark.asyncio
async def test_transform_args_called_during_execution(regular_user, agent_memory):
"""Test that transform_args is called during tool execution flow."""
print("\n=== transform_args Called During Execution Test ===")
class InstrumentedRegistry(ToolRegistry):
def __init__(self):
super().__init__()
self.transform_called = False
self.transform_call_count = 0
async def transform_args(self, tool, args, user, context):
self.transform_called = True
self.transform_call_count += 1
return await super().transform_args(tool, args, user, context)
registry = InstrumentedRegistry()
tool = MockTool("test_tool")
registry.register_local_tool(tool, access_groups=[])
context = ToolContext(
user=regular_user,
conversation_id="test_conv",
request_id="test_req",
agent_memory=agent_memory,
)
tool_call = ToolCall(
id="call_1",
name="test_tool",
arguments={"message": "test"},
)
result = await registry.execute(tool_call, context)
print(f"✓ transform_args was called during execution")
print(f" Called: {registry.transform_called}")
print(f" Call count: {registry.transform_call_count}")
assert result.success is True
assert registry.transform_called is True
assert registry.transform_call_count == 1
@pytest.mark.asyncio
async def test_transform_args_receives_correct_parameters(regular_user, agent_memory):
"""Test that transform_args receives correct parameters."""
print("\n=== transform_args Parameter Validation Test ===")
class ParameterCheckRegistry(ToolRegistry):
def __init__(self):
super().__init__()
self.received_tool = None
self.received_args = None
self.received_user = None
self.received_context = None
async def transform_args(self, tool, args, user, context):
self.received_tool = tool
self.received_args = args
self.received_user = user
self.received_context = context
return await super().transform_args(tool, args, user, context)
registry = ParameterCheckRegistry()
tool = MockTool("test_tool")
registry.register_local_tool(tool, access_groups=[])
context = ToolContext(
user=regular_user,
conversation_id="test_conv_123",
request_id="test_req_456",
agent_memory=agent_memory,
)
tool_call = ToolCall(
id="call_1",
name="test_tool",
arguments={"message": "test message"},
)
result = await registry.execute(tool_call, context)
print(f"✓ transform_args received correct parameters")
print(f" Tool name: {registry.received_tool.name}")
print(f" Args message: {registry.received_args.message}")
print(f" User: {registry.received_user.username}")
print(f" Context conv_id: {registry.received_context.conversation_id}")
assert result.success is True
assert registry.received_tool is not None
assert registry.received_tool.name == "test_tool"
assert registry.received_args is not None
assert registry.received_args.message == "test message"
assert registry.received_user is not None
assert registry.received_user.id == regular_user.id
assert registry.received_context is not None
assert registry.received_context.conversation_id == "test_conv_123"
@pytest.mark.asyncio
async def test_transform_args_called_during_agent_send_message():
"""Test that transform_args is called during Agent.send_message workflow."""
print("\n=== transform_args in Agent.send_message Test ===")
# Import necessary components
from vanna import Agent
from vanna.core.user.resolver import UserResolver
from vanna.core.user.request_context import RequestContext
from vanna.core.llm import LlmService, LlmRequest, LlmResponse, LlmMessage
from vanna.core.agent.config import AgentConfig
# Create a custom registry that tracks transform_args calls
class InstrumentedAgentRegistry(ToolRegistry):
def __init__(self):
super().__init__()
self.transform_calls = []
async def transform_args(self, tool, args, user, context):
# Track that transform_args was called
self.transform_calls.append(
{
"tool_name": tool.name,
"args": args,
"user_id": user.id,
"conversation_id": context.conversation_id,
}
)
# Apply a transformation to verify it's used
if isinstance(args, SimpleToolArgs):
modified_args = SimpleToolArgs(message=f"{args.message} [transformed]")
return modified_args
return args
# Create a simple user resolver
class TestUserResolver(UserResolver):
async def resolve_user(self, request_context: RequestContext) -> User:
return User(
id="test_user_123",
username="test_user",
email="test@example.com",
group_memberships=["user"],
)
# Create a mock LLM service that calls a tool
class MockLlmService(LlmService):
async def send_request(self, request: LlmRequest) -> LlmResponse:
# Return a response that calls our mock tool
return LlmResponse(
content="I'll use the mock tool",
tool_calls=[
ToolCall(
id="call_123",
name="mock_tool",
arguments={"message": "test message"},
)
],
raw_response=None,
)
async def stream_request(self, request: LlmRequest):
# Yield a single chunk with tool call
from vanna.core.llm import LlmStreamChunk
yield LlmStreamChunk(
content="I'll use the mock tool",
tool_calls=[
ToolCall(
id="call_123",
name="mock_tool",
arguments={"message": "test message"},
)
],
raw_chunk=None,
)
async def validate_tools(self, tools: list[ToolSchema]) -> None:
# No validation needed for this test
pass
# Set up the agent
instrumented_registry = InstrumentedAgentRegistry()
tool = MockTool("mock_tool")
instrumented_registry.register_local_tool(tool, access_groups=[])
agent_memory = DemoAgentMemory(max_items=100)
agent = Agent(
llm_service=MockLlmService(),
tool_registry=instrumented_registry,
user_resolver=TestUserResolver(),
agent_memory=agent_memory,
config=AgentConfig(),
)
# Send a message through the agent
request_context = RequestContext(cookies={}, headers={})
components = []
async for component in agent.send_message(request_context, "test message"):
components.append(component)
print(f"✓ Agent.send_message completed")
print(f" Transform calls: {len(instrumented_registry.transform_calls)}")
print(f" Components received: {len(components)}")
# Verify that transform_args was called
assert len(instrumented_registry.transform_calls) > 0, (
"transform_args should be called during Agent.send_message"
)
# Check the first transform call
first_call = instrumented_registry.transform_calls[0]
assert first_call["tool_name"] == "mock_tool"
assert first_call["user_id"] == "test_user_123"
assert first_call["conversation_id"] is not None
print(f" ✓ transform_args was called with correct parameters")
print(f" Tool: {first_call['tool_name']}")
print(f" User: {first_call['user_id']}")
print(
f" Total transform_args calls: {len(instrumented_registry.transform_calls)}"
)
# Verify that the args passed to transform_args have the expected message
assert first_call["args"].message == "test message"
print(f" Original args message: {first_call['args'].message}")
print(
f" ✓ All checks passed - transform_args is called during Agent.send_message workflow"
)
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_tool_permissions.py",
"license": "MIT License",
"lines": 713,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
vanna-ai/vanna:tests/test_workflow.py | """
Tests for the default workflow handler, including memory display and deletion.
"""
import pytest
import uuid
from datetime import datetime
from vanna.core.workflow.default import DefaultWorkflowHandler
from vanna.core.user import User
from vanna.core.user.resolver import UserResolver
from vanna.core.user.request_context import RequestContext
from vanna.core.storage import Conversation
from vanna.core.tool import ToolContext
from vanna.capabilities.agent_memory import ToolMemory, TextMemory
from vanna.integrations.local.agent_memory import DemoAgentMemory
from vanna.core.rich_component import ComponentType
class SimpleUserResolver(UserResolver):
"""Simple user resolver for tests."""
async def resolve_user(self, request_context: RequestContext) -> User:
return User(
id="test_user", email="test@example.com", group_memberships=["user"]
)
class MockAgent:
"""Mock agent for testing workflow handlers."""
def __init__(self, agent_memory=None, tool_registry=None):
self.agent_memory = agent_memory
self.tool_registry = tool_registry or MockToolRegistry()
class MockToolRegistry:
"""Mock tool registry for testing."""
async def get_schemas(self, user):
"""Return mock tool schemas."""
return []
class MockConversation:
"""Mock conversation for testing."""
def __init__(self, conversation_id=None):
self.id = conversation_id or str(uuid.uuid4())
@pytest.fixture
def test_user():
"""Create a test user."""
return User(id="test_user", email="test@example.com", group_memberships=["user"])
@pytest.fixture
def admin_test_user():
"""Create an admin test user for tests that require admin access."""
return User(id="admin_user", email="admin@example.com", group_memberships=["admin"])
@pytest.fixture
def test_conversation():
"""Create a test conversation."""
return MockConversation()
@pytest.fixture
def workflow_handler():
"""Create a workflow handler instance."""
return DefaultWorkflowHandler()
@pytest.fixture
def agent_with_memory():
"""Create a mock agent with memory."""
memory = DemoAgentMemory(max_items=100)
return MockAgent(agent_memory=memory)
@pytest.fixture
def agent_without_memory():
"""Create a mock agent without memory."""
return MockAgent(agent_memory=None)
class TestWorkflowCommands:
"""Test basic workflow command handling."""
@pytest.mark.asyncio
async def test_help_command(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test that /help command returns help message (non-admin view)."""
result = await workflow_handler.try_handle(
agent_with_memory, test_user, test_conversation, "/help"
)
assert result.should_skip_llm is True
assert len(result.components) > 0
# Check that help content includes basic commands
help_component = result.components[0]
content = help_component.rich_component.content
assert "/help" in content
# Admin commands should NOT be visible to non-admin users
assert "Admin Commands" not in content
assert "/status" not in content
assert "/memories" not in content
assert "/delete" not in content
@pytest.mark.asyncio
async def test_status_command(
self,
workflow_handler,
agent_with_memory,
admin_test_user,
test_conversation,
):
"""Test that /status command returns status information (admin only)."""
result = await workflow_handler.try_handle(
agent_with_memory, admin_test_user, test_conversation, "/status"
)
assert result.should_skip_llm is True
assert len(result.components) > 0
@pytest.mark.asyncio
async def test_memories_command(
self,
workflow_handler,
agent_with_memory,
admin_test_user,
test_conversation,
):
"""Test that /memories command returns memory list (admin only)."""
result = await workflow_handler.try_handle(
agent_with_memory, admin_test_user, test_conversation, "/memories"
)
assert result.should_skip_llm is True
assert len(result.components) > 0
@pytest.mark.asyncio
async def test_unknown_command(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test that unknown commands are passed to LLM."""
result = await workflow_handler.try_handle(
agent_with_memory, test_user, test_conversation, "What is the weather?"
)
assert result.should_skip_llm is False
class TestMemoriesView:
"""Test the memories view functionality."""
@pytest.mark.asyncio
async def test_memories_no_agent_memory(
self, workflow_handler, agent_without_memory, test_user, test_conversation
):
"""Test memories view when agent has no memory capability."""
result = await workflow_handler._get_recent_memories(
agent_without_memory, test_user, test_conversation
)
assert result.should_skip_llm is True
assert len(result.components) == 1
content = result.components[0].rich_component.content
assert "No Memory System" in content
@pytest.mark.asyncio
async def test_memories_empty(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test memories view when no memories exist."""
result = await workflow_handler._get_recent_memories(
agent_with_memory, test_user, test_conversation
)
assert result.should_skip_llm is True
assert len(result.components) == 1
content = result.components[0].rich_component.content
assert "No recent memories found" in content
@pytest.mark.asyncio
async def test_memories_with_tool_memories(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test memories view displays tool memories correctly."""
# Create a context and add some tool memories
context = ToolContext(
user=test_user,
conversation_id=test_conversation.id,
request_id=str(uuid.uuid4()),
agent_memory=agent_with_memory.agent_memory,
)
# Add tool memories
await agent_with_memory.agent_memory.save_tool_usage(
question="What is the total sales?",
tool_name="run_sql",
args={"query": "SELECT SUM(total) FROM invoices"},
context=context,
success=True,
)
await agent_with_memory.agent_memory.save_tool_usage(
question="Show me customer names",
tool_name="run_sql",
args={"query": "SELECT name FROM customers"},
context=context,
success=True,
)
# Get memories view
result = await workflow_handler._get_recent_memories(
agent_with_memory, test_user, test_conversation
)
assert result.should_skip_llm is True
assert len(result.components) > 1 # Header + at least one memory card
# Check header
header = result.components[0].rich_component.content
assert "Recent Memories" in header
assert "2" in header # Should show count
# Check that we have tool memory section
found_tool_section = False
for component in result.components:
if hasattr(component.rich_component, "content"):
if "Tool Memories" in component.rich_component.content:
found_tool_section = True
break
assert found_tool_section
@pytest.mark.asyncio
async def test_memories_with_text_memories(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test memories view displays text memories correctly."""
# Create a context and add some text memories
context = ToolContext(
user=test_user,
conversation_id=test_conversation.id,
request_id=str(uuid.uuid4()),
agent_memory=agent_with_memory.agent_memory,
)
# Add text memories
await agent_with_memory.agent_memory.save_text_memory(
content="Remember to always check the data quality",
context=context,
)
await agent_with_memory.agent_memory.save_text_memory(
content="The fiscal year starts in April",
context=context,
)
# Get memories view
result = await workflow_handler._get_recent_memories(
agent_with_memory, test_user, test_conversation
)
assert result.should_skip_llm is True
assert len(result.components) > 1 # Header + at least one memory card
# Check that we have text memory section
found_text_section = False
for component in result.components:
if hasattr(component.rich_component, "content"):
if "Text Memories" in component.rich_component.content:
found_text_section = True
break
assert found_text_section
@pytest.mark.asyncio
async def test_memories_with_both_types(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test memories view displays both tool and text memories."""
# Create a context
context = ToolContext(
user=test_user,
conversation_id=test_conversation.id,
request_id=str(uuid.uuid4()),
agent_memory=agent_with_memory.agent_memory,
)
# Add tool memory
await agent_with_memory.agent_memory.save_tool_usage(
question="What is the total sales?",
tool_name="run_sql",
args={"query": "SELECT SUM(total) FROM invoices"},
context=context,
success=True,
)
# Add text memory
await agent_with_memory.agent_memory.save_text_memory(
content="Important note about the data",
context=context,
)
# Get memories view
result = await workflow_handler._get_recent_memories(
agent_with_memory, test_user, test_conversation
)
assert result.should_skip_llm is True
# Should have header + text section + text cards + tool section + tool cards
assert len(result.components) >= 4
# Check both sections exist
content_str = str(
[
c.rich_component.content
if hasattr(c.rich_component, "content")
else str(c.rich_component)
for c in result.components
]
)
assert "Text Memories" in content_str
assert "Tool Memories" in content_str
@pytest.mark.asyncio
async def test_memories_have_delete_buttons(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test that memory cards include delete buttons."""
# Create a context and add a memory
context = ToolContext(
user=test_user,
conversation_id=test_conversation.id,
request_id=str(uuid.uuid4()),
agent_memory=agent_with_memory.agent_memory,
)
await agent_with_memory.agent_memory.save_tool_usage(
question="Test question",
tool_name="test_tool",
args={"param": "value"},
context=context,
success=True,
)
# Get memories view
result = await workflow_handler._get_recent_memories(
agent_with_memory, test_user, test_conversation
)
# Find a card component with actions
found_delete_button = False
for component in result.components:
if (
hasattr(component.rich_component, "actions")
and component.rich_component.actions
):
for action in component.rich_component.actions:
if "/delete" in action.get("action", ""):
found_delete_button = True
break
assert found_delete_button, "Should have delete button in memory cards"
class TestMemoryDeletion:
"""Test memory deletion functionality."""
@pytest.mark.asyncio
async def test_delete_no_agent_memory(
self, workflow_handler, agent_without_memory, test_user, test_conversation
):
"""Test delete command when agent has no memory capability."""
result = await workflow_handler._delete_memory(
agent_without_memory, test_user, test_conversation, "test-id"
)
assert result.should_skip_llm is True
content = result.components[0].rich_component.content
assert "No Memory System" in content
@pytest.mark.asyncio
async def test_delete_no_id_provided(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test delete command without memory ID."""
result = await workflow_handler._delete_memory(
agent_with_memory, test_user, test_conversation, ""
)
assert result.should_skip_llm is True
content = result.components[0].rich_component.content
assert "Invalid Command" in content
assert "memory_id" in content
@pytest.mark.asyncio
async def test_delete_nonexistent_memory(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test deleting a memory that doesn't exist."""
result = await workflow_handler._delete_memory(
agent_with_memory, test_user, test_conversation, "nonexistent-id"
)
assert result.should_skip_llm is True
content = result.components[0].rich_component.content
assert "Memory Not Found" in content
@pytest.mark.asyncio
async def test_delete_tool_memory_success(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test successfully deleting a tool memory."""
# Create a context and add a memory
context = ToolContext(
user=test_user,
conversation_id=test_conversation.id,
request_id=str(uuid.uuid4()),
agent_memory=agent_with_memory.agent_memory,
)
await agent_with_memory.agent_memory.save_tool_usage(
question="Test question",
tool_name="test_tool",
args={"param": "value"},
context=context,
success=True,
)
# Get the memory ID
memories = await agent_with_memory.agent_memory.get_recent_memories(
context, limit=1
)
assert len(memories) == 1
memory_id = memories[0].memory_id
# Delete the memory
result = await workflow_handler._delete_memory(
agent_with_memory, test_user, test_conversation, memory_id
)
assert result.should_skip_llm is True
content = result.components[0].rich_component.content
assert "Memory Deleted" in content
assert memory_id in content
# Verify memory is gone
memories_after = await agent_with_memory.agent_memory.get_recent_memories(
context, limit=10
)
assert len(memories_after) == 0
@pytest.mark.asyncio
async def test_delete_text_memory_success(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test successfully deleting a text memory."""
# Create a context and add a text memory
context = ToolContext(
user=test_user,
conversation_id=test_conversation.id,
request_id=str(uuid.uuid4()),
agent_memory=agent_with_memory.agent_memory,
)
text_memory = await agent_with_memory.agent_memory.save_text_memory(
content="Test text memory",
context=context,
)
memory_id = text_memory.memory_id
# Delete the memory
result = await workflow_handler._delete_memory(
agent_with_memory, test_user, test_conversation, memory_id
)
assert result.should_skip_llm is True
content = result.components[0].rich_component.content
assert "Memory Deleted" in content
# Verify memory is gone
text_memories_after = (
await agent_with_memory.agent_memory.get_recent_text_memories(
context, limit=10
)
)
assert len(text_memories_after) == 0
@pytest.mark.asyncio
async def test_delete_command_parsing(
self,
workflow_handler,
agent_with_memory,
admin_test_user,
test_conversation,
):
"""Test that /delete command is properly parsed (admin only)."""
# Add a memory first
context = ToolContext(
user=admin_test_user,
conversation_id=test_conversation.id,
request_id=str(uuid.uuid4()),
agent_memory=agent_with_memory.agent_memory,
)
await agent_with_memory.agent_memory.save_tool_usage(
question="Test",
tool_name="test",
args={},
context=context,
success=True,
)
memories = await agent_with_memory.agent_memory.get_recent_memories(
context, limit=1
)
memory_id = memories[0].memory_id
# Test command parsing
result = await workflow_handler.try_handle(
agent_with_memory,
admin_test_user,
test_conversation,
f"/delete {memory_id}",
)
assert result.should_skip_llm is True
content = result.components[0].rich_component.content
assert "Memory Deleted" in content or "Memory Not Found" in content
class TestWorkflowComponentStructure:
"""Test the structure of components returned by workflow."""
@pytest.mark.asyncio
async def test_help_has_rich_component(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test that help command returns properly structured components."""
result = await workflow_handler.try_handle(
agent_with_memory, test_user, test_conversation, "/help"
)
assert len(result.components) > 0
for component in result.components:
assert hasattr(component, "rich_component")
assert hasattr(component, "simple_component")
@pytest.mark.asyncio
async def test_memories_cards_have_proper_structure(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test that memory cards have proper structure."""
# Add a memory
context = ToolContext(
user=test_user,
conversation_id=test_conversation.id,
request_id=str(uuid.uuid4()),
agent_memory=agent_with_memory.agent_memory,
)
await agent_with_memory.agent_memory.save_tool_usage(
question="Test",
tool_name="test_tool",
args={"key": "value"},
context=context,
success=True,
)
result = await workflow_handler._get_recent_memories(
agent_with_memory, test_user, test_conversation
)
# Find card components
card_found = False
for component in result.components:
if hasattr(component.rich_component, "type"):
from vanna.core.rich_component import ComponentType
if component.rich_component.type == ComponentType.CARD:
card_found = True
# Check card has required fields
assert hasattr(component.rich_component, "title")
assert hasattr(component.rich_component, "content")
assert hasattr(component.rich_component, "actions")
assert len(component.rich_component.actions) > 0
assert card_found, "Should have at least one card component"
class TestStarterUI:
"""Test the starter UI functionality."""
@pytest.mark.asyncio
async def test_starter_ui_single_component(
self, workflow_handler, agent_with_memory, test_user, test_conversation
):
"""Test that starter UI returns a single component."""
# Mock tool registry with SQL tool
class MockToolRegistryWithSQL:
async def get_schemas(self, user):
from vanna.core.tool import ToolSchema
return [
ToolSchema(name="run_sql", description="Run SQL", parameters={})
]
agent_with_memory.tool_registry = MockToolRegistryWithSQL()
components = await workflow_handler.get_starter_ui(
agent_with_memory, test_user, test_conversation
)
assert components is not None
assert len(components) == 1, "Starter UI should return exactly one component"
assert hasattr(components[0], "rich_component")
@pytest.mark.asyncio
async def test_starter_ui_user_view(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that non-admin users get a simple welcome message via RichTextComponent."""
# Create user without admin role
user = User(
id="test_user", email="test@example.com", group_memberships=["user"]
)
# Mock tool registry with SQL tool
class MockToolRegistryWithSQL:
async def get_schemas(self, user):
from vanna.core.tool import ToolSchema
return [
ToolSchema(name="run_sql", description="Run SQL", parameters={})
]
agent_with_memory.tool_registry = MockToolRegistryWithSQL()
components = await workflow_handler.get_starter_ui(
agent_with_memory, user, test_conversation
)
assert len(components) == 1
rich_text = components[0].rich_component
assert rich_text.type == ComponentType.TEXT
assert "Welcome to Vanna AI" in rich_text.content
# User view should be simple and not mention memory management
assert "Memory Management" not in rich_text.content
assert "Admin" not in rich_text.content
@pytest.mark.asyncio
async def test_starter_ui_admin_view(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that admin users get setup status and memory management info."""
# Create admin user
admin_user = User(
id="admin_user", email="admin@example.com", group_memberships=["admin"]
)
# Mock tool registry with SQL and memory tools
class MockToolRegistryComplete:
async def get_schemas(self, user):
from vanna.core.tool import ToolSchema
return [
ToolSchema(name="run_sql", description="Run SQL", parameters={}),
ToolSchema(
name="search_saved_correct_tool_uses",
description="Search",
parameters={},
),
ToolSchema(
name="save_question_tool_args",
description="Save",
parameters={},
),
]
agent_with_memory.tool_registry = MockToolRegistryComplete()
components = await workflow_handler.get_starter_ui(
agent_with_memory, admin_user, test_conversation
)
assert len(components) == 1
card = components[0].rich_component
assert card.type == ComponentType.CARD
assert hasattr(card, "title")
assert "Admin" in card.title # Should indicate admin status
assert "🔒 Admin View" in card.content # Should show admin badge
assert "Setup:" in card.content
# Admin view should include memory management info
assert "Memory Management" in card.content
assert "As an admin" in card.content
# Should have View Memories button
assert hasattr(card, "actions")
assert any(
"View Memories" in action.get("label", "") for action in card.actions
)
@pytest.mark.asyncio
async def test_starter_ui_admin_without_memory(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that admin users see setup status even without memory tools."""
# Create admin user
admin_user = User(
id="admin_user", email="admin@example.com", group_memberships=["admin"]
)
# Mock tool registry with only SQL
class MockToolRegistrySQL:
async def get_schemas(self, user):
from vanna.core.tool import ToolSchema
return [
ToolSchema(name="run_sql", description="Run SQL", parameters={}),
]
agent_with_memory.tool_registry = MockToolRegistrySQL()
components = await workflow_handler.get_starter_ui(
agent_with_memory, admin_user, test_conversation
)
assert len(components) == 1
card = components[0].rich_component
assert card.type == ComponentType.CARD
# Admin should see setup status showing incomplete memory setup
assert "Admin" in card.title
assert "🔒 Admin View" in card.content
assert "Setup:" in card.content
assert "Memory ✗" in card.content
# Should NOT have View Memories button since memory is not available
memory_button_exists = any(
"View Memories" in action.get("label", "")
for action in (card.actions or [])
)
assert not memory_button_exists
class TestAdminOnlyCommands:
"""Test that admin-only commands are properly restricted."""
@pytest.mark.asyncio
async def test_non_admin_cannot_access_status(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that non-admin users cannot access /status command."""
# Create non-admin user
user = User(id="user", email="user@example.com", group_memberships=["user"])
result = await workflow_handler.try_handle(
agent_with_memory, user, test_conversation, "/status"
)
assert result.should_skip_llm is True
assert len(result.components) == 1
rich_text = result.components[0].rich_component
assert "Access Denied" in rich_text.content
assert "administrators" in rich_text.content
@pytest.mark.asyncio
async def test_non_admin_cannot_access_memories(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that non-admin users cannot access /memories command."""
# Create non-admin user
user = User(id="user", email="user@example.com", group_memberships=["user"])
result = await workflow_handler.try_handle(
agent_with_memory, user, test_conversation, "/memories"
)
assert result.should_skip_llm is True
assert len(result.components) == 1
rich_text = result.components[0].rich_component
assert "Access Denied" in rich_text.content
assert "administrators" in rich_text.content
@pytest.mark.asyncio
async def test_non_admin_cannot_delete_memories(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that non-admin users cannot use /delete command."""
# Create non-admin user
user = User(id="user", email="user@example.com", group_memberships=["user"])
result = await workflow_handler.try_handle(
agent_with_memory, user, test_conversation, "/delete some-memory-id"
)
assert result.should_skip_llm is True
assert len(result.components) == 1
rich_text = result.components[0].rich_component
assert "Access Denied" in rich_text.content
assert "administrators" in rich_text.content
@pytest.mark.asyncio
async def test_admin_can_access_memories(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that admin users can access /memories command."""
# Create admin user
admin_user = User(
id="admin", email="admin@example.com", group_memberships=["admin"]
)
result = await workflow_handler.try_handle(
agent_with_memory, admin_user, test_conversation, "/memories"
)
assert result.should_skip_llm is True
# Should show memories (even if empty, no access denied)
assert len(result.components) >= 1
assert "Access Denied" not in result.components[0].rich_component.content
@pytest.mark.asyncio
async def test_help_shows_admin_commands_for_admin(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that /help shows admin commands for admin users."""
# Create admin user
admin_user = User(
id="admin", email="admin@example.com", group_memberships=["admin"]
)
result = await workflow_handler.try_handle(
agent_with_memory, admin_user, test_conversation, "/help"
)
assert result.should_skip_llm is True
content = result.components[0].rich_component.content
assert "Admin Commands" in content
assert "/status" in content
assert "/memories" in content
assert "/delete" in content
@pytest.mark.asyncio
async def test_help_hides_admin_commands_for_non_admin(
self, workflow_handler, agent_with_memory, test_conversation
):
"""Test that /help hides admin commands for non-admin users."""
# Create non-admin user
user = User(id="user", email="user@example.com", group_memberships=["user"])
result = await workflow_handler.try_handle(
agent_with_memory, user, test_conversation, "/help"
)
assert result.should_skip_llm is True
content = result.components[0].rich_component.content
assert "Admin Commands" not in content
# Still shows regular commands
assert "/help" in content
# But not admin commands
assert "/status" not in content
if __name__ == "__main__":
pytest.main([__file__, "-v"])
| {
"repo_id": "vanna-ai/vanna",
"file_path": "tests/test_workflow.py",
"license": "MIT License",
"lines": 720,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
verl-project/verl:verl/utils/fp8_utils.py | # Copyright 2025 Bytedance Ltd. and/or its affiliates
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
import torch
from verl.utils.kernel.fp8_kernel import scaled_fp8_blockwise
logger = logging.getLogger(__file__)
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO"))
class FP8QuantizerHelper:
def __init__(self, quant_config):
self.quant_config = quant_config
def should_quantize_param(self, param_name):
"""Determine whether to quantize to FP8 based on parameter name
Quantization rules:
- Must end with .weight (exclude bias)
- Exclude embedding layers
- Exclude normalization layers
- Exclude output layer (lm_head)
"""
# Must be a weight parameter
if not param_name.endswith(".weight"):
return False
# Layer types to exclude
exclude_patterns = [
"embed_tokens", # Embedding layer
"lm_head", # Output layer
"layernorm", # LayerNorm
"norm", # Various Norm layers
"ln_", # LayerNorm variants
"embeddings", # Embeddings
"mlp.gate.weight", # MoE router
]
# Check if matches exclude patterns
param_lower = param_name.lower()
for pattern in exclude_patterns:
if pattern in param_lower:
return False
# Layer types to include (Linear layers)
include_patterns = [
"q_proj", # Query projection
"k_proj", # Key projection
"v_proj", # Value projection
"o_proj", # Output projection
"gate_proj", # Gate projection (for MLP)
"up_proj", # Up projection (for MLP)
"down_proj", # Down projection (for MLP)
"fc1", # Fully connected 1
"fc2", # Fully connected 2
"mlp", # MLP layers
]
# Check if matches include patterns
for pattern in include_patterns:
if pattern in param_lower:
logger.debug(f"Will quantize FP8: {param_name}")
return True
# Do not quantize by default
logger.debug(f"Skip quantization: {param_name}")
return False
def quant_weights_by_name(self, weights, dtype=torch.bfloat16):
"""FP8 quantization based on parameter name using a memory-efficient generator.
Args:
weights: Generator or iterable of (name, tensor) pairs
dtype: Data type for intermediate computation
Yields:
Tuples of (name, tensor) for each weight and its scale
"""
if isinstance(self.quant_config, dict):
weight_block_size = self.quant_config.get("weight_block_size")
else:
weight_block_size = getattr(self.quant_config, "weight_block_size", None)
if weight_block_size is None:
raise ValueError("weight_block_size not found in quant_config")
for k, v in weights:
# Check if quantization is needed
if not self.should_quantize_param(k):
yield (k, v)
continue
# Quantize to FP8
try:
if torch.distributed.get_rank() == 0:
logger.debug(f"Quantizing to FP8 blockwise: {k}")
param_lp, param_scale = scaled_fp8_blockwise(
v.to(dtype),
weight_block_size=weight_block_size,
)
param_scale = param_scale.squeeze(-1)
# Yield the quantized weight and scale
yield (k, param_lp)
yield (k + "_scale_inv", param_scale)
# Explicitly delete to help GC
del param_lp, param_scale
except Exception as e:
logger.error(f"Failed to quantize {k}: {e}")
# If quantization fails, use original weights
yield (k, v)
| {
"repo_id": "verl-project/verl",
"file_path": "verl/utils/fp8_utils.py",
"license": "Apache License 2.0",
"lines": 107,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
verl-project/verl:verl/utils/trtllm/trtllm_fp8_utils.py | # Copyright 2025 Bytedance Ltd. and/or its affiliates
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from verl.utils.fp8_utils import FP8QuantizerHelper
class TRTLLMFP8QuantizerHelper(FP8QuantizerHelper):
def __init__(self, quant_config):
super().__init__(quant_config)
| {
"repo_id": "verl-project/verl",
"file_path": "verl/utils/trtllm/trtllm_fp8_utils.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
verl-project/verl:examples/fapo_trainer/prepare_data.py | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Preprocess the dataset to parquet format
"""
import argparse
import os
from functools import partial
from datasets import concatenate_datasets, load_dataset
from verl.utils.hdfs_io import copy, makedirs
def example_map_fn(example, idx, process_fn, data_source, ability, split):
question, prompt, ground_truth = process_fn(example)
data = {
"data_source": data_source,
"prompt": [{"role": "user", "content": prompt}],
"ability": ability,
"reward_model": {"style": "rule", "ground_truth": ground_truth},
"extra_info": {"split": split, "index": idx, "question": question},
}
return data
def build_aime2024_dataset():
def process_aime2024(example):
question, ground_truth = example["Problem"], str(example["Answer"])
prompt = question.strip() + "\n\n" + "Please reason step by step, and put your final answer within \\boxed{}."
return question, prompt, ground_truth
data_source = "Maxwell-Jia/AIME_2024"
print(f"Loading the {data_source} dataset from huggingface...", flush=True)
dataset = load_dataset(data_source, split="train")
map_fn = partial(example_map_fn, process_fn=process_aime2024, data_source="aime24", ability="Math", split="test")
dataset = dataset.map(map_fn, with_indices=True, remove_columns=dataset.column_names)
return dataset
def build_aime2025_dataset():
def process_aime2025(example):
question, ground_truth = example["problem"], str(example["solution"])
prompt = question.strip() + "\n\n" + "Please reason step by step, and put your final answer within \\boxed{}."
return question, prompt, ground_truth
data_source = "yentinglin/aime_2025"
print(f"Loading the {data_source} dataset from huggingface...", flush=True)
dataset = load_dataset(data_source, split="train")
map_fn = partial(example_map_fn, process_fn=process_aime2025, data_source="aime25", ability="Math", split="test")
dataset = dataset.map(map_fn, with_indices=True, remove_columns=dataset.column_names)
return dataset
def build_gpqa_diamond_dataset():
import random
GPQA_QUERY_TEMPLATE = (
"{Question}\n"
"A. {A}\nB. {B}\nC. {C}\nD. {D}\n\n"
"Please reason step by step, and put your final answer (only the choice letter) within \\boxed{{}}."
)
def process_gpqa_diamond(example):
choices = [
example["Incorrect Answer 1"].strip(),
example["Incorrect Answer 2"].strip(),
example["Incorrect Answer 3"].strip(),
]
random.shuffle(choices)
gold_index = random.randint(0, 3)
choices.insert(gold_index, example["Correct Answer"].strip())
question = example["Question"]
query_prompt = GPQA_QUERY_TEMPLATE.format(
A=choices[0],
B=choices[1],
C=choices[2],
D=choices[3],
Question=question,
)
gold_choice = "ABCD"[gold_index]
return question, query_prompt, gold_choice
data_source = "Idavidrein/gpqa"
print(f"Loading the {data_source} dataset from huggingface...", flush=True)
dataset = load_dataset(data_source, "gpqa_diamond", split="train")
map_fn = partial(
example_map_fn, process_fn=process_gpqa_diamond, data_source="gpqa-diamond", ability="General", split="test"
)
dataset = dataset.map(map_fn, with_indices=True, remove_columns=dataset.column_names)
return dataset
def build_dapo_train_dataset():
def process_dapo(example):
question, ground_truth = example["prompt"], example["solution"]
prompt = question.strip() + "\n\n" + "Please reason step by step, and put your final answer within \\boxed{}."
return question, prompt, ground_truth
data_source = "open-r1/DAPO-Math-17k-Processed"
print(f"Loading the {data_source} dataset from huggingface...", flush=True)
dataset = load_dataset(data_source, "all", split="train")
map_fn = partial(example_map_fn, process_fn=process_dapo, data_source="math-dapo", ability="Math", split="train")
dataset = dataset.map(map_fn, with_indices=True, remove_columns=dataset.column_names)
return dataset
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--local_dir", default="~/data/genrm")
parser.add_argument("--hdfs_dir", default=None)
parser.add_argument("--tasks", default="all")
args = parser.parse_args()
train_dataset = build_dapo_train_dataset()
train_dataset = concatenate_datasets([train_dataset for _ in range(20)])
test_datasets = []
# AIME 2024
aime24_dataset = build_aime2024_dataset()
test_datasets.extend([aime24_dataset for _ in range(32)])
# AIME 2025
aime25_dataset = build_aime2025_dataset()
test_datasets.extend([aime25_dataset for _ in range(32)])
# GPQA Diamond
gpqa_dataset = build_gpqa_diamond_dataset()
test_datasets.extend([gpqa_dataset for _ in range(4)])
test_dataset = concatenate_datasets(test_datasets)
local_dir = args.local_dir
hdfs_dir = args.hdfs_dir
train_dataset.to_parquet(os.path.join(local_dir, "fapo-train-boxed.parquet"))
test_dataset.to_parquet(os.path.join(local_dir, "fapo-test-full-boxed.parquet"))
if hdfs_dir is not None:
makedirs(hdfs_dir)
copy(src=local_dir, dst=hdfs_dir)
| {
"repo_id": "verl-project/verl",
"file_path": "examples/fapo_trainer/prepare_data.py",
"license": "Apache License 2.0",
"lines": 124,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
verl-project/verl:examples/fapo_trainer/reward_fn.py | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import logging
import os
import aiohttp
from transformers import PreTrainedTokenizer
from verl.utils.ray_utils import get_event_loop
from verl.utils.reward_score.math_dapo import last_boxed_only_string, normalize_final_answer, remove_boxed
logger = logging.getLogger(__name__)
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
def verify(
solution_str: str,
gt: str,
) -> tuple[bool, str]:
solution_str = solution_str[-300:]
boxed_answer = last_boxed_only_string(solution_str)
if boxed_answer is not None:
extracted_answer = remove_boxed(boxed_answer)
else:
extracted_answer = "[INVALID]"
pred = normalize_final_answer(extracted_answer)
gt = normalize_final_answer(gt)
return (pred == gt), pred
async def compute_score_baseline(
solution_str: str,
ground_truth: str,
**kwargs,
):
loop = get_event_loop()
"""Compute the reward score for Baseline."""
correct, pred = await loop.run_in_executor(None, lambda: verify(solution_str, ground_truth))
reward_score = 1.0 if correct else -1.0
return {"score": reward_score, "acc": correct, "pred": pred}
# FAPO Hyper-parameters
FAPO_GENRM_TEMPLATE = (
"The following is a math problem with its ground truth answer, along with an AI solution (split into steps):\n\n"
"[Math Problem]\n\n"
"{problem}\n\n"
"[Ground Truth]\n\n"
"{ground_truth}\n\n"
"[AI Solution]\n\n"
"{solution}\n\n"
"Your task is to review and critique the solution step by step. "
"Once you identify an error in a step, return the index of the step where the earliest error occurs. "
"Otherwise, return the index of -1 (which typically denotes 'not found').\n\n"
"Please reason step by step, put your final answer (i.e., the index) in \\boxed{{}}."
)
MAX_TOKENS = 16384
FLAWED_REWARD_PENALTY = 1.0
# async def generate_aiohttp(router_address: str, prompt_ids: list[int], sampling_params: dict):
# payload = {
# "input_ids": prompt_ids,
# "sampling_params": sampling_params,
# }
# url = f"http://{router_address}/generate"
# try:
# session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=None))
# async with session.post(url, json=payload) as resp:
# output = await resp.text()
# try:
# output = json.loads(output)
# return output
# except Exception:
# logger.error(f"Failed to parse JSON response: {output}")
# return {}
# finally:
# await session.close()
async def post_request(router_address: str, payload: dict, endpoint: str, max_retries: int = 5):
url = f"http://{router_address}/{endpoint}"
last_exception = None
for attempt in range(max_retries):
try:
# It's safer to have a timeout instead of None, which can hang indefinitely.
timeout = aiohttp.ClientTimeout(total=None)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(url, json=payload) as resp:
resp.raise_for_status()
return await resp.json()
except aiohttp.ClientResponseError as e:
# Do not retry on 4xx client errors, but retry on 5xx server errors.
if 400 <= e.status < 500:
logger.error(f"Request to {url} failed with client error HTTP {e.status}: {e}. Not retrying.")
raise
last_exception = e
logger.warning(
f"[Attempt {attempt + 1}/{max_retries}] Request to {url} failed with HTTP {e.status}: {e}. Retrying..."
)
except (asyncio.TimeoutError, aiohttp.ClientConnectorError) as e:
last_exception = e
logger.warning(f"[Attempt {attempt + 1}/{max_retries}] Request to {url} failed: {e}. Retrying...")
except Exception as e:
last_exception = e
logger.warning(
f"[Attempt {attempt + 1}/{max_retries}] Request to {url} failed with unexpected error: {e}. Retrying..."
)
if attempt < max_retries - 1:
# Using exponential backoff is generally better than a fixed sleep.
backoff_seconds = 2**attempt
await asyncio.sleep(min(backoff_seconds, 30))
logger.error(f"Max retries ({max_retries}) reached for request to {url}.")
if last_exception:
raise last_exception
async def compute_score_fapo(
data_source: str,
solution_str: str,
ground_truth: str,
extra_info: dict,
reward_router_address: str,
reward_model_tokenizer: PreTrainedTokenizer,
):
"""Compute the reward score for FAPO."""
loop = get_event_loop()
question, split = extra_info["question"], extra_info["split"]
correct, pred = await loop.run_in_executor(None, lambda: verify(solution_str, ground_truth))
reward_score = 1.0 if correct else -1.0
is_flawed_positive = False
# for test set or incorrect solution, directly return the reward score
if split == "test" or not correct:
return {"score": reward_score, "acc": correct, "pred": pred, "is_flawed_positive": is_flawed_positive}
grm_prompt = FAPO_GENRM_TEMPLATE.format(
problem=question,
ground_truth=ground_truth,
solution=solution_str,
)
messages = [{"role": "user", "content": grm_prompt}]
grm_outputs = await post_request(
router_address=reward_router_address,
payload={
"messages": messages,
"max_tokens": MAX_TOKENS,
},
endpoint="v1/chat/completions",
)
grm_response = grm_outputs["choices"][0]["message"]["content"]
try:
err_location = remove_boxed(last_boxed_only_string(grm_response))
is_flawed_positive = int(err_location) != -1
except Exception:
is_flawed_positive = False
if is_flawed_positive:
reward_score -= FLAWED_REWARD_PENALTY
return {"score": reward_score, "acc": correct, "pred": pred, "is_flawed_positive": is_flawed_positive}
| {
"repo_id": "verl-project/verl",
"file_path": "examples/fapo_trainer/reward_fn.py",
"license": "Apache License 2.0",
"lines": 154,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
verl-project/verl:verl/checkpoint_engine/mooncake_checkpoint_engine.py | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import gc
import logging
import os
import time
from typing import Any, AsyncGenerator, Generator
import ray
import torch
from mooncake.engine import TransferEngine
from vllm.distributed.utils import StatelessProcessGroup
from verl.checkpoint_engine.base import CheckpointEngine, CheckpointEngineRegistry, TensorMeta
from verl.utils.device import get_torch_device
from verl.utils.net_utils import get_free_port
logger = logging.getLogger(__name__)
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO"))
@CheckpointEngineRegistry.register("mooncake")
class MooncakeCheckpointEngine(CheckpointEngine):
"""Mooncake checkpoint engine with p2p communication using TransferEngine
Args:
bucket_size (int): Bucket size in bytes to transfer multiple weights at one time.
device (str): The device to use for the checkpoint engine, "cpu" or "cuda".
rollout_dtype (torch.dtype): The dtype of the weights received from rollout workers.
device_name (str): Mooncake device name filter.
"""
def __init__(
self,
bucket_size: int,
device: str = "cuda",
rollout_dtype: torch.dtype = torch.bfloat16,
device_name: str = "",
is_master: bool = False,
rebuild_group: bool = False,
):
self.bucket_size = bucket_size
self.device = device
self.rollout_dtype = rollout_dtype
self.is_master = is_master
self.rebuild_group = rebuild_group
rank = int(os.environ["RANK"])
device_count = get_torch_device().device_count()
local_rank = rank % device_count
get_torch_device().set_device(local_rank)
self.engine = TransferEngine()
hostname = ray.util.get_node_ip_address().strip("[]")
ret = self.engine.initialize(
hostname,
"P2PHANDSHAKE",
"ascend_direct" if self.device == "npu" else "rdma",
device_name,
)
assert ret == 0, f"TransferEngine initialize failed ret={ret}"
rpc_port = self.engine.get_rpc_port()
self.session_id = f"{hostname}:{rpc_port}"
self.hostname = hostname
self.buf = torch.empty(2 * self.bucket_size, dtype=torch.uint8, device=self.device)
self.magic_buf = torch.empty(4 * 1024, dtype=torch.uint8, device=self.device)
ret = self.engine.batch_register_memory(
[self.buf.data_ptr(), self.magic_buf.data_ptr()],
[2 * self.bucket_size, 4 * 1024],
)
assert ret == 0, f"batch_register_memory failed ret={ret}"
logger.info(f"__init__ session_id={self.session_id}")
def prepare(self) -> dict[str, Any]:
"""Prepare send and recv buckets"""
logger.info(
f"prepare ptr={self.buf.data_ptr():#x} len={2 * self.bucket_size} "
f"magic_buf_ptr={self.magic_buf.data_ptr():#x}"
)
port, _ = get_free_port(self.hostname)
return {"addr": self.hostname, "port": port}
@classmethod
def build_topology(cls, trainer_world_size: int, rollout_world_size: int, metadatas: list[dict]):
trainer_kwargs = {
"rank": [0] + [-1] * (trainer_world_size - 1),
"world_size": [rollout_world_size + 1] * trainer_world_size,
"metadata": [metadatas[0]] * trainer_world_size,
}
rollout_kwargs = {
"rank": list(range(1, rollout_world_size + 1)),
"world_size": [rollout_world_size + 1] * rollout_world_size,
"metadata": [metadatas[0]] * rollout_world_size,
}
return trainer_kwargs, rollout_kwargs
def init_process_group(self, rank: int, world_size: int, metadata: dict[str, Any]):
self.rank = rank
self.world_size = world_size
if rank < 0:
logger.info(f"init_process_group rank={rank}")
return
self.store = StatelessProcessGroup.create(
host=metadata["addr"],
port=metadata["port"],
rank=rank,
world_size=world_size,
)
info = {
"session_id": self.session_id,
"ptr": self.buf.data_ptr(),
}
info_list = self.store.all_gather_obj(info)
self.buffer_info = None if rank == 0 else info_list[rank - 1]
logger.info(f"init_process_group rank={rank} world_size={world_size} buffer_info={self.buffer_info}")
def finalize(self):
"""Cleanup communication and deregister memory"""
self.store = None
get_torch_device().empty_cache()
gc.collect()
logger.info(f"finalize rank={self.rank}")
async def wait_for_complete(self, buf: torch.Tensor):
magic = torch.tensor([0xAB, 0xDC, 0xEF, 0x88], dtype=torch.uint8, device=self.device)
while True:
if torch.equal(buf[:4], magic):
break
await asyncio.sleep(0)
@torch.no_grad()
async def send_weights(self, weights: Generator[tuple[str, torch.Tensor], None, None]):
"""Send weights using Mooncake TransferEngine"""
if self.rank < 0:
for name, weight in weights:
pass
logger.info(f"send_weights rank={self.rank}")
return
total_bytes = 0
start_time = time.time()
bucket_meta: dict[str, TensorMeta] = {}
offset = 0
should_wait = False
bufs = [self.buf[: self.bucket_size], self.buf[self.bucket_size :]]
idx = 0
current = bufs[idx]
for name, weight in weights:
weight = weight.to(self.rollout_dtype)
if offset + weight.nbytes > self.bucket_size:
total_bytes += offset
get_torch_device().synchronize()
info = {
"bucket_meta": bucket_meta,
"ptr": current.data_ptr(),
"len": offset,
"is_last": False,
}
# send to rank 1
self.store.send_obj(info, 1)
idx ^= 1
current = bufs[idx]
bucket_meta = {}
offset = 0
if should_wait:
await self.wait_for_complete(current)
should_wait = True
assert offset + weight.nbytes <= self.bucket_size, (
f"Weight {name}({weight.shape}, {weight.dtype}) is too large to fit in the bucket."
)
bucket_meta[name] = {
"name": name,
"shape": weight.shape,
"dtype": weight.dtype,
"offset": offset,
}
current[offset : offset + weight.nbytes].copy_(weight.view(-1).view(torch.uint8), non_blocking=True)
offset += weight.nbytes
get_torch_device().synchronize()
info = {
"bucket_meta": bucket_meta,
"ptr": current.data_ptr(),
"len": offset,
"is_last": True,
}
self.store.send_obj(info, 1)
await self.wait_for_complete(current)
time_cost = time.time() - start_time
bandwidth = total_bytes / time_cost / (1024 * 1024 * 1024)
logger.info(
f"Rank {self.rank} send weights done, "
f"total bytes: {total_bytes} time cost: {time_cost:.2f}s bandwidth: {bandwidth:.2f} GB/s"
)
@torch.no_grad()
async def receive_weights(self) -> AsyncGenerator[tuple[str, torch.Tensor], None]:
"""Receive weights using Mooncake TransferEngine"""
start_time = time.time()
total_bytes = 0
bufs = [self.buf[: self.bucket_size], self.buf[self.bucket_size :]]
idx = 0
current = bufs[idx]
self.magic_buf[:4] = torch.tensor([0xAB, 0xDC, 0xEF, 0x88], dtype=torch.uint8, device=self.device)
while True:
# 1 receive info from previous rank
info = self.store.recv_obj(self.rank - 1)
if idx >= 2 and self.rank < self.world_size - 1:
await self.wait_for_complete(current)
ptr = info["ptr"]
ret = self.engine.transfer_sync_read(
self.buffer_info["session_id"],
current.data_ptr(),
ptr,
info["len"],
)
assert ret == 0, f"transfer_sync_read failed {ret}"
total_bytes += info["len"]
# 2 send info to next rank
info["ptr"] = current.data_ptr()
if self.rank < self.world_size - 1:
self.store.send_obj(info, self.rank + 1)
# 3 yield tensor from current buffer
for name, meta in info["bucket_meta"].items():
dtype, shape = meta["dtype"], meta["shape"]
size = dtype.itemsize * shape.numel()
tensor = current[meta["offset"] : meta["offset"] + size].view(dtype=dtype).view(shape)
yield name, tensor
# 4 write magic data to previous rank
ret = self.engine.transfer_sync_write(
self.buffer_info["session_id"],
self.magic_buf.data_ptr(),
ptr,
4,
)
assert ret == 0, f"transfer_sync_write failed {ret}"
# 5 swap buffer
idx += 1
current = bufs[idx % 2]
get_torch_device().synchronize()
if info["is_last"]:
break
time_cost = time.time() - start_time
bandwidth = total_bytes / time_cost / (1024 * 1024 * 1024)
logger.info(
f"Rank {self.rank} receive weights done, time cost: {time_cost:.2f}s, bandwidth: {bandwidth:.2f} GB/s"
)
| {
"repo_id": "verl-project/verl",
"file_path": "verl/checkpoint_engine/mooncake_checkpoint_engine.py",
"license": "Apache License 2.0",
"lines": 241,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
verl-project/verl:tests/utils/test_bucketed_weight_transfer.py | # Copyright 2025 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for BucketedWeightSender and BucketedWeightReceiver.
Sender and receiver run in separate processes to match real-world usage
and because CUDA IPC requires distinct processes.
"""
import asyncio
import multiprocessing as mp
import uuid
import pytest
import torch
from verl.utils.device import get_device_name, get_torch_device, is_support_ipc
PROCESS_TIMEOUT = 60
# Use string checks to avoid initializing CUDA in the main pytest process,
# which would make subsequent fork-based multiprocessing in other tests unsafe.
HAS_ACCELERATOR = get_device_name() != "cpu"
HAS_CUDA = "cuda" in get_device_name()
def _unique_zmq_handle():
return f"ipc:///tmp/test-bwt-{uuid.uuid4().hex}.sock"
def _generate_weights(weight_specs, seed):
"""Deterministically generate weights on the best available device from specs.
Args:
weight_specs: list of (name, shape, dtype) tuples
seed: random seed for reproducibility
Returns:
list of (name, tensor_on_device) tuples
"""
device_name = get_device_name()
device = torch.device(f"{device_name}:0")
get_torch_device().manual_seed(seed)
weights = []
for name, shape, dtype in weight_specs:
# Generate in float32 then cast, since torch.randn doesn't support all dtypes
t = torch.randn(shape, dtype=torch.float32, device=device).to(dtype)
weights.append((name, t))
return weights
# ---------------------------------------------------------------------------
# Process entry points (must be module-level for pickling with spawn)
# ---------------------------------------------------------------------------
def _sender_fn(zmq_handle, weight_specs, seed, bucket_size_mb, use_shm):
"""Sender process: generate weights, move to device, send."""
from verl.workers.rollout.vllm_rollout.bucketed_weight_transfer import BucketedWeightSender
weights = _generate_weights(weight_specs, seed)
sender = BucketedWeightSender(
zmq_handle=zmq_handle,
bucket_size_mb=bucket_size_mb,
use_shm=use_shm,
)
asyncio.run(sender.async_send_weights(iter(weights)))
def _receiver_fn(zmq_handle, use_shm, result_queue):
"""Receiver process: receive weights, send back (name, dtype, shape, checksum)."""
from verl.utils.device import get_device_name
from verl.workers.rollout.vllm_rollout.bucketed_weight_transfer import BucketedWeightReceiver
device = torch.device(f"{get_device_name()}:0")
receiver = BucketedWeightReceiver(
zmq_handle=zmq_handle,
device=device,
use_shm=use_shm,
)
received = []
receiver.receive_weights(on_bucket_received=lambda w: received.extend(w))
# Only send lightweight metadata + checksum back through the queue
summaries = [(name, t.dtype, tuple(t.shape), t.float().sum().item()) for name, t in received]
result_queue.put(summaries)
# ---------------------------------------------------------------------------
# Test helper
# ---------------------------------------------------------------------------
def _transfer_and_validate(weight_specs, bucket_size_mb, use_shm):
"""Spawn sender + receiver processes, then validate received tensors."""
zmq_handle = _unique_zmq_handle()
seed = 42
ctx = mp.get_context("spawn")
result_queue = ctx.Queue()
sender_p = ctx.Process(
target=_sender_fn,
args=(zmq_handle, weight_specs, seed, bucket_size_mb, use_shm),
)
receiver_p = ctx.Process(
target=_receiver_fn,
args=(zmq_handle, use_shm, result_queue),
)
# Start sender first (it binds), then receiver (it connects)
sender_p.start()
receiver_p.start()
sender_p.join(timeout=PROCESS_TIMEOUT)
receiver_p.join(timeout=PROCESS_TIMEOUT)
assert sender_p.exitcode == 0, f"Sender process failed with exit code {sender_p.exitcode}"
assert receiver_p.exitcode == 0, f"Receiver process failed with exit code {receiver_p.exitcode}"
summaries = result_queue.get(timeout=5)
# Regenerate expected weights on device with the same seed
expected = _generate_weights(weight_specs, seed)
assert len(summaries) == len(expected), f"Expected {len(expected)} weights, got {len(summaries)}"
for (exp_name, exp_tensor), (recv_name, recv_dtype, recv_shape, recv_cksum) in zip(
expected, summaries, strict=False
):
assert exp_name == recv_name, f"Name mismatch: expected {exp_name}, got {recv_name}"
assert tuple(exp_tensor.shape) == recv_shape, (
f"Shape mismatch for {exp_name}: expected {tuple(exp_tensor.shape)}, got {recv_shape}"
)
assert exp_tensor.dtype == recv_dtype, (
f"Dtype mismatch for {exp_name}: expected {exp_tensor.dtype}, got {recv_dtype}"
)
exp_sum = exp_tensor.float().sum().item()
assert exp_sum == recv_cksum, f"Data mismatch for {exp_name}"
# ---------------------------------------------------------------------------
# Shared memory tests
# ---------------------------------------------------------------------------
@pytest.mark.skipif(not (HAS_ACCELERATOR and not HAS_CUDA), reason="Requires (shm only tested)")
class TestBucketedWeightTransferSHM:
"""Test BucketedWeightSender/Receiver via shared memory path."""
def test_single_small_weight(self):
specs = [("layer.weight", (32, 16), torch.float32)]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=True)
def test_multiple_weights_single_bucket(self):
specs = [
("layer0.weight", (16, 16), torch.float32),
("layer0.bias", (16,), torch.float32),
("layer1.weight", (16, 8), torch.bfloat16),
]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=True)
def test_multiple_buckets(self):
# ~64 KB each x 20 = ~1.25 MB, bucket = 1 MB => spans 2 buckets
specs = [(f"layer{i}.weight", (128, 128), torch.float32) for i in range(20)]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=True)
def test_mixed_dtypes(self):
specs = [
("fp32_param", (64, 64), torch.float32),
("bf16_param", (64, 64), torch.bfloat16),
("fp16_param", (32, 32), torch.float16),
]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=True)
def test_empty_weights(self):
_transfer_and_validate([], bucket_size_mb=1, use_shm=True)
# ---------------------------------------------------------------------------
# CUDA IPC tests (CUDA only — IPC is not supported on NPU)
# ---------------------------------------------------------------------------
@pytest.mark.skipif(not is_support_ipc(), reason="Requires IPC support")
class TestBucketedWeightTransferIPC:
"""Test BucketedWeightSender/Receiver via CUDA IPC path."""
def test_single_small_weight(self):
specs = [("layer.weight", (32, 16), torch.float32)]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=False)
def test_multiple_weights_single_bucket(self):
specs = [
("layer0.weight", (16, 16), torch.float32),
("layer0.bias", (16,), torch.float32),
("layer1.weight", (16, 8), torch.bfloat16),
]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=False)
def test_multiple_buckets(self):
specs = [(f"layer{i}.weight", (128, 128), torch.float32) for i in range(20)]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=False)
def test_mixed_dtypes(self):
specs = [
("fp32_param", (64, 64), torch.float32),
("bf16_param", (64, 64), torch.bfloat16),
("fp16_param", (32, 32), torch.float16),
]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=False)
def test_empty_weights(self):
_transfer_and_validate([], bucket_size_mb=1, use_shm=False)
def test_exact_bucket_boundary(self):
# 1 MB bucket = 1048576 bytes; float32 = 4 bytes => 262144 elements
numel = (1 << 20) // 4
specs = [("exact_fit", (numel,), torch.float32)]
_transfer_and_validate(specs, bucket_size_mb=1, use_shm=False)
| {
"repo_id": "verl-project/verl",
"file_path": "tests/utils/test_bucketed_weight_transfer.py",
"license": "Apache License 2.0",
"lines": 177,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
verl-project/verl:verl/workers/rollout/vllm_rollout/bucketed_weight_transfer.py | # Copyright 2025 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Bucketed weight transfer via ZMQ + IPC (or shared memory fallback).
Not recommended depending on vllm for this file.
"""
import gc
import logging
import os
from multiprocessing import shared_memory
from typing import Callable, TypedDict
import torch
import zmq
from torch.multiprocessing.reductions import reduce_tensor
from verl.utils.device import get_device_id, get_device_name, get_torch_device
logger = logging.getLogger(__file__)
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "INFO"))
class TensorMetadata(TypedDict):
name: str
shape: torch.Size
dtype: torch.dtype
offset: int
# copy from https://github.com/vllm-project/vllm/blob/main/examples/offline_inference/rlhf_utils.py
def rebuild_ipc(handle: tuple[Callable, tuple], device_id: int | None = None) -> torch.Tensor:
func, args = handle
list_args = list(args)
if device_id is not None:
# the key is to change device id to the current device id
# in case two processes have different CUDA_VISIBLE_DEVICES
list_args[6] = device_id
buffer = func(*list_args)
return buffer
def create_shared_memory(size: int, name: str):
"""Create shared memory for weight transfer. If already exists, attach to it."""
try:
shm = shared_memory.SharedMemory(name=name, create=True, size=size)
except FileExistsError:
shm = shared_memory.SharedMemory(name=name)
assert shm.size >= size, f"Stale shm segment '{name}': expected {size} bytes, got {shm.size}"
return shm
def rebuild_shared_memory(name: str, size: int, dtype=torch.uint8):
"""Rebuild tensor from shared memory."""
shm = shared_memory.SharedMemory(name=name)
tensor = torch.frombuffer(shm.buf[:size], dtype=dtype)
return tensor, shm
class BucketedWeightSender:
"""
Send model weights via bucketed IPC transfer over ZMQ.
Packs weight tensors into a fixed-size communication buffer and sends them
in buckets to the receiver. Supports CUDA IPC and shared memory fallback.
Args:
zmq_handle: ZMQ IPC socket path (e.g., "ipc:///tmp/rl-colocate-zmq-<uuid>.sock")
bucket_size_mb: Communication buffer size in MB
use_shm: Use shared memory instead of CUDA IPC (for NPU compatibility)
"""
def __init__(
self,
zmq_handle: str,
bucket_size_mb: int = 512,
use_shm: bool = False,
):
self.zmq_handle = zmq_handle
self.bucket_size_mb = bucket_size_mb
self.bucket_size = int(bucket_size_mb) << 20
self.use_shm = use_shm
self.zmq_context = zmq.Context.instance()
self.socket = None
self.buffer = None
self.shm = None
async def async_send_weights(self, weights):
"""
Send weights to the receiver. Accepts a sync generator or async iterator.
Args:
weights: Generator or async iterator yielding (name, tensor) pairs
"""
from verl.workers.rollout.utils import ensure_async_iterator
try:
self._init_socket()
self._init_buffer()
# send bucket weights
offset = 0
bucket_meta: dict[str, TensorMetadata] = {}
# dtype = PrecisionType.to_dtype(self.config.dtype)
async for name, weight in ensure_async_iterator(weights):
# model parameters are in fp32 full precision
# (vermouth1992) we should not force cast weight here because some parameters
# (such as moe gate) have to keep fp32 precision. If a weight is bf16 in the rollout side,
# the rollout should automatically cast on demand. However, this would incur a higher weight
# transfer volume.
# weight = weight.to(dtype, non_blocking=True)
# fill the tensor bucket
if offset + weight.nbytes > self.bucket_size:
get_torch_device().synchronize()
self.socket.send_pyobj({"bucket_meta": bucket_meta, "is_last": False})
self.socket.recv()
bucket_meta = {}
offset = 0
# TODO: slice embedding layer weight into chunks
assert offset + weight.nbytes <= self.bucket_size, (
f"Weight {name}({weight.shape}, {weight.dtype}) is too large to fit in the bucket."
f"Please increase rollout.update_weights_bucket_megabytes({self.bucket_size_mb} MB)."
)
bucket_meta[name] = {
"name": name,
"shape": weight.shape,
"dtype": weight.dtype,
"offset": offset,
}
self.buffer[offset : offset + weight.nbytes].copy_(weight.view(-1).view(torch.uint8), non_blocking=True)
offset += weight.nbytes
# send the last bucket
get_torch_device().synchronize()
self.socket.send_pyobj({"bucket_meta": bucket_meta, "is_last": True})
self.socket.recv()
finally:
self._cleanup()
def _init_socket(self):
"""Initialize ZMQ REQ socket and bind."""
self.socket = self.zmq_context.socket(zmq.REQ)
self.socket.bind(self.zmq_handle)
def _init_buffer(self):
"""build communication buffer"""
buffer, shm = None, None
if not self.use_shm:
buffer = torch.empty(self.bucket_size, dtype=torch.uint8, device=f"{get_device_name()}:{get_device_id()}")
handle = reduce_tensor(buffer)
self.socket.send_pyobj(handle)
else:
import uuid
# Create unique name for shared memory
shm_name = f"verl_weights_{uuid.uuid4().hex}"
shm = create_shared_memory(self.bucket_size, shm_name)
buffer = torch.frombuffer(shm.buf, dtype=torch.uint8)
comm_metadata = {"name": shm_name, "size": self.bucket_size}
self.socket.send_pyobj(comm_metadata)
self.socket.recv()
self.buffer = buffer
self.shm = shm
def _cleanup(self):
"""clean up"""
if self.socket is not None:
self.socket.close()
self.socket = None
del self.buffer
self.buffer = None
if self.shm is not None:
self.shm.close()
self.shm.unlink()
del self.shm
self.shm = None
gc.collect()
get_torch_device().ipc_collect()
get_torch_device().empty_cache()
class BucketedWeightReceiver:
"""
Receive model weights via bucketed IPC transfer over ZMQ.
Receives weight tensors from BucketedWeightSender and passes each
bucket to a callback for processing (e.g., loading into the model).
Args:
zmq_handle: ZMQ IPC socket path (must match sender)
device: Target device for received tensors
use_shm: Use shared memory instead of CUDA IPC
"""
def __init__(
self,
zmq_handle: str,
device: torch.device,
use_shm: bool = False,
):
self.zmq_handle = zmq_handle
self.device = device
self.use_shm = use_shm
self.zmq_context = zmq.Context.instance()
self.socket = None
self.buffer = None
self.shm = None
def receive_weights(self, on_bucket_received: callable):
"""
Receive weights from sender and process each bucket via callback.
Args:
on_bucket_received: Callback function(weights: list[(name, tensor)]) called per bucket.
"""
try:
self._init_socket()
self._init_buffer()
# receive bucket and update weights
while True:
metadata = self.socket.recv_pyobj()
weights, tensor = [], None
for name, meta in metadata["bucket_meta"].items():
shape, dtype, offset = meta["shape"], meta["dtype"], meta["offset"]
size = dtype.itemsize * shape.numel()
# NOTE: we need to clone the tensor to release CUDA IPC memory
# but for shared memory, it's not necessary and if we do clone,
# it will cause extra memory copy overhead and slow down the process.
tensor = self.buffer[offset : offset + size].view(dtype=dtype).view(shape)
if not self.use_shm:
tensor = tensor.clone()
else:
tensor = tensor.to(self.device)
weights.append((name, tensor))
get_torch_device().synchronize()
self.socket.send(b"")
on_bucket_received(weights)
del weights, tensor
if metadata["is_last"]:
break
finally:
self._cleanup()
def _init_socket(self):
"""Initialize ZMQ REP socket and connect."""
self.socket = self.zmq_context.socket(zmq.REP)
self.socket.connect(self.zmq_handle)
def _init_buffer(self):
"""Receive and rebuild communication buffer from sender."""
comm_metadata = self.socket.recv_pyobj()
buffer, shm = None, None
if not self.use_shm:
handle = comm_metadata
buffer = rebuild_ipc(handle, self.device.index)
assert buffer.dtype == torch.uint8
else:
shm_name = comm_metadata["name"]
shm_size = comm_metadata["size"]
buffer, shm = rebuild_shared_memory(shm_name, shm_size, dtype=torch.uint8)
self.socket.send(b"")
self.buffer = buffer
self.shm = shm
def _cleanup(self):
"""clean up"""
if self.socket is not None:
self.socket.close()
self.socket = None
# Synchronize before releasing the buffer to ensure all async ops
# referencing it (e.g. clone, .to()) have completed.
get_torch_device().synchronize()
del self.buffer
self.buffer = None
if self.shm is not None:
self.shm.close()
del self.shm
self.shm = None
gc.collect()
get_torch_device().ipc_collect()
get_torch_device().empty_cache()
| {
"repo_id": "verl-project/verl",
"file_path": "verl/workers/rollout/vllm_rollout/bucketed_weight_transfer.py",
"license": "Apache License 2.0",
"lines": 256,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
verl-project/verl:tests/utils/test_tokenizer_normalize_on_cpu.py | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import pytest
from verl.utils.tokenizer import normalize_token_ids
class DummyBatchEncoding:
def __init__(self, input_ids):
self.input_ids = input_ids
class DummyToList:
def __init__(self, data):
self._data = data
def tolist(self):
return self._data
@pytest.mark.parametrize(
("tokenized_output", "expected"),
[
# transformers v4-style direct token ids
([1, 2, 3], [1, 2, 3]),
((1, 2, 3), [1, 2, 3]),
# common list-like outputs with tolist()/ndarray paths
(DummyToList([1, 2, 3]), [1, 2, 3]),
(np.array([1, 2, 3], dtype=np.int64), [1, 2, 3]),
# transformers v5-like mapping / BatchEncoding-style outputs
({"input_ids": [1, 2, 3]}, [1, 2, 3]),
({"input_ids": DummyToList([1, 2, 3])}, [1, 2, 3]),
({"input_ids": [[1, 2, 3]]}, [1, 2, 3]),
(DummyBatchEncoding([1, 2, 3]), [1, 2, 3]),
(DummyBatchEncoding(DummyToList([[1, 2, 3]])), [1, 2, 3]),
# scalar item() support
([np.int64(1), np.int32(2), np.int16(3)], [1, 2, 3]),
],
)
def test_normalize_token_ids_valid_outputs(tokenized_output, expected):
assert normalize_token_ids(tokenized_output) == expected
@pytest.mark.parametrize(
"tokenized_output",
[
"not-token-ids",
{"attention_mask": [1, 1, 1]},
[[1, 2], [3, 4]], # ambiguous batched ids should fail fast
[1, object(), 3],
],
)
def test_normalize_token_ids_invalid_outputs(tokenized_output):
with pytest.raises(TypeError):
normalize_token_ids(tokenized_output)
| {
"repo_id": "verl-project/verl",
"file_path": "tests/utils/test_tokenizer_normalize_on_cpu.py",
"license": "Apache License 2.0",
"lines": 57,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
verl-project/verl:verl/checkpoint_engine/kimi_checkpoint_engine.py | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import concurrent.futures
import logging
import os
import time
import types
from collections import defaultdict
from dataclasses import dataclass
from typing import AsyncGenerator, Generator
import checkpoint_engine.distributed as dist
import ray
import torch
from checkpoint_engine.ps import H2DBucket, ParameterMeta, ParameterServer, _gen_h2d_buckets, _to_named_tensor
from verl.checkpoint_engine.base import CheckpointEngine, CheckpointEngineRegistry
from verl.utils.device import get_nccl_backend, get_torch_device
from verl.utils.net_utils import get_free_port
logger = logging.getLogger(__name__)
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
def ckpt_get_named_tensor_buckets(
iterable: Generator[tuple[str, torch.Tensor], None, None],
bucket_bytes: int,
world_size: int,
rank_id: int,
rollout_dtype: torch.dtype = torch.bfloat16,
) -> dict[str, torch.Tensor]:
if bucket_bytes <= 0:
raise ValueError(f"bucket_bytes must be greater than 0, got {bucket_bytes}")
current_bucket = {}
current_size = 0
for tensor_idx, (name, tensor) in enumerate(iterable):
tensor = tensor.to(rollout_dtype)
if tensor_idx % world_size == rank_id:
tensor_size = tensor.element_size() * tensor.numel()
if current_size + tensor_size > bucket_bytes:
if current_bucket:
yield current_bucket
current_bucket = {}
current_size = 0
current_bucket[name] = tensor
current_size += tensor_size
if current_bucket:
yield current_bucket
async def receive_tensor(
self,
checkpoint_name: str,
ranks_group: int,
ranks: list[int] | None = None,
bucket_size: int = 2 << 30,
disable_h2d_buffer: bool = False,
) -> AsyncGenerator[tuple[str, torch.Tensor], None]:
assert len(self._current_global_parameter_metas) != 0, "parameter metas is empty"
assert dist.is_initialized(), "process group is not initialized"
assert self._p2p_store is not None, "p2p store is not initialized"
assert ranks, "ranks should be set"
# first execute a barrier to avoid subsequent device oom
dist.barrier(group=ranks_group)
buckets = _gen_h2d_buckets(
self._current_global_parameter_metas,
bucket_size,
self._local_rdma_devices,
self._remote_rdma_devices,
ranks,
)
h2d_buffer: torch.Tensor | None = (
None
if disable_h2d_buffer
else torch.empty(bucket_size, dtype=torch.uint8, device=self.device_manager.device_type)
)
# p2p store need to register h2d_buffer to let other ranks read
if ranks:
h2d_buffer_name = "__h2d_buffer__"
if h2d_buffer is not None and self._p2p_store is not None:
self._p2p_store.register_named_tensors({h2d_buffer_name: h2d_buffer})
receiver_rank_buckets: list[tuple[int, H2DBucket]] = []
for receiver_rank, owner_rank, bucket in buckets:
if receiver_rank != self._rank:
continue
receiver_rank_buckets.append((owner_rank, bucket))
buffer = torch.empty(bucket_size * 2, dtype=torch.uint8, device=self.device_manager.device_type)
buckets_by_receiver_rank: dict[int, list[H2DBucket]] = defaultdict(list)
max_len = 0
for receiver_rank, _, bucket in buckets:
buckets_by_receiver_rank[receiver_rank].append(bucket)
if len(buckets_by_receiver_rank[receiver_rank]) > max_len:
max_len = len(buckets_by_receiver_rank[receiver_rank])
gidx = 0
metadata: list[ParameterMeta]
try:
for i in range(max_len):
if i < len(receiver_rank_buckets) and not disable_h2d_buffer:
self._copy_to_buffer(
checkpoint_name,
receiver_rank_buckets[i][1],
h2d_buffer,
receiver_rank_buckets[i][0] if ranks else None,
)
for receiver_rank, _buckets in buckets_by_receiver_rank.items():
if i >= len(_buckets):
continue
bucket = _buckets[i]
start = gidx % 2 * bucket_size
buffer_b: torch.Tensor = buffer[start : start + bucket.size]
if receiver_rank == self._rank:
if disable_h2d_buffer:
self._copy_to_buffer(checkpoint_name, bucket, buffer_b)
else:
buffer_b.data.copy_(h2d_buffer[: bucket.size])
broadcast_op = BroadcastOperation(
rank=receiver_rank,
ranks_group=ranks_group,
bucket=buffer_b,
metadata=bucket.items,
)
if gidx == 0:
metadata = await broadcast_op.wait_for_complete()
gidx += 1
continue
meta_list = _to_named_tensor(metadata, (gidx - 1) % 2 * bucket_size)
for item in meta_list:
shape = item["shape"]
if isinstance(shape, list | tuple):
shape = torch.Size(shape)
assert isinstance(shape, torch.Size)
dtype, offset = item["dtype"], item["offset"]
size = dtype.itemsize * shape.numel()
tensor = buffer[offset : offset + size].view(dtype=dtype).view(shape)
yield item["name"], tensor
metadata = await broadcast_op.wait_for_complete()
self.device_manager.device_module.synchronize()
gidx += 1
meta_list = _to_named_tensor(metadata, (gidx - 1) % 2 * bucket_size)
for item in meta_list:
shape = item["shape"]
if isinstance(shape, list | tuple):
shape = torch.Size(shape)
assert isinstance(shape, torch.Size)
dtype, offset = item["dtype"], item["offset"]
size = dtype.itemsize * shape.numel()
tensor = buffer[offset : offset + size].view(dtype=dtype).view(shape)
yield item["name"], tensor
finally:
dist.barrier(group=ranks_group)
if ranks and h2d_buffer is not None:
self._p2p_store.unregister_named_tensors([h2d_buffer_name])
self.device_manager.device_module.empty_cache()
@dataclass
class MasterMetadata:
zmq_ip: str
zmq_port: int
dist_ip: str
dist_port: int
class BroadcastOperation:
"""Async broadcast operation in separate thread.
Args:
rank (int): The rank of the current process.
ranks_group (int): The process group's value.
bucket (torch.Tensor): The tensor to broadcast.
metadata (list[ParameterMeta]): The metadata of the tensor.
"""
def __init__(
self,
rank: int,
ranks_group: int,
bucket: torch.Tensor,
metadata: list[ParameterMeta],
) -> None:
self.rank = rank
self.ranks_group = ranks_group
self.bucket = bucket
self.metadata = metadata
loop = asyncio.get_running_loop()
self._task = loop.run_in_executor(None, self._run)
def _run(self):
# broadcast tensor
dist.broadcast(self.bucket, src=self.rank, group=self.ranks_group)
async def wait_for_complete(self) -> list[ParameterMeta]:
"""Wait for the broadcast operation to complete.
Returns:
list[ParameterMeta]: The bucket meta after broadcast.
"""
await self._task
return self.metadata
@CheckpointEngineRegistry.register("kimi_ckpt_engine")
class KIMICheckpointEngine(CheckpointEngine):
"""kimi checkpoint engine with collective communication.
Args:
bucket_size (int): Bucket size in bytes to transfer multiple weights at one time. Note that we use
two buffer to send and recv weights at same time, so the device memory overhead is 2 * bucket_size.
rebuild_group (bool): Whether to rebuild the process group in each update. Defaults to False.
is_master (bool): Whether the current process is the master process. Defaults to False.
rollout_dtype (torch.dtype): The dtype of the weights received from rollout workers. Defaults to torch.bfloat16.
"""
def __init__(
self,
bucket_size: int,
rebuild_group: bool = False,
is_master: bool = False,
rollout_dtype: torch.dtype = torch.bfloat16,
) -> None:
self.bucket_size = bucket_size
self.rebuild_group = rebuild_group
self.rollout_dtype = rollout_dtype
self.is_master = is_master
self.initialized = False
self.checkpoint_name = "kimi_checkpoint_engine"
def prepare(self) -> MasterMetadata:
if self.is_master:
self.ip = ray.util.get_node_ip_address().strip("[]")
self.listen_port, _ = get_free_port(self.ip)
return (
MasterMetadata(zmq_ip=None, zmq_port=None, dist_ip=self.ip, dist_port=self.listen_port)
if self.is_master
else None
)
def finalize(self):
"""Destroy the ckpt engine process group if rebuild_group is True."""
if self.rebuild_group:
dist.destroy_process_group()
self.rank = None
self.world_size = None
self.initialized = False
@classmethod
def build_topology(cls, trainer_world_size: int, rollout_world_size: int, metadata: list[dict]):
trainer_kwargs = {
"method": ["init_process_group"] * trainer_world_size,
"rank": list(range(0, trainer_world_size)),
"trainer_world_size": [trainer_world_size] * trainer_world_size,
"rollout_world_size": [rollout_world_size] * trainer_world_size,
"master_metadata": [metadata[0]] * trainer_world_size,
}
rollout_kwargs = {
"method": ["init_process_group"] * rollout_world_size,
"rank": list(range(trainer_world_size, trainer_world_size + rollout_world_size)),
"trainer_world_size": [trainer_world_size] * rollout_world_size,
"rollout_world_size": [rollout_world_size] * rollout_world_size,
"master_metadata": [metadata[0]] * rollout_world_size,
}
return trainer_kwargs, rollout_kwargs
def init_process_group(
self,
rank: int,
trainer_world_size: int,
rollout_world_size: int,
master_metadata: MasterMetadata,
):
"""Initialize the ckpt engine process group.
Args:
rank (int): The rank of the current process.
world_size (int): The total number of processes.
"""
self.rank = rank
self.trainer_world_size = trainer_world_size
self.rollout_world_size = rollout_world_size
self.world_size = trainer_world_size + rollout_world_size
if not self.initialized:
self.parameter_server = ParameterServer(
rank=rank,
world_size=self.world_size,
auto_pg=False,
master_addr=master_metadata.dist_ip,
master_port=master_metadata.dist_port,
)
self.parameter_server.receive_tensor = types.MethodType(receive_tensor, self.parameter_server)
dist.use_backend(f"vllm_{get_nccl_backend()}")
self.parameter_server.init_process_group()
self.rollout_ranks = list(range(self.trainer_world_size, self.world_size))
self.rollout_group = dist.new_group(self.rollout_ranks)
self.initialized = True
@torch.no_grad()
async def send_weights(self, weights: Generator[tuple[str, torch.Tensor], None, None]):
"""Send the weights of the model.
Args:
weights: A generator that yields the name of the weight tensor and the tensor itself.
"""
def offload_cpu(name: str, tensor: torch.Tensor) -> tuple[str, torch.Tensor]:
return name, tensor.to("cpu", non_blocking=True)
start_time = time.time()
named_tensors = {}
for named_tensors_gpu in ckpt_get_named_tensor_buckets(
weights, self.bucket_size, self.trainer_world_size, self.rank, self.rollout_dtype
):
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
futures = [
executor.submit(
offload_cpu,
name,
tensor,
)
for name, tensor in named_tensors_gpu.items()
]
for future in concurrent.futures.as_completed(futures):
name, tensor_cpu = future.result()
named_tensors[name] = tensor_cpu
get_torch_device().synchronize()
self.parameter_server.register_checkpoint(self.checkpoint_name, named_tensors=named_tensors)
named_tensors = {}
get_torch_device().empty_cache()
logger.info(f"Rank {self.rank} offload and register, time cost: {time.time() - start_time:.2f}s")
self.parameter_server.gather_metas(self.checkpoint_name)
dist.barrier()
self.parameter_server.unregister_checkpoint(self.checkpoint_name)
logger.info(f"Rank {self.rank} send weights done, time cost: {time.time() - start_time:.2f}s")
@torch.no_grad()
async def receive_weights(self) -> AsyncGenerator[tuple[str, torch.Tensor], None]:
"""Receive the weights of the model.
Yields:
A tuple of the name of the weight tensor and the tensor itself.
"""
self.parameter_server.gather_metas(self.checkpoint_name)
start_time = time.time()
total_bytes, total_params = 0, 0
async for name, tensor in self.parameter_server.receive_tensor(
self.checkpoint_name, self.rollout_group, self.rollout_ranks, self.bucket_size
):
total_bytes += tensor.element_size() * tensor.nelement()
total_params += 1
yield name, tensor
dist.barrier()
time_cost = time.time() - start_time
bandwidth = total_bytes / time_cost / (1024 * 1024 * 1024)
logger.info(
f"Rank {self.rank} receive weights done, total_params: {total_params}, "
f"time cost: {time_cost:.2f}s, bandwidth: {bandwidth:.2f} GB/s"
)
| {
"repo_id": "verl-project/verl",
"file_path": "verl/checkpoint_engine/kimi_checkpoint_engine.py",
"license": "Apache License 2.0",
"lines": 337,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
verl-project/verl:verl/workers/engine/torchtitan/transformer_impl.py | # Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The concrete Engine implementation using PyTorch TorchTitan parallelism (FSDP2 + TP + PP)
"""
import gc
import importlib
import logging
import os
import re
from contextlib import nullcontext
from typing import Any, Callable, Optional
import torch
import torch.distributed
from tensordict import TensorDict
from torch.distributed.checkpoint.state_dict import get_model_state_dict
from torch.distributed.tensor import DTensor
from torchtitan.components.checkpoint import CheckpointManager
from torchtitan.components.lr_scheduler import LRSchedulersContainer
from torchtitan.components.optimizer import OptimizersContainer
from torchtitan.config import CompileConfig, ParallelismConfig, TrainingConfig
from torchtitan.distributed import utils as dist_utils
from torchtitan.distributed.context_parallel import prepare_context_parallel_input
from torchtitan.distributed.parallel_dims import ParallelDims
from torchtitan.train import Trainer
import verl.utils.torch_functional as verl_F
from verl.trainer.config import CheckpointConfig
from verl.utils import tensordict_utils as tu
from verl.utils.dataset.dataset_utils import DatasetPadMode
from verl.utils.debug import log_gpu_memory_usage
from verl.utils.device import get_device_id, get_device_name
from verl.utils.fsdp_utils import (
load_fsdp_model_to_gpu,
load_fsdp_optimizer,
offload_fsdp_model_to_cpu,
offload_fsdp_optimizer,
)
from verl.utils.model import extract_multi_modal_inputs
from verl.utils.torch_functional import logprobs_from_logits
from verl.workers.config import HFModelConfig, TorchtitanEngineConfig, TorchtitanOptimizerConfig
from verl.workers.engine.torchtitan.utils import (
NoOpDataLoader,
derive_torchtitan_name_and_flavor,
enable_fsdp_gradient_division,
get_attention_masks,
iter_per_tensor_params_ep,
)
from ..base import BaseEngine, BaseEngineCtx, EngineRegistry
from ..utils import enable_full_determinism, postprocess_batch_func, prepare_micro_batches
logger = logging.getLogger(__file__)
logger.setLevel(os.getenv("VERL_LOGGING_LEVEL", "WARN"))
device_name = get_device_name()
class TorchTitanEngine(BaseEngine):
"""
Concrete Engine implementation using PyTorch TorchTitan parallelism.
Supports model sharding with FSDP2, tensor parallelism, activation/optimizer offloading,
LoRA, and sequence parallelism following the TorchTitan design.
"""
def __init__(
self,
model_config: HFModelConfig,
engine_config: TorchtitanEngineConfig,
optimizer_config: TorchtitanOptimizerConfig,
checkpoint_config: CheckpointConfig,
):
"""
Initialize the TorchTitanEngine.
Sets up distributed device meshes for tensor and data parallelism, LoRA, and offload policies.
Args:
model_config: Configuration for HuggingFace model.
engine_config: Configuration for FSDP/TorchTitan engine (uses FSDP2).
optimizer_config: Configuration for optimizer.
checkpoint_config: Configuration for checkpointing.
"""
super().__init__()
self.model_config = model_config
self.engine_config = engine_config
self.optimizer_config = optimizer_config
self.checkpoint_config = checkpoint_config
# Derive torchtitan model name and flavor from HF config
torchtitan_name, torchtitan_flavor = derive_torchtitan_name_and_flavor(self.model_config.hf_config)
# Get ModelSpec from model registry
model_module = importlib.import_module(f"torchtitan.models.{torchtitan_name}")
model_spec = model_module.model_registry(torchtitan_flavor)
# Override attn_backend on the model config if needed
attn_type = self.engine_config.attn_type
if hasattr(model_spec.model, "layer") and hasattr(model_spec.model.layer, "attention"):
model_spec.model.layer.attention.attn_backend = attn_type
optimizer = OptimizersContainer.Config(
name=self.optimizer_config.name,
lr=self.optimizer_config.lr,
eps=self.optimizer_config.eps,
beta1=self.optimizer_config.betas[0],
beta2=self.optimizer_config.betas[1],
weight_decay=self.optimizer_config.weight_decay,
)
total_steps = self.optimizer_config.total_training_steps
lr_warmup_steps = self.optimizer_config.lr_warmup_steps
if lr_warmup_steps is None or lr_warmup_steps <= 0:
lr_warmup_steps = int(self.optimizer_config.lr_warmup_steps_ratio * total_steps)
lr_scheduler = LRSchedulersContainer.Config(
warmup_steps=lr_warmup_steps,
decay_type=self.optimizer_config.decay_type,
min_lr_factor=self.optimizer_config.min_lr_factor,
)
parallelism = ParallelismConfig(
data_parallel_replicate_degree=self.engine_config.data_parallel_replicate_size,
data_parallel_shard_degree=self.engine_config.data_parallel_shard_size,
fsdp_reshard_after_forward=self.engine_config.reshard_after_forward,
tensor_parallel_degree=self.engine_config.tensor_parallel_size,
pipeline_parallel_degree=self.engine_config.pipeline_parallel_size,
context_parallel_degree=self.engine_config.context_parallel_size,
expert_parallel_degree=self.engine_config.expert_parallel_size,
expert_tensor_parallel_degree=self.engine_config.expert_tensor_parallel_size,
)
checkpoint = CheckpointManager.Config(
enable=True,
initial_load_in_hf=True,
initial_load_model_only=True,
initial_load_path=model_config.path,
)
compile_config = CompileConfig(enable=self.engine_config.use_torch_compile)
training_kwargs = {}
if self.engine_config.max_seq_len is not None:
training_kwargs["seq_len"] = self.engine_config.max_seq_len
if self.engine_config.offload_policy or self.engine_config.forward_only:
training = TrainingConfig(enable_cpu_offload=True, **training_kwargs)
else:
training = TrainingConfig(**training_kwargs)
# Construct Torchtitan's Trainer.Config
self.config = Trainer.Config(
model_spec=model_spec,
hf_assets_path=self.model_config.path,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
parallelism=parallelism,
checkpoint=checkpoint,
compile=compile_config,
training=training,
# Use a no-op dataloader since verl has its own data loading
dataloader=NoOpDataLoader.Config(),
)
self.trainer = Trainer(self.config)
self._init_device_mesh()
# Re-enable FSDP's gradient division for verl's loss scaling.
# TorchTitan disables gradient division by default (for global token normalization),
# but verl's loss function multiplies by dp_size to compensate for gradient averaging.
if self.engine_config.data_parallel_shard_size > 1:
dp_size = self.get_data_parallel_size()
for model_part in self.trainer.model_parts:
enable_fsdp_gradient_division(model_part, dp_size)
if self.engine_config.full_determinism:
enable_full_determinism(seed=self.engine_config.seed)
# set FSDP offload params
self._is_offload_param = self.engine_config.param_offload
self._is_offload_optimizer = self.engine_config.optimizer_offload
if self.engine_config.entropy_from_logits_with_chunking:
entropy_from_logits = verl_F.entropy_from_logits_with_chunking
else:
entropy_from_logits = verl_F.entropy_from_logits
self.compute_entropy_from_logits = (
torch.compile(entropy_from_logits, dynamic=True)
if self.engine_config.use_torch_compile
else entropy_from_logits
)
@property
def is_param_offload_enabled(self) -> bool:
return self._is_offload_param
@property
def is_optimizer_offload_enabled(self) -> bool:
return self._is_offload_optimizer
def is_mp_src_rank_with_outputs(self):
"""
Whether the current rank is the first rank in model parallel group that contains model outputs
"""
is_collect = True
# TP: outputs are on TP rank 0
if self.parallel_dims.tp > 1:
tp_mesh = self.parallel_dims.get_optional_mesh("tp")
is_collect = is_collect and (tp_mesh.get_local_rank() == 0)
# PP: outputs are on the last PP rank
if self.parallel_dims.pp > 1:
pp_mesh = self.parallel_dims.get_optional_mesh("pp")
is_collect = is_collect and (pp_mesh.get_local_rank() == self.parallel_dims.pp - 1)
# CP: outputs are on CP rank 0
if self.parallel_dims.cp > 1:
cp_mesh = self.parallel_dims.get_optional_mesh("cp")
is_collect = is_collect and (cp_mesh.get_local_rank() == 0)
return is_collect
def initialize(self):
"""
Build the model, optimizer, and learning rate scheduler with TorchTitan parallelism.
Applies device, dtype, and precision configurations, including mixed precision.
Sets up checkpoint manager.
"""
self.module = self.trainer.model_parts
self.checkpointer = self.trainer.checkpointer
# load initial HF weights
self.checkpointer.load()
if not self.engine_config.forward_only:
self.optimizer = self.trainer.optimizers
self.lr_scheduler = self.trainer.lr_schedulers
else:
self.optimizer = None
self.lr_scheduler = None
self.to(
device="cpu",
model=self._is_offload_param,
optimizer=self._is_offload_optimizer,
grad=self._is_offload_param,
)
log_gpu_memory_usage("After offload model/optimizer/grad during init", logger=logger)
def _init_device_mesh(self):
"""Initialize the device mesh for TorchTitan style parallelism."""
world_size = torch.distributed.get_world_size()
self.parallel_dims = ParallelDims(
dp_shard=self.engine_config.data_parallel_shard_size,
dp_replicate=self.engine_config.data_parallel_replicate_size,
cp=self.engine_config.context_parallel_size,
tp=self.engine_config.tensor_parallel_size,
pp=self.engine_config.pipeline_parallel_size,
ep=self.engine_config.expert_parallel_size,
etp=self.engine_config.expert_tensor_parallel_size,
world_size=world_size,
)
self.device_mesh = self.parallel_dims.build_mesh()
def train_mode(self, **kwargs):
"""Return a context manager for training mode."""
return EngineTrainModeCtx(self, **kwargs)
def eval_mode(self, **kwargs):
"""Return a context manager for evaluation mode."""
return EngineEvalModeCtx(self, **kwargs)
def get_data_parallel_rank(self):
mesh = self._get_data_parallel_mesh()
return 0 if mesh is None else mesh.get_local_rank()
def get_data_parallel_size(self):
return self.engine_config.data_parallel_shard_size * self.engine_config.data_parallel_replicate_size
def get_data_parallel_group(self):
mesh = self._get_data_parallel_mesh()
if mesh is not None:
return mesh.get_group()
# If world_size == dp_size (e.g. single GPU, or all ranks are DP),
# return WORLD so that collective ops in _postprocess_output
# (allgather_dict_into_dict, all_reduce) still run and produce the
# correct metric aggregation format.
if torch.distributed.get_world_size() == self.get_data_parallel_size():
return torch.distributed.group.WORLD
return None
def _get_data_parallel_mesh(self):
"""Get the data parallel mesh, handling hybrid/fully/replicate shard modes."""
mesh = self.parallel_dims.get_optional_mesh(["dp_replicate", "fsdp"])
if mesh is None:
mesh = self.parallel_dims.get_optional_mesh("fsdp")
if mesh is None:
mesh = self.parallel_dims.get_optional_mesh("dp_replicate")
return mesh
def forward_backward_batch(self, data: TensorDict, loss_function: Callable, forward_only=False):
"""Perform forward and optionally backward pass on a batch."""
tu.assign_non_tensor(data, sp_size=self.engine_config.tensor_parallel_size)
# Compute num_tokens in global batch for loss normalization
batch_num_tokens = data["loss_mask"].sum().to(get_device_id())
dp_group = self.get_data_parallel_group()
if dp_group is not None:
torch.distributed.all_reduce(batch_num_tokens, op=torch.distributed.ReduceOp.SUM, group=dp_group)
tu.assign_non_tensor(data, batch_num_tokens=batch_num_tokens.item())
tu.assign_non_tensor(data, dp_size=self.get_data_parallel_size())
micro_batches, indices = prepare_micro_batches(
data=data,
dp_group=self.get_data_parallel_group(),
same_micro_num_in_dp=True,
)
output_lst = []
ctx = torch.no_grad() if forward_only else nullcontext()
for micro_batch in micro_batches:
with ctx:
loss, output = self.forward_step(micro_batch, loss_function=loss_function, forward_only=forward_only)
if not forward_only:
loss.backward()
output_lst.append(output)
return postprocess_batch_func(output_lst=output_lst, indices=indices, data=data)
def model_forward_step(
self,
*,
inputs: torch.Tensor,
extra_inputs: dict[str, torch.Tensor] | None = None,
extra_kwargs: dict[str, torch.Tensor] | None = None,
) -> torch.Tensor:
"""
Perform a forward pass through the trainer model without backward.
"""
model_parts = self.module
parallel_dims = self.parallel_dims
if parallel_dims.pp_enabled:
raise NotImplementedError(
"Pipeline parallelism is not yet supported in model_forward_step. "
"This will be implemented in a follow-up PR."
)
else:
# Non-PP forward
assert len(model_parts) == 1
with self.trainer.train_context():
with self.trainer.maybe_enable_amp:
pred = model_parts[0](inputs, **extra_inputs, **extra_kwargs)
if isinstance(pred, DTensor):
pred = pred.full_tensor()
return pred
def forward_step(self, micro_batch: TensorDict, loss_function, forward_only):
raise NotImplementedError("forward_step must be implemented in subclass")
def optimizer_zero_grad(self):
"""Zero gradients."""
self.optimizer.zero_grad()
def optimizer_step(self):
"""Perform optimizer step with gradient clipping."""
grad_norm = dist_utils.clip_grad_norm_(
[p for m in self.module for p in m.parameters()],
self.config.training.max_norm,
foreach=True,
pp_mesh=self.parallel_dims.get_optional_mesh("pp"),
ep_enabled=self.parallel_dims.ep_enabled,
)
# if grad_norm is not finite, skip the update
if not torch.isfinite(grad_norm):
logger.warning(f"grad_norm is not finite: {grad_norm}")
self.optimizer.zero_grad()
else:
self.optimizer.step()
return grad_norm.item()
def lr_scheduler_step(self):
"""Advance learning rate scheduler."""
self.lr_scheduler.step()
lr = self.lr_scheduler.schedulers[0].get_last_lr()[0]
return lr
def to(self, device: str, model: bool = True, optimizer: bool = True, grad: bool = True):
"""Move model and/or optimizer to CPU or GPU."""
super().to(device=device, model=model, optimizer=optimizer, grad=grad)
if self.engine_config.forward_only:
return
device_name = get_device_name()
assert device in (device_name, "cpu")
if device == device_name:
if model:
for module in self.module:
load_fsdp_model_to_gpu(module)
if optimizer and self.optimizer is not None:
load_fsdp_optimizer(self.optimizer, device)
gc.collect()
elif device == "cpu":
if model:
for module in self.module:
offload_fsdp_model_to_cpu(module)
if optimizer and self.optimizer is not None:
offload_fsdp_optimizer(self.optimizer)
else:
raise ValueError(f"Invalid device type: {device}")
def save_checkpoint(
self,
local_path: str,
hdfs_path: Optional[str] = None,
global_step: int = 0,
max_ckpt_to_keep: Optional[int] = None,
**kwargs,
) -> None:
"""Save checkpoint."""
if self._is_offload_param:
for module in self.module:
load_fsdp_model_to_gpu(module)
# Override TorchTitan's folder to use verl's path
parent_dir = os.path.dirname(local_path)
self.checkpointer.folder = parent_dir
if max_ckpt_to_keep is not None:
self.checkpointer.keep_latest_k = max_ckpt_to_keep
self.checkpointer.save(curr_step=global_step)
torch.distributed.barrier()
if self._is_offload_param:
for module in self.module:
offload_fsdp_model_to_cpu(module)
def load_checkpoint(
self, local_path: str, hdfs_path: Optional[str] = None, del_local_after_load: int = True, **kwargs
) -> None:
"""Load checkpoint."""
if self._is_offload_param:
for module in self.module:
load_fsdp_model_to_gpu(module)
# Override TorchTitan's folder to use verl's path
parent_dir = os.path.dirname(local_path)
self.checkpointer.folder = parent_dir
# Extract step number from path (verl uses global_step_N format)
match = re.search(r"global_step_(\d+)", local_path)
if match:
step = int(match.group(1))
self.checkpointer.load(step=step)
else:
# Fallback to latest
self.checkpointer.load(step=-1)
torch.distributed.barrier()
if self._is_offload_param:
for module in self.module:
offload_fsdp_model_to_cpu(module)
if self._is_offload_optimizer:
offload_fsdp_optimizer(self.optimizer)
def get_per_tensor_param(self, **kwargs):
for module in self.module:
load_fsdp_model_to_gpu(module)
# Collect state dicts from all model parts
params = {}
for module in self.module:
module_params = get_model_state_dict(module)
params.update(module_params)
if self._is_offload_param:
for module in self.module:
offload_fsdp_model_to_cpu(module)
# Convert TorchTitan key names to HuggingFace key names (expected by vLLM)
sd_adapter = self.checkpointer.sd_adapter
if sd_adapter is not None:
params = sd_adapter.to_hf(params)
# When weight tying is enabled, the sd_adapter skips lm_head.weight during
# to_hf() conversion (since it's the same tensor as embed_tokens.weight in
# the torchtitan model). But vLLM needs lm_head.weight explicitly, so we
# add it back as a reference to embed_tokens.weight.
if "model.embed_tokens.weight" in params and "lm_head.weight" not in params:
params["lm_head.weight"] = params["model.embed_tokens.weight"]
device = get_device_id() # used when fsdp2 set cpu_offload_policy
# When Expert Parallel (EP) is used, sd_adapter.to_hf() only produces
# individual expert weights for the locally-owned experts (e.g., 16 out of
# 128 with EP=8). vLLM needs ALL experts. We gather the missing experts
# by all-gathering each expert weight across the EP process group.
if self.parallel_dims.ep_enabled:
ep_mesh = self.parallel_dims.get_optional_mesh("ep")
ep_group = ep_mesh.get_group()
ep_size = self.parallel_dims.ep
per_tensor_param = iter_per_tensor_params_ep(params, device, ep_group, ep_size)
else:
# TODO: cast fp32 to bf16 to reduce weight sync overhead, need more fine-grained control, e.g MoE gate
per_tensor_param = (
(
name,
param.to(device, non_blocking=True).full_tensor().to(torch.bfloat16, non_blocking=True)
if isinstance(param, DTensor)
else param,
)
for name, param in params.items()
)
# TODO: support Torchtitan PEFT
return per_tensor_param, None
class EngineEvalModeCtx(BaseEngineCtx):
def __init__(self, engine: TorchTitanEngine, **kwargs):
super().__init__(engine=engine, mode="eval", **kwargs)
def __enter__(self):
assert isinstance(self.engine, TorchTitanEngine)
super().__enter__()
for module in self.engine.module:
module.eval()
def __exit__(self, exc_type, exc_value, traceback):
assert isinstance(self.engine, TorchTitanEngine)
# Reshard the root FSDP module
if self.engine.engine_config.data_parallel_shard_size > 1:
for module in self.engine.module:
module.reshard()
super().__exit__(exc_type, exc_value, traceback)
class EngineTrainModeCtx(BaseEngineCtx):
def __init__(self, engine: TorchTitanEngine, **kwargs):
super().__init__(engine=engine, mode="train", **kwargs)
def __enter__(self):
assert isinstance(self.engine, TorchTitanEngine)
super().__enter__()
for module in self.engine.module:
module.train()
def __exit__(self, exc_type, exc_value, traceback):
assert isinstance(self.engine, TorchTitanEngine)
self.engine.optimizer_zero_grad()
super().__exit__(exc_type, exc_value, traceback)
@EngineRegistry.register(model_type="language_model", backend=["torchtitan"], device=["cuda", "npu"])
class TorchTitanEngineWithLMHead(TorchTitanEngine):
"""TorchTitan engine implementation for language models with LM head."""
def prepare_model_inputs(self, micro_batch: TensorDict):
use_remove_padding = tu.get_non_tensor_data(data=micro_batch, key="use_remove_padding", default=True)
pad_mode = tu.get_non_tensor_data(data=micro_batch, key="pad_mode", default=DatasetPadMode.NO_PADDING)
assert pad_mode == DatasetPadMode.NO_PADDING, f"pad_mode {pad_mode} not supported"
multi_modal_inputs = extract_multi_modal_inputs(micro_batch.get("multi_modal_inputs", []))
input_ids = micro_batch["input_ids"]
position_ids = micro_batch["position_ids"]
output_args = {}
if use_remove_padding:
input_ids = input_ids.values().unsqueeze(0)
if position_ids.dim() == 3:
position_ids = position_ids.values().unsqueeze(1)
else:
position_ids = position_ids.values().unsqueeze(0)
labels = torch.roll(input_ids, shifts=-1, dims=1)
attn_type = self.trainer.model_config.layer.attention.attn_backend
attention_mask = get_attention_masks(
input_batch=input_ids,
positions=position_ids,
attn_type=attn_type,
)
else:
loss_mask = micro_batch["loss_mask"]
pad_token_id = tu.get_non_tensor_data(data=micro_batch, key="pad_token_id", default=0)
batch_size = micro_batch.batch_size[0]
max_seq_len = max(input_ids.offsets().diff())
labels = torch.roll(input_ids.values(), shifts=-1, dims=0)
input_ids = torch.nested.to_padded_tensor(
input_ids, padding=pad_token_id, output_size=(batch_size, max_seq_len)
)
if position_ids.dim() == 3:
position_ids = torch.nested.to_padded_tensor(
position_ids, padding=0, output_size=(batch_size, 4, max_seq_len)
).transpose(0, 1)
else:
position_ids = torch.nested.to_padded_tensor(
position_ids, padding=0, output_size=(batch_size, max_seq_len)
)
attention_mask_list = [torch.ones_like(t, dtype=torch.int32) for t in loss_mask]
attention_mask = torch.nested.as_nested_tensor(attention_mask_list, layout=torch.jagged)
attention_mask = torch.nested.to_padded_tensor(
attention_mask, padding=0, output_size=(batch_size, max_seq_len)
)
extra_inputs = {
"positions": position_ids,
}
# For arguments, like attention_masks, we have to put them in a separate
# dict as extra_inputs are not forwarded to other stages in PP, but
# extra_kwargs are.
extra_kwargs: dict[str, Any] = {"attention_masks": attention_mask}
if self.parallel_dims.cp_enabled:
input_ids, labels, extra_kwargs = prepare_context_parallel_input(
input_ids,
labels,
extra_kwargs,
self.parallel_dims.get_mesh("cp"),
self.trainer.device,
self.trainer.config.parallelism.context_parallel_load_balancer,
)
# TODO(jessicazhong): multimodal is not yet supported for Torchtitan engine
extra_inputs.update(multi_modal_inputs)
output_args["labels"] = labels
return input_ids, extra_inputs, extra_kwargs, output_args
def prepare_model_outputs(self, logits, output_args, micro_batch: TensorDict):
use_remove_padding = tu.get_non_tensor_data(data=micro_batch, key="use_remove_padding", default=True)
pad_mode = tu.get_non_tensor_data(data=micro_batch, key="pad_mode", default=DatasetPadMode.NO_PADDING)
assert pad_mode == DatasetPadMode.NO_PADDING, f"pad_mode {pad_mode} not supported"
temperature = micro_batch["temperature"]
calculate_entropy = tu.get_non_tensor_data(data=micro_batch, key="calculate_entropy", default=False)
labels = output_args["labels"]
model_output = {}
input_ids = micro_batch["input_ids"]
cu_seqlens = input_ids.offsets()
if use_remove_padding:
labels = labels.squeeze(0)
logits_rmpad = logits.squeeze(0)
# PyTorch's autograd doesn't allow in-place modification of views when gradients need to flow back
logits_rmpad = logits_rmpad / temperature
inplace_backward = True
if calculate_entropy:
inplace_backward = False
log_probs = logprobs_from_logits(
logits=logits_rmpad,
labels=labels,
inplace_backward=inplace_backward,
)
if calculate_entropy:
if not self.engine_config.entropy_checkpointing:
entropy_rmpad = self.compute_entropy_from_logits(logits_rmpad)
else:
entropy_rmpad = torch.utils.checkpoint.checkpoint(self.compute_entropy_from_logits, logits_rmpad)
log_probs = torch.nested.nested_tensor_from_jagged(log_probs.squeeze(0), cu_seqlens)
if calculate_entropy:
entropy = torch.nested.nested_tensor_from_jagged(entropy_rmpad, cu_seqlens)
else:
logits.div_(temperature)
if calculate_entropy:
if not self.engine_config.entropy_checkpointing:
entropy = verl_F.entropy_from_logits(logits)
else:
entropy = torch.utils.checkpoint.checkpoint(verl_F.entropy_from_logits, logits)
seq_lengths = cu_seqlens.diff()
starts = torch.zeros_like(seq_lengths, dtype=torch.int64)
logits = torch.nested.narrow(logits, 1, starts, seq_lengths, layout=torch.jagged)
logits_rmpad = torch.cat([t for t in logits.unbind()])
log_probs = logprobs_from_logits(logits=logits_rmpad, labels=output_args["labels"])
log_probs = torch.nested.nested_tensor_from_jagged(log_probs, cu_seqlens)
if calculate_entropy:
entropy = torch.nested.narrow(entropy, 1, starts, seq_lengths, layout=torch.jagged)
entropy_rmpad = torch.cat([t for t in entropy.unbind()])
entropy = torch.nested.nested_tensor_from_jagged(entropy_rmpad, cu_seqlens)
model_output["log_probs"] = log_probs
if calculate_entropy:
model_output["entropy"] = entropy
return model_output
def forward_step(self, micro_batch: TensorDict, loss_function, forward_only):
device_name = get_device_name()
micro_batch = micro_batch.to(get_device_id())
input_ids, extra_inputs, extra_kwargs, output_args = self.prepare_model_inputs(micro_batch=micro_batch)
with torch.autocast(device_type=device_name, dtype=torch.bfloat16):
logits = self.model_forward_step(inputs=input_ids, extra_inputs=extra_inputs, extra_kwargs=extra_kwargs)
model_output = self.prepare_model_outputs(logits=logits, output_args=output_args, micro_batch=micro_batch)
if loss_function is not None:
loss, metrics = loss_function(
model_output=model_output, data=micro_batch, dp_group=self.get_data_parallel_group()
)
else:
assert forward_only, "forward_only must be True when loss_function is None"
loss = torch.tensor(1.0, device=device_name)
metrics = {}
output = {
"model_output": model_output,
"loss": loss.detach().item(),
"metrics": metrics,
}
return loss, output
| {
"repo_id": "verl-project/verl",
"file_path": "verl/workers/engine/torchtitan/transformer_impl.py",
"license": "Apache License 2.0",
"lines": 621,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | license |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.