code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def write_jsonl(filename: str, data: Iterable[Dict], append: bool = False): """ Writes an iterable of dictionaries to jsonl """ if append: mode = 'ab' else: mode = 'wb' filename = os.path.expanduser(filename) if filename.endswith(".gz"): with open(filename, mode) as f...
Writes an iterable of dictionaries to jsonl
write_jsonl
python
xjdr-alt/entropix
evals/human-eval/human_eval/data.py
https://github.com/xjdr-alt/entropix/blob/master/evals/human-eval/human_eval/data.py
Apache-2.0
def entry_point( sample_file: str, k: str = "1,10,100", n_workers: int = 4, timeout: float = 3.0, problem_file: str = HUMAN_EVAL, ): """ Evaluates the functional correctness of generated samples, and writes results to f"{sample_file}_results.jsonl.gz" """ k = list(map(int, k.spli...
Evaluates the functional correctness of generated samples, and writes results to f"{sample_file}_results.jsonl.gz"
entry_point
python
xjdr-alt/entropix
evals/human-eval/human_eval/evaluate_functional_correctness.py
https://github.com/xjdr-alt/entropix/blob/master/evals/human-eval/human_eval/evaluate_functional_correctness.py
Apache-2.0
def estimate_pass_at_k( num_samples: Union[int, List[int], np.ndarray], num_correct: Union[List[int], np.ndarray], k: int ) -> np.ndarray: """ Estimates pass@k of each problem and returns them in an array. """ def estimator(n: int, c: int, k: int) -> float: """ Calculates 1 ...
Estimates pass@k of each problem and returns them in an array.
estimate_pass_at_k
python
xjdr-alt/entropix
evals/human-eval/human_eval/evaluation.py
https://github.com/xjdr-alt/entropix/blob/master/evals/human-eval/human_eval/evaluation.py
Apache-2.0
def evaluate_functional_correctness( sample_file: str, k: List[int] = [1, 10, 100], n_workers: int = 4, timeout: float = 3.0, problem_file: str = HUMAN_EVAL, ): """ Evaluates the functional correctness of generated samples, and writes results to f"{sample_file}_results.jsonl.gz" """ ...
Evaluates the functional correctness of generated samples, and writes results to f"{sample_file}_results.jsonl.gz"
evaluate_functional_correctness
python
xjdr-alt/entropix
evals/human-eval/human_eval/evaluation.py
https://github.com/xjdr-alt/entropix/blob/master/evals/human-eval/human_eval/evaluation.py
Apache-2.0
def check_correctness(problem: Dict, completion: str, timeout: float, completion_id: Optional[int] = None) -> Dict: """ Evaluates the functional correctness of a completion by running the test suite provided in the problem. :param completion_id: an optional completion ID so we can...
Evaluates the functional correctness of a completion by running the test suite provided in the problem. :param completion_id: an optional completion ID so we can match the results later even if execution finishes asynchronously.
check_correctness
python
xjdr-alt/entropix
evals/human-eval/human_eval/execution.py
https://github.com/xjdr-alt/entropix/blob/master/evals/human-eval/human_eval/execution.py
Apache-2.0
def reliability_guard(maximum_memory_bytes: Optional[int] = None): """ This disables various destructive functions and prevents the generated code from interfering with the test (e.g. fork bomb, killing other processes, removing filesystem files, etc.) WARNING This function is NOT a security sa...
This disables various destructive functions and prevents the generated code from interfering with the test (e.g. fork bomb, killing other processes, removing filesystem files, etc.) WARNING This function is NOT a security sandbox. Untrusted code, including, model- generated code, should not be...
reliability_guard
python
xjdr-alt/entropix
evals/human-eval/human_eval/execution.py
https://github.com/xjdr-alt/entropix/blob/master/evals/human-eval/human_eval/execution.py
Apache-2.0
def setup_logger( level: int = logging.ERROR, rich_tracebacks: bool = True, log_format: str | None = None, propagate: bool = False, **kwargs: Any, ) -> None: """Configure the any_agent logger with the specified settings. Args: level: The logging level to use (default: logging.INFO) ...
Configure the any_agent logger with the specified settings. Args: level: The logging level to use (default: logging.INFO) rich_tracebacks: Whether to enable rich tracebacks (default: True) log_format: Optional custom log format string propagate: Whether to propagate logs to parent l...
setup_logger
python
mozilla-ai/any-agent
src/any_agent/logging.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/logging.py
Apache-2.0
def get_evidence_from_spans(self) -> str: """Get a summary of what happened in each step/span of the agent trace. This includes information about the input, output, and tool calls for each step. Returns: str: The evidence of all the spans in the trace """ evidence ...
Get a summary of what happened in each step/span of the agent trace. This includes information about the input, output, and tool calls for each step. Returns: str: The evidence of all the spans in the trace
get_evidence_from_spans
python
mozilla-ai/any-agent
src/any_agent/evaluation/agent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/evaluation/agent.py
Apache-2.0
def from_yaml(cls, evaluation_case_path: str) -> EvaluationCase: """Load a test case from a YAML file and process it.""" with open(evaluation_case_path, encoding="utf-8") as f: evaluation_case_dict = yaml.safe_load(f) if "ground_truth" in evaluation_case_dict: # remove t...
Load a test case from a YAML file and process it.
from_yaml
python
mozilla-ai/any-agent
src/any_agent/evaluation/evaluation_case.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/evaluation/evaluation_case.py
Apache-2.0
def evaluate_checkpoints( model: str, trace: AgentTrace, checkpoints: Sequence[CheckpointCriteria], ) -> list[EvaluationResult]: """Verify each checkpoint against the trace data using LLM. Args: model: The model to use for evaluation trace: The trace data to evaluate checkpo...
Verify each checkpoint against the trace data using LLM. Args: model: The model to use for evaluation trace: The trace data to evaluate checkpoints: List of checkpoint criteria to verify processor: Trace processor to extract evidence Returns: List of evaluation results ...
evaluate_checkpoints
python
mozilla-ai/any-agent
src/any_agent/evaluation/evaluators.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/evaluation/evaluators.py
Apache-2.0
def _calculate_f1_score(prediction: str, ground_truth: str) -> float: """Calculate F1 score between prediction and ground truth strings.""" # Normalize strings: lowercase and roughly split into words pred_tokens = set(prediction.lower().split()) truth_tokens = set(ground_truth.lower().split()) if n...
Calculate F1 score between prediction and ground truth strings.
_calculate_f1_score
python
mozilla-ai/any-agent
src/any_agent/evaluation/evaluators.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/evaluation/evaluators.py
Apache-2.0
def evaluate_final_output( final_output: str, ground_truth_answer: GroundTruthAnswer, ) -> EvaluationResult: """Compare answers using simple string matching and F1 score.""" ground_truth_text = str(ground_truth_answer["value"]) # Check for exact match (case-insensitive) exact_match = final_outp...
Compare answers using simple string matching and F1 score.
evaluate_final_output
python
mozilla-ai/any-agent
src/any_agent/evaluation/evaluators.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/evaluation/evaluators.py
Apache-2.0
def score(self) -> float: """Calculate the score based on the evaluation results.""" if self.ground_truth_result is not None: all_results = [*self.checkpoint_results, self.ground_truth_result] else: all_results = self.checkpoint_results total_points = sum([result....
Calculate the score based on the evaluation results.
score
python
mozilla-ai/any-agent
src/any_agent/evaluation/schemas.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/evaluation/schemas.py
Apache-2.0
def _get_model(self, agent_config: AgentConfig) -> "Model": """Get the model configuration for an Agno agent.""" model_type = agent_config.model_type or DEFAULT_MODEL_TYPE return model_type( id=agent_config.model_id, api_base=agent_config.api_base, api_key=ag...
Get the model configuration for an Agno agent.
_get_model
python
mozilla-ai/any-agent
src/any_agent/frameworks/agno.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/agno.py
Apache-2.0
def create( cls, agent_framework: AgentFramework | str, agent_config: AgentConfig, ) -> AnyAgent: """Create an agent using the given framework and config.""" return run_async_in_sync( cls.create_async( agent_framework=agent_framework, ...
Create an agent using the given framework and config.
create
python
mozilla-ai/any-agent
src/any_agent/frameworks/any_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/any_agent.py
Apache-2.0
async def create_async( cls, agent_framework: AgentFramework | str, agent_config: AgentConfig, ) -> AnyAgent: """Create an agent using the given framework and config.""" agent_cls = cls._get_agent_type_by_framework(agent_framework) agent = agent_cls(agent_config) ...
Create an agent using the given framework and config.
create_async
python
mozilla-ai/any-agent
src/any_agent/frameworks/any_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/any_agent.py
Apache-2.0
async def run_async( self, prompt: str, instrument: bool = True, **kwargs: Any ) -> AgentTrace: """Run the agent asynchronously with the given prompt. Args: prompt: The user prompt to be passed to the agent. instrument: Whether to instrument the underlying framework ...
Run the agent asynchronously with the given prompt. Args: prompt: The user prompt to be passed to the agent. instrument: Whether to instrument the underlying framework to generate LLM Calls and Tool Execution Spans. If `False` the returned `AgentTrace` w...
run_async
python
mozilla-ai/any-agent
src/any_agent/frameworks/any_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/any_agent.py
Apache-2.0
def serve(self, serving_config: A2AServingConfig | None = None) -> None: """Serve this agent using the protocol defined in the serving_config. Args: serving_config: Configuration for serving the agent. If None, uses default A2AServingConfig. Must be an instance of ...
Serve this agent using the protocol defined in the serving_config. Args: serving_config: Configuration for serving the agent. If None, uses default A2AServingConfig. Must be an instance of A2AServingConfig. Raises: ImportError: If the `serving` depende...
serve
python
mozilla-ai/any-agent
src/any_agent/frameworks/any_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/any_agent.py
Apache-2.0
async def serve_async( self, serving_config: A2AServingConfig | None = None ) -> tuple[asyncio.Task[Any], uvicorn.Server]: """Serve this agent asynchronously using the protocol defined in the serving_config. Args: serving_config: Configuration for serving the agent. If None, use...
Serve this agent asynchronously using the protocol defined in the serving_config. Args: serving_config: Configuration for serving the agent. If None, uses default A2AServingConfig. Must be an instance of A2AServingConfig. Returns: A tuple containing: ...
serve_async
python
mozilla-ai/any-agent
src/any_agent/frameworks/any_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/any_agent.py
Apache-2.0
async def _run_async(self, prompt: str, **kwargs: Any) -> str | BaseModel: """To be implemented by each framework."""
To be implemented by each framework.
_run_async
python
mozilla-ai/any-agent
src/any_agent/frameworks/any_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/any_agent.py
Apache-2.0
def _get_model(self, agent_config: AgentConfig) -> "BaseLlm": """Get the model configuration for a Google agent.""" model_type = agent_config.model_type or DEFAULT_MODEL_TYPE model_args = agent_config.model_args or {} if self.config.output_type: model_args["tool_choice"] = "r...
Get the model configuration for a Google agent.
_get_model
python
mozilla-ai/any-agent
src/any_agent/frameworks/google.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/google.py
Apache-2.0
async def _load_agent(self) -> None: """Load the Google agent with the given configuration.""" if not adk_available: msg = "You need to `pip install 'any-agent[google]'` to use this agent" raise ImportError(msg) tools, _ = await self._load_tools(self.config.tools) ...
Load the Google agent with the given configuration.
_load_agent
python
mozilla-ai/any-agent
src/any_agent/frameworks/google.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/google.py
Apache-2.0
def _get_model(self, agent_config: AgentConfig) -> "LanguageModelLike": """Get the model configuration for a LangChain agent.""" model_type = agent_config.model_type or DEFAULT_MODEL_TYPE model_args = agent_config.model_args or {} return cast( "LanguageModelLike", ...
Get the model configuration for a LangChain agent.
_get_model
python
mozilla-ai/any-agent
src/any_agent/frameworks/langchain.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/langchain.py
Apache-2.0
async def _load_agent(self) -> None: """Load the LangChain agent with the given configuration.""" if not langchain_available: msg = "You need to `pip install 'any-agent[langchain]'` to use this agent" raise ImportError(msg) imported_tools, _ = await self._load_tools(self...
Load the LangChain agent with the given configuration.
_load_agent
python
mozilla-ai/any-agent
src/any_agent/frameworks/langchain.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/langchain.py
Apache-2.0
def _get_model(self, agent_config: AgentConfig) -> "LLM": """Get the model configuration for a llama_index agent.""" model_type = agent_config.model_type or DEFAULT_MODEL_TYPE return cast( "LLM", model_type( model=agent_config.model_id, api...
Get the model configuration for a llama_index agent.
_get_model
python
mozilla-ai/any-agent
src/any_agent/frameworks/llama_index.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/llama_index.py
Apache-2.0
async def _load_agent(self) -> None: """Load the LLamaIndex agent with the given configuration.""" if not llama_index_available: msg = "You need to `pip install 'any-agent[llama_index]'` to use this agent" raise ImportError(msg) instructions = self.config.instructions ...
Load the LLamaIndex agent with the given configuration.
_load_agent
python
mozilla-ai/any-agent
src/any_agent/frameworks/llama_index.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/llama_index.py
Apache-2.0
def _get_model( self, agent_config: AgentConfig, ) -> "Model": """Get the model configuration for an OpenAI agent.""" model_type = agent_config.model_type or DEFAULT_MODEL_TYPE return model_type( model=agent_config.model_id, base_url=agent_config.api_b...
Get the model configuration for an OpenAI agent.
_get_model
python
mozilla-ai/any-agent
src/any_agent/frameworks/openai.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/openai.py
Apache-2.0
async def _load_agent(self) -> None: """Load the OpenAI agent with the given configuration.""" if not agents_available: msg = "You need to `pip install 'any-agent[openai]'` to use this agent" raise ImportError(msg) if not agents_available: msg = "You need to `...
Load the OpenAI agent with the given configuration.
_load_agent
python
mozilla-ai/any-agent
src/any_agent/frameworks/openai.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/openai.py
Apache-2.0
def _filter_mcp_tools(self, tools: list[Any], mcp_servers: list[Any]) -> list[Any]: """OpenAI frameowrk doesn't expect the mcp tool to be included in `tools`.""" non_mcp_tools = [] for tool in tools: if any(tool in mcp_server.tools for mcp_server in mcp_servers): cont...
OpenAI frameowrk doesn't expect the mcp tool to be included in `tools`.
_filter_mcp_tools
python
mozilla-ai/any-agent
src/any_agent/frameworks/openai.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/openai.py
Apache-2.0
def _get_model(self, agent_config: AgentConfig) -> Any: """Get the model configuration for a smolagents agent.""" model_type = agent_config.model_type or DEFAULT_MODEL_TYPE model_args = agent_config.model_args or {} kwargs = { "model_id": agent_config.model_id, "a...
Get the model configuration for a smolagents agent.
_get_model
python
mozilla-ai/any-agent
src/any_agent/frameworks/smolagents.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/smolagents.py
Apache-2.0
async def _load_agent(self) -> None: """Load the Smolagents agent with the given configuration.""" if not smolagents_available: msg = "You need to `pip install 'any-agent[smolagents]'` to use this agent" raise ImportError(msg) tools, _ = await self._load_tools(self.confi...
Load the Smolagents agent with the given configuration.
_load_agent
python
mozilla-ai/any-agent
src/any_agent/frameworks/smolagents.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/smolagents.py
Apache-2.0
async def call_tool(self, request: dict[str, Any]) -> str: """Call the tool function. Args: request: The tool request with name and arguments Returns: Tool execution result """ try: arguments = request.get("arguments", {}) if ha...
Call the tool function. Args: request: The tool request with name and arguments Returns: Tool execution result
call_tool
python
mozilla-ai/any-agent
src/any_agent/frameworks/tinyagent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/tinyagent.py
Apache-2.0
def __init__(self, config: AgentConfig) -> None: """Initialize the TinyAgent. Args: config: Agent configuration tracing: Optional tracing configuration """ super().__init__(config) self.clients: dict[str, ToolExecutor] = {} self.completion_params...
Initialize the TinyAgent. Args: config: Agent configuration tracing: Optional tracing configuration
__init__
python
mozilla-ai/any-agent
src/any_agent/frameworks/tinyagent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/tinyagent.py
Apache-2.0
async def _load_agent(self) -> None: """Load the agent and its tools.""" wrapped_tools, mcp_servers = await self._load_tools(self.config.tools) self._mcp_servers = ( mcp_servers # Store servers so that they don't get garbage collected ) self._tools = wrapped_tools ...
Load the agent and its tools.
_load_agent
python
mozilla-ai/any-agent
src/any_agent/frameworks/tinyagent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/frameworks/tinyagent.py
Apache-2.0
async def serve_a2a_async( server: A2AStarletteApplication, host: str, port: int, endpoint: str, log_level: str = "warning", ) -> tuple[asyncio.Task[Any], uvicorn.Server]: """Provide an A2A server to be used in an event loop.""" uv_server = _create_server(server, host, port, endpoint, log_le...
Provide an A2A server to be used in an event loop.
serve_a2a_async
python
mozilla-ai/any-agent
src/any_agent/serving/server.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/serving/server.py
Apache-2.0
async def a2a_tool_async( url: str, toolname: str | None = None, http_kwargs: dict[str, Any] | None = None ) -> Callable[[str], Coroutine[Any, Any, str]]: """Perform a query using A2A to another agent. Args: url (str): The url in which the A2A agent is located. toolname (str): The name for ...
Perform a query using A2A to another agent. Args: url (str): The url in which the A2A agent is located. toolname (str): The name for the created tool. Defaults to `call_{agent name in card}`. Leading and trailing whitespace are removed. Whitespace in the middle is replaced by `_`. ...
a2a_tool_async
python
mozilla-ai/any-agent
src/any_agent/tools/a2a.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/a2a.py
Apache-2.0
def a2a_tool( url: str, toolname: str | None = None, http_kwargs: dict[str, Any] | None = None ) -> Callable[[str], str]: """Perform a query using A2A to another agent (synchronous version). Args: url (str): The url in which the A2A agent is located. toolname (str): The name for the created...
Perform a query using A2A to another agent (synchronous version). Args: url (str): The url in which the A2A agent is located. toolname (str): The name for the created tool. Defaults to `call_{agent name in card}`. Leading and trailing whitespace are removed. Whitespace in the middle is ...
a2a_tool
python
mozilla-ai/any-agent
src/any_agent/tools/a2a.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/a2a.py
Apache-2.0
def __init__(self, output_type: type[BaseModel]): """Create the function that will be used as a tool.""" self.output_type = output_type # Set docstring for the callable object self.__doc__ = f"""You must call this tool in order to return the final answer. Args: answe...
Create the function that will be used as a tool.
__init__
python
mozilla-ai/any-agent
src/any_agent/tools/final_output.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/final_output.py
Apache-2.0
def search_web(query: str) -> str: """Perform a duckduckgo web search based on your query (think a Google search) then returns the top search results. Args: query (str): The search query to perform. Returns: The top search results. """ ddgs = DDGS() results = ddgs.text(query, ...
Perform a duckduckgo web search based on your query (think a Google search) then returns the top search results. Args: query (str): The search query to perform. Returns: The top search results.
search_web
python
mozilla-ai/any-agent
src/any_agent/tools/web_browsing.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/web_browsing.py
Apache-2.0
def visit_webpage(url: str) -> str: """Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages. Args: url: The url of the webpage to visit. """ try: response = requests.get(url) response.raise_for_status() markdown_cont...
Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages. Args: url: The url of the webpage to visit.
visit_webpage
python
mozilla-ai/any-agent
src/any_agent/tools/web_browsing.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/web_browsing.py
Apache-2.0
def search_tavily(query: str, include_images: bool = False) -> str: """Perform a Tavily web search based on your query and return the top search results. See https://blog.tavily.com/getting-started-with-the-tavily-search-api for more information. Args: query (str): The search query to perform. ...
Perform a Tavily web search based on your query and return the top search results. See https://blog.tavily.com/getting-started-with-the-tavily-search-api for more information. Args: query (str): The search query to perform. include_images (bool): Whether to include images in the results. ...
search_tavily
python
mozilla-ai/any-agent
src/any_agent/tools/web_browsing.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/web_browsing.py
Apache-2.0
def verify_callable(tool: Callable[..., Any]) -> None: """Verify that `tool` is a valid callable. - It needs to have some sort of docstring that describes what it does - It needs to have typed argument - It needs to have a typed return. We need these things because this info gets provided to the a...
Verify that `tool` is a valid callable. - It needs to have some sort of docstring that describes what it does - It needs to have typed argument - It needs to have a typed return. We need these things because this info gets provided to the agent so that they know how and when to call the tool.
verify_callable
python
mozilla-ai/any-agent
src/any_agent/tools/wrappers.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/wrappers.py
Apache-2.0
async def list_tools(self) -> list[T]: """List tools from the MCP server."""
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/mcp_connection.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/mcp_connection.py
Apache-2.0
def _filter_tools(self, tools: Sequence[T]) -> Sequence[T]: """Filter the tools to only include the ones listed in mcp_tool['tools'].""" requested_tools = list(self.mcp_tool.tools or []) if not requested_tools: return tools name_to_tool = { tool.name if isinstan...
Filter the tools to only include the ones listed in mcp_tool['tools'].
_filter_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/mcp_connection.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/mcp_connection.py
Apache-2.0
async def list_tools(self) -> list["AgnoMCPTools"]: """List tools from the MCP server.""" if self._server is None: msg = "MCP server is not set up. Please call `list_tools` from a concrete class." raise ValueError(msg) tools = await self._exit_stack.enter_async_context(s...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/agno.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/agno.py
Apache-2.0
async def list_tools(self) -> list["AgnoMCPTools"]: """List tools from the MCP server.""" from mcp import StdioServerParameters server_params = StdioServerParameters( command=self.mcp_tool.command, args=list(self.mcp_tool.args), env=self.mcp_tool.env, ...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/agno.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/agno.py
Apache-2.0
async def list_tools(self) -> list["AgnoMCPTools"]: """List tools from the MCP server.""" client = sse_client( url=self.mcp_tool.url, headers=dict(self.mcp_tool.headers or {}), ) sse_transport = await self._exit_stack.enter_async_context(client) stdio, wri...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/agno.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/agno.py
Apache-2.0
def _check_dependencies(self) -> None: """Check if the required dependencies for the MCP server are available.""" self.libraries = "any-agent[mcp,agno]" self.mcp_available = mcp_available super()._check_dependencies()
Check if the required dependencies for the MCP server are available.
_check_dependencies
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/agno.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/agno.py
Apache-2.0
async def list_tools(self) -> list["GoogleMCPTool"]: """List tools from the MCP server.""" if not self._params: msg = "MCP params is not set up. Please call `list_tools` from a concrete class." raise ValueError(msg) server = GoogleMCPToolset(connection_params=self._param...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/google.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/google.py
Apache-2.0
async def list_tools(self) -> list["GoogleMCPTool"]: """List tools from the MCP server.""" self._params = GoogleStdioServerParameters( command=self.mcp_tool.command, args=list(self.mcp_tool.args), env=self.mcp_tool.env, ) return await super().list_tool...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/google.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/google.py
Apache-2.0
async def list_tools(self) -> list["GoogleMCPTool"]: """List tools from the MCP server.""" self._params = GoogleSseServerParameters( url=self.mcp_tool.url, headers=dict(self.mcp_tool.headers or {}), ) return await super().list_tools()
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/google.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/google.py
Apache-2.0
def _check_dependencies(self) -> None: """Check if the required dependencies for the MCP server are available.""" self.libraries = "any-agent[mcp,google]" self.mcp_available = mcp_available super()._check_dependencies()
Check if the required dependencies for the MCP server are available.
_check_dependencies
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/google.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/google.py
Apache-2.0
async def list_tools(self) -> list["BaseTool"]: """List tools from the MCP server.""" if not self._client: msg = "MCP client is not set up. Please call `list_tools` from a concrete class." raise ValueError(msg) stdio, write = await self._exit_stack.enter_async_context(se...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/langchain.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/langchain.py
Apache-2.0
async def list_tools(self) -> list["BaseTool"]: """List tools from the MCP server.""" server_params = StdioServerParameters( command=self.mcp_tool.command, args=list(self.mcp_tool.args), env=self.mcp_tool.env, ) self._client = stdio_client(server_para...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/langchain.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/langchain.py
Apache-2.0
async def list_tools(self) -> list["BaseTool"]: """List tools from the MCP server.""" kwargs = {} if self.mcp_tool.client_session_timeout_seconds: kwargs["sse_read_timeout"] = self.mcp_tool.client_session_timeout_seconds self._client = sse_client( url=self.mcp_too...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/langchain.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/langchain.py
Apache-2.0
async def list_tools(self) -> list["LlamaIndexFunctionTool"]: """List tools from the MCP server.""" if not self._client: msg = "MCP client is not set up. Please call `list_tool` from a concrete class." raise ValueError(msg) allowed_tools = self.mcp_tool.tools if ...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/llama_index.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/llama_index.py
Apache-2.0
async def list_tools(self) -> list["LlamaIndexFunctionTool"]: """List tools from the MCP server.""" kwargs = {} if self.mcp_tool.client_session_timeout_seconds: kwargs["timeout"] = self.mcp_tool.client_session_timeout_seconds self._client = LlamaIndexMCPClient( co...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/llama_index.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/llama_index.py
Apache-2.0
async def list_tools(self) -> list["LlamaIndexFunctionTool"]: """List tools from the MCP server.""" kwargs = {} if self.mcp_tool.client_session_timeout_seconds: kwargs["timeout"] = self.mcp_tool.client_session_timeout_seconds self._client = LlamaIndexMCPClient( co...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/llama_index.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/llama_index.py
Apache-2.0
def _check_dependencies(self) -> None: """Check if the required dependencies for the MCP server are available.""" self.libraries = "any-agent[mcp,llama_index]" self.mcp_available = mcp_available super()._check_dependencies()
Check if the required dependencies for the MCP server are available.
_check_dependencies
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/llama_index.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/llama_index.py
Apache-2.0
async def list_tools(self) -> list["MCPTool"]: """List tools from the MCP server.""" if not self._server: msg = "MCP server is not set up. Please call `setup` from a concrete class." raise ValueError(msg) await self._exit_stack.enter_async_context(self._server) t...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/openai.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/openai.py
Apache-2.0
async def list_tools(self) -> list["MCPTool"]: """List tools from the MCP server.""" params = OpenAIInternalMCPServerStdioParams( command=self.mcp_tool.command, args=list(self.mcp_tool.args), env=self.mcp_tool.env, # type: ignore[typeddict-item] ) se...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/openai.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/openai.py
Apache-2.0
async def list_tools(self) -> list["MCPTool"]: """List tools from the MCP server.""" params = OpenAIInternalMCPServerSseParams(url=self.mcp_tool.url) self._server = OpenAIInternalMCPServerSse( name="OpenAI MCP Server", params=params, client_session_timeout_se...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/openai.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/openai.py
Apache-2.0
def _check_dependencies(self) -> None: """Check if the required dependencies for the MCP server are available.""" self.libraries = "any-agent[mcp,openai]" self.mcp_available = mcp_available super()._check_dependencies()
Check if the required dependencies for the MCP server are available.
_check_dependencies
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/openai.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/openai.py
Apache-2.0
async def list_tools(self) -> list["SmolagentsTool"]: """List tools from the MCP server.""" if not self._client: msg = "Tool collection is not set up. Please call `list_tools` from a concrete class." raise ValueError(msg) tools = self._client.get_tools() return s...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/smolagents.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/smolagents.py
Apache-2.0
async def list_tools(self) -> list["SmolagentsTool"]: """List tools from the MCP server.""" server_parameters = StdioServerParameters( command=self.mcp_tool.command, args=list(self.mcp_tool.args), env=self.mcp_tool.env, ) self._client = MCPClient(serve...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/smolagents.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/smolagents.py
Apache-2.0
async def list_tools(self) -> list["SmolagentsTool"]: """List tools from the MCP server.""" server_parameters = { "url": self.mcp_tool.url, } self._client = MCPClient(server_parameters) return await super().list_tools()
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/smolagents.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/smolagents.py
Apache-2.0
def _check_dependencies(self) -> None: """Check if the required dependencies for the MCP server are available.""" self.libraries = "any-agent[mcp,smolagents]" self.mcp_available = mcp_available super()._check_dependencies()
Check if the required dependencies for the MCP server are available.
_check_dependencies
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/smolagents.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/smolagents.py
Apache-2.0
async def list_tools(self) -> list["MCPTool"]: """List tools from the MCP server.""" if not self._client: msg = "MCP client is not set up. Please call `setup` from a concrete class." raise ValueError(msg) # Setup the client connection using exit stack to manage lifecycle...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/tinyagent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/tinyagent.py
Apache-2.0
def _create_tool_from_info( self, tool: Tool, session: "ClientSession" ) -> Callable[..., Any]: """Create a tool function from tool information.""" tool_name = tool.name if hasattr(tool, "name") else tool tool_description = tool.description if hasattr(tool, "description") else "" ...
Create a tool function from tool information.
_create_tool_from_info
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/tinyagent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/tinyagent.py
Apache-2.0
async def tool_function(*args, **kwargs) -> Any: # type: ignore[no-untyped-def] """Tool function that calls the MCP server.""" # Combine args and kwargs combined_args = {} if args and len(args) > 0: combined_args = args[0] combined_args.update...
Tool function that calls the MCP server.
tool_function
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/tinyagent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/tinyagent.py
Apache-2.0
async def list_tools(self) -> list["MCPTool"]: """List tools from the MCP server.""" server_params = StdioServerParameters( command=self.mcp_tool.command, args=list(self.mcp_tool.args), env={**os.environ}, ) self._client = stdio_client(server_params) ...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/tinyagent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/tinyagent.py
Apache-2.0
async def list_tools(self) -> list["MCPTool"]: """List tools from the MCP server.""" kwargs = {} if self.mcp_tool.client_session_timeout_seconds: kwargs["sse_read_timeout"] = self.mcp_tool.client_session_timeout_seconds self._client = sse_client( url=self.mcp_tool...
List tools from the MCP server.
list_tools
python
mozilla-ai/any-agent
src/any_agent/tools/mcp/frameworks/tinyagent.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tools/mcp/frameworks/tinyagent.py
Apache-2.0
def from_otel(cls, otel_span: Span) -> AgentSpan: """Create an AgentSpan from an OTEL Span.""" return cls( name=otel_span.name, kind=SpanKind.from_otel(otel_span.kind), parent=SpanContext.from_otel(otel_span.parent), start_time=otel_span.start_time, ...
Create an AgentSpan from an OTEL Span.
from_otel
python
mozilla-ai/any-agent
src/any_agent/tracing/agent_trace.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/agent_trace.py
Apache-2.0
def to_readable_span(self) -> ReadableSpan: """Create an ReadableSpan from the AgentSpan.""" return ReadableSpan( name=self.name, kind=self.kind, parent=self.parent, start_time=self.start_time, end_time=self.end_time, status=self.st...
Create an ReadableSpan from the AgentSpan.
to_readable_span
python
mozilla-ai/any-agent
src/any_agent/tracing/agent_trace.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/agent_trace.py
Apache-2.0
def serialize_final_output(self, value: str | BaseModel | None) -> Any: """Serialize the final_output and handle any BaseModel subclass.""" if value is None: return None if isinstance(value, str): return value if isinstance(value, BaseModel): # This wi...
Serialize the final_output and handle any BaseModel subclass.
serialize_final_output
python
mozilla-ai/any-agent
src/any_agent/tracing/agent_trace.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/agent_trace.py
Apache-2.0
def _invalidate_usage_and_cost_cache(self) -> None: """Clear the cached usage_and_cost property if it exists.""" if "usage" in self.__dict__: del self.tokens if "cost" in self.__dict__: del self.cost
Clear the cached usage_and_cost property if it exists.
_invalidate_usage_and_cost_cache
python
mozilla-ai/any-agent
src/any_agent/tracing/agent_trace.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/agent_trace.py
Apache-2.0
def add_span(self, span: AgentSpan | Span) -> None: """Add an AgentSpan to the trace and clear the usage_and_cost cache if present.""" if not isinstance(span, AgentSpan): span = AgentSpan.from_otel(span) self.spans.append(span) self._invalidate_usage_and_cost_cache()
Add an AgentSpan to the trace and clear the usage_and_cost cache if present.
add_span
python
mozilla-ai/any-agent
src/any_agent/tracing/agent_trace.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/agent_trace.py
Apache-2.0
def duration(self) -> timedelta: """Duration of the parent `invoke_agent` span as a datetime.timedelta object. The duration is computed from the span's start and end time (in nanoseconds). Raises ValueError if: - There are no spans. - The invoke_agent span is not the la...
Duration of the parent `invoke_agent` span as a datetime.timedelta object. The duration is computed from the span's start and end time (in nanoseconds). Raises ValueError if: - There are no spans. - The invoke_agent span is not the last span. - Any of the start/end ...
duration
python
mozilla-ai/any-agent
src/any_agent/tracing/agent_trace.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/agent_trace.py
Apache-2.0
def tokens(self) -> TokenInfo: """The current total token count for this trace. Cached after first computation.""" sum_input_tokens = 0 sum_output_tokens = 0 for span in self.spans: if span.is_llm_call(): sum_input_tokens += span.attributes.get("gen_ai.usage.i...
The current total token count for this trace. Cached after first computation.
tokens
python
mozilla-ai/any-agent
src/any_agent/tracing/agent_trace.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/agent_trace.py
Apache-2.0
def cost(self) -> CostInfo: """The current total cost for this trace. Cached after first computation.""" sum_input_cost = 0.0 sum_output_cost = 0.0 for span in self.spans: if span.is_llm_call(): cost_info = compute_cost_info(span.attributes) if...
The current total cost for this trace. Cached after first computation.
cost
python
mozilla-ai/any-agent
src/any_agent/tracing/agent_trace.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/agent_trace.py
Apache-2.0
def enable_console_traces() -> None: """Enable printing traces to the console.""" has_console_exporter = any( isinstance(getattr(p, "span_exporter", None), _ConsoleExporter) for p in TRACE_PROVIDER._active_span_processor._span_processors ) if not has_console_exporter: TRACE_PROVI...
Enable printing traces to the console.
enable_console_traces
python
mozilla-ai/any-agent
src/any_agent/tracing/__init__.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/__init__.py
Apache-2.0
def disable_console_traces() -> None: """Disable printing traces to the console.""" with TRACE_PROVIDER._active_span_processor._lock: TRACE_PROVIDER._active_span_processor._span_processors = tuple( p for p in TRACE_PROVIDER._active_span_processor._span_processors if n...
Disable printing traces to the console.
disable_console_traces
python
mozilla-ai/any-agent
src/any_agent/tracing/__init__.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/tracing/__init__.py
Apache-2.0
def run_async_in_sync(coro: Coroutine[Any, Any, T]) -> T: """Run an async coroutine in a synchronous context. Handles different event loop scenarios: - If a loop is running, uses threading to avoid conflicts - If no loop exists, creates one or uses the current loop Args: coro: The coroutin...
Run an async coroutine in a synchronous context. Handles different event loop scenarios: - If a loop is running, uses threading to avoid conflicts - If no loop exists, creates one or uses the current loop Args: coro: The coroutine to execute Returns: The result of the coroutine ex...
run_async_in_sync
python
mozilla-ai/any-agent
src/any_agent/utils/asyncio_sync.py
https://github.com/mozilla-ai/any-agent/blob/master/src/any_agent/utils/asyncio_sync.py
Apache-2.0
async def echo_sse_server() -> AsyncGenerator[dict[str, str]]: """This fixture runs a FastMCP server in a subprocess. I thought about trying to mock all the individual mcp client calls, but I went with this because this way we don't need to actually mock anything. This is similar to what MCPAdapt does i...
This fixture runs a FastMCP server in a subprocess. I thought about trying to mock all the individual mcp client calls, but I went with this because this way we don't need to actually mock anything. This is similar to what MCPAdapt does in their testing https://github.com/grll/mcpadapt/blob/main/tests/test_...
echo_sse_server
python
mozilla-ai/any-agent
tests/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/conftest.py
Apache-2.0
def configure_logging(pytestconfig: pytest.Config) -> None: """Configure the logging level based on the verbosity of the test run. This is a session fixture, so it only gets called once per test session. """ verbosity = pytestconfig.getoption("verbose") level = logging.DEBUG if verbosity > 0 else lo...
Configure the logging level based on the verbosity of the test run. This is a session fixture, so it only gets called once per test session.
configure_logging
python
mozilla-ai/any-agent
tests/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/conftest.py
Apache-2.0
def mock_litellm_response() -> ModelResponse: """Fixture to create a standard mock LiteLLM response""" return ModelResponse.model_validate_json( '{"id":"chatcmpl-BWnfbHWPsQp05roQ06LAD1mZ9tOjT","created":1747157127,"model":"gpt-4o-2024-08-06","object":"chat.completion","system_fingerprint":"fp_f5bdcc3276...
Fixture to create a standard mock LiteLLM response
mock_litellm_response
python
mozilla-ai/any-agent
tests/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/conftest.py
Apache-2.0
def mock_litellm_streaming() -> Callable[[Any, Any], AsyncGenerator[Any]]: """ Create a fixture that returns an async generator function to mock streaming responses. This returns a function that can be used as a side_effect. """ async def _mock_streaming_response( *args: Any, **kwargs: Any ...
Create a fixture that returns an async generator function to mock streaming responses. This returns a function that can be used as a side_effect.
mock_litellm_streaming
python
mozilla-ai/any-agent
tests/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/conftest.py
Apache-2.0
def mock_visit_webpage(url: str) -> str: """Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages. Args: url: The url of the webpage to visit. """ return ( "# Any Agent Framework Review\n" "Any Agent is the top choice for deve...
Visits a webpage at the given url and reads its content as a markdown string. Use this to browse webpages. Args: url: The url of the webpage to visit.
mock_visit_webpage
python
mozilla-ai/any-agent
tests/integration/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/conftest.py
Apache-2.0
def pytest_addoption(parser: pytest.Parser) -> None: """ Add custom command-line options to pytest. This hook adds the `--update-trace-assets` flag to pytest, which can be used when running integration tests. When this flag is set, tests that generate trace asset files (aka the integration test that ...
Add custom command-line options to pytest. This hook adds the `--update-trace-assets` flag to pytest, which can be used when running integration tests. When this flag is set, tests that generate trace asset files (aka the integration test that produces agent traces) will update the asset files in the ...
pytest_addoption
python
mozilla-ai/any-agent
tests/integration/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/conftest.py
Apache-2.0
def _is_port_available(port: int, host: str = "localhost") -> bool: """Check if a port is available for binding. This isn't a perfect check but it at least tells us if there is absolutely no chance of binding to the port. """ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: try:...
Check if a port is available for binding. This isn't a perfect check but it at least tells us if there is absolutely no chance of binding to the port.
_is_port_available
python
mozilla-ai/any-agent
tests/integration/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/conftest.py
Apache-2.0
def _get_deterministic_port(test_name: str, framework_name: str) -> int: """Generate a deterministic port number based on test name and framework. This ensures each test gets a unique port that remains consistent across runs. """ # Create a unique string by combining test name and framework unique_...
Generate a deterministic port number based on test name and framework. This ensures each test gets a unique port that remains consistent across runs.
_get_deterministic_port
python
mozilla-ai/any-agent
tests/integration/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/conftest.py
Apache-2.0
def test_port(request, agent_framework): """Single fixture that provides a unique, deterministic port for each test.""" test_name = request.node.name framework_name = agent_framework.value port = _get_deterministic_port(test_name, framework_name) # Ensure the port is available, if not, try nearby ...
Single fixture that provides a unique, deterministic port for each test.
test_port
python
mozilla-ai/any-agent
tests/integration/conftest.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/conftest.py
Apache-2.0
def assert_first_llm_call(llm_call: AgentSpan) -> None: """Checks the `_set_llm_inputs` implemented by each framework's instrumentation.""" assert llm_call.attributes.get("gen_ai.input.messages", None) is not None # input.messages should be a valid JSON string (list of dicts) input_messa...
Checks the `_set_llm_inputs` implemented by each framework's instrumentation.
assert_first_llm_call
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_agent.py
Apache-2.0
def assert_first_tool_execution(tool_execution: AgentSpan) -> None: """Checks the tools setup implemented by each framework's instrumentation.""" assert tool_execution.attributes.get("gen_ai.tool.args", None) is not None # tool.args should be a JSON string (dict) args = json.loads(tool_e...
Checks the tools setup implemented by each framework's instrumentation.
assert_first_tool_execution
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_agent.py
Apache-2.0
def mock_capital(query: str) -> str: """Perform a duckduckgo web search based on your query (think a Google search) then returns the top search results. Args: query (str): The search query to perform. Returns: The top search results. """ if "France" in query: return "The c...
Perform a duckduckgo web search based on your query (think a Google search) then returns the top search results. Args: query (str): The search query to perform. Returns: The top search results.
mock_capital
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_agent_twice.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_agent_twice.py
Apache-2.0
async def test_run_agent_twice(agent_framework: AgentFramework) -> None: """When an agent is run twice, state from the first run shouldn't bleed into the second run""" model_id = "gpt-4.1-nano" env_check = validate_environment(model_id) if not env_check["keys_in_environment"]: pytest.skip(f"{env...
When an agent is run twice, state from the first run shouldn't bleed into the second run
test_run_agent_twice
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_agent_twice.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_agent_twice.py
Apache-2.0
def _assert_contains_current_date_info(final_output: str) -> None: """Assert that the final output contains current date and time information.""" now = datetime.datetime.now() assert all( [ str(now.year) in final_output, str(now.day) in final_output, now.strftime(...
Assert that the final output contains current date and time information.
_assert_contains_current_date_info
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_multi_agent_a2a_tool.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_multi_agent_a2a_tool.py
Apache-2.0
def _assert_has_date_agent_tool_call(agent_trace: AgentTrace) -> None: """Assert that the agent trace contains a tool execution span for the date agent.""" assert any( span.is_tool_execution() and span.attributes.get("gen_ai.tool.name", None) == "call_date_agent" for span in agent_trace....
Assert that the agent trace contains a tool execution span for the date agent.
_assert_has_date_agent_tool_call
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_multi_agent_a2a_tool.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_multi_agent_a2a_tool.py
Apache-2.0
async def test_load_and_run_multi_agent_a2a(agent_framework: AgentFramework) -> None: """Tests that an agent contacts another using A2A using the adapter tool. Note that there is an issue when using Google ADK: https://github.com/google/adk-python/pull/566 """ if agent_framework in [ # async a2...
Tests that an agent contacts another using A2A using the adapter tool. Note that there is an issue when using Google ADK: https://github.com/google/adk-python/pull/566
test_load_and_run_multi_agent_a2a
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_multi_agent_a2a_tool.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_multi_agent_a2a_tool.py
Apache-2.0
def _run_server( agent_framework_str: str, port: int, endpoint: str, model_id: str, server_queue: Queue, ): """Run the server for the sync test. This needs to be defined outside the test function so that it can be run in a separate process.""" date_agent_description = "Agent that can return ...
Run the server for the sync test. This needs to be defined outside the test function so that it can be run in a separate process.
_run_server
python
mozilla-ai/any-agent
tests/integration/test_load_and_run_multi_agent_a2a_tool.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_load_and_run_multi_agent_a2a_tool.py
Apache-2.0