id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
154,535
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `copytree` function. Write a Python function `def copytree(src, dst, metadata=True, symlinks=False, ignore=None)` to solve the following problem: This is a contributed re-implementation of 'copytree' that should work with the exact same behavior on multiple platforms. When `metadata` is False, file metadata such as permissions and modification times are not copied. Here is the function: def copytree(src, dst, metadata=True, symlinks=False, ignore=None): """ This is a contributed re-implementation of 'copytree' that should work with the exact same behavior on multiple platforms. When `metadata` is False, file metadata such as permissions and modification times are not copied. """ def copy_file(src, dst, item): s = os.path.join(src, item) d = os.path.join(dst, item) if symlinks and os.path.islink(s): # pragma: no cover if os.path.lexists(d): os.remove(d) os.symlink(os.readlink(s), d) if metadata: try: st = os.lstat(s) mode = stat.S_IMODE(st.st_mode) os.lchmod(d, mode) except Exception: pass # lchmod not available elif os.path.isdir(s): copytree(s, d, metadata, symlinks, ignore) else: shutil.copy2(s, d) if metadata else shutil.copy(s, d) try: lst = os.listdir(src) if not os.path.exists(dst): os.makedirs(dst) if metadata: shutil.copystat(src, dst) except NotADirectoryError: # egg-link files copy_file(os.path.dirname(src), os.path.dirname(dst), os.path.basename(src)) return if ignore: excl = ignore(src, lst) lst = [x for x in lst if x not in excl] for item in lst: copy_file(src, dst, item)
This is a contributed re-implementation of 'copytree' that should work with the exact same behavior on multiple platforms. When `metadata` is False, file metadata such as permissions and modification times are not copied.
154,536
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `parse_s3_url` function. Write a Python function `def parse_s3_url(url)` to solve the following problem: Parses S3 URL. Returns bucket (domain) and file (full path). Here is the function: def parse_s3_url(url): """ Parses S3 URL. Returns bucket (domain) and file (full path). """ bucket = "" path = "" if url: result = urlparse(url) bucket = result.netloc path = result.path.strip("/") return bucket, path
Parses S3 URL. Returns bucket (domain) and file (full path).
154,537
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `human_size` function. Write a Python function `def human_size(num, suffix="B")` to solve the following problem: Convert bytes length to a human-readable version Here is the function: def human_size(num, suffix="B"): """ Convert bytes length to a human-readable version """ for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"): if abs(num) < 1024.0: return "{0:3.1f}{1!s}{2!s}".format(num, unit, suffix) num /= 1024.0 return "{0:.1f}{1!s}{2!s}".format(num, "Yi", suffix)
Convert bytes length to a human-readable version
154,538
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `string_to_timestamp` function. Write a Python function `def string_to_timestamp(timestring)` to solve the following problem: Accepts a str, returns an int timestamp. Here is the function: def string_to_timestamp(timestring): """ Accepts a str, returns an int timestamp. """ ts = None # Uses an extended version of Go's duration string. try: delta = durationpy.from_str(timestring) past = datetime.datetime.now(datetime.timezone.utc) - delta ts = calendar.timegm(past.timetuple()) return ts except Exception: pass if ts: return ts return 0
Accepts a str, returns an int timestamp.
154,539
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `detect_django_settings` function. Write a Python function `def detect_django_settings()` to solve the following problem: Automatically try to discover Django settings files, return them as relative module paths. Here is the function: def detect_django_settings(): """ Automatically try to discover Django settings files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, "*settings.py"): full = os.path.join(root, filename) if "site-packages" in full: continue full = os.path.join(root, filename) package_path = full.replace(os.getcwd(), "") package_module = package_path.replace(os.sep, ".").split(".", 1)[1].replace(".py", "") matches.append(package_module) return matches
Automatically try to discover Django settings files, return them as relative module paths.
154,540
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `detect_flask_apps` function. Write a Python function `def detect_flask_apps()` to solve the following problem: Automatically try to discover Flask apps files, return them as relative module paths. Here is the function: def detect_flask_apps(): """ Automatically try to discover Flask apps files, return them as relative module paths. """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.filter(filenames, "*.py"): full = os.path.join(root, filename) if "site-packages" in full: continue full = os.path.join(root, filename) with io.open(full, "r", encoding="utf-8") as f: lines = f.readlines() for line in lines: app = None # Kind of janky.. if "= Flask(" in line: app = line.split("= Flask(")[0].strip() if "=Flask(" in line: app = line.split("=Flask(")[0].strip() if not app: continue package_path = full.replace(os.getcwd(), "") package_module = package_path.replace(os.sep, ".").split(".", 1)[1].replace(".py", "") app_module = package_module + "." + app matches.append(app_module) return matches
Automatically try to discover Flask apps files, return them as relative module paths.
154,541
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy def get_venv_from_python_version(): return "python{}.{}".format(*sys.version_info)
null
154,542
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy def get_runtime_from_python_version(): """ """ if sys.version_info[0] < 3: raise ValueError("Python 2.x is no longer supported.") else: if sys.version_info[1] <= 7: raise ValueError("Python 3.7 and below are no longer supported.") elif sys.version_info[1] == 8: return "python3.8" elif sys.version_info[1] == 9: return "python3.9" elif sys.version_info[1] == 10: return "python3.10" elif sys.version_info[1] == 11: return "python3.11" elif sys.version_info[1] == 12: return "python3.12" else: raise ValueError(f"Python f{'.'.join(str(v) for v in sys.version_info[:2])} is not yet supported.")
null
154,543
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `get_topic_name` function. Write a Python function `def get_topic_name(lambda_name)` to solve the following problem: Topic name generation Here is the function: def get_topic_name(lambda_name): """Topic name generation""" return "%s-zappa-async" % lambda_name
Topic name generation
154,544
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy def get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary item, a session and a lambda_arn, hack into Kappa's Gibson, create out an object we can call to schedule this event, and return the event source. """ import kappa.awsclient import kappa.event_source.base import kappa.event_source.cloudwatch import kappa.event_source.dynamodb_stream import kappa.event_source.kinesis import kappa.event_source.s3 import kappa.event_source.sns import kappa.function import kappa.policy import kappa.restapi import kappa.role class PseudoContext: def __init__(self): return class PseudoFunction: def __init__(self): return # Mostly adapted from kappa - will probably be replaced by kappa support class SqsEventSource(kappa.event_source.base.EventSource): def __init__(self, context, config): super().__init__(context, config) self._lambda = kappa.awsclient.create_client("lambda", context.session) def batch_window(self): return self._config.get("batch_window", 1 if self.batch_size > 10 else 0) def _get_uuid(self, function): uuid = None response = self._lambda.call( "list_event_source_mappings", FunctionName=function.name, EventSourceArn=self.arn, ) LOG.debug(response) if len(response["EventSourceMappings"]) > 0: uuid = response["EventSourceMappings"][0]["UUID"] return uuid def add(self, function): try: response = self._lambda.call( "create_event_source_mapping", FunctionName=function.name, EventSourceArn=self.arn, BatchSize=self.batch_size, MaximumBatchingWindowInSeconds=self.batch_window, Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to add event source") def enable(self, function): self._config["enabled"] = True try: response = self._lambda.call( "update_event_source_mapping", UUID=self._get_uuid(function), Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to enable event source") def disable(self, function): self._config["enabled"] = False try: response = self._lambda.call( "update_event_source_mapping", FunctionName=function.name, Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to disable event source") def update(self, function): response = None uuid = self._get_uuid(function) if uuid: try: response = self._lambda.call( "update_event_source_mapping", BatchSize=self.batch_size, MaximumBatchingWindowInSeconds=self.batch_window, Enabled=self.enabled, FunctionName=function.arn, ) LOG.debug(response) except Exception: LOG.exception("Unable to update event source") def remove(self, function): response = None uuid = self._get_uuid(function) if uuid: response = self._lambda.call("delete_event_source_mapping", UUID=uuid) LOG.debug(response) return response def status(self, function): response = None LOG.debug("getting status for event source %s", self.arn) uuid = self._get_uuid(function) if uuid: try: response = self._lambda.call("get_event_source_mapping", UUID=self._get_uuid(function)) LOG.debug(response) except botocore.exceptions.ClientError: LOG.debug("event source %s does not exist", self.arn) response = None else: LOG.debug("No UUID for event source %s", self.arn) return response class ExtendedSnsEventSource(kappa.event_source.sns.SNSEventSource): def filters(self): return self._config.get("filters") def add_filters(self, function): try: subscription = self.exists(function) if subscription: response = self._sns.call( "set_subscription_attributes", SubscriptionArn=subscription["SubscriptionArn"], AttributeName="FilterPolicy", AttributeValue=json.dumps(self.filters), ) kappa.event_source.sns.LOG.debug(response) except Exception: kappa.event_source.sns.LOG.exception("Unable to add filters for SNS topic %s", self.arn) def add(self, function): super().add(function) if self.filters: self.add_filters(function) event_source_map = { "dynamodb": kappa.event_source.dynamodb_stream.DynamoDBStreamEventSource, "kinesis": kappa.event_source.kinesis.KinesisEventSource, "s3": kappa.event_source.s3.S3EventSource, "sns": ExtendedSnsEventSource, "sqs": SqsEventSource, "events": kappa.event_source.cloudwatch.CloudWatchEventSource, } arn = event_source["arn"] _, _, svc, _ = arn.split(":", 3) event_source_func = event_source_map.get(svc, None) if not event_source_func: raise ValueError("Unknown event source: {0}".format(arn)) def autoreturn(self, function_name): return function_name event_source_func._make_notification_id = autoreturn ctx = PseudoContext() ctx.session = boto_session funk = PseudoFunction() funk.name = lambda_arn # Kappa 0.6.0 requires this nasty hacking, # hopefully we can remove at least some of this soon. # Kappa 0.7.0 introduces a whole host over other changes we don't # really want, so we're stuck here for a little while. # Related: https://github.com/Miserlou/Zappa/issues/684 # https://github.com/Miserlou/Zappa/issues/688 # https://github.com/Miserlou/Zappa/commit/3216f7e5149e76921ecdf9451167846b95616313 if svc == "s3": split_arn = lambda_arn.split(":") arn_front = ":".join(split_arn[:-1]) arn_back = split_arn[-1] ctx.environment = arn_back funk.arn = arn_front funk.name = ":".join([arn_back, target_function]) else: funk.arn = lambda_arn funk._context = ctx event_source_obj = event_source_func(ctx, event_source) return event_source_obj, ctx, funk The provided code snippet includes necessary dependencies for implementing the `add_event_source` function. Write a Python function `def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False)` to solve the following problem: Given an event_source dictionary, create the object and add the event source. Here is the function: def add_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and add the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) # TODO: Detect changes in config and refine exists algorithm if not dry: if not event_source_obj.status(funk): event_source_obj.add(funk) return "successful" if event_source_obj.status(funk) else "failed" else: return "exists" return "dryrun"
Given an event_source dictionary, create the object and add the event source.
154,545
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy def get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary item, a session and a lambda_arn, hack into Kappa's Gibson, create out an object we can call to schedule this event, and return the event source. """ import kappa.awsclient import kappa.event_source.base import kappa.event_source.cloudwatch import kappa.event_source.dynamodb_stream import kappa.event_source.kinesis import kappa.event_source.s3 import kappa.event_source.sns import kappa.function import kappa.policy import kappa.restapi import kappa.role class PseudoContext: def __init__(self): return class PseudoFunction: def __init__(self): return # Mostly adapted from kappa - will probably be replaced by kappa support class SqsEventSource(kappa.event_source.base.EventSource): def __init__(self, context, config): super().__init__(context, config) self._lambda = kappa.awsclient.create_client("lambda", context.session) def batch_window(self): return self._config.get("batch_window", 1 if self.batch_size > 10 else 0) def _get_uuid(self, function): uuid = None response = self._lambda.call( "list_event_source_mappings", FunctionName=function.name, EventSourceArn=self.arn, ) LOG.debug(response) if len(response["EventSourceMappings"]) > 0: uuid = response["EventSourceMappings"][0]["UUID"] return uuid def add(self, function): try: response = self._lambda.call( "create_event_source_mapping", FunctionName=function.name, EventSourceArn=self.arn, BatchSize=self.batch_size, MaximumBatchingWindowInSeconds=self.batch_window, Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to add event source") def enable(self, function): self._config["enabled"] = True try: response = self._lambda.call( "update_event_source_mapping", UUID=self._get_uuid(function), Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to enable event source") def disable(self, function): self._config["enabled"] = False try: response = self._lambda.call( "update_event_source_mapping", FunctionName=function.name, Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to disable event source") def update(self, function): response = None uuid = self._get_uuid(function) if uuid: try: response = self._lambda.call( "update_event_source_mapping", BatchSize=self.batch_size, MaximumBatchingWindowInSeconds=self.batch_window, Enabled=self.enabled, FunctionName=function.arn, ) LOG.debug(response) except Exception: LOG.exception("Unable to update event source") def remove(self, function): response = None uuid = self._get_uuid(function) if uuid: response = self._lambda.call("delete_event_source_mapping", UUID=uuid) LOG.debug(response) return response def status(self, function): response = None LOG.debug("getting status for event source %s", self.arn) uuid = self._get_uuid(function) if uuid: try: response = self._lambda.call("get_event_source_mapping", UUID=self._get_uuid(function)) LOG.debug(response) except botocore.exceptions.ClientError: LOG.debug("event source %s does not exist", self.arn) response = None else: LOG.debug("No UUID for event source %s", self.arn) return response class ExtendedSnsEventSource(kappa.event_source.sns.SNSEventSource): def filters(self): return self._config.get("filters") def add_filters(self, function): try: subscription = self.exists(function) if subscription: response = self._sns.call( "set_subscription_attributes", SubscriptionArn=subscription["SubscriptionArn"], AttributeName="FilterPolicy", AttributeValue=json.dumps(self.filters), ) kappa.event_source.sns.LOG.debug(response) except Exception: kappa.event_source.sns.LOG.exception("Unable to add filters for SNS topic %s", self.arn) def add(self, function): super().add(function) if self.filters: self.add_filters(function) event_source_map = { "dynamodb": kappa.event_source.dynamodb_stream.DynamoDBStreamEventSource, "kinesis": kappa.event_source.kinesis.KinesisEventSource, "s3": kappa.event_source.s3.S3EventSource, "sns": ExtendedSnsEventSource, "sqs": SqsEventSource, "events": kappa.event_source.cloudwatch.CloudWatchEventSource, } arn = event_source["arn"] _, _, svc, _ = arn.split(":", 3) event_source_func = event_source_map.get(svc, None) if not event_source_func: raise ValueError("Unknown event source: {0}".format(arn)) def autoreturn(self, function_name): return function_name event_source_func._make_notification_id = autoreturn ctx = PseudoContext() ctx.session = boto_session funk = PseudoFunction() funk.name = lambda_arn # Kappa 0.6.0 requires this nasty hacking, # hopefully we can remove at least some of this soon. # Kappa 0.7.0 introduces a whole host over other changes we don't # really want, so we're stuck here for a little while. # Related: https://github.com/Miserlou/Zappa/issues/684 # https://github.com/Miserlou/Zappa/issues/688 # https://github.com/Miserlou/Zappa/commit/3216f7e5149e76921ecdf9451167846b95616313 if svc == "s3": split_arn = lambda_arn.split(":") arn_front = ":".join(split_arn[:-1]) arn_back = split_arn[-1] ctx.environment = arn_back funk.arn = arn_front funk.name = ":".join([arn_back, target_function]) else: funk.arn = lambda_arn funk._context = ctx event_source_obj = event_source_func(ctx, event_source) return event_source_obj, ctx, funk The provided code snippet includes necessary dependencies for implementing the `remove_event_source` function. Write a Python function `def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False)` to solve the following problem: Given an event_source dictionary, create the object and remove the event source. Here is the function: def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and remove the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) # This is slightly dirty, but necessary for using Kappa this way. funk.arn = lambda_arn if not dry: rule_response = event_source_obj.remove(funk) return rule_response else: return event_source_obj
Given an event_source dictionary, create the object and remove the event source.
154,546
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy def get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary item, a session and a lambda_arn, hack into Kappa's Gibson, create out an object we can call to schedule this event, and return the event source. """ import kappa.awsclient import kappa.event_source.base import kappa.event_source.cloudwatch import kappa.event_source.dynamodb_stream import kappa.event_source.kinesis import kappa.event_source.s3 import kappa.event_source.sns import kappa.function import kappa.policy import kappa.restapi import kappa.role class PseudoContext: def __init__(self): return class PseudoFunction: def __init__(self): return # Mostly adapted from kappa - will probably be replaced by kappa support class SqsEventSource(kappa.event_source.base.EventSource): def __init__(self, context, config): super().__init__(context, config) self._lambda = kappa.awsclient.create_client("lambda", context.session) def batch_window(self): return self._config.get("batch_window", 1 if self.batch_size > 10 else 0) def _get_uuid(self, function): uuid = None response = self._lambda.call( "list_event_source_mappings", FunctionName=function.name, EventSourceArn=self.arn, ) LOG.debug(response) if len(response["EventSourceMappings"]) > 0: uuid = response["EventSourceMappings"][0]["UUID"] return uuid def add(self, function): try: response = self._lambda.call( "create_event_source_mapping", FunctionName=function.name, EventSourceArn=self.arn, BatchSize=self.batch_size, MaximumBatchingWindowInSeconds=self.batch_window, Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to add event source") def enable(self, function): self._config["enabled"] = True try: response = self._lambda.call( "update_event_source_mapping", UUID=self._get_uuid(function), Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to enable event source") def disable(self, function): self._config["enabled"] = False try: response = self._lambda.call( "update_event_source_mapping", FunctionName=function.name, Enabled=self.enabled, ) LOG.debug(response) except Exception: LOG.exception("Unable to disable event source") def update(self, function): response = None uuid = self._get_uuid(function) if uuid: try: response = self._lambda.call( "update_event_source_mapping", BatchSize=self.batch_size, MaximumBatchingWindowInSeconds=self.batch_window, Enabled=self.enabled, FunctionName=function.arn, ) LOG.debug(response) except Exception: LOG.exception("Unable to update event source") def remove(self, function): response = None uuid = self._get_uuid(function) if uuid: response = self._lambda.call("delete_event_source_mapping", UUID=uuid) LOG.debug(response) return response def status(self, function): response = None LOG.debug("getting status for event source %s", self.arn) uuid = self._get_uuid(function) if uuid: try: response = self._lambda.call("get_event_source_mapping", UUID=self._get_uuid(function)) LOG.debug(response) except botocore.exceptions.ClientError: LOG.debug("event source %s does not exist", self.arn) response = None else: LOG.debug("No UUID for event source %s", self.arn) return response class ExtendedSnsEventSource(kappa.event_source.sns.SNSEventSource): def filters(self): return self._config.get("filters") def add_filters(self, function): try: subscription = self.exists(function) if subscription: response = self._sns.call( "set_subscription_attributes", SubscriptionArn=subscription["SubscriptionArn"], AttributeName="FilterPolicy", AttributeValue=json.dumps(self.filters), ) kappa.event_source.sns.LOG.debug(response) except Exception: kappa.event_source.sns.LOG.exception("Unable to add filters for SNS topic %s", self.arn) def add(self, function): super().add(function) if self.filters: self.add_filters(function) event_source_map = { "dynamodb": kappa.event_source.dynamodb_stream.DynamoDBStreamEventSource, "kinesis": kappa.event_source.kinesis.KinesisEventSource, "s3": kappa.event_source.s3.S3EventSource, "sns": ExtendedSnsEventSource, "sqs": SqsEventSource, "events": kappa.event_source.cloudwatch.CloudWatchEventSource, } arn = event_source["arn"] _, _, svc, _ = arn.split(":", 3) event_source_func = event_source_map.get(svc, None) if not event_source_func: raise ValueError("Unknown event source: {0}".format(arn)) def autoreturn(self, function_name): return function_name event_source_func._make_notification_id = autoreturn ctx = PseudoContext() ctx.session = boto_session funk = PseudoFunction() funk.name = lambda_arn # Kappa 0.6.0 requires this nasty hacking, # hopefully we can remove at least some of this soon. # Kappa 0.7.0 introduces a whole host over other changes we don't # really want, so we're stuck here for a little while. # Related: https://github.com/Miserlou/Zappa/issues/684 # https://github.com/Miserlou/Zappa/issues/688 # https://github.com/Miserlou/Zappa/commit/3216f7e5149e76921ecdf9451167846b95616313 if svc == "s3": split_arn = lambda_arn.split(":") arn_front = ":".join(split_arn[:-1]) arn_back = split_arn[-1] ctx.environment = arn_back funk.arn = arn_front funk.name = ":".join([arn_back, target_function]) else: funk.arn = lambda_arn funk._context = ctx event_source_obj = event_source_func(ctx, event_source) return event_source_obj, ctx, funk The provided code snippet includes necessary dependencies for implementing the `get_event_source_status` function. Write a Python function `def get_event_source_status(event_source, lambda_arn, target_function, boto_session, dry=False)` to solve the following problem: Given an event_source dictionary, create the object and get the event source status. Here is the function: def get_event_source_status(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and get the event source status. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) return event_source_obj.status(funk)
Given an event_source dictionary, create the object and get the event source status.
154,547
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `check_new_version_available` function. Write a Python function `def check_new_version_available(this_version)` to solve the following problem: Checks if a newer version of Zappa is available. Returns True is updateable, else False. Here is the function: def check_new_version_available(this_version): """ Checks if a newer version of Zappa is available. Returns True is updateable, else False. """ import requests pypi_url = "https://pypi.org/pypi/Zappa/json" resp = requests.get(pypi_url, timeout=1.5) top_version = resp.json()["info"]["version"] return this_version != top_version
Checks if a newer version of Zappa is available. Returns True is updateable, else False.
154,548
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy class InvalidAwsLambdaName(Exception): """Exception: proposed AWS Lambda name is invalid""" pass The provided code snippet includes necessary dependencies for implementing the `validate_name` function. Write a Python function `def validate_name(name, maxlen=80)` to solve the following problem: Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with longest known region name and assuming that no alias or version would be longer than `$LATEST`. Based on AWS Lambda spec http://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html Return: the name Raise: InvalidAwsLambdaName, if the name is invalid. Here is the function: def validate_name(name, maxlen=80): """Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with longest known region name and assuming that no alias or version would be longer than `$LATEST`. Based on AWS Lambda spec http://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html Return: the name Raise: InvalidAwsLambdaName, if the name is invalid. """ if not isinstance(name, str): msg = "Name must be of type string" raise InvalidAwsLambdaName(msg) if len(name) > maxlen: msg = "Name is longer than {maxlen} characters." raise InvalidAwsLambdaName(msg.format(maxlen=maxlen)) if len(name) == 0: msg = "Name must not be empty string." raise InvalidAwsLambdaName(msg) if not re.match("^[a-zA-Z0-9-_]+$", name): msg = "Name can only contain characters from a-z, A-Z, 0-9, _ and -" raise InvalidAwsLambdaName(msg) return name
Validate name for AWS Lambda function. name: actual name (without `arn:aws:lambda:...:` prefix and without `:$LATEST`, alias or version suffix. maxlen: max allowed length for name without prefix and suffix. The value 80 was calculated from prefix with longest known region name and assuming that no alias or version would be longer than `$LATEST`. Based on AWS Lambda spec http://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html Return: the name Raise: InvalidAwsLambdaName, if the name is invalid.
154,549
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `contains_python_files_or_subdirs` function. Write a Python function `def contains_python_files_or_subdirs(folder)` to solve the following problem: Checks (recursively) if the directory contains .py or .pyc files Here is the function: def contains_python_files_or_subdirs(folder): """ Checks (recursively) if the directory contains .py or .pyc files """ for root, dirs, files in os.walk(folder): if [filename for filename in files if filename.endswith(".py") or filename.endswith(".pyc")]: return True for d in dirs: for _, subdirs, subfiles in os.walk(d): if [filename for filename in subfiles if filename.endswith(".py") or filename.endswith(".pyc")]: return True return False
Checks (recursively) if the directory contains .py or .pyc files
154,550
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `conflicts_with_a_neighbouring_module` function. Write a Python function `def conflicts_with_a_neighbouring_module(directory_path)` to solve the following problem: Checks if a directory lies in the same directory as a .py file with the same name. Here is the function: def conflicts_with_a_neighbouring_module(directory_path): """ Checks if a directory lies in the same directory as a .py file with the same name. """ parent_dir_path, current_dir_name = os.path.split(os.path.normpath(directory_path)) neighbours = os.listdir(parent_dir_path) conflicting_neighbour_filename = current_dir_name + ".py" return conflicting_neighbour_filename in neighbours
Checks if a directory lies in the same directory as a .py file with the same name.
154,551
import calendar import datetime import fnmatch import io import json import logging import os import re import shutil import stat import sys from typing import Any, Callable from urllib.parse import urlparse import botocore import durationpy The provided code snippet includes necessary dependencies for implementing the `is_valid_bucket_name` function. Write a Python function `def is_valid_bucket_name(name)` to solve the following problem: Checks if an S3 bucket name is valid according to: https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules Here is the function: def is_valid_bucket_name(name): """ Checks if an S3 bucket name is valid according to: https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules """ # Bucket names must be at least 3 and no more than 63 characters long. if len(name) < 3 or len(name) > 63: return False # Bucket names must not contain uppercase characters or underscores. if any(x.isupper() for x in name): return False if "_" in name: return False # Bucket names must start with a lowercase letter or number. if not (name[0].islower() or name[0].isdigit()): return False # Bucket names must be a series of one or more labels. Adjacent labels are separated by a single period (.). for label in name.split("."): # Each label must start and end with a lowercase letter or a number. if len(label) < 1: return False if not (label[0].islower() or label[0].isdigit()): return False if not (label[-1].islower() or label[-1].isdigit()): return False # Bucket names must not be formatted as an IP address (for example, 192.168.5.4). looks_like_IP = True for label in name.split("."): if not label.isdigit(): looks_like_IP = False break if looks_like_IP: return False return True
Checks if an S3 bucket name is valid according to: https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules
154,552
from werkzeug.wsgi import ClosingIterator The provided code snippet includes necessary dependencies for implementing the `all_casings` function. Write a Python function `def all_casings(input_string)` to solve the following problem: Permute all casings of a given string. A pretty algorithm, via @Amber http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python Here is the function: def all_casings(input_string): """ Permute all casings of a given string. A pretty algorithm, via @Amber http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python """ if not input_string: yield "" else: first = input_string[:1] if first.lower() == first.upper(): for sub_casing in all_casings(input_string[1:]): yield first + sub_casing else: for sub_casing in all_casings(input_string[1:]): yield first.lower() + sub_casing yield first.upper() + sub_casing
Permute all casings of a given string. A pretty algorithm, via @Amber http://stackoverflow.com/questions/6792803/finding-all-possible-case-permutations-in-python
154,553
import atexit import base64 import binascii import copy import hashlib import json import logging import os import re import shutil import subprocess import tempfile import textwrap import time from urllib.request import urlopen import requests def create_domain_key(): devnull = open(os.devnull, "wb") out = subprocess.check_output(["openssl", "genrsa", "2048"], stderr=devnull) with open(os.path.join(gettempdir(), "domain.key"), "wb") as f: f.write(out) def create_domain_csr(domain): subj = "/CN=" + domain cmd = [ "openssl", "req", "-new", "-sha256", "-key", os.path.join(gettempdir(), "domain.key"), "-subj", subj, ] devnull = open(os.devnull, "wb") out = subprocess.check_output(cmd, stderr=devnull) with open(os.path.join(gettempdir(), "domain.csr"), "wb") as f: f.write(out) def create_chained_certificate(): signed_crt = open(os.path.join(gettempdir(), "signed.crt"), "rb").read() cross_cert_url = "https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem" cert = requests.get(cross_cert_url) with open(os.path.join(gettempdir(), "intermediate.pem"), "wb") as intermediate_pem: intermediate_pem.write(cert.content) with open(os.path.join(gettempdir(), "chained.pem"), "wb") as chained_pem: chained_pem.write(signed_crt) chained_pem.write(cert.content) def get_cert(zappa_instance, log=LOGGER, CA=DEFAULT_CA): """ Call LE to get a new signed CA. """ out = parse_account_key() header = get_boulder_header(out) accountkey_json = json.dumps(header["jwk"], sort_keys=True, separators=(",", ":")) thumbprint = _b64(hashlib.sha256(accountkey_json.encode("utf8")).digest()) # find domains domains = parse_csr() # get the certificate domains and expiration register_account() # verify each domain for domain in domains: log.info("Verifying {0}...".format(domain)) # get new challenge code, result = _send_signed_request( CA + "/acme/new-authz", { "resource": "new-authz", "identifier": {"type": "dns", "value": domain}, }, ) if code != 201: raise ValueError("Error requesting challenges: {0} {1}".format(code, result)) challenge = [ch for ch in json.loads(result.decode("utf8"))["challenges"] if ch["type"] == "dns-01"][0] token = re.sub(r"[^A-Za-z0-9_\-]", "_", challenge["token"]) keyauthorization = "{0}.{1}".format(token, thumbprint).encode("utf-8") # sha256_b64 digest = _b64(hashlib.sha256(keyauthorization).digest()) zone_id = zappa_instance.get_hosted_zone_id_for_domain(domain) if not zone_id: raise ValueError("Could not find Zone ID for: " + domain) zappa_instance.set_dns_challenge_txt(zone_id, domain, digest) # resp is unused print("Waiting for DNS to propagate..") # What's optimal here? # import time # double import; import in loop; shadowed import time.sleep(45) # notify challenge are met code, result = _send_signed_request( challenge["uri"], { "resource": "challenge", "keyAuthorization": keyauthorization.decode("utf-8"), }, ) if code != 202: raise ValueError("Error triggering challenge: {0} {1}".format(code, result)) # wait for challenge to be verified verify_challenge(challenge["uri"]) # Challenge verified, clean up R53 zappa_instance.remove_dns_challenge_txt(zone_id, domain, digest) # Sign result = sign_certificate() # Encode to PEM format encode_certificate(result) return True def gettempdir(): """ Lazily creates a temporary directory in a secure manner. When Python exits, or the cleanup() function is called, the directory is erased. """ global __tempdir if __tempdir is not None: return __tempdir __tempdir = tempfile.mkdtemp() return __tempdir The provided code snippet includes necessary dependencies for implementing the `get_cert_and_update_domain` function. Write a Python function `def get_cert_and_update_domain( zappa_instance, lambda_name, api_stage, domain=None, manual=False, )` to solve the following problem: Main cert installer path. Here is the function: def get_cert_and_update_domain( zappa_instance, lambda_name, api_stage, domain=None, manual=False, ): """ Main cert installer path. """ try: create_domain_key() create_domain_csr(domain) get_cert(zappa_instance) create_chained_certificate() with open("{}/signed.crt".format(gettempdir())) as f: certificate_body = f.read() with open("{}/domain.key".format(gettempdir())) as f: certificate_private_key = f.read() with open("{}/intermediate.pem".format(gettempdir())) as f: certificate_chain = f.read() if not manual: if domain: if not zappa_instance.get_domain_name(domain): zappa_instance.create_domain_name( domain_name=domain, certificate_name=domain + "-Zappa-LE-Cert", certificate_body=certificate_body, certificate_private_key=certificate_private_key, certificate_chain=certificate_chain, certificate_arn=None, lambda_name=lambda_name, stage=api_stage, ) print( "Created a new domain name. " "Please note that it can take up to 40 minutes " "for this domain to be created and propagated through AWS, " "but it requires no further work on your part." ) else: zappa_instance.update_domain_name( domain_name=domain, certificate_name=domain + "-Zappa-LE-Cert", certificate_body=certificate_body, certificate_private_key=certificate_private_key, certificate_chain=certificate_chain, certificate_arn=None, lambda_name=lambda_name, stage=api_stage, ) else: print("Cerificate body:\n") print(certificate_body) print("\nCerificate private key:\n") print(certificate_private_key) print("\nCerificate chain:\n") print(certificate_chain) except Exception as e: print(e) return False return True
Main cert installer path.
154,554
import atexit import base64 import binascii import copy import hashlib import json import logging import os import re import shutil import subprocess import tempfile import textwrap import time from urllib.request import urlopen import requests __tempdir = None The provided code snippet includes necessary dependencies for implementing the `cleanup` function. Write a Python function `def cleanup()` to solve the following problem: Delete any temporary files. Here is the function: def cleanup(): """ Delete any temporary files. """ global __tempdir if __tempdir is not None: shutil.rmtree(__tempdir) __tempdir = None
Delete any temporary files.
154,555
import base64 import collections import datetime import importlib import inspect import json import logging import os import sys import tarfile import traceback from builtins import str from types import ModuleType from typing import Tuple import boto3 from werkzeug.wrappers import Response def lambda_handler(event, context): # pragma: no cover return LambdaHandler.lambda_handler(event, context) The provided code snippet includes necessary dependencies for implementing the `keep_warm_callback` function. Write a Python function `def keep_warm_callback(event, context)` to solve the following problem: Method is triggered by the CloudWatch event scheduled when keep_warm setting is set to true. Here is the function: def keep_warm_callback(event, context): """Method is triggered by the CloudWatch event scheduled when keep_warm setting is set to true.""" lambda_handler(event={}, context=context) # overriding event with an empty one so that web app initialization will # be triggered.
Method is triggered by the CloudWatch event scheduled when keep_warm setting is set to true.
154,556
import base64 import logging import sys from io import BytesIO from typing import Optional from urllib.parse import unquote, urlencode from .utilities import ApacheNCSAFormatter, merge_headers, titlecase_keys BINARY_METHODS = ["POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS"] def get_wsgi_string(string, encoding="utf-8"): """ Returns wsgi-compatible string """ return string.encode(encoding).decode("iso-8859-1") def titlecase_keys(d): """ Takes a dict with keys of type str and returns a new dict with all keys titlecased. """ return {k.title(): v for k, v in d.items()} def merge_headers(event): """ Merge the values of headers and multiValueHeaders into a single dict. Opens up support for multivalue headers via API Gateway and ALB. See: https://github.com/Miserlou/Zappa/pull/1756 """ headers = event.get("headers") or {} multi_headers = (event.get("multiValueHeaders") or {}).copy() for h in set(headers.keys()): if h not in multi_headers: multi_headers[h] = [headers[h]] for h in multi_headers.keys(): multi_headers[h] = ", ".join(multi_headers[h]) return multi_headers The provided code snippet includes necessary dependencies for implementing the `create_wsgi_request` function. Write a Python function `def create_wsgi_request( event_info, server_name="zappa", script_name=None, trailing_slash=True, binary_support=False, base_path=None, context_header_mappings={}, )` to solve the following problem: Given some event_info via API Gateway, create and return a valid WSGI request environ. Here is the function: def create_wsgi_request( event_info, server_name="zappa", script_name=None, trailing_slash=True, binary_support=False, base_path=None, context_header_mappings={}, ): """ Given some event_info via API Gateway, create and return a valid WSGI request environ. """ method = event_info.get("httpMethod", None) headers = merge_headers(event_info) or {} # Allow for the AGW console 'Test' button to work (Pull #735) # API Gateway and ALB both started allowing for multi-value querystring # params in Nov. 2018. If there aren't multi-value params present, then # it acts identically to 'queryStringParameters', so we can use it as a # drop-in replacement. # # The one caveat here is that ALB will only include _one_ of # queryStringParameters _or_ multiValueQueryStringParameters, which means # we have to check for the existence of one and then fall back to the # other. # Assumes that the lambda event provides the unencoded string as # the value in "queryStringParameters"/"multiValueQueryStringParameters" # The QUERY_STRING value provided to WSGI expects the query string to be properly urlencoded. # See https://github.com/zappa/Zappa/issues/1227 for discussion of this behavior. if "multiValueQueryStringParameters" in event_info: query = event_info["multiValueQueryStringParameters"] query_string = urlencode(query, doseq=True) if query else "" else: query = event_info.get("queryStringParameters", {}) query_string = urlencode(query) if query else "" if context_header_mappings: for key, value in context_header_mappings.items(): parts = value.split(".") header_val = event_info["requestContext"] for part in parts: if part not in header_val: header_val = None break else: header_val = header_val[part] if header_val is not None: headers[key] = header_val # Related: https://github.com/Miserlou/Zappa/issues/677 # https://github.com/Miserlou/Zappa/issues/683 # https://github.com/Miserlou/Zappa/issues/696 # https://github.com/Miserlou/Zappa/issues/836 # https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Summary_table if binary_support and (method in BINARY_METHODS): if event_info.get("isBase64Encoded", False): encoded_body = event_info["body"] body = base64.b64decode(encoded_body) else: body = event_info["body"] if isinstance(body, str): body = body.encode("utf-8") else: body = event_info["body"] if isinstance(body, str): body = body.encode("utf-8") # Make header names canonical, e.g. content-type => Content-Type # https://github.com/Miserlou/Zappa/issues/1188 headers = titlecase_keys(headers) path = unquote(event_info["path"]) if base_path: script_name = "/" + base_path if path.startswith(script_name): path = path[len(script_name) :] x_forwarded_for = headers.get("X-Forwarded-For", "") if "," in x_forwarded_for: # The last one is the cloudfront proxy ip. The second to last is the real client ip. # Everything else is user supplied and untrustworthy. addresses = [addr.strip() for addr in x_forwarded_for.split(",")] remote_addr = addresses[-2] else: remote_addr = x_forwarded_for or "127.0.0.1" environ = { "PATH_INFO": get_wsgi_string(path), "QUERY_STRING": get_wsgi_string(query_string), "REMOTE_ADDR": remote_addr, "REQUEST_METHOD": method, "SCRIPT_NAME": get_wsgi_string(str(script_name)) if script_name else "", "SERVER_NAME": str(server_name), "SERVER_PORT": headers.get("X-Forwarded-Port", "80"), "SERVER_PROTOCOL": str("HTTP/1.1"), "wsgi.version": (1, 0), "wsgi.url_scheme": headers.get("X-Forwarded-Proto", "http"), # This must be Bytes or None # - https://docs.djangoproject.com/en/4.2/releases/4.2/#miscellaneous # - https://wsgi.readthedocs.io/en/latest/definitions.html#envvar-wsgi.input # > Manually instantiated WSGIRequest objects must be provided # > a file-like object for wsgi.input. "wsgi.input": BytesIO(body), "wsgi.errors": sys.stderr, "wsgi.multiprocess": False, "wsgi.multithread": False, "wsgi.run_once": False, } # Systems calling the Lambda (other than API Gateway) may not provide the field requestContext # Extract remote_user, authorizer if Authorizer is enabled remote_user = None if "requestContext" in event_info: authorizer = event_info["requestContext"].get("authorizer", None) if authorizer: remote_user = authorizer.get("principalId") environ["API_GATEWAY_AUTHORIZER"] = authorizer elif event_info["requestContext"].get("identity"): remote_user = event_info["requestContext"]["identity"].get("userArn") # Input processing if method in ["POST", "PUT", "PATCH", "DELETE"]: if "Content-Type" in headers: environ["CONTENT_TYPE"] = headers["Content-Type"] if body: environ["CONTENT_LENGTH"] = str(len(body)) else: environ["CONTENT_LENGTH"] = "0" for header in headers: wsgi_name = "HTTP_" + header.upper().replace("-", "_") environ[wsgi_name] = str(headers[header]) if script_name: environ["SCRIPT_NAME"] = script_name path_info = environ["PATH_INFO"] if script_name in path_info: environ["PATH_INFO"].replace(script_name, "") if remote_user: environ["REMOTE_USER"] = remote_user return environ
Given some event_info via API Gateway, create and return a valid WSGI request environ.
154,557
import base64 import logging import sys from io import BytesIO from typing import Optional from urllib.parse import unquote, urlencode from .utilities import ApacheNCSAFormatter, merge_headers, titlecase_keys logger = logging.getLogger(__name__) def ApacheNCSAFormatter(with_response_time: bool = True) -> Callable: """A factory that returns the wanted formatter""" if with_response_time: return ApacheNCSAFormatters.format_log_with_response_time else: return ApacheNCSAFormatters.format_log The provided code snippet includes necessary dependencies for implementing the `common_log` function. Write a Python function `def common_log(environ, response, response_time: Optional[int] = None)` to solve the following problem: Given the WSGI environ and the response, log this event in Common Log Format. response_time: response time in micro-seconds Here is the function: def common_log(environ, response, response_time: Optional[int] = None): """ Given the WSGI environ and the response, log this event in Common Log Format. response_time: response time in micro-seconds """ logger = logging.getLogger(__name__) if response_time: formatter = ApacheNCSAFormatter(with_response_time=True) log_entry = formatter( response.status_code, environ, len(response.content), rt_us=response_time, ) else: formatter = ApacheNCSAFormatter(with_response_time=False) log_entry = formatter(response.status_code, environ, len(response.content)) logger.info(log_entry) return log_entry
Given the WSGI environ and the response, log this event in Common Log Format. response_time: response time in micro-seconds
154,558
import importlib import inspect import json import os import time import uuid from functools import update_wrapper, wraps import boto3 import botocore from .utilities import get_topic_name, validate_json_serializable def run_message(message): """ Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py """ if message.get("capture_response", False): DYNAMODB_CLIENT.put_item( TableName=ASYNC_RESPONSE_TABLE, Item={ "id": {"S": str(message["response_id"])}, "ttl": {"N": str(int(time.time() + 600))}, "async_status": {"S": "in progress"}, "async_response": {"S": str(json.dumps("N/A"))}, }, ) func = import_and_get_task(message["task_path"]) if hasattr(func, "sync"): response = func.sync(*message["args"], **message["kwargs"]) else: response = func(*message["args"], **message["kwargs"]) if message.get("capture_response", False): DYNAMODB_CLIENT.update_item( TableName=ASYNC_RESPONSE_TABLE, Key={"id": {"S": str(message["response_id"])}}, UpdateExpression="SET async_response = :r, async_status = :s", ExpressionAttributeValues={ ":r": {"S": str(json.dumps(response))}, ":s": {"S": "complete"}, }, ) return response The provided code snippet includes necessary dependencies for implementing the `route_lambda_task` function. Write a Python function `def route_lambda_task(event, context)` to solve the following problem: Deserialises the message from event passed to zappa.handler.run_function imports the function, calls the function with args Here is the function: def route_lambda_task(event, context): """ Deserialises the message from event passed to zappa.handler.run_function imports the function, calls the function with args """ message = event return run_message(message)
Deserialises the message from event passed to zappa.handler.run_function imports the function, calls the function with args
154,559
import importlib import inspect import json import os import time import uuid from functools import update_wrapper, wraps import boto3 import botocore from .utilities import get_topic_name, validate_json_serializable def run_message(message): """ Runs a function defined by a message object with keys: 'task_path', 'args', and 'kwargs' used by lambda routing and a 'command' in handler.py """ if message.get("capture_response", False): DYNAMODB_CLIENT.put_item( TableName=ASYNC_RESPONSE_TABLE, Item={ "id": {"S": str(message["response_id"])}, "ttl": {"N": str(int(time.time() + 600))}, "async_status": {"S": "in progress"}, "async_response": {"S": str(json.dumps("N/A"))}, }, ) func = import_and_get_task(message["task_path"]) if hasattr(func, "sync"): response = func.sync(*message["args"], **message["kwargs"]) else: response = func(*message["args"], **message["kwargs"]) if message.get("capture_response", False): DYNAMODB_CLIENT.update_item( TableName=ASYNC_RESPONSE_TABLE, Key={"id": {"S": str(message["response_id"])}}, UpdateExpression="SET async_response = :r, async_status = :s", ExpressionAttributeValues={ ":r": {"S": str(json.dumps(response))}, ":s": {"S": "complete"}, }, ) return response The provided code snippet includes necessary dependencies for implementing the `route_sns_task` function. Write a Python function `def route_sns_task(event, context)` to solve the following problem: Gets SNS Message, deserialises the message, imports the function, calls the function with args Here is the function: def route_sns_task(event, context): """ Gets SNS Message, deserialises the message, imports the function, calls the function with args """ record = event["Records"][0] message = json.loads(record["Sns"]["Message"]) return run_message(message)
Gets SNS Message, deserialises the message, imports the function, calls the function with args
154,560
import importlib import inspect import json import os import time import uuid from functools import update_wrapper, wraps import boto3 import botocore from .utilities import get_topic_name, validate_json_serializable ASYNC_CLASSES = { "lambda": LambdaAsyncResponse, "sns": SnsAsyncResponse, } def get_func_task_path(func): """ Format the modular task path for a function via inspection. """ module_path = inspect.getmodule(func).__name__ task_path = "{module_path}.{func_name}".format(module_path=module_path, func_name=func.__name__) return task_path The provided code snippet includes necessary dependencies for implementing the `run` function. Write a Python function `def run( func, args=[], kwargs={}, service="lambda", capture_response=False, remote_aws_lambda_function_name=None, remote_aws_region=None, **task_kwargs )` to solve the following problem: Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call this: import zappa.asynchronous.run zappa.asynchronous.run(func, args, kwargs) If you want to use SNS, then do: zappa.asynchronous.run(func, args, kwargs, service='sns') and other arguments are similar to @task Here is the function: def run( func, args=[], kwargs={}, service="lambda", capture_response=False, remote_aws_lambda_function_name=None, remote_aws_region=None, **task_kwargs ): """ Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call this: import zappa.asynchronous.run zappa.asynchronous.run(func, args, kwargs) If you want to use SNS, then do: zappa.asynchronous.run(func, args, kwargs, service='sns') and other arguments are similar to @task """ lambda_function_name = remote_aws_lambda_function_name or os.environ.get("AWS_LAMBDA_FUNCTION_NAME") aws_region = remote_aws_region or os.environ.get("AWS_REGION") task_path = get_func_task_path(func) return ASYNC_CLASSES[service]( lambda_function_name=lambda_function_name, aws_region=aws_region, capture_response=capture_response, **task_kwargs ).send(task_path, args, kwargs)
Instead of decorating a function with @task, you can just run it directly. If you were going to do func(*args, **kwargs), then you will call this: import zappa.asynchronous.run zappa.asynchronous.run(func, args, kwargs) If you want to use SNS, then do: zappa.asynchronous.run(func, args, kwargs, service='sns') and other arguments are similar to @task
154,561
import importlib import inspect import json import os import time import uuid from functools import update_wrapper, wraps import boto3 import botocore from .utilities import get_topic_name, validate_json_serializable def task(*args, **kwargs): """Async task decorator so that running Args: func (function): the function to be wrapped Further requirements: func must be an independent top-level function. i.e. not a class method or an anonymous function service (str): either 'lambda' or 'sns' remote_aws_lambda_function_name (str): the name of a remote lambda function to call with this task remote_aws_region (str): the name of a remote region to make lambda/sns calls against Returns: A replacement function that dispatches func() to run asynchronously through the service in question """ func = None if len(args) == 1 and callable(args[0]): func = args[0] if not kwargs: # Default Values service = "lambda" lambda_function_name_arg = None aws_region_arg = None else: # Arguments were passed service = kwargs.get("service", "lambda") lambda_function_name_arg = kwargs.get("remote_aws_lambda_function_name") aws_region_arg = kwargs.get("remote_aws_region") capture_response = kwargs.get("capture_response", False) def func_wrapper(func): task_path = get_func_task_path(func) def _run_async(*args, **kwargs): """ This is the wrapping async function that replaces the function that is decorated with @task. Args: These are just passed through to @task's func Assuming a valid service is passed to task() and it is run inside a Lambda process (i.e. AWS_LAMBDA_FUNCTION_NAME exists), it dispatches the function to be run through the service variable. Otherwise, it runs the task synchronously. Returns: In async mode, the object returned includes state of the dispatch. For instance When outside of Lambda, the func passed to @task is run and we return the actual value. """ lambda_function_name = lambda_function_name_arg or os.environ.get("AWS_LAMBDA_FUNCTION_NAME") aws_region = aws_region_arg or os.environ.get("AWS_REGION") if (service in ASYNC_CLASSES) and (lambda_function_name): send_result = ASYNC_CLASSES[service]( lambda_function_name=lambda_function_name, aws_region=aws_region, capture_response=capture_response, ).send(task_path, args, kwargs) return send_result else: validate_json_serializable(*args, **kwargs) return func(*args, **kwargs) update_wrapper(_run_async, func) _run_async.service = service _run_async.sync = func return _run_async return func_wrapper(func) if func else func_wrapper The provided code snippet includes necessary dependencies for implementing the `task_sns` function. Write a Python function `def task_sns(func)` to solve the following problem: SNS-based task dispatcher. Functions the same way as task() Here is the function: def task_sns(func): """ SNS-based task dispatcher. Functions the same way as task() """ return task(func, service="sns")
SNS-based task dispatcher. Functions the same way as task()
154,562
import importlib import inspect import json import os import time import uuid from functools import update_wrapper, wraps import boto3 import botocore from .utilities import get_topic_name, validate_json_serializable The provided code snippet includes necessary dependencies for implementing the `get_async_response` function. Write a Python function `def get_async_response(response_id)` to solve the following problem: Get the response from the async table Here is the function: def get_async_response(response_id): """ Get the response from the async table """ response = DYNAMODB_CLIENT.get_item(TableName=ASYNC_RESPONSE_TABLE, Key={"id": {"S": str(response_id)}}) if "Item" not in response: return None return { "status": response["Item"]["async_status"]["S"], "response": json.loads(response["Item"]["async_response"]["S"]), }
Get the response from the async table
154,563
import argparse import logging import random import uuid import numpy as np from transformers import pipeline from diffusers import DiffusionPipeline, StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler from diffusers.utils import load_image from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler from diffusers.utils import export_to_video from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, SpeechT5ForSpeechToSpeech from transformers import BlipProcessor, BlipForConditionalGeneration from transformers import TrOCRProcessor, VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer from datasets import load_dataset from PIL import Image import flask from flask import request, jsonify import waitress from flask_cors import CORS import io from torchvision import transforms import torch import torchaudio from speechbrain.pretrained import WaveformEnhancement import joblib from huggingface_hub import hf_hub_url, cached_download from transformers import AutoImageProcessor, TimesformerForVideoClassification from transformers import MaskFormerFeatureExtractor, MaskFormerForInstanceSegmentation, AutoFeatureExtractor from controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector, CannyDetector, MidasDetector from controlnet_aux.open_pose.body import Body from controlnet_aux.mlsd.models.mbv2_mlsd_large import MobileV2_MLSD_Large from controlnet_aux.hed import Network from transformers import DPTForDepthEstimation, DPTFeatureExtractor import warnings import time from espnet2.bin.tts_inference import Text2Speech import soundfile as sf from asteroid.models import BaseModel import traceback import os import yaml device = config.get("device", "cuda:0") local_fold = "models" pipes = load_pipes(local_deployment) def load_pipes(local_deployment): other_pipes = {} standard_pipes = {} controlnet_sd_pipes = {} if local_deployment in ["full"]: other_pipes = { "nlpconnect/vit-gpt2-image-captioning":{ "model": VisionEncoderDecoderModel.from_pretrained(f"{local_fold}/nlpconnect/vit-gpt2-image-captioning"), "feature_extractor": ViTImageProcessor.from_pretrained(f"{local_fold}/nlpconnect/vit-gpt2-image-captioning"), "tokenizer": AutoTokenizer.from_pretrained(f"{local_fold}/nlpconnect/vit-gpt2-image-captioning"), "device": device }, # "Salesforce/blip-image-captioning-large": { # "model": BlipForConditionalGeneration.from_pretrained(f"{local_fold}/Salesforce/blip-image-captioning-large"), # "processor": BlipProcessor.from_pretrained(f"{local_fold}/Salesforce/blip-image-captioning-large"), # "device": device # }, "damo-vilab/text-to-video-ms-1.7b": { "model": DiffusionPipeline.from_pretrained(f"{local_fold}/damo-vilab/text-to-video-ms-1.7b", torch_dtype=torch.float16, variant="fp16"), "device": device }, # "facebook/maskformer-swin-large-ade": { # "model": MaskFormerForInstanceSegmentation.from_pretrained(f"{local_fold}/facebook/maskformer-swin-large-ade"), # "feature_extractor" : AutoFeatureExtractor.from_pretrained("facebook/maskformer-swin-large-ade"), # "device": device # }, # "microsoft/trocr-base-printed": { # "processor": TrOCRProcessor.from_pretrained(f"{local_fold}/microsoft/trocr-base-printed"), # "model": VisionEncoderDecoderModel.from_pretrained(f"{local_fold}/microsoft/trocr-base-printed"), # "device": device # }, # "microsoft/trocr-base-handwritten": { # "processor": TrOCRProcessor.from_pretrained(f"{local_fold}/microsoft/trocr-base-handwritten"), # "model": VisionEncoderDecoderModel.from_pretrained(f"{local_fold}/microsoft/trocr-base-handwritten"), # "device": device # }, "JorisCos/DCCRNet_Libri1Mix_enhsingle_16k": { "model": BaseModel.from_pretrained("JorisCos/DCCRNet_Libri1Mix_enhsingle_16k"), "device": device }, "espnet/kan-bayashi_ljspeech_vits": { "model": Text2Speech.from_pretrained(f"espnet/kan-bayashi_ljspeech_vits"), "device": device }, "lambdalabs/sd-image-variations-diffusers": { "model": DiffusionPipeline.from_pretrained(f"{local_fold}/lambdalabs/sd-image-variations-diffusers"), #torch_dtype=torch.float16 "device": device }, # "CompVis/stable-diffusion-v1-4": { # "model": DiffusionPipeline.from_pretrained(f"{local_fold}/CompVis/stable-diffusion-v1-4"), # "device": device # }, # "stabilityai/stable-diffusion-2-1": { # "model": DiffusionPipeline.from_pretrained(f"{local_fold}/stabilityai/stable-diffusion-2-1"), # "device": device # }, "runwayml/stable-diffusion-v1-5": { "model": DiffusionPipeline.from_pretrained(f"{local_fold}/runwayml/stable-diffusion-v1-5"), "device": device }, # "microsoft/speecht5_tts":{ # "processor": SpeechT5Processor.from_pretrained(f"{local_fold}/microsoft/speecht5_tts"), # "model": SpeechT5ForTextToSpeech.from_pretrained(f"{local_fold}/microsoft/speecht5_tts"), # "vocoder": SpeechT5HifiGan.from_pretrained(f"{local_fold}/microsoft/speecht5_hifigan"), # "embeddings_dataset": load_dataset(f"{local_fold}/Matthijs/cmu-arctic-xvectors", split="validation"), # "device": device # }, # "speechbrain/mtl-mimic-voicebank": { # "model": WaveformEnhancement.from_hparams(source="speechbrain/mtl-mimic-voicebank", savedir="models/mtl-mimic-voicebank"), # "device": device # }, "microsoft/speecht5_vc":{ "processor": SpeechT5Processor.from_pretrained(f"{local_fold}/microsoft/speecht5_vc"), "model": SpeechT5ForSpeechToSpeech.from_pretrained(f"{local_fold}/microsoft/speecht5_vc"), "vocoder": SpeechT5HifiGan.from_pretrained(f"{local_fold}/microsoft/speecht5_hifigan"), "embeddings_dataset": load_dataset(f"{local_fold}/Matthijs/cmu-arctic-xvectors", split="validation"), "device": device }, # "julien-c/wine-quality": { # "model": joblib.load(cached_download(hf_hub_url("julien-c/wine-quality", "sklearn_model.joblib"))) # }, # "facebook/timesformer-base-finetuned-k400": { # "processor": AutoImageProcessor.from_pretrained(f"{local_fold}/facebook/timesformer-base-finetuned-k400"), # "model": TimesformerForVideoClassification.from_pretrained(f"{local_fold}/facebook/timesformer-base-finetuned-k400"), # "device": device # }, "facebook/maskformer-swin-base-coco": { "feature_extractor": MaskFormerFeatureExtractor.from_pretrained(f"{local_fold}/facebook/maskformer-swin-base-coco"), "model": MaskFormerForInstanceSegmentation.from_pretrained(f"{local_fold}/facebook/maskformer-swin-base-coco"), "device": device }, "Intel/dpt-hybrid-midas": { "model": DPTForDepthEstimation.from_pretrained(f"{local_fold}/Intel/dpt-hybrid-midas", low_cpu_mem_usage=True), "feature_extractor": DPTFeatureExtractor.from_pretrained(f"{local_fold}/Intel/dpt-hybrid-midas"), "device": device } } if local_deployment in ["full", "standard"]: standard_pipes = { # "superb/wav2vec2-base-superb-ks": { # "model": pipeline(task="audio-classification", model=f"{local_fold}/superb/wav2vec2-base-superb-ks"), # "device": device # }, "openai/whisper-base": { "model": pipeline(task="automatic-speech-recognition", model=f"{local_fold}/openai/whisper-base"), "device": device }, "microsoft/speecht5_asr": { "model": pipeline(task="automatic-speech-recognition", model=f"{local_fold}/microsoft/speecht5_asr"), "device": device }, "Intel/dpt-large": { "model": pipeline(task="depth-estimation", model=f"{local_fold}/Intel/dpt-large"), "device": device }, # "microsoft/beit-base-patch16-224-pt22k-ft22k": { # "model": pipeline(task="image-classification", model=f"{local_fold}/microsoft/beit-base-patch16-224-pt22k-ft22k"), # "device": device # }, "facebook/detr-resnet-50-panoptic": { "model": pipeline(task="image-segmentation", model=f"{local_fold}/facebook/detr-resnet-50-panoptic"), "device": device }, "facebook/detr-resnet-101": { "model": pipeline(task="object-detection", model=f"{local_fold}/facebook/detr-resnet-101"), "device": device }, # "openai/clip-vit-large-patch14": { # "model": pipeline(task="zero-shot-image-classification", model=f"{local_fold}/openai/clip-vit-large-patch14"), # "device": device # }, "google/owlvit-base-patch32": { "model": pipeline(task="zero-shot-object-detection", model=f"{local_fold}/google/owlvit-base-patch32"), "device": device }, # "microsoft/DialoGPT-medium": { # "model": pipeline(task="conversational", model=f"{local_fold}/microsoft/DialoGPT-medium"), # "device": device # }, # "bert-base-uncased": { # "model": pipeline(task="fill-mask", model=f"{local_fold}/bert-base-uncased"), # "device": device # }, # "deepset/roberta-base-squad2": { # "model": pipeline(task = "question-answering", model=f"{local_fold}/deepset/roberta-base-squad2"), # "device": device # }, # "facebook/bart-large-cnn": { # "model": pipeline(task="summarization", model=f"{local_fold}/facebook/bart-large-cnn"), # "device": device # }, # "google/tapas-base-finetuned-wtq": { # "model": pipeline(task="table-question-answering", model=f"{local_fold}/google/tapas-base-finetuned-wtq"), # "device": device # }, # "distilbert-base-uncased-finetuned-sst-2-english": { # "model": pipeline(task="text-classification", model=f"{local_fold}/distilbert-base-uncased-finetuned-sst-2-english"), # "device": device # }, # "gpt2": { # "model": pipeline(task="text-generation", model="gpt2"), # "device": device # }, # "mrm8488/t5-base-finetuned-question-generation-ap": { # "model": pipeline(task="text2text-generation", model=f"{local_fold}/mrm8488/t5-base-finetuned-question-generation-ap"), # "device": device # }, # "Jean-Baptiste/camembert-ner": { # "model": pipeline(task="token-classification", model=f"{local_fold}/Jean-Baptiste/camembert-ner", aggregation_strategy="simple"), # "device": device # }, # "t5-base": { # "model": pipeline(task="translation", model=f"{local_fold}/t5-base"), # "device": device # }, "impira/layoutlm-document-qa": { "model": pipeline(task="document-question-answering", model=f"{local_fold}/impira/layoutlm-document-qa"), "device": device }, "ydshieh/vit-gpt2-coco-en": { "model": pipeline(task="image-to-text", model=f"{local_fold}/ydshieh/vit-gpt2-coco-en"), "device": device }, "dandelin/vilt-b32-finetuned-vqa": { "model": pipeline(task="visual-question-answering", model=f"{local_fold}/dandelin/vilt-b32-finetuned-vqa"), "device": device } } if local_deployment in ["full", "standard", "minimal"]: controlnet = ControlNetModel.from_pretrained(f"{local_fold}/lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16) controlnetpipe = StableDiffusionControlNetPipeline.from_pretrained( f"{local_fold}/runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16 ) def mlsd_control_network(): model = MobileV2_MLSD_Large() model.load_state_dict(torch.load(f"{local_fold}/lllyasviel/ControlNet/annotator/ckpts/mlsd_large_512_fp32.pth"), strict=True) return MLSDdetector(model) hed_network = Network(f"{local_fold}/lllyasviel/ControlNet/annotator/ckpts/network-bsds500.pth") controlnet_sd_pipes = { "openpose-control": { "model": OpenposeDetector(Body(f"{local_fold}/lllyasviel/ControlNet/annotator/ckpts/body_pose_model.pth")) }, "mlsd-control": { "model": mlsd_control_network() }, "hed-control": { "model": HEDdetector(hed_network) }, "scribble-control": { "model": HEDdetector(hed_network) }, "midas-control": { "model": MidasDetector(model_path=f"{local_fold}/lllyasviel/ControlNet/annotator/ckpts/dpt_hybrid-midas-501f0c75.pt") }, "canny-control": { "model": CannyDetector() }, "lllyasviel/sd-controlnet-canny":{ "control": controlnet, "model": controlnetpipe, "device": device }, "lllyasviel/sd-controlnet-depth":{ "control": ControlNetModel.from_pretrained(f"{local_fold}/lllyasviel/sd-controlnet-depth", torch_dtype=torch.float16), "model": controlnetpipe, "device": device }, "lllyasviel/sd-controlnet-hed":{ "control": ControlNetModel.from_pretrained(f"{local_fold}/lllyasviel/sd-controlnet-hed", torch_dtype=torch.float16), "model": controlnetpipe, "device": device }, "lllyasviel/sd-controlnet-mlsd":{ "control": ControlNetModel.from_pretrained(f"{local_fold}/lllyasviel/sd-controlnet-mlsd", torch_dtype=torch.float16), "model": controlnetpipe, "device": device }, "lllyasviel/sd-controlnet-openpose":{ "control": ControlNetModel.from_pretrained(f"{local_fold}/lllyasviel/sd-controlnet-openpose", torch_dtype=torch.float16), "model": controlnetpipe, "device": device }, "lllyasviel/sd-controlnet-scribble":{ "control": ControlNetModel.from_pretrained(f"{local_fold}/lllyasviel/sd-controlnet-scribble", torch_dtype=torch.float16), "model": controlnetpipe, "device": device }, "lllyasviel/sd-controlnet-seg":{ "control": ControlNetModel.from_pretrained(f"{local_fold}/lllyasviel/sd-controlnet-seg", torch_dtype=torch.float16), "model": controlnetpipe, "device": device } } pipes = {**standard_pipes, **other_pipes, **controlnet_sd_pipes} return pipes
null
154,564
import argparse import logging import random import uuid import numpy as np from transformers import pipeline from diffusers import DiffusionPipeline, StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler from diffusers.utils import load_image from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler from diffusers.utils import export_to_video from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, SpeechT5ForSpeechToSpeech from transformers import BlipProcessor, BlipForConditionalGeneration from transformers import TrOCRProcessor, VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer from datasets import load_dataset from PIL import Image import flask from flask import request, jsonify import waitress from flask_cors import CORS import io from torchvision import transforms import torch import torchaudio from speechbrain.pretrained import WaveformEnhancement import joblib from huggingface_hub import hf_hub_url, cached_download from transformers import AutoImageProcessor, TimesformerForVideoClassification from transformers import MaskFormerFeatureExtractor, MaskFormerForInstanceSegmentation, AutoFeatureExtractor from controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector, CannyDetector, MidasDetector from controlnet_aux.open_pose.body import Body from controlnet_aux.mlsd.models.mbv2_mlsd_large import MobileV2_MLSD_Large from controlnet_aux.hed import Network from transformers import DPTForDepthEstimation, DPTFeatureExtractor import warnings import time from espnet2.bin.tts_inference import Text2Speech import soundfile as sf from asteroid.models import BaseModel import traceback import os import yaml def running(): return jsonify({"running": True})
null
154,565
import argparse import logging import random import uuid import numpy as np from transformers import pipeline from diffusers import DiffusionPipeline, StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler from diffusers.utils import load_image from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler from diffusers.utils import export_to_video from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, SpeechT5ForSpeechToSpeech from transformers import BlipProcessor, BlipForConditionalGeneration from transformers import TrOCRProcessor, VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer from datasets import load_dataset from PIL import Image import flask from flask import request, jsonify import waitress from flask_cors import CORS import io from torchvision import transforms import torch import torchaudio from speechbrain.pretrained import WaveformEnhancement import joblib from huggingface_hub import hf_hub_url, cached_download from transformers import AutoImageProcessor, TimesformerForVideoClassification from transformers import MaskFormerFeatureExtractor, MaskFormerForInstanceSegmentation, AutoFeatureExtractor from controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector, CannyDetector, MidasDetector from controlnet_aux.open_pose.body import Body from controlnet_aux.mlsd.models.mbv2_mlsd_large import MobileV2_MLSD_Large from controlnet_aux.hed import Network from transformers import DPTForDepthEstimation, DPTFeatureExtractor import warnings import time from espnet2.bin.tts_inference import Text2Speech import soundfile as sf from asteroid.models import BaseModel import traceback import os import yaml pipes = load_pipes(local_deployment) print(f"[ ready ] {during}s") def status(model_id): disabled_models = ["microsoft/trocr-base-printed", "microsoft/trocr-base-handwritten"] if model_id in pipes.keys() and model_id not in disabled_models: print(f"[ check {model_id} ] success") return jsonify({"loaded": True}) else: print(f"[ check {model_id} ] failed") return jsonify({"loaded": False})
null
154,566
import argparse import logging import random import uuid import numpy as np from transformers import pipeline from diffusers import DiffusionPipeline, StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler from diffusers.utils import load_image from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler from diffusers.utils import export_to_video from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan, SpeechT5ForSpeechToSpeech from transformers import BlipProcessor, BlipForConditionalGeneration from transformers import TrOCRProcessor, VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer from datasets import load_dataset from PIL import Image import flask from flask import request, jsonify import waitress from flask_cors import CORS import io from torchvision import transforms import torch import torchaudio from speechbrain.pretrained import WaveformEnhancement import joblib from huggingface_hub import hf_hub_url, cached_download from transformers import AutoImageProcessor, TimesformerForVideoClassification from transformers import MaskFormerFeatureExtractor, MaskFormerForInstanceSegmentation, AutoFeatureExtractor from controlnet_aux import OpenposeDetector, MLSDdetector, HEDdetector, CannyDetector, MidasDetector from controlnet_aux.open_pose.body import Body from controlnet_aux.mlsd.models.mbv2_mlsd_large import MobileV2_MLSD_Large from controlnet_aux.hed import Network from transformers import DPTForDepthEstimation, DPTFeatureExtractor import warnings import time from espnet2.bin.tts_inference import Text2Speech import soundfile as sf from asteroid.models import BaseModel import traceback import os import yaml config = yaml.load(open(args.config, "r"), Loader=yaml.FullLoader) device = config.get("device", "cuda:0") if config["proxy"]: PROXY = { "https": config["proxy"], } start = time.time() pipes = load_pipes(local_deployment) end = time.time() during = end - start print(f"[ ready ] {during}s") def models(model_id): while "using" in pipes[model_id] and pipes[model_id]["using"]: print(f"[ inference {model_id} ] waiting") time.sleep(0.1) pipes[model_id]["using"] = True print(f"[ inference {model_id} ] start") start = time.time() pipe = pipes[model_id]["model"] if "device" in pipes[model_id]: try: pipe.to(pipes[model_id]["device"]) except: pipe.device = torch.device(pipes[model_id]["device"]) pipe.model.to(pipes[model_id]["device"]) result = None try: # text to video if model_id == "damo-vilab/text-to-video-ms-1.7b": pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) # pipe.enable_model_cpu_offload() prompt = request.get_json()["text"] video_frames = pipe(prompt, num_inference_steps=50, num_frames=40).frames video_path = export_to_video(video_frames) file_name = str(uuid.uuid4())[:4] os.system(f"LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/ffmpeg -i {video_path} -vcodec libx264 public/videos/{file_name}.mp4") result = {"path": f"/videos/{file_name}.mp4"} # controlnet if model_id.startswith("lllyasviel/sd-controlnet-"): pipe.controlnet.to('cpu') pipe.controlnet = pipes[model_id]["control"].to(pipes[model_id]["device"]) pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config) control_image = load_image(request.get_json()["img_url"]) # generator = torch.manual_seed(66) out_image: Image = pipe(request.get_json()["text"], num_inference_steps=20, image=control_image).images[0] file_name = str(uuid.uuid4())[:4] out_image.save(f"public/images/{file_name}.png") result = {"path": f"/images/{file_name}.png"} if model_id.endswith("-control"): image = load_image(request.get_json()["img_url"]) if "scribble" in model_id: control = pipe(image, scribble = True) elif "canny" in model_id: control = pipe(image, low_threshold=100, high_threshold=200) else: control = pipe(image) file_name = str(uuid.uuid4())[:4] control.save(f"public/images/{file_name}.png") result = {"path": f"/images/{file_name}.png"} # image to image if model_id == "lambdalabs/sd-image-variations-diffusers": im = load_image(request.get_json()["img_url"]) file_name = str(uuid.uuid4())[:4] with open(f"public/images/{file_name}.png", "wb") as f: f.write(request.data) tform = transforms.Compose([ transforms.ToTensor(), transforms.Resize( (224, 224), interpolation=transforms.InterpolationMode.BICUBIC, antialias=False, ), transforms.Normalize( [0.48145466, 0.4578275, 0.40821073], [0.26862954, 0.26130258, 0.27577711]), ]) inp = tform(im).to(pipes[model_id]["device"]).unsqueeze(0) out = pipe(inp, guidance_scale=3) out["images"][0].save(f"public/images/{file_name}.jpg") result = {"path": f"/images/{file_name}.jpg"} # image to text if model_id == "Salesforce/blip-image-captioning-large": raw_image = load_image(request.get_json()["img_url"]).convert('RGB') text = request.get_json()["text"] inputs = pipes[model_id]["processor"](raw_image, return_tensors="pt").to(pipes[model_id]["device"]) out = pipe.generate(**inputs) caption = pipes[model_id]["processor"].decode(out[0], skip_special_tokens=True) result = {"generated text": caption} if model_id == "ydshieh/vit-gpt2-coco-en": img_url = request.get_json()["img_url"] generated_text = pipe(img_url)[0]['generated_text'] result = {"generated text": generated_text} if model_id == "nlpconnect/vit-gpt2-image-captioning": image = load_image(request.get_json()["img_url"]).convert("RGB") pixel_values = pipes[model_id]["feature_extractor"](images=image, return_tensors="pt").pixel_values pixel_values = pixel_values.to(pipes[model_id]["device"]) generated_ids = pipe.generate(pixel_values, **{"max_length": 200, "num_beams": 1}) generated_text = pipes[model_id]["tokenizer"].batch_decode(generated_ids, skip_special_tokens=True)[0] result = {"generated text": generated_text} # image to text: OCR if model_id == "microsoft/trocr-base-printed" or model_id == "microsoft/trocr-base-handwritten": image = load_image(request.get_json()["img_url"]).convert("RGB") pixel_values = pipes[model_id]["processor"](image, return_tensors="pt").pixel_values pixel_values = pixel_values.to(pipes[model_id]["device"]) generated_ids = pipe.generate(pixel_values) generated_text = pipes[model_id]["processor"].batch_decode(generated_ids, skip_special_tokens=True)[0] result = {"generated text": generated_text} # text to image if model_id == "runwayml/stable-diffusion-v1-5": file_name = str(uuid.uuid4())[:4] text = request.get_json()["text"] out = pipe(prompt=text) out["images"][0].save(f"public/images/{file_name}.jpg") result = {"path": f"/images/{file_name}.jpg"} # object detection if model_id == "google/owlvit-base-patch32" or model_id == "facebook/detr-resnet-101": img_url = request.get_json()["img_url"] open_types = ["cat", "couch", "person", "car", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird"] result = pipe(img_url, candidate_labels=open_types) # VQA if model_id == "dandelin/vilt-b32-finetuned-vqa": question = request.get_json()["text"] img_url = request.get_json()["img_url"] result = pipe(question=question, image=img_url) #DQA if model_id == "impira/layoutlm-document-qa": question = request.get_json()["text"] img_url = request.get_json()["img_url"] result = pipe(img_url, question) # depth-estimation if model_id == "Intel/dpt-large": output = pipe(request.get_json()["img_url"]) image = output['depth'] name = str(uuid.uuid4())[:4] image.save(f"public/images/{name}.jpg") result = {"path": f"/images/{name}.jpg"} if model_id == "Intel/dpt-hybrid-midas" and model_id == "Intel/dpt-large": image = load_image(request.get_json()["img_url"]) inputs = pipes[model_id]["feature_extractor"](images=image, return_tensors="pt") with torch.no_grad(): outputs = pipe(**inputs) predicted_depth = outputs.predicted_depth prediction = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1), size=image.size[::-1], mode="bicubic", align_corners=False, ) output = prediction.squeeze().cpu().numpy() formatted = (output * 255 / np.max(output)).astype("uint8") image = Image.fromarray(formatted) name = str(uuid.uuid4())[:4] image.save(f"public/images/{name}.jpg") result = {"path": f"/images/{name}.jpg"} # TTS if model_id == "espnet/kan-bayashi_ljspeech_vits": text = request.get_json()["text"] wav = pipe(text)["wav"] name = str(uuid.uuid4())[:4] sf.write(f"public/audios/{name}.wav", wav.cpu().numpy(), pipe.fs, "PCM_16") result = {"path": f"/audios/{name}.wav"} if model_id == "microsoft/speecht5_tts": text = request.get_json()["text"] inputs = pipes[model_id]["processor"](text=text, return_tensors="pt") embeddings_dataset = pipes[model_id]["embeddings_dataset"] speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0).to(pipes[model_id]["device"]) pipes[model_id]["vocoder"].to(pipes[model_id]["device"]) speech = pipe.generate_speech(inputs["input_ids"].to(pipes[model_id]["device"]), speaker_embeddings, vocoder=pipes[model_id]["vocoder"]) name = str(uuid.uuid4())[:4] sf.write(f"public/audios/{name}.wav", speech.cpu().numpy(), samplerate=16000) result = {"path": f"/audios/{name}.wav"} # ASR if model_id == "openai/whisper-base" or model_id == "microsoft/speecht5_asr": audio_url = request.get_json()["audio_url"] result = { "text": pipe(audio_url)["text"]} # audio to audio if model_id == "JorisCos/DCCRNet_Libri1Mix_enhsingle_16k": audio_url = request.get_json()["audio_url"] wav, sr = torchaudio.load(audio_url) with torch.no_grad(): result_wav = pipe(wav.to(pipes[model_id]["device"])) name = str(uuid.uuid4())[:4] sf.write(f"public/audios/{name}.wav", result_wav.cpu().squeeze().numpy(), sr) result = {"path": f"/audios/{name}.wav"} if model_id == "microsoft/speecht5_vc": audio_url = request.get_json()["audio_url"] wav, sr = torchaudio.load(audio_url) inputs = pipes[model_id]["processor"](audio=wav, sampling_rate=sr, return_tensors="pt") embeddings_dataset = pipes[model_id]["embeddings_dataset"] speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0) pipes[model_id]["vocoder"].to(pipes[model_id]["device"]) speech = pipe.generate_speech(inputs["input_ids"].to(pipes[model_id]["device"]), speaker_embeddings, vocoder=pipes[model_id]["vocoder"]) name = str(uuid.uuid4())[:4] sf.write(f"public/audios/{name}.wav", speech.cpu().numpy(), samplerate=16000) result = {"path": f"/audios/{name}.wav"} # segmentation if model_id == "facebook/detr-resnet-50-panoptic": result = [] segments = pipe(request.get_json()["img_url"]) image = load_image(request.get_json()["img_url"]) colors = [] for i in range(len(segments)): colors.append((random.randint(100, 255), random.randint(100, 255), random.randint(100, 255), 50)) for segment in segments: mask = segment["mask"] mask = mask.convert('L') layer = Image.new('RGBA', mask.size, colors[i]) image.paste(layer, (0, 0), mask) name = str(uuid.uuid4())[:4] image.save(f"public/images/{name}.jpg") result = {"path": f"/images/{name}.jpg"} if model_id == "facebook/maskformer-swin-base-coco" or model_id == "facebook/maskformer-swin-large-ade": image = load_image(request.get_json()["img_url"]) inputs = pipes[model_id]["feature_extractor"](images=image, return_tensors="pt").to(pipes[model_id]["device"]) outputs = pipe(**inputs) result = pipes[model_id]["feature_extractor"].post_process_panoptic_segmentation(outputs, target_sizes=[image.size[::-1]])[0] predicted_panoptic_map = result["segmentation"].cpu().numpy() predicted_panoptic_map = Image.fromarray(predicted_panoptic_map.astype(np.uint8)) name = str(uuid.uuid4())[:4] predicted_panoptic_map.save(f"public/images/{name}.jpg") result = {"path": f"/images/{name}.jpg"} except Exception as e: print(e) traceback.print_exc() result = {"error": {"message": "Error when running the model inference."}} if "device" in pipes[model_id]: try: pipe.to("cpu") torch.cuda.empty_cache() except: pipe.device = torch.device("cpu") pipe.model.to("cpu") torch.cuda.empty_cache() pipes[model_id]["using"] = False if result is None: result = {"error": {"message": "model not found"}} end = time.time() during = end - start print(f"[ complete {model_id} ] {during}s") print(f"[ result {model_id} ] {result}") return jsonify(result)
null
154,567
import base64 import copy from io import BytesIO import io import os import random import time import traceback import uuid import requests import re import json import logging import argparse import yaml from PIL import Image, ImageDraw from diffusers.utils import load_image from pydub import AudioSegment import threading from queue import Queue import flask from flask import request, jsonify import waitress from flask_cors import CORS, cross_origin from get_token_ids import get_token_ids_for_task_parsing, get_token_ids_for_choose_model, count_tokens, get_max_context_length from huggingface_hub.inference_api import InferenceApi from huggingface_hub.inference_api import ALL_TASKS args = parser.parse_args() if args.mode in ["test", "cli"]: assert API_TYPE, "Only server mode supports dynamic endpoint." def resource_has_dep(command): args = command["args"] for _, v in args.items(): if "<GENERATED>" in v: return True return False
null
154,568
import base64 import copy from io import BytesIO import io import os import random import time import traceback import uuid import requests import re import json import logging import argparse import yaml from PIL import Image, ImageDraw from diffusers.utils import load_image from pydub import AudioSegment import threading from queue import Queue import flask from flask import request, jsonify import waitress from flask_cors import CORS, cross_origin from get_token_ids import get_token_ids_for_task_parsing, get_token_ids_for_choose_model, count_tokens, get_max_context_length from huggingface_hub.inference_api import InferenceApi from huggingface_hub.inference_api import ALL_TASKS API_TYPE = None API_KEY = None API_ENDPOINT = None if API_TYPE == "local": API_ENDPOINT = f"{config['local']['endpoint']}/v1/{api_name}" elif API_TYPE == "azure": API_ENDPOINT = f"{config['azure']['base_url']}/openai/deployments/{config['azure']['deployment_name']}/{api_name}?api-version={config['azure']['api_version']}" API_KEY = config["azure"]["api_key"] elif API_TYPE == "openai": API_ENDPOINT = f"https://api.openai.com/v1/{api_name}" if config["openai"]["api_key"].startswith("sk-"): # Check for valid OpenAI key in config file API_KEY = config["openai"]["api_key"] elif "OPENAI_API_KEY" in os.environ and os.getenv("OPENAI_API_KEY").startswith("sk-"): # Check for environment variable OPENAI_API_KEY API_KEY = os.getenv("OPENAI_API_KEY") else: raise ValueError(f"Incorrect OpenAI key. Please check your {args.config} file.") def chat_huggingface(messages, api_key, api_type, api_endpoint, return_planning = False, return_results = False): start = time.time() context = messages[:-1] input = messages[-1]["content"] logger.info("*"*80) logger.info(f"input: {input}") task_str = parse_task(context, input, api_key, api_type, api_endpoint) if "error" in task_str: record_case(success=False, **{"input": input, "task": task_str, "reason": f"task parsing error: {task_str['error']['message']}", "op":"report message"}) return {"message": task_str["error"]["message"]} task_str = task_str.strip() logger.info(task_str) try: tasks = json.loads(task_str) except Exception as e: logger.debug(e) response = chitchat(messages, api_key, api_type, api_endpoint) record_case(success=False, **{"input": input, "task": task_str, "reason": "task parsing fail", "op":"chitchat"}) return {"message": response} if task_str == "[]": # using LLM response for empty task record_case(success=False, **{"input": input, "task": [], "reason": "task parsing fail: empty", "op": "chitchat"}) response = chitchat(messages, api_key, api_type, api_endpoint) return {"message": response} if len(tasks) == 1 and tasks[0]["task"] in ["summarization", "translation", "conversational", "text-generation", "text2text-generation"]: record_case(success=True, **{"input": input, "task": tasks, "reason": "chitchat tasks", "op": "chitchat"}) response = chitchat(messages, api_key, api_type, api_endpoint) return {"message": response} tasks = unfold(tasks) tasks = fix_dep(tasks) logger.debug(tasks) if return_planning: return tasks results = {} threads = [] tasks = tasks[:] d = dict() retry = 0 while True: num_thread = len(threads) for task in tasks: # logger.debug(f"d.keys(): {d.keys()}, dep: {dep}") for dep_id in task["dep"]: if dep_id >= task["id"]: task["dep"] = [-1] break dep = task["dep"] if dep[0] == -1 or len(list(set(dep).intersection(d.keys()))) == len(dep): tasks.remove(task) thread = threading.Thread(target=run_task, args=(input, task, d, api_key, api_type, api_endpoint)) thread.start() threads.append(thread) if num_thread == len(threads): time.sleep(0.5) retry += 1 if retry > 160: logger.debug("User has waited too long, Loop break.") break if len(tasks) == 0: break for thread in threads: thread.join() results = d.copy() logger.debug(results) if return_results: return results response = response_results(input, results, api_key, api_type, api_endpoint).strip() end = time.time() during = end - start answer = {"message": response} record_case(success=True, **{"input": input, "task": task_str, "results": results, "response": response, "during": during, "op":"response"}) logger.info(f"response: {response}") return answer def cli(): messages = [] print("Welcome to Jarvis! A collaborative system that consists of an LLM as the controller and numerous expert models as collaborative executors. Jarvis can plan tasks, schedule Hugging Face models, generate friendly responses based on your requests, and help you with many things. Please enter your request (`exit` to exit).") while True: message = input("[ User ]: ") if message == "exit": break messages.append({"role": "user", "content": message}) answer = chat_huggingface(messages, API_KEY, API_TYPE, API_ENDPOINT, return_planning=False, return_results=False) print("[ Jarvis ]: ", answer["message"]) messages.append({"role": "assistant", "content": answer["message"]})
null
154,569
import base64 import copy from io import BytesIO import io import os import random import time import traceback import uuid import requests import re import json import logging import argparse import yaml from PIL import Image, ImageDraw from diffusers.utils import load_image from pydub import AudioSegment import threading from queue import Queue import flask from flask import request, jsonify import waitress from flask_cors import CORS, cross_origin from get_token_ids import get_token_ids_for_task_parsing, get_token_ids_for_choose_model, count_tokens, get_max_context_length from huggingface_hub.inference_api import InferenceApi from huggingface_hub.inference_api import ALL_TASKS if __name__ != "__main__": args.config = "configs/config.gradio.yaml" args.mode = "gradio" config = yaml.load(open(args.config, "r"), Loader=yaml.FullLoader) if not config["debug"]: handler.setLevel(logging.CRITICAL) if config["dev"] and LLM == "gpt-3.5-turbo": LLM_encoding = "text-davinci-003" API_TYPE = None if "dev" in config and config["dev"]: API_TYPE = "local" elif "azure" in config: API_TYPE = "azure" elif "openai" in config: API_TYPE = "openai" else: logger.warning(f"No endpoint specified in {args.config}. The endpoint will be set dynamically according to the client.") API_KEY = None API_ENDPOINT = None if API_TYPE == "local": API_ENDPOINT = f"{config['local']['endpoint']}/v1/{api_name}" elif API_TYPE == "azure": API_ENDPOINT = f"{config['azure']['base_url']}/openai/deployments/{config['azure']['deployment_name']}/{api_name}?api-version={config['azure']['api_version']}" API_KEY = config["azure"]["api_key"] elif API_TYPE == "openai": API_ENDPOINT = f"https://api.openai.com/v1/{api_name}" if config["openai"]["api_key"].startswith("sk-"): # Check for valid OpenAI key in config file API_KEY = config["openai"]["api_key"] elif "OPENAI_API_KEY" in os.environ and os.getenv("OPENAI_API_KEY").startswith("sk-"): # Check for environment variable OPENAI_API_KEY API_KEY = os.getenv("OPENAI_API_KEY") else: raise ValueError(f"Incorrect OpenAI key. Please check your {args.config} file.") if config["proxy"]: PROXY = { "https": config["proxy"], } if config["huggingface"]["token"] and config["huggingface"]["token"].startswith("hf_"): # Check for valid huggingface token in config file HUGGINGFACE_HEADERS = { "Authorization": f"Bearer {config['huggingface']['token']}", } elif "HUGGINGFACE_ACCESS_TOKEN" in os.environ and os.getenv("HUGGINGFACE_ACCESS_TOKEN").startswith("hf_"): # Check for environment variable HUGGINGFACE_ACCESS_TOKEN HUGGINGFACE_HEADERS = { "Authorization": f"Bearer {os.getenv('HUGGINGFACE_ACCESS_TOKEN')}", } else: raise ValueError(f"Incorrect HuggingFace token. Please check your {args.config} file.") def chat_huggingface(messages, api_key, api_type, api_endpoint, return_planning = False, return_results = False): def server(): http_listen = config["http_listen"] host = http_listen["host"] port = http_listen["port"] app = flask.Flask(__name__, static_folder="public", static_url_path="/") app.config['DEBUG'] = False CORS(app) @cross_origin() @app.route('/tasks', methods=['POST']) def tasks(): data = request.get_json() messages = data["messages"] api_key = data.get("api_key", API_KEY) api_endpoint = data.get("api_endpoint", API_ENDPOINT) api_type = data.get("api_type", API_TYPE) if api_key is None or api_type is None or api_endpoint is None: return jsonify({"error": "Please provide api_key, api_type and api_endpoint"}) response = chat_huggingface(messages, api_key, api_type, api_endpoint, return_planning=True) return jsonify(response) @cross_origin() @app.route('/results', methods=['POST']) def results(): data = request.get_json() messages = data["messages"] api_key = data.get("api_key", API_KEY) api_endpoint = data.get("api_endpoint", API_ENDPOINT) api_type = data.get("api_type", API_TYPE) if api_key is None or api_type is None or api_endpoint is None: return jsonify({"error": "Please provide api_key, api_type and api_endpoint"}) response = chat_huggingface(messages, api_key, api_type, api_endpoint, return_results=True) return jsonify(response) @cross_origin() @app.route('/hugginggpt', methods=['POST']) def chat(): data = request.get_json() messages = data["messages"] api_key = data.get("api_key", API_KEY) api_endpoint = data.get("api_endpoint", API_ENDPOINT) api_type = data.get("api_type", API_TYPE) if api_key is None or api_type is None or api_endpoint is None: return jsonify({"error": "Please provide api_key, api_type and api_endpoint"}) response = chat_huggingface(messages, api_key, api_type, api_endpoint) return jsonify(response) print("server running...") waitress.serve(app, host=host, port=port)
null
154,570
import tiktoken encodings = { "gpt-4": tiktoken.get_encoding("cl100k_base"), "gpt-4-32k": tiktoken.get_encoding("cl100k_base"), "gpt-3.5-turbo": tiktoken.get_encoding("cl100k_base"), "gpt-3.5-turbo-0301": tiktoken.get_encoding("cl100k_base"), "text-davinci-003": tiktoken.get_encoding("p50k_base"), "text-davinci-002": tiktoken.get_encoding("p50k_base"), "text-davinci-001": tiktoken.get_encoding("r50k_base"), "text-curie-001": tiktoken.get_encoding("r50k_base"), "text-babbage-001": tiktoken.get_encoding("r50k_base"), "text-ada-001": tiktoken.get_encoding("r50k_base"), "davinci": tiktoken.get_encoding("r50k_base"), "curie": tiktoken.get_encoding("r50k_base"), "babbage": tiktoken.get_encoding("r50k_base"), "ada": tiktoken.get_encoding("r50k_base"), } def get_token_ids_for_task_parsing(model_name): text = '''{"task": "text-classification", "token-classification", "text2text-generation", "summarization", "translation", "question-answering", "conversational", "text-generation", "sentence-similarity", "tabular-classification", "object-detection", "image-classification", "image-to-image", "image-to-text", "text-to-image", "visual-question-answering", "document-question-answering", "image-segmentation", "text-to-speech", "text-to-video", "automatic-speech-recognition", "audio-to-audio", "audio-classification", "canny-control", "hed-control", "mlsd-control", "normal-control", "openpose-control", "canny-text-to-image", "depth-text-to-image", "hed-text-to-image", "mlsd-text-to-image", "normal-text-to-image", "openpose-text-to-image", "seg-text-to-image", "args", "text", "path", "dep", "id", "<GENERATED>-"}''' res = encodings[model_name].encode(text) res = list(set(res)) return res
null
154,571
import tiktoken encodings = { "gpt-4": tiktoken.get_encoding("cl100k_base"), "gpt-4-32k": tiktoken.get_encoding("cl100k_base"), "gpt-3.5-turbo": tiktoken.get_encoding("cl100k_base"), "gpt-3.5-turbo-0301": tiktoken.get_encoding("cl100k_base"), "text-davinci-003": tiktoken.get_encoding("p50k_base"), "text-davinci-002": tiktoken.get_encoding("p50k_base"), "text-davinci-001": tiktoken.get_encoding("r50k_base"), "text-curie-001": tiktoken.get_encoding("r50k_base"), "text-babbage-001": tiktoken.get_encoding("r50k_base"), "text-ada-001": tiktoken.get_encoding("r50k_base"), "davinci": tiktoken.get_encoding("r50k_base"), "curie": tiktoken.get_encoding("r50k_base"), "babbage": tiktoken.get_encoding("r50k_base"), "ada": tiktoken.get_encoding("r50k_base"), } def get_token_ids_for_choose_model(model_name): text = '''{"id": "reason"}''' res = encodings[model_name].encode(text) res = list(set(res)) return res
null
154,572
import uuid import gradio as gr import re from diffusers.utils import load_image import requests from awesome_chat import chat_huggingface OPENAI_KEY = "" def set_openai_key(openai_key): global OPENAI_KEY OPENAI_KEY = openai_key return OPENAI_KEY
null
154,573
import uuid import gradio as gr import re from diffusers.utils import load_image import requests from awesome_chat import chat_huggingface OPENAI_KEY = "" def add_message(content, role): message = {"role":role, "content":content} all_messages.append(message) def extract_medias(message): image_pattern = re.compile(r"(http(s?):|\/)?([\.\/_\w:-])*?\.(jpg|jpeg|tiff|gif|png)") image_urls = [] for match in image_pattern.finditer(message): if match.group(0) not in image_urls: image_urls.append(match.group(0)) audio_pattern = re.compile(r"(http(s?):|\/)?([\.\/_\w:-])*?\.(flac|wav)") audio_urls = [] for match in audio_pattern.finditer(message): if match.group(0) not in audio_urls: audio_urls.append(match.group(0)) video_pattern = re.compile(r"(http(s?):|\/)?([\.\/_\w:-])*?\.(mp4)") video_urls = [] for match in video_pattern.finditer(message): if match.group(0) not in video_urls: video_urls.append(match.group(0)) return image_urls, audio_urls, video_urls def add_text(messages, message): if len(OPENAI_KEY) == 0 or not OPENAI_KEY.startswith("sk-"): return messages, "Please set your OpenAI API key first." add_message(message, "user") messages = messages + [(message, None)] image_urls, audio_urls, video_urls = extract_medias(message) for image_url in image_urls: if not image_url.startswith("http"): image_url = "public/" + image_url image = load_image(image_url) name = f"public/images/{str(uuid.uuid4())[:4]}.jpg" image.save(name) messages = messages + [((f"{name}",), None)] for audio_url in audio_urls: if not audio_url.startswith("http"): audio_url = "public/" + audio_url ext = audio_url.split(".")[-1] name = f"public/audios/{str(uuid.uuid4()[:4])}.{ext}" response = requests.get(audio_url) with open(name, "wb") as f: f.write(response.content) messages = messages + [((f"{name}",), None)] for video_url in video_urls: if not video_url.startswith("http"): video_url = "public/" + video_url ext = video_url.split(".")[-1] name = f"public/audios/{str(uuid.uuid4()[:4])}.{ext}" response = requests.get(video_url) with open(name, "wb") as f: f.write(response.content) messages = messages + [((f"{name}",), None)] return messages, ""
null
154,574
import uuid import gradio as gr import re from diffusers.utils import load_image import requests from awesome_chat import chat_huggingface all_messages = [] OPENAI_KEY = "" def add_message(content, role): message = {"role":role, "content":content} all_messages.append(message) def extract_medias(message): image_pattern = re.compile(r"(http(s?):|\/)?([\.\/_\w:-])*?\.(jpg|jpeg|tiff|gif|png)") image_urls = [] for match in image_pattern.finditer(message): if match.group(0) not in image_urls: image_urls.append(match.group(0)) audio_pattern = re.compile(r"(http(s?):|\/)?([\.\/_\w:-])*?\.(flac|wav)") audio_urls = [] for match in audio_pattern.finditer(message): if match.group(0) not in audio_urls: audio_urls.append(match.group(0)) video_pattern = re.compile(r"(http(s?):|\/)?([\.\/_\w:-])*?\.(mp4)") video_urls = [] for match in video_pattern.finditer(message): if match.group(0) not in video_urls: video_urls.append(match.group(0)) return image_urls, audio_urls, video_urls def chat_huggingface(messages, api_key, api_type, api_endpoint, return_planning = False, return_results = False): start = time.time() context = messages[:-1] input = messages[-1]["content"] logger.info("*"*80) logger.info(f"input: {input}") task_str = parse_task(context, input, api_key, api_type, api_endpoint) if "error" in task_str: record_case(success=False, **{"input": input, "task": task_str, "reason": f"task parsing error: {task_str['error']['message']}", "op":"report message"}) return {"message": task_str["error"]["message"]} task_str = task_str.strip() logger.info(task_str) try: tasks = json.loads(task_str) except Exception as e: logger.debug(e) response = chitchat(messages, api_key, api_type, api_endpoint) record_case(success=False, **{"input": input, "task": task_str, "reason": "task parsing fail", "op":"chitchat"}) return {"message": response} if task_str == "[]": # using LLM response for empty task record_case(success=False, **{"input": input, "task": [], "reason": "task parsing fail: empty", "op": "chitchat"}) response = chitchat(messages, api_key, api_type, api_endpoint) return {"message": response} if len(tasks) == 1 and tasks[0]["task"] in ["summarization", "translation", "conversational", "text-generation", "text2text-generation"]: record_case(success=True, **{"input": input, "task": tasks, "reason": "chitchat tasks", "op": "chitchat"}) response = chitchat(messages, api_key, api_type, api_endpoint) return {"message": response} tasks = unfold(tasks) tasks = fix_dep(tasks) logger.debug(tasks) if return_planning: return tasks results = {} threads = [] tasks = tasks[:] d = dict() retry = 0 while True: num_thread = len(threads) for task in tasks: # logger.debug(f"d.keys(): {d.keys()}, dep: {dep}") for dep_id in task["dep"]: if dep_id >= task["id"]: task["dep"] = [-1] break dep = task["dep"] if dep[0] == -1 or len(list(set(dep).intersection(d.keys()))) == len(dep): tasks.remove(task) thread = threading.Thread(target=run_task, args=(input, task, d, api_key, api_type, api_endpoint)) thread.start() threads.append(thread) if num_thread == len(threads): time.sleep(0.5) retry += 1 if retry > 160: logger.debug("User has waited too long, Loop break.") break if len(tasks) == 0: break for thread in threads: thread.join() results = d.copy() logger.debug(results) if return_results: return results response = response_results(input, results, api_key, api_type, api_endpoint).strip() end = time.time() during = end - start answer = {"message": response} record_case(success=True, **{"input": input, "task": task_str, "results": results, "response": response, "during": during, "op":"response"}) logger.info(f"response: {response}") return answer def bot(messages): if len(OPENAI_KEY) == 0 or not OPENAI_KEY.startswith("sk-"): return messages message = chat_huggingface(all_messages, OPENAI_KEY, "openai", "https://api.openai.com/v1/completions")["message"] image_urls, audio_urls, video_urls = extract_medias(message) add_message(message, "assistant") messages[-1][1] = message for image_url in image_urls: if not image_url.startswith("http"): image_url = image_url.replace("public/", "") messages = messages + [((None, (f"public/{image_url}",)))] for audio_url in audio_urls: if not audio_url.startswith("http"): audio_url = audio_url.replace("public/", "") messages = messages + [((None, (f"public/{audio_url}",)))] for video_url in video_urls: if not video_url.startswith("http"): video_url = video_url.replace("public/", "") messages = messages + [((None, (f"public/{video_url}",)))] return messages
null
154,575
import math def normalize(res, round_to=2): def add_(args): return normalize(sum(args))
null
154,576
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res def subtract_(args): res = args[0] for arg in args[1:]: res -= arg return normalize(res)
null
154,577
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res def multiply_(args): res = args[0] for arg in args[1:]: res *= arg return normalize(res)
null
154,578
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res def divide_(args): res = args[0] for arg in args[1:]: res /= arg return normalize(res)
null
154,579
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res def power_(args): res = args[0] for arg in args[1:]: res **= arg return normalize(res)
null
154,580
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res import math def sqrt_(args): res = args[0] return normalize(math.sqrt(res))
null
154,581
import math def normalize(res, round_to=2): import math def log_(args): # if only one argument is passed, it is 10th log if len(args) == 1: res = args[0] return normalize(math.log10(res)) # if two arguments are passed, it is log with base as the second argument elif len(args) == 2: res = args[0] base = args[1] return normalize(math.log(res, base)) else: raise Exception("Invalid number of arguments passed to log function")
null
154,582
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res import math def ln_(args): res = args[0] return normalize(math.log(res))
null
154,583
import math def normalize(res, round_to=2): import math def choose_(args): n = args[0] r = args[1] return normalize(math.comb(n, r))
null
154,584
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res import math def permutate_(args): n = args[0] r = args[1] return normalize(math.perm(n, r))
null
154,585
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res import math def gcd_(args): res = args[0] for arg in args[1:]: res = math.gcd(res, arg) return normalize(res)
null
154,586
import math def normalize(res, round_to=2): import math def lcm_(args): res = args[0] for arg in args[1:]: res = res * arg // math.gcd(res, arg) return normalize(res)
null
154,587
import math def normalize(res, round_to=2): # we round the result to 2 decimal places res = custom_round(res, round_to) res = str(res) if "." in res: while res[-1] == "0": res = res[:-1] res = res.strip(".") # scientific notation if "e" in res: res = scito_decimal(res) return res def remainder_(args): dividend = args[0] divisor = args[1] return normalize(dividend % divisor)
null
154,588
import os import gdown import shutil import json from zipfile import ZipFile def read_jsonline(address): not_mark = [] with open(address, 'r', encoding="utf-8") as f: for jsonstr in f.readlines(): jsonstr = json.loads(jsonstr) not_mark.append(jsonstr) return not_mark
null
154,589
import os import gdown import shutil import json from zipfile import ZipFile def read_json(address): with open(address, 'r', encoding='utf-8') as json_file: json_data = json.load(json_file) return json_data def toolbench_process(data_file, dataset): ls = read_json(data_file) all_data = read_json(f"{dataset}/tool_instruction/toolbench_tool_instruction.json") all_dic = {} for ID in all_data.keys(): all_dic[all_data[ID]["tool_name"]] = all_data[ID] not_in = [] for data in ls: Tool_dic = [] data_dic = {} already = [] for tool in data['api_list']: if tool['tool_name'] in all_dic: if all_dic[tool['tool_name']]["ID"] not in already: already.append(all_dic[tool['tool_name']]["ID"]) Tool_dic.append({"ID": all_dic[tool['tool_name']]["ID"], "Description": all_dic[tool['tool_name']]["tool_description"], }) data["Tool_dic"] = Tool_dic json_str = json.dumps(ls, indent=4) with open(data_file, 'w', encoding='utf-8') as json_file: json.dump(ls, json_file, ensure_ascii=False, indent=4)
null
154,590
json import re import os def read_jsonline(address): not_mark = [] with open(address, 'r', encoding="utf-8") as f: for jsonstr in f.readlines(): jsonstr = json.loads(jsonstr) not_mark.append(jsonstr) return not_mark
null
154,591
json import re import os def save_json(ls, address): json_str = json.dumps(ls, indent=4) with open(address, 'w', encoding='utf-8') as json_file: json.dump(ls, json_file, ensure_ascii=False, indent=4)
null
154,592
json import re import os def read_json(address): with open(address, 'r', encoding='utf-8') as json_file: json_data = json.load(json_file) return json_data
null
154,593
import re import os def remove_key(item, key_to_remove): if isinstance(item, dict): if key_to_remove in item: del item[key_to_remove] for key, value in list(item.items()): # 使用list包裹,防止字典大小改变时引发错误 item[key] = remove_key(value, key_to_remove) elif isinstance(item, list): for index, value in enumerate(item): item[index] = remove_key(value, key_to_remove) return item def data_clean(dic, key): dic = remove_key(dic, key) return dic
null
154,594
import re import os def change_name(name): change_list = ["from", "class", "return", "false", "true", "id", "and", "", "ID"] if name in change_list: name = "is_" + name.lower() return name def lowercase_parameter_keys(input_dict): if "parameters" in input_dict and isinstance(input_dict["parameters"], dict): # Convert all keys in the "parameters" dictionary to uppercase input_dict["parameters"] = {change_name(k.lower()): v for k, v in input_dict["parameters"].items()} return input_dict
null
154,595
import re import os def build_index(base_path): index = {} for root, dirs, files in os.walk(base_path): for dir_name in dirs: if dir_name not in index: index[dir_name] = [] index[dir_name].append(root) return index
null
154,596
import re import os def standardize(string): res = re.compile("[^\\u4e00-\\u9fa5^a-z^A-Z^0-9^_]") string = res.sub("_", string) string = re.sub(r"(_)\1+", "_", string).lower() while True: if len(string) == 0: return string if string[0] == "_": string = string[1:] else: break while True: if len(string) == 0: return string if string[-1] == "_": string = string[:-1] else: break if string[0].isdigit(): string = "get_" + string return string
null
154,597
import re import os The provided code snippet includes necessary dependencies for implementing the `get_last_processed_index` function. Write a Python function `def get_last_processed_index(progress_file)` to solve the following problem: Retrieve the last processed index from the progress file. Here is the function: def get_last_processed_index(progress_file): """Retrieve the last processed index from the progress file.""" if os.path.exists(progress_file): with open(progress_file, 'r', encoding='utf-8') as f: last_index = f.read().strip() return int(last_index) if last_index else 0 else: return 0
Retrieve the last processed index from the progress file.
154,598
import re import os The provided code snippet includes necessary dependencies for implementing the `update_progress` function. Write a Python function `def update_progress(progress_file, index)` to solve the following problem: Update the last processed index in the progress file. Here is the function: def update_progress(progress_file, index): """Update the last processed index in the progress file.""" with open(progress_file, 'w', encoding='utf-8') as f: f.write(str(index))
Update the last processed index in the progress file.
154,599
import json import logging import sys import argparse from langchain.chat_models import ChatOpenAI from langchain.prompts import ( ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate ) from langchain import LLMChain import numpy as np import requests import os import subprocess import re import importlib.util from sklearn.metrics.pairwise import cosine_similarity import pickle from util import * from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the `get_last_processed_index` function. Write a Python function `def get_last_processed_index(progress_file)` to solve the following problem: Retrieve the last processed index from the progress file. Here is the function: def get_last_processed_index(progress_file): """Retrieve the last processed index from the progress file.""" if os.path.exists(progress_file): with open(progress_file, 'r', encoding='utf-8') as f: last_index = f.read().strip() return int(last_index) if last_index else 0 else: return 0
Retrieve the last processed index from the progress file.
154,600
import json import logging import sys import argparse from langchain.chat_models import ChatOpenAI from langchain.prompts import ( ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate ) from langchain import LLMChain import numpy as np import requests import os import subprocess import re import importlib.util from sklearn.metrics.pairwise import cosine_similarity import pickle from util import * from tqdm import tqdm def update_progress(progress_file, index): """Update the last processed index in the progress file.""" with open(progress_file, 'w', encoding='utf-8') as f: f.write(str(index)) def task_decompose(question, Tool_dic, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "We have spotify database and the following tools:\n" "{Tool_dic}" "You need to decompose a complex user's question into some simple subtasks and let the model execute it step by step with these tools.\n" "Please note that: \n" "1. you should break down tasks into appropriate subtasks to use the tools mentioned above.\n" "2. You should not only list the subtask, but also list the ID of the tool used to solve this subtask.\n" "3. If you think you do not need to use the tool to solve the subtask, just leave it as {{\"ID\": -1}}\n" "4. You must consider the logical connections, order and constraints among the tools to achieve a correct tool path." "5. You must ONLY output the ID of the tool you chose in a parsible JSON format. Two examples output look like:\n" "'''\n" "Question: Pause the player" "Example 1: [{{\"Task\":\"Get information about the user’s current playback state\", \"ID\":15}}, {{\"Task\":\"Pause playback on the user's account\", \"ID\":19}}]\n" "'''\n" "This is the user's question: {question}\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question, Tool_dic=Tool_dic) result = eval(result.split('\n\n')[0]) break except Exception as e: print(f"task decompose fails: {e}") if ind > 10: return -1 ind += 1 continue return result def task_execution( Tool_dic, dic_tool, test_data, progress_file, start_index, total_files, retrieval_num, ind, model_name): with tqdm(total=total_files, desc="Processing files", initial=start_index) as pbar: for i, data in enumerate(test_data[start_index:], start=start_index): question = data["query"] print(question) task_path = task_decompose(question, Tool_dic, model_name) tool_choice_ls = [] for task in task_path: if isinstance(task["ID"], list): for ele in task["ID"]: tool_choice_ls.append(dic_tool[ele]['tool_usage']) elif int(task["ID"]) in dic_tool.keys(): tool_choice_ls.append(dic_tool[task["ID"]]['tool_usage']) ind = ind + 1 with open(f"restbench_{model_name}_Easytool.jsonl", 'a+', encoding='utf-8') as f: line = json.dumps({ "ID": ind, "question": question, "task_path": task_path, "tool_choice_ls": tool_choice_ls }, ensure_ascii=False) f.write(line + '\n') print(tool_choice_ls) update_progress(progress_file, i + 1) pbar.update(1)
null
154,602
import json import logging import sys import argparse from langchain.chat_models import ChatOpenAI from langchain.prompts import ( ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate ) from langchain import LLMChain import numpy as np import requests import os import subprocess import re import importlib.util from sklearn.metrics.pairwise import cosine_similarity import pickle from util import * from tqdm import tqdm def update_progress(progress_file, index): """Update the last processed index in the progress file.""" with open(progress_file, 'w', encoding='utf-8') as f: f.write(str(index)) def answer_generation(question, API_instruction, call_result, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You should answer the question based on the response output by the API tool." "Please note that:\n" "1. Answer the question in natural language based on the API response reasonably and effectively.\n" "2. The user cannot directly get API response, " "so you need to make full use of the response and give the information " "in the response that can satisfy the user's question in as much detail as possible.\n" "This is the user's question:\n {question}\n" "This is the API response:\n {call_result}\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question, call_result=call_result) break except Exception as e: print(f"answer generation fails: {e}") if ind > 2: return -1 ind += 1 continue return result def answer_generation_depend(question, API_instruction, call_result, model_name, previous_log): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You should answer the question based on the response output by the API tool." "Please note that:\n" "1. Try to organize the response into a natural language answer.\n" "2. We will not show the API response to the user, " "thus you need to make full use of the response and give the information " "in the response that can satisfy the user's question in as much detail as possible.\n" "3. The question may have dependencies on answers of other questions, so we will provide logs of previous questions and answers.\n" "There are logs of previous questions and answers: \n {previous_log}\n" "This is the user's question: {question}\n" "This is the response output by the API tool: \n{call_result}\n" "We will not show the API response to the user, " "thus you need to make full use of the response and give the information " "in the response that can satisfy the user's question in as much detail as possible.\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question, call_result=call_result, previous_log=previous_log) break except Exception as e: print(f"answer generation depend fails: {e}") if ind > 2: return -1 ind += 1 continue return result def answer_check(question, answer, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "Please check whether the response can reasonably and accurately answer the question." "If can, please output 'YES'; If not, please output 'NO'\n" "You need to give reasons first and then decide whether the response can reasonably and accurately answer the question. You must only output in a parsible JSON format. Two example outputs look like:\n" "Example 1: {{\"Reason\": \"The reason why you think the response can reasonably and accurately answer the question\", \"Choice\": \"Yes\"}}\n" "Example 2: {{\"Reason\": \"The reason why you think the response cannot reasonably and accurately answer the question\", \"Choice\": \"No\"}}\n" "This is the user's question: {question}\n" "This is the response: {answer}\n" "Output: " ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) result = chain.run(question=question, answer=answer) if 'yes'.lower() in str(result).lower(): return 1 else: return -1 def retrieval(question, Tool_dic, dataset, tool_used, ind, model_name, index, previous_log=None): tool_id = choose_tool(question, Tool_dic, tool_used, model_name) if tool_id == -1: return tool_id, "", "", "", "" if str(tool_id["ID"]) not in dataset: return tool_id, "", "", "", "" tool_instruction = dataset[str(tool_id["ID"])] API_instruction = tool_instruction["tool_description"] API_tool = tool_instruction["standardized_name"] API_list = [] for ele in tool_instruction["tool_guidelines"].keys(): API_list.append(ele) api_selection = choose_API(API_instruction, API_list, question, model_name) api_result = [] if len(api_selection) == 0: call_result = "" print("No Calling") return tool_id, api_result, call_result, tool_instruction, API_instruction for api in api_selection: if previous_log is None: parameter = choose_parameter(API_instruction, api, tool_instruction["tool_guidelines"][api], question, model_name) else: parameter = choose_parameter_depend(API_instruction, api, tool_instruction["tool_guidelines"][api], question, previous_log, model_name) if parameter == -1: continue api_result.append({"api_name": api, "parameters": parameter}) if len(api_result) == 0: call_result = "" return tool_id, api_result, call_result, tool_instruction, API_instruction if isinstance(api_result, set) or isinstance(api_result, list): call_results = [] for api in api_result: api_name = change_name(standardize(api["api_name"])) if isinstance(api["parameters"], dict): parameters = {} for key in api["parameters"]: value = api["parameters"][key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, api_name, parameters, index, ind) if call_result == -1: continue call_results.append(str(call_result)) elif isinstance(api["parameters"], list): for para_ls in api["parameters"]: parameters = {} for key in para_ls: value = para_ls[key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, api_name, parameters, index, ind) if call_result == -1: continue call_results.append(str(call_result)) call_result = '\n\n'.join(call_results) elif isinstance(api_result, dict): api_name = change_name(standardize(api_result["api_name"])) api = api_result if isinstance(api["parameters"], dict): parameters = {} for key in api["parameters"]: value = api["parameters"][key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, api_name, parameters, index, ind) elif isinstance(api["parameters"], list): call_results = [] for para_ls in api["parameters"]: parameters = {} for key in para_ls: value = para_ls[key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, api_name, parameters, index, ind) if call_result == -1: continue call_results.append(str(call_result)) call_result = '\n\n'.join(call_results) return tool_id, api_result, call_result, tool_instruction, API_instruction def task_decompose(question, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You need to decompose a complex user's question into some simple subtasks and let the model execute it step by step.\n" "This is the user's question: {question}\n" "Please note that: \n" "1. You should only decompose this complex user's question into some simple subtasks which can be executed easily by using a single tool.\n" "2. Each simple subtask should be expressed into natural language.\n" "3. Each subtask should contain the necessary information from the original question and should be complete, explicit and self-consistent.\n" "4. You must ONLY output the ID of the tool you chose in a parsible JSON format. An example output looks like:\n" "'''\n" "{{\"Tasks\": [\"Task 1\", \"Task 2\", ...]}}\n" "'''\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question) result = eval(result.split('\n\n')[0]) a = result["Tasks"] break except Exception as e: print(f"task decompose fails: {e}") if ind > 10: return -1 ind += 1 continue return result def task_topology(question, task_ls, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "Given a complex user's question, I have decompose this question into some simple subtasks" "I think there exists a logical connections and order amontg the tasks. " "Thus you need to help me output this logical connections and order.\n" "You must ONLY output in a parsible JSON format with the following format:\n" "'''\n" "[{{\"task\": task, \"id\", task_id, \"dep\": [dependency_task_id1, dependency_task_id2, ...]}}]\n" "'''\n" "The \"dep\" field denotes the id of the previous task which generates a new resource upon which the current task depends. If there are no dependencies, set \"dep\" to -1.\n\n" "This is user's question: {question}\n" "These are subtasks of this question:\n" "{task_ls}\n" "Output: " ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question, task_ls=task_ls) result = eval(result) for i in range(len(result)): if isinstance(result[i]['dep'], str): temp = [] for ele in result[i]['dep'].split(','): temp.append(int(ele)) result[i]['dep'] = temp elif isinstance(result[i]['dep'], int): result[i]['dep'] = [result[i]['dep']] elif isinstance(result[i]['dep'], list): temp = [] for ele in result[i]['dep']: temp.append(int(ele)) result[i]['dep'] = temp elif result[i]['dep'] == -1: result[i]['dep'] = [-1] a = result[i]['dep'][0] return result except Exception as e: print(f"task topology fails: {e}") if ind > 10: return -1 ind += 1 continue return result def answer_summarize(question, answer_task, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "We break down a complex user's problems into simple subtasks and provide answers to each simple subtask. " "You need to organize these answers to each subtask and form a self-consistent final answer to the user's question\n" "This is the user's question: {question}\n" "These are subtasks and their answers: {answer_task}\n" "Final answer:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) result = chain.run(question=question, answer_task=answer_task) return result def answer_generation_direct(task, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You need to answer the user's question.\n" "This is the user's question: {task}\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) result = chain.run(task=task) return result def tool_check(task, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful language model which can use external APIs to solve user's question." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "As a powerful language model, you're equipped to answer user's question with accumulated knowledge. " "However, in some cases, you need to use external APIs to answer accurately." "Thus, you need to check whether the user's question requires you to call an external API to solve it.\n" "Here are some tips to help you check: \n" "1. If the user's question requires real-time information, since your knowledge base isn't updated in real-time, any such question will demand an API call.\n" "2. If you need to obtain information (e.g., ID, name, phone number, geographical location, rank, etc.), you need to call the database APIs if you are not sure.\n" "3. If the question demand a database search or internet research to generate an answer, this is another situation where an API call is necessary.\n" "If need, please output 'YES'; If not, please output 'NO'\n" "You need to give reasons first and then decide whether to keep it or not. You must only output in a parsible JSON format. Two example outputs look like:\n" "Example 1: {{\"Reason\": \"The reason why you think you do not need to call an external API to solve the user's question\", \"Choice\": \"No\"}}\n" "Example 2: {{\"Reason\": \"The reason why you think you need to call an external API to solve the user's question\", \"Choice\": \"Yes\"}}\n" "This is the user's question: {task}\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(task=task) result = eval(result) a = result["Reason"] b = result["Choice"] if 'yes' in b.lower(): return result, -1 else: return result, 1 except Exception as e: print(f"tool check fails: {e}") if ind > 10: return "", -1 ind += 1 continue return result, -1 def task_execution(data_type, base_path, index, dataset, test_data, progress_file, start_index, total_files, retrieval_num, ind, model_name): with tqdm(total=total_files, desc="Processing files", initial=start_index) as pbar: for i, data in enumerate(test_data[start_index:], start=start_index): answer_ls = [] question = data["query"] print(question) temp = task_decompose(question, model_name)['Tasks'] task_ls = [] for t in range(len(temp)): task_ls.append({"task": temp[t], "id": t + 1}) task_ls = task_topology(question, task_ls, model_name) task_depend = {} for task_dic in task_ls: task_depend[task_dic['id']] = {'task': task_dic['task'], 'answer': ''} answer_task = [] api_result_ls = [] call_result_ls = [] tool_check_reason_ls = [] parameter_ls = [] for task_dic in task_ls: task = task_dic['task'] tool_check_reason, tool_check_result = tool_check(task, model_name) tool_check_reason_ls.append(tool_check_reason) if tool_check_result == 1: print("Do not need tool.") answer = answer_generation_direct(task) answer_task.append({'task': task, 'answer': answer}) else: print("Do need tool.") depend_id = task_dic['dep'] tool_used = [] for r in range(retrieval_num): Tool_dic = data["Tool_dic"] if depend_id[0] == -1: tool_id, api_result, call_result, tool_instruction, API_instruction = retrieval(task, Tool_dic, dataset, tool_used, ind, model_name, index) call_result = str(call_result)[:1000] answer = answer_generation(task, API_instruction, call_result, model_name) else: previous_log = [] for ids in depend_id: previous_log.append(task_depend[ids]) tool_id, api_result, call_result, tool_instruction, API_instruction = retrieval(task, Tool_dic, dataset, tool_used, ind, model_name, index, previous_log=previous_log) call_result = str(call_result)[:1000] answer = answer_generation_depend(task, API_instruction, call_result, model_name, previous_log=previous_log) check_index = answer_check(task, answer, model_name) if check_index == 1: answer_task.append({'task': task, 'answer': answer}) api_result_ls.append(api_result) call_result_ls.append(call_result) break else: answer_ls.append({'task': task, 'answer': answer}) try: tool_used.append(str(tool_id["ID"])) except: continue print('****Try Again****') task_depend[task_dic['id']]['answer'] = answer final_answer = answer_summarize(question, answer_task, model_name) check_index = answer_check(question, final_answer, model_name) ind = ind + 1 with open(f'''{data_type}_{model_name}_Easytool.jsonl''', 'a+', encoding='utf-8') as f: line = json.dumps({ "ID": ind, "question": question, "final_answer": final_answer, "subtask": task_ls, "answer_subtask": answer_task, "answer_wrong": answer_ls, "check_index": check_index, "execute_log": { "api_result_ls": api_result_ls, "parameter_ls": parameter_ls, "call_result_ls": call_result_ls, "tool_check_reason_ls": tool_check_reason_ls, } }, ensure_ascii=False) f.write(line + '\n') print(final_answer) update_progress(progress_file, i + 1) pbar.update(1)
null
154,604
import json import logging import sys import argparse from langchain.chat_models import ChatOpenAI from langchain.prompts import ( ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate ) from langchain import LLMChain import numpy as np import requests import os import subprocess import re import importlib.util from sklearn.metrics.pairwise import cosine_similarity import pickle from util import * from tqdm import tqdm def update_progress(progress_file, index): def retrieve_reference(embedded_texts, filenames, question, k): def answer_generation(question, API_instruction, call_result, model_name): def answer_generation_depend(question, API_instruction, call_result, model_name, previous_log): def answer_check(question, answer, model_name): def retrieval(question, Tool_dic, dataset, tool_used, ind, model_name, index, previous_log=None): def task_decompose(question, model_name): def task_topology(question, task_ls, model_name): def answer_summarize(question, answer_task, model_name): def answer_generation_direct(task, model_name): def tool_check(task, model_name): def task_execution(data_type, base_path, index, dataset, test_data, progress_file, start_index, total_files, retrieval_num, ind, model_name): with open("data_toolbench/tool_instruction/API_description_embeddings.pkl", "rb") as file: filenames, embedded_texts = pickle.load(file) with tqdm(total=total_files, desc="Processing files", initial=start_index) as pbar: for i, data in enumerate(test_data[start_index:], start=start_index): answer_ls = [] question = data["query"] print(question) temp = task_decompose(question, model_name)['Tasks'] task_ls = [] for t in range(len(temp)): task_ls.append({"task": temp[t], "id": t + 1}) task_ls = task_topology(question, task_ls, model_name) task_depend = {} for task_dic in task_ls: task_depend[task_dic['id']] = {'task': task_dic['task'], 'answer': ''} answer_task = [] api_result_ls = [] call_result_ls = [] tool_check_reason_ls = [] parameter_ls = [] for task_dic in task_ls: task = task_dic['task'] tool_check_reason, tool_check_result = tool_check(task, model_name) tool_check_reason_ls.append(tool_check_reason) if tool_check_result == 1: print("Do not need tool.") answer = answer_generation_direct(task) answer_task.append({'task': task, 'answer': answer}) else: print("Do need tool.") depend_id = task_dic['dep'] tool_used = [] Tool_dic = [{tool: dataset[str(tool)]["tool_description"]} for tool in retrieve_reference(embedded_texts, filenames, task, k=5)] for r in range(retrieval_num): if depend_id[0] == -1: tool_id, api_result, call_result, tool_instruction, API_instruction = retrieval(task, Tool_dic, dataset, tool_used, ind, model_name, index) call_result = str(call_result)[:1000] answer = answer_generation(task, API_instruction, call_result, model_name) else: previous_log = [] for ids in depend_id: previous_log.append(task_depend[ids]) tool_id, api_result, call_result, tool_instruction, API_instruction = retrieval(task, Tool_dic, dataset, tool_used, ind, model_name, index, previous_log=previous_log) call_result = str(call_result)[:1000] answer = answer_generation_depend(task, API_instruction, call_result, model_name, previous_log=previous_log) check_index = answer_check(task, answer, model_name) if check_index == 1: answer_task.append({'task': task, 'answer': answer}) api_result_ls.append(api_result) call_result_ls.append(call_result) break else: answer_ls.append({'task': task, 'answer': answer}) try: tool_used.append(str(tool_id["ID"])) except: continue print('****Try Again****') task_depend[task_dic['id']]['answer'] = answer final_answer = answer_summarize(question, answer_task, model_name) check_index = answer_check(question, final_answer, model_name) ind = ind + 1 with open(f'''{data_type}_{model_name}_retrieve_Easytool.jsonl''', 'a+', encoding='utf-8') as f: line = json.dumps({ "ID": ind, "question": question, "final_answer": final_answer, "subtask": task_ls, "answer_subtask": answer_task, "answer_wrong": answer_ls, "check_index": check_index, "execute_log": { "api_result_ls": api_result_ls, "parameter_ls": parameter_ls, "call_result_ls": call_result_ls, "tool_check_reason_ls": tool_check_reason_ls, } }, ensure_ascii=False) f.write(line + '\n') print(final_answer) update_progress(progress_file, i + 1) pbar.update(1)
null
154,606
import json import logging import sys import argparse from langchain.chat_models import ChatOpenAI from langchain.prompts import ( ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate ) from langchain import LLMChain import numpy as np import requests import os import subprocess import re import importlib.util from sklearn.metrics.pairwise import cosine_similarity import pickle from util import * from tqdm import tqdm def answer_generation_direct(task, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You need to answer the user's question.\n" "This is the user's question: {task}\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) result = chain.run(task=task) return result
null
154,607
import json import logging import sys import argparse from langchain.chat_models import ChatOpenAI from langchain.prompts import ( ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate ) from langchain import LLMChain import numpy as np import requests import os import subprocess import re import importlib.util from sklearn.metrics.pairwise import cosine_similarity import pickle from util import * from tqdm import tqdm def update_progress(progress_file, index): """Update the last processed index in the progress file.""" with open(progress_file, 'w', encoding='utf-8') as f: f.write(str(index)) def task_decompose(question, Tool_dic, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You need to decompose a complex user's question into some simple subtasks and let the model execute it step by step.\n" "This is the user's question: {question}\n" "This is tool list:\n" "{Tool_list}\n" "Please note that: \n" "1. You should only decompose this complex user's question into some simple subtasks which can be executed easily by using one single tool in the tool list.\n" "2. If one subtask need the results from other subtask, you can should write clearly. For example:" "{{\"Tasks\": [\"Convert 23 km/h to X km/min by 'divide_'\", \"Multiply X km/min by 45 min to get Y by 'multiply_'\"]}}\n" "3. You must ONLY output in a parsible JSON format. An example output looks like:\n" "'''\n" "{{\"Tasks\": [\"Task 1\", \"Task 2\", ...]}}\n" "'''\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) Tool_list = [] for ele in Tool_dic: Tool_list.append(str(ele)) ind = 0 while True: try: result = chain.run(question=question, Tool_list=Tool_list) result = eval(result.split('\n\n')[0]) a = result["Tasks"] break except Exception as e: print(f"task decompose fails: {e}") if ind > 10: return -1 ind += 1 continue return result def task_topology(question, task_ls, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "Given a complex user's question, I have decompose this question into some simple subtasks" "I think there exists a logical connections and order amontg the tasks. " "Thus you need to help me output this logical connections and order.\n" "You must ONLY output in a parsible JSON format with the following format:\n" "'''\n" "[{{\"task\": task, \"id\", task_id, \"dep\": [dependency_task_id1, dependency_task_id2, ...]}}]\n" "'''\n" "The \"dep\" field denotes the id of the previous task which generates a new resource upon which the current task depends. If there are no dependencies, set \"dep\" to -1.\n\n" "This is user's question: {question}\n" "These are subtasks of this question:\n" "{task_ls}\n" "Output: " ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question, task_ls=task_ls) result = eval(result) for i in range(len(result)): if isinstance(result[i]['dep'], str): temp = [] for ele in result[i]['dep'].split(','): temp.append(int(ele)) result[i]['dep'] = temp elif isinstance(result[i]['dep'], int): result[i]['dep'] = [result[i]['dep']] elif isinstance(result[i]['dep'], list): temp = [] for ele in result[i]['dep']: temp.append(int(ele)) result[i]['dep'] = temp elif result[i]['dep'] == -1: result[i]['dep'] = [-1] a = result[i]['dep'][0] return result except Exception as e: print(f"task topology fails: {e}") if ind > 10: return -1 ind += 1 continue return result def retrieval(question, Tool_dic, dataset, tool_used, ind, model_name, previous_log=None): tool_id = choose_tool(question, Tool_dic, tool_used, model_name) if tool_id == -1: return tool_id, "", "", "", "" tool_instruction = dataset[str(tool_id["ID"])] API_instruction = tool_instruction["API_description"] API_tool = tool_instruction["standardized_name"] api_selection = [API_tool] api_result = [] for api in api_selection: if previous_log is None: parameter = choose_parameter(API_instruction, api, tool_instruction["Usage"], question, model_name) else: parameter = choose_parameter_depend(API_instruction, api, tool_instruction["Usage"], question, model_name, previous_log) if parameter == -1: continue api_result.append({"api_name": api, "parameters": parameter}) if len(api_result) == 0: call_result = "" return tool_id, api_result, call_result, tool_instruction, API_instruction if isinstance(api_result, set) or isinstance(api_result, list): call_results = [] for api in api_result: if isinstance(api["parameters"], dict): parameters = {} for key in api["parameters"]: value = api["parameters"][key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, parameters, ind) if call_result == -1: continue call_results.append(str(call_result)) elif isinstance(api["parameters"], list): for para_ls in api["parameters"]: parameters = {} for key in para_ls: value = para_ls[key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, parameters, ind) if call_result == -1: continue call_results.append(str(call_result)) call_result = '\n\n'.join(call_results) elif isinstance(api_result, dict): api = api_result if isinstance(api["parameters"], dict): parameters = {} for key in api["parameters"]: value = api["parameters"][key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, parameters, ind) elif isinstance(api["parameters"], list): call_results = [] for para_ls in api["parameters"]: parameters = {} for key in para_ls: value = para_ls[key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, parameters, ind) if call_result == -1: continue call_results.append(str(call_result)) call_result = '\n\n'.join(call_results) return tool_id, api_result, call_result, tool_instruction, API_instruction def answer_generation(question, API_instruction, call_result, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You should answer the question based on the response output by the API tool." "Please note that:\n" "1. Answer the question in natural language based on the API response reasonably and effectively.\n" "2. The user cannot directly get API response, " "so you need to make full use of the response and give the information " "in the response that can satisfy the user's question in as much detail as possible.\n" "3. If the API tool does not provide useful information in the response, " "please answer with your knowledge.\n" "This is the user's question:\n {question}\n" "This is the API response:\n {call_result}\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question, API_instruction=API_instruction, call_result=call_result, ) break except Exception as e: print(f"answer generation fails: {e}") if ind > 2: return -1 ind += 1 continue return result def answer_generation_depend(question, API_instruction, call_result, previous_log, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You should answer the question based on the response output by the API tool." "Please note that:\n" "1. Try to organize the response into a natural language answer.\n" "2. We will not show the API response to the user, " "thus you need to make full use of the response and give the information " "in the response that can satisfy the user's question in as much detail as possible.\n" "3. If the API tool does not provide useful information in the response, " "please answer with your knowledge.\n" "4. The question may have dependencies on answers of other questions, so we will provide logs of previous questions and answers.\n" "There are logs of previous questions and answers: \n {previous_log}\n" "This is the user's question: {question}\n" "This is the response output by the API tool: \n{call_result}\n" "We will not show the API response to the user, " "thus you need to make full use of the response and give the information " "in the response that can satisfy the user's question in as much detail as possible.\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question, API_instruction=API_instruction, call_result=call_result, previous_log=previous_log) break except Exception as e: print(f"answer generation depend fails: {e}") if ind > 2: return -1 ind += 1 continue return result def answer_summarize(question, answer_task, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "We break down a complex user's problems into simple subtasks and provide answers to each simple subtask. " "You need to organize these answers to each subtask and form a self-consistent final answer to the user's question\n" "This is the user's question: {question}\n" "These are subtasks and their answers: {answer_task}\n" "Final answer:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) result = chain.run(question=question, answer_task=answer_task) return result def answer_check(question, answer, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "Please check whether the response can reasonably and accurately answer the question." "If can, please output 'YES'; If not, please output 'NO'\n" "You need to give reasons first and then decide whether the response can reasonably and accurately answer the question. You must only output in a parsible JSON format. Two example outputs look like:\n" "Example 1: {{\"Reason\": \"The reason why you think the response can reasonably and accurately answer the question\", \"Choice\": \"Yes\"}}\n" "Example 2: {{\"Reason\": \"The reason why you think the response cannot reasonably and accurately answer the question\", \"Choice\": \"No\"}}\n" "This is the user's question: {question}\n" "This is the response: {answer}\n" "Output: " ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) result = chain.run(question=question, answer=answer) if 'yes'.lower() in eval(result)["Choice"].lower(): return 1 else: return -1 def task_execution_mh(data_type, start_index, total_files, retrieval_num, ind, model_name, dataset, Tool_dic, test_data, progress_file): with tqdm(total=total_files, desc="Processing files", initial=start_index) as pbar: for i, data in enumerate(test_data[start_index:], start=start_index): answer_ls = [] question = data["question"] print(question) temp = task_decompose(question, Tool_dic, model_name)['Tasks'] task_ls = [] for t in range(len(temp)): task_ls.append({"task": temp[t], "id": t + 1}) task_ls = task_topology(question, task_ls, model_name) task_depend = {'Original Question': question} for task_dic in task_ls: task_depend[task_dic['id']] = {'task': task_dic['task'], 'answer': ''} answer_task = [] tool_instruction_ls = [] api_result_ls = [] call_result_ls = [] tool_check_reason_ls = [] for task_dic in task_ls: task = task_dic['task'] print("Do need tool.") tool_used = [] depend_id = [1] for r in range(retrieval_num): if depend_id[0] == -1: tool_id, api_result, call_result, tool_instruction, API_instruction = retrieval(task, Tool_dic, dataset, tool_used, ind, model_name) if len(str(call_result)) > 5000: call_result = str(call_result)[:5000] answer = answer_generation(task, API_instruction, call_result, model_name) else: previous_log = task_depend tool_id, api_result, call_result, tool_instruction, API_instruction = retrieval(task, Tool_dic, dataset, tool_used, ind, model_name, previous_log=previous_log) if len(str(call_result)) > 5000: call_result = str(call_result)[:5000] answer = answer_generation_depend(task, API_instruction, call_result, previous_log, model_name) check_index = 1 if str(call_result).strip() == '-1' or str(call_result).strip() == '': check_index = -1 if check_index == 1: answer_task.append({'task': task, 'answer': answer}) tool_instruction_ls.append(tool_instruction) api_result_ls.append(api_result) call_result_ls.append(call_result) break else: answer_ls.append({'task': task, 'answer': answer}) try: tool_used.append(str(tool_id["ID"])) except: continue print('****Try Again****') task_depend[task_dic['id']]['answer'] = answer final_answer = answer_summarize(question, answer_task, model_name) check_index = answer_check(question, final_answer, model_name) ind = ind + 1 with open(f"FuncQA_{data_type}_{model_name}_easytool.jsonl", 'a+', encoding='utf-8') as f: line = json.dumps({ "ID": ind, "question": question, "final_answer": final_answer, "subtask": task_ls, "answer_subtask": answer_task, "answer_wrong": answer_ls, "check_index": check_index, "execute_log": { "api_result_ls": api_result_ls, "call_result_ls": call_result_ls, "tool_check_reason_ls": tool_check_reason_ls, "tool_instruction_ls": tool_instruction_ls, }, "check": 0 }, ensure_ascii=False) f.write(line + '\n') print(final_answer) update_progress(progress_file, i + 1) pbar.update(1)
null
154,608
import json import logging import sys import argparse from langchain.chat_models import ChatOpenAI from langchain.prompts import ( ChatPromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, HumanMessagePromptTemplate ) from langchain import LLMChain import numpy as np import requests import os import subprocess import re import importlib.util from sklearn.metrics.pairwise import cosine_similarity import pickle from util import * from tqdm import tqdm def update_progress(progress_file, index): """Update the last processed index in the progress file.""" with open(progress_file, 'w', encoding='utf-8') as f: f.write(str(index)) def retrieval(question, Tool_dic, dataset, tool_used, ind, model_name, previous_log=None): tool_id = choose_tool(question, Tool_dic, tool_used, model_name) if tool_id == -1: return tool_id, "", "", "", "" tool_instruction = dataset[str(tool_id["ID"])] API_instruction = tool_instruction["API_description"] API_tool = tool_instruction["standardized_name"] api_selection = [API_tool] api_result = [] for api in api_selection: if previous_log is None: parameter = choose_parameter(API_instruction, api, tool_instruction["Usage"], question, model_name) else: parameter = choose_parameter_depend(API_instruction, api, tool_instruction["Usage"], question, model_name, previous_log) if parameter == -1: continue api_result.append({"api_name": api, "parameters": parameter}) if len(api_result) == 0: call_result = "" return tool_id, api_result, call_result, tool_instruction, API_instruction if isinstance(api_result, set) or isinstance(api_result, list): call_results = [] for api in api_result: if isinstance(api["parameters"], dict): parameters = {} for key in api["parameters"]: value = api["parameters"][key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, parameters, ind) if call_result == -1: continue call_results.append(str(call_result)) elif isinstance(api["parameters"], list): for para_ls in api["parameters"]: parameters = {} for key in para_ls: value = para_ls[key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, parameters, ind) if call_result == -1: continue call_results.append(str(call_result)) call_result = '\n\n'.join(call_results) elif isinstance(api_result, dict): api = api_result if isinstance(api["parameters"], dict): parameters = {} for key in api["parameters"]: value = api["parameters"][key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, parameters, ind) elif isinstance(api["parameters"], list): call_results = [] for para_ls in api["parameters"]: parameters = {} for key in para_ls: value = para_ls[key] key = change_name(key) parameters[key] = value call_result = Call_function(API_tool, parameters, ind) if call_result == -1: continue call_results.append(str(call_result)) call_result = '\n\n'.join(call_results) return tool_id, api_result, call_result, tool_instruction, API_instruction def answer_generation(question, API_instruction, call_result, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "You should answer the question based on the response output by the API tool." "Please note that:\n" "1. Answer the question in natural language based on the API response reasonably and effectively.\n" "2. The user cannot directly get API response, " "so you need to make full use of the response and give the information " "in the response that can satisfy the user's question in as much detail as possible.\n" "3. If the API tool does not provide useful information in the response, " "please answer with your knowledge.\n" "This is the user's question:\n {question}\n" "This is the API response:\n {call_result}\n" "Output:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) ind = 0 while True: try: result = chain.run(question=question, API_instruction=API_instruction, call_result=call_result, ) break except Exception as e: print(f"answer generation fails: {e}") if ind > 2: return -1 ind += 1 continue return result def answer_summarize(question, answer_task, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "We break down a complex user's problems into simple subtasks and provide answers to each simple subtask. " "You need to organize these answers to each subtask and form a self-consistent final answer to the user's question\n" "This is the user's question: {question}\n" "These are subtasks and their answers: {answer_task}\n" "Final answer:" ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) result = chain.run(question=question, answer_task=answer_task) return result def answer_check(question, answer, model_name): chat = ChatOpenAI(model_name=model_name) template = "You are a helpful assistant." system_message_prompt = SystemMessagePromptTemplate.from_template(template) human_message_prompt = HumanMessagePromptTemplate.from_template( "Please check whether the response can reasonably and accurately answer the question." "If can, please output 'YES'; If not, please output 'NO'\n" "You need to give reasons first and then decide whether the response can reasonably and accurately answer the question. You must only output in a parsible JSON format. Two example outputs look like:\n" "Example 1: {{\"Reason\": \"The reason why you think the response can reasonably and accurately answer the question\", \"Choice\": \"Yes\"}}\n" "Example 2: {{\"Reason\": \"The reason why you think the response cannot reasonably and accurately answer the question\", \"Choice\": \"No\"}}\n" "This is the user's question: {question}\n" "This is the response: {answer}\n" "Output: " ) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) chain = LLMChain(llm=chat, prompt=chat_prompt) result = chain.run(question=question, answer=answer) if 'yes'.lower() in eval(result)["Choice"].lower(): return 1 else: return -1 def task_execution_oh(data_type, start_index, total_files, retrieval_num, ind, model_name, dataset, Tool_dic, test_data, progress_file): with tqdm(total=total_files, desc="Processing files", initial=start_index) as pbar: for i, data in enumerate(test_data[start_index:], start=start_index): answer_ls = [] question = data["question"] print(question) task_ls = [{"task": question}] answer_task = [] tool_instruction_ls = [] api_result_ls = [] call_result_ls = [] tool_check_reason_ls = [] for task_dic in task_ls: task = task_dic['task'] print("Do need tool.") tool_used = [] depend_id = [1] for r in range(retrieval_num): tool_id, api_result, call_result, tool_instruction, API_instruction = retrieval(task, Tool_dic, dataset, tool_used, ind, model_name) if len(str(call_result)) > 5000: call_result = str(call_result)[:5000] answer = answer_generation(task, API_instruction, call_result, model_name) check_index = 1 if str(call_result).strip() == '-1' or str(call_result).strip() == '': check_index = -1 if check_index == 1: answer_task.append({'task': task, 'answer': answer}) tool_instruction_ls.append(tool_instruction) api_result_ls.append(api_result) call_result_ls.append(call_result) break else: answer_ls.append({'task': task, 'answer': answer}) try: tool_used.append(str(tool_id["ID"])) except: continue print('****Try Again****') final_answer = answer_summarize(question, answer_task, model_name) check_index = answer_check(question, final_answer, model_name) ind = ind + 1 with open(f"FuncQA_{data_type}_{model_name}_easytool.jsonl", 'a+', encoding='utf-8') as f: line = json.dumps({ "ID": ind, "question": question, "final_answer": final_answer, "subtask": task_ls, "answer_subtask": answer_task, "answer_wrong": answer_ls, "check_index": check_index, "execute_log": { "api_result_ls": api_result_ls, "call_result_ls": call_result_ls, "tool_check_reason_ls": tool_check_reason_ls, "tool_instruction_ls": tool_instruction_ls, }, "check": 0 }, ensure_ascii=False) f.write(line + '\n') print(final_answer) update_progress(progress_file, i + 1) pbar.update(1)
null
154,609
import os import json import click import asyncio import aiohttp import logging import emoji logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.handlers = [] async def get_response(url, payload, id, reformat, reformat_by, dependency_type, log_detail=False): headers = { 'Content-Type': 'application/json' } async with aiohttp.ClientSession() as session: async with session.post(url, headers=headers, data=payload, timeout=300) as response: resp = await response.json() if response.status == 429: raise RateLimitError(f"{resp}") if response.status != 200: raise Exception(f"{resp}") if log_detail: logger.info(json.loads(payload)["messages"][0]["content"]) logger.info(resp["choices"][0]["message"]["content"]) oring_content = resp["choices"][0]["message"]["content"] oring_content = oring_content.replace("\n", "") oring_content = oring_content.replace("\_", "_") content = oring_content.replace("\\", "") start_pos = content.find("RESULT #:") if start_pos!=-1: content = content[start_pos+len("RESULT #:"):] try: content = json.loads(content) if isinstance(content, list) and len(content): merge_content = {} for c in content: for k, v in c.items(): merge_content[k].extend(v) if k in merge_content else merge_content.update({k: v}) return content except json.JSONDecodeError as e: if reformat: if dependency_type == "resource": prompt = """Please format the result # RESULT # to a strict JSON format # STRICT JSON FORMAT #. \nRequirements:\n1. Do not change the meaning of task steps and task nodes;\n2. Don't tolerate any possible irregular formatting to ensure that the generated content can be converted by json.loads();\n3. You must output the result in this schema: {"task_steps": [ step description of one or more steps ], "task_nodes": [{"task": "tool name must be from # TOOL LIST #", "arguments": [ a concise list of arguments for the tool. Either original text, or user-mentioned filename, or tag '<node-j>' (start from 0) to refer to the output of the j-th node. ]}]}\n# RESULT #:{{illegal_result}}\n# STRICT JSON FORMAT #:""" else: prompt = """Please format the result # RESULT # to a strict JSON format # STRICT JSON FORMAT #. \nRequirements:\n1. Do not change the meaning of task steps, task nodes and task links;\n2. Don't tolerate any possible irregular formatting to ensure that the generated content can be converted by json.loads();\n3. Pay attention to the matching of brackets. Write in a compact format and avoid using too many space formatting controls;\n4. You must output the result in this schema: {"task_steps": [ "concrete steps, format as Step x: Call xxx tool with xxx: 'xxx' and xxx: 'xxx'" ], "task_nodes": [{"task": "task name must be from # TASK LIST #", "arguments": [ {"name": "parameter name", "value": "parameter value, either user-specified text or the specific name of the tool whose result is required by this node"} ]}], "task_links": [{"source": "task name i", "target": "task name j"}]}\n# RESULT #:{{illegal_result}}\n# STRICT JSON FORMAT #:""" prompt = prompt.replace("{{illegal_result}}", oring_content) payload = json.loads(payload) if reformat_by != "self": if payload["model"] == "text-davinci-003": url = url.replace("8012", "8002") else: url = url.replace("8015", "8002") payload["model"] = reformat_by if log_detail: logger.info(f"{emoji.emojize(':warning:')} #id {id} Illegal JSON format: {content}") logger.info(f"{emoji.emojize(':sparkles:')} #id {id} Detected illegal JSON format, try to reformat by {payload['model']}...") payload["messages"][0]["content"] = prompt payload = json.dumps(payload) async with aiohttp.ClientSession() as session: async with session.post(url, headers=headers, data=payload, timeout=120) as response: resp = await response.json() if response.status == 429: raise RateLimitError(f"{resp}") if response.status != 200: raise Exception(f"{resp}") if log_detail: logger.info(json.loads(payload)["messages"][0]["content"]) logger.info(resp["choices"][0]["message"]["content"]) content = resp["choices"][0]["message"]["content"] content = content.replace("\n", "") content = content.replace("\_", "_") start_pos = content.find("STRICT JSON FORMAT #:") if start_pos!=-1: content = content[start_pos+len("STRICT JSON FORMAT #:"):] content = content[content.find("{"):content.rfind("}")+1] try: content = json.loads(content) return content except json.JSONDecodeError as e: raise ContentFormatError(f"{content}") else: raise ContentFormatError(f"{content}") async def inference(input, url, temperature, top_p, tool_string, wf, llm, demos, reformat, reformat_by, dependency_type, log_detail = False): user_request = input["user_request"] if dependency_type == "resource": prompt = """\n# GOAL #: Based on the above tools, I want you generate task steps and task nodes to solve the # USER REQUEST #. The format must in a strict JSON format, like: {"task_steps": [ step description of one or more steps ], "task_nodes": [{"task": "tool name must be from # TOOL LIST #", "arguments": [ a concise list of arguments for the tool. Either original text, or user-mentioned filename, or tag '<node-j>' (start from 0) to refer to the output of the j-th node. ]}]} """ prompt += """\n\n# REQUIREMENTS #: \n1. the generated task steps and task nodes can resolve the given user request # USER REQUEST # perfectly. Task name must be selected from # TASK LIST #; \n2. the task steps should strictly aligned with the task nodes, and the number of task steps should be same with the task nodes; \n3. the dependencies among task steps should align with the argument dependencies of the task nodes; \n4. the tool arguments should be align with the input-type field of # TASK LIST #;""" else: prompt = """\n# GOAL #:\nBased on the above tools, I want you generate task steps and task nodes to solve the # USER REQUEST #. The format must in a strict JSON format, like: {"task_steps": [ "concrete steps, format as Step x: Call xxx tool with xxx: 'xxx' and xxx: 'xxx'" ], "task_nodes": [{"task": "task name must be from # TASK LIST #", "arguments": [ {"name": "parameter name", "value": "parameter value, either user-specified text or the specific name of the tool whose result is required by this node"} ]}], "task_links": [{"source": "task name i", "target": "task name j"}]}""" prompt += """\n\n# REQUIREMENTS #: \n1. the generated task steps and task nodes can resolve the given user request # USER REQUEST # perfectly. Task name must be selected from # TASK LIST #; \n2. the task steps should strictly aligned with the task nodes, and the number of task steps should be same with the task nodes; \n3. The task links (task_links) should reflect the temporal dependencies among task nodes, i.e. the order in which the APIs are invoked;""" if len(demos) > 0: prompt += "\n" for demo in demos: prompt += f"""\n# EXAMPLE #:\n# USER REQUEST #: {demo["user_request"]}\n# RESULT #: {json.dumps(demo["result"])}""" prompt += """\n\n# USER REQUEST #: {{user_request}}\nnow please generate your result in a strict JSON format:\n# RESULT #:""" final_prompt = tool_string + prompt.replace("{{user_request}}", user_request) payload = json.dumps({ "model": f"{llm}", "messages": [ { "role": "user", "content": final_prompt } ], "temperature": temperature, "top_p": top_p, "frequency_penalty": 0, "presence_penalty": 1.05, "max_tokens": 2000, "stream": False, "stop": None }) try: result = await get_response(url, payload, input['id'], reformat, reformat_by, dependency_type, log_detail) except Exception as e: logger.info(f"Failed #id {input['id']}: {type(e)} {e}") raise e logger.info(f"Success #id {input['id']}") input["result"] = result wf.write(json.dumps(input) + "\n") wf.flush()
null
154,610
import json import networkx as nx import matplotlib.pyplot as plt import click def visialize_graph(data_dir): graph_file = f"{data_dir}/graph_desc.json" with open(graph_file, "r") as f: data = json.load(f) G = nx.DiGraph() for node in data["nodes"]: G.add_node(node["id"]) for link in data["links"]: G.add_edge(link["source"], link["target"]) pos = nx.spring_layout(G) pos = nx.random_layout(G) pos = nx.kamada_kawai_layout(G) # Show the visualization plt.figure(figsize=(60, 60), dpi=80) plt.tight_layout() plt.axis("off") plt.show() nx.draw_networkx_nodes(G, pos, node_color="skyblue", node_size=1200) nx.draw_networkx_edges(G, pos, arrows=True, arrowsize=40) nx.draw_networkx_labels(G, pos, font_size=50, font_color="green", font_weight="bold") plt.savefig(graph_file.replace(".json", ".pdf"))
null
154,611
import os import random import traceback import uuid import json import networkx as nx from datetime import datetime from concurrent.futures import ThreadPoolExecutor, as_completed import shutil import warnings from graph_sampler import GraphSampler import click import matplotlib.pyplot as plt import asyncio import aiohttp import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.handlers = [] logger.addHandler(console_handler) class RateLimitError(Exception): def __init__(self, message): super().__init__(message) class ContentFormatError(Exception): def __init__(self, message): super().__init__(message) async def sample(url, llm, temperature, top_p, check, tool_number, sampler, tools, method, figure_dir, wf, dependency_type): start_time = datetime.now() sample_id = str(uuid.uuid4().int)[:8] sub_G = sampler.sample_subgraph(tool_number, sample_method=method) tool_list = list(sub_G.nodes) tool_edge = list(sub_G.edges) seed = random.randint(0, 1000000) headers = { 'Content-Type': 'application/json' } sampled_tools_string = "Given a tool graph with tools as nodes, and invoking chains between tools as edges. The following tools (nodes) are available with their corresponding descriptions and input/outputs types:\n" for k, tool in enumerate(tool_list): sampled_tools_string += f"Node {k+1}:" + json.dumps(tools[tool]) + "\n" sampled_links_string = "These tools can be connected as follows (the directed edges are invoking chains among tools):\n" for k, edge in enumerate(tool_edge): sampled_links_string += f"Edge: " + edge[0] + " -> " + edge[1] + "\n" prompt = """\nBased on the above tool graph, please be skillful to generate the according task steps, user request and tool invoking graph. \nRequirements: \n1. the generated user request should be somewhat clear, self-contained (user-specified text, image, video, audio, content should be contained in the request) and practical (help users solve a practical problem); \n2. the task steps must be strictly aligned with the tool graph (nodes and edges) and reasonable, the tool invoking graph must align with task steps, also with the given tool graph; \n3. the user request just can be decomposed into task steps solved by the tool invoking graph; \n4. each task step corresponds to a tool node in the tool graph and tool invoking graph, and the number of task steps must be same with the nodes. Each tool node can only be used once; \n5. if need image/audio/video resources in user request, please use files 'example.[jpg/mp4/wav/png]'; \n6. the dependencies among task steps must align with the edges of tool graph and tool invoking graph; \n7. the number and types of tool parameters in the generated tool invoking graph need to be consistent with the pre-defined input/outputs types of the tools. \nNow please generate your result (with random seed {""" + f"{seed}"+ """}) in a compact JSON format""" if dependency_type == "resource": prompt += """{"task_steps": [ step description of one or more steps ], "user_request": "your high-quality and self-contained synthesized request", "invoking_graph": {"nodes": [{"id": "tool name", "input": [ either user-specified text or resource file 'example.[jpg/mp4/wav/png' ] in the above user request, or the dependent tool name whose output is required by this node ]}], "links": [{"source": "tool name i", "target": "tool name j"}]}""" else: prompt += """{"task_steps": [ "concrete steps, format as Step x: Call xxx tool with xxx: 'xxx' and xxx: 'xxx'" ], "user_request": "your high-quality, concrete and self-contained synthesized request, with explicit parameter values", "invoking_graph": {"nodes": [{"id": "tool name", "arguments": [ {"name": "parameter name", "value": "parameter value, either user-specified text or the specific name of the tool whose result is required by this node"} ]}], "links": [{"source": "tool name i", "target": "tool name j"}]}""" if check: prompt += """, "check_by_teacher": "This field is filled by your strict and well-trained teacher, minor mistakes are complete intolerable to him. He evaluated whether your synthesized user request, tool invoking graph are valid and whether they are aligned with the given tool graph (strictly checked step by step according to the above requirements). Some comments from him place here (start with 'Let me check your result step by step, and evaluate the 'Executable' and 'Correct' of the tool invoking graph (Executable means that the tool invoking graph executed successfully, regardless of alignment with the given tool graph. While Correct implies that the tool invoking graph are not only 'Executable' but also strictly consistent (with strictly same nodes and same edges) with the given tool graph). After carefully evaluating, found some mistakes:' and end with a conclusion: 'Conclusion: Executable: no/yes, Correct: no/yes'.)""" prompt += "}:" final_prompt = sampled_tools_string + sampled_links_string + prompt if dependency_type == "temporal": final_prompt = final_prompt.replace("tool", "API") payload = json.dumps({ "model": f"{llm}", "messages": [ { "role": "user", "content": final_prompt } ], "temperature": temperature, "top_p": top_p, "frequency_penalty": 0, "presence_penalty": 0, "max_tokens": 2500, "stream": False, "stop": None }) try: async with aiohttp.ClientSession() as session: async with session.post(url, headers=headers, data=payload, timeout=120) as response: resp = await response.json() if response.status == 429: raise RateLimitError(f"{resp}") if response.status != 200: raise Exception(f"{resp}") content = resp["choices"][0]["message"]["content"] content = content.replace("\n", "") json_start = 0 json_end = len(content) if "```json" in content: json_start = content.find("```json") + 7 if "```" in content: json_end = content.rfind("```") content = content[json_start:json_end] logger.info(content) try: content = json.loads(content) except json.JSONDecodeError as e: raise ContentFormatError(f"{content}") if dependency_type == "resource": sampled_nodes = [{"id": tool, "input-type": tools[tool]["input-type"], "output-type": tools[tool]["output-type"]} for tool in tool_list] else: sampled_nodes = [{"id": tool, "parameters": tools[tool]["parameters"]} for tool in tool_list] sampled_links = [{"source": edge[0], "target": edge[1]} for edge in tool_edge] sampled_nodes = sorted(sampled_nodes, key=lambda x: x["id"]) sampled_links = sorted(sampled_links, key=lambda x: (x["source"], x["target"])) content["invoking_graph"]["nodes"] = sorted(content["invoking_graph"]["nodes"], key=lambda x: x["id"]) content["invoking_graph"]["links"] = sorted(content["invoking_graph"]["links"], key=lambda x: (x["source"], x["target"])) result = {"id": sample_id, "seed": seed, "method": method, "number_of_tools": tool_number, "sampled_nodes": sampled_nodes, "sampled_links": sampled_links, "result": content} if wf: wf.write(json.dumps(result) + "\n") if figure_dir: plt.figure() pos = nx.circular_layout(sub_G) nx.draw_networkx_nodes(sub_G, pos, node_color="skyblue", node_size=300) nx.draw_networkx_edges(sub_G, pos, arrows=True) nx.draw_networkx_labels(sub_G, pos, font_size=8) plt.tight_layout() plt.savefig(f"{figure_dir}/{sample_id}.jpg") plt.close() sampled_nodes_ids = [node["id"] for node in sampled_nodes] generated_nodes_ids = [node["id"] for node in content["invoking_graph"]["nodes"]] end_time = datetime.now() logger.info(f"Sample {sample_id} finished, time cost: {end_time - start_time}") if sampled_links == content["invoking_graph"]["links"] and sampled_nodes_ids == generated_nodes_ids: logger.info("Check success: invoking graph and sampled graph are aligned.") elif sampled_nodes_ids != generated_nodes_ids: logger.info("Check fail: mismatched nodes") logger.info("Sampled node:\n" + json.dumps(sampled_nodes_ids, indent=2)) logger.info("Generated node:\n" + json.dumps(generated_nodes_ids, indent=2)) logger.info(f"Sample {sample_id}:\n{json.dumps(result, indent=2)}") else: logger.info("Check fail: mismatched links") logger.info("Sampled link:\n" + json.dumps(sampled_links, indent=2)) logger.info("Generated link:\n" + json.dumps(content["invoking_graph"]["links"], indent=2)) logger.info(f"Sample {sample_id}:\n{json.dumps(result, indent=2)}") except Exception as e: logger.info(f"Failed: {type(e)}") print(traceback.format_exc()) raise e return result
null
154,612
import json import click import traceback def formulate_sample(data, dependency_type): def formulate(data_dir, dependency_type): rf = open(f"{data_dir}/data_raw.json", "r") wf_format = open(f"{data_dir}/data.json", "w") wf_error = open(f"{data_dir}/data_error.json", "w") wf_ur = open(f"{data_dir}/user_requests.json", "w") all = 0 format = 0 for line in rf: all += 1 data = json.loads(line) method = data["method"] n_tools = data["number_of_tools"] seed = data["seed"] _id = data["id"] sampled_nodes = data["sampled_nodes"] sampled_links = data["sampled_links"] for sampled_node in sampled_nodes: sampled_node["task"] = sampled_node["id"] sampled_node.pop("id") if dependency_type == "resource": sampled_node["task"] = sampled_node["task"].replace("_", " ") if "input" in sampled_node: sampled_node["input-type"] = sampled_node["input"] sampled_node.pop("input") sampled_node["output-type"] = sampled_node["output"] sampled_node.pop("output") else: sampled_node["arguments"] = sampled_node["parameters"] sampled_node.pop("parameters") user_request, task_steps, links, nodes, check_by_teacher = formulate_sample(data, dependency_type) if user_request is None: wf_error.write(line) continue format += 1 result = { "id": _id, "seed": seed, "type": method, "n_tools": n_tools, "sampled_nodes": sampled_nodes, "sampled_links": sampled_links, "user_request": user_request, "task_steps": task_steps, "task_nodes": nodes, "task_links": links, "check_by_teacher": check_by_teacher, } wf_format.write(json.dumps(result)+"\n") ur_result = { "id": _id, "user_request": user_request, } wf_ur.write(json.dumps(ur_result)+"\n") wf_format.close() wf_error.close() wf_ur.close() rf.close() print(f"Format {format} out of {all}")
null
154,613
import traceback import numpy as np from scipy.optimize import linear_sum_assignment import json import click from datasets import load_metric import Levenshtein from sklearn.metrics import precision_recall_fscore_support as prfs import warnings import logging import os import itertools def compute_assignment_matrix(graph_1, graph_2): cost_matrix = create_cost_matrix(graph_1, graph_2) row_ind, col_ind = linear_sum_assignment(cost_matrix) return row_ind, col_ind, cost_matrix[row_ind, col_ind].sum() def matching(graph_1, graph_2): indices_1, indices_2, total_cost = compute_assignment_matrix(graph_1, graph_2) return indices_1, indices_2
null
154,614
import traceback import numpy as np from scipy.optimize import linear_sum_assignment import json import click from datasets import load_metric import Levenshtein from sklearn.metrics import precision_recall_fscore_support as prfs import warnings import logging import os import itertools logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.handlers = [] def ratio_levenshtein(x, y): def flatten(gt, pred, types = None): def print_results(per_type, micro, macro, types, result_dict = None): def get_content_type(content): def evaluate(data_dir, prediction_dir, llm, split, n_tool, metric, tool_desc, tool_map, tool_output_type_map, tool_map_reverse, all_metric_dict, dependency_type, alignment = None): if f"{split}_{n_tool}" in all_metric_dict: metric_dict = all_metric_dict[f"{split}_{n_tool}"] else: metric_dict = {} all_metric_dict[f"{split}_{n_tool}"] = metric_dict label_rf = open(f"{data_dir}/data.json", "r") alignment_ids = None if alignment is not None: if alignment == "human": label_rf = open(f"{data_dir}/data.json", "r") logger.info(f"Alignment Mode: {alignment} ({len(label_rf.readlines())})") else: alignment_file = open(f"{data_dir}/alignment_ids.json", "r") alignment_ids = json.load(alignment_file) alignment_ids = list(itertools.chain(*alignment_ids[f"{alignment}_alignment_id"].values())) logger.info(f"Alignment Mode: {alignment} ({len(alignment_ids)})") predcition_rf = open(f"{data_dir}/{prediction_dir}/{llm}.json", "r") predcitions = {} labels = {} label_rf = open(f"{data_dir}/data.json", "r") for line in label_rf: data = json.loads(line) real_tool_num = len(data["task_nodes"]) if alignment_ids is None or data["id"] in alignment_ids: if split == "overall" or data["type"] == split: if n_tool == "overall" or str(real_tool_num) == n_tool: id = data["id"] labels[id] = data for line in predcition_rf: try: data = json.loads(line) except Exception as e: print(e) print(line) exit() id = data["id"] predcitions[id] = data ids = set(labels.keys()).intersection(set(predcitions.keys())) labels = {id: labels[id] for id in ids} predcitions = {id: predcitions[id] for id in ids} predcition_task_steps = [] label_task_steps = [] predcition_names = [] label_names = [] label_graphs = [] predcition_graphs = [] label_links = [] predcition_links = [] label_task_arg_names = [] predcition_task_arg_names = [] label_task_arg_name_values = [] predcition_task_arg_name_values = [] for id in ids: try: label = labels[id] predcition = predcitions[id] if "rouge" in metric or "bertscore" in metric: predcition_task_step = predcition["result"]["task_steps"] label_task_step = label["task_steps"] try: if isinstance(predcition_task_step[0], str): predcition_task_steps.append("\n".join(predcition_task_step)) else: if "task" in predcition_task_step[0]: predcition_task_steps.append("\n".join([step["task"] for step in predcition_task_step])) elif "step" in predcition_task_step[0]: predcition_task_steps.append("\n".join([step["step"] for step in predcition_task_step])) elif "id" in predcition_task_step[0]: predcition_task_steps.append("\n".join([step["id"] for step in predcition_task_step])) elif "step_name" in predcition_task_step[0]: predcition_task_steps.append("\n".join([step["step_name"] for step in predcition_task_step])) else: predcition_task_steps.append("\n".join([step["description"] for step in predcition_task_step])) except Exception as e: predcition_task_steps.append(str(predcition_task_step)) label_task_steps.append("\n".join(label_task_step)) label_nodes = label["task_nodes"] predcition_nodes = predcition["result"]["task_nodes"] label_node_name = [node["task"] for node in label_nodes] predcition_node_name = [node["task"] for node in predcition_nodes] label_task_arg_name = [] predcition_task_arg_name = [] label_task_arg_name_value = [] predcition_task_arg_name_value = [] if dependency_type == "resource": predcition_node_name = [name.replace("_", " ") for name in predcition_node_name] label_node_name = [name.replace("_", " ") for name in label_node_name] label_link = [] predcition_link = [] for inx, node in enumerate(label_nodes): new_arguments = [] for i, argument in enumerate(node["arguments"]): try: if isinstance(argument, dict): argument = list(argument.values())[0] if isinstance(argument, list): argument = " ".join(argument) if "<node-" in argument: index_start = argument.index("<node-") + 6 index_end = argument.index(">") if int(argument[index_start: index_end]) == inx: continue argument_tool_name = label_node_name[int(argument[index_start: index_end])] label_link.append({"source": argument_tool_name, "target": node["task"]}) new_argument = {"name": tool_output_type_map.get(argument_tool_name, "other"), "value": argument_tool_name} else: new_argument = {"name": get_content_type(argument), "value": argument} except Exception as e: pass new_arguments.append(new_argument) node["arguments"] = new_arguments for inx, node in enumerate(predcition_nodes): new_arguments = [] for i, argument in enumerate(node.get("arguments", [])): try: if isinstance(argument, dict): argument = list(argument.values())[0] if isinstance(argument, list): argument = " ".join(argument) if isinstance(argument, str) and "<node-" in argument: index_start = argument.index("<node-") + 6 index_end = argument.index(">") if int(argument[index_start: index_end]) == inx: continue prediction_tool_name = predcition_node_name[int(argument[index_start: index_end])] predcition_link.append({"source": prediction_tool_name, "target": node["task"]}) new_argument = {"name": tool_output_type_map.get(prediction_tool_name, "other"), "value": prediction_tool_name} else: new_argument = {"name": get_content_type(argument), "value": argument} except Exception as e: pass new_arguments.append(new_argument) node["arguments"] = new_arguments else: predcition_link = predcition["result"]["task_links"] label_link = label["task_links"] predcition_node_argument = [node.get("arguments", []) for node in predcition_nodes] label_node_argument = [node["arguments"] for node in label_nodes] for task, arguments in zip (predcition_node_name, predcition_node_argument): for argument in arguments: label_task_arg_name.append(f"{task}-{argument['name']}") label_task_arg_name_value.append(f"{task}-{argument['name']}-{argument['value']}") for task, arguments in zip (label_node_name, label_node_argument): for argument in arguments: predcition_task_arg_name.append(f"{task}-{argument['name']}") predcition_task_arg_name_value.append(f"{task}-{argument['name']}-{argument['value']}") label_graph = { "nodes": label_node_name, "links": label_link, "arguments": label_node_argument } predcition_graph = { "nodes": predcition_node_name, "links": predcition_link, "arguments": predcition_node_argument } label_graphs.append(label_graph) predcition_graphs.append(predcition_graph) for node_name in predcition_node_name: assert isinstance(node_name, str), node_name predcition_names.append(predcition_node_name) label_names.append(label_node_name) predcition_task_arg_names.append(predcition_task_arg_name) label_task_arg_names.append(label_task_arg_name) predcition_task_arg_name_values.append(predcition_task_arg_name_value) label_task_arg_name_values.append(label_task_arg_name_value) label_links.append(label_link) predcition_links.append(predcition_link) except Exception as e: logger.info(f"Parsing Error: {e}, Ignore #id {id}") logger.info(traceback.format_exc()) logger.info(f"Step Supports: {len(label_task_steps)} / {len(ids)}") logger.info(f"Node Support: {len(label_names)} / {len(ids)}") logger.info(f"Link Support: {len(label_links)} / {len(ids)}") logger.info(f"Argument Support: {len(label_graphs)} / {len(ids)}") metric_dict["all_samples"] = len(ids) metric_dict["step_supports"] = len(label_task_steps) metric_dict["node_supports"] = len(label_names) metric_dict["link_supports"] = len(label_links) metric_dict["argument_supports"] = len(label_graphs) if len(label_graphs) == 0 or len(label_names) == 0 or len(label_links) == 0: logger.info("No supports, skip") return if "rouge" in metric: rouge = load_metric("rouge") rouge_scores = rouge.compute(predictions=predcition_task_steps, references=label_task_steps, use_aggregator=True) for key in rouge_scores: logger.info(f"Step {key}: {rouge_scores[key].mid.fmeasure}") metric_dict[f"step_{key}"] = rouge_scores[key].mid.fmeasure if "bertscore" in metric: bertscore = load_metric("bertscore") bertscore_scores = bertscore.compute(predictions=predcition_task_steps, references=label_task_steps, model_type="roberta-large") for key in bertscore_scores: if key in ["precision", "recall", "f1"]: bertscore_scores[key] = np.mean(bertscore_scores[key]) logger.info(f"Step BERTScore {key}: {bertscore_scores[key]}") metric_dict[f"step_bertscore_{key}"] = bertscore_scores[key] if "f1" in metric or "argument" in metric: types = list(range(1, len(tool_desc["nodes"])+1)) types_name = [tool_map_reverse[i] for i in types] gt_flat, pred_flat = flatten(label_names, predcition_names, types = types_name) per_type = prfs(gt_flat, pred_flat, labels=types, average=None) micro = prfs(gt_flat, pred_flat, labels=types, average='micro')[:-1] macro = prfs(gt_flat, pred_flat, labels=types, average='macro')[:-1] total_support = sum(per_type[-1]) logger.info(f"Node Micro Precision [ No Matching ]: {micro[0]}") logger.info(f"Node Micro Recall [ No Matching ]: {micro[1]}") logger.info(f"Node Micro F1 [ No Matching ]: {micro[2]}") logger.info(f"Node Macro Precision [ No Matching ]: {macro[0]}") logger.info(f"Node Macro Recall [ No Matching ]: {macro[1]}") logger.info(f"Node Macro F1 [ No Matching ]: {macro[2]}") logger.info("Node Detailed Report [ No Matching ]: ") metric_dict["node_micro_precision_no_matching"] = micro[0] metric_dict["node_micro_recall_no_matching"] = micro[1] metric_dict["node_micro_f1_no_matching"] = micro[2] metric_dict["node_macro_precision_no_matching"] = macro[0] metric_dict["node_macro_recall_no_matching"] = macro[1] metric_dict["node_macro_f1_no_matching"] = macro[2] per_type_metric = {} metric_dict["node_per_type_no_matchcing"] = per_type_metric print_results(per_type, list(micro) + [total_support], list(macro) + [total_support], types_name, result_dict = per_type_metric) gt_flat, pred_flat = flatten(label_task_arg_names, predcition_task_arg_names) micro = prfs(gt_flat, pred_flat, average="binary")[:-1] logger.info(f"Argument Task-ArgName Binary F1: [ No Matching ]: {micro[-1]}") metric_dict["argument_task_argname_binary_f1_no_matching"] = micro[-1] gt_flat, pred_flat = flatten(label_task_arg_name_values, predcition_task_arg_name_values) micro = prfs(gt_flat, pred_flat, average="binary")[:-1] logger.info(f"Argument Task-ArgName-Value Binary F1 [ No Matching ]: {micro[-1]}") metric_dict["argument_task_argname_value_binary_f1_no_matching"] = micro[-1] if "ed" in metric: labels = [] predcitions = [] for label_name, predcition_name in zip(label_names, predcition_names): labels.append([tool_map.get(name, 0) for name in label_name]) predcitions.append([tool_map.get(name, 0) for name in predcition_name]) ed = ratio_levenshtein(predcitions, labels) logger.info(f"Edit Distance: {1-ed}") metric_dict["edit_distance"] = 1-ed if "link" in metric: tuple_label_links = [] tuple_predcition_links = [] for label_link, predcition_link in zip(label_links, predcition_links): tuple_label_links.append([(link["source"], link["target"]) for link in label_link]) tuple_predcition_links.append([(link["source"], link["target"]) for link in predcition_link]) gt_flat, pred_flat = flatten(tuple_label_links, tuple_predcition_links) micro = prfs(gt_flat, pred_flat, average="binary")[:-1] logger.info(f"Link Binary F1: {micro[-1]}") metric_dict["link_binary_f1"] = micro[-1]
null
154,615
import json import click def generate_graph_resource(tool_file): with open(tool_file) as f: data = json.load(f) data = data["nodes"] assert "input-type" in data[0] and "output-type" in data[0], "Input and output types are not defined" nodes = [] for i in range(len(data)): nodes.append({"id": data[i]["id"], "desc": data[i]["desc"], "input-type": data[i]["input-type"], "output-type": data[i]["output-type"]}) links = [] for i in range(len(nodes)): for j in range(len(nodes)): if i != j: if len(set(nodes[i]["output-type"]).intersection(set(nodes[j]["input-type"]))) > 0: links.append({"source": nodes[i]["id"], "target": nodes[j]["id"], "type": list(set(nodes[i]["output-type"]).intersection(set(nodes[j]["input-type"])))[0]}) graph = {"nodes": nodes, "links": links} with open(tool_file.replace("tools", "graph"), 'w') as f: json.dump(graph, f, indent=2) def generate_graph_temporal(tool_file): with open(tool_file) as f: data = json.load(f) nodes = [] data = data["nodes"] if "parameters" not in data[0] and "input-type" not in data[0]: for i in range(len(data)): nodes.append({"id": data[i]["id"], "desc": data[i]["desc"]}) elif "input-type" not in data[0]: for i in range(len(data)): nodes.append({"id": data[i]["id"], "desc": data[i]["desc"], "parameters": data[i]["parameters"]}) else: for i in range(len(data)): nodes.append({"id": data[i]["id"], "desc": data[i]["desc"], "parameters": data[i]["parameters"], "input-type": data[i]["input-type"], "output-type": data[i]["output-type"]}) links = [] for i in range(len(nodes)): for j in range(len(nodes)): if i != j: links.append({"source": nodes[i]["id"], "target": nodes[j]["id"], "type": "complete"}) graph = {"nodes": nodes, "links": links} with open(tool_file.replace("tools", "graph"), 'w') as f: json.dump(graph, f, indent=2) def generate_graph(tool_desc, data_dir, dependency_type): if tool_desc: tool_file = tool_desc else: tool_file = f"{data_dir}/graph_desc.json" if dependency_type == "temporal": generate_graph_temporal(tool_file) elif dependency_type == "resource": generate_graph_resource(tool_file) else: print("Type not supported")
null
154,616
import argparse import os from typing import List, Dict from openai.types.chat import ChatCompletionMessageParam import openai import chromadb def build_prompt(query: str, context: List[str]) -> List[ChatCompletionMessageParam]: """ Builds a prompt for the LLM. # This function builds a prompt for the LLM. It takes the original query, and the returned context, and asks the model to answer the question based only on what's in the context, not what's in its weights. More information: https://platform.openai.com/docs/guides/chat/introduction Args: query (str): The original query. context (List[str]): The context of the query, returned by embedding search. Returns: A prompt for the LLM (List[ChatCompletionMessageParam]). """ system: ChatCompletionMessageParam = { "role": "system", "content": "I am going to ask you a question, which I would like you to answer" "based only on the provided context, and not any other information." "If there is not enough information in the context to answer the question," 'say "I am not sure", then try to make a guess.' "Break your answer up into nicely readable paragraphs.", } user: ChatCompletionMessageParam = { "role": "user", "content": f"The question is {query}. Here is all the context you have:" f'{(" ").join(context)}', } return [system, user] The provided code snippet includes necessary dependencies for implementing the `get_chatGPT_response` function. Write a Python function `def get_chatGPT_response(query: str, context: List[str], model_name: str) -> str` to solve the following problem: Queries the GPT API to get a response to the question. Args: query (str): The original query. context (List[str]): The context of the query, returned by embedding search. Returns: A response to the question. Here is the function: def get_chatGPT_response(query: str, context: List[str], model_name: str) -> str: """ Queries the GPT API to get a response to the question. Args: query (str): The original query. context (List[str]): The context of the query, returned by embedding search. Returns: A response to the question. """ response = openai.chat.completions.create( model=model_name, messages=build_prompt(query, context), ) return response.choices[0].message.content # type: ignore
Queries the GPT API to get a response to the question. Args: query (str): The original query. context (List[str]): The context of the query, returned by embedding search. Returns: A response to the question.
154,617
import argparse import os from typing import List import google.generativeai as genai import chromadb from chromadb.utils import embedding_functions model = genai.GenerativeModel("gemini-pro") def build_prompt(query: str, context: List[str]) -> str: """ Builds a prompt for the LLM. # This function builds a prompt for the LLM. It takes the original query, and the returned context, and asks the model to answer the question based only on what's in the context, not what's in its weights. Args: query (str): The original query. context (List[str]): The context of the query, returned by embedding search. Returns: A prompt for the LLM (str). """ base_prompt = { "content": "I am going to ask you a question, which I would like you to answer" " based only on the provided context, and not any other information." " If there is not enough information in the context to answer the question," ' say "I am not sure", then try to make a guess.' " Break your answer up into nicely readable paragraphs.", } user_prompt = { "content": f" The question is '{query}'. Here is all the context you have:" f'{(" ").join(context)}', } # combine the prompts to output a single prompt string system = f"{base_prompt['content']} {user_prompt['content']}" return system The provided code snippet includes necessary dependencies for implementing the `get_gemini_response` function. Write a Python function `def get_gemini_response(query: str, context: List[str]) -> str` to solve the following problem: Queries the Gemini API to get a response to the question. Args: query (str): The original query. context (List[str]): The context of the query, returned by embedding search. Returns: A response to the question. Here is the function: def get_gemini_response(query: str, context: List[str]) -> str: """ Queries the Gemini API to get a response to the question. Args: query (str): The original query. context (List[str]): The context of the query, returned by embedding search. Returns: A response to the question. """ response = model.generate_content(build_prompt(query, context)) return response.text
Queries the Gemini API to get a response to the question. Args: query (str): The original query. context (List[str]): The context of the query, returned by embedding search. Returns: A response to the question.
154,618
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry OneOrMany = Union[T, List[T]] URI = str URIs = List[URI] def maybe_cast_one_to_many_uri(target: OneOrMany[URI]) -> URIs: if isinstance(target, str): # One URI return cast(URIs, [target]) # Already a sequence return cast(URIs, target)
null
154,619
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry OneOrMany = Union[T, List[T]] ID = str IDs = List[ID] def maybe_cast_one_to_many_ids(target: OneOrMany[ID]) -> IDs: if isinstance(target, str): # One ID return cast(IDs, [target]) # Already a sequence return cast(IDs, target)
null
154,620
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry OneOrMany = Union[T, List[T]] Embedding = Vector Embeddings = List[Embedding] def maybe_cast_one_to_many_embedding(target: OneOrMany[Embedding]) -> Embeddings: if isinstance(target, List): # One Embedding if isinstance(target[0], (int, float)): return cast(Embeddings, [target]) # Already a sequence return cast(Embeddings, target)
null
154,621
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry OneOrMany = Union[T, List[T]] Metadatas = List[Metadata] Metadata = Mapping[str, Union[str, int, float, bool]] def maybe_cast_one_to_many_metadata(target: OneOrMany[Metadata]) -> Metadatas: # One Metadata dict if isinstance(target, dict): return cast(Metadatas, [target]) # Already a sequence return cast(Metadatas, target)
null
154,622
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry OneOrMany = Union[T, List[T]] Document = str Documents = List[Document] def is_document(target: Any) -> bool: if not isinstance(target, str): return False return True def maybe_cast_one_to_many_document(target: OneOrMany[Document]) -> Documents: # One Document if is_document(target): return cast(Documents, [target]) # Already a sequence return cast(Documents, target)
null
154,623
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry OneOrMany = Union[T, List[T]] Image = NDArray[ImageDType] Images = List[Image] def is_image(target: Any) -> bool: if not isinstance(target, np.ndarray): return False if len(target.shape) < 2: return False return True def maybe_cast_one_to_many_image(target: OneOrMany[Image]) -> Images: if is_image(target): return cast(Images, [target]) # Already a sequence return cast(Images, target)
null
154,624
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry Embeddable = Union[Documents, Images] class EmbeddingFunction(Protocol[D]): def __call__(self, input: D) -> Embeddings: ... def __init_subclass__(cls) -> None: super().__init_subclass__() # Raise an exception if __call__ is not defined since it is expected to be defined call = getattr(cls, "__call__") def __call__(self: EmbeddingFunction[D], input: D) -> Embeddings: result = call(self, input) return validate_embeddings(maybe_cast_one_to_many_embedding(result)) setattr(cls, "__call__", __call__) def embed_with_retries(self, input: D, **retry_kwargs: Dict) -> Embeddings: return retry(**retry_kwargs)(self.__call__)(input) def validate_embedding_function( embedding_function: EmbeddingFunction[Embeddable], ) -> None: function_signature = signature( embedding_function.__class__.__call__ ).parameters.keys() protocol_signature = signature(EmbeddingFunction.__call__).parameters.keys() if not function_signature == protocol_signature: raise ValueError( f"Expected EmbeddingFunction.__call__ to have the following signature: {protocol_signature}, got {function_signature}\n" "Please see https://docs.trychroma.com/embeddings for details of the EmbeddingFunction interface.\n" "Please note the recent change to the EmbeddingFunction interface: https://docs.trychroma.com/migration#migration-to-0416---november-7-2023 \n" )
null
154,625
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry IDs = List[ID] The provided code snippet includes necessary dependencies for implementing the `validate_ids` function. Write a Python function `def validate_ids(ids: IDs) -> IDs` to solve the following problem: Validates ids to ensure it is a list of strings Here is the function: def validate_ids(ids: IDs) -> IDs: """Validates ids to ensure it is a list of strings""" if not isinstance(ids, list): raise ValueError(f"Expected IDs to be a list, got {type(ids).__name__} as IDs") if len(ids) == 0: raise ValueError(f"Expected IDs to be a non-empty list, got {len(ids)} IDs") seen = set() dups = set() for id_ in ids: if not isinstance(id_, str): raise ValueError(f"Expected ID to be a str, got {id_}") if id_ in seen: dups.add(id_) else: seen.add(id_) if dups: n_dups = len(dups) if n_dups < 10: example_string = ", ".join(dups) message = ( f"Expected IDs to be unique, found duplicates of: {example_string}" ) else: examples = [] for idx, dup in enumerate(dups): examples.append(dup) if idx == 10: break example_string = ( f"{', '.join(examples[:5])}, ..., {', '.join(examples[-5:])}" ) message = f"Expected IDs to be unique, found {n_dups} duplicated IDs: {example_string}" raise errors.DuplicateIDError(message) return ids
Validates ids to ensure it is a list of strings
154,626
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry UpdateMetadata = Mapping[str, Union[int, float, str, bool, None]] The provided code snippet includes necessary dependencies for implementing the `validate_update_metadata` function. Write a Python function `def validate_update_metadata(metadata: UpdateMetadata) -> UpdateMetadata` to solve the following problem: Validates metadata to ensure it is a dictionary of strings to strings, ints, floats or bools Here is the function: def validate_update_metadata(metadata: UpdateMetadata) -> UpdateMetadata: """Validates metadata to ensure it is a dictionary of strings to strings, ints, floats or bools""" if not isinstance(metadata, dict) and metadata is not None: raise ValueError( f"Expected metadata to be a dict or None, got {type(metadata)}" ) if metadata is None: return metadata if len(metadata) == 0: raise ValueError(f"Expected metadata to be a non-empty dict, got {metadata}") for key, value in metadata.items(): if not isinstance(key, str): raise ValueError(f"Expected metadata key to be a str, got {key}") # isinstance(True, int) evaluates to True, so we need to check for bools separately if not isinstance(value, bool) and not isinstance( value, (str, int, float, type(None)) ): raise ValueError( f"Expected metadata value to be a str, int, or float, got {value}" ) return metadata
Validates metadata to ensure it is a dictionary of strings to strings, ints, floats or bools
154,627
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry Metadatas = List[Metadata] def validate_metadata(metadata: Metadata) -> Metadata: """Validates metadata to ensure it is a dictionary of strings to strings, ints, floats or bools""" if not isinstance(metadata, dict) and metadata is not None: raise ValueError( f"Expected metadata to be a dict or None, got {type(metadata).__name__} as metadata" ) if metadata is None: return metadata if len(metadata) == 0: raise ValueError( f"Expected metadata to be a non-empty dict, got {len(metadata)} metadata attributes" ) for key, value in metadata.items(): if key == META_KEY_CHROMA_DOCUMENT: raise ValueError( f"Expected metadata to not contain the reserved key {META_KEY_CHROMA_DOCUMENT}" ) if not isinstance(key, str): raise TypeError( f"Expected metadata key to be a str, got {key} which is a {type(key).__name__}" ) # isinstance(True, int) evaluates to True, so we need to check for bools separately if not isinstance(value, bool) and not isinstance(value, (str, int, float)): raise ValueError( f"Expected metadata value to be a str, int, float or bool, got {value} which is a {type(value).__name__}" ) return metadata The provided code snippet includes necessary dependencies for implementing the `validate_metadatas` function. Write a Python function `def validate_metadatas(metadatas: Metadatas) -> Metadatas` to solve the following problem: Validates metadatas to ensure it is a list of dictionaries of strings to strings, ints, floats or bools Here is the function: def validate_metadatas(metadatas: Metadatas) -> Metadatas: """Validates metadatas to ensure it is a list of dictionaries of strings to strings, ints, floats or bools""" if not isinstance(metadatas, list): raise ValueError(f"Expected metadatas to be a list, got {metadatas}") for metadata in metadatas: validate_metadata(metadata) return metadatas
Validates metadatas to ensure it is a list of dictionaries of strings to strings, ints, floats or bools
154,628
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry Where = Where Where = Dict[ Union[str, LogicalOperator], Union[LiteralValue, OperatorExpression, List["Where"]] ] The provided code snippet includes necessary dependencies for implementing the `validate_where` function. Write a Python function `def validate_where(where: Where) -> Where` to solve the following problem: Validates where to ensure it is a dictionary of strings to strings, ints, floats or operator expressions, or in the case of $and and $or, a list of where expressions Here is the function: def validate_where(where: Where) -> Where: """ Validates where to ensure it is a dictionary of strings to strings, ints, floats or operator expressions, or in the case of $and and $or, a list of where expressions """ if not isinstance(where, dict): raise ValueError(f"Expected where to be a dict, got {where}") if len(where) != 1: raise ValueError(f"Expected where to have exactly one operator, got {where}") for key, value in where.items(): if not isinstance(key, str): raise ValueError(f"Expected where key to be a str, got {key}") if ( key != "$and" and key != "$or" and key != "$in" and key != "$nin" and not isinstance(value, (str, int, float, dict)) ): raise ValueError( f"Expected where value to be a str, int, float, or operator expression, got {value}" ) if key == "$and" or key == "$or": if not isinstance(value, list): raise ValueError( f"Expected where value for $and or $or to be a list of where expressions, got {value}" ) if len(value) <= 1: raise ValueError( f"Expected where value for $and or $or to be a list with at least two where expressions, got {value}" ) for where_expression in value: validate_where(where_expression) # Value is a operator expression if isinstance(value, dict): # Ensure there is only one operator if len(value) != 1: raise ValueError( f"Expected operator expression to have exactly one operator, got {value}" ) for operator, operand in value.items(): # Only numbers can be compared with gt, gte, lt, lte if operator in ["$gt", "$gte", "$lt", "$lte"]: if not isinstance(operand, (int, float)): raise ValueError( f"Expected operand value to be an int or a float for operator {operator}, got {operand}" ) if operator in ["$in", "$nin"]: if not isinstance(operand, list): raise ValueError( f"Expected operand value to be an list for operator {operator}, got {operand}" ) if operator not in [ "$gt", "$gte", "$lt", "$lte", "$ne", "$eq", "$in", "$nin", ]: raise ValueError( f"Expected where operator to be one of $gt, $gte, $lt, $lte, $ne, $eq, $in, $nin, " f"got {operator}" ) if not isinstance(operand, (str, int, float, list)): raise ValueError( f"Expected where operand value to be a str, int, float, or list of those type, got {operand}" ) if isinstance(operand, list) and ( len(operand) == 0 or not all(isinstance(x, type(operand[0])) for x in operand) ): raise ValueError( f"Expected where operand value to be a non-empty list, and all values to obe of the same type " f"got {operand}" ) return where
Validates where to ensure it is a dictionary of strings to strings, ints, floats or operator expressions, or in the case of $and and $or, a list of where expressions
154,629
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry WhereDocument = Dict[WhereDocumentOperator, Union[str, List["WhereDocument"]]] The provided code snippet includes necessary dependencies for implementing the `validate_where_document` function. Write a Python function `def validate_where_document(where_document: WhereDocument) -> WhereDocument` to solve the following problem: Validates where_document to ensure it is a dictionary of WhereDocumentOperator to strings, or in the case of $and and $or, a list of where_document expressions Here is the function: def validate_where_document(where_document: WhereDocument) -> WhereDocument: """ Validates where_document to ensure it is a dictionary of WhereDocumentOperator to strings, or in the case of $and and $or, a list of where_document expressions """ if not isinstance(where_document, dict): raise ValueError( f"Expected where document to be a dictionary, got {where_document}" ) if len(where_document) != 1: raise ValueError( f"Expected where document to have exactly one operator, got {where_document}" ) for operator, operand in where_document.items(): if operator not in ["$contains", "$not_contains", "$and", "$or"]: raise ValueError( f"Expected where document operator to be one of $contains, $and, $or, got {operator}" ) if operator == "$and" or operator == "$or": if not isinstance(operand, list): raise ValueError( f"Expected document value for $and or $or to be a list of where document expressions, got {operand}" ) if len(operand) <= 1: raise ValueError( f"Expected document value for $and or $or to be a list with at least two where document expressions, got {operand}" ) for where_document_expression in operand: validate_where_document(where_document_expression) # Value is a $contains operator elif not isinstance(operand, str): raise ValueError( f"Expected where document operand value for operator $contains to be a str, got {operand}" ) elif len(operand) == 0: raise ValueError( "Expected where document operand value for operator $contains to be a non-empty str" ) return where_document
Validates where_document to ensure it is a dictionary of WhereDocumentOperator to strings, or in the case of $and and $or, a list of where_document expressions
154,630
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry Include = List[ Union[ Literal["documents"], Literal["embeddings"], Literal["metadatas"], Literal["distances"], Literal["uris"], Literal["data"], ] ] The provided code snippet includes necessary dependencies for implementing the `validate_include` function. Write a Python function `def validate_include(include: Include, allow_distances: bool) -> Include` to solve the following problem: Validates include to ensure it is a list of strings. Since get does not allow distances, allow_distances is used to control if distances is allowed Here is the function: def validate_include(include: Include, allow_distances: bool) -> Include: """Validates include to ensure it is a list of strings. Since get does not allow distances, allow_distances is used to control if distances is allowed""" if not isinstance(include, list): raise ValueError(f"Expected include to be a list, got {include}") for item in include: if not isinstance(item, str): raise ValueError(f"Expected include item to be a str, got {item}") allowed_values = ["embeddings", "documents", "metadatas", "uris", "data"] if allow_distances: allowed_values.append("distances") if item not in allowed_values: raise ValueError( f"Expected include item to be one of {', '.join(allowed_values)}, got {item}" ) return include
Validates include to ensure it is a list of strings. Since get does not allow distances, allow_distances is used to control if distances is allowed
154,631
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry The provided code snippet includes necessary dependencies for implementing the `validate_n_results` function. Write a Python function `def validate_n_results(n_results: int) -> int` to solve the following problem: Validates n_results to ensure it is a positive Integer. Since hnswlib does not allow n_results to be negative. Here is the function: def validate_n_results(n_results: int) -> int: """Validates n_results to ensure it is a positive Integer. Since hnswlib does not allow n_results to be negative.""" # Check Number of requested results if not isinstance(n_results, int): raise ValueError( f"Expected requested number of results to be a int, got {n_results}" ) if n_results <= 0: raise TypeError( f"Number of requested results {n_results}, cannot be negative, or zero." ) return n_results
Validates n_results to ensure it is a positive Integer. Since hnswlib does not allow n_results to be negative.
154,632
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry Embeddings = List[Embedding] The provided code snippet includes necessary dependencies for implementing the `validate_embeddings` function. Write a Python function `def validate_embeddings(embeddings: Embeddings) -> Embeddings` to solve the following problem: Validates embeddings to ensure it is a list of list of ints, or floats Here is the function: def validate_embeddings(embeddings: Embeddings) -> Embeddings: """Validates embeddings to ensure it is a list of list of ints, or floats""" if not isinstance(embeddings, list): raise ValueError( f"Expected embeddings to be a list, got {type(embeddings).__name__}" ) if len(embeddings) == 0: raise ValueError( f"Expected embeddings to be a list with at least one item, got {len(embeddings)} embeddings" ) if not all([isinstance(e, list) for e in embeddings]): raise ValueError( "Expected each embedding in the embeddings to be a list, got " f"{list(set([type(e).__name__ for e in embeddings]))}" ) for i, embedding in enumerate(embeddings): if len(embedding) == 0: raise ValueError( f"Expected each embedding in the embeddings to be a non-empty list, got empty embedding at pos {i}" ) if not all( [ isinstance(value, (int, float)) and not isinstance(value, bool) for value in embedding ] ): raise ValueError( "Expected each value in the embedding to be a int or float, got an embedding with " f"{list(set([type(value).__name__ for value in embedding]))} - {embedding}" ) return embeddings
Validates embeddings to ensure it is a list of list of ints, or floats
154,633
from typing import Optional, Union, TypeVar, List, Dict, Any, Tuple, cast from numpy.typing import NDArray import numpy as np from typing_extensions import Literal, TypedDict, Protocol import chromadb.errors as errors from chromadb.types import ( Metadata, UpdateMetadata, Vector, LiteralValue, LogicalOperator, WhereOperator, OperatorExpression, Where, WhereDocumentOperator, WhereDocument, ) from inspect import signature from tenacity import retry URIs = List[URI] IDs = List[ID] Embeddings = List[Embedding] Metadatas = List[Metadata] Documents = List[Document] def validate_batch( batch: Tuple[ IDs, Optional[Embeddings], Optional[Metadatas], Optional[Documents], Optional[URIs], ], limits: Dict[str, Any], ) -> None: if len(batch[0]) > limits["max_batch_size"]: raise ValueError( f"Batch size {len(batch[0])} exceeds maximum batch size {limits['max_batch_size']}" )
null
154,634
import orjson as json import logging from typing import Optional, cast, Tuple from typing import Sequence from uuid import UUID import requests from overrides import override import chromadb.errors as errors from chromadb.types import Database, Tenant import chromadb.utils.embedding_functions as ef from chromadb.api import ServerAPI from chromadb.api.models.Collection import Collection from chromadb.api.types import ( DataLoader, Documents, Embeddable, Embeddings, EmbeddingFunction, IDs, Include, Loadable, Metadatas, URIs, Where, WhereDocument, GetResult, QueryResult, CollectionMetadata, validate_batch, ) from chromadb.auth import ( ClientAuthProvider, ) from chromadb.auth.providers import RequestsClientAuthProtocolAdapter from chromadb.auth.registry import resolve_provider from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System from chromadb.telemetry.opentelemetry import ( OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.telemetry.product import ProductTelemetryClient from urllib.parse import urlparse, urlunparse, quote The provided code snippet includes necessary dependencies for implementing the `raise_chroma_error` function. Write a Python function `def raise_chroma_error(resp: requests.Response) -> None` to solve the following problem: Raises an error if the response is not ok, using a ChromaError if possible Here is the function: def raise_chroma_error(resp: requests.Response) -> None: """Raises an error if the response is not ok, using a ChromaError if possible""" if resp.ok: return chroma_error = None try: body = json.loads(resp.text) if "error" in body: if body["error"] in errors.error_types: chroma_error = errors.error_types[body["error"]](body["message"]) except BaseException: pass if chroma_error: raise chroma_error try: resp.raise_for_status() except requests.HTTPError: raise (Exception(resp.text))
Raises an error if the response is not ok, using a ChromaError if possible
154,635
from chromadb.api import ServerAPI from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System from chromadb.db.system import SysDB from chromadb.quota import QuotaEnforcer, Resource from chromadb.rate_limiting import rate_limit from chromadb.segment import SegmentManager, MetadataReader, VectorReader from chromadb.telemetry.opentelemetry import ( add_attributes_to_current_span, OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.telemetry.product import ProductTelemetryClient from chromadb.ingest import Producer from chromadb.api.models.Collection import Collection from chromadb import __version__ from chromadb.errors import InvalidDimensionException, InvalidCollectionException import chromadb.utils.embedding_functions as ef from chromadb.api.types import ( URI, CollectionMetadata, Embeddable, Document, EmbeddingFunction, DataLoader, IDs, Embeddings, Embedding, Loadable, Metadatas, Documents, URIs, Where, WhereDocument, Include, GetResult, QueryResult, validate_metadata, validate_update_metadata, validate_where, validate_where_document, validate_batch, ) from chromadb.telemetry.product.events import ( CollectionAddEvent, CollectionDeleteEvent, CollectionGetEvent, CollectionUpdateEvent, CollectionQueryEvent, ClientCreateCollectionEvent, ) import chromadb.types as t from typing import Any, Optional, Sequence, Generator, List, cast, Set, Dict from overrides import override from uuid import UUID, uuid4 import time import logging import re def check_index_name(index_name: str) -> None: msg = ( "Expected collection name that " "(1) contains 3-63 characters, " "(2) starts and ends with an alphanumeric character, " "(3) otherwise contains only alphanumeric characters, underscores or hyphens (-), " "(4) contains no two consecutive periods (..) and " "(5) is not a valid IPv4 address, " f"got {index_name}" ) if len(index_name) < 3 or len(index_name) > 63: raise ValueError(msg) if not re.match("^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$", index_name): raise ValueError(msg) if ".." in index_name: raise ValueError(msg) if re.match("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$", index_name): raise ValueError(msg)
null
154,636
from chromadb.api import ServerAPI from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System from chromadb.db.system import SysDB from chromadb.quota import QuotaEnforcer, Resource from chromadb.rate_limiting import rate_limit from chromadb.segment import SegmentManager, MetadataReader, VectorReader from chromadb.telemetry.opentelemetry import ( add_attributes_to_current_span, OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.telemetry.product import ProductTelemetryClient from chromadb.ingest import Producer from chromadb.api.models.Collection import Collection from chromadb import __version__ from chromadb.errors import InvalidDimensionException, InvalidCollectionException import chromadb.utils.embedding_functions as ef from chromadb.api.types import ( URI, CollectionMetadata, Embeddable, Document, EmbeddingFunction, DataLoader, IDs, Embeddings, Embedding, Loadable, Metadatas, Documents, URIs, Where, WhereDocument, Include, GetResult, QueryResult, validate_metadata, validate_update_metadata, validate_where, validate_where_document, validate_batch, ) from chromadb.telemetry.product.events import ( CollectionAddEvent, CollectionDeleteEvent, CollectionGetEvent, CollectionUpdateEvent, CollectionQueryEvent, ClientCreateCollectionEvent, ) import chromadb.types as t from typing import Any, Optional, Sequence, Generator, List, cast, Set, Dict from overrides import override from uuid import UUID, uuid4 import time import logging import re URIs = List[URI] IDs = List[ID] Embeddings = List[Embedding] Metadatas = List[Metadata] Documents = List[Document] The provided code snippet includes necessary dependencies for implementing the `_records` function. Write a Python function `def _records( operation: t.Operation, ids: IDs, collection_id: UUID, embeddings: Optional[Embeddings] = None, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> Generator[t.SubmitEmbeddingRecord, None, None]` to solve the following problem: Convert parallel lists of embeddings, metadatas and documents to a sequence of SubmitEmbeddingRecords Here is the function: def _records( operation: t.Operation, ids: IDs, collection_id: UUID, embeddings: Optional[Embeddings] = None, metadatas: Optional[Metadatas] = None, documents: Optional[Documents] = None, uris: Optional[URIs] = None, ) -> Generator[t.SubmitEmbeddingRecord, None, None]: """Convert parallel lists of embeddings, metadatas and documents to a sequence of SubmitEmbeddingRecords""" # Presumes that callers were invoked via Collection model, which means # that we know that the embeddings, metadatas and documents have already been # normalized and are guaranteed to be consistently named lists. for i, id in enumerate(ids): metadata = None if metadatas: metadata = metadatas[i] if documents: document = documents[i] if metadata: metadata = {**metadata, "chroma:document": document} else: metadata = {"chroma:document": document} if uris: uri = uris[i] if metadata: metadata = {**metadata, "chroma:uri": uri} else: metadata = {"chroma:uri": uri} record = t.SubmitEmbeddingRecord( id=id, embedding=embeddings[i] if embeddings else None, encoding=t.ScalarEncoding.FLOAT32, # Hardcode for now metadata=metadata, operation=operation, collection_id=collection_id, ) yield record
Convert parallel lists of embeddings, metadatas and documents to a sequence of SubmitEmbeddingRecords
154,637
from chromadb.api import ServerAPI from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System from chromadb.db.system import SysDB from chromadb.quota import QuotaEnforcer, Resource from chromadb.rate_limiting import rate_limit from chromadb.segment import SegmentManager, MetadataReader, VectorReader from chromadb.telemetry.opentelemetry import ( add_attributes_to_current_span, OpenTelemetryClient, OpenTelemetryGranularity, trace_method, ) from chromadb.telemetry.product import ProductTelemetryClient from chromadb.ingest import Producer from chromadb.api.models.Collection import Collection from chromadb import __version__ from chromadb.errors import InvalidDimensionException, InvalidCollectionException import chromadb.utils.embedding_functions as ef from chromadb.api.types import ( URI, CollectionMetadata, Embeddable, Document, EmbeddingFunction, DataLoader, IDs, Embeddings, Embedding, Loadable, Metadatas, Documents, URIs, Where, WhereDocument, Include, GetResult, QueryResult, validate_metadata, validate_update_metadata, validate_where, validate_where_document, validate_batch, ) from chromadb.telemetry.product.events import ( CollectionAddEvent, CollectionDeleteEvent, CollectionGetEvent, CollectionUpdateEvent, CollectionQueryEvent, ClientCreateCollectionEvent, ) import chromadb.types as t from typing import Any, Optional, Sequence, Generator, List, cast, Set, Dict from overrides import override from uuid import UUID, uuid4 import time import logging import re The provided code snippet includes necessary dependencies for implementing the `_doc` function. Write a Python function `def _doc(metadata: Optional[t.Metadata]) -> Optional[str]` to solve the following problem: Retrieve the document (if any) from a Metadata map Here is the function: def _doc(metadata: Optional[t.Metadata]) -> Optional[str]: """Retrieve the document (if any) from a Metadata map""" if metadata and "chroma:document" in metadata: return str(metadata["chroma:document"]) return None
Retrieve the document (if any) from a Metadata map