id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
4,375 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,376 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,377 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,378 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,379 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,380 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,381 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,382 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,383 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,384 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,385 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,386 | import functools
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.... | null |
4,387 |
def patch_sdk():
pass | null |
4,389 | from azure.core.pipeline.transport import HttpRequest
def _convert_request(request, files=None):
data = request.content if not files else None
request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data)
if files:
request.set_formdata_body(files)
return requ... | null |
4,390 | from os import PathLike
from pathlib import Path
from typing import IO, AnyStr, Optional, Union
from ._utils import is_arm_id
The provided code snippet includes necessary dependencies for implementing the `load_flow` function. Write a Python function `def load_flow( source: Union[str, PathLike, IO[AnyStr]], *,... | Construct a flow object from a yaml file. :param source: The local yaml source of a compute. Must be either a path to a local file, or an already-open file. If the source is a path, it will be open and read. An exception is raised if the file does not exist. If the source is an open file, the file will be read directly... |
4,391 | import ast
import datetime
import threading
client_map = {}
_token_timeout = 60 * 4
def _get_client_from_map(client_key: str):
client = client_map.get(client_key, None)
if client is None:
return None
if client["expire_at"] > datetime.datetime.now():
return client["client"]
return None
d... | null |
4,392 | import json
import logging
from dataclasses import asdict, dataclass
from enum import Enum
from typing import Any, Dict, List, Optional, Type, TypeVar
from promptflow._constants import CONNECTION_NAME_PROPERTY
from .multimedia import Image
from .types import AssistantDefinition, FilePath, PromptTemplate, Secret
T = Typ... | null |
4,393 | import os
import typing
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from ._constants import (
PF_TRACING_SKIP_LOCAL_SETUP_ENVIRON,
RESOURCE_ATTRIBUTES_SERVICE_NAME,
ResourceAttributesFieldName,
)
from ._openai_injector i... | Start a tracing session. Instrument `openai`, and set tracer provider for current tracing session. :param resource_attributes: Specify the resource attributes for current tracing session. :type resource_attributes: typing.Optional[dict] :param session: Specify the session id for current tracing session. :type session: ... |
4,394 | import os
import typing
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from ._constants import (
PF_TRACING_SKIP_LOCAL_SETUP_ENVIRON,
RESOURCE_ATTRIBUTES_SERVICE_NAME,
ResourceAttributesFieldName,
)
from ._openai_injector i... | null |
4,395 | import asyncio
import functools
import importlib
import json
import logging
import os
from importlib.metadata import version
import openai
from promptflow._core.operation_context import OperationContext
from ._trace import _traced_async, _traced_sync
from .contracts.trace import TraceType
def available_openai_apis_and_... | This function restores the original create methods of the OpenAI API classes by assigning them back from the _original attributes of the modified methods. |
4,396 | import re
from promptflow._core._errors import NotSupported
from promptflow.contracts.flow import InputAssignment, InputValueType
from promptflow.executor._errors import (
InputNotFound,
InputNotFoundFromAncestorNodeOutput,
InvalidReferenceProperty,
UnsupportedReference,
)
def parse_node_property(node_n... | null |
4,397 | import asyncio
import contextvars
import inspect
import os
import signal
import threading
import time
import traceback
from asyncio import Task
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Dict, List, Tuple
from promptflow._core.flow_execution_context import FlowExecutionContext
from prompt... | Start a thread to monitor coroutines after receiving signal. |
4,398 | import asyncio
import contextvars
import inspect
import os
import signal
import threading
import time
import traceback
from asyncio import Task
from concurrent.futures import ThreadPoolExecutor
from typing import Any, Dict, List, Tuple
from promptflow._core.flow_execution_context import FlowExecutionContext
from prompt... | null |
4,399 | import asyncio
import contextlib
import copy
import functools
import inspect
import os
import uuid
from pathlib import Path
from threading import current_thread
from types import GeneratorType
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from opentelemetry.trace.status import StatusCode
from p... | Inject the stream options to the decorated function. AzureOpenAI.completion and AzureOpenAI.chat tools support both stream and non-stream mode. The stream mode is controlled by the "stream" parameter. |
4,400 | import asyncio
import contextlib
import copy
import functools
import inspect
import os
import uuid
from pathlib import Path
from threading import current_thread
from types import GeneratorType
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from opentelemetry.trace.status import StatusCode
from p... | Enable the stream mode for LLM tools that support it. :param f: The function to wrap. :type f: function :return: The wrapped function. :rtype: function AzureOpenAI.completion and AzureOpenAI.chat tools support both stream and non-stream mode. The stream mode is turned off by default. Use this wrapper to turn it on. |
4,401 | import asyncio
import contextlib
import copy
import functools
import inspect
import os
import uuid
from pathlib import Path
from threading import current_thread
from types import GeneratorType
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from opentelemetry.trace.status import StatusCode
from p... | Ensure the node result is serializable. Some of the nodes may return a generator of strings to create streaming outputs. This is useful when the flow is deployed as a web service. However, in the interactive mode, the executor assumes that the node result is JSON serializable. This wrapper ensures the node result is se... |
4,402 | import asyncio
import contextlib
import copy
import functools
import inspect
import os
import uuid
from pathlib import Path
from threading import current_thread
from types import GeneratorType
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple
from opentelemetry.trace.status import StatusCode
from p... | Execute the flow, including aggregation nodes. :param flow_file: The path to the flow file. :type flow_file: Path :param working_dir: The working directory of the flow. :type working_dir: Path :param output_dir: Relative path relative to working_dir. :type output_dir: Path :param connections: A dictionary containing co... |
4,403 | import asyncio
import contextvars
import multiprocessing
import os
import queue
import signal
import sys
import threading
from datetime import datetime
from functools import partial
from logging import INFO
from multiprocessing import Manager, Queue
from multiprocessing.pool import ThreadPool
from pathlib import Path
f... | null |
4,404 | import asyncio
import contextvars
import multiprocessing
import os
import queue
import signal
import sys
import threading
from datetime import datetime
from functools import partial
from logging import INFO
from multiprocessing import Manager, Queue
from multiprocessing.pool import ThreadPool
from pathlib import Path
f... | null |
4,405 | import multiprocessing
import queue
import signal
import time
from dataclasses import dataclass
from enum import Enum
from functools import partial
from multiprocessing import Process, Queue
from typing import Dict, List
import psutil
from promptflow._core.operation_context import OperationContext
from promptflow._core... | Manages the creation, termination, and signaling of processes using the 'fork' context. |
4,406 | from fastapi import APIRouter
from fastapi.responses import JSONResponse
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.logger_utils import service_logger
from promptflow.executor._service.contracts.execution_request import (
CancelExecutionRequest,
FlowExecutionRequest,
... | null |
4,407 | from fastapi import APIRouter
from fastapi.responses import JSONResponse
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.logger_utils import service_logger
from promptflow.executor._service.contracts.execution_request import (
CancelExecutionRequest,
FlowExecutionRequest,
... | null |
4,408 | from fastapi import APIRouter
from fastapi.responses import JSONResponse
from promptflow._utils.context_utils import _change_working_dir
from promptflow._utils.logger_utils import service_logger
from promptflow.executor._service.contracts.execution_request import (
CancelExecutionRequest,
FlowExecutionRequest,
... | null |
4,409 | from fastapi import APIRouter
from promptflow._core.tool_meta_generator import generate_tool_meta_in_subprocess
from promptflow._core.tools_manager import collect_package_tools
from promptflow._utils.logger_utils import service_logger
from promptflow.executor._service.contracts.tool_request import RetrieveToolFuncResul... | null |
4,410 | from fastapi import APIRouter
from promptflow._core.tool_meta_generator import generate_tool_meta_in_subprocess
from promptflow._core.tools_manager import collect_package_tools
from promptflow._utils.logger_utils import service_logger
from promptflow.executor._service.contracts.tool_request import RetrieveToolFuncResul... | null |
4,411 | from fastapi import APIRouter
from promptflow._core.tool_meta_generator import generate_tool_meta_in_subprocess
from promptflow._core.tools_manager import collect_package_tools
from promptflow._utils.logger_utils import service_logger
from promptflow.executor._service.contracts.tool_request import RetrieveToolFuncResul... | null |
4,412 | from fastapi import APIRouter
from fastapi.responses import PlainTextResponse
from promptflow._utils.feature_utils import get_feature_list
from promptflow.executor._service.utils.service_utils import get_executor_version
def health_check():
return PlainTextResponse("healthy") | null |
4,413 | from fastapi import APIRouter
from fastapi.responses import PlainTextResponse
from promptflow._utils.feature_utils import get_feature_list
from promptflow.executor._service.utils.service_utils import get_executor_version
def version():
return {
"status": "healthy",
"version": get_executor_version()... | null |
4,414 | from fastapi import FastAPI
from fastapi.responses import JSONResponse
from promptflow.executor._service.apis.common import router as common_router
from promptflow.executor._service.apis.execution import router as execution_router
from promptflow.executor._service.apis.tool import router as tool_router
from promptflow.... | null |
4,415 | import asyncio
import contextlib
import json
import multiprocessing
import os
from datetime import datetime, timedelta
from typing import Callable
import psutil
from promptflow._core._errors import UnexpectedError
from promptflow._core.operation_context import OperationContext
from promptflow._utils.exception_utils imp... | null |
4,416 | import json
import os
from typing import Any, Mapping, Union
from promptflow._core.connection_manager import ConnectionManager
from promptflow._core.operation_context import OperationContext
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter, JsonSerializedPromptflowException
from promptflo... | null |
4,417 | import json
import os
from typing import Any, Mapping, Union
from promptflow._core.connection_manager import ConnectionManager
from promptflow._core.operation_context import OperationContext
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter, JsonSerializedPromptflowException
from promptflo... | null |
4,418 | import json
import os
from typing import Any, Mapping, Union
from promptflow._core.connection_manager import ConnectionManager
from promptflow._core.operation_context import OperationContext
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter, JsonSerializedPromptflowException
from promptflo... | null |
4,419 | import json
import os
from typing import Any, Mapping, Union
from promptflow._core.connection_manager import ConnectionManager
from promptflow._core.operation_context import OperationContext
from promptflow._utils.exception_utils import ErrorResponse, ExceptionPresenter, JsonSerializedPromptflowException
from promptflo... | null |
4,420 | import base64
import json
import os
import re
import streamlit as st
from pathlib import Path
from streamlit_quill import st_quill
from bs4 import BeautifulSoup, NavigableString, Tag
from promptflow._sdk._utils import print_yellow_warning
from promptflow._sdk._serving.flow_invoker import FlowInvoker
from promptflow._u... | null |
4,421 | import os
import sys
from promptflow._cli._pf._connection import create_connection
from streamlit.web import cli as st_cli
from streamlit.runtime import exists
from main import start
def is_yaml_file(file_path):
_, file_extension = os.path.splitext(file_path)
return file_extension.lower() in ('.yaml', '.yml')
... | null |
4,422 | import json
import logging
from flask import Flask, jsonify, request
from promptflow import load_flow
from promptflow.connections import AzureOpenAIConnection
from promptflow.entities import FlowContext
from promptflow.exceptions import SystemErrorException, UserErrorException
def handle_error(e):
if isinstance(e,... | null |
4,423 | import json
import logging
from flask import Flask, jsonify, request
from promptflow import load_flow
from promptflow.connections import AzureOpenAIConnection
from promptflow.entities import FlowContext
from promptflow.exceptions import SystemErrorException, UserErrorException
The provided code snippet includes necess... | Check if the runtime is alive. |
4,424 | import json
import logging
from flask import Flask, jsonify, request
from promptflow import load_flow
from promptflow.connections import AzureOpenAIConnection
from promptflow.entities import FlowContext
from promptflow.exceptions import SystemErrorException, UserErrorException
logger = logging.getLogger(__name__)
logge... | process a flow request in the runtime. |
4,425 | import json
import logging
from flask import Flask, jsonify, request
from promptflow import load_flow
from promptflow.connections import AzureOpenAIConnection
from promptflow.entities import FlowContext
from promptflow.exceptions import SystemErrorException, UserErrorException
app = SimpleScoreApp(__name__)
def create... | null |
4,426 | from promptflow import tool
from promptflow.connections import AzureOpenAIConnection
def echo_connection(flow_input: str, node_input: str, connection: AzureOpenAIConnection):
print(f"Flow input: {flow_input}")
print(f"Node input: {node_input}")
print(f"Flow connection: {connection._to_dict()}")
# get f... | null |
4,427 | from enum import Enum
from promptflow import tool
class ConversationModality(str, Enum):
TEXT = "text"
TRANSCRIPT = "transcript"
def create_conversation_item(line: str, id: int) -> dict:
name_and_text = line.split(":", maxsplit=1)
name = name_and_text[0].strip()
text = name_and_text[1].strip()
r... | This tool creates a conversation input for conversation-based language skills. Conversation text is assumed to be of the following form: <speaker id>: <speaker text> <speaker id>: <speaker text> ... :param text: conversation text. :param modality: conversation modality. :param language: conversation language. :param id... |
4,428 | from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `read_file` function. Write a Python function `def read_file(file_path: str) -> str` to solve the following problem:
This tool opens a file and reads its contents into a string. :param file_path: the file path of... | This tool opens a file and reads its contents into a string. :param file_path: the file path of the file to be read. |
4,429 | from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `create_document` function. Write a Python function `def create_document(text: str, language: str, id: int) -> dict` to solve the following problem:
This tool creates a document input for document-based language ... | This tool creates a document input for document-based language skills :param text: document text. :param language: document language. :param id: document id. |
4,430 | from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `extract_language_code` function. Write a Python function `def extract_language_code(ld_output: dict) -> str` to solve the following problem:
This tool extracts the ISO 639-1 language code from language detection... | This tool extracts the ISO 639-1 language code from language detection output. :param ld_output: language detection output (parsed). |
4,431 | from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `create_redacted_conversation` function. Write a Python function `def create_redacted_conversation(conversation: dict, pii_output: dict) -> dict` to solve the following problem:
This tool creates a conversation i... | This tool creates a conversation input for conversation-based language skills from the task output of conversational PII. It does so by replacing all original text with the PII redacted text. :param conversation: original conversation object. :param pii_output: conversational pii node output (parsed). |
4,432 | from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `parse_skill_to_text` function. Write a Python function `def parse_skill_to_text(output: object, skill: str) -> str` to solve the following problem:
This tool parses a language skill result into a string, when po... | This tool parses a language skill result into a string, when possible. Not all skills give logical string parsings. :param output: skill output. :param skill: skill type to parse. |
4,435 | from typing import List
from promptflow import tool
from promptflow import log_metric
def accuracy_aggregate(processed_results: List[int]):
num_exception = 0
num_correct = 0
for i in range(len(processed_results)):
if processed_results[i] == -1:
num_exception += 1
elif processe... | null |
4,436 | from promptflow import tool
def line_process(groundtruth: str, prediction: str) -> int:
processed_result = 0
if prediction == "JSONDecodeError" or prediction.startswith("Unknown Error:"):
processed_result = -1
return processed_result
try:
groundtruth = float(groundtruth)
... | null |
4,437 | from typing import List
from promptflow import tool
def aggregate(perceived_intelligence_score: List[float]):
aggregated_results = {"perceived_intelligence_score": 0.0, "count": 0}
# Calculate average perceived_intelligence_score
for i in range(len(perceived_intelligence_score)):
aggregated_result... | null |
4,438 | from promptflow import tool
import re
def extract_float(s):
def parse_score(gpt_score: str):
return float(extract_float(gpt_score)) | null |
4,439 | import logging
import logging.config
import re
from pathlib import Path
from typing import List
import promptflow
import yaml
from openai import AzureOpenAI
from promptflow.connections import AzureOpenAIConnection
from tenacity import (
RetryError,
Retrying,
after_log,
before_sleep_log,
stop_after_a... | Using GPT, evaluate a generated summary with respect to a source document from which it was generated. This function should be used for four dimensions of summarization evaluation inline with the SummEval benchmark: fluency, coherence, consistency, relevance. Args: prompt_with_src_and_gen (str): The prompt containing t... |
4,440 | from typing import Dict, List
from promptflow import log_metric, tool
The provided code snippet includes necessary dependencies for implementing the `aggregate` function. Write a Python function `def aggregate( fluency_list: List[float], consistency_list: List[float], relevance_list: List[float], coher... | Takes list of scores for 4 dims and outputs average for them. Args: fluency_list (List(float)): list of fluency scores consistency_list (List(float)): list of consistency scores relevance_list (List(float)): list of relevance scores coherence_list (List(float)): list of coherence scores Returns: Dict[str, float]: Retur... |
4,441 | from promptflow import tool
from typing import List
from promptflow import log_metric
def log_metrics(match_counts: List[dict]):
exact_match_rate = sum([m["exact_match"] for m in match_counts]) / len(match_counts)
partial_match_rate = sum([m["partial_match"] for m in match_counts]) / len(match_counts)
log... | null |
4,442 | from promptflow import tool
from typing import List
def is_match(
answer: List[str],
ground_truth: List[str],
ignore_case: bool,
ignore_order: bool,
allow_partial: bool) -> bool:
if ignore_case:
answer = [a.lower() for a in answer]
ground_truth = [g.lower() fo... | null |
4,443 | from typing import List
from promptflow import tool
def cleansing(entities_str: str) -> List[str]:
# Split, remove leading and trailing spaces/tabs/dots
parts = entities_str.split(",")
cleaned_parts = [part.strip(" \t.\"") for part in parts]
entities = [part for part in cleaned_parts if len(part) > 0]
... | null |
4,445 | from promptflow import tool
def string_to_number(raw_string: str) -> float:
''' Try to parse the prediction string and groundtruth string to float number.
Support parse int, float, fraction and recognize non-numeric string with wrong format.
Wrong format cases: 'the answer is \box{2/3}', '0, 5, or any numbe... | Early stop |
4,446 | from promptflow import tool
def grade(groundtruth: str, prediction: str):
return "Correct" if groundtruth.lower() == prediction.lower() else "Incorrect" | null |
4,447 | from typing import List
from promptflow import log_metric, tool
def calculate_accuracy(grades: List[str]):
result = []
for index in range(len(grades)):
grade = grades[index]
result.append(grade)
# calculate accuracy for each variant
accuracy = round((result.count("Correct") / len(resul... | null |
4,448 | from promptflow import tool
def select_metrics(metrics: str) -> str:
supported_metrics = ('gpt_relevance', 'gpt_groundedness', 'gpt_retrieval_score')
user_selected_metrics = [metric.strip() for metric in metrics.split(',') if metric]
metric_selection_dict = {}
for metric in supported_metrics:
i... | null |
4,449 | from promptflow import tool
import numpy as np
def concat_results(rag_retrieval_score: dict = None,
rag_grounding_score: dict = None, rag_generation_score: dict = None):
load_list = [{'name': 'gpt_groundedness', 'result': rag_grounding_score},
{'name': 'gpt_retrieval_score', 'r... | null |
4,450 | from promptflow import tool
import re
def parse_generation_output(rag_generation_score: str) -> str:
quality_score = float('nan')
quality_reasoning = ''
for sent in rag_generation_score.split('\n'):
sent = sent.strip()
if re.match(r"\s*(<)?Quality score:", sent):
numbers_found =... | null |
4,451 | from promptflow import tool
import re
def parse_retrieval_output(retrieval_output: str) -> str:
score_response = [sent.strip() for sent in
retrieval_output.strip("\"").split("# Result")[-1].strip().split('.') if sent.strip()]
parsed_score_response = re.findall(r"\d+", score_response[-1])
... | null |
4,452 | from typing import List
from promptflow import tool, log_metric
import numpy as np
def aggregate_variants_results(results: List[dict], metrics: List[str]):
aggregate_results = {}
for result in results:
for name, value in result.items():
if name not in aggregate_results.keys():
... | null |
4,453 | from promptflow import tool
def is_valid(input_item):
return True if input_item and input_item.strip() else False
def validate_input(question: str, answer: str, documents: str, selected_metrics: dict) -> dict:
input_data = {"question": is_valid(question), "answer": is_valid(answer), "documents": is_valid(docum... | null |
4,454 | from promptflow import tool
import re
def parse_grounding_output(rag_grounding_score: str) -> str:
try:
numbers_found = re.findall(r"Quality score:\s*(\d+)\/\d", rag_grounding_score)
score = float(numbers_found[0]) if len(numbers_found) > 0 else 0
except Exception:
score = float("nan")
... | null |
4,455 | from typing import List
from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `aggregate` function. Write a Python function `def aggregate(processed_results: List[str])` to solve the following problem:
This tool aggregates the processed result of all lines to the va... | This tool aggregates the processed result of all lines to the variant level and log metric for each variant. :param processed_results: List of the output of line_process node. |
4,456 | from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `line_process` function. Write a Python function `def line_process(groundtruth: str, prediction: str)` to solve the following problem:
This tool processes the prediction of a single line and returns the processed... | This tool processes the prediction of a single line and returns the processed result. :param groundtruth: the groundtruth of a single line. :param prediction: the prediction of a single line. |
4,457 | from promptflow import tool
def select_metrics(metrics: str) -> str:
supported_metrics = ('gpt_coherence', 'gpt_similarity', 'gpt_fluency', 'gpt_relevance', 'gpt_groundedness',
'f1_score', 'ada_similarity')
user_selected_metrics = [metric.strip() for metric in metrics.split(',') if met... | null |
4,458 | from promptflow import tool
import numpy as np
from numpy.linalg import norm
def compute_ada_cosine_similarity(a, b) -> float:
return np.dot(a, b)/(norm(a)*norm(b)) | null |
4,459 | from promptflow import tool
import numpy as np
import re
def concat_results(gpt_coherence_score: str = None,
gpt_similarity_score: str = None,
gpt_fluency_score: str = None,
gpt_relevance_score: str = None,
gpt_groundedness_score: str = None,
... | null |
4,460 | from promptflow import tool
from collections import Counter
def compute_f1_score(ground_truth: str, answer: str) -> str:
import string
import re
class QASplitTokenizer:
def __call__(self, line):
"""Tokenizes an input line using split() on whitespace
:param line: a segment ... | null |
4,461 | from typing import List
from promptflow import tool, log_metric
import numpy as np
def aggregate_variants_results(results: List[dict], metrics: List[str]):
aggregate_results = {}
for result in results:
for name, value in result.items():
if name in metrics[0]:
if name not in ... | null |
4,462 | from promptflow import tool
def validate_input(question: str, answer: str, context: str, ground_truth: str, selected_metrics: dict) -> dict:
input_data = {"question": question, "answer": answer, "context": context, "ground_truth": ground_truth}
expected_input_cols = set(input_data.keys())
dict_metric_requi... | null |
4,463 | from typing import List
from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `aggregate` function. Write a Python function `def aggregate(groundedness_scores: List[float])` to solve the following problem:
This tool aggregates the processed result of all lines to th... | This tool aggregates the processed result of all lines to the variant level and log metric for each variant. :param processed_results: List of the output of line_process node. :param variant_ids: List of variant ids that can be used to group the results by variant. :param line_numbers: List of line numbers of the varia... |
4,464 | from promptflow import tool
import re
def extract_float(s):
match = re.search(r"[-+]?\d*\.\d+|\d+", s)
if match:
return float(match.group())
else:
return None
def parse_score(gpt_score: str):
return float(extract_float(gpt_score)) | null |
4,465 | import re
import bs4
import requests
from promptflow import tool
def decode_str(string):
return string.encode().decode("unicode-escape").encode("latin1").decode("utf-8")
def remove_nested_parentheses(string):
pattern = r"\([^()]+\)"
while re.search(pattern, string):
string = re.sub(pattern, "", stri... | null |
4,466 | import random
import time
from concurrent.futures import ThreadPoolExecutor
from functools import partial
import bs4
import requests
from promptflow import tool
def fetch_text_content_from_url(url: str, count: int = 10):
# Send a request to the URL
try:
headers = {
"User-Agent": "Mozilla/5.0... | null |
4,467 | from promptflow import tool
def process_search_result(search_result):
def format(doc: dict):
return f"Content: {doc['Content']}\nSource: {doc['Source']}"
try:
context = []
for url, content in search_result:
context.append({"Content": content, "Source": url})
context... | null |
4,468 | from promptflow import tool
import json
import re
def my_python_tool(input1: str) -> str:
input1 = re.sub(r'[$\\!]', '', input1)
try:
json_answer = json.loads(input1)
answer = json_answer['answer']
except Exception:
answer = input1
return answer | null |
4,469 | import os
from typing import Union
from promptflow import tool
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection
from chat_with_pdf.utils.lock import acquire_lock
BASE_DIR = os.path.dirname(os.path.abspath(__file__)) + "/chat_with_pdf/"
def acquire_lock(filename):
if not sys.platform.start... | null |
4,470 | from promptflow import tool
from chat_with_pdf.rewrite_question import rewrite_question
def rewrite_question(question: str, history: list):
template = Environment(
loader=FileSystemLoader(os.path.dirname(os.path.abspath(__file__)))
).get_template("rewrite_question_prompt.md")
token_limit = int(os.e... | null |
4,471 | from promptflow import tool
from chat_with_pdf.download import download
def download(url: str) -> str:
path = os.path.join(PDF_DIR, normalize_filename(url) + ".pdf")
lock_path = path + ".lock"
with acquire_lock(lock_path):
if os.path.exists(path):
log("Pdf already exists in " + os.path... | null |
4,472 | from promptflow import tool
from chat_with_pdf.build_index import create_faiss_index
def create_faiss_index(pdf_path: str) -> str:
chunk_size = int(os.environ.get("CHUNK_SIZE"))
chunk_overlap = int(os.environ.get("CHUNK_OVERLAP"))
log(f"Chunk size: {chunk_size}, chunk overlap: {chunk_overlap}")
file_n... | null |
4,473 | from promptflow import tool
from chat_with_pdf.qna import qna
def convert_chat_history_to_chatml_messages(history):
def qna(prompt: str, history: list):
def qna_tool(prompt: str, history: list):
stream = qna(prompt, convert_chat_history_to_chatml_messages(history))
answer = ""
for str in stream:
... | null |
4,474 | from promptflow import tool
from chat_with_pdf.find_context import find_context
def find_context(question: str, index_path: str):
def find_context_tool(question: str, index_path: str):
prompt, context = find_context(question, index_path)
return {"prompt": prompt, "context": [c.text for c in context]} | null |
4,475 | import argparse
from dotenv import load_dotenv
import os
from qna import qna
from find_context import find_context
from rewrite_question import rewrite_question
from build_index import create_faiss_index
from download import download
from utils.lock import acquire_lock
from constants import PDF_DIR, INDEX_DIR
def chat_... | null |
4,476 | from typing import Tuple, Union, Optional, Type
import functools
import time
import random
def retry_and_handle_exceptions(
exception_to_check: Union[Type[Exception], Tuple[Type[Exception], ...]],
max_retries: int = 3,
initial_delay: float = 1,
exponential_base: float = 2,
jitter: bool = False,
... | null |
4,477 | from typing import Tuple, Union, Optional, Type
import functools
import time
import random
def retry_and_handle_exceptions_for_generator(
exception_to_check: Union[Type[Exception], Tuple[Type[Exception], ...]],
max_retries: int = 3,
initial_delay: float = 1,
exponential_base: float = 2,
jitter: boo... | null |
4,478 | from typing import List
import openai
from openai.version import VERSION as OPENAI_VERSION
import os
import tiktoken
from jinja2 import Template
from .retry import (
retry_and_handle_exceptions,
retry_and_handle_exceptions_for_generator,
)
from .logging import log
def count_token(text: str) -> int:
encoding... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.