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 _generate_thread(self, idx: int): """Step token generation and insert prefills from backlog.""" logging.info("---------Spinning up generate thread %d.---------", idx) generate_engine = self._generate_engines[idx] my_slots = self._generate_slots[idx] my_generate_backlog = self._generate_backlogs[...
Step token generation and insert prefills from backlog.
_generate_thread
python
xjdr-alt/entropix
entropix/orchestrator.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/orchestrator.py
Apache-2.0
def _detokenize_thread(self, idx: int): """Detokenize sampled tokens and returns them to the user.""" # One of these per generate engine. # For all filled my_slots, pop the sampled token onto the relevant # requests return channel. If it done, place it back onto free slots. my_detokenize_backlog = s...
Detokenize sampled tokens and returns them to the user.
_detokenize_thread
python
xjdr-alt/entropix
entropix/orchestrator.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/orchestrator.py
Apache-2.0
def decode(self, t: Sequence[int]) -> str: """ Decodes a list of token IDs into a string. Args: t (List[int]): The list of token IDs to be decoded. Returns: str: The decoded string. """ # Typecast is safe here. Tiktoken doesn't do anything list-related with the sequence. re...
Decodes a list of token IDs into a string. Args: t (List[int]): The list of token IDs to be decoded. Returns: str: The decoded string.
decode
python
xjdr-alt/entropix
entropix/tokenizer.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/tokenizer.py
Apache-2.0
def take_nearest_length(lengths: list[int], length: int) -> int: """Gets the nearest length to the right in a set of lengths.""" pos = bisect_left(lengths, length) if pos == len(lengths): return lengths[-1] return lengths[pos]
Gets the nearest length to the right in a set of lengths.
take_nearest_length
python
xjdr-alt/entropix
entropix/token_utils.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/token_utils.py
Apache-2.0
def tokenize_and_pad( s: str, vocab, is_bos: bool = True, prefill_lengths: Optional[List[int]] = None, max_prefill_length: Optional[int] = None, jax_padding: bool = True, ) -> Tuple[Union[jax.Array, np.ndarray], int]: """Tokenize and pads a string. Args: s: String to tokenize. vocab: Vocabulary...
Tokenize and pads a string. Args: s: String to tokenize. vocab: Vocabulary to tokenize with. is_bos: Whether or not this is the beginning of a sequence. Default to yes as prefill is typically used when beginning sequences. prefill_lengths: Buckets to pad the sequence to for static compilation. ...
tokenize_and_pad
python
xjdr-alt/entropix
entropix/token_utils.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/token_utils.py
Apache-2.0
def pad_tokens( tokens: np.ndarray, bos_id: int, pad_id: int, is_bos: bool = True, prefill_lengths: Optional[List[int]] = None, max_prefill_length: Optional[int] = None, jax_padding: bool = True, ) -> Tuple[Union[jax.Array, np.ndarray], int]: """Pads tokens to the nearest prefill length that is equal to...
Pads tokens to the nearest prefill length that is equal to or greater than the token length. Args: tokens: Tokens. bos_id: Bos ID. pad_id: Pad ID. is_bos: Add a beginning of sequence token if this is ture. prefill_lengths: Buckets to pad the sequence to for static compilation. max_prefil...
pad_tokens
python
xjdr-alt/entropix
entropix/token_utils.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/token_utils.py
Apache-2.0
def process_result_tokens( tokenizer: Tokenizer, slot: int, slot_max_length: int, result_tokens: ResultTokens, complete: np.ndarray, is_client_side_tokenization: bool = False, debug: bool = False, ) -> Tuple[List[ReturnSample], np.ndarray]: """Processes a result tokens into a list of strings, handling m...
Processes a result tokens into a list of strings, handling multiple samples. Args: slot: The slot at which to draw tokens from. slot_max_length: Max length for a sample in the slot. result_tokens: The tokens to access by slot. complete: Array representing the completion status of each sample in t...
process_result_tokens
python
xjdr-alt/entropix
entropix/token_utils.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/token_utils.py
Apache-2.0
def is_byte_token(s: str) -> bool: """Returns True if s is a byte string like "<0xAB>".""" # Bytes look like "<0xAB>". if len(s) != 6 or s[0:3] != "<0x" or s[-1] != ">": return False return True
Returns True if s is a byte string like "<0xAB>".
is_byte_token
python
xjdr-alt/entropix
entropix/token_utils.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/token_utils.py
Apache-2.0
def create_mesh(device_count: int) -> jax.sharding.Mesh: """Creates device mesh for distributed execution.""" devices = jax.devices() mesh_shape = (device_count, 1) device_mesh = jax.experimental.mesh_utils.create_device_mesh(mesh_shape) return jax.sharding.Mesh(device_mesh, ("mp", "fsdp"))
Creates device mesh for distributed execution.
create_mesh
python
xjdr-alt/entropix
entropix/weights.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/weights.py
Apache-2.0
def load_weights( ckpt_dir: Path, model_params, weight_config: Optional[WeightConfig] = None ) -> Tuple[XfmrWeights, jax.sharding.Mesh]: """Load and shard model weights across devices.""" weight_config = weight_config or WeightConfig() mesh = create_mesh(jax.device_count()) w = {} layer_weights = [] for...
Load and shard model weights across devices.
load_weights
python
xjdr-alt/entropix
entropix/weights.py
https://github.com/xjdr-alt/entropix/blob/master/entropix/weights.py
Apache-2.0
def aggregate_results( single_eval_results: list[SingleEvalResult], default_stats: tuple[str] = ("mean", "std"), name2stats: dict[str, tuple[str]] | None = None, ) -> EvalResult: """ Aggregate results from multiple evaluations into a single EvalResult. """ name2stats = name2stats or {} name2values = def...
Aggregate results from multiple evaluations into a single EvalResult.
aggregate_results
python
xjdr-alt/entropix
evals/common.py
https://github.com/xjdr-alt/entropix/blob/master/evals/common.py
Apache-2.0
def map_with_progress(f: callable, xs: list[Any], num_threads: int = 50): """ Apply f to each element of xs, using a ThreadPool, and show progress. """ if os.getenv("debug"): return list(map(f, tqdm(xs, total=len(xs)))) else: with ThreadPool(min(num_threads, len(xs))) as pool: return list(tqdm(p...
Apply f to each element of xs, using a ThreadPool, and show progress.
map_with_progress
python
xjdr-alt/entropix
evals/common.py
https://github.com/xjdr-alt/entropix/blob/master/evals/common.py
Apache-2.0
def message_to_html(message: Message) -> str: """ Generate HTML snippet (inside a <div>) for a message. """ return jinja_env.from_string(_message_template).render( role=message["role"], content=message["content"], variant=message.get("variant", None), )
Generate HTML snippet (inside a <div>) for a message.
message_to_html
python
xjdr-alt/entropix
evals/common.py
https://github.com/xjdr-alt/entropix/blob/master/evals/common.py
Apache-2.0
def make_report(eval_result: EvalResult) -> str: """ Create a standalone HTML report from an EvalResult. """ return jinja_env.from_string(_report_template).render( score=eval_result.score, metrics=eval_result.metrics, htmls=eval_result.htmls, )
Create a standalone HTML report from an EvalResult.
make_report
python
xjdr-alt/entropix
evals/common.py
https://github.com/xjdr-alt/entropix/blob/master/evals/common.py
Apache-2.0
def make_report_from_example_htmls(htmls: list[str]): """ Create a standalone HTML report from a list of example htmls """ return jinja_env.from_string(_report_template).render( score=None, metrics={}, htmls=htmls )
Create a standalone HTML report from a list of example htmls
make_report_from_example_htmls
python
xjdr-alt/entropix
evals/common.py
https://github.com/xjdr-alt/entropix/blob/master/evals/common.py
Apache-2.0
def normalize_response(response: str) -> str: """ Normalize the response by removing markdown and LaTeX formatting that may prevent a match. """ return ( response.replace("**", "") .replace("$\\boxed{", "") .replace("}$", "") .replace("\\$", "") .replace("$\\text{", "") .replace("$", ""...
Normalize the response by removing markdown and LaTeX formatting that may prevent a match.
normalize_response
python
xjdr-alt/entropix
evals/common.py
https://github.com/xjdr-alt/entropix/blob/master/evals/common.py
Apache-2.0
def _align_bags(predicted: List[Set[str]], gold: List[Set[str]]) -> List[float]: """ Takes gold and predicted answer sets and first finds the optimal 1-1 alignment between them and gets maximum metric values over all the answers. """ scores = np.zeros([len(gold), len(predicted)]) for gold_index, gold_item i...
Takes gold and predicted answer sets and first finds the optimal 1-1 alignment between them and gets maximum metric values over all the answers.
_align_bags
python
xjdr-alt/entropix
evals/drop_eval.py
https://github.com/xjdr-alt/entropix/blob/master/evals/drop_eval.py
Apache-2.0
def get_drop_metrics( predicted: Union[str, List[str], Tuple[str, ...]], gold: Union[str, List[str], Tuple[str, ...]], ) -> Tuple[float, float]: """ Takes a predicted answer and a gold answer (that are both either a string or a list of strings), and returns exact match and the DROP F1 metric for the predictio...
Takes a predicted answer and a gold answer (that are both either a string or a list of strings), and returns exact match and the DROP F1 metric for the prediction. If you are writing a script for evaluating objects in memory (say, the output of predictions during validation, or while training), this is the fu...
get_drop_metrics
python
xjdr-alt/entropix
evals/drop_eval.py
https://github.com/xjdr-alt/entropix/blob/master/evals/drop_eval.py
Apache-2.0
def answer_json_to_strings(answer: Dict[str, Any]) -> Tuple[Tuple[str, ...], str]: """ Takes an answer JSON blob from the DROP data release and converts it into strings used for evaluation. """ if "number" in answer and answer["number"]: return tuple([str(answer["number"])]), "number" elif "spans" in an...
Takes an answer JSON blob from the DROP data release and converts it into strings used for evaluation.
answer_json_to_strings
python
xjdr-alt/entropix
evals/drop_eval.py
https://github.com/xjdr-alt/entropix/blob/master/evals/drop_eval.py
Apache-2.0
def evaluate_functional_correctness( sample: dict[str, str], completions: list[str], n_workers: int = 4, timeout: float = 3.0, ): """ Evaluates the functional correctness of generated samples, and writes results to f"{sample_file}_results.jsonl.gz" """ import copy # Check the generated samples agai...
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/humaneval_eval.py
https://github.com/xjdr-alt/entropix/blob/master/evals/humaneval_eval.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 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
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
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
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 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
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
def test_load_and_run_multi_agent_a2a_sync(agent_framework: AgentFramework) -> None: """Tests that an agent contacts another using A2A using the sync adapter tool. Note that there is an issue when using Google ADK: https://github.com/google/adk-python/pull/566 """ if agent_framework in [ # asyn...
Tests that an agent contacts another using A2A using the sync 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_sync
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_agent_serving_and_communication(test_port): """This test can be refactored to remove the need for multiproc, once we have support for control of the uvicorn server.""" # Start the agent in a subprocess proc = multiprocessing.Process(target=run_agent, args=(test_port,), daemon=True) proc.s...
This test can be refactored to remove the need for multiproc, once we have support for control of the uvicorn server.
test_agent_serving_and_communication
python
mozilla-ai/any-agent
tests/integration/test_serve_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/integration/test_serve_agent.py
Apache-2.0
def test_evaluate_runs_all_evaluators( evaluation_case: EvaluationCase, agent_trace: AgentTrace ) -> None: """This unit test checks that all evaluators are called when evaluating a trace.""" #### Set up the mocks for the evaluators so that we don't actually call LLMs. mock_checkpoint_evaluate = MagicMoc...
This unit test checks that all evaluators are called when evaluating a trace.
test_evaluate_runs_all_evaluators
python
mozilla-ai/any-agent
tests/unit/evaluation/test_evaluate.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/evaluation/test_evaluate.py
Apache-2.0
def test_evaluate_when_no_final_output( evaluation_case: EvaluationCase, agent_trace: AgentTrace ) -> None: """This unit test checks that the hypothesis and qa evaluators are not called when there is no final output.""" #### Set up the mocks for the evaluators so that we don't actually call LLMs. mock_c...
This unit test checks that the hypothesis and qa evaluators are not called when there is no final output.
test_evaluate_when_no_final_output
python
mozilla-ai/any-agent
tests/unit/evaluation/test_evaluate.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/evaluation/test_evaluate.py
Apache-2.0
def test_trace_evaluation_result_score_calculation(agent_trace: AgentTrace) -> None: """Test that the score property of TraceEvaluationResult correctly calculates the ratio of passed points to total points.""" # Create evaluation results with different point values and pass status checkpoint_results = [ ...
Test that the score property of TraceEvaluationResult correctly calculates the ratio of passed points to total points.
test_trace_evaluation_result_score_calculation
python
mozilla-ai/any-agent
tests/unit/evaluation/test_evaluate.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/evaluation/test_evaluate.py
Apache-2.0
def create_agent_with_model_args(framework: AgentFramework) -> AnyAgent: """Helper function to create an agent with test model arguments""" return AnyAgent.create( framework, AgentConfig( model_id="gpt-4o", model_args={ "temperature": TEST_TEMPERATURE, ...
Helper function to create an agent with test model arguments
create_agent_with_model_args
python
mozilla-ai/any-agent
tests/unit/frameworks/test_any_agent.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/frameworks/test_any_agent.py
Apache-2.0
def test_get_agent_card_with_explicit_skills(agent_framework: AgentFramework) -> None: """Test that when skills are explicitly provided in A2AServingConfig, they are used instead of inferring from tools.""" agent = MagicMock() agent.config = AgentConfig(model_id="foo", description="test agent") agent.fr...
Test that when skills are explicitly provided in A2AServingConfig, they are used instead of inferring from tools.
test_get_agent_card_with_explicit_skills
python
mozilla-ai/any-agent
tests/unit/serving/test_agent_card.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/serving/test_agent_card.py
Apache-2.0
def test_bad_functions(agent_framework: AgentFramework) -> None: """Test the verify_callable function with various bad functions.""" # Test missing return type def missing_return_type(foo: str): # type: ignore[no-untyped-def] """Docstring for foo.""" return foo with pytest.raises(Valu...
Test the verify_callable function with various bad functions.
test_bad_functions
python
mozilla-ai/any-agent
tests/unit/tools/test_unit_wrappers.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/test_unit_wrappers.py
Apache-2.0
async def test_agno_client_session_timeout_passed(): """Test that client_session_timeout_seconds parameter is properly passed to AgnoMCPTools (STDIO only).""" custom_timeout = 15 stdio_params = MCPStdio( command="echo", args=["test"], client_session_timeout_seconds=custom_timeout, ...
Test that client_session_timeout_seconds parameter is properly passed to AgnoMCPTools (STDIO only).
test_agno_client_session_timeout_passed
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_agno_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_agno_mcp.py
Apache-2.0
async def test_langchain_client_session_timeout_passed(): """Test that client_session_timeout_seconds parameter is properly passed to LangChain ClientSession (STDIO and SSE).""" custom_timeout = 15.0 stdio_params = MCPStdio( command="echo", args=["test"], client_session_timeout_secon...
Test that client_session_timeout_seconds parameter is properly passed to LangChain ClientSession (STDIO and SSE).
test_langchain_client_session_timeout_passed
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_langchain_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_langchain_mcp.py
Apache-2.0
async def test_llamaindex_client_session_timeout_passed(): """Test that client_session_timeout_seconds parameter is properly passed to LlamaIndex BasicMCPClient (STDIO only).""" custom_timeout = 15.0 stdio_params = MCPStdio( command="echo", args=["test"], client_session_timeout_secon...
Test that client_session_timeout_seconds parameter is properly passed to LlamaIndex BasicMCPClient (STDIO only).
test_llamaindex_client_session_timeout_passed
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_llama_index_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_llama_index_mcp.py
Apache-2.0
def test_openai_mcpsse( mcp_sse_params_no_tools: MCPSse, ) -> None: """This is a test kept for legacy purposes.""" agent_config = AgentConfig(model_id="gpt-4o", tools=[mcp_sse_params_no_tools]) agent = AnyAgent.create("openai", agent_config) servers = agent._mcp_servers assert servers ser...
This is a test kept for legacy purposes.
test_openai_mcpsse
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_openai_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_openai_mcp.py
Apache-2.0
def test_openai_client_session_timeout_passed(): """Test that client_session_timeout_seconds parameter is properly passed to OpenAI MCPServerStdio and MCPServerSse.""" custom_timeout = 15.0 stdio_params = MCPStdio( command="echo", args=["test"], client_session_timeout_seconds=custom_...
Test that client_session_timeout_seconds parameter is properly passed to OpenAI MCPServerStdio and MCPServerSse.
test_openai_client_session_timeout_passed
python
mozilla-ai/any-agent
tests/unit/tools/mcp/test_unit_openai_mcp.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tools/mcp/test_unit_openai_mcp.py
Apache-2.0
def test_set_llm_input_missing_fields() -> None: """It should not fail when missing fields.""" span = MagicMock() _set_llm_input([Message(role="user")], span) span.set_attribute.assert_called_with( "gen_ai.input.messages", '[{"role": "user", "content": null}]' )
It should not fail when missing fields.
test_set_llm_input_missing_fields
python
mozilla-ai/any-agent
tests/unit/tracing/instrumentation/test_unit_agno_instrumentation.py
https://github.com/mozilla-ai/any-agent/blob/master/tests/unit/tracing/instrumentation/test_unit_agno_instrumentation.py
Apache-2.0