Skip to content

[FEAT][Implement MCP into agent.py] #819

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 176 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
176 commits
Select commit Hold shift + click to select a range
13f81a6
Checkpoint before assistant change: Improves project setup
Apr 17, 2025
631ad71
feat: enhance MCP integration in Swarms with full testing support
ascender1729 Apr 17, 2025
9355f06
chore: add langchain-openai and libxcrypt to support testing environment
Apr 17, 2025
9859fcf
feat: implement interactive multi-agent system with MCP integration
ascender1729 Apr 17, 2025
d7c8616
feat: create MCP server using FastMCP and set up integration test
ascender1729 Apr 17, 2025
6e2d79d
chore: rename workflow button to 'Run MCP Server' in .replit config
Apr 17, 2025
d710308
fix: improve MCP server and test integration with robust error handling
ascender1729 Apr 17, 2025
2e2ebc4
fix: update MCP server and client integration based on FastMCP and Sw…
ascender1729 Apr 17, 2025
10e056a
test: enhance MCP integration test with tool discovery and user guidance
ascender1729 Apr 17, 2025
6954a9a
feat: set up multiple MCP servers and integrate with multi-agent test…
ascender1729 Apr 17, 2025
1ac9c57
fix: correct port configuration for MCP servers to match FastMCP API
ascender1729 Apr 17, 2025
4e457e3
fix: correct MCP server configuration to comply with FastMCP API
ascender1729 Apr 17, 2025
c4c81a4
feat: set up interactive multi-agent MCP test environment with multi-…
ascender1729 Apr 17, 2025
04ed17d
chore: configure MCP servers to run in parallel with proper networking
ascender1729 Apr 17, 2025
e051e2d
fix: resolve FastMCP server configuration and runtime workflow issues
ascender1729 Apr 17, 2025
f495299
fix: update server configuration and add graceful shutdown to integra…
ascender1729 Apr 17, 2025
64c7952
fix: finalize MCP server configurations and resolve model warnings
ascender1729 Apr 17, 2025
a418c6f
feat: enhance test integration with timestamped logging and request w…
ascender1729 Apr 17, 2025
d51b450
chore: add test environment log for multi-agent system
Apr 17, 2025
ef2abb0
fix: update MCP server config and add API key support
ascender1729 Apr 17, 2025
7c00cf1
feat: support both Swarms and OpenAI API keys in integration test
ascender1729 Apr 17, 2025
2787e96
chore: add test log for financial statement analysis environment
Apr 17, 2025
61f9256
fix: adjust agent output formatting and math server config
ascender1729 Apr 17, 2025
cb85838
fix: handle user input correctly in Multi-Agent MCP test environment
Apr 17, 2025
3fe1ec1
fix: resolve MCP integration and agent response handling issues
ascender1729 Apr 17, 2025
d30ca92
chore: set model name to 'gpt-4o-mini' in server and test configs
ascender1729 Apr 17, 2025
db5ccd4
feat: implement multi-agent MCP architecture with math tools
ascender1729 Apr 17, 2025
f854c8a
docs: add README for MCP integration and implementation summary
ascender1729 Apr 17, 2025
0761165
fix: enhance MCP integration with robust error handling and task cove…
ascender1729 Apr 17, 2025
a64dab8
feat: implement multi-agent MCP system with multiple server instances
ascender1729 Apr 17, 2025
db37461
chore: set explicit model configuration for all agents
ascender1729 Apr 17, 2025
9faf83b
fix: set model_name='gpt-4o-mini' for all agents to suppress warnings
ascender1729 Apr 17, 2025
a877cc8
style: enhance output formatting in multi-agent architecture
ascender1729 Apr 17, 2025
c75fa97
fix: resolve LiteLLM initialization issues in math and calc servers
ascender1729 Apr 17, 2025
885a50c
fix: debug MCP server setup and enhance response handling logic
ascender1729 Apr 17, 2025
3da7bd6
fix: resolve MCP server response handling and LiteLLM output issues
ascender1729 Apr 17, 2025
3273747
fix: correct imports and server setup in math and calc servers
ascender1729 Apr 17, 2025
f07ca75
fix: refine MCP server configuration for multi-agent multi-server rou…
ascender1729 Apr 17, 2025
c8954eb
fix: resolve numerical parsing error in multi-agent calculation logic
Apr 17, 2025
60d5145
fix: correct MCP server port binding and test response logic
ascender1729 Apr 17, 2025
cb6eca6
fix: update MCP server config and test script for single-agent multi-…
ascender1729 Apr 17, 2025
86cb09a
chore: restore repository state to commit 8d1d22d for stability
ascender1729 Apr 17, 2025
757ad59
chore: apply config changes after restoring to checkpoint 8d1d22d
ascender1729 Apr 17, 2025
9e62c12
test: rewrite MCP integration tests from user perspective
ascender1729 Apr 17, 2025
8d079f6
test: improve multi-agent MCP testing workflow using pytest
Apr 17, 2025
a8ad884
feat: implement mock MCP server and multi-agent system with full inte…
ascender1729 Apr 17, 2025
e8cd786
chore: add detailed logging to math problem solver for model usage an…
Apr 17, 2025
3899a22
fix: correct MCP agent response handling and model configuration
ascender1729 Apr 17, 2025
9436375
fix: update mock multi-agent system to route requests to single calcu…
ascender1729 Apr 17, 2025
6bb6136
docs: add reference file listing supported math problem types
Apr 17, 2025
40cd524
fix: align math server tools and agent prompt with available capabili…
ascender1729 Apr 17, 2025
ae4b0b5
feat: add basic multi-agent math problem solver for arithmetic operat…
Apr 17, 2025
80146d8
docs: refine math agent system prompt to clarify capabilities and lim…
Apr 17, 2025
f69682f
chore: add detailed logging to MCP server for end-to-end data flow vi…
ascender1729 Apr 17, 2025
26ef5ed
feat: add Calculator agent to multi-agent system for basic math solving
Apr 17, 2025
0f787de
feat: add stock market analysis agent and corresponding server
ascender1729 Apr 17, 2025
50a11f3
fix: correct MathAgent initialization by removing extra argument
ascender1729 Apr 17, 2025
b172ce0
feat: add input validation to MathAgent for math-specific queries
ascender1729 Apr 17, 2025
63bbc34
fix: update stock server setup and multi-agent routing logic
ascender1729 Apr 17, 2025
b9ddc14
feat: enhance agent responses to describe supported capabilities
ascender1729 Apr 17, 2025
610064b
fix: update stock analyst agent logic to handle financial queries pro…
ascender1729 Apr 17, 2025
4b12eca
style: enhance multi-agent output formatting with clear visual separa…
ascender1729 Apr 17, 2025
7febc47
chore: add initial structure for examples, documentation, and tests
ascender1729 Apr 17, 2025
b8dda6f
feat: add advanced technical use case examples for real-world scenarios
ascender1729 Apr 17, 2025
0a3d619
docs: add detailed MCP integration summary in markdown format
ascender1729 Apr 17, 2025
c16448f
chore: add summary markdown to .gitignore
ascender1729 Apr 17, 2025
fd723e7
fix: correct port binding in MCP stock server implementation
ascender1729 Apr 17, 2025
7ec5796
chore: update cleanup and publish script
ascender1729 Apr 18, 2025
f7055a6
chore: update cleanup and publish script
ascender1729 Apr 18, 2025
be9d06e
chore: remove replit.nix and attached_assets directory
ascender1729 Apr 18, 2025
24e6d1d
test(mcp): improve Replit config and add workflow for interactive MCP…
Apr 18, 2025
28186aa
feat(demo): add presentation script showcasing end-to-end MCP integra…
ascender1729 Apr 18, 2025
868f096
feat(agent): run tasks in parallel to prevent duplication across agents
Apr 18, 2025
9666c17
fix(agent): ensure tasks are routed only to relevant agents based on …
ascender1729 Apr 18, 2025
e7e72b2
style(response): simplify output to display only final agent answer a…
ascender1729 Apr 18, 2025
da6ba0d
feat(math): enhance agent response handling and improve user input er…
Apr 18, 2025
07f4c65
style(agent): simplify output format by removing agent distinction in…
ascender1729 Apr 18, 2025
702d9f2
feat(stock-server): update stock server to use FastMCP for better per…
ascender1729 Apr 18, 2025
cb6aae8
fix(mcp): update FastMCP server configuration in mock_stock_server.py
ascender1729 Apr 18, 2025
4284eab
docs: add presentation script explaining MCP integration with mock mu…
ascender1729 Apr 18, 2025
049869e
docs(presentation): update script with detailed MCP integration infor…
ascender1729 Apr 18, 2025
7c550d9
fix(mcp): improve MCP client response handling and display formatting
ascender1729 Apr 18, 2025
f4a134e
fix(agent): improve agent's response and handling for price inquiries
Apr 18, 2025
66ccd9b
fix(server): correct FastMCP configuration for price query handling
ascender1729 Apr 18, 2025
f52bcbc
fix(server): resolve FastMCP server initialization issues in mock_sto…
ascender1729 Apr 18, 2025
8b01167
feat(agent): include agent names in capability responses for clarity
ascender1729 Apr 18, 2025
a228faf
fix(stock): update stock server config to handle price queries correctly
ascender1729 Apr 18, 2025
c4eb44e
fix(agent): standardize agent initialization to match example pattern
ascender1729 Apr 19, 2025
eef1a53
Restored to 'eae5d510b502852f51ba86a44012b42d892fd643'
ascender1729 Apr 19, 2025
eedcab4
fix(mcp): implement proper client-side usage for MCP client integration
ascender1729 Apr 19, 2025
2cdf71e
fix(agent): separate server and client code for proper agent initiali…
Apr 19, 2025
cc56f43
fix(mcp): update architecture to initialize agents on the client side…
ascender1729 Apr 19, 2025
824dea0
feat(mcp): improve server connection speed by integrating FastMCP lib…
Apr 20, 2025
41ccffc
feat(mcp): update integration to use FastMCP and support FastMCP in A…
ascender1729 Apr 20, 2025
fe7faf9
docs(setup): add README with setup instructions, examples, and API de…
Apr 20, 2025
77324e6
feat(agent): add MCP test agent prompts and update client with server…
ascender1729 Apr 20, 2025
977623a
refactor(mcp): simplify client to use math agent only, remove finance…
ascender1729 Apr 20, 2025
b35ace1
feat(prompts): add MATH_AGENT_PROMPT to agent_prompts.py
ascender1729 Apr 20, 2025
0654a29
fix(math-agent): refine calculations by removing max_loops limit and …
Apr 20, 2025
802a489
fix(mcp): update server setup and add missing math agent prompt defin…
ascender1729 Apr 20, 2025
725f304
fix(agent_prompts): remove duplicate MATH_AGENT_PROMPT definition and…
ascender1729 Apr 20, 2025
ba76575
fix(agent): update MATH_AGENT_PROMPT import path and ensure correct u…
ascender1729 Apr 20, 2025
552f5cc
fix(prompts): resolve MATH_AGENT_PROMPT import by updating to source …
ascender1729 Apr 20, 2025
242cfcd
fix(agent): re-add mcp_servers parameter and fix NotRequired import f…
Apr 20, 2025
1a075ca
fix(mcp): restore mcp_servers attribute and update typing imports for…
ascender1729 Apr 20, 2025
8919dc6
fix(imports): correct fastmcp import to match library v2.0 changes
Apr 20, 2025
9cd53bb
fix(mcp): update FastMCP imports and server configuration for compati…
ascender1729 Apr 20, 2025
ddd1b60
fix(mcp): update fastmcp imports to v2.x for client-based transports
ascender1729 Apr 20, 2025
c136911
fix(agent): resolve module import errors and enable MCP server commun…
Apr 20, 2025
d7e8849
fix(mcp): update imports to use mcp package and fix FastMCP server tr…
ascender1729 Apr 20, 2025
9207a1b
fix(agent): resolve import errors and compatibility issues in MCP int…
Apr 20, 2025
9a682a2
fix(mcp): update imports and fix server transport args for MCP integr…
ascender1729 Apr 20, 2025
cb136d7
feat(math): integrate gpt-4o-mini model and fix streaming issues in m…
Apr 20, 2025
a55589f
feat(agent): integrate MCP execution flow and add gpt-4o-mini model s…
ascender1729 Apr 20, 2025
b4fc45e
fix(agent): resolve indentation error in apply_response_filters method
ascender1729 Apr 20, 2025
e34b446
fix(agent): resolve math agent error by fixing streaming response han…
Apr 20, 2025
96c2669
fix(mcp): update server and client configurations and agent initializ…
ascender1729 Apr 20, 2025
fd50b02
fix(math-agent): await coroutine and correct Fast-MCP endpoint URL
Apr 20, 2025
58e2f5c
fix(mcp): resolve server and async coroutine handling issues
ascender1729 Apr 20, 2025
effa590
fix(agent): resolve indentation error and typo in add_response_filter…
Apr 20, 2025
0a028ce
fix(agent): correct indentation and typo in add_response_filter method
ascender1729 Apr 20, 2025
b8c712c
fix(calculation): restore missing import and fix coroutine return in …
Apr 20, 2025
901f868
fix(mcp): restore imports and fix execution flow in MCP integration
ascender1729 Apr 20, 2025
fc91b11
fix(agent): resolve coroutine issue in batch_mcp_flow function
Apr 20, 2025
0ca3f03
fix(mcp): correct async flow and server port configuration for MCP in…
ascender1729 Apr 20, 2025
3e159f5
chore(agent): add logging for math agent initialization and query han…
Apr 20, 2025
e730e57
fix(mcp): resolve async coroutine warning by awaiting batch_mcp_flow …
ascender1729 Apr 20, 2025
f8d422f
fix(math): resolve calculation error by fixing async handling in mcp_…
Apr 20, 2025
ff19580
fix(mcp): implement proper async handling for MCP integration
ascender1729 Apr 20, 2025
9eeb625
fix(agent): resolve communication bug by correcting async operations …
Apr 20, 2025
47e509e
fix(agent): resolve unterminated string literal in add_tool method an…
ascender1729 Apr 20, 2025
f5c2de1
fix(agent): resolve unterminated docstring in add_tool method
ascender1729 Apr 20, 2025
248a943
fix(agent): resolve unterminated docstring in add_tool method
ascender1729 Apr 20, 2025
c1af0f2
chore(mcp): update integration to improve efficiency and error handling
ascender1729 Apr 20, 2025
2802a0a
chore(mcp): update FastMCP server initialization in mock_math_server.py
ascender1729 Apr 20, 2025
2f1c779
Revert "chore: remove replit.nix"
ascender1729 Apr 20, 2025
b398753
refactor: simplify math agent prompt and client output
ascender1729 Apr 20, 2025
eb9d337
Update MCP integration: Clean up server and client code, improve erro…
ascender1729 Apr 20, 2025
dba38f2
Update agent.py and add project structure documentation
ascender1729 Apr 20, 2025
10936b5
swarms agent in rust docs
kyegomez Apr 17, 2025
0229e65
docs -- contributing to docs
kyegomez Apr 17, 2025
24482a9
clean up docs for contributing docs
kyegomez Apr 17, 2025
8e6bf76
contributors
kyegomez Apr 17, 2025
81affd6
contributing custom tools docs
kyegomez Apr 17, 2025
55965be
docs formatting contributing to docs
kyegomez Apr 17, 2025
9e23325
formatting output + create agent + agent benchmark
kyegomez Apr 20, 2025
c490e82
Checkpoint before assistant change: Improved a math calculator
Apr 20, 2025
d46da9c
Checkpoint before assistant change: Fixes a math calculator error
Apr 20, 2025
925709d
fix(mcp): resolve client initialization and update server configurati…
ascender1729 Apr 20, 2025
d75bbed
test(mcp): streamline testing workflows and add new tests for mcp_int…
Apr 20, 2025
1a84b24
chore(mcp): update server/client implementations and configure workflows
ascender1729 Apr 20, 2025
16a2321
fix(mcp): fix indentation error in mcp_integration.py
ascender1729 Apr 20, 2025
c7206ba
feat(calculator): add basic math agent for addition, multiplication, …
Apr 20, 2025
4b6f9a5
feat(mcp): integrate natural language interface for improved agent in…
ascender1729 Apr 20, 2025
d9f1144
feat(calculator): add math calculator with error handling and example…
Apr 20, 2025
ea66e78
fix(mcp): resolve async execution flow issues in client and agent
ascender1729 Apr 20, 2025
a612352
fix(calculator): update math calculator prompt, enhance error handlin…
Apr 20, 2025
f61ada7
fix(mcp): resolve indentation error in mcp_client.py
ascender1729 Apr 20, 2025
616c575
fix(mcp): resolve server connection errors and improve error handling
Apr 20, 2025
1f54917
fix(mcp): update server parameters and connection test for correct SS…
ascender1729 Apr 20, 2025
8fd41d2
fix(mcp): update server parameters to resolve SSE connection error
ascender1729 Apr 20, 2025
812115a
refactor(math): simplify math operations and improve logging in mcp_c…
Apr 20, 2025
b567b30
fix(mcp): update server parameters to resolve connection error in mcp…
ascender1729 Apr 20, 2025
51bb308
fix(mcp): correct MCPServerSseParams initialization in mcp_client.py
ascender1729 Apr 20, 2025
e8912f3
updated example
ascender1729 Apr 21, 2025
ee9230f
Update MCP integration with improved error handling and testing
ascender1729 Apr 21, 2025
1a96821
chore: remove unnecessary files (mcp_integration_summary.md, project_…
ascender1729 Apr 22, 2025
3aad5ac
Delete attached_assets directory
ascender1729 Apr 22, 2025
3383b59
docs: simplify MCP integration documentation to focus on basic agent …
ascender1729 Apr 22, 2025
c3d3ee9
Merge branch 'feature/mcp-integration' of https://github.com/ascender…
ascender1729 Apr 22, 2025
ffaeef8
Merge branch 'master' into feature/mcp-integration
ascender1729 Apr 22, 2025
4464c90
Update .gitignore
ascender1729 Apr 23, 2025
6d16ea5
Update __init__.py
ascender1729 Apr 23, 2025
1c98fbb
Update mkdocs.yml
ascender1729 Apr 23, 2025
9e5f755
Update agent_prompts.py
ascender1729 Apr 23, 2025
9806d5e
Update pyproject.toml
ascender1729 Apr 23, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -404,4 +404,3 @@ flycheck_*.el

# network security
/network-security.data

284 changes: 284 additions & 0 deletions agent_exec_benchmark.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
import asyncio
import concurrent.futures
import json
import os
import psutil

Check failure

Code scanning / Pyre

Undefined import Error

Undefined import [21]: Could not find a module corresponding to import psutil.
import datetime
from pathlib import Path
from typing import List, Dict, Any, Optional
from swarms.structs.agent import Agent
from loguru import logger

Check failure

Code scanning / Pyre

Undefined import Error

Undefined import [21]: Could not find a module corresponding to import loguru.


class AgentBenchmark:
def __init__(
self,
num_iterations: int = 5,
output_dir: str = "benchmark_results",
):
self.num_iterations = num_iterations
self.output_dir = Path(output_dir)
self.output_dir.mkdir(exist_ok=True)

# Use process pool for CPU-bound tasks
self.process_pool = concurrent.futures.ProcessPoolExecutor(
max_workers=min(os.cpu_count(), 4)

Check failure

Code scanning / Pyre

Incompatible parameter type Error

Incompatible parameter type [6]: In call min, for 1st positional argument, expected Variable[SupportsRichComparisonT (bound to Union[SupportsDunderGT[typing.Any], SupportsDunderLT[typing.Any]])] but got Optional[int].
)

# Use thread pool for I/O-bound tasks
self.thread_pool = concurrent.futures.ThreadPoolExecutor(
max_workers=min(os.cpu_count() * 2, 8)

Check failure

Code scanning / Pyre

Unsupported operand Error

Unsupported operand [58]: \* is not supported for operand types Optional[int] and int.
)

self.default_queries = [
"Conduct an analysis of the best real undervalued ETFs",
"What are the top performing tech stocks this quarter?",
"Analyze current market trends in renewable energy sector",
"Compare Bitcoin and Ethereum investment potential",
"Evaluate the risk factors in emerging markets",
]

self.agent = self._initialize_agent()
self.process = psutil.Process()

# Cache for storing repeated query results
self._query_cache = {}

def _initialize_agent(self) -> Agent:
return Agent(
agent_name="Financial-Analysis-Agent",
agent_description="Personal finance advisor agent",
# system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
max_loops=1,
model_name="gpt-4o-mini",
dynamic_temperature_enabled=True,
interactive=False,
)

def _get_system_metrics(self) -> Dict[str, float]:
# Optimized system metrics collection
return {
"cpu_percent": self.process.cpu_percent(),
"memory_mb": self.process.memory_info().rss / 1024 / 1024,
}

def _calculate_statistics(
self, values: List[float]
) -> Dict[str, float]:
if not values:
return {}

sorted_values = sorted(values)
n = len(sorted_values)
mean_val = sum(values) / n

stats = {
"mean": mean_val,
"median": sorted_values[n // 2],
"min": sorted_values[0],
"max": sorted_values[-1],
}

# Only calculate stdev if we have enough values
if n > 1:
stats["std_dev"] = (
sum((x - mean_val) ** 2 for x in values) / n
) ** 0.5

return {k: round(v, 3) for k, v in stats.items()}

async def process_iteration(
self, query: str, iteration: int
) -> Dict[str, Any]:
"""Process a single iteration of a query"""
try:
# Check cache for repeated queries
cache_key = f"{query}_{iteration}"
if cache_key in self._query_cache:
return self._query_cache[cache_key]

iteration_start = datetime.datetime.now()
pre_metrics = self._get_system_metrics()

# Run the agent
try:
self.agent.run(query)
success = True
except Exception as e:
str(e)
success = False

execution_time = (
datetime.datetime.now() - iteration_start
).total_seconds()
post_metrics = self._get_system_metrics()

result = {
"execution_time": execution_time,
"success": success,
"pre_metrics": pre_metrics,
"post_metrics": post_metrics,
"iteration_data": {
"iteration": iteration + 1,
"execution_time": round(execution_time, 3),
"success": success,
"system_metrics": {
"pre": pre_metrics,
"post": post_metrics,
},
},
}

# Cache the result
self._query_cache[cache_key] = result
return result

except Exception as e:
logger.error(f"Error in iteration {iteration}: {e}")
raise

async def run_benchmark(
self, queries: Optional[List[str]] = None
) -> Dict[str, Any]:
"""Run the benchmark asynchronously"""
queries = queries or self.default_queries
benchmark_data = {
"metadata": {
"timestamp": datetime.datetime.now().isoformat(),
"num_iterations": self.num_iterations,
"agent_config": {
"model_name": self.agent.model_name,
"max_loops": self.agent.max_loops,
},
},
"results": {},
}

async def process_query(query: str):
query_results = {
"execution_times": [],
"system_metrics": [],
"iterations": [],
}

# Process iterations concurrently
tasks = [
self.process_iteration(query, i)
for i in range(self.num_iterations)
]
iteration_results = await asyncio.gather(*tasks)

for result in iteration_results:
query_results["execution_times"].append(
result["execution_time"]
)
query_results["system_metrics"].append(
result["post_metrics"]
)
query_results["iterations"].append(
result["iteration_data"]
)

# Calculate statistics
query_results["statistics"] = {
"execution_time": self._calculate_statistics(
query_results["execution_times"]
),
"memory_usage": self._calculate_statistics(
[
m["memory_mb"]
for m in query_results["system_metrics"]
]
),
"cpu_usage": self._calculate_statistics(
[
m["cpu_percent"]
for m in query_results["system_metrics"]
]
),
}

Check failure

Code scanning / Pyre

Incompatible parameter type Error

Incompatible parameter type [6]: In call dict.\_\_setitem\_\_, for 2nd positional argument, expected List[typing.Any] but got Dict[str, Dict[str, float]].

return query, query_results

# Execute all queries concurrently
query_tasks = [process_query(query) for query in queries]
query_results = await asyncio.gather(*query_tasks)

for query, results in query_results:
benchmark_data["results"][query] = results

return benchmark_data

def save_results(self, benchmark_data: Dict[str, Any]) -> str:
"""Save benchmark results efficiently"""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = (
self.output_dir / f"benchmark_results_{timestamp}.json"
)

# Write results in a single operation
with open(filename, "w") as f:

Check failure

Code scanning / Bearer

Unsanitized dynamic input in file path Error

Unsanitized dynamic input in file path
json.dump(benchmark_data, f, indent=2)

logger.info(f"Benchmark results saved to: {filename}")
return str(filename)

def print_summary(self, results: Dict[str, Any]):
"""Print a summary of the benchmark results"""
print("\n=== Benchmark Summary ===")
for query, data in results["results"].items():
print(f"\nQuery: {query[:50]}...")
stats = data["statistics"]["execution_time"]
print(f"Average time: {stats['mean']:.2f}s")
print(
f"Memory usage (avg): {data['statistics']['memory_usage']['mean']:.1f}MB"
)
print(
f"CPU usage (avg): {data['statistics']['cpu_usage']['mean']:.1f}%"
)

async def run_with_timeout(
self, timeout: int = 300
) -> Dict[str, Any]:
"""Run benchmark with timeout"""
try:
return await asyncio.wait_for(
self.run_benchmark(), timeout
)
except asyncio.TimeoutError:

Check failure

Code scanning / Pyre

Undefined attribute Error

Undefined attribute [16]: Module builtins has no attribute TimeoutError.
logger.error(
f"Benchmark timed out after {timeout} seconds"
)
raise

def cleanup(self):
"""Cleanup resources"""
self.process_pool.shutdown()
self.thread_pool.shutdown()
self._query_cache.clear()


async def main():
try:
# Create and run benchmark
benchmark = AgentBenchmark(num_iterations=1)

# Run benchmark with timeout
results = await benchmark.run_with_timeout(timeout=300)

# Save results
benchmark.save_results(results)

# Print summary
benchmark.print_summary(results)

except Exception as e:
logger.error(f"Benchmark failed: {e}")
finally:
# Cleanup resources
benchmark.cleanup()


if __name__ == "__main__":
# Run the async main function
asyncio.run(main())
Loading
Loading