input string | label int64 | category string | sample_id string |
|---|---|---|---|
return set()
@staticmethod
def get_orientation(input_file, options):
return OrientationConfidence(0, 0.0)
@staticmethod
def get_deskew(input_file, options):
return 0.0
@staticmethod
def generate_hocr(inpu... | 1 | test | ocrmypdf/OCRmyPDF:tests/test_ocr_engine_interface.py:TestOcrEngineInterface.test_supports_generate_ocr_default_false |
"crewai_tools.tools.rag.rag_tool.build_embedder",
return_value=mock_embedding_func,
):
config = {
"embedding_model": {
"provider": "openai",
"config": {
"model": "text-embedding-3-small",
"api_key": "sk-test123",
... | 0 | test | crewAIInc/crewAI:lib/crewai-tools/tests/tools/test_txt_search_tool_config.py:test_txt_search_tool_with_openai_config_without_env_vars |
_tensors=return_tensors,
**kwargs,
)
elif original_sizes is not None:
if isinstance(original_sizes, torch.Tensor):
original_sizes = original_sizes.cpu().tolist()
encoding_image_processor = BatchEncoding({"original_sizes": original_sizes}, tenso... | 0 | function_complex | huggingface/transformers:src/transformers/models/sam3_video/processing_sam3_video.py:Sam3VideoProcessor.__call__ |
torchify=True)
for image in image_inputs:
self.assertIsInstance(image[0], torch.Tensor)
# Test not batched input
process_out = image_processing(image_inputs[0], return_tensors="pt")
encoded_images = process_out.pixel_values
image_grid_thws =... | 0 | test | huggingface/transformers:tests/models/video_llama_3/test_image_processing_video_llama_3.py:VideoLlama3ImageProcessingTest.test_call_pytorch |
response=error_msg,
turn_number=params.turn_number,
context_id=params.context_id,
is_multiturn=params.is_multiturn,
status="failed",
final=True,
agent_role=params.agent_role,
endpoint=params.endpoint,
a2a_agent_name=par... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/a2a/updates/push_notifications/handler.py:_handle_push_error |
assert table2.schema == table1.schema
assert table1.num_columns == table2.num_columns
for col1, col2 in zip(table1.columns, table2.columns):
assert col1.num_chunks == col2.num_chunks
for chunk1, chunk2 in zip(col1.chunks, col2.chunks):
bufs1 = chunk1.buffe... | 0 | test | ray-project/ray:python/ray/data/tests/unit/test_transform_pyarrow.py:test_arrow_block_slice_copy |
�的 Document IR JSON,并统计章节/图表数量。
解析失败时返回 None;成功时会打印章节数与图表数,便于确认
输入报告的规模。
参数:
file_path: IR 文件路径
返回:
dict | None: 解析后的 Document IR;失败返回 None。
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
document_ir = json.load | 1 | function_complex | 666ghj/BettaFish:regenerate_latest_pdf.py:load_document_ir |
""
points_url = f"{NWS_API_BASE}/points/{latitude},{longitude}"
points_data = await make_nws_request(points_url)
if not points_data or "properties" not in points_data:
return "Unable to fetch forecast data for this location."
forecast_url = points_data["properties"].get("forecast")
if not f... | 0 | function_complex | ray-project/ray:doc/source/ray-overview/examples/multi_agent_a2a/content/mcps/weather_mcp_server.py:get_forecast |
lr=lr,
hidden_dim=hidden_dim)
# Create DeepSpeed model and mark leaf modules BEFORE initialization
torch.manual_seed(42)
model_deepspeed = LeafModuleModel(hidden_dim=hidden_dim)
leaf_modules =... | 1 | test | deepspeedai/DeepSpeed:tests/unit/v1/zero/test_zero_user_backward.py:TestZeroUserBackwardLeafModule.test_leaf_module_backward |
"""
if not self._initialized:
raise RuntimeError("Provider not initialized. Call initialize() first.")
# Normalize language
language = self._normalize_language(template)
# The executor_manager manages instances internally via container pool
# We create a lo... | 1 | function_simple | infiniflow/ragflow:agent/sandbox/providers/self_managed.py:SelfManagedProvider.create_instance |
"""Stream chat with the AI Gateway by delegating to the current LLM."""
while True:
try:
current_llm = self._get_current_llm()
return current_llm.stream_chat(messages, **kwargs)
except Exception as e:
# Try next LLM on failure
... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py:CloudflareAIGateway.stream_chat |
"""Test File creation from PNG bytes auto-detects image type."""
png_bytes = (
b"\x89PNG\r\n\x1a\n"
b"\x00\x00\x00\rIHDR"
b"\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00"
b"\x90wS\xde"
b"\x00\x00\x00\x00IEND\xaeB`\x82"
)
... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/utilities/test_files.py:TestGenericFile.test_file_from_png_bytes |
", '{"key_c": "val_c"}'),
]
delta_message, _ = extract_harmony_streaming_delta(
harmony_parser=parser,
token_states=token_states,
prev_recipient="functions.tool_a",
include_reasoning=False,
)
assert delta_message is not None
tool... | 1 | test | vllm-project/vllm:tests/entrypoints/openai/test_serving_chat_stream_harmony.py:TestExtractHarmonyStreamingDelta.test_tool_call_index_consistency_with_ongoing_call |
_alias_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
"p_alias": {
"anyOf": [
{"type": "string", "contentMediaType": "... | 1 | test | fastapi/fastapi:tests/test_request_params/test_file/test_optional.py:test_optional_alias_schema |
single config
print("\nTest 1: Single config")
result = await dispatcher.crawl_url("https://example.com/file.pdf", pdf_config, "test1")
assert result["config_id"] == id(pdf_config)
print("✓ Single config works")
# Test config list selection
print("\nTest 2: Config list selection")
test... | 1 | test | unclecode/crawl4ai:tests/test_config_selection.py:test_dispatcher_config_selection |
via pydantic-ai.
Manages connection credentials and model creation. Uses pydantic-ai's
model inference to support any provider (OpenAI, Anthropic, Google,
Bedrock, Ollama, vLLM, etc.).
Connection fields:
- **password**: API key (OpenAI, Anthropic, Groq, Mistral, etc.)
- **host**: Base URL (optional — for cus... | 1 | documentation | apache/airflow:providers/common/ai/src/airflow/providers/common/ai/hooks/pydantic_ai.py:PydanticAIHook:class_doc |
print(f"✓ Initial sleeping state: {initial_sleep_state}")
# Step 2: Record baseline GPU memory
print("\n=== Step 2: Recording baseline GPU memory ===")
baseline_memory_mb = get_total_gpu_memory_mb()
print(f"Baseline GPU memory: {baseline_memory_mb:.2f} MB")
assert baseline_me... | 0 | test | ray-project/ray:release/llm_tests/serve/test_llm_serve_sleep_wakeup.py:test_sleep_wakeup_lifecycle |
print("Running with tracing disabled...")
result_no_trace = await Runner.run(
root_agent,
"This run won't be traced.",
run_config=RunConfig(tracing_disabled=True)
)
print(f"Run completed without tracing: {result_no_trace.run_id}")
print("(This run won't appear in traces ... | 0 | function_simple | Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/10_tracing_observability/10_1_default_tracing/agent.py:tracing_configuration |
(`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
The tensors corresponding to the input videos.
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
The temporal, height and width of feature shape of each video in LLM.
v... | 0 | function_simple | huggingface/transformers:src/transformers/models/video_llama_3/modular_video_llama_3.py:VideoLlama3Model.get_video_features |
.github.io/posts/muon/)
return max(1, out_chs / in_chs) ** 0.5
elif adjust_lr_fn == "match_rms_adamw":
# Kimi (https://arxiv.org/abs/2502.16982)
return 0.2 * max(out_chs, in_chs) ** 0.5
elif adjust_lr_fn == "rms_to_rms":
# Scion (https://arxiv.org/abs/2502.07529, https://github.c... | 1 | function_simple | huggingface/pytorch-image-models:timm/optim/muon.py:get_lr_scale |
}} else if (y + imgHeight >= window.innerHeight) {{
y = window.innerHeight - imgHeight;
dy = -Math.abs(dy);
}}
img.style.left = `${{x}}px`;
img.style.top = `${{y}}px`;
requestAnimationFrame(animate);
}}
animate();
// Responsive: update bounds on resize
win... | 0 | function_simple | browser-use/browser-use:browser_use/browser/watchdogs/aboutblank_watchdog.py:AboutBlankWatchdog._show_dvd_screensaver_loading_animation_cdp |
sync_playwright().start()
browser = playwright.chromium.connect_over_cdp(
endpoint_url=ws_url, headers=headers, timeout=30000
)
logger.info(
f"Successfully connected to sync browser for thread {thread_id}"
)
# Store session re... | 0 | function_simple | crewAIInc/crewAI:lib/crewai-tools/src/crewai_tools/aws/bedrock/browser/browser_session_manager.py:BrowserSessionManager._create_sync_browser_session |
_name = "test_team"
mock_manager = mock_manager_class.return_value
mock_manager._bundle_config = {"test_bundle": mock_bundle_config}
# First call (team-specific) fails, second call (global) succeeds
mock_lookup.side_effect = [UnknownExecutorException("Team executor not found"), None]
... | 1 | test | apache/airflow:airflow-core/tests/unit/dag_processing/test_dagbag.py:TestValidateExecutorFields.test_global_executor_fallback_success |
Args:
video (`np.ndarray`):
The video to get the dimensions of.
channel_dim (`ChannelDimension`, *optional*):
Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the video.
Returns:
A tuple of the video's height and wid... | 0 | function_simple | huggingface/transformers:src/transformers/video_utils.py:get_video_size |
test_custom_base_url_usage(mock_post, custom_url_tool):
mock_response = MagicMock()
mock_response.json.return_value = {
"url": "https://custom.crewai.com/studio/project-789"
}
mock_post.return_value = mock_response
custom_url_tool.run(prompt="Create automation")
mock_post.assert_calle... | 0 | test | crewAIInc/crewAI:lib/crewai-tools/tests/tools/generate_crewai_automation_tool_test.py:test_custom_base_url_usage |
user\n<image>\nWhat is this?\nassistant",
]
image1 = Image.open(requests.get("https://llava-vl.github.io/static/images/view.jpg", stream=True).raw)
image2 = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)
inputs = self.processor(images... | 0 | test | huggingface/transformers:tests/models/fast_vlm/test_modeling_fast_vlm.py:FastVlmForConditionalGenerationIntegrationTest.test_small_model_integration_test_batch |
_tester.prepare_config_and_inputs_for_common()
config.hidden_act = "relu2" # Ensure we're using relu2 activation
model = ArceeModel(config)
# Check that the MLP layers use the correct activation
mlp = model.layers[0].mlp
# Test with a simple input
x = torch.randn(1, 10,... | 0 | test | huggingface/transformers:tests/models/arcee/test_modeling_arcee.py:ArceeModelTest.test_arcee_mlp_uses_relu_squared |
TestClient, _DummyRuntime],
) -> None:
"""Ensure the media endpoint serves byte ranges for streaming clients."""
client, runtime = starlette_client
storage = runtime.media_file_mgr._storage
file_id = storage.load_and_get_id(
b"abcdefghij", "video/mp4", MediaFileKind.MEDIA, "clip.mp4"
)
r... | 1 | test | streamlit/streamlit:lib/tests/streamlit/web/server/starlette/starlette_app_test.py:test_media_endpoint_supports_range_requests |
{"role": "system", "content": "你是一个专业的新闻分析师,擅长从热点新闻中提取关键词和撰写分析总结。"},
{"role": "user", "content": prompt}
],
max_tokens=1500,
temperature=0.3
)
# 解析返回结果
result_text = | 1 | function_simple | 666ghj/BettaFish:MindSpider/BroadTopicExtraction/topic_extractor.py:TopicExtractor.extract_keywords_and_summary |
mixed_end_tags_1(self):
template = self.engine.get_template("nested_partials_mixed_end_1_template")
empty_proxy = template.extra_data["partials"]["outer"]
other_proxy = template.extra_data["partials"]["inner"]
outer_result = empty_proxy.find_partial_source(template.source)
self... | 1 | test | django/django:tests/template_tests/test_partials.py:FindPartialSourceTests.test_find_partial_source_supports_nested_partials_and_mixed_end_tags_1 |
add_chunk,
HttpApiAuth,
dataset_id,
document_id,
{"content": f"chunk test {i}"},
)
for i in range(count)
]
responses = list(as_completed(futures))
assert len(responses) == count... | 1 | test | infiniflow/ragflow:test/testcases/test_http_api/test_chunk_management_within_dataset/test_add_chunk.py:TestAddChunk.test_concurrent_add_chunk |
ds = ds.with_column("times_two", multiply_by_two(col("plus_one")))
ds = ds.with_column("div_three", divide_by_three(col("times_two")))
# Convert to pandas and compare with expected result
result_df = ds.to_pandas()
expected_df = pd.DataFrame(
{
"id": [0, 1, 2, 3, 4],
"... | 0 | test | ray-project/ray:python/ray/data/tests/test_with_column.py:test_with_column_udf_multiple_udfs |
ConnectionError: If cannot connect to server
requests.exceptions.HTTPError: If server returns error status
"""
try:
if method == "GET":
response = requests.get(
url, headers=dict(self.headers), timeout=self.timeout, **kwargs
)
... | 1 | function_complex | docling-project/docling:docling/models/inference_engines/common/kserve_v2_http.py:KserveV2HttpClient._execute_http_request |
(start_index=0, end_index=3)
annotated_extractions = [
data.Extraction(extraction_class="foo", extraction_text="zero"),
data.Extraction(extraction_class="foo", extraction_text="one"),
]
chunk_text = chunking.get_token_interval_text(tokenized_text, chunk)
token_offset = chunk.start_index... | 1 | test | google/langextract:tests/resolver_test.py:ResolverTest.test_align_with_discontinuous_tokenized_text_but_right_chunk |
This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
"Attention Is All You Need".
"""
half_dim = embedding_dim // 2
emb = math.log(10000) / (half_dim - 1)
emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() *... | 0 | function_simple | huggingface/transformers:src/transformers/models/kosmos2_5/modeling_kosmos2_5.py:Kosmos2_5TextSinusoidalPositionalEmbedding.get_embedding |
)
metadata.fps = 24 if metadata.fps is None else metadata.fps
# if timestamps are not provided, calculate them
curr_timestamp = self._calculate_timestamps(
metadata.frames_indices,
metadata.fps,
... | 0 | function_complex | huggingface/transformers:src/transformers/models/qwen3_vl/modular_qwen3_vl.py:Qwen3VLProcessor.__call__ |
TS5 search first (good for English and word-based languages)
2. If no FTS5 or no results and query contains CJK: Use LIKE search
"""
if scopes is None:
scopes = ["shared"]
if user_id:
scopes.append("user")
# Try FTS5 search first (if avail... | 1 | function_complex | zhayujie/chatgpt-on-wechat:agent/memory/storage.py:MemoryStorage.search_keyword |
is repetitive garbage.
Returns: (is_problematic, error_message)
"""
# Check 1: Stop reason indicates max_tokens
if stop_reason == 'max_tokens':
return True, f'Response terminated due to max_tokens limit (stop_reason: {stop_reason})'
# Check 2: Used 90%+ of max_tokens (if we have both values)
if completion_to... | 0 | function_complex | browser-use/browser-use:browser_use/code_use/utils.py:detect_token_limit_issue |
errors.extend(
[
f"{filename}: Function error in node {node_data.get('id', 'unknown')}: {error}"
for error in validation_result["function"]["errors"]
]
... | 1 | function_complex | langflow-ai/langflow:src/backend/base/langflow/utils/template_validation.py:validate_flow_code |
AI Gateway by delegating to the current LLM."""
while True:
try:
current_llm = self._get_current_llm()
return current_llm.stream_complete(prompt, formatted, **kwargs)
except Exception as e:
# Try next LLM on failure
logger.... | 1 | function_simple | run-llama/llama_index:llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py:CloudflareAIGateway.stream_complete |
str:
"""
Get the first model from the vLLM server.
"""
try:
models: SyncPage[Model] = client.models.list()
except APIConnectionError as e:
raise RuntimeError(
"Failed to get the list of models from the vLLM server at "
f"{client.base_url} with API key {client... | 1 | function_simple | vllm-project/vllm:examples/online_serving/utils.py:get_first_model |
, not the entire SVN tree
svn_dirs = self.get_svn_directories()
for svn_dir in svn_dirs:
# Check for SVN locks before attempting update (prevents hanging)
if self._check_svn_locks(svn_dir.parent):
console_print(f"[red]SVN working copy is locked: {svn_dir.parent}[... | 1 | function_complex | apache/airflow:dev/breeze/src/airflow_breeze/utils/release_validator.py:ReleaseValidator._update_svn |
# Check for schema defaults that don't have corresponding server defaults
for field_name, schema_value in schema_defaults.items():
if field_name not in server_defaults:
# Some schema fields are computed properties (like has_on_*_callback)
computed_properties = {
"h... | 1 | function_complex | apache/airflow:scripts/in_container/run_schema_defaults_check.py:compare_dag_defaults |
str, tree_actor):
router = PrefixCacheAffinityRouter(
deployment_id=DeploymentID(name=deployment_name),
handle_source=DeploymentHandleSource.REPLICA,
use_replica_queue_len_cache=False,
get_curr_time_s=TIMER.time,
)
rout... | 0 | test | ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py:TestMultiDeploymentIsolation.test_two_deployments_get_separate_tree_actors |
result = await self.crawler.arun(url=url, config=config)
# Extract the actual CrawlResult from the container
if hasattr(result, '_results') and result._results:
result = result._results[0]
# Filter our all links do not have head_date
if hasattr(... | 1 | function_complex | unclecode/crawl4ai:crawl4ai/adaptive_crawler copy.py:AdaptiveCrawler._crawl_with_preview |
a SINQLinear
module instead of a plain nn.Linear.
"""
from ..core_model_loading import WeightConverter
if self.pre_quantized:
from ..integrations.sinq import SinqDeserialize
return [
WeightConverter(
source_patterns=[
... | 0 | function_simple | huggingface/transformers:src/transformers/quantizers/quantizer_sinq.py:SinqHfQuantizer.get_weight_conversions |
mock_engine.input_processor = MagicMock()
mock_engine.io_processor = MagicMock()
mock_engine.renderer = _build_renderer(mock_engine.model_config)
serving_completion = _build_serving_completion(mock_engine)
completion_output = CompletionOutput(
index=0,
text="",
token_ids=[... | 1 | test | vllm-project/vllm:tests/entrypoints/openai/test_completion_error.py:test_completion_error_non_stream |
importance: float | None = None,
) -> MemoryRecord:
"""Update an existing memory record by ID.
Args:
record_id: ID of the record to update.
content: New content; re-embedded if provided.
scope: New scope path.
categories: New categories.
... | 0 | function_complex | crewAIInc/crewAI:lib/crewai/src/crewai/memory/unified_memory.py:Memory.update |
r1 = FakeRunningReplica("r1")
prefix_request_router.update_replicas([r1])
# Insert text that exceeds eviction_threshold_chars
ray.get(
prefix_request_router._tree_actor.insert.remote(
"verylongtext", r1.replica_id.to_full_id_str(), time.time()
)
... | 0 | test | ray-project/ray:python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py:TestPromptNormalization.test_eviction_threshold_behavior |
crewai_event_bus.emit("emitter", event)
time.sleep(0.001)
def register_continuously() -> None:
for _ in range(10):
@crewai_event_bus.on(ThreadSafetyTestEvent)
def handler(source: object, event: BaseEvent) -> None:
with l... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/utilities/events/test_thread_safety.py:test_concurrent_emit_and_registration |
=strategy,
max_pages=20,
top_k_links=3,
min_gain_threshold=0.05,
**kwargs
)
async with AsyncWebCrawler(verbose=False) as crawler:
adaptive = AdaptiveCrawler(crawler, config)
start_time = time.time()
result = await adaptive.digest(start_url=ur... | 1 | function_simple | unclecode/crawl4ai:docs/examples/adaptive_crawling/embedding_vs_statistical.py:crawl_with_strategy |
list[float] | None = None,
**kwargs,
):
r"""
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
Args:
scheduler (`SchedulerMixin`):
The sched... | 1 | function_complex | huggingface/diffusers:src/diffusers/pipelines/flux/pipeline_flux_kontext.py:retrieve_timesteps |
type_str = get_type_str(param.type_hint) if param.type_hint != Any else ""
name = f"**{param.kwargs_type}" if param.name is None and param.kwargs_type is not None else param.name
param_str = f"- `{name}` (`{type_str}`"
if hasattr(param, "required") and not param.required:
para... | 1 | function_complex | huggingface/diffusers:src/diffusers/modular_pipelines/modular_pipeline_utils.py:format_params_markdown |
allocation)
# [read] mode: receives block release messages from decode side
# Decode Role:
# [write] mode: receives KV cache write completion notifications
handled = False
try:
data = msgpack.loads(msg)
if isinstance(data, dict) and "req_id" in data:
... | 1 | function_complex | vllm-project/vllm:vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_engine.py:MoRIIOWrapper._handle_message |
api import WebSocket
# Capture WebSocket connections
ws_connections: list[WebSocket] = []
def capture_ws(ws: WebSocket) -> None:
ws_connections.append(ws)
# Note: We need to register the handler before navigation, but the app fixture
# already navigated. So we reload to capture the WebSoc... | 1 | test | streamlit/streamlit:e2e_playwright/web_server_test.py:test_websocket_connection_to_stream_endpoint |
32, but hidden_states may be bf16
topk_weights = topk_weights.to(hidden_states.dtype)
# Get routing indices for grouped GEMM
with torch.no_grad():
token_counts_by_expert, gather_indices = get_routing_indices(
topk_indices, self.n_routed_experts
)
# Use grouped GEMM for expe... | 0 | function_simple | unslothai/unsloth:unsloth/models/glm4_moe.py:Glm4MoeLiteMoE_fast_forward |
:12345", "GET", "/ping", "1.1", 200),
exc_info=None,
)
assert filter.filter(record_get) is False
# Test POST
record_post = logging.LogRecord(
name="uvicorn.access",
level=logging.INFO,
pathname="",
lineno=0,
msg='%s... | 1 | test | vllm-project/vllm:tests/test_access_log_filter.py:TestUvicornAccessLogFilter.test_filter_different_http_methods |
test_try_finally_with_filtered_tools(echo_server_script):
serverparams = StdioServerParameters(
command="uv", args=["run", "python", "-c", echo_server_script]
)
try:
# Select both tools but in reverse order
mcp_server_adapter = MCPServerAdapter(serverparams, "calc_tool", "echo_tool"... | 0 | test | crewAIInc/crewAI:lib/crewai-tools/tests/adapters/mcp_adapter_test.py:test_try_finally_with_filtered_tools |
create_session_with_chat_assistant(HttpApiAuth, chat_assistant_ids[0], payload)
elif payload["name"] == "case insensitive":
create_session_with_chat_assistant(HttpApiAuth, chat_assistant_ids[0], {"name": payload["name"].upper()})
res = create_session_with_chat_assistant(HttpApiA... | 1 | test | infiniflow/ragflow:test/testcases/test_http_api/test_session_management/test_create_session_with_chat_assistant.py:TestSessionWithChatAssistantCreate.test_name |
-> str:
"""Map LlamaIndex FilterOperator to SQL operator string."""
if operator == FilterOperator.EQ:
return "="
if operator == FilterOperator.GT:
return ">"
if operator == FilterOperator.LT:
return "<"
if operator == FilterOperator.NE:
... | 1 | function_complex | run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-volcenginemysql/llama_index/vector_stores/volcengine_mysql/base.py:VolcengineMySQLVectorStore._to_mysql_operator |
node_embeddings: List[TextNode]
) -> None:
yb_hybrid.add(hybrid_node_embeddings)
assert isinstance(yb_hybrid, YBVectorStore)
assert hasattr(yb_hybrid, "_engine")
# text search should work when query is a sentence and not just a single word
q = VectorStoreQuery(
query_embedding=_get_sample_v... | 1 | test | run-llama/llama_index:llama-index-integrations/vector_stores/llama-index-vector-stores-yugabytedb/tests/test_yugabytedb.py:test_sparse_query |
has a seq_len dimension) and the mamba cache
(which has a constant shape regardless of seq_len).
This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each ... | 0 | documentation | huggingface/transformers:src/transformers/models/falcon_h1/modular_falcon_h1.py:FalconHybridMambaAttentionDynamicCache:class_doc |
\w+)\((.*)\)", tool_call)
if not match:
return f"Could not parse tool call: {tool_call}"
tool_name = match.group(1)
args_str = match.group(2)
# Parse kwargs
kwargs = {}
for arg in args_str.split(", "):
if "=" in arg:
... | 0 | function_complex | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/single_agent_apps/ai_agent_governance/ai_agent_governance.py:GovernedAgent._execute_tool_call |
else MistralTokenizerType.spm
)
self._cache_get_vocab: dict[str, int] | None = None
self._all_special_ids = self._get_all_special_ids()
self._all_special_tokens = self.convert_ids_to_tokens(self.all_special_ids)
super().__init__(
truncation_side=truncation_side,... | 0 | function_simple | huggingface/transformers:src/transformers/tokenization_mistral_common.py:MistralCommonBackend.__init__ |
[str]) -> list[str]:
"""Check which model cards have incorrect HF commit dates and return their names"""
incorrect_dates = []
for model_card in model_card_list:
model_card = _normalize_model_card_name(model_card)
if _should_skip_model_card(model_card):
continue
content ... | 0 | function_complex | huggingface/transformers:utils/add_dates.py:check_incorrect_dates |
AEps(len=1349 done=True R=1349.0 id_=0aa924b047494c83a5e63e67f3d180c9)]
episode_return = episodes[0].get_return()
print(f"episodes[0].id_: {episodes[0].id_}")
print(f"Found episode with return {episode_return}")
# Assert the episode has a decent return.
assert episodes[0].get_re... | 0 | test | ray-project/ray:rllib/offline/tests/test_offline_rl_stateful.py:OfflineRLStatefulTest.test_training_on_single_episode_and_evaluate |
client
include_system_in_user: If True, system messages are included in the first user message
supports_structured_output: If True, uses native JSON mode; if False, uses prompt-based fallback
max_retries: Number of retries for retryable errors (default: 5)
retryable_status_codes: List o... | 0 | documentation | browser-use/browser-use:browser_use/llm/google/chat.py:ChatGoogle:class_doc |
def _version_from_dynamic_linker(self) -> tuple[int, int] | None:
""" Attempt to get the default version from ldconfig or $LD_LIBRARY_PATH
Returns
-------
tuple[int, int, int] | None
The detected default ROCm version. ``None`` if not version detected
"""
path... | 1 | function_simple | deepfakes/faceswap:lib/system/ml_libs.py:CudaLinux._version_from_dynamic_linker |
test_optional_list_str_schema(path: str):
openapi = app.openapi()
body_model_name = get_body_model_name(openapi, path)
assert app.openapi()["components"]["schemas"][body_model_name] == {
"properties": {
"p": {
"anyOf": [
{"items": {"type": "string"},... | 1 | test | fastapi/fastapi:tests/test_request_params/test_body/test_optional_list.py:test_optional_list_str_schema |
def stop(self, value: list[str] | str | None) -> None:
"""Set stop sequences.
Synchronizes stop_sequences to ensure values set by CrewAgentExecutor
are properly sent to the Gemini API.
Args:
value: Stop sequences as a list, single string, or None
"""
if valu... | 0 | function_simple | crewAIInc/crewAI:lib/crewai/src/crewai/llms/providers/gemini/completion.py:GeminiCompletion.stop |
)
yield CfgBranch(
positive=True,
embeds=pos_embeds,
mask=pos_mask,
pooled=pos_pooled,
cond_latents=pos_cond,
)
neg_embeds, neg_mask, neg_pooled, neg_cond = (
prompt_data.get_c... | 0 | function_simple | exo-explore/exo:src/exo/worker/engines/image/pipeline/runner.py:DiffusionRunner._get_cfg_branches |
Returns:
ResolvedFile representing the appropriate delivery format.
"""
constraints = get_constraints_for_provider(provider)
if self._is_url_source(file) and self._supports_url(constraints):
return self._resolve_as_url(file)
context = self._build_file_context(f... | 0 | function_simple | crewAIInc/crewAI:lib/crewai-files/src/crewai_files/resolution/resolver.py:FileResolver.resolve |
else:
inputs_embeds = self.model.get_input_embeddings()[generation_steps - 1](input_ids)
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs: BaseModelOutputWithPast = self.model(
input_ids=None,
attention_mask=attention_mask,
... | 0 | function_simple | huggingface/transformers:src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py:Qwen3OmniMoeTalkerCodePredictorModelForConditionalGeneration.forward |
_by_index(params.index)
if node is None:
msg = f'Element index {params.index} not available - page may have changed. Try refreshing browser state.'
logger.warning(f'⚠️ {msg}')
return ActionResult(extracted_content=msg)
# Dispatch GetDropdownOptionsEvent to the event handler
event = browser_sessio... | 0 | function_simple | browser-use/browser-use:browser_use/tools/service.py:dropdown_options |
�化处理节点。
顺序实例化模板选择、文档布局、篇幅规划、章节生成四个节点,
其中章节节点额外依赖 IR 校验器与章节存储器。
"""
self.template_selection_node = TemplateSelectionNode(
self.llm_client,
self.config.TEMPLATE_DIR
)
self.document_layout_node = DocumentLayoutNode(self.llm_client)
| 1 | function_simple | 666ghj/BettaFish:ReportEngine/agent.py:ReportAgent._initialize_nodes |
,
"avg_chunk_size": 50.0,
"embedding_provider": "OpenAI",
"embedding_model": "text-embedding-3-small",
"id": "test-uuid",
"size": 1024,
"source_types": [],
"chunk_size": None,
"chunk_overlap": None,
"separator": ... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_knowledge_bases_api.py:TestGetKBMetaData.test_get_metadata_fast_success |
.
if hf_repo_id != "apple/aimv2-large-patch14-224-lit":
config.use_head = False
if hf_repo_id == "apple/aimv2-large-patch14-native":
config.is_native = True
original_state_dict = load_original_state_dict(hf_repo_id)
print("Converting model...")
state_dict = {}
result = conver... | 0 | function_complex | huggingface/transformers:src/transformers/models/aimv2/convert_aimv2_original_pytorch_to_hf.py:write_model |
proxy_state_manager.add_proxy_details(
"node1", "10.0.0.1", "proxy1"
)
direct_ingress_controller.proxy_state_manager.add_proxy_details(
"node2", "10.0.0.2", "proxy2"
)
target_groups = direct_ingress_controller.get_target_groups()
expected_target_groups = [
TargetGroup(
... | 0 | test | ray-project/ray:python/ray/serve/tests/unit/test_controller_direct_ingress.py:test_get_target_groups_empty_when_no_apps |
tell me what the current weather is in Berlin and the "
"forecast for the next 5 days, in fahrenheit?",
},
]
response = await client.responses.create(
model=model_name,
input=prompt,
tools=tools,
tool_choice=tool_choice,
temperature=0.0,
)
as... | 1 | test | vllm-project/vllm:tests/v1/entrypoints/openai/serving_responses/test_function_call.py:test_function_tool_use |
st.success(f"✅ Completed in {execution_time:.2f}s")
st.write("**Response:**")
st.write(result.final_output)
except Exception as e:
st.error(f"❌ Error: {e}")
with col3:
... | 0 | function_complex | Shubhamsaboo/awesome-llm-apps:ai_agent_framework_crash_course/openai_sdk_crash_course/4_running_agents/agent_runner.py:render_execution_methods |
._is_newer_than_start(doc_or_failure.doc_updated_at, start):
yield doc_or_failure
# Now get attachments for that page:
attachment_docs, attachment_failures = self._fetch_page_attachments(
page, start, end
)
# yield attached docs and failur... | 1 | function_complex | infiniflow/ragflow:common/data_source/confluence_connector.py:ConfluenceConnector._fetch_document_batches |
() -> Dict[str, str]:
"""Load existing categories from search_categories.json created by create_categories.py."""
try:
with open("context/search_categories.json", "r", encoding="utf-8") as f:
categories_data = json.load(f)
# Convert to filename -> category mapping
category_m... | 0 | function_complex | Zie619/n8n-workflows:scripts/generate_search_index.py:load_existing_categories |
result = await llm.acall(
messages=[{"role": "user", "content": "Calculate 1+1"}],
tools=[{
"type": "function",
"function": {
"name": "calculator",
"description": "Calculate expression",
"parameters": {"... | 0 | test | crewAIInc/crewAI:lib/crewai/tests/llms/openai/test_openai.py:test_openai_async_streaming_returns_tool_calls_without_available_functions |
back.providers``), which serves both feedback
and input collection via console.
Example (default console input):
```python
from crewai.flow import Flow, start
class MyFlow(Flow):
@start()
def gather_info(self):
topic = self.ask("What topic should we research?")
ret... | 0 | documentation | crewAIInc/crewAI:lib/crewai/src/crewai/flow/input_provider.py:module_doc |
ds1 = ray.data.read_parquet("example://iris.parquet")
ds2 = ray.data.read_parquet("example://iris.parquet")
ds3 = ray.data.read_parquet("example://iris.parquet")
ds = ds1.union(ds2).union(ds3).filter(expr=col("sepal.length") > 5.0)
# Verify correctness: should have 3x the filtered res... | 0 | test | ray-project/ray:python/ray/data/tests/test_predicate_pushdown.py:TestPushIntoBranchesBehavior.test_multiple_unions_with_filter |
Directory() as temp_dir, patch.dict(os.environ, {"LANGFLOW_CONFIG_DIR": temp_dir}):
auth_settings = AuthSettings(CONFIG_DIR=temp_dir)
# Current behavior: refresh token uses 'none' (allows cross-site)
assert auth_settings.REFRESH_SAME_SITE == "none" # Current: allows cross-site (less... | 1 | test | langflow-ai/langflow:src/backend/tests/unit/test_security_cors.py:TestRefreshTokenSecurity.test_refresh_token_samesite_setting_current_behavior |
voice_file = f"{temp_dir}/tts-azure-v1-{voice_name}.mp3"
subtitle_file = f"{temp_dir}/tts-azure-v1-{voice_name}.srt"
sub_maker = vs.azure_tts_v1(
text=text_zh, voice_name=voice_name, voice_file=voice_file, voice_rate=voice_rate
)
if not sub_maker:
self.fai... | 0 | test | harry0703/MoneyPrinterTurbo:test/services/test_voice.py:TestVoiceService.test_azure_tts_v1 |
self.assertIsInstance(video[0], Image.Image)
video_metadata = self.video_processor_tester.prepare_video_metadata(video_inputs)
encoded_videos = video_processing(
video_inputs[0], video_metadata=[video_metadata[0]], return_tensors="pt"
)[self.input_name]
... | 0 | test | huggingface/transformers:tests/models/qwen3_vl/test_video_processing_qwen3_vl.py:Qwen3VLVideoProcessingTest.test_call_pil |
risk_keywords = {
"HIGH": ["vulnerability", "exploit", "cve", "critical", "breach"],
"MEDIUM": ["breaking", "deprecated", "removed", "migration"],
}
for level, keywords in risk_keywords.items():
if any(kw in title for kw in keywords):
risk_leve... | 0 | function_simple | Shubhamsaboo/awesome-llm-apps:advanced_ai_agents/multi_agent_apps/devpulse_ai/agents/risk_agent.py:RiskAgent._fallback_assessment |
"{RequestStatus.WAITING_FOR_FSM}" == "WAITING_FOR_FSM"
assert f"{RequestStatus.WAITING_FOR_REMOTE_KVS}" == "WAITING_FOR_REMOTE_KVS"
assert f"{RequestStatus.WAITING_FOR_STREAMING_REQ}" == "WAITING_FOR_STREAMING_REQ"
assert f"{RequestStatus.RUNNING}" == "RUNNING"
assert f"{RequestStatus.PREEMPTED}" == "PR... | 1 | test | vllm-project/vllm:tests/v1/test_request.py:test_request_status_fmt_str |
'], arguments['text'])
elif tool_name == 'browser_get_state':
state_json, screenshot_b64 = await self._get_browser_state(arguments.get('include_screenshot', False))
content: list[types.TextContent | types.ImageContent] = [types.TextContent(type='text', text=state_json)]
if screenshot_b64:
content.a... | 0 | function_complex | browser-use/browser-use:browser_use/mcp/server.py:BrowserUseServer._execute_tool |
获取Report Engine状态,包括引擎就绪情况与当前任务信息。
返回:
Response: JSON结构包含initialized/engines_ready/当前任务等。
"""
try:
engines_status = check_engines_ready()
return jsonify({
'success': True,
'initialized': report_agent is not None,
'engines_ready': engines_status[... | 1 | function_simple | 666ghj/BettaFish:ReportEngine/flask_interface.py:get_status |
loss: Loss function to use for feature distillation. Can be:
- String identifier (e.g., 'mse', 'cosine_similarity', 'mae')
- Keras loss instance
- Nested structure of losses matching the layer output structure
- `None` to skip distillation for that output (useful for
multi-... | 1 | documentation | keras-team/keras:keras/src/distillation/distillation_loss.py:FeatureDistillation:class_doc |
workers for small files
# Medium files (1-10MB)
workers = S3FileSystem._calculate_optimal_workers(
num_files=50, total_size=50 * 5 * 1024 * 1024 # 50 files * 5MB each
)
assert workers == 25 # Should use moderate workers
# Large files (> 10MB)
workers = S3... | 0 | test | ray-project/ray:python/ray/llm/tests/common/cloud/test_s3_filesystem.py:TestS3FileSystem.test_calculate_optimal_workers |
"frontend",
"yarn",
"exec",
"prettier",
"--write",
"--config",
"./.prettierrc",
]
# Add file paths with proper relative path prefix
cmd.extend(f"../{relative_path}" for relative... | 1 | function_simple | streamlit/streamlit:scripts/sync_vscode_devcontainer.py:DevcontainerSync._format_with_prettier |
str: str) -> OcrOptions:
"""Reconstruct from JSON with special handling for non-serializable types."""
data = json.loads(json_str)
# Handle special types during deserialization
def _deserialize_value(value):
if isinstance(value, dict) and '__type__' in value:
... | 1 | function_complex | ocrmypdf/OCRmyPDF:src/ocrmypdf/_options.py:OcrOptions.model_validate_json_safe |
_MEAN = torch.tensor([[9.3306, 8.1721, 6.4764, 7.6011, 11.1218, 7.5343, 7.1195, 8.0956]])
torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2)
# slicing logits[0, 0, 0:30]
EXPECTED_SLICE = torch.tensor(
[15.7759, 17.6274, 16.3404, 14.5543, 13.1366, 14.2475, 1... | 0 | test | huggingface/transformers:tests/models/smollm3/test_modeling_smollm3.py:SmolLM3IntegrationTest.test_model_3b_logits |
f"Namespace column '{group_col_name}' contains null values; "
"fill or drop them before writing with namespace_column."
)
# Sort by the namespace column so _iter_groups_sorted can yield
# contiguous zero-copy slices for each unique namespace value.
sort_key = Sor... | 0 | function_complex | ray-project/ray:python/ray/data/_internal/datasource/turbopuffer_datasink.py:TurbopufferDatasink._write_multi_namespace |
)
except httpx.ConnectError as e:
msg = (
f"Could not connect to LiteLLM Proxy at {base_url}. Verify the URL is correct and the proxy is running."
)
raise ValueError(msg) from e
except httpx.TimeoutException as e:
msg = f"Connectio... | 1 | function_simple | langflow-ai/langflow:src/lfx/src/lfx/components/litellm/litellm_proxy.py:LiteLLMProxyComponent._validate_proxy_connection |
self.get_dummy_inputs(generator_device)
inputs["height"] = inputs["width"] = 128
output_without_tiling = pipe(**inputs)[0]
# With tiling
pipe.vae.enable_tiling(tile_sample_min_size=96)
inputs = self.get_dummy_inputs(generator_device)
inputs["height"] = inputs["width"] =... | 1 | test | huggingface/diffusers:tests/pipelines/hunyuan_image_21/test_hunyuanimage.py:HunyuanImagePipelineFastTests.test_vae_tiling |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.