### Install SDK Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/README.md Command to install the dashscope SDK. ```bash pip install dashscope>=1.25.19 ``` -------------------------------- ### Python SDK Examples Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Examples demonstrating how to test Rollout and Reward functions using the Python SDK. ```python # Test Rollout result = await AgenticRL.test_functions( instance_id=rollout_iids[0], functype=FunctionType.ROLLOUT, input_data="resouces/rollout_input.json" # path to JSON file ) # Test Reward reward_input = { "func_type": "reward", "agent_output": { "messages": [{"role": "user", "content": "Test"}], "reward_score": null } } result = await AgenticRL.test_functions( instance_id=reward_iids[0], functype=FunctionType.REWARD, input_data=reward_input ) ``` -------------------------------- ### Example: Run Full Workflow (Auto) Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md This example demonstrates how to run the full reinforcement learning workflow using a configuration file and enabling verbose output. ```bash dashscope rl run \ --config "job.yaml" \ --verbose ``` -------------------------------- ### CLI example for getting job information Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Example command to get job information using the CLI. ```bash dashscope rl get "$JOB_ID" -o json ``` -------------------------------- ### SDK example for getting job information Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Example of how to get job information using the AgenticRL SDK. ```python from dashscope.finetune.agentic_rl import AgenticRL job = AgenticRL.get("job-12345") ``` -------------------------------- ### Instrumented Rollout Processor Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md An example demonstrating how to create an instrumented rollout processor by tracing LLM clients and tools. ```python import openai from dashscope.finetune.reinforcement import AbstractRolloutProcessor, RolloutInput, RolloutOutput from dashscope.finetune.reinforcement.component.data.base_data_model import AgentOutput, TaskStatus from dashscope.finetune.reinforcement.component.observability import ( observe_processor, trace_client, trace_tool, ) class MyRolloutProcessor(AbstractRolloutProcessor): async def setup(self) -> None: # 1. Trace LLM Client self._client = openai.AsyncOpenAI(base_url="...", api_key="...") trace_client(self._client) # 2. Trace Tools (e.g., MCP) from langchain_mcp_adapters.client import MultiServerMCPClient client = MultiServerMCPClient({...}) self._tools = await client.get_tools() trace_tool(self._tools) @observe_processor async def process(self, input: RolloutInput) -> RolloutOutput: messages = input.messages or [] model = input.model_resource.model_name # This call is automatically traced due to trace_client(self._client) response = await self._client.chat.completions.create( model=model, messages=messages, ) content = response.choices[0].message.content if response.choices else "" return RolloutOutput( agent_output=AgentOutput(messages=messages, reward_score=0.0), status=TaskStatus.SUCCESS, ) ``` -------------------------------- ### AgenticRL Initialization Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Example of initializing the AgenticRL instance with an API key. ```python from dashscope.finetune.agentic_rl import AgenticRL rl = AgenticRL(api_key="your_api_key") ``` -------------------------------- ### Example requirements.txt Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Mandatory file for deploying Function Components to the cloud, listing necessary dependencies. ```txt fastapi==0.136.0 uvicorn==0.45.0 typer==0.24.1 rich==15.0.0 pyyaml==6.0.3 protobuf>=4.25.8,<7.0 #6.33.6 fsspec==2026.3.0 httpx==0.28.1 tenacity==9.1.4 ``` -------------------------------- ### Install from Source (For Development) Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Clones the dashscope-sdk-python repository and installs it in editable mode for development. ```bash git clone https://github.com/dashscope/dashscope-sdk-python.git cd dashscope-sdk-python pip install -e . # Install in editable mode for development ``` -------------------------------- ### Configuring Dependencies File Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/README.md Example requirements.txt for Function Compute environment. ```requirements.txt # Base (Must) dashscope>=1.25.19 # Framework dependencies fastapi==0.136.0 uvicorn==0.45.0 # ... # Trajectory function dependencies langchain-core==1.3.0 langchain-mcp-adapters==0.2.2 langchain-openai==1.2.0 # ... # Add other custom dependencies... ``` -------------------------------- ### AgenticRL Initialization from Config Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Example of initializing the AgenticRL instance from a YAML configuration file with overrides. ```python from dashscope.finetune.agentic_rl import AgenticRL rl = AgenticRL().init("job.yaml", job_name="custom_job") ``` -------------------------------- ### Quick Start: Text Generation Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/README.md A basic example demonstrating how to use the Generation.call method for text generation. Ensure the API key is set before making calls. ```python from http import HTTPStatus from dashscope import Generation responses = Generation.call( model="qwen-plus", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who are you?"}, ], result_format="message", ) if responses.status_code == HTTPStatus.OK: print(responses.output.choices[0].message.content) else: print(f"Error: {responses.code} - {responses.message}") ``` -------------------------------- ### Install DashScope Python SDK Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/README.md Install the SDK using pip. For local development from source, use the editable install option. To enable tokenizer functionality locally, install with the tokenizer extra. ```shell pip install dashscope ``` ```shell pip install -e . ``` ```shell pip install dashscope[tokenizer] ``` -------------------------------- ### Code Examples and Error Handling Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/SUMMARY.txt The SDK includes over 100 code examples demonstrating basic usage, streaming, async patterns, error handling, and complete workflows, alongside documentation for 15+ error codes. ```APIDOC ## Code Examples and Error Handling **Code Examples:** 100+ - Basic usage examples. - Streaming and async patterns. - Error handling and retry logic. - Complete workflows. - Integration patterns. - Best practices. **Error Codes:** 15+ documented - HTTP status codes (200, 400, 401, 403, 404, 429, 500, 503). - DashScope error codes (InvalidApiKey, ModelNotFound, RateLimitExceeded, etc.). - Exception types (InputRequired, ModelRequired, InvalidTask, etc.). - Error handling patterns with examples. ``` -------------------------------- ### Core SDK Features Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/SUMMARY.txt The SDK documentation covers essential aspects like quick start guides, API overviews, authentication methods, type definitions, configuration options, and error handling patterns. ```APIDOC ## Core SDK Features The core documentation for the DashScope Python SDK includes: - **README.md**: Quick start guide, API overview, and authentication details. - **INDEX.md**: A comprehensive file index and navigation guide. - **types.md**: Definitions for all types, enums, and data structures used within the SDK. - **configuration.md**: Information on API key management, environment variables, and SDK configuration. - **errors.md**: Details on error codes, exception types, and recommended handling patterns. ``` -------------------------------- ### SDK example for cancelling a job Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Example of how to cancel a job using the AgenticRL SDK. ```python from dashscope.finetune.agentic_rl import AgenticRL AgenticRL.cancel("job-12345") ``` -------------------------------- ### CLI example for cancelling a job Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Example command to cancel a job using the CLI. ```bash dashscope rl cancel "$JOB_ID" ``` -------------------------------- ### Initialize Pre-commit Hooks for Development Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dev.md Commands to install necessary testing dependencies and initialize the pre-commit hooks. These hooks automatically enforce PEP8 standards, linting, and formatting on every commit. ```bash pip install -r requirements/tests.txt pre-commit install ``` -------------------------------- ### Asynchronous Image Analysis with AioMultiModalConversation Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/multimodal-conversation.md Example demonstrating how to perform asynchronous image analysis using the `AioMultiModalConversation.call` method. Ensure you have the necessary libraries installed and an event loop running. ```python from dashscope import AioMultiModalConversation import asyncio async def analyze_image(): response = await AioMultiModalConversation.call( model="qwen-vl-max", messages=[{ "role": "user", "content": [ {"image": "https://example.com/image.jpg"}, {"text": "Analyze this image"} ] }]) return response.output.choices[0].message.content result = asyncio.run(analyze_image()) ``` -------------------------------- ### Instantiate MultiModalEmbeddingItemText Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/types.md Example of creating a MultiModalEmbeddingItemText instance with custom text and factor. ```python item = MultiModalEmbeddingItemText( text="A description", factor=1.5 ) ``` -------------------------------- ### Fine-Tuning Workflow Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/fine-tuning.md A complete example demonstrating the end-to-end fine-tuning process, from uploading training data to deploying and using the fine-tuned model. ```APIDOC ## Complete Fine-Tuning Workflow This section outlines the steps to fine-tune a model using the DashScope Python SDK. ### 1. Prepare and Upload Training Data First, create a training data file (e.g., `training.jsonl`) and upload it using `Files.upload`. ```python from dashscope import Files # Create a dummy training file with open("training.jsonl", "w") as f: f.write('{"messages": [{"role": "user", "content": "Q1"}, {"role": "assistant", "content": "A1"}]}\\n') # Upload the file for fine-tuning upload_response = Files.upload( file_path="training.jsonl", purpose="fine-tune" ) file_id = upload_response.output.id print(f"Uploaded file ID: {file_id}") ``` ### 2. Start Fine-Tuning Job Initiate a fine-tuning job using `FineTunes.call`, specifying the base model and the uploaded training file. ```python from dashscope import FineTunes # Start the fine-tuning job ft_response = FineTunes.call( model="qwen-turbo", training_file_ids=[file_id], hyper_parameters={"n_epochs": 2} ) job_id = ft_response.output.id print(f"Started fine-tuning job: {job_id}") ``` ### 3. Monitor Job Status Periodically check the status of the fine-tuning job using `FineTunes.get` until it succeeds or fails. ```python import time from dashscope import FineTunes # Monitor job status while True: status_response = FineTunes.get(job_id) job = status_response.output print(f"Job Status: {job.status}") if job.status == "succeeded": model_name = job.fine_tuned_model print(f"Fine-tuned model name: {model_name}") break elif job.status in ["failed", "cancelled"]: print(f"Fine-tuning job failed with status: {job.status}") exit(1) time.sleep(30) # Wait for 30 seconds before checking again ``` ### 4. Deploy the Fine-Tuned Model Once the fine-tuning is successful, deploy the new model using `Deployments.call`. ```python from dashscope import Deployments # Deploy the fine-tuned model deploy_response = Deployments.call( model=model_name, # Use the model_name obtained from the succeeded job capacity=1 ) print(f"Model deployed: {model_name}") ``` ### 5. Use the Deployed Model Interact with your newly deployed fine-tuned model for generation tasks. ```python from dashscope import Generation # Use the deployed model for generation gen_response = Generation.call( model=model_name, # Use the deployed fine-tuned model messages=[{"role": "user", "content": "Test"}], result_format="message" ) print(f"Generation response: {gen_response.output.choices[0].message['content']}") ``` ### 6. Clean Up Resources After use, it is recommended to delete the deployed model and the uploaded file to avoid incurring further costs. ```python from dashscope import Deployments, Files # Clean up: Delete deployment Deployments.delete(model_name) print(f"Deployment deleted: {model_name}") # Clean up: Delete uploaded file Files.delete(file_id) print(f"Uploaded file deleted: {file_id}") ``` ``` -------------------------------- ### Asynchronous Text Generation Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/generation.md Example demonstrating how to use AioGeneration.call() for asynchronous text generation. Ensure you have the necessary imports and an asyncio event loop. ```python from dashscope import AioGeneration import asyncio async def generate(): response = await AioGeneration.call( model="qwen-plus", messages=[{"role": "user", "content": "Hello"}], result_format="message" ) return response.output.choices[0].message.content result = asyncio.run(generate()) ``` -------------------------------- ### SpeechSynthesizer.call() Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/audio.md Synthesizes text to speech using the SpeechSynthesizer and saves the resulting audio to a file. Ensure the correct model and voice are specified during initialization. ```python from dashscope.audio.tts_v2 import SpeechSynthesizer synthesizer = SpeechSynthesizer( model="cosyvoice-v1", voice="longxiaochun" ) audio = synthesizer.call("Hello, welcome to DashScope!") with open("output.wav", "wb") as f: f.write(audio) ``` -------------------------------- ### Runs.create() Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/assistants.md Starts a new assistant run on a specified thread. You can override the assistant's default model, instructions, tools, and metadata. ```APIDOC ## Runs.create() ### Description Start a new assistant run on a thread. Allows overriding assistant's model, instructions, tools, and metadata. ### Method Signature ```python Runs.create( thread_id: str, assistant_id: str, model: str = None, instructions: str = None, tools: List[Dict] = None, metadata: Dict = None, workspace: str = None, api_key: str = None, **kwargs, ) -> Run ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters Table | Parameter | Type | Description | |---|---|---| | thread_id | str | Thread ID | | assistant_id | str | Assistant ID | | model | str | Override assistant's model | | instructions | str | Override assistant's instructions | | tools | List[Dict] | Override assistant's tools | | metadata | Dict | Custom metadata | | workspace | str | DashScope workspace ID | | api_key | str | API key override | ### Request Example ```python from dashscope import Runs run = Runs.create( thread_id="thread_123", assistant_id="assistant_456" ) ``` ### Response #### Success Response (200) Returns a `Run` object representing the newly created run. #### Response Example (Run object details not specified in source) ``` -------------------------------- ### CLI get job information usage Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Command-line interface usage for querying job status and metadata. ```bash Usage: dashscope get [OPTIONS] JOB_ID ๐Ÿ“Š Query the current status and metadata of a specific job โ•ญโ”€ Arguments โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ * job_id TEXT Target job ID [required] โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ญโ”€ Options โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ --api-key TEXT DashScope API Key (uses DASHSCOPE_API_KEY env var if omitted) [env var: DASHSCOPE_API_KEY] โ”‚ โ”‚ --output-format -o TEXT [default: table] โ”‚ โ”‚ --help Show this message and exit. โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ ``` -------------------------------- ### Multi-modal Content Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/generation.md Illustrates how to format multi-modal content within a message, combining image URLs with text prompts. ```python [ {"image": "https://example.com/image.jpg"}, {"text": "What's in this image?"} ] ``` -------------------------------- ### Hyperparameter Tuning Configurations Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/fine-tuning.md Provides example hyperparameter dictionaries for different tuning strategies: conservative for better accuracy, aggressive for speed, and balanced. ```python { "n_epochs": 3, "learning_rate": 1e-5, "batch_size": 16, "warmup_ratio": 0.1, } ``` ```python { "n_epochs": 1, "learning_rate": 5e-5, "batch_size": 32, "warmup_ratio": 0.05, } ``` ```python { "n_epochs": 2, "learning_rate": 2e-5, "batch_size": 32, "warmup_ratio": 0.1, } ``` -------------------------------- ### Transcription Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/audio.md Example demonstrating how to submit a transcription task and retrieve the results. ```APIDOC ## Example ```python from dashscope import Transcription from http import HTTPStatus # Submit task = Transcription.async_call( model="paraformer-v1", file_urls=["https://example.com/audio.wav"] ) # Wait for result result = Transcription.wait(task) if result.status_code == HTTPStatus.OK: transcription = result.output.results[0].transcription print(f"Text: {transcription}") ``` ``` -------------------------------- ### CLI Help and Commands Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/README.md Displays the help message for the dashscope rl CLI and lists available commands with brief descriptions. ```bash dashscope rl --help # View full command help Usage: dashscope [OPTIONS] COMMAND [ARGS]... ๐Ÿš€ Agentic RL Fine-Tuning CLI โ•ญโ”€ Options โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ --help Show this message and exit. โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ญโ”€ Commands โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ register_functions ๐Ÿงฉ Register Rollout/Reward function components, returns entity_id & instance_id โ”‚ โ”‚ test_functions ๐Ÿงช Test a registered Rollout/Reward function instance with custom input data. โ”‚ โ”‚ upload_data ๐Ÿ“ฆ Upload training/validation datasets to the platform, returns file IDs โ”‚ โ”‚ run ๐Ÿš€ Launch the complete RL tuning workflow (function registration โ†’ dataset upload โ†’ job submission) โ”‚ โ”‚ get ๐Ÿ“Š Query the current status and metadata of a specific job โ”‚ โ”‚ list ๐Ÿ“‹ List historical fine-tuning jobs with pagination โ”‚ โ”‚ cancel ๐Ÿ›‘ Cancel a running job โ”‚ โ”‚ delete ๐Ÿ—‘๏ธ Delete a job record (releases metadata) โ”‚ โ”‚ logs ๐Ÿ“œ Fetch job execution logs (supports pagination) โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ ``` -------------------------------- ### Create Assistant Run Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/assistants.md Starts a new assistant run on a specified thread. You can override the assistant's default model and instructions if needed. ```python from dashscope import Runs run = Runs.create( thread_id="thread_123", assistant_id="assistant_456" ) ``` -------------------------------- ### Image-to-Video Generation Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/video-synthesis.md Example of generating a video from an image URL and a text prompt. ```APIDOC ## Image-to-Video ```python task = VideoSynthesis.async_call( model="wan2.7-i2v", image_url="https://example.com/photo.jpg", prompt="The camera zooms in on the subject" ) result = VideoSynthesis.wait(task) ``` ``` -------------------------------- ### Video Generation with Custom Duration and FPS Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/video-synthesis.md Example showing how to specify custom duration and frames per second (FPS) for video generation. ```APIDOC ## Custom Duration and FPS ```python task = VideoSynthesis.async_call( model="wan2.7-t2v", prompt="Fast-paced action sequence", duration=10, # 10 seconds fps=30 # 30 frames per second ) ``` ``` -------------------------------- ### Text-to-Video Generation Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/video-synthesis.md Example of submitting a text-to-video generation task asynchronously and waiting for the result. ```APIDOC ## Text-to-Video ```python from dashscope import VideoSynthesis # Submit task task = VideoSynthesis.async_call( model="wan2.7-t2v", prompt="A serene waterfall in a tropical forest, soft light" ) # Wait for completion result = VideoSynthesis.wait(task, timeout_seconds=7200) # 2 hours if result.status_code == 200: video_url = result.output.results[0].url print(f"Generated video: {video_url}") ``` ``` -------------------------------- ### Video Generation with Negative Prompts Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/video-synthesis.md Example demonstrating how to use negative prompts to refine video generation by specifying elements to exclude. ```APIDOC ## With Negative Prompts ```python task = VideoSynthesis.async_call( model="wan2.7-t2v", prompt="A person dancing in a ballroom", negative_prompt="blurry, low quality, watermark, text overlay" ) ``` ``` -------------------------------- ### Dependencies for Observability (Tracing) Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Additional dependencies to include in requirements.txt for enabling observability spans. ```txt opentelemetry-api==1.41.1 opentelemetry-sdk==1.41.1 opentelemetry-exporter-otlp-proto-http==1.41.1 opentelemetry-processor-baggage==0.62b1 loongsuite-util-genai==0.4.0 ``` -------------------------------- ### Set and Get API Key File Path Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/configuration.md Configure the path to a file containing the API key. The SDK will read the key from this file. ```python import dashscope # Set dashscope.api_key_file_path = '~/.dashscope/api_key' # Get path = dashscope.api_key_file_path ``` -------------------------------- ### Setting Environment Variables Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/README.md Environment variables for API key and log level. ```bash # Required: API key (can also be initialized in code: AgenticRL(api_key="for your api key") ) export DASHSCOPE_API_KEY="your_api_key_here" # Optional: Log level setting info/debug/warning/critical (default info) export LOG_LEVEL="info" ``` -------------------------------- ### Get Execution Steps Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/assistants.md Retrieves a list of execution steps for a given run. Supports pagination with `after` and limiting results with `limit`. ```python Steps.list( thread_id: str, run_id: str, limit: int = None, after: str = None, **kwargs, ) -> RunStepList ``` -------------------------------- ### Local Tokenizer Usage Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/README.md Instantiate and use a local tokenizer. Requires installing the `dashscope[tokenizer]` extra. Use `get_tokenizer` to obtain the tokenizer instance. ```python from dashscope import get_tokenizer tokenizer = get_tokenizer("qwen-turbo") tokens = tokenizer.encode("Hello world") ``` -------------------------------- ### Function Execution (Register + Test) Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/README.md Command to execute functions for registration and testing. ```bash python test_functions.py ``` -------------------------------- ### CLI One-Step Workflow Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Command-line interface usage for the `dashscope run` command, which initiates the complete RL tuning workflow. ```bash ๐Ÿš€ Launch the complete RL tuning workflow (function registration โ†’ dataset upload โ†’ job submission) Execution modes: 1. Configuration-driven: Use -c/--config to specify a YAML file 2. Direct parameter: Provide all required arguments via CLI options Required parameters: - rollout_classpath - reward_classpaths (at least one) - training_files (at least one) โ•ญโ”€ Options โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ --config -c PATH Path to YAML configuration file โ”‚ โ”‚ --model TEXT Base model identifier โ”‚ โ”‚ --training-files TEXT Paths to training dataset files โ”‚ โ”‚ --validation-files TEXT Paths to validation dataset files โ”‚ โ”‚ --rollout-classpath TEXT Python import path to rollout class (module:Class) โ”‚ โ”‚ --reward-classpaths TEXT List for reward class path (file.py:ClassName) โ”‚ โ”‚ --group-reward-classpaths TEXT List for group-reward class path (file.py:ClassName) โ”‚ ``` -------------------------------- ### DashScope CLI Usage Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Command-line interface for DashScope RL fine-tuning, listing available options and commands. ```bash ๐Ÿš€ Agentic RL Fine-Tuning CLI โ•ญโ”€ Options โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ --help Show this message and exit. โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ญโ”€ Commands โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ register_functions ๐Ÿงฉ Register Rollout/Reward function components, returns entity_id & instance_id โ”‚ โ”‚ test_functions ๐Ÿงช Test a registered Rollout/Reward function instance with custom input data. โ”‚ โ”‚ upload_data ๐Ÿ“ฆ Upload training/validation datasets to the platform, returns file IDs โ”‚ โ”‚ submit ๐Ÿ“ค Submit fine-tuning job (requires pre-registered functions & uploaded datasets) โ”‚ โ”‚ run ๐Ÿš€ Launch the complete RL tuning workflow (function registration โ†’ dataset upload โ†’ job submission) โ”‚ โ”‚ status ๐Ÿ“Š Query the current status and metadata of a specific job โ”‚ โ”‚ list ๐Ÿ“‹ List historical fine-tuning jobs with pagination โ”‚ โ”‚ cancel ๐Ÿ›‘ Cancel a running job โ”‚ โ”‚ delete ๐Ÿ—‘๏ธ Delete a job record (releases metadata) โ”‚ โ”‚ logs ๐Ÿ“œ Fetch job execution logs (supports pagination) โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ ``` -------------------------------- ### Complete Assistant Workflow Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/assistants.md Demonstrates a full assistant workflow: creating an assistant, a thread, adding a user message, running the assistant, waiting for completion, retrieving messages, and cleaning up resources. ```python from dashscope import Assistants, Threads, Messages, Runs from http import HTTPStatus # 1. Create assistant assistant = Assistants.create( model="qwen-max", name="Math Helper", instructions="Help the user with math problems." ) # 2. Create conversation thread thread = Threads.create() # 3. Add user message message = Messages.create( thread_id=thread.id, role="user", content="What is the square root of 16?" ) # 4. Run assistant run = Runs.create( thread_id=thread.id, assistant_id=assistant.id ) # 5. Wait for completion result = Runs.wait(run.id, thread_id=thread.id) if result.status == "completed": # 6. Get all messages (including assistant response) messages = Messages.list(thread_id=thread.id) for msg in messages.data: print(f"{msg.role}: {msg.content}") # 7. Clean up Threads.delete(thread.id) Assistants.delete(assistant.id) ``` -------------------------------- ### Video Generation Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/README.md Synthesize videos from text prompts using the VideoSynthesis API. This example demonstrates the asynchronous task pattern, requiring a subsequent call to `wait` for the result. ```python from dashscope import VideoSynthesis # Text-to-video response = VideoSynthesis.async_call( model="wan2.7-t2v", prompt="A cat playing with a ball of yarn", ) result = VideoSynthesis.wait(response) ``` -------------------------------- ### Define Google-Style Python Docstring Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/docs/README.md Example of a function implementing the Google Python style docstring format. It includes sections for arguments, examples, and return values to ensure consistency and readability. ```python def load(file, file_format=None, **kwargs): """Load data from json/yaml/pickle files. This method provides a unified api for loading data from serialized files. Args: file (str or :obj:`Path` or file-like object): Filename or a file-like object. file_format (str, optional): If not specified, the file format will be inferred from the file extension, otherwise use the specified one. Currently supported formats include "json", "yaml/yml". Examples: >>> load('/path/of/your/file') # file is stored in disk >>> load('https://path/of/your/file') # file is stored on internet >>> load('oss://path/of/your/file') # file is stored in petrel Returns: The content from the file. """ ``` -------------------------------- ### SDK get job information Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Python function signature for retrieving job information. ```python def get(cls, job_id: str, api_key: str = None, workspace: str = None, **kwargs) -> FineTune: ... ``` -------------------------------- ### Create an Assistant using Assistants.create() Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/assistants.md Use this method to create a new AI assistant. Specify the model, name, description, instructions, tools, and file IDs for knowledge bases. Optional parameters include metadata, workspace, API key, and sampling configurations. ```python from dashscope import Assistants assistant = Assistants.create( model="qwen-max", name="Math Tutor", description="Teaches mathematics concepts", instructions="You are an expert math tutor. Explain concepts clearly with examples.", ) print(f"Created assistant: {assistant.id}") ``` -------------------------------- ### Rollout Processor Implementation Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Example implementation of a Rollout Processor for generating agent trajectories. ```python from dashscope.finetune.reinforcement import AbstractRolloutProcessor, RolloutInput, RolloutOutput class DemoRolloutProcessor(AbstractRolloutProcessor): async def process(self, input: RolloutInput) -> RolloutOutput: # Generate trajectory (supports async/def) pass ``` -------------------------------- ### Reward Processor Implementation Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md Example implementation of a Reward Processor for scoring steps or final outputs. ```python from dashscope.finetune.reinforcement import AbstractRewardProcessor, RewardInput, RewardOutput class DemoRewardProcessor(AbstractRewardProcessor): def process(self, input: RewardInput) -> RewardOutput: # Calculate reward score pass ``` -------------------------------- ### Build Documentation via Makefile Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/docs/README.md Command to trigger the documentation build process from the project root directory. Requires a configured Makefile in the environment. ```shell make docs ``` -------------------------------- ### Handle Assistant Creation and Listing Errors Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/assistants.md Demonstrates how to catch exceptions during assistant creation and check the status code for listing assistants. Ensure necessary imports are present. ```python from http import HTTPStatus try: assistant = Assistants.create(model="qwen-max", ...) except Exception as e: print(f"Failed to create assistant: {e}") # Check response status response = Assistants.list() if response.status_code != HTTPStatus.OK: print(f"Error: {response.code}") ``` -------------------------------- ### Group Reward Processor Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/dashscope/finetune/reinforcement/examples/workspace/UserGuide.md An example of a group reward processor that scores a batch of trajectories collectively, useful for ranking scenarios. ```python from dashscope.finetune.reinforcement import AbstractGroupRewardProcessor, GroupRewardInput, GroupRewardOutput class DemoGroupRewardProcessor(AbstractGroupRewardProcessor): def setup(self) -> None: pass async def process(self, input: GroupRewardInput) -> GroupRewardOutput: # Calculate group rewards pass ``` -------------------------------- ### Complete Fine-Tuning Workflow Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/fine-tuning.md Demonstrates the end-to-end process of fine-tuning a model, from uploading training data to deploying and using the fine-tuned model, followed by cleanup. ```python from dashscope import Files, FineTunes, Deployments, Generation from http import HTTPStatus # 1. Prepare and upload training data with open("training.jsonl", "w") as f: f.write('{"messages": [{"role": "user", "content": "Q1"}, {"role": "assistant", "content": "A1"}]} ') upload_response = Files.upload( file_path="training.jsonl", purpose="fine-tune" ) file_id = upload_response.output.id # 2. Start fine-tuning job ft_response = FineTunes.call( model="qwen-turbo", training_file_ids=[file_id], hyper_parameters={"n_epochs": 2} ) job_id = ft_response.output.id print(f"Started job: {job_id}") # 3. Monitor job status import time while True: status_response = FineTunes.get(job_id) job = status_response.output print(f"Status: {job.status}") if job.status == "succeeded": model_name = job.fine_tuned_model print(f"Fine-tuned model: {model_name}") break elif job.status in ["failed", "cancelled"]: print(f"Job failed: {job.status}") exit(1) time.sleep(30) # 4. Deploy the fine-tuned model deploy_response = Deployments.call( model=model_name, capacity=1 ) # 5. Use the deployed model gen_response = Generation.call( model=model_name, messages=[{"role": "user", "content": "Test"}], result_format="message" ) # 6. Clean up Deployments.delete(model_name) Files.delete(file_id) ``` -------------------------------- ### Assistants.create() Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/assistants.md Creates a new AI assistant instance with specified configurations including model, name, description, instructions, tools, and file knowledge bases. ```APIDOC ## Assistants.create() ### Description Create a new assistant. ### Method Signature ```python @classmethod def create( cls, *, model: str, name: str = None, description: str = None, instructions: str = None, tools: List[Dict] = None, file_ids: List[str] = None, metadata: Dict = None, workspace: str = None, api_key: str = None, top_p: float = None, top_k: int = None, temperature: float = None, max_tokens: int = None, **kwargs, ) -> Assistant ``` ### Parameters #### Required Parameters - **model** (str): Model (e.g., "qwen-max") #### Optional Parameters - **name** (str): Display name - **description** (str): Assistant description - **instructions** (str): System instructions/prompt - **tools** (List[Dict]): Tool definitions - **file_ids** (List[str]): Files for knowledge base (default: []) - **metadata** (Dict): Custom key-value pairs - **workspace** (str): DashScope workspace ID - **api_key** (str): API key override - **temperature** (float): Sampling temperature [0, 2) - **top_p** (float): Nucleus sampling (0, 1.0] - **top_k** (int): Top-k sampling - **max_tokens** (int): Max output tokens ### Returns `Assistant` object ### Example ```python from dashscope import Assistants assistant = Assistants.create( model="qwen-max", name="Math Tutor", description="Teaches mathematics concepts", instructions="You are an expert math tutor. Explain concepts clearly with examples.", ) print(f"Created assistant: {assistant.id}") ``` ``` -------------------------------- ### Method and Type Documentation Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/SUMMARY.txt The SDK provides detailed documentation for over 100 methods and 30+ classes, including complete signatures, parameter tables, return types, error conditions, and code examples. ```APIDOC ## Method and Type Documentation Detailed documentation is available for: **Classes Documented:** 30+ - Generation, AioGeneration - MultiModalConversation, AioMultiModalConversation - TextEmbedding, MultiModalEmbedding, AioMultiModalEmbedding - BatchTextEmbedding - ImageSynthesis, VideoSynthesis - SpeechSynthesizer, HttpSpeechSynthesizer, Transcription - Assistants, Threads, Messages, Runs, Steps - Files, FineTunes, Deployments - TextReRank, AioTextReRank - Application, Tokenization, Models, Understanding, CodeGeneration **Methods Documented:** 100+ - Complete method signatures with parameter types. - Return type specifications. - Parameter tables (name, type, required, default, description). - Exception/error conditions. - Working code examples. - Use case patterns. ``` -------------------------------- ### Batch Text Embedding Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/embeddings.md Example demonstrating how to use both the synchronous `call` method and the asynchronous `async_call` followed by `wait` for batch text embeddings. ```APIDOC ## Example Usage ```python from dashscope import BatchTextEmbedding # Option 1: synchronous (wait for result) result = BatchTextEmbedding.call( model="text-embedding-async-v2", url="https://your-bucket/texts.jsonl" ) # Option 2: submit and poll task = BatchTextEmbedding.async_call( model="text-embedding-async-v2", url="https://your-bucket/texts.jsonl" ) result = BatchTextEmbedding.wait(task) ``` ``` -------------------------------- ### Text-to-Image Generation (Basic) Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/image-synthesis.md Demonstrates a basic asynchronous text-to-image generation request and how to wait for and process the result. ```python response = ImageSynthesis.async_call( model="wanx-v1", prompt="A Victorian mansion with gardens" ) result = ImageSynthesis.wait(response) if result.status_code == 200: for image in result.output.results: print(f"Generated: {image.url}") ``` -------------------------------- ### Similarity Matching Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/reranking.md Find the most relevant documents from a corpus based on a given query. This example demonstrates how to use the reranking API for similarity matching and retrieve the original documents. ```python corpus = [ "Python is a programming language.", "Java is a compiled language.", "SQL is for database queries.", "R is used for data analysis.", ] response = TextReRank.call( model="gte-rerank-v2", query="statistical programming", documents=corpus, return_documents=True ) for result in response.output.results: print(f"Rank {result.index}: {result.relevance_score:.2%}") print(f" {result.document}\n") ``` -------------------------------- ### Legacy Conversation API Example Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/other-apis.md This is a legacy method for handling conversations. It is recommended to use the `Generation` API for new development. This example demonstrates adding a user message to the history before calling the conversation API. ```python from dashscope import Conversation, History, HistoryItem history = History() history.add(HistoryItem(role="user", content="Hi")) response = Conversation.call( model="qwen-turbo", prompt="How are you?", history=history ) ``` -------------------------------- ### Complete Assistant Workflow Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/assistants.md Demonstrates a complete workflow for interacting with the DashScope Assistants API, including creating an assistant, a thread, adding messages, running the assistant, and retrieving the response. ```APIDOC ## Complete Assistant Workflow ### Description This example demonstrates the full lifecycle of an assistant interaction, from creation to cleanup. ### Steps 1. **Create Assistant**: Initializes a new assistant with specified model and instructions. 2. **Create Thread**: Starts a new conversation thread. 3. **Add User Message**: Posts a message from the user to the thread. 4. **Run Assistant**: Initiates the assistant's processing of the thread. 5. **Wait for Completion**: Polls for the run to complete. 6. **Get Messages**: Retrieves all messages in the thread, including the assistant's response. 7. **Clean Up**: Deletes the created thread and assistant. ### Usage ```python from dashscope import Assistants, Threads, Messages, Runs from http import HTTPStatus # 1. Create assistant assistant = Assistants.create( model="qwen-max", name="Math Helper", instructions="Help the user with math problems." ) # 2. Create conversation thread thread = Threads.create() # 3. Add user message message = Messages.create( thread_id=thread.id, role="user", content="What is the square root of 16?" ) # 4. Run assistant run = Runs.create( thread_id=thread.id, assistant_id=assistant.id ) # 5. Wait for completion result = Runs.wait(run.id, thread_id=thread.id) if result.status == "completed": # 6. Get all messages (including assistant response) messages = Messages.list(thread_id=thread.id) for msg in messages.data: print(f"{msg.role}: {msg.content}") # 7. Clean up Threads.delete(thread.id) Assistants.delete(assistant.id) ``` ``` -------------------------------- ### Deployments - Get Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/README.md Retrieves information about a specific deployment by its name. ```APIDOC ## Deployments - Get ### Description Retrieves information about a specific deployment by its name. ### Method `Deployments.get()` ### Parameters - `name` (string) - Required - The name of the deployment to retrieve (e.g., "deployed-model-name"). ### Request Example ```python from dashscope import Deployments info = Deployments.get("deployed-model-name") ``` ``` -------------------------------- ### Authentication Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/README.md Demonstrates how to set the API key for authentication, either through code or environment variables. ```python import dashscope # Set API key via code dashscope.api_key = 'your-api-key' # Alternatively, set the DASHSCOPE_API_KEY environment variable. ``` -------------------------------- ### Complete File Upload Workflow Source: https://github.com/dashscope/dashscope-sdk-python/blob/main/_autodocs/api-reference/files.md Demonstrates the end-to-end process of uploading a file for fine-tuning, including preparing data, uploading, using the file in a fine-tuning job, listing files, and cleaning up. ```python from dashscope import Files, FineTunes from http import HTTPStatus # 1. Prepare training data with open("training.jsonl", "w") as f: f.write('{"messages": [{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi!"}]} ') f.write('{"messages": [{"role": "user", "content": "Help"}, {"role": "assistant", "content": "I will help."}]} ') # 2. Upload file upload_response = Files.upload( file_path="training.jsonl", purpose="fine-tune" ) if upload_response.status_code != HTTPStatus.OK: print(f"Upload failed: {upload_response.code}") exit(1) file_id = upload_response.output.id print(f"Uploaded: {file_id}") # 3. Use in fine-tuning job ft_response = FineTunes.call( model="qwen-turbo", training_file_ids=[file_id] ) # 4. List uploaded files list_response = Files.list(purpose="fine-tune") for file in list_response.output.data: print(f" {file.id}: {file.filename}") # 5. Clean up Files.delete(file_id) ```