### Install Volcengine SDK Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/index.md Instructions for installing the Volcengine SDK using pip. Requires Python 2.7 or higher. ```bash pip install volcengine ``` -------------------------------- ### Query Billing Information with Python SDK Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides an example of how to initialize the BillingService and retrieve a list of bills for a specific period. ```python from volcengine.billing.BillingService import BillingService billing_service = BillingService() billing_service.set_ak('your_access_key') billing_service.set_sk('your_secret_key') list_bill_body = {"BillPeriod": "2024-01", "Limit": 100, "Offset": 0} bill_resp = billing_service.list_bill(list_bill_body) print(f"账单列表: {bill_resp}") ``` -------------------------------- ### Manage Live Streaming Services with Python SDK Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides examples for managing live streaming infrastructure, including domain creation, authentication configuration, stream control (forbid/resume), and setting up transcoding and recording presets. ```python from volcengine.live.LiveService import LiveService from volcengine.const.Const import REGION_CN_NORTH1 live_service = LiveService(region=REGION_CN_NORTH1) live_service.set_ak('your_access_key') live_service.set_sk('your_secret_key') # Create and configure domain create_domain_body = {"Vhost": "live.example.com", "Domain": "push.live.example.com", "Type": "push"} create_resp = live_service.create_domain(create_domain_body) # Generate push/play URLs push_url_resp = live_service.generate_push_url({"Vhost": "live.example.com", "Domain": "push.live.example.com", "App": "live", "Stream": "test_stream", "ValidDuration": 3600}) # Stream control forbid_resp = live_service.forbid_stream({"Vhost": "live.example.com", "App": "live", "Stream": "test_stream", "EndTime": "2024-12-31T23:59:59Z"}) ``` -------------------------------- ### Search Logs in TLS using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides an example of searching logs within a specified time range and topic in Volcengine TLS using the Python SDK. It demonstrates setting search parameters like query string, start time, end time, and limit. ```python import time from volcengine.tls.models import SearchLogsRequest # Assuming tls_service and topic_id are already initialized search_req = SearchLogsRequest( topic_id=topic_id, query="level:ERROR", start_time=int(time.time() - 3600) * 1000, # 1小时前 end_time=int(time.time()) * 1000, limit=100 ) search_resp = tls_service.search_logs(search_req) print(f"搜索结果: {search_resp}") ``` -------------------------------- ### Install Volcengine SDK for Python Source: https://github.com/volcengine/volc-sdk-python/blob/main/README.md Installs or upgrades the Volcengine SDK for Python using pip. Ensure Python version is 3.7 or higher. ```bash pip install --user volcengine ``` ```bash pip install --upgrade volcengine ``` -------------------------------- ### Full Log Service Workflow: Create, Write, Consume, and Search Logs Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/tls/README.md This comprehensive Python example showcases the end-to-end workflow of the Log Service Python SDK. It covers initializing the client, creating a project, creating a topic, setting up an index, writing logs in batches using put_logs_v2, consuming logs with describe_cursor and consume_logs, and performing various search operations including full-text, key-value, and SQL analysis using search_logs_v2. ```python # coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from volcengine.tls.TLSService import TLSService from volcengine.tls.tls_requests import * if __name__ == "__main__": # Initialize the client, it is recommended to obtain Volcengine key and other identity authentication information dynamically through environment variables to avoid data security risks caused by AccessKey hardcoding. For detailed instructions, please refer to https://www.volcengine.com/docs/6470/1166455 # When using STS, ak and sk both use temporary keys, and set VOLCENGINE_TOKEN; when not using STS, pass an empty string for VOLCENGINE_TOKEN. endpoint = os.environ["VOLCENGINE_ENDPOINT"] region = os.environ["VOLCENGINE_REGION"] access_key_id = os.environ["VOLCENGINE_ACCESS_KEY_ID"] access_key_secret = os.environ["VOLCENGINE_ACCESS_KEY_SECRET"] # Instantiate the TLS client tls_service = TLSService(endpoint, access_key_id, access_key_secret, region) now = str(int(time.time())) # Create a log project create_project_request = CreateProjectRequest(project_name="project-name-" + now, region=region, description="project-description") create_project_response = tls_service.create_project(create_project_request) project_id = create_project_response.project_id # Create a log topic create_topic_request = CreateTopicRequest(topic_name="topic-name-" + now, project_id=project_id, ttl=3650, description="topic-description", shard_count=2) create_topic_response = tls_service.create_topic(create_topic_request) topic_id = create_topic_response.get_topic_id() # Create an index full_text = FullTextInfo(case_sensitive=False, delimiter=",-;", include_chinese=False) value_info_a = ValueInfo(value_type="text", delimiter="", case_sensitive=True, include_chinese=False, sql_flag=True) value_info_b = ValueInfo(value_type="long", delimiter="", case_sensitive=False, include_chinese=False, sql_flag=True) key_value_info_a = KeyValueInfo(key="key1", value=value_info_a) key_value_info_b = KeyValueInfo(key="key2", value=value_info_b) key_value = [key_value_info_a, key_value_info_b] create_index_request = CreateIndexRequest(topic_id, full_text, key_value) create_index_response = tls_service.create_index(create_index_request) # Write log data # It is recommended that you aggregate multiple logs at once and call the put_logs_v2 interface once to improve log upload throughput. logs = PutLogsV2Logs(source="192.168.1.1", filename="sys.log") for i in range(100): logs.add_log(contents={"key1": "value1-" + str(i + 1), "key2": "value2-" + str(i + 1)}, log_time=int(round(time.time()))) tls_service.put_logs_v2(PutLogsV2Request(topic_id, logs)) time.sleep(30) # Query consumption cursor describe_cursor_request = DescribeCursorRequest(topic_id, shard_id=0, from_time="begin") describe_cursor_response = tls_service.describe_cursor(describe_cursor_request) # Consume log data consume_logs_request = ConsumeLogsRequest(topic_id, shard_id=0, cursor=describe_cursor_response.cursor) consume_logs_response = tls_service.consume_logs(consume_logs_request) # When you need to retrieve and analyze logs, it is recommended that you use the search_logs_v2 method provided by the Python SDK. The following code provides a specific calling example. # Query log data (full-text search) search_logs_request = SearchLogsRequest(topic_id, query="error", limit=10, start_time=1346457600000, end_time=1630454400000) search_logs_response = tls_service.search_logs_v2(search_logs_request) # Query log data (key-value search) search_logs_request = SearchLogsRequest(topic_id, query="key1:error", limit=10, start_time=1346457600000, end_time=1630454400000) search_logs_response = tls_service.search_logs_v2(search_logs_request) # Query log data (SQL analysis) search_logs_request = SearchLogsRequest(topic_id, query="* | select key1, key2", limit=10, start_time=1346457600000, end_time=1630454400000) search_logs_response = tls_service.search_logs_v2(search_logs_request) # Query log data (SQL analysis) search_logs_request = SearchLogsRequest(topic_id, query="* | select key1, key2", limit=10, start_time=1346457600000, end_time=1630454400000) search_logs_response = tls_service.search_logs(search_logs_request) ``` -------------------------------- ### Get Notebook Server Extra Packages Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/bioos.md Retrieves information about extra packages installed on the current Notebook Server. ```APIDOC ## GET /api/bioos/notebook_servers/extra_packages/{workspace_id} ### Description Fetches the details of extra packages (Pip, Conda, R, APT) installed on the Notebook Server within a given workspace. ### Method GET ### Endpoint /api/bioos/notebook_servers/extra_packages/{workspace_id} ### Parameters #### Path Parameters - **workspace_id** (str) - Required - The ID of the workspace. Example: "wcxxxxxxxxxxxxxxxxxxx" ### Response #### Success Response (200) - **ExtraPackages** (Dict) - A dictionary containing lists of installed packages. - **Pip** (Dict[str, str]) - Optional - Pip packages and their versions. Example: {"numpy":"1.22.2"} - **Conda** (Dict[str, str]) - Optional - Conda packages and their versions. Example: {"numpy":"1.22.2"} - **R** (Dict[str, str]) - Optional - R packages and their versions. Example: {"ggplot2":"3.4.4"} - **APT** (Dict[str, str]) - Optional - APT packages and their versions. Example: {"python3-dev":"1.22.2"} #### Response Example ```json { "ExtraPackages": { "Pip": {"numpy":"1.22.2"}, "Conda": {"numpy":"1.22.2"}, "R": {"ggplot2":"3.4.4"}, "APT": {"python3-dev":"1.22.2"} } } ``` ``` -------------------------------- ### Install Dependencies for Text Privatization Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/maas/text_privatization/README.md Installs necessary Python packages for text privatization, including numpy, typing_extensions, sentencepiece, torch, and transformers. ```bash pip install numpy typing_extensions sentencepiece torch~=1.13 transformers~=4.30 ``` -------------------------------- ### ImageX: Image Upload, Processing, and URL Generation (Python) Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides examples for uploading local images and binary data, applying for upload addresses, committing uploads, and generating processed image URLs using the Volcengine ImageX SDK. ```python from volcengine.imagex.ImageXService import ImageXService from volcengine.const.Const import REGION_CN_NORTH1 import json # Initialize ImageX service imagex_service = ImageXService(region=REGION_CN_NORTH1) imagex_service.set_ak('your_access_key') imagex_service.set_sk('your_secret_key') # Upload local images params = { "ServiceId": "your_service_id" } file_paths = ["/path/to/image1.jpg", "/path/to/image2.png"] try: upload_resp = imagex_service.upload_image(params, file_paths) print(f"上传结果: {upload_resp}") except Exception as e: print(f"上传失败: {e}") # Upload binary image data image_bytes = open("/path/to/image.jpg", "rb").read() upload_resp = imagex_service.upload_image_data(params, [image_bytes]) print(f"二进制上传结果: {upload_resp}") # Apply for upload address apply_params = { "ServiceId": "your_service_id", "UploadNum": 2, "StoreKeys": ["custom_key1.jpg", "custom_key2.png"] } apply_resp = imagex_service.apply_upload(apply_params) print(f"申请上传地址: {apply_resp}") # Commit upload completion commit_body = { "ServiceId": "your_service_id", "SessionKey": apply_resp['Result']['UploadAddress']['SessionKey'] } commit_resp = imagex_service.commit_upload( {"ServiceId": "your_service_id"}, json.dumps(commit_body) ) print(f"提交上传结果: {commit_resp}") # Get image processing URL service_id = "your_service_id" store_uri = "tos-cn-xxx/xxx.jpg" process_url = f"https://{service_id}.imagex.cn/{store_uri}~tplv-{service_id}-image.webp?w=200&h=200" print(f"处理后的图片URL: {process_url}") ``` -------------------------------- ### Manage IAM Resources with Volcengine SDK (Python) Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides Python code examples for managing Identity and Access Management (IAM) resources. This includes creating, querying, listing users, policies, and roles, as well as attaching policies to users and creating access keys. ```python from volcengine.iam.IamService import IamService import json # Initialize service iam_service = IamService() iam_service.set_ak('your_access_key') iam_service.set_sk('your_secret_key') # Create user create_user_resp = iam_service.create_user({ 'UserName': 'test_user', 'DisplayName': '测试用户', 'Description': '测试用户描述' }) print(f"创建用户结果: {create_user_resp}") # Get user get_user_resp = iam_service.get_user({'UserName': 'test_user'}) print(f"用户信息: {get_user_resp}") # List users list_users_resp = iam_service.list_users({'Limit': 10, 'Offset': 0}) print(f"用户列表: {list_users_resp}") # Create policy policy_document = { "Statement": [{ "Effect": "Allow", "Action": ["iam:*"], "Resource": ["*"] }] } create_policy_resp = iam_service.create_policy({ 'PolicyName': 'TestPolicy', 'PolicyDocument': json.dumps(policy_document), 'Description': '测试策略' }) print(f"创建策略结果: {create_policy_resp}") # Attach policy to user attach_resp = iam_service.attach_user_policy({ 'UserName': 'test_user', 'PolicyName': 'TestPolicy', 'PolicyType': 'Custom' }) print(f"附加策略结果: {attach_resp}") # Create role trust_policy = { "Statement": [{ "Effect": "Allow", "Action": ["sts:AssumeRole"], "Principal": {"Service": ["ecs.volcengine.com"]} }] } create_role_resp = iam_service.create_role({ 'RoleName': 'TestRole', 'TrustPolicyDocument': json.dumps(trust_policy), 'Description': '测试角色' }) print(f"创建角色结果: {create_role_resp}") # List roles list_roles_resp = iam_service.list_roles({'Limit': 10}) print(f"角色列表: {list_roles_resp}") # Create access key create_ak_resp = iam_service.create_access_key({'UserName': 'test_user'}) print(f"访问密钥: {create_ak_resp}") ``` -------------------------------- ### VOD: Get Subtitle Auth Token and Apply Upload Info (Python) Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates how to obtain a subtitle authorization token and apply for upload information for custom upload processes using the Volcengine VOD SDK. ```python from volcengine.vod.VodService import VodService from volcengine.vod.models.request.VodRequest import VodApplyUploadInfoRequest # Assuming vod_service is an initialized VodService object # vod_service = VodService() # Get subtitle authorization token class SubtitleRequest: Vid = "your_video_id" subtitle_token = vod_service.get_subtitle_auth_token(SubtitleRequest(), expire=3600) print(f"字幕授权Token: {subtitle_token}") # Apply for upload information for custom upload process apply_request = VodApplyUploadInfoRequest() apply_request.SpaceName = "your_space_name" apply_request.FileSize = 1024 * 1024 * 100 # 100MB apply_request.FileType = "video" apply_request.FileName = "custom_video" apply_request.FileExtension = ".mp4" apply_resp = vod_service.apply_upload_info(apply_request) print(f"上传地址信息: {apply_resp}") ``` -------------------------------- ### Utilize Visual Intelligence Services with Volcengine SDK (Python) Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates the use of Volcengine's Visual Intelligence services via the Python SDK. Includes examples for various computer vision tasks such as human segmentation, general image segmentation, OCR (normal, ID card, bank card), driving license recognition, VAT invoice recognition, image enhancement, super-resolution, face swapping, and car plate detection. ```python from volcengine.visual.VisualService import VisualService # Initialize service visual_service = VisualService() visual_service.set_ak('your_access_key') visual_service.set_sk('your_secret_key') # Human segmentation human_segment_resp = visual_service.human_segment({ "image_url": "https://example.com/person.jpg", "refine": 1, "return_foreground_image": 1 }) print(f"人像分割结果: {human_segment_resp}") # General image segmentation general_segment_resp = visual_service.general_segment({ "image_url": "https://example.com/image.jpg" }) print(f"通用分割结果: {general_segment_resp}") # General OCR ocr_resp = visual_service.ocr_normal({ "image_base64": "base64_encoded_image_string" }) print(f"OCR 识别结果: {ocr_resp}") # ID card OCR id_card_resp = visual_service.id_card({ "image_base64": "base64_encoded_image_string" }) print(f"身份证识别结果: {id_card_resp}") # Bank card OCR bank_card_resp = visual_service.bank_card({ "image_base64": "base64_encoded_image_string" }) print(f"银行卡识别结果: {bank_card_resp}") # Driving license OCR driving_license_resp = visual_service.driving_license({ "image_base64": "base64_encoded_image_string" }) print(f"驾驶证识别结果: {driving_license_resp}") # VAT invoice OCR vat_invoice_resp = visual_service.vat_invoice({ "image_base64": "base64_encoded_image_string" }) print(f"增值税发票识别结果: {vat_invoice_resp}") # Image enhancement enhance_resp = visual_service.enhance_photo({ "image_url": "https://example.com/photo.jpg", "resolution_boundary": "2k" }) print(f"图像增强结果: {enhance_resp}") # Super resolution over_resolution_resp = visual_service.over_resolution({ "image_url": "https://example.com/low_res_image.jpg", "multiple": 2 }) print(f"超分辨率结果: {over_resolution_resp}") # Face swap face_swap_resp = visual_service.face_swap({ "image_url_1": "https://example.com/face1.jpg", "image_url_2": "https://example.com/face2.jpg" }) print(f"人脸换脸结果: {face_swap_resp}") # Car plate detection car_plate_resp = visual_service.car_plate_detection({ "image_url": "https://example.com/car.jpg" }) print(f"车牌检测结果: {car_plate_resp}") ``` -------------------------------- ### Consume Logs with Consumer Group in Python Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/tls/README.md Demonstrates how to implement a custom LogProcessor to handle consumed log groups and how to configure and start a TLSConsumer. The code initializes the TLS service, defines the consumer configuration, and manages the lifecycle of the consumer instance. ```python # coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from volcengine.tls.TLSService import TLSService from volcengine.tls.consumer.consumer import TLSConsumer, LogProcessor from volcengine.tls.consumer.consumer_model import ConsumerConfig from volcengine.tls.log_pb2 import LogGroupList class MyLogProcessor(LogProcessor): def process(self, topic_id: str, shard_id: int, log_group_list: LogGroupList): print(topic_id + " --- " + str(shard_id)) count = 0 for log_group in log_group_list.log_groups: for log in log_group.logs: count += 1 print("*** Count = {} ***".format(count)) for content in log.contents: print("{}: {}".format(content.key, content.value)) print() if __name__ == '__main__': endpoint = os.environ["VOLCENGINE_ENDPOINT"] region = os.environ["VOLCENGINE_REGION"] access_key_id = os.environ["VOLCENGINE_ACCESS_KEY_ID"] access_key_secret = os.environ["VOLCENGINE_ACCESS_KEY_SECRET"] tls_service = TLSService(endpoint, access_key_id, access_key_secret, region) consumer_config = ConsumerConfig(project_id="ProjectID", consumer_group_name="python-consumer-group", consumer_name="python-consumer", topic_id_list=["TopicID"]) tls_consumer = TLSConsumer(consumer_config, tls_service, MyLogProcessor()) tls_consumer.start() time.sleep(10) tls_consumer.stop() ``` -------------------------------- ### Create Collection in VikingDB using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides an example of creating a new collection in VikingDB using the Python SDK. It specifies the collection name, defined fields, and an optional description for the collection. ```python from volcengine.viking_db.common import Field, FieldType, VectorIndexParams, IndexType, DistanceType # Assuming viking_db is initialized # Define fields (as shown in previous snippet) fields = [ Field(field_name="id", field_type=FieldType.String, is_primary_key=True), Field(field_name="title", field_type=FieldType.String), Field(field_name="content", field_type=FieldType.String), Field(field_name="embedding", field_type=FieldType.Vector, dim=1024) ] # Create collection collection_name = "my_collection" collection = viking_db.create_collection( collection_name=collection_name, fields=fields, description="测试向量集合" ) print(f"创建集合成功: {collection_name}") ``` -------------------------------- ### Python Bank Card OCR with Volcengine SDK Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/visual/README.md This Python code snippet demonstrates how to perform Bank Card OCR using the Volcengine Visual Service SDK. It requires the SDK to be installed and optionally takes API keys and host configuration. The input is a base64 encoded image string, and the output is the OCR result. ```Python # coding: utf-8 from __future__ import print_function from volc.visual.VisualService import VisualService if __name__ == '__main__': visual_service = VisualService() # call below method if you dont set ak and sk in $HOME/.volc/config visual_service.set_ak('ak') visual_service.set_sk('sk') # visual_service.set_host('host') params = dict() form = { "image_base64": "image_base64_str" } resp = visual_service.bank_card(form) print(resp) ``` -------------------------------- ### Perform Sentiment Analysis with Volcengine Python SDK Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/nlp/README.md This Python code snippet demonstrates how to use the Volcengine NLP service to perform sentiment analysis on a given text. It requires the volcengine SDK to be installed and credentials to be configured. The function takes a dictionary containing the text as input and returns the sentiment analysis result. ```python # -*- coding: utf-8 -*- from __future__ import print_function from volcengine.nlp.NLPService import NLPService if __name__ == '__main__': nlp_service = NLPService() # call below method if you dont set ak and sk in $HOME/.volc/config nlp_service.set_ak('ak') nlp_service.set_sk('sk') params = dict() form = { "text": "我很生气" } resp = nlp_service.sentiment_analysis(form) print(resp) ``` -------------------------------- ### Initialize BioOsService and List Workspaces Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/index.md Demonstrates how to import the BioOsService, configure authentication credentials, and list workspaces. This snippet assumes the user has set up their endpoint and region. ```python from __future__ import print_function from volcengine.bioos.BioOsService import BioOsService if __name__ == '__main__': # set endpoint/region here if the default value is unsatisfied bioos_service = BioOsService(endpoint='endpoint', region='region') # call below method if you don't set ak and sk in $HOME/.volc/config bioos_service.set_ak('ak') bioos_service.set_sk('sk') params = {} resp = bioos_service.list_workspaces(params) print(resp) ``` -------------------------------- ### GET /list_clusters_of_workspace Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/bioos.md Retrieves the list of clusters bound to a specific workspace. ```APIDOC ## GET /list_clusters_of_workspace ### Description Retrieves the list of clusters associated with a specific workspace, filtered by the association type. ### Method GET ### Endpoint /list_clusters_of_workspace ### Parameters #### Request Body - **ID** (str) - Required - The workspace ID. - **Type** (str) - Required - The association type (workflow, notebook). ### Request Example { "ID": "wcxxxxxxxxxxxxxxxxxxx", "Type": "workflow" } ### Response #### Success Response (200) - **Items** (List[Dict]) - List of cluster information objects. - **PageNumber** (int) - Current page number. - **PageSize** (int) - Number of items per page. - **TotalCount** (int) - Total number of clusters. #### Response Example { "Items": [{"ID": "ucxxxxxxxxxxxxxxxxxxx", "Name": "name", "Status": "Creating"}], "TotalCount": 10 } ``` -------------------------------- ### Manage CDN Services with Python SDK Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates how to initialize the CDN service, manage domain configurations, perform cache refreshes/preloads, and query traffic data or access logs. ```python from volcengine.cdn.service import CdnService cdn_service = CdnService() cdn_service.set_ak('your_access_key') cdn_service.set_sk('your_secret_key') add_domain_body = { "Domain": "cdn.example.com", "ServiceType": "web", "Origin": [{"OriginAction": {"OriginLines": [{"Address": "origin.example.com", "Weight": "100"}]}}] } add_resp = cdn_service.add_cdn_domain(add_domain_body) list_domains_body = {"PageNum": 1, "PageSize": 10} list_resp = cdn_service.list_cdn_domains(list_domains_body) update_config_body = { "Domain": "cdn.example.com", "Cache": [{"CacheAction": {"CacheRules": [{"CacheTime": 86400, "Condition": {"Connective": "and", "Conditions": [{"ConditionType": "extension", "Operator": "equals", "Object": "jpg,png,gif"}]}}]}}] } update_resp = cdn_service.update_cdn_config(update_config_body) refresh_body = {"Type": "file", "Urls": "https://cdn.example.com/path/to/file.jpg"} refresh_resp = cdn_service.submit_refresh_task(refresh_body) ``` -------------------------------- ### GET /list_workspace_labels Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/bioos.md Retrieves a list of labels associated with workspaces, with optional filtering. ```APIDOC ## GET /list_workspace_labels ### Description Fetches the list of labels available for workspaces, supporting filtering by keywords and matching criteria. ### Method GET ### Endpoint /list_workspace_labels ### Parameters #### Request Body - **Filter** (Dict) - Optional - Filtering criteria. - **Exact** (bool) - Optional - Whether to perform an exact match. - **MatchPreset** (bool) - Optional - Whether to match preset labels. - **IsPublic** (bool) - Optional - Whether to query public workspaces. - **Keywords** (List[str]) - Optional - List of keywords to match. ### Request Example { "Filter": { "Keywords": ["DNA"] } } ### Response #### Success Response (200) - **Items** (List[Dict]) - List of labels and their associated workspace counts. - **TotalCount** (int) - Total number of labels. #### Response Example { "Items": [{"Name": "DNA", "Count": 10}], "TotalCount": 1 } ``` -------------------------------- ### Manage TLS Logging Services with Python SDK Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates the initialization of the TLS service and the creation of log projects and topics for log collection and management. ```python from volcengine.tls.TLSService import TLSService from volcengine.tls.tls_requests import * tls_service = TLSService(endpoint="tls-cn-beijing.ivolces.com", region="cn-beijing") tls_service.set_ak('your_access_key') tls_service.set_sk('your_secret_key') # Create project create_project_req = CreateProjectRequest(project_name="my_project", region="cn-beijing", description="测试项目") project_resp = tls_service.create_project(create_project_req) # Create topic create_topic_req = CreateTopicRequest(project_id=project_resp.project_id, topic_name="my_topic", ttl=30, shard_count=2, description="测试主题") topic_resp = tls_service.create_topic(create_topic_req) ``` -------------------------------- ### GET /list_workflows Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/bioos.md Retrieves a list of workflows based on specified filters and pagination settings. ```APIDOC ## GET /list_workflows ### Description Query a list of workflows within a specific workspace with optional filtering and sorting. ### Method GET ### Endpoint bioos.BioOsService.BioOsService.list_workflows ### Parameters #### Request Body - **WorkspaceID** (str) - Required - The ID of the workspace. - **PageNumber** (int) - Optional - Page number. - **PageSize** (int) - Optional - Number of items per page. - **Filter** (Dict) - Optional - Filtering criteria (Keyword, IDs). - **SortBy** (str) - Optional - Field to sort by (Name, CreateTime). - **SortOrder** (str) - Optional - Sort order (Desc, Asc). ### Response #### Success Response (200) - **Items** (List[Dict]) - List of workflow objects. - **TotalCount** (int) - Total number of workflows. ``` -------------------------------- ### Configure Authentication for Volcengine SDK (Python) Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates three methods for configuring Access Key (AK) and Secret Key (SK) for authentication with Volcengine services: direct code setting, environment variables, and configuration files. Direct code setting is recommended for ease of use. ```python from volcengine.iam.IamService import IamService iam_service = IamService() iam_service.set_ak('your_access_key') iam_service.set_sk('your_secret_key') ``` ```bash # Export environment variables export VOLC_ACCESSKEY="your_access_key" export VOLC_SECRETKEY="your_secret_key" ``` ```json # Configuration file: ~/.volc/config { "ak": "your_access_key", "sk": "your_secret_key" } ``` ```ini # Credentials file: ~/.volc/credentials [default] access_key_id = your_access_key secret_access_key = your_secret_key ``` -------------------------------- ### Query Bill Overview by Product using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt This snippet demonstrates how to obtain a billing overview by product for a given period using the Volcengine SDK for Python. Ensure the billing_service client is properly configured. ```python overview_body = { "BillPeriod": "2024-01" } overview_resp = billing_service.list_bill_overview_by_prod(overview_body) print(f"账单概览: {overview_resp}") ``` -------------------------------- ### GET /SearchLogsV2 Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/tls/README.md Retrieves and analyzes log data using full-text search, key-value search, or SQL analysis. ```APIDOC ## GET /SearchLogsV2 ### Description Performs log retrieval and analysis based on a query string within a specified time range. ### Method GET ### Parameters #### Query Parameters - **topic_id** (string) - Required - The ID of the topic to search. - **query** (string) - Required - The search or SQL query string. - **start_time** (long) - Required - Start timestamp in milliseconds. - **end_time** (long) - Required - End timestamp in milliseconds. - **limit** (int) - Optional - Maximum number of logs to return. ``` -------------------------------- ### List Notebook Server Resource Options Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/bioos.md Fetches the available resource configurations (CPU, Memory) for Notebook Servers. ```python params = {} response = bioos_service.list_notebook_server_resource_opts(params) ``` -------------------------------- ### Get Tokenizer and Embedding Model Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/maas/text_privatization/README.md Retrieves a tokenizer and embedding model from Hugging Face using the `get_bottom_model` function. This is a prerequisite for text privatization. ```python from volcengine.maas.text_privatization import get_bottom_model your_tokenizer, your_embedding_model = get_bottom_model(model_id="MODEL_ID") ``` -------------------------------- ### Initialize TLS Client with Environment Variables Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/tls/README.md Demonstrates how to initialize the TLSService client using credentials and endpoint information fetched from environment variables. This approach avoids hardcoding sensitive keys, enhancing security. It requires setting VOLCENGINE_ENDPOINT, VOLCENGINE_REGION, VOLCENGINE_ACCESS_KEY_ID, and VOLCENGINE_ACCESS_KEY_SECRET. ```python import os from volcengine.tls.TLSService import TLSService # Note: The endpoint in the environment variable does not include the protocol header (https:// or http://), e.g., tls-cn-beijing.ivolces.com. endpoint = os.environ["VOLCENGINE_ENDPOINT"] region = os.environ["VOLCENGINE_REGION"] access_key_id = os.environ["VOLCENGINE_ACCESS_KEY_ID"] access_key_secret = os.environ["VOLCENGINE_ACCESS_KEY_SECRET"] tls_service = TLSService(endpoint, access_key_id, access_key_secret, region) ``` -------------------------------- ### Get Collection Information in VikingDB using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates how to retrieve information about an existing collection in VikingDB using the Python SDK. This involves specifying the collection name. ```python # Assuming viking_db is initialized collection_name = "my_collection" collection = viking_db.get_collection(collection_name) print(f"集合信息: {collection}") ``` -------------------------------- ### Drop Collection in VikingDB using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides an example of deleting a collection from VikingDB using the Python SDK. This operation permanently removes the specified collection and all its data. ```python # Assuming viking_db is initialized collection_name = "my_collection" viking_db.drop_collection(collection_name) print(f"删除集合成功: {collection_name}") ``` -------------------------------- ### Create Notebook Server Image Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/bioos.md Creates a new custom Notebook Server image with specified base environment and package dependencies. ```python params = { "BaseImage": "python:latest", "ImageName": "custom:v1.0.0", "DisplayName": "custom", "Source": "building", "ImageVersion": "1.0.0", "Packages": { "Pip": {"numpy": "1.22.2"} } } bioos_service.create_notebook_server_image(params) ``` -------------------------------- ### Configure Security Credentials for Volcengine SDK Source: https://github.com/volcengine/volc-sdk-python/blob/main/README.md Demonstrates three methods for configuring Access Key (AK) and Secret Access Key (SK) for the Volcengine SDK for Python. Replace 'Your AK' and 'Your SK' with actual credentials. ```python from volcengine.iam import IamService iam_service = IamService() am_service.set_ak('Your AK') am_service.set_sk('Your SK') ``` ```bash export VOLC_ACCESSKEY="Your AK" export VOLC_SECRETKEY="Your SK" ``` ```json { "ak": "Your AK", "sk": "Your SK" } ``` -------------------------------- ### Describe Projects in TLS using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates how to retrieve a list of projects within Volcengine TLS using the Python SDK. It shows how to specify pagination parameters like page number and page size for the request. ```python from volcengine.tls.models import DescribeProjectsRequest # Assuming tls_service is initialized describe_projects_req = DescribeProjectsRequest( page_number=1, page_size=10 ) projects_resp = tls_service.describe_projects(describe_projects_req) print(f"项目列表: {projects_resp}") ``` -------------------------------- ### Fetch Data by ID in VikingDB using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides an example of fetching specific data records from a VikingDB collection by their IDs using the Python SDK. It allows specifying which fields to retrieve for the matching records. ```python # Assuming collection is obtained fetch_result = collection.fetch_data( ids=["doc_1", "doc_2"], output_fields=["id", "title", "content"] ) print(f"查询结果: {fetch_result}") ``` -------------------------------- ### Query Bill Detail using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt This snippet shows how to query detailed billing information for a specific period and product using the Volcengine SDK for Python. It requires the billing_service client to be initialized with appropriate credentials. ```python bill_detail_body = { "BillPeriod": "2024-01", "Product": "CDN", "Limit": 100, "Offset": 0 } detail_resp = billing_service.list_bill_detail(bill_detail_body) print(f"账单明细: {detail_resp}") ``` -------------------------------- ### Insert Data into VikingDB Collection using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Provides an example of inserting or updating data in a VikingDB collection using the Python SDK. It demonstrates the format for data entries, including IDs, text fields, and vector embeddings. ```python import random # Assuming collection is obtained data = [ { "id": "doc_1", "title": "火山引擎介绍", "content": "火山引擎是字节跳动旗下的云服务平台", "embedding": [random.random() for _ in range(1024)] }, { "id": "doc_2", "title": "VikingDB介绍", "content": "VikingDB是一款高性能向量数据库", "embedding": [random.random() for _ in range(1024)] } ] collection.upsert_data(data) print(f"插入数据成功") ``` -------------------------------- ### List Notebook Server Resource Options Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/bioos.md Retrieves a list of available resource configurations for Notebook Servers, including CPU and Memory specifications. ```APIDOC ## GET /api/bioos/resource-opts ### Description Lists the available resource options (CPU, Memory) for Notebook Servers. ### Method GET ### Endpoint /api/bioos/resource-opts ### Parameters No parameters are required for this request. ### Response #### Success Response (200) - **ResourceSize** (List[Dict]) - A list of available resource configurations. - **ResourceSize** (str) - The name of the resource size (e.g., 'small', 'middle', 'large'). - **Cpu** (int) - The number of CPU cores available for this resource size. - **Memory** (int) - The amount of memory available in bytes for this resource size. #### Response Example ```json { "ResourceSize": [ { "ResourceSize": "small", "Cpu": 2, "Memory": 8589934592 } ] } ``` ``` -------------------------------- ### Initialize VikingDB Service using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Shows how to initialize the VikingDBService client in Python. This involves providing connection details such as host, region, access key, secret key, and scheme. ```python from volcengine.viking_db import VikingDBService # Initialize service viking_db = VikingDBService( host="api-vikingdb.volces.com", region="cn-north-1", ak="your_access_key", sk="your_secret_key", scheme="https" ) ``` -------------------------------- ### Create Index in TLS using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates how to create a full-text index for a topic in Volcengine TLS using the Python SDK. It specifies index parameters like delimiters and case sensitivity for full-text search and key-value pairs for structured data. ```python from volcengine.tls.models import CreateIndexRequest, FullTextInfo, KeyValueInfo, ValueInfo # Assuming tls_service and topic_id are already initialized create_index_req = CreateIndexRequest( topic_id=topic_id, full_text=FullTextInfo( delimiter=", '\";=()[]{}?@&<>/:\n\t\r", case_sensitive=False ), key_value=[ KeyValueInfo( key="level", value=ValueInfo( value_type="text", case_sensitive=False ) ), KeyValueInfo( key="timestamp", value=ValueInfo( value_type="long" ) ) ] ) index_resp = tls_service.create_index(create_index_req) print(f"创建索引成功: {index_resp}") ``` -------------------------------- ### Create Alarm in TLS using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Illustrates how to create an alarm in Volcengine TLS using the Python SDK. This includes defining alarm conditions, query requests, notification groups, and other parameters to monitor log data for specific events. ```python from volcengine.tls.models import CreateAlarmRequest, AlarmQueryRequest # Assuming tls_service, topic_id, project_id, and notify_group_id are initialized create_alarm_req = CreateAlarmRequest( alarm_name="error_alarm", project_id=project_id, status=True, query_request=AlarmQueryRequest( topic_id=topic_id, query="level:ERROR | SELECT COUNT(*) as error_count", start_time_offset=-300, # 5分钟前 end_time_offset=0 ), alarm_period=60, # 告警周期(秒) condition="$1.error_count > 10", # 触发条件 alarm_notify_group=["notify_group_id"] ) alarm_resp = tls_service.create_alarm(create_alarm_req) print(f"创建告警成功: {alarm_resp}") ``` -------------------------------- ### Create Notebook Server Image Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/bioos/doc/source/bioos.md Creates a new Notebook Server image. This process involves specifying base image details, image name, display name, and optionally providing build scripts and package information. ```APIDOC ## POST /api/bioos/images/create ### Description Creates a new custom Notebook Server image. Requires details about the base image, desired name, and package configurations. ### Method POST ### Endpoint /api/bioos/images/create ### Parameters #### Request Body - **BaseImage** (str) - Required - The base image to use for building (e.g., 'python:latest'). Only required for 'building' source images. - **ImageName** (str) - Required - The unique name for the new image (e.g., 'custom:v1.0.0'). - **DisplayName** (str) - Required - A human-readable display name for the image (e.g., 'custom'). - **Description** (str) - Optional - A description for the image. - **BuildScript** (str) - Optional - A shell script to execute during the image build process. - **Source** (str) - Required - The source of the image, must be 'building' for custom images. - **Packages** (Dict) - Required - A dictionary specifying the packages to install. - **Pip** (Dict[str, str]) - Optional - Pip packages to install (e.g., `{"numpy": "1.22.2"}`). - **Conda** (Dict[str, str]) - Optional - Conda packages to install (e.g., `{"numpy": "1.22.2"}`). - **R** (Dict[str, str]) - Optional - R packages to install (e.g., `{"ggplot2": "3.4.4"}`). - **APT** (Dict[str, str]) - Optional - APT packages to install (e.g., `{"python3-dev": "1.22.2"}`). - **BasicEnv** (List[str]) - Optional - A list of basic environment parameters (e.g., `["Python3.9.10"]`). - **ImageVersion** (str) - Required - The version of the image (e.g., '1.0.0'). ### Request Example ```json { "BaseImage": "python:latest", "ImageName": "custom:v1.0.0", "DisplayName": "custom", "Description": "description", "BuildScript": "", "Source": "building", "Packages": { "Pip": {"numpy": "1.22.2"}, "Conda": {"numpy": "1.22.2"}, "R": {"ggplot2": "3.4.4"}, "APT": {"python3-dev": "1.22.2"} }, "BasicEnv": ["Python3.9.10", "R 4.1.2", "Julia 1.7.2"], "ImageVersion": "1.0.0" } ``` ### Response #### Success Response (200) - Returns an empty dictionary upon successful operation. The image creation is an asynchronous process. #### Response Example ```json {} ``` ``` -------------------------------- ### POST /CreateProject Source: https://github.com/volcengine/volc-sdk-python/blob/main/volcengine/tls/README.md Creates a new log project in the specified region. ```APIDOC ## POST /CreateProject ### Description Creates a new log project to group log topics. ### Method POST ### Parameters #### Request Body - **project_name** (string) - Required - The name of the project. - **region** (string) - Required - The region where the project is created. - **description** (string) - Optional - Description of the project. ### Response #### Success Response (200) - **project_id** (string) - The unique identifier of the created project. ``` -------------------------------- ### List Collections in VikingDB using Python Source: https://context7.com/volcengine/volc-sdk-python/llms.txt Demonstrates how to list all available collections in VikingDB using the Python SDK. This provides an overview of the collections managed by the service. ```python # Assuming viking_db is initialized collections = viking_db.list_collections() print(f"集合列表: {collections}") ```