id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
4,479 | 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 |
4,480 | from promptflow import tool
from chat_with_pdf.main import chat_with_pdf
def convert_chat_history_to_chatml_messages(history):
messages = []
for item in history:
messages.append({"role": "user", "content": item["inputs"]["question"]})
messages.append({"role": "assistant", "content": item["output... | null |
4,481 | from promptflow import tool
from chat_with_pdf.main import chat_with_pdf
def convert_chatml_messages_to_chat_history(messages):
history = []
for i in range(0, len(messages), 2):
history.append(
{
"inputs": {"question": messages[i]["content"]},
"outputs": {"an... | null |
4,482 | from promptflow import tool
import json
The provided code snippet includes necessary dependencies for implementing the `get_current_weather` function. Write a Python function `def get_current_weather(location, unit="fahrenheit")` to solve the following problem:
Get the current weather in a given location
Here is the ... | Get the current weather in a given location |
4,483 | from promptflow import tool
import json
The provided code snippet includes necessary dependencies for implementing the `get_n_day_weather_forecast` function. Write a Python function `def get_n_day_weather_forecast(location, format, num_days)` to solve the following problem:
Get next num_days weather in a given locatio... | Get next num_days weather in a given location |
4,484 | from promptflow import tool
import json
def run_function(response_message: dict) -> str:
if "function_call" in response_message:
function_name = response_message["function_call"]["name"]
function_args = json.loads(response_message["function_call"]["arguments"])
print(function_args)
... | null |
4,485 | import os
from promptflow import tool
from promptflow.connections import CustomConnection
from intent import extract_intent
def extract_intent(chat_prompt: str):
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage
if "AZURE_OPENAI_API_KEY" not in os.environ:
... | null |
4,486 | import os
import pip
from langchain.chat_models import AzureChatOpenAI
from langchain.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import HumanMessage
def extract_intent(chat_prompt: str):
if "AZURE_OPENAI_API_KEY" not ... | null |
4,487 | import os
import pip
from langchain.chat_models import AzureChatOpenAI
from langchain.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.prompts.prompt import PromptTemplate
from langchain.schema import HumanMessage
def generate_prompt(customer_info: str, history: list, user_prompt_templ... | null |
4,488 | from typing import Union
from openai.version import VERSION as OPENAI_VERSION
from promptflow import tool
from promptflow.connections import CustomConnection, AzureOpenAIConnection
def to_bool(value) -> bool:
def get_client(connection: Union[CustomConnection, AzureOpenAIConnection]):
def my_python_tool(
prompt: st... | null |
4,489 | from promptflow import tool
import ast
import json
def infinite_loop_check(code_snippet):
def syntax_error_check(code_snippet):
def error_fix(code_snippet):
def code_refine(original_code: str) -> str:
try:
original_code = json.loads(original_code)["code"]
fixed_code = None
if infinite_loo... | null |
4,490 | from promptflow import tool
def prepare_example():
return [
{
"question": "What is 37593 * 67?",
"code": "{\n \"code\": \"print(37593 * 67)\"\n}",
"answer": "2512641",
},
{
"question": "What is the value of x in the equation 2x + 3 = 11?",
"code": "{\n ... | null |
4,491 | from promptflow import tool
import sys
from io import StringIO
def func_exe(code_snippet: str):
if code_snippet == "JSONDecodeError" or code_snippet.startswith("Unknown Error:"):
return code_snippet
# Define the result variable before executing the code snippet
old_stdout = sys.stdout
redirect... | null |
4,492 | import time
from typing import List
import re
import tiktoken
import logging
import sys
import json
FORMATTER = logging.Formatter(
fmt="[%(asctime)s] %(name)-8s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S %z",
)
def get_logger(name: str, level=logging.INFO) -> logging.Logger:
logger = logging.... | null |
4,493 | import time
from typing import List
import re
import tiktoken
import logging
import sys
import json
def preprocess_json_input(input_str: str) -> str:
# Replace single backslashes with double backslashes, while leaving already escaped ones intact
corrected_str = re.sub(r'(?<!\\)\\(?!["\\/bfnrt]|u[0-9a-fA-F]{4})'... | null |
4,494 | import time
from typing import List
import re
import tiktoken
import logging
import sys
import json
The provided code snippet includes necessary dependencies for implementing the `count_string_tokens` function. Write a Python function `def count_string_tokens(string: str, model_name="gpt-3.5-turbo") -> int` to solve t... | Returns the number of tokens in a text string. Args: string (str): The text string. model_name (str): The name of the encoding to use. (e.g., "gpt-3.5-turbo") Returns: int: The number of tokens in the text string. |
4,495 | import time
from typing import List
import re
import tiktoken
import logging
import sys
import json
def count_message_tokens(
messages: List, model: str = "gpt-3.5-turbo-0301"
) -> int:
def create_chat_message(role, content, name=None):
def generate_context(prompt, full_message_history, user_prompt, model="gpt-3.5... | null |
4,496 | import time
from typing import List
import re
import tiktoken
import logging
import sys
import json
def construct_prompt(current_context):
update_current_context = []
for item in current_context:
role = item.get("role", None)
content = item.get("content", None)
name = item.get("name", N... | null |
4,497 | from promptflow import tool
def functions_format() -> list:
functions = [
{
"name": "search",
"description": """The action will search this entity name on Wikipedia and returns the first {count}
sentences if it exists. If not, it will return some related entities to sear... | null |
4,498 | import sys
from io import StringIO
import functools
import logging
import ast
from typing import Dict, Optional
logger = logging.getLogger(__name__)
def warn_once() -> None:
# Warn that the PythonREPL
logger.warning("Python REPL can execute arbitrary code. Use with caution.") | null |
4,499 | from promptflow import tool
The provided code snippet includes necessary dependencies for implementing the `generate_goal` function. Write a Python function `def generate_goal(items: list = []) -> str` to solve the following problem:
Generate a numbered list from given items based on the item_type. Args: items (list):... | Generate a numbered list from given items based on the item_type. Args: items (list): A list of items to be numbered. Returns: str: The formatted numbered list. |
4,500 | from typing import Union
from promptflow import tool
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection
def search(entity: str, count: int = 10):
"""
The input is an exact entity name. The action will search this entity name on Wikipedia and returns the first
count sentences if it e... | null |
4,501 | import os
from openai.version import VERSION as OPENAI_VERSION
from dotenv import load_dotenv
from promptflow import tool
def to_bool(value) -> bool:
return str(value).lower() == "true"
def get_client():
if OPENAI_VERSION.startswith("0."):
raise Exception(
"Please upgrade your OpenAI package... | null |
4,502 | import io
from promptflow import tool
from promptflow.contracts.multimedia import Image
from PIL import Image as PIL_Image
def passthrough(input_image: Image) -> Image:
image_stream = io.BytesIO(input_image)
pil_image = PIL_Image.open(image_stream)
flipped_image = pil_image.transpose(PIL_Image.FLIP_LEFT_RI... | null |
4,503 | from promptflow import tool
def generate_result(llm_result="", default_result="") -> str:
if llm_result:
return llm_result
else:
return default_result | null |
4,504 | from promptflow import tool
import random
def content_safety_check(text: str) -> str:
# You can use a content safety node to replace this tool.
return random.choice([True, False]) | null |
4,505 | from promptflow import tool
def llm_result(question: str) -> str:
# You can use an LLM node to replace this tool.
return (
"Prompt flow is a suite of development tools designed to streamline "
"the end-to-end development cycle of LLM-based AI applications."
) | null |
4,506 | from promptflow import tool
def default_result(question: str) -> str:
return f"I'm not familiar with your query: {question}." | null |
4,508 | import difflib
import webbrowser
def show_diff(left_content, right_content, name="file"):
d = difflib.HtmlDiff()
html = d.make_file(
left_content.splitlines(),
right_content.splitlines(),
"origin " + name,
"new " + name,
context=True,
numlines=20)
html = html... | null |
4,509 | from promptflow import tool
from divider import Divider
from typing import List
class Divider:
language = 'py'
def divide_file(cls, text) -> List[str]:
matches = list(re.finditer(Settings.divide_file[Divider.language], text))
splitted_content = []
min_pos = matches[0].start() if len(ma... | null |
4,510 | from promptflow import tool
from file import File
class File:
def __init__(self, source: str):
self._source = source
self._is_url = source.startswith("http://") or source.startswith("https://")
if self._is_url:
parsed_url = urlparse(source)
path = parsed_url.path
... | null |
4,511 | import ast
import asyncio
import logging
import os
import sys
from typing import Union, List
from promptflow import tool
from azure_open_ai import ChatLLM
from divider import Divider
from prompt import docstring_prompt, PromptLimitException
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection
def... | null |
4,512 | import ast
import asyncio
import logging
import os
import sys
from typing import Union, List
from promptflow import tool
from azure_open_ai import ChatLLM
from divider import Divider
from prompt import docstring_prompt, PromptLimitException
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection
asyn... | null |
4,513 | from promptflow import tool
from divider import Divider
class Divider:
def divide_file(cls, text) -> List[str]:
def divide_half(cls, text) -> List[str]:
def get_functions_and_pos(cls, text):
def combine(cls, divided: List[str]):
def merge_doc2code(cls, docstring: str, origin_code: str) -> str:... | null |
4,514 | from promptflow import tool
def order_search(query: str) -> str:
print(f"Your query is {query}.\nSearching for order...")
return "Your order is being mailed, please wait patiently." | null |
4,515 | from promptflow import tool
def product_info(query: str) -> str:
print(f"Your query is {query}.\nLooking for product information...")
return "This product is produced by Microsoft." | null |
4,516 | from promptflow import tool
def generate_response(order_search="", product_info="", product_recommendation="") -> str:
default_response = "Sorry, no results matching your search were found."
responses = [order_search, product_info, product_recommendation]
return next((response for response in responses if ... | null |
4,517 | from promptflow import tool
def product_recommendation(query: str) -> str:
print(f"Your query is {query}.\nRecommending products...")
return "I recommend promptflow to you, which can solve your problem very well." | null |
4,518 | from promptflow import tool
def class_check(llm_result: str) -> str:
intentions_list = ["order_search", "product_info", "product_recommendation"]
matches = [intention for intention in intentions_list if intention in llm_result.lower()]
return matches[0] if matches else "unknown" | null |
4,519 | import bs4
import requests
from promptflow import tool
def fetch_text_content_from_url(url: str):
# Send a request to the URL
try:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/113.0.0.0 Safari/537.36 Edg/11... | null |
4,520 | import json
from promptflow import tool
def convert_to_dict(input_str: str):
try:
return json.loads(input_str)
except Exception as e:
print("The input is not valid, error: {}".format(e))
return {"category": "None", "evidence": "None"} | null |
4,521 | from promptflow import tool
def prepare_examples():
return [
{
"url": "https://play.google.com/store/apps/details?id=com.spotify.music",
"text_content": "Spotify is a free music and podcast streaming app with millions of songs, albums, and "
"original podcasts. It also o... | null |
4,522 | from promptflow import tool
from promptflow.connections import CustomStrongTypeConnection
from promptflow.contracts.types import Secret
class MyCustomConnection(CustomStrongTypeConnection):
def my_tool(connection: MyCustomConnection, input_text: str) -> str:
# Replace with your tool code.
# Use custom strong t... | null |
4,523 |
def hello(input_text: str) -> str:
# Replace with your own code.
return "Hello " + input_text | null |
4,524 | from promptflow import tool
from typing import List, Union, Dict
The provided code snippet includes necessary dependencies for implementing the `my_list_func` function. Write a Python function `def my_list_func(prefix: str = "", size: int = 10, **kwargs) -> List[Dict[str, Union[str, int, float, list, Dict]]]` to solve... | This is a dummy function to generate a list of items. :param prefix: prefix to add to each item. :param size: number of items to generate. :param kwargs: other parameters. :return: a list of items. Each item is a dict with the following keys: - value: for backend use. Required. - display_value: for UI display. Optional... |
4,525 | from promptflow import tool
from typing import List, Union, Dict
The provided code snippet includes necessary dependencies for implementing the `list_endpoint_names` function. Write a Python function `def list_endpoint_names(subscription_id: str = None, resource_group_name: str = None, ... | This is an example to show how to get Azure ML resource in tool input list function. :param subscription_id: Azure subscription id. :param resource_group_name: Azure resource group name. :param workspace_name: Azure ML workspace name. :param prefix: prefix to add to each item. |
4,526 | from promptflow import tool
from typing import List, Union, Dict
def my_tool(input_prefix: str, input_text: list, endpoint_name: str) -> str:
return f"Hello {input_prefix} {','.join(input_text)} {endpoint_name}" | null |
4,527 | from pathlib import Path
from ruamel.yaml import YAML
def collect_tools_from_directory(base_dir) -> dict:
tools = {}
yaml = YAML()
for f in Path(base_dir).glob("**/*.yaml"):
with open(f, "r") as f:
tools_in_file = yaml.load(f)
for identifier, tool in tools_in_file.items():
... | List package tools |
4,528 | from promptflow import tool
from promptflow.connections import CustomStrongTypeConnection
from promptflow.contracts.types import Secret
class MyCustomConnection(CustomStrongTypeConnection):
"""My custom strong type connection.
:param api_key: The api key get from "https://xxx.com".
:type api_key: Secret
... | null |
4,529 | from enum import Enum
from promptflow import tool
class UserType(str, Enum):
STUDENT = "student"
TEACHER = "teacher"
The provided code snippet includes necessary dependencies for implementing the `my_tool` function. Write a Python function `def my_tool(user_type: Enum, student_id: str = "", teacher_id: str = "... | This is a dummy function to support cascading inputs. :param user_type: user type, student or teacher. :param student_id: student id. :param teacher_id: teacher id. :return: id of the user. If user_type is student, return student_id. If user_type is teacher, return teacher_id. |
4,530 | from promptflow import tool
from promptflow.connections import CustomConnection
def my_tool(connection: CustomConnection, input_text: str) -> str:
# Replace with your tool code.
# Usually connection contains configs to connect to an API.
# Use CustomConnection is a dict. You can use it like: connection.api... | null |
4,531 | from jinja2 import Template
from promptflow import tool
from promptflow.connections import CustomConnection
from promptflow.contracts.types import PromptTemplate
def my_tool(
connection: CustomConnection,
api: str,
deployment_name: str,
temperature: float,
prompt: PromptTemplate,
**kwargs
) -> ... | null |
4,532 | import importlib
from pathlib import Path
from promptflow import tool
from promptflow.contracts.types import FilePath
def my_tool(input_file: FilePath, input_text: str) -> str:
# customise your own code to handle and use the input_file here
new_module = importlib.import_module(Path(input_file).stem)
retur... | null |
4,533 | from typing import Union
from promptflow import tool
from typing import Dict, List
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection, CognitiveSearchConnection
The provided code snippet includes necessary dependencies for implementing the `generate_index_json` function. Write a Python function... | This is a dummy function to generate a index json based on the inputs. |
4,534 | from typing import Union
from promptflow import tool
from typing import Dict, List
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection, CognitiveSearchConnection
The provided code snippet includes necessary dependencies for implementing the `reverse_generate_index_json` function. Write a Python ... | This is a dummy function to generate origin inputs from index_json. |
4,535 | from typing import Union
from promptflow import tool
from typing import Dict, List
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection, CognitiveSearchConnection
def list_index_types(subscription_id, resource_group_name, workspace_name) -> List[str]:
return [
{"value": "Azure Cogniti... | null |
4,536 | from typing import Union
from promptflow import tool
from typing import Dict, List
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection, CognitiveSearchConnection
def list_indexes(
subscription_id,
resource_group_name,
workspace_name
) -> List[Dict[str, Union[str, int, flo... | null |
4,537 | from typing import Union
from promptflow import tool
from typing import Dict, List
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection, CognitiveSearchConnection
def list_fields(subscription_id, resource_group_name, workspace_name) -> List[str]:
return [
{"value": "id"},
{"va... | null |
4,538 | from typing import Union
from promptflow import tool
from typing import Dict, List
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection, CognitiveSearchConnection
def list_semantic_configuration(subscription_id, resource_group_name, workspace_name) -> List[str]:
return [{"value": "azureml-def... | null |
4,539 | from typing import Union
from promptflow import tool
from typing import Dict, List
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection, CognitiveSearchConnection
def list_embedding_deployment(embedding_connection: str) -> List[str]:
return [{"value": "text-embedding-ada-002"}, {"value": "ada... | null |
4,540 | from typing import Union
from promptflow import tool
from typing import Dict, List
from promptflow.connections import AzureOpenAIConnection, OpenAIConnection, CognitiveSearchConnection
def my_tool(index_json: str, queries: str, top_k: int) -> str:
return f"Hello {index_json}" | null |
4,541 | import argparse
import time
from pathlib import Path
import requests
from azure.ai.ml import MLClient, load_environment
from azure.identity import AzureCliCredential
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--path", help="Path to config.json", type=str)
... | null |
4,542 | import argparse
import time
from pathlib import Path
import requests
from azure.ai.ml import MLClient, load_environment
from azure.identity import AzureCliCredential
def init_ml_client(
subscription_id: str,
resource_group_name: str,
workspace_name: str,
) -> MLClient:
return MLClient(
credenti... | null |
4,543 | import argparse
import time
from pathlib import Path
import requests
from azure.ai.ml import MLClient, load_environment
from azure.identity import AzureCliCredential
ENVIRONMENT_YAML = Path(__file__).parent / "runtime-env" / "env.yaml"
def create_environment(ml_client: MLClient) -> str:
environment = load_environm... | null |
4,544 | import argparse
import json
import os
import re
from datetime import datetime, timedelta
from azure.storage.blob import (
AccountSasPermissions,
BlobServiceClient,
ContentSettings,
ResourceTypes,
generate_account_sas,
)
The provided code snippet includes necessary dependencies for implementing the ... | The wheel filename is {distribution}-{version}(-{build tag})?-{python tag}-{abi tag}-{platform tag}.whl. The distribution name is normalized from the package name. |
4,545 | import argparse
import json
import os
import re
from datetime import datetime, timedelta
from azure.storage.blob import (
AccountSasPermissions,
BlobServiceClient,
ContentSettings,
ResourceTypes,
generate_account_sas,
)
def get_connection_string(storage_account, storage_key):
return f"DefaultEnd... | null |
4,546 | import sys
from gallery_directive import GalleryDirective
class GalleryDirective(SphinxDirective):
"""A directive to show a gallery of images and links in a grid."""
name = "gallery-grid"
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = True
opti... | null |
4,547 | import argparse
import json
from pathlib import Path
from azure.keyvault.secrets import SecretClient
from azure.identity import ClientSecretCredential, DefaultAzureCredential
def get_secret_client(
tenant_id: str, client_id: str, client_secret: str
) -> SecretClient:
try:
if (tenant_id is None) or (cli... | null |
4,548 | import argparse
import json
from pathlib import Path
from azure.keyvault.secrets import SecretClient
from azure.identity import ClientSecretCredential, DefaultAzureCredential
def get_secret(secret_name: str, client: SecretClient):
secret = client.get_secret(secret_name)
return secret.value | null |
4,549 | import argparse
import json
from pathlib import Path
from azure.keyvault.secrets import SecretClient
from azure.identity import ClientSecretCredential, DefaultAzureCredential
def list_secret_names(client: SecretClient) -> list:
secret_properties = client.list_properties_of_secrets()
return [secret.name for se... | null |
4,550 | import argparse
import json
from pathlib import Path
from azure.keyvault.secrets import SecretClient
from azure.identity import ClientSecretCredential, DefaultAzureCredential
def fill_key_to_dict(template_dict, keys_dict):
if not isinstance(template_dict, dict):
return
for key, val in template_dict.ite... | null |
4,551 | import argparse
from pathlib import Path
from platform import system
from utils import print_blue, run_command
def print_blue(message):
def run_command(
commands, cwd=None, stderr=subprocess.STDOUT, shell=False, stream_stdout=True, throw_on_retcode=True, logger=None
):
def setup_promptflow(extra_deps: lis... | null |
4,552 | import logging
import os
import subprocess
import sys
import time
import traceback
class Color:
PURPLE = "\033[95m"
CYAN = "\033[96m"
DARKCYAN = "\033[36m"
BLUE = "\033[94m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
END = "\033... | null |
4,553 | import logging
import os
import subprocess
import sys
import time
import traceback
module_logger = logging.getLogger(__name__)
def get_test_files(testpath):
if os.path.isfile(testpath):
return [testpath]
else:
res = []
for root, dirs, files in os.walk(testpath):
module_logge... | null |
4,554 | import logging
import os
import subprocess
import sys
import time
import traceback
def retry(fn, num_attempts=3):
if num_attempts <= 0:
raise Exception("Illegal num_attempts: {}".format(num_attempts))
count = 0
for _ in range(0, num_attempts):
try:
return fn()
except Exc... | null |
4,555 | import os
import fnmatch
import subprocess
import time
import argparse
import json
import sys
github_repository = "microsoft/promptflow"
snippet_debug = os.getenv("SNIPPET_DEBUG", 0)
merge_commit = ""
loop_times = 30
github_workspace = os.path.expanduser("~/promptflow/")
failed_reason = ""
def trigger_checks(valid_stat... | null |
4,556 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
def create_tmp_dir():
tmp_dir = tempfile.mkdtemp()
return tmp_dir | null |
4,557 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
def is_valid_sha256sum(a_file, expected_sum):
sha256 = hashlib.sha256()
with open(a_file, 'rb') as f:
sha256.update(f.read())
computed_hash = sha256.hexdigest()
return expected_sum ==... | null |
4,558 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
def exec_command(command_list, cwd=None, env=None):
print_status('Executing: '+str(command_list))
subprocess.check_call(command_list, cwd=cwd, env=env)
def create_virtualenv(install_dir):
cmd = [... | null |
4,559 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
def exec_command(command_list, cwd=None, env=None):
print_status('Executing: '+str(command_list))
subprocess.check_call(command_list, cwd=cwd, env=env)
def install_cli(install_dir, tmp_dir):
path... | null |
4,560 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
PF_DISPATCH_TEMPLATE = """#!/usr/bin/env bash
export PF_INSTALLER=Script
{install_dir}/bin/python -m promptflow._cli._pf.entry "$@"
"""
PFAZURE_DISPATCH_TEMPLATE = """#!/usr/bin/env bash
{install_dir}/bin/pyt... | null |
4,561 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
DEFAULT_INSTALL_DIR = os.path.expanduser(os.path.join('~', 'lib', 'promptflow'))
def print_status(msg=''):
print('-- '+msg)
def prompt_input_with_default(msg, default):
if default:
return prom... | null |
4,562 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
DEFAULT_EXEC_DIR = os.path.expanduser(os.path.join('~', 'bin'))
PFAZURE_EXECUTABLE_NAME = 'pfazure'
PFS_EXECUTABLE_NAME = 'pfs'
def print_status(msg=''):
print('-- '+msg)
def prompt_input_with_default(msg... | null |
4,563 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
class CLIInstallError(Exception):
pass
def print_status(msg=''):
print('-- '+msg)
def prompt_y_n(msg, default=None):
if default not in [None, 'y', 'n']:
raise ValueError("Valid values for ... | null |
4,564 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
class CLIInstallError(Exception):
pass
def print_status(msg=''):
print('-- '+msg)
def verify_python_version():
print_status('Verifying Python version.')
v = sys.version_info
if v < (3, 8)... | null |
4,565 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
class CLIInstallError(Exception):
def print_status(msg=''):
def prompt_y_n(msg, default=None):
def _native_dependencies_for_dist(verify_cmd_args, install_cmd_args, dep_list):
try:
print_status("E... | null |
4,566 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
def _get_linux_distro():
if platform.system() != 'Linux':
return None, None
try:
with open('/etc/os-release') as lines:
tokens = [line.strip() for line in lines]
exce... | null |
4,567 | import os
import sys
import platform
import stat
import tempfile
import shutil
import subprocess
import hashlib
PF_EXECUTABLE_NAME = 'pf'
PFAZURE_EXECUTABLE_NAME = 'pfazure'
PFS_EXECUTABLE_NAME = 'pfs'
class CLIInstallError(Exception):
pass
def verify_install_dir_exec_path_conflict(install_dir, exec_dir):
for ... | null |
4,568 | import argparse
import json
from pathlib import Path
from utils.secret_manager import get_secret, get_secret_client, list_secret_names
def fill_key_to_dict(template_dict, keys_dict):
if not isinstance(template_dict, dict):
return
for key, val in template_dict.items():
if isinstance(val, str) an... | null |
4,569 | import argparse
import os
import re
from jinja2 import Environment, FileSystemLoader
def make_pythonic_variable_name(input_string):
variable_name = input_string.strip()
variable_name = re.sub(r'\W|^(?=\d)', '_', variable_name)
if not variable_name[0].isalpha() and variable_name[0] != '_':
variable_... | null |
4,570 | import argparse
import os
import re
from jinja2 import Environment, FileSystemLoader
def convert_tool_name_to_class_name(tool_name):
return ''.join(word.title() for word in tool_name.split('_'))
def create_file(path):
with open(path, 'w'):
pass
def create_folder(path):
os.makedirs(path, exist_ok=Tru... | null |
4,571 | import argparse
import base64
import os
import io
from PIL import Image
def get_image_size(image_path):
with Image.open(image_path) as img:
width, height = img.size
return width, height | null |
4,572 | import argparse
import base64
import os
import io
from PIL import Image
def get_image_storage_size(image_path):
file_size_bytes = os.path.getsize(image_path)
file_size_mb = file_size_bytes / (1024 * 1024)
return file_size_mb | null |
4,573 | import argparse
import base64
import os
import io
from PIL import Image
def create_html_file(data_uri, output_path):
html_content = '<html>\n<body>\n<img src="{}" alt="My Image">\n</body>\n</html>'.format(data_uri)
with open(output_path, 'w') as file:
file.write(html_content) | null |
4,574 | import argparse
import base64
import os
import io
from PIL import Image
def image_to_data_url(image_path):
with open(image_path, "rb") as image_file:
# Create a BytesIO object from the image file
image_data = io.BytesIO(image_file.read())
# Open the image and resize it
img = Image.open(image... | null |
4,575 | import inspect
import types
from dataclasses import asdict
from utils.tool_utils import function_to_interface
from promptflow.contracts.tool import Tool, ToolType
from promptflow._internal import ToolProvider
from promptflow.exceptions import ErrorTarget, UserErrorException
def generate_python_tools_in_module(module, n... | null |
4,576 | import inspect
import types
from dataclasses import asdict
from utils.tool_utils import function_to_interface
from promptflow.contracts.tool import Tool, ToolType
from promptflow._internal import ToolProvider
from promptflow.exceptions import ErrorTarget, UserErrorException
def generate_custom_llm_tools_in_module(modul... | null |
4,577 | import json
import os
import shutil
import subprocess
from datetime import datetime
from pathlib import Path
import requests
scripts_dir = os.path.join(os.getcwd(), "scripts")
ado_promptflow_repo_url_format = "https://{0}@dev.azure.com/msdata/Vienna/_git/PromptFlow"
def replace_lines_from_file_under_hint(file_path, hin... | null |
4,578 | import json
import os
import shutil
import subprocess
from datetime import datetime
from pathlib import Path
import requests
scripts_dir = os.path.join(os.getcwd(), "scripts")
def deploy_test_endpoint(branch_name: str, ado_pat: str):
# PromptFlow-deploy-endpoint pipeline in ADO: https://msdata.visualstudio.com/Vie... | null |
4,579 | import re
from azure.core.exceptions import HttpResponseError, ResourceExistsError
from azure.identity import ClientSecretCredential
from azure.keyvault.secrets import SecretClient
from exceptions import (
SecretNameAlreadyExistsException,
SecretNameInvalidException,
SecretNoSetPermissionException,
)
reserv... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.