input string | label int64 | category string | sample_id string |
|---|---|---|---|
cls,
llm: BaseLanguageModel,
chain: LLMChain,
critique_prompt: BasePromptTemplate = CRITIQUE_PROMPT,
revision_prompt: BasePromptTemplate = REVISION_PROMPT,
**kwargs: Any,
) -> "ConstitutionalChain":
"""Create a chain from an LLM."""
critique_chain = LL... | 1 | function_simple | langchain-ai/langchain:libs/langchain/langchain_classic/chains/constitutional_ai/base.py:ConstitutionalChain.from_llm |
ync def test_async_streaming_from_docs(
self, researcher: Agent, simple_task: Task
) -> None:
"""Test async streaming example from documentation."""
crew = Crew(
agents=[researcher],
tasks=[simple_task],
stream=True,
verbose=False,
)
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/test_streaming_integration.py:TestStreamingCrewIntegration.test_async_streaming_from_docs |
GenAIGeminiCreateEmbeddingsBatchJobOperator(
task_id=TASK_ID,
project_id=GCP_PROJECT,
location=GCP_LOCATION,
input_source=TEST_FILE_NAME,
model=EMBEDDING_MODEL,
gemini_api_key=TEST_GEMINI_API_KEY,
gcp_conn... | 1 | test | apache/airflow:providers/google/tests/unit/google/cloud/operators/test_gen_ai.py:TestGenAIGeminiCreateEmbeddingsBatchJobOperator.test_init_results_folder_not_exists_raises_airflow_exception |
deployment
@serve.ingress(fastapi_app)
class EchoRequestID:
@fastapi_app.get("/")
async def root(self, request: Request) -> PlainTextResponse:
return PlainTextResponse(request.headers.get("x-request-id", ""))
else:
@serve.deployment
class Ech... | 0 | test | ray-project/ray:python/ray/serve/tests/test_direct_ingress.py:test_http_request_id |
Start a long-running command asynchronously (synchronous version).
Args:
command (str): The command to execute asynchronously.
thread_id (str): Thread ID for the code interpreter session. Default is "default".
Returns:
str: The task ID and status.
"""... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/llama_index/tools/aws_bedrock_agentcore/code_interpreter/base.py:AgentCoreCodeInterpreterToolSpec.start_command |
, ymax = locations.split(1, dim=-1)
q_xmin = (xmin / per_bin_w).floor().clamp(0, bins_w - 1)
q_ymin = (ymin / per_bin_h).floor().clamp(0, bins_h - 1)
q_xmax = (xmax / per_bin_w).floor().clamp(0, bins_w - 1)
q_ymax = (ymax / per_bin_h).floor().clamp(0, bins_h - 1)
... | 0 | function_simple | huggingface/transformers:src/transformers/models/florence2/modular_florence2.py:Florence2PostProcessor.quantize |
_from_bedrock(message: AIMessage) -> list[types.ContentBlock]:
"""Convert bedrock message content to v1 format."""
out = _convert_to_v1_from_anthropic(message)
content_tool_call_ids = {
block.get("id")
for block in out
if isinstance(block, dict) and block.get("type") == "tool_call"
... | 1 | function_complex | langchain-ai/langchain:libs/core/langchain_core/messages/block_translators/bedrock.py:_convert_to_v1_from_bedrock |
_map_operator()
downstream_op, downstream_op_state = self._mock_operator()
op.output_dependencies = [downstream_op]
topology = {op: op_state, downstream_op: downstream_op_state}
context = self._create_context(backpressure_ratio=2.0)
rm = self._mock_resource_manager()
# H... | 0 | test | ray-project/ray:python/ray/data/tests/test_downstream_capacity_backpressure_policy.py:TestDownstreamCapacityBackpressurePolicy.test_max_bytes_returns_zero_for_high_queue_ratio |
# Define the path for the Parquet file in the tmp_path directory
parquet_file = tmp_path / "sample_data.parquet"
# Write DataFrame to a Parquet file
table = pa.Table.from_pandas(df)
pq.write_table(table, parquet_file)
# Load parquet dataset
parquet_ds = ray.data.read_parquet(str(parquet_file... | 0 | test | ray-project/ray:python/ray/data/tests/test_filter.py:test_filter_with_invalid_expression |
file.aread()
file_data = io.BytesIO(content)
file_data.name = file.filename
logger.info(
f"Uploading file '{file.filename}' to Gemini ({len(content)} bytes)"
)
uploaded_file = await client.aio.files.upload(
... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-files/src/crewai_files/uploaders/gemini.py:GeminiFileUploader.aupload |
_config.num_channels
real_batch_size = batch_size // 2 if self._uses_cfg else batch_size
if decoder_input_ids is None:
decoder_input_ids = torch.full(
(real_batch_size, 1, num_channels), decoder_start_token_id, dtype=torch.long, device=device
... | 0 | function_complex | huggingface/transformers:src/transformers/models/dia/generation_dia.py:DiaGenerationMixin._prepare_decoder_input_ids_for_generation |
redis_conn_id="redis_default",
poll_interval=0.0001,
)
mock_redis_conn().pubsub().get_message.return_value = {
"type": "message",
"channel": b"test",
"data": b"d1",
}
trigger_gen = trigger.run()
task = asyncio.create_task(trig... | 1 | test | apache/airflow:providers/redis/tests/unit/redis/triggers/test_redis_await_message.py:TestAwaitMessageTrigger.test_trigger_run_succeed_with_bytes |
():
self.skipTest(f"image_processor attribute not present in {self.processor_class}")
image_processor = self.get_component("image_processor", max_patches=1024, patch_size={"height": 8, "width": 8})
tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length")
pro... | 0 | test | huggingface/transformers:tests/models/kosmos2_5/test_processor_kosmos2_5.py:Kosmos2_5ProcessorTest.test_image_processor_defaults_preserved_by_image_kwargs |
include_markdown: Whether to include markdown formatting
Returns:
Scraped website content as a string
"""
try:
# Serper API endpoint
api_url = "https://scrape.serper.dev"
# Get API key from environment variable for security
... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/tools/serper_scrape_website_tool/serper_scrape_website_tool.py:SerperScrapeWebsiteTool._run |
self,
key: str,
adapter: BypassAdapter,
strength: float = 1.0,
):
"""
Add an adapter for a specific weight key.
Args:
key: Weight key (e.g., "model.layers.0.self_attn.q_proj.weight")
adapter: The weight adapter (LoRAAdapter, LoKrAdapter... | 1 | function_simple | Comfy-Org/ComfyUI:comfy/weight_adapter/bypass.py:BypassInjectionManager.add_adapter |
# Client without auth token
channel = aiogrpc.insecure_channel(f"localhost:{port}")
stub = reporter_pb2_grpc.LogServiceStub(channel)
request = reporter_pb2.StreamLogRequest(log_file_name="test.log")
# Should fail with UNAUTHENTICATED when trying to iterate
... | 0 | test | ray-project/ray:python/ray/tests/authentication/test_async_grpc_interceptors.py:test_async_streaming_response_without_token_fails |
| None = None
last_challenges: dict[str, dict[str, str]] = {}
for attempt in range(max_retries):
response = await request_func()
if response.status_code != 401:
return response
last_response = response
if auth_scheme is None:
response.raise_for_status... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/a2a/auth/utils.py:retry_on_401 |
_scope_index(self) -> None:
"""Create a BTREE scalar index on the ``scope`` column if not present.
A scalar index lets LanceDB skip a full table scan when filtering by
scope prefix, which is the hot path for ``list_records``,
``get_scope_info``, and ``list_scopes``. The call is best-ef... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/memory/storage/lancedb_storage.py:LanceDBStorage._ensure_scope_index |
dataset, num_rows
)
head_rows = _format_rows_for_repr(head_data, columns)
tail_rows = _format_rows_for_repr(tail_data, columns)
except RayError:
head_rows = []
tail_rows = []
return _build_dataset_ascii_repr_from_rows(
schema=... | 0 | function_simple | ray-project/ray:python/ray/data/_internal/dataset_repr.py:_build_dataset_ascii_repr |
`self.pad` where all images are padded to the maximum image size,
Owlv2 pads an image to square.
"""
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
processed_images_grouped = {}
for shape, stacked_images in grouped_images.... | 0 | function_simple | huggingface/transformers:src/transformers/models/owlv2/modular_owlv2.py:Owlv2ImageProcessorFast.pad |
trigger with
the prefetches used by the runner.
"""
annotated_actions = (
WorkflowAction.objects.select_related(
"assign_correspondent",
"assign_document_type",
"assign_storage_path",
"assign_owner",
"email",
"webhook",
... | 1 | function_simple | paperless-ngx/paperless-ngx:src/documents/workflows/utils.py:get_workflows_for_trigger |
_score_mod(self) -> _score_mod_signature | None:
"""Creates the transformed score_mod function for FlexAttention.
This function wraps the user's score_mod to handle physical-to-logical
index conversion, similar to how get_mask_mod works for mask functions.
"""
if self.score_mod ... | 1 | function_simple | vllm-project/vllm:vllm/v1/attention/backends/flex_attention.py:FlexAttentionMetadata.get_transformed_score_mod |
:
query (Union[ImageDocument, Image.Image, str, ImageBlock]): An ImageDocument or an ImageBlock, a PIL Image or a string representing an image URL.
"""
if isinstance(query, (ImageBlock, ImageDocument)):
image_buffer = query.resolve_image()
image_query = Image.open(image_buffer)
elif... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/indices/llama-index-indices-managed-lancedb/llama_index/indices/managed/lancedb/utils.py:aquery_multimodal |
ClientSession(headers=self.headers) as session:
async with session.get(url, params=params) as response:
if response.status == 200:
return await response.json()
else:
print(f"请求失败: {response.status}")
... | 1 | function_complex | binary-husky/gpt_academic:crazy_functions/review_fns/data_sources/scopus_source.py:ScopusSource._make_request |
streaming_content_incremental(
chat_response: ChatResponse,
output_cls: Type[Model],
cur_object: Optional[Union[Model, FlexibleModel]] = None,
) -> Union[Model, FlexibleModel]:
"""
Process streaming response content with true incremental list handling.
This version can extract partial progress ... | 1 | function_complex | run-llama/llama_index:llama-index-core/llama_index/core/program/streaming_utils.py:process_streaming_content_incremental |
combining characters
content = dedent("""\
<?xml version="1.0" encoding="UTF-8"?>
<html>
<body>
<div class='ocr_page' title='bbox 0 0 1000 500'>
<p class='ocr_par'>
<span class='ocr_line' title='bbox 100 100 900 150... | 1 | test | ocrmypdf/OCRmyPDF:tests/test_hocr_parser.py:TestHocrParserEdgeCases.test_unicode_normalization |
experts.0.w2.weight"],
raw_tensors[f"{layer_prefix}.experts.1.w2.weight"],
],
dim=0,
)
moe_2 = torch.stack(
[
raw_tensors[f"{layer_prefix}.experts.2.w2.weight"],
raw_tensors[f"{layer_prefi... | 0 | test | huggingface/transformers:tests/utils/test_core_model_loading.py:TestConvertAndLoadStateDict.test_ernie4_5_vl_moe_conversion |
end_with_class_path():
# Register with explicit class path
register_backend(
backend=AttentionBackendEnum.CUSTOM,
class_path="tests.test_attention_backend_registry.CustomAttentionBackend",
is_mamba=False,
)
# Check that CUSTOM backend is registered
assert AttentionBackendEnu... | 1 | test | vllm-project/vllm:tests/test_attention_backend_registry.py:test_register_custom_backend_with_class_path |
- continuing download
previous_progress = file_progress.get("model.safetensors")
# This is NOT a re-download (curr_bytes > previous downloaded)
is_redownload = (
previous_progress is not None
and curr_bytes < previous_progress.downloaded.in_bytes
)
if i... | 0 | test | exo-explore/exo:src/exo/download/tests/test_download_verification.py:TestProgressResetOnRedownload.test_progress_accumulates_on_continuing_download |
TPU accelerator generation, (e.g. "v4", "v5p", "v6e").
resources_per_bundle: Specify the number of resources to reserve per bundle.
When unspecified, SlicePlacementGroup defaults to reserving 1 bundle per TPU host in
a topology, with the bundle resources set to the number of TPU in a ho... | 0 | function_simple | ray-project/ray:python/ray/util/tpu.py:slice_placement_group |
) -> bool:
"""
Determine whether to create an index column for a given side of the join.
A column is "supported" if it is "joinable", and "unsupported" otherwise.
A supported_table is a table with only "supported" columns. Index columns are
needed when we have both supported ... | 0 | function_simple | ray-project/ray:python/ray/data/_internal/execution/operators/join.py:JoiningAggregation._should_index_side |
sys.modules", {"psutil": mock_psutil}),
patch(
"langflow.utils.mcp_cleanup._terminate_child_mcp_processes",
new_callable=AsyncMock,
return_value=2,
) as mock_child,
patch(
"langflow.utils.mcp_cleanup._terminate_orphaned_... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/utils/test_mcp_cleanup.py:TestKillMcpProcesses.test_kills_child_and_orphaned_processes |
result: int = Field(description="The result of the calculation")
explanation: str = Field(description="Brief explanation of the calculation")
@tool
def add_numbers(a: int, b: int) -> int:
"""Add two numbers together and return the sum."""
return a + b
agent = Agent(
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/llms/google/test_google.py:test_gemini_agent_kickoff_structured_output_with_tools |
f'<a href="{href}" title="{title}" target="_blank" rel="noopener">')
suffix.insert(0, "</a>")
else:
prefix.append('<span class="broken-link">')
suffix.insert(0, "</span>")
elif mark_type == "color":
value = mark.get(... | 1 | function_complex | 666ghj/BettaFish:ReportEngine/renderers/html_renderer.py:HTMLRenderer._render_inline |
},
"Trigger Type": {
"select": {"name": workflow.get("trigger_type", "")}
},
"Complexity": {
"select": {"name": workflow.get("complexity", "")}
... | 0 | function_complex | Zie619/n8n-workflows:src/integration_hub.py:IntegrationHub.sync_with_notion |
pipe = self.pipeline_class(**self.get_dummy_components())
pipe = pipe.to(torch_device)
inputs = self.get_dummy_inputs(torch_device)
height_width_pairs = [(32, 32), (64, 64), (32, 64)]
for height, width in height_width_pairs:
expected_height = height
expected... | 1 | test | huggingface/diffusers:tests/pipelines/bria_fibo_edit/test_pipeline_bria_fibo_edit.py:BriaFiboPipelineFastTests.test_image_output_shape |
_unit, enabled, last_run
FROM tasks
WHERE enabled = 1
AND (
last_run IS NULL
OR
CASE frequency_unit
WHEN 'minutes' THEN datetime(last_run, '+' || frequency || ' minutes') <= datetime('now', 'localtime')
... | 0 | function_simple | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_news_and_podcast_agents/beifong/services/task_service.py:TaskService.get_pending_tasks |
):
The batch size with which the model will be used.
dtype (`torch.dtype`, *optional*, defaults to `torch.bfloat16`):
The default `dtype` to use when initializing the layer.
device (`torch.device` or `str`, *optional*):
The device on which the cache should be initialized. Should be the s... | 0 | documentation | huggingface/transformers:src/transformers/models/xlstm/modeling_xlstm.py:xLSTMCache:class_doc |
: DOMSelectorMap, cdp_session=None, filter_highlight_ids: bool = True
) -> str:
"""Async wrapper for creating highlighted screenshots.
Args:
screenshot_b64: Base64 encoded screenshot
selector_map: Map of interactive elements
cdp_session: CDP session for getting viewport info
filter_highlight_ids:... | 0 | function_simple | browser-use/browser-use:browser_use/browser/python_highlights.py:create_highlighted_screenshot_async |
Run this from the ray directory root.
config = IQLConfig().training(actor_lr=0.00001, gamma=0.99)
config = config.offline_data(
input_="./rllib/offline/tests/data/pendulum/pendulum-v1_enormous")
# Build an Algorithm object from the config and run 1 training iteration.
algo = config.build()
... | 0 | documentation | ray-project/ray:rllib/algorithms/iql/iql.py:IQLConfig:class_doc |
.stream(self.copy_stream):
for name, offloader in self._param_offloaders.items():
cpu_storage = offloader._cpu_storage
gpu_buffer = offloader._gpu_buffer
assert cpu_storage is not None, "CPU storage not initialized"
assert gpu_buffer is not Non... | 1 | function_simple | vllm-project/vllm:vllm/model_executor/offloader/prefetch.py:_ModuleOffloader.start_onload_to_static |
def get_jobs_by_flow_id(self, flow_id: UUID | str, page: int = 1, page_size: int = 10) -> list[Job]:
"""Get jobs for a specific flow with pagination.
Args:
flow_id: The flow ID to filter jobs by
page: Page number (1-indexed)
page_size: Number of jobs per page
... | 1 | function_simple | langflow-ai/langflow:src/backend/base/langflow/services/jobs/service.py:JobService.get_jobs_by_flow_id |
(self, text: str) -> int:
"""
Estimate token count for text.
Uses tiktoken for OpenAI models, simple approximation for others.
"""
try:
# Try to use tiktoken for accurate counting
if 'gpt' in self.llm_config.provider.lower():
encoding = tik... | 1 | function_simple | unclecode/crawl4ai:crawl4ai/table_extraction.py:LLMTableExtraction._estimate_tokens |
kwargs):
"""
This transforms the weights obtained using `convert_gpt_oss.py` to load them into `Mxfp4GptOssExperts`.
"""
PrecisionConfig, FlexCtx, InFlexData = (
triton_kernels_hub.matmul_ogs.PrecisionConfig,
triton_kernels_hub.matmul_ogs.FlexCtx,
triton_kernels_hub.matmul_ogs.In... | 0 | function_complex | huggingface/transformers:src/transformers/integrations/mxfp4.py:load_and_swizzle_mxfp4 |
agents.
Args:
manifest: Extension manifest
extension_dir: Path to extension directory
project_root: Path to project root
Returns:
Dictionary mapping agent names to list of registered commands
"""
results = {}
# Detect which agen... | 0 | function_complex | github/spec-kit:src/specify_cli/extensions.py:CommandRegistrar.register_commands_for_all_agents |
content="You are a helpful assistant",
additional_kwargs={"temperature": 0.7, "model": "gpt-4"},
response_metadata={"region": "us-east"},
)
request = _make_request()
new_system_message = metadata_middleware(request)
assert len(new_system_messag... | 1 | test | langchain-ai/langchain:libs/langchain_v1/tests/unit_tests/agents/test_system_message.py:TestDynamicSystemPromptMiddleware.test_middleware_can_use_system_message_with_metadata |
self, mockserver: MockServer
) -> None:
# copy of TestCrawl.test_headers_received_stop_download_errback()
crawler = get_crawler(HeadersReceivedErrbackSpider, self.settings_dict)
await crawler.crawl_async(mockserver=mockserver, is_secure=self.is_secure)
assert isinstance(craw... | 1 | test | scrapy/scrapy:tests/test_downloader_handlers_http_base.py:TestHttpWithCrawlerBase.test_headers_received_stop_download_errback |
"""
expired_entries: list[CachedUpload] = []
if delete_from_provider:
for provider in _get_providers_from_cache(cache):
uploads = await cache.aget_all_for_provider(provider)
expired_entries.extend(upload for upload in uploads if upload.is_expired())
removed = await cache.a... | 0 | function_complex | crewAIInc/crewAI:lib/crewai-files/src/crewai_files/cache/cleanup.py:acleanup_expired_files |
_preserves_original_history(mock_llm):
"""Test that substitution doesn't modify the original history"""
agent = Agent(task='test', llm=mock_llm)
# Create mock history
element = create_test_element(attributes={'type': 'email'})
history = create_mock_history(
[
({'input': {'index': 1, 'text': 'old@example.com'... | 0 | test | browser-use/browser-use:tests/ci/test_variable_substitution.py:test_substitute_preserves_original_history |
ACY
or metric_name not in MetricCardinality.get_high_cardinality_metrics()
):
_HIGH_CARDINALITY_LABELS[metric_name] = []
return []
_HIGH_CARDINALITY_LABELS[metric_name] = [WORKER_ID_TAG_KEY]
if cardinality_level == MetricCardinality.LOW and metric_name in [
... | 0 | function_simple | ray-project/ray:python/ray/_private/telemetry/metric_cardinality.py:MetricCardinality.get_high_cardinality_labels_to_drop |
) -> dict[str, Any]:
"""
Extract standard Transformers PreTrainedConfig config from speculators config.
"""
speculators_model_type = config_dict.get("speculators_model_type")
if speculators_model_type not in SUPPORTED_SPECULATORS_TYPES:
raise ValueError(
... | 1 | function_simple | vllm-project/vllm:vllm/transformers_utils/configs/speculators/base.py:SpeculatorsConfig.extract_transformers_pre_trained_config |
_reasoning_parser(
cls,
reasoning_parser_name: str | None,
) -> type[ReasoningParser] | None:
"""Get the reasoning parser based on the name."""
from vllm.reasoning import ReasoningParserManager
parser: type[ReasoningParser] | None = None
if not reasoning_parser_name:... | 1 | function_simple | vllm-project/vllm:vllm/parser/parser_manager.py:ParserManager.get_reasoning_parser |
ment(name=name)
@serve.ingress(fastapi_app)
class Handler:
@fastapi_app.get("/")
def get_root(self):
return "Hello World!"
serve.run(Handler.bind(), logging_config={"encoding": "TEXT"})
# Get log file information
nodes = list_nodes()
serve_log_dir = get_serve_logs_d... | 0 | test | ray-project/ray:python/ray/serve/tests/test_logging_2.py:test_http_access_log_in_proxy_logs_file |
saved with a .png extension.
Only rejects files when we can definitively detect a mismatch. Files with
unrecognized content are allowed through (they may fail later, but that's
better than false positives blocking valid files).
Args:
file_path: Path to the image file
content: Optional... | 1 | function_complex | langflow-ai/langflow:src/lfx/src/lfx/base/data/storage_utils.py:validate_image_content_type |
doc_id: Document ID
meta_fields: Metadata dictionary
Returns:
True if successful, False otherwise
"""
try:
# Get document with tenant_id
doc_query = Document.select(Document, Knowledgebase.tenant_id).join(
Knowledgebase, on... | 1 | function_complex | infiniflow/ragflow:api/db/services/doc_metadata_service.py:DocMetadataService.update_document_metadata |
return json_response({})
results = db.search(q, tables=['apps', 'articles'])
# Parse JSON fields in results
for table, items in results.items():
for item in items:
if table == 'apps' and item.get('screenshots'):
item['screenshots'] = json.loads(item['screenshots'])
... | 1 | function_complex | unclecode/crawl4ai:docs/md_v2/marketplace/backend/server.py:search |
"delete_events",
return_value={"deletedEventIds": ["e1"]},
) as p_del_events,
patch.object(
AgentCoreMemory,
"batch_delete_memory_records",
) as p_batch,
):
out = memory.delete_all_memory_for_session(
... | 1 | test | run-llama/llama_index:llama-index-integrations/memory/llama-index-memory-bedrock-agentcore/tests/test_agentcore_memory.py:TestBaseAgentCoreMemoryMethods.test_delete_all_memory_for_session_events_only |
in the final dimension. Requires the original image size in (height, width)
format.
"""
old_height, old_width = original_size
scale = target_size * 1.0 / max(old_height, old_width)
new_height, new_width = old_height * scale, old_width * scale
new_width = int(new_width + 0.5)
new_height = i... | 0 | function_simple | huggingface/transformers:src/transformers/models/sam/image_processing_sam_fast.py:_normalize_coordinates |
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
config.output_attentions = True
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(... | 0 | test | huggingface/transformers:tests/models/qwen3_next/test_modeling_qwen3_next.py:Qwen3NextModelTest.test_attention_outputs |
('%Y-%m-%d %H:%M:%S', time.localtime(session_data['created_at']))
last_activity = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(session_data['last_activity']))
# Check if session is still active
is_active = hasattr(session, 'cdp_client') and session.cdp_client is not None
sessions_info.append(
{
... | 0 | function_simple | browser-use/browser-use:browser_use/mcp/server.py:BrowserUseServer._list_sessions |
print(f" - Stored cached_at: {metadata.get('cached_at', 'N/A')}")
# ========== CRAWL 2: Cache hit WITHOUT validation ==========
config2 = CrawlerRunConfig(
cache_mode=CacheMode.ENABLED,
check_cache_freshness=False, # Skip validation - pure cache hit
)
as... | 1 | test | unclecode/crawl4ai:tests/cache_validation/test_end_to_end.py:TestEndToEndCacheValidation.test_full_cache_flow_docs_python |
with patch.object(llm.client, 'complete') as mock_complete:
mock_message = MagicMock()
mock_message.content = "test response"
mock_message.tool_calls = None
mock_choice = MagicMock()
mock_choice.message = mock_message
mock_response = MagicMock()
mock_response... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/llms/azure/test_azure.py:test_azure_token_usage_tracking |
, config):
"""Test with multiple task handlers."""
def make_consumer(cfg):
@task_consumer(task_processor_config=cfg)
class MyConsumer:
@task_handler
def task1(self):
pass
@task_handler
def task2... | 0 | test | ray-project/ray:python/ray/serve/tests/unit/test_task_consumer.py:TestTaskConsumerDecorator.test_task_consumer_multiple_handlers |
resolves 'google' to google-generativeai provider."""
config = {
"provider": "google",
"config": {
"api_key": "test-key",
"model": "gemini-embedding-001",
},
}
from unittest.mock import patch, MagicMock
with patch("cr... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/rag/embeddings/test_backward_compatibility.py:TestFactoryBackwardCompatibility.test_factory_with_google_alias |
var_file for table_to_file mode with SELECT statement."""
source_conn = {"host": "source_host", "login": "source_user", "password": "source_pass"}
result = prepare_tdload_job_var_file(
mode="table_to_file",
source_table=None,
select_stmt="SELECT * FROM source_table W... | 1 | test | apache/airflow:providers/teradata/tests/unit/teradata/utils/test_tpt_util.py:TestTptUtil.test_prepare_tdload_job_var_file_table_to_file_with_select |
"content": [{"type": "text", "text": "Tell me more about image A."}],
},
]
text = processor.apply_chat_template(messages, add_generation_prompt=True)
images = [[self.small_image, self.small_image]]
inputs = processor(text=text, images=images, do_image_splitting=False... | 0 | test | huggingface/transformers:tests/models/lfm2_vl/test_processing_lfm2_vl.py:Lfm2VlProcessorTest.test_multi_turn_multi_image |
ors, backend="torch_gloo")
# Check that we cannot create another group using the same actors.
with pytest.raises(RuntimeError, match="already in group"):
ray.experimental.collective.create_collective_group(
actors, backend="torch_gloo"
)
with pytest.raises(RuntimeError, match="a... | 0 | test | ray-project/ray:python/ray/tests/test_experimental_collective.py:test_api_exceptions |
_parallel_size,
tensor_parallel_size=tensor_parallel_size,
distributed_executor_backend=distributed_executor_backend,
)
if max_model_len is not None:
engine_kwargs["max_model_len"] = max_model_len
config = vLLMEngineProcessorConfig(
model_source=model,
batch_size=bat... | 0 | function_simple | ray-project/ray:python/ray/llm/_internal/batch/benchmark/benchmark_processor.py:_build_vllm_engine_config |
for_condition(
check_metric_float_eq,
timeout=15,
metric="ray_serve_autoscaling_target_replicas",
expected=5,
expected_tags=base_tags,
timeseries=timeseries,
)
print("Target replicas metric verified.")
# Test 2: Check that autoscaling decision metric is 5 (10... | 0 | test | ray-project/ray:python/ray/serve/tests/test_metrics_3.py:test_autoscaling_metrics |
factory(
trace_name: str, span_kind: Optional[Any] = None
) -> Callable:
"""
Factory function to create a tracing decorator for instrumenting functions/methods
with distributed tracing.
Args:
trace_name: The name of the trace.
span_kind: The kind of span to create
(e.g.,... | 0 | function_complex | ray-project/ray:python/ray/serve/_private/tracing_utils.py:tracing_decorator_factory |
return "HAProxyManager" in {actor["class_name"] for actor in actors}
wait_for_condition(check_proxy_alive)
[proxy_actor] = list_actors(
filters=[("class_name", "=", "HAProxyManager"), ("state", "=", "ALIVE")]
)
proxy_actor = ray.get_actor(proxy_actor.name, namespace=SERVE_NAMESPACE)
... | 0 | test | ray-project/ray:python/ray/serve/tests/test_haproxy.py:test_haproxy_update_draining_health_checks |
id_to_trace[rid] = s["context"]["trace_id"]
assert (
len(id_to_trace) == 6
), f"Expected 6 upstream request spans, saw {len(id_to_trace)}"
# Exactly two batch spans, one per each batch, are expected
batched_spans = [s for s in replica_spans if s["name"] == "batched_span"]
asser... | 0 | test | ray-project/ray:python/ray/serve/tests/test_tracing_utils.py:test_batched_span_attached_to_first_request_trace |
."""
from vllm.tool_parsers import ToolParserManager
parser: type[ToolParser] | None = None
if not enable_auto_tools or tool_parser_name is None:
return parser
logger.info('"auto" tool choice has been enabled.')
try:
if (
tool_parser_name... | 1 | function_complex | vllm-project/vllm:vllm/parser/parser_manager.py:ParserManager.get_tool_parser |
()
# Detect format from content type or URL
content_type = response.headers.get('content-type', '').lower()
if 'jpeg' in content_type or url.lower().endswith(('.jpg', '.jpeg')):
image_format = 'jpeg'
elif 'png' in content_type or url.lower().endswith('.png'):
image_format = 'png'
elif 'gif' in c... | 0 | function_complex | browser-use/browser-use:browser_use/llm/aws/serializer.py:AWSBedrockMessageSerializer._download_and_convert_image |
" or "json". Default is "json".
Returns:
List[Document]: A single Document containing the structured reasoning
response. Citations are stored in metadata["citations"].
"""
response = self.client.recall.ask(
input=question,
output_format=outpu... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/tools/llama-index-tools-igpt-email/llama_index/tools/igpt_email/base.py:IGPTEmailToolSpec.ask |
task: Parent task
**kwargs: Additional arguments
Returns:
Step output
"""
# Verify invoker if policy requires it
invoker_card = kwargs.get("invoker_card")
if self._policy.require_verification and invoker_card:
result = self.verify_peer(invok... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/agent/llama-index-agent-agentmesh/llama_index/agent/agentmesh/worker.py:TrustedAgentWorker.arun_step |
.assign_rank("replica_3", "node_1")
rank4 = rank_manager.assign_rank("replica_4", "node_2")
rank5 = rank_manager.assign_rank("replica_5", "node_3")
# Verify global ranks are sequential
assert rank1.rank == 0
assert rank2.rank == 1
assert rank3.rank == 2
assert ra... | 0 | test | ray-project/ray:python/ray/serve/tests/unit/test_deployment_rank_manager.py:TestDeploymentRankManagerMultiNode.test_assign_rank_multiple_nodes |
the _get_native_provider to return a failing class
with patch('crewai.llm.LLM._get_native_provider') as mock_get_provider:
class FailingCompletion:
def __init__(self, *args, **kwargs):
raise Exception("Native AWS Bedrock SDK failed")
mock_get_provider.return_value = Fa... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/llms/bedrock/test_bedrock.py:test_native_bedrock_raises_error_when_initialization_fails |
param description: A description of the group context.
:param rule: The rules governing the group context.
:param agents: A list of agents in the context.
"""
self.name = name
self.description = description
self.rule = rule
self.agents = agents
self.user_t... | 1 | function_simple | zhayujie/chatgpt-on-wechat:agent/protocol/context.py:TeamContext.__init__ |
for platform, count in sorted_platforms:
markdown += f"- **{platform}**: {count} 条新闻\n"
# 趋势变化(如果是周报)
if report_type == "weekly":
markdown += "\n## 📈 趋势分析\n\n"
markdown += "本周热度持续的话题(样本数据):\n\n"
# 简单的趋势分析
| 1 | function_complex | sansan0/TrendRadar:mcp_server/tools/analytics.py:AnalyticsTools.generate_summary_report |
def _run_agent(self, runner: InMemoryRunner, session_id: str, prompt: str) -> str:
"""Run an agent and return its response."""
user_content = types.Content(
role='user',
parts=[types.Part(text=prompt)]
)
response_text = ""
async for event in runn... | 0 | function_simple | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agents/orchestrator.py:NegotiationOrchestrator._run_agent |
padding_side="left",
).to(torch_device)
# it should not matter whether two images are the same size or not
output = model.generate(**inputs, max_new_tokens=30)
generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, output)]
result = se... | 0 | test | huggingface/transformers:tests/models/paddleocr_vl/test_modeling_paddleocr_vl.py:PaddleOCRVLIntegrationTest.test_small_model_integration_test_batch |
handler.setFormatter(BrowserUseFormatter('%(levelname)-8s [%(name)s] %(message)s'))
# Configure root logger - Replace ALL handlers, not just stdout handlers
root = logging.getLogger()
# Clear all existing handlers to prevent output to stdout/stderr
root.handlers = []
root.addHandler(log_handler)
# Set lo... | 0 | function_complex | browser-use/browser-use:browser_use/cli.py:BrowserUseApp.setup_richlog_logging |
optimized_count = self._count_project_operators(optimized_plan)
print(f"After optimization: {optimized_count} operators")
# Should have 1 operator now (changed from 2)
assert (
optimized_count == 1
), f"All operations should fuse into 1 operator, got {optimized_count}"
... | 0 | test | ray-project/ray:python/ray/data/tests/test_projection_fusion.py:TestProjectionFusion.test_dependency_prevents_fusion |
: Optional[ToolContext] = None) -> dict:
"""
Start the negotiation battle!
Returns:
Initial negotiation state and instructions
"""
if negotiation_state.status != "ready":
return {"error": "Please configure the negotiation first using configure_negotiation"}
scenario = g... | 0 | function_simple | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/ai_negotiation_battle_simulator/backend/agent.py:start_negotiation |
Python files to analyze.
module_match_string: An optional string to filter imports. Only imports
containing this string will be included in the result.
Returns:
A dictionary mapping module names to a list of their import statements.
The module names are derived... | 0 | function_simple | ray-project/ray:python/ray/train/lint/check_circular_imports.py:get_file_module_imports |
batched_speech = self.pad(
BatchFeature({"input_features": raw_speech}),
padding=padding,
max_length=max_length,
truncation=truncation,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
)
p... | 0 | function_simple | huggingface/transformers:src/transformers/models/gemma3n/feature_extraction_gemma3n.py:Gemma3nAudioFeatureExtractor.__call__ |
broadcast instead of averaging.
"""
if not is_distributed():
return
handles = []
for buffer in buffers:
if torch.is_floating_point(buffer.data):
if average:
handle = torch.distributed.all_reduce(buffer.data, op=torch.distributed.ReduceOp.SUM, async_op=True)
... | 1 | function_complex | RVC-Boss/GPT-SoVITS:GPT_SoVITS/module/distrib.py:sync_buffer |
def test_pdf_search_tool(mock_adapter):
mock_adapter.query.return_value = "this is a test"
tool = PDFSearchTool(pdf="test.pdf", adapter=mock_adapter)
result = tool._run(query="test content")
assert "this is a test" in result.lower()
mock_adapter.add.assert_called_once_with("test.pdf", data_type=Dat... | 0 | test | crewAIInc/crewAI:lib/crewai-tools/tests/tools/test_search_tools.py:test_pdf_search_tool |
"built_result": {"message": Mock()},
"full_data": {},
"results": {"message": Mock()},
}
# Simulate cache restoration failure
vertex_run2.finalize_build = Mock(side_effect=ValueError("Simulated failure"))
# Act - simulate build_vertex for second run
... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/graph/test_cache_restoration.py:TestCacheRestorationIntegration.test_second_run_scenario_with_fix |
embedding_model_dims=3,
user="test_user",
password="test_pass",
host="localhost",
port=5432,
diskann=False,
hnsw=False,
minconn=1,
maxconn=4
)
results = pgvector.search("test query", [0.1, 0.2, 0.3... | 1 | test | mem0ai/mem0:tests/vector_stores/test_pgvector.py:TestPGVector.test_search_psycopg3 |
if self.version:
raise AirflowException("Refreshing a specific version is not supported")
with self.lock():
self._log.debug(
"Downloading DAGs from s3://%s/%s to %s", self.bucket_name, self.prefix, self.s3_dags_dir
)
self.s3_hook.sync_to_loc... | 1 | function_simple | apache/airflow:providers/amazon/src/airflow/providers/amazon/aws/bundles/s3.py:S3DagBundle.refresh |
PERCENTILE_TO_STD_TABLE)
_TRITON_TABLE_CACHE[logits.device] = (
normal_cdf_to_sigma_table,
percentile_to_std_table,
)
else:
normal_cdf_to_sigma_table, percentile_to_std_table = tables
_topk_topp_kernel[(NUM_PROGRAMS,)](
logits,
buffer,
per... | 1 | function_complex | vllm-project/vllm:vllm/v1/sample/ops/topk_topp_triton.py:apply_top_k_top_p_triton |
from external API)
print("\n3. Testing ConnectionError handling (simulating HTTP 503)...")
with patch("importlib.import_module", side_effect=ConnectionError("503 Service Unavailable")):
result = _process_single_module("lfx.components.nvidia.nvidia")
assert result is None, "Shoul... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_load_components.py:TestComponentLoading.test_process_single_module_exception_handling |
name="d1",
ray_actor_options={"num_cpus": 0},
max_ongoing_requests=2,
num_replicas=3,
).bind(),
WaitForSignal.options(
name="d2",
ray_actor_... | 0 | test | ray-project/ray:python/ray/serve/tests/test_metrics_2.py:TestHandleMetrics.test_running_requests_gauge |
(len(batch) == ds.count() for batch in batches)
assert len(batches) == 1
assert pd.concat(batches, ignore_index=True).equals(
pd.concat(dfs, ignore_index=True)
)
# Batch size drop partial.
batch_size = 5
batches = list(
ds.iter_batches(batch_size=batch_size, drop_last=True, batc... | 0 | test | ray-project/ray:python/ray/data/tests/test_dataset_iter.py:test_iter_batches_basic |
else:
llm = llm_class(model=model_name)
agent = Agent(task='Click the button on the page', llm=llm)
# Create temporary directory that will stay alive during the test
with tempfile.TemporaryDirectory() as temp_dir:
# Create mock state message
mock_message = create_mock_state_message(temp_dir)
agent.messa... | 0 | test | browser-use/browser-use:browser_use/llm/tests/test_single_step.py:test_single_step_parametrized |
that multiple after hooks can chain modifications."""
def hook1(context):
if context.response:
return context.response + " [hook1]"
return None
def hook2(context):
if context.response:
return context.response + " [hook2]"
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/hooks/test_llm_hooks.py:TestLLMHooksIntegration.test_multiple_after_hooks_chain_modifications |
config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.num_labels = 3
config.problem_type = "single_label_classification"
input_ids = input_dict["input_ids"]
attention_mask = input_ids.ne(1).to(torch_device)
sequence_labels = ids_tensor([self.m... | 0 | test | huggingface/transformers:tests/models/t5gemma/test_modeling_t5gemma.py:T5GemmaModelTest.test_T5Gemma_sequence_classification_model_for_single_label |
logging.error(f"Failed to parse tool arguments: {e}")
function_args = {}
# Execute tool
result = self._handle_tool_execution(
function_name=function_name,
function_args=function_args,
available_fun... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/azure/completion.py:AzureCompletion._process_completion_response |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.