### Run Get Utility Functions Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Examples of how to call the 'get' utility functions to retrieve specific resources. Uncomment to execute. ```python # wl = get_workload_identity("my-workload-name") # print(wl) # op = get_oauth2_provider("my-oauth2-provider") # print(op) # ap = get_api_key_provider("my-api-key-provider") # print(ap) # sp = get_sts_provider("my-sts-provider") # print(sp) ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Installs the SDK with development dependencies, enabling local development and testing. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Install Dependencies Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_tools/README.md Install the necessary Python libraries for the project. This command should be run in your terminal. ```bash pip install -r requirements.txt ``` -------------------------------- ### LangGraph Agent Example Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md This example demonstrates how to wrap a LangGraph agent as an HTTP server using AgentArtsRuntimeApp. It defines the agent's state, builds a simple graph for processing messages, and exposes an entrypoint handler for invocations. Ensure OPENAI_API_KEY and OPENAI_MODEL_NAME environment variables are set. ```Python # agent.py import os from typing import Dict, Any, TypedDict, Annotated from operator import add from agentarts.sdk import AgentArtsRuntimeApp, RequestContext app = AgentArtsRuntimeApp() class State(TypedDict): messages: Annotated[list, add] query: str response: str class LangGraphAgent: def __init__(self): self.model_name = os.environ.get("OPENAI_MODEL_NAME", "gpt-4o-mini") self._graph = None def _build_graph(self): from langgraph.graph import StateGraph, END from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage, AIMessage llm = ChatOpenAI( model=self.model_name, api_key=os.environ.get("OPENAI_API_KEY"), base_url=os.environ.get("OPENAI_BASE_URL") ) async def process_node(state: State) -> Dict[str, Any]: query = state.get("query", "") messages = state.get("messages", []) or [HumanMessage(content=query)] response = await llm.ainvoke(messages) return { "messages": [AIMessage(content=response.content)], "response": response.content, } workflow = StateGraph(State) workflow.add_node("process", process_node) workflow.set_entry_point("process") workflow.add_edge("process", END) return workflow.compile() async def run(self, query: str) -> Dict[str, Any]: graph = self._graph or self._build_graph() self._graph = graph result = await graph.ainvoke({"messages": [], "query": query, "response": ""}) return {"response": result.get("response", "")} _agent = LangGraphAgent() @app.entrypoint async def handler(payload: Dict[str, Any], context: RequestContext = None) -> Dict[str, Any]: query = payload.get("message", "") return await _agent.run(query) if __name__ == "__main__": app.run() ``` -------------------------------- ### Install AgentArts SDK via pip Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Installs the AgentArts SDK package using pip. This is the standard installation method. ```bash pip install agentarts-sdk ``` -------------------------------- ### Install AgentArts SDK from Source (Windows) Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Installs the AgentArts SDK from its source code repository on Windows, including development dependencies. ```powershell git clone https://github.com/huaweicloud/agentarts-sdk-python.git cd agentarts-sdk-python # Create and activate virtual environment python -m venv venv .\venv\Scripts\Activate.ps1 # Install in development mode pip install -e ".[dev]" ``` -------------------------------- ### Install AgentArts SDK with Optional Dependencies Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Installs the AgentArts SDK with support for specific frameworks like LangChain or LangGraph, or all optional dependencies. ```bash # With LangChain support pip install agentarts-sdk[langchain] # With LangGraph support pip install agentarts-sdk[langgraph] # With all optional dependencies pip install agentarts-sdk[all] ``` -------------------------------- ### Start Local Development Server Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Starts the local development server for the agent. The server typically runs on http://127.0.0.1:8080 and provides endpoints for invocation and health checks. ```bash # Start local development server agentarts dev # Server runs at http://127.0.0.1:8080 # Endpoints: # POST /invocations - Invoke agent # GET /ping - Health check ``` -------------------------------- ### Run Update Workload Identity URLs Example Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Example of how to manually update a workload identity's allowed callback URLs. Uncomment to execute. ```python # test_workload_name = "test-update-w-xxxx" # print(f"Updating workload identity {test_workload_name}...") # # Update to allow multiple URLs # update_workload_identity_urls( # workload_name=test_workload_name, # allowed_urls=["http://localhost:8000/callback", "https://myapp.com/callback"] # ) ``` -------------------------------- ### Install AgentArts SDK from Source (Linux/macOS) Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Installs the AgentArts SDK from its source code repository on Linux or macOS, including development dependencies. ```bash git clone https://github.com/huaweicloud/agentarts-sdk-python.git cd agentarts-sdk-python # Create and activate virtual environment python -m venv venv source venv/bin/activate # Install in development mode pip install -e ".[dev]" ``` -------------------------------- ### Setup FastAPI Callback Server Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/oauth2_example.ipynb Initializes a FastAPI application to handle the callback requests from the Identity Provider. This server listens on http://localhost:8000. ```python app = FastAPI() BASE_URL = "http://localhost:8000" CALLBACK_URL = f"{BASE_URL}/callback" ``` -------------------------------- ### Run Jupyter Lab with Uvicorn Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/README.md This command starts a Jupyter Lab environment using uv, which is useful for running the interactive notebook examples provided in the SDK. ```bash uv run jupyter lab ``` -------------------------------- ### Install and Use Pre-commit Hooks Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/CONTRIBUTING.md Set up pre-commit hooks to automatically run code quality checks before each commit. This helps catch issues early in the development cycle. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Run Update Google OAuth2 Secret Example Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Example of how to manually update an existing Google OAuth2 provider's secret. Uncomment to execute. ```python # test_provider_name = "test-update-p-xxxx" # print(f"Updating provider {test_provider_name}...") # update_google_oauth2_secret( # provider_name=test_provider_name, # client_id="initial-client-id", # new_client_secret="newly-rotated-secret" # ) ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/oauth2_example.ipynb Imports essential libraries for SDK interaction, asynchronous operations, web server setup, and unique identifier generation. ```python import threading import uuid from typing import Any import uvicorn from fastapi import FastAPI, HTTPException, Request from huaweicloudsdkagentidentity.v1 import AuthorizerType from huaweicloudsdkagentidentity.v1.model import UserIdentifier from agentarts.sdk import ( AgentArtsRuntimeContext, IdentityClient, require_access_token, ) from agentarts.sdk.identity.types import OAuth2Vendor ``` -------------------------------- ### Execute Cleanup for Specific Test Patterns Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Provides commented-out examples of how to call the cleanup functions with a specific prefix to remove resources associated with particular test patterns. ```python # cleanup_workload_identities(prefix="oauth-workload-") # cleanup_oauth2_providers(prefix="google-oauth-") ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/CONTRIBUTING.md Illustrates various commit types and scopes according to the Conventional Commits specification, including features, fixes, documentation, refactoring, performance improvements, and breaking changes. ```bash # Feature feat(runtime): add async context support # Bug fix fix(memory): resolve vector store connection timeout # Documentation docs(readme): update installation instructions # Refactoring refactor(tools): simplify code interpreter sandbox # Performance perf(memory): optimize vector search algorithm # Breaking change feat(runtime)!: change AgentRuntime API signature BREAKING CHANGE: The `execute` method now requires an explicit `context` parameter. ``` -------------------------------- ### Define Get STS Provider Function Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Retrieves details for a specific STS credential provider. Requires an initialized 'raw_client'. ```python def get_sts_provider(provider_name: str): """Retrieve details for a specific STS credential provider.""" print(f"Getting STS Provider: {provider_name}...") request = GetStsCredentialProviderRequest(credential_provider_name=provider_name) response = raw_client.get_sts_credential_provider(request) return response.credential_provider ``` -------------------------------- ### Define Get API Key Provider Function Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Retrieves details for a specific API Key credential provider. Assumes 'raw_client' is available. ```python def get_api_key_provider(provider_name: str): """Retrieve details for a specific API Key credential provider.""" print(f"Getting API Key Provider: {provider_name}...") request = GetApiKeyCredentialProviderRequest(credential_provider_name=provider_name) response = raw_client.get_api_key_credential_provider(request) return response.credential_provider ``` -------------------------------- ### Pull Request Title Format Example Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/CONTRIBUTING.md Demonstrates the required format for pull request titles, which aligns with the Conventional Commits specification for consistency. ```bash feat(runtime): add async context support fix(memory): resolve vector store connection timeout docs: update API reference ``` -------------------------------- ### Define Get Workload Identity Function Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Retrieves details for a specific workload identity. Ensure the 'raw_client' is initialized before use. ```python def get_workload_identity(workload_name: str): """Retrieve details for a specific workload identity.""" print(f"Getting Workload Identity: {workload_name}...") request = GetWorkloadIdentityRequest(workload_identity_name=workload_name) response = raw_client.get_workload_identity(request) return response.workload_identity ``` -------------------------------- ### Define System Prompt for Agent Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_tools/README.md Define the system prompt that guides the AI assistant's behavior, specifying its capabilities and usage principles for the Python execution tool. ```python app = AgentArtsRuntimeApp() SYSTEM_PROMPT = """你是一个AI助手,可以使用Python代码执行工具来解决问题。 可用工具: - execute_python_tool(code: str, description: str): 执行Python代码 使用原则: 1. 仅在需要精确计算或复杂逻辑时使用工具 2. 简单问题直接回答,无需工具验证 3. 工具调用最多1-2次,避免重复验证 4. 获得结果后立即返回答案 """ ``` -------------------------------- ### Define Get OAuth2 Provider Function Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Retrieves details for a specific OAuth2 credential provider. Requires an initialized 'raw_client'. ```python def get_oauth2_provider(provider_name: str): """Retrieve details for a specific OAuth2 credential provider.""" print(f"Getting OAuth2 Provider: {provider_name}...") request = GetOauth2CredentialProviderRequest(credential_provider_name=provider_name) response = raw_client.get_oauth2_credential_provider(request) return response.credential_provider ``` -------------------------------- ### Initialize New Agent Project Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Initializes a new agent project using a specified template, such as 'langgraph'. ```bash # Create a new agent project with LangGraph template agentarts init -n my_agent -t langgraph # Available templates: basic, langchain, langgraph, google-adk ``` -------------------------------- ### Set Up Environment Variables for SDK Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/client_manual_example.ipynb Configure necessary environment variables for SDK authentication. Ensure these secrets are not committed to version control. ```python import os # Ensure you DO NOT commit these secrets to version control. # os.environ["HUAWEICLOUD_SDK_AK"] = "your-access-key-id" # os.environ["HUAWEICLOUD_SDK_SK"] = "your-secret-access-key" # os.environ["HUAWEICLOUD_SDK_REGION"] = "ap-southeast-4" # os.environ["HUAWEICLOUD_SDK_PROJECT_ID"] = "your-project-id" # os.environ["HUAWEICLOUD_SDK_DOMAIN_ID"] = "your-domain-id" print("Environment variables ready.") ``` -------------------------------- ### Initialize AgentArts SDK Context and Client Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/api_key_example.ipynb Import necessary SDK components and set the user ID for the runtime context. Then, initialize the IdentityClient with the specified region and SSL verification settings. ```python import uuid from agentarts.sdk import AgentArtsRuntimeContext, IdentityClient, require_api_key # 0. Generate random identifiers for testing random_suffix = uuid.uuid4().hex[:8] user_id = f"user-{random_suffix}" workload_name = f"workload-for-{user_id}" # 1. Set the user ID for context AgentArtsRuntimeContext.set_user_id(user_id) print(f"Context set for User ID: {user_id}") # 2. Initialize IdentityClient using the region from the environment region = os.getenv("HUAWEICLOUD_SDK_REGION", "cn-southwest-301") client = IdentityClient(region=region, ignore_ssl_verification=True) print(f"IdentityClient initialized for region: {region}") ``` -------------------------------- ### Import necessary SDKs and configure credentials Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/sts_token_example.ipynb Imports required modules from Huawei Cloud SDKs and the Agent Arts SDK. It also shows how to set environment variables for credentials, which should not be committed to version control. ```python import json import os import uuid from huaweicloudsdkagentidentity.v1 import AuthorizerType from huaweicloudsdkcore.http.http_config import HttpConfig from huaweicloudsdkiam.v5 import ( CreateAgencyReqBody, CreateAgencyV5Request, IamClient, ) from agentarts.sdk import ( AgentArtsRuntimeContext, IdentityClient, require_sts_token, ) from agentarts.sdk.identity.types import StsCredentials # Manually set your credentials here for testing if not already in your environment. # Ensure you DO NOT commit these secrets to version control. # os.environ["HUAWEICLOUD_SDK_AK"] = "your-access-key-id" # os.environ["HUAWEICLOUD_SDK_SK"] = "your-secret-access-key" # os.environ["HUAWEICLOUD_SDK_REGION"] = "ap-southeast-4" # os.environ["HUAWEICLOUD_SDK_PROJECT_ID"] = "your-project-id" # os.environ["HUAWEICLOUD_SDK_DOMAIN_ID"] = "your-domain-id" print("Environment variables ready.") ``` -------------------------------- ### Configure Huawei Cloud Credentials (Windows Command Prompt) Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Sets Huawei Cloud Access Key (AK) and Secret Key (SK) as environment variables in Windows Command Prompt. ```cmd set HUAWEICLOUD_SDK_AK=your-access-key set HUAWEICLOUD_SDK_SK=your-secret-key ``` -------------------------------- ### Create and Activate Virtual Environment (Linux/macOS) Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Creates and activates a Python virtual environment on Linux or macOS using the venv module. ```bash # Create virtual environment python -m venv venv # Activate virtual environment source venv/bin/activate ``` -------------------------------- ### Configure Huawei Cloud Credentials (Linux/macOS) Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Sets Huawei Cloud Access Key (AK) and Secret Key (SK) as environment variables in Linux or macOS. ```bash export HUAWEICLOUD_SDK_AK="your-access-key" export HUAWEICLOUD_SDK_SK="your-secret-key" ``` -------------------------------- ### Initialize IdentityClient and Create Workload Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/client_manual_example.ipynb Instantiate the IdentityClient with a region and create a workload identity. The workload is created with AuthorizerType.NONE. ```python region = os.getenv("HUAWEICLOUD_SDK_REGION", "ap-southeast-4") client = IdentityClient(region=region, ignore_ssl_verification=True) print(f"IdentityClient initialized for region: {region}") random_suffix = uuid.uuid4().hex[:8] user_id = f"user-{random_suffix}" workload_name = f"manual-workload-{random_suffix}" print(f"Creating workload identity: {workload_name}...") workload = client.create_workload_identity( name=workload_name, authorizer_type=AuthorizerType.NONE ) print(f"Created Workload: {workload.name}") ``` -------------------------------- ### Run All Code Quality Checks Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/CONTRIBUTING.md Execute Black for formatting, isort for imports, mypy for type checking, and Ruff for linting. This command ensures the codebase adheres to established quality standards. ```bash black . isort . mypy agentarts ruff check . # Or run all at once black . && isort . && mypy agentarts && ruff check . ``` -------------------------------- ### Deploy Agent to Huawei Cloud Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Deploys the configured agent to the Huawei Cloud environment. ```bash # Deploy to cloud agentarts deploy ``` -------------------------------- ### Create and Activate Virtual Environment (Windows) Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Creates and activates a Python virtual environment on Windows using the venv module. ```powershell # Create virtual environment python -m venv venv # Activate virtual environment .\venv\Scripts\Activate.ps1 # Or using Command Prompt .\venv\Scripts\activate.bat ``` -------------------------------- ### Fetch API Key Using Manual Token Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/client_manual_example.ipynb Request an API key by manually providing the previously obtained workload access token. This demonstrates resource fetching with direct token usage. ```python provider_name = f"manual-provider-{random_suffix}" print(f"Ensuring API Key provider '{provider_name}' exists...") try: client.create_api_key_credential_provider( name=provider_name, api_key="sk-dummy-key" ) except Exception as e: print(f"Provider might already exist: {e}") print("\nManually fetching API key...") api_key = client.get_resource_api_key( provider_name=provider_name, workload_access_token=workload_access_token ) print(f"Successfully retrieved API Key: {api_key}") ``` -------------------------------- ### Initialize Agent Identity Client and Raw Client Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Initializes the IdentityClient from the SDK and accesses the underlying raw AgentIdentityClient for direct API interactions. Ensure Huawei Cloud AK/SK and region are configured. ```python import os from huaweicloudsdkagentidentity.v1 import ( DeleteApiKeyCredentialProviderRequest, DeleteOauth2CredentialProviderRequest, DeleteStsCredentialProviderRequest, DeleteWorkloadIdentityRequest, GetApiKeyCredentialProviderRequest, GetOauth2CredentialProviderRequest, GetStsCredentialProviderRequest, GetWorkloadIdentityRequest, GoogleOauth2ProviderConfigInput, ListApiKeyCredentialProvidersRequest, ListOauth2CredentialProvidersRequest, ListStsCredentialProvidersRequest, ListWorkloadIdentitiesRequest, Oauth2ProviderConfigInput, UpdateOauth2CredentialProviderReqBody, UpdateOauth2CredentialProviderRequest, UpdateWorkloadIdentityReqBody, UpdateWorkloadIdentityRequest, ) from agentarts.sdk import IdentityClient # Initialize the IdentityClient from the SDK to get the underlying raw client region = os.getenv("HUAWEICLOUD_SDK_REGION", "ap-southeast-4") client = IdentityClient(region=region, ignore_ssl_verification=True) raw_client = client.client # Access the underlying AgentIdentityClient print(f"Utility tools initialized for region: {region}") ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_tools/README.md Import the required modules from LangChain, LangGraph, and AgentArts SDK for building the Agent and using the code interpreter. ```python import json import os from typing import Annotated, TypedDict from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage from langchain_core.tools import tool from langchain_openai import ChatOpenAI from langgraph.graph import END, StateGraph from langgraph.graph.message import add_messages from langgraph.prebuilt import ToolNode from agentarts.sdk import AgentArtsRuntimeApp from agentarts.sdk.tools import code_session ``` -------------------------------- ### Import necessary libraries Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/context_usage_example.ipynb Imports the asyncio library for asynchronous operations and AgentArtsRuntimeContext for context management. ```python import asyncio from agentarts.sdk import AgentArtsRuntimeContext ``` -------------------------------- ### Import Necessary SDK Components Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/client_manual_example.ipynb Import the IdentityClient and AuthorizerType from the SDK. These are required for direct client interaction. ```python import uuid from huaweicloudsdkagentidentity.v1 import AuthorizerType from agentarts.sdk import IdentityClient ``` -------------------------------- ### Initialize Identity Client and Context Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/oauth2_example.ipynb Generates unique identifiers for the session and initializes the IdentityClient. Sets the user ID in the runtime context. ```python # 0. Generate random identifiers for testing random_suffix = uuid.uuid4().hex[:8] user_id = f"user-{random_suffix}" workload_name = f"oauth-workload-{random_suffix}" provider_name = f"google-oauth-{random_suffix}" # 1. Set the user ID for context AgentArtsRuntimeContext.set_user_id(user_id) # 2. Initialize client region = os.getenv("HUAWEICLOUD_SDK_REGION", "ap-southeast-4") client = IdentityClient(region=region, ignore_ssl_verification=True) print(f"Context set for User ID: {user_id}") ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/CONTRIBUTING.md Execute tests and generate an HTML report of code coverage. This helps identify areas of the code that are not adequately tested. ```bash pytest --cov=agentarts --cov-report=html ``` -------------------------------- ### Configure Huawei Cloud Credentials (Windows PowerShell) Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Sets Huawei Cloud Access Key (AK) and Secret Key (SK) as environment variables in Windows PowerShell. ```powershell $env:HUAWEICLOUD_SDK_AK = "your-access-key" $env:HUAWEICLOUD_SDK_SK = "your-secret-key" ``` -------------------------------- ### Execute and verify context isolation Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/context_usage_example.ipynb Spawns multiple asynchronous tasks concurrently using asyncio.gather and verifies that the main context remains unchanged after the tasks complete. ```python print("=== Spawning Isolated Tasks ===") await asyncio.gather( isolated_task("Task A", "user-task-a"), isolated_task("Task B", "user-task-b") ) print("=== Back to Main Context ===") print(f"After tasks, Main User ID is still untouched: {AgentArtsRuntimeContext.get_user_id()}") ``` -------------------------------- ### Configure Agent with LangGraph Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_tools/README.md Configure the Agent using LangGraph by defining the LLM, tools, and the workflow state. The `call_model` function invokes the LLM with the system prompt and messages, while `should_continue` determines if the agent should continue using tools or end. ```python # 创建Agent llm = ChatOpenAI( model="DeepSeek-V3", api_key=os.environ.get("MODEL_API_KEY", ""), base_url=os.environ.get("BASE_URL", ""), max_tokens=1000, temperature=0.7, ) # 创建工具列表 tools = [execute_python_tool] # 工具绑定Agent llm = llm.bind_tools(tools) # 定义graph状态 class AgentState(TypedDict): messages: Annotated[list[BaseMessage], add_messages] def call_model(state: AgentState): """调用模型并返回响应""" if not state["messages"] or all( not isinstance(msg, SystemMessage) for msg in state["messages"] ): messages = [SystemMessage(content=SYSTEM_PROMPT)] + state["messages"] else: messages = state["messages"] response = llm.invoke(messages) return {"messages": [response]} def should_continue(state): """判断是否继续使用工具""" last_message = state["messages"][-1] if isinstance(last_message, AIMessage): has_tool_calls = bool(last_message.tool_calls) if has_tool_calls: return "tools" return END # 创建LangGraph工作流 workflow = StateGraph(AgentState) workflow.add_node("agent", call_model) workflow.add_node("tools", ToolNode(tools)) # 设置入口 workflow.set_entry_point("agent") # 添加边 workflow.add_conditional_edges("agent", should_continue, {"tools": "tools", "__end__": "__end__"}) workflow.add_edge("tools", "agent") agent = workflow.compile() ``` -------------------------------- ### Create an IAM Agency using IAM SDK Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/sts_token_example.ipynb Dynamically creates an IAM agency with a trust policy that allows the 'sts::SetContext' and 'sts:agencies:assume' actions for the 'service.AgentIdentity'. This is a prerequisite for using STS credential providers. ```python # 3. Create an IAM Agency region = os.getenv("HUAWEICLOUD_SDK_REGION", "ap-southeast-4") print("Initializing IAM SDK Client to create a dynamic agency...") hc = HttpConfig.get_default_config() hc.ignore_ssl_verification = True iam_client = ( IamClient.new_builder() .with_http_config(hc) .with_endpoint("https://iam.myhuaweicloud.com") .build() ) try: # Ensure your domain ID is available via env or provider chain domain_id = os.getenv("HUAWEICLOUD_SDK_DOMAIN_ID", "your-domain-id") agency_name = f"sts-agency-{random_suffix}" print(f"Creating dynamic agency '{agency_name}' in domain '{domain_id}'...") policy = { "Version": "5.0", "Statement": [ { "Effect": "Allow", "Action": ["sts:agencies:assume", "sts::SetContext"], "Principal": {"Service": ["service.AgentIdentity"]}, } ], } req_body = CreateAgencyReqBody( agency_name=agency_name, trust_policy=json.dumps(policy), description="Dynamic agency created by unionsdk for STS token example", ) create_response = iam_client.create_agency_v5(CreateAgencyV5Request(body=req_body)) agency_urn = create_response.agency.urn print(f"Successfully created agency.\nURN: {agency_urn}") except Exception as e: print(f"Failed to create agency dynamically (are credentials configured?): {e}") print("Falling back to a dummy URN for testing purposes.") agency_urn = "urn:huaweicloud:iam::123456789:agency:my-agency" ``` -------------------------------- ### Format Code Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Applies code formatting using Black and sorts imports using isort to maintain consistent code style. ```bash black . && isort . ``` -------------------------------- ### Agent Execution and Response Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_tools/README.md This section defines the entry point for the Agent chat application. It invokes the compiled LangGraph agent with the user's query and returns the final response from the Agent. ```python @app.entrypoint def agent_chat(payload: dict): query = "告诉我1到100之间最大的质数" # 运行Agent result = agent.invoke({"messages": [HumanMessage(content=query)]}) return result["messages"][-1].content if __name__ == "__main__": app.run() ``` -------------------------------- ### Initialize the IdentityClient Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/sts_token_example.ipynb Initializes the IdentityClient, which is used to interact with Huawei Cloud services. It takes the region as a parameter and can optionally ignore SSL verification. ```python # 2. Initialize IdentityClient using the region from the environment region = os.getenv("HUAWEICLOUD_SDK_REGION", "ap-southeast-4") client = IdentityClient(region=region, ignore_ssl_verification=True) print(f"IdentityClient initialized for region: {region}") ``` -------------------------------- ### OAuth2 Callback Server Implementation Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/oauth2_example.ipynb Sets up a FastAPI application to handle OAuth2 callback requests, extracting the session URI and completing the resource token authentication. This server runs in a background thread. ```python AgentArtsRuntimeContext.set_oauth2_callback_url(CALLBACK_URL) @app.get("/callback") async def oauth_callback(request: Request) -> dict[str, Any]: params = dict(request.query_params) session_uri = params.get("session_uri") if not session_uri: return {"error": "Missing 'session_uri' parameter"} try: print(f"\n[Server] Binding user {user_id} to session {session_uri}") client.complete_resource_token_auth( session_uri=session_uri, user_identifier=UserIdentifier(user_id=user_id) ) print("[Server] Binding complete! You can return to the notebook.") return { "status": "success", "message": "User successfully bound. Return to notebook.", } except Exception as e: print(f"[Server] Error binding token: {e}") raise HTTPException(status_code=500, detail=str(e)) # Start the server in a background thread def run_server(): uvicorn.run(app, host="0.0.0.0", port=8000, log_level="warning") server_thread = threading.Thread(target=run_server, daemon=True) server_thread.start() print(f"Background callback server running on {BASE_URL}") ``` -------------------------------- ### Set Huawei Cloud Credentials Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/oauth2_example.ipynb Manually set your Huawei Cloud AK/SK and other credentials as environment variables for testing. Ensure these are not committed to version control. ```python import os # Manually set your credentials here for testing if not already in your environment. # Ensure you DO NOT commit these secrets to version control. # os.environ["HUAWEICLOUD_SDK_AK"] = "your-access-key-id" # os.environ["HUAWEICLOUD_SDK_SK"] = "your-secret-access-key" # os.environ["HUAWEICLOUD_SDK_REGION"] = "ap-southeast-4" # os.environ["HUAWEICLOUD_SDK_PROJECT_ID"] = "your-project-id" # os.environ["HUAWEICLOUD_SDK_DOMAIN_ID"] = "your-domain-id" print("Environment variables ready.") ``` -------------------------------- ### Set and retrieve base context values Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/context_usage_example.ipynb Sets initial user ID and OAuth2 callback URL in the root scope and then retrieves them to demonstrate baseline context. ```python print("=== Main Context Setup ===") AgentArtsRuntimeContext.set_user_id("user-main") AgentArtsRuntimeContext.set_oauth2_callback_url("http://main.example.com/callback") print(f"Current User ID: {AgentArtsRuntimeContext.get_user_id()}") print(f"Current Callback URL: {AgentArtsRuntimeContext.get_oauth2_callback_url()}") ``` -------------------------------- ### Set Huawei Cloud Credentials and Region Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/api_key_example.ipynb Configure your Huawei Cloud AK/SK, region, and project/domain IDs. These can be set as environment variables. Ensure secrets are not committed to version control. Optionally, customize the Agent Identity service endpoint. ```python import os # Manually set your credentials here for testing if not already in your environment. # Ensure you DO NOT commit these secrets to version control. # os.environ["HUAWEICLOUD_SDK_AK"] = "your-access-key-id" # os.environ["HUAWEICLOUD_SDK_SK"] = "your-secret-access-key" # os.environ["HUAWEICLOUD_SDK_REGION"] = "cn-southwest-301" # os.environ["HUAWEICLOUD_SDK_PROJECT_ID"] = "your-project-id" # os.environ["HUAWEICLOUD_SDK_DOMAIN_ID"] = "your-domain-id" # (Optional) Customize the endpoint for a specific region # os.environ["HUAWEICLOUD_SDK_REGION_AGENTIDENTITY_CN_SOUTHWEST_301"] = "https://agent-identity-open.cn-southwest-301.beta.myhuaweicloud.com" print("Environment variables ready.") ``` -------------------------------- ### Define the Query Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_tools/README.md Define the user's query that will be passed to the Agent for processing. ```python query = "告诉我1到100之间最大的质数" ``` -------------------------------- ### Create API Key Credential Provider Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/api_key_example.ipynb Register an API Key Credential Provider with the identity service. A unique provider name is generated for the session. Handle potential pre-existence errors. ```python # 3. Create an API Key Credential Provider api_key_provider_name = f"my-llm-provider-{random_suffix}" print(f"Creating API Key Credential Provider: {api_key_provider_name}...") try: provider = client.create_api_key_credential_provider( name=api_key_provider_name, api_key="sk-dummy-api-key-12345" ) print(f"Successfully created provider: {provider.name}") except Exception as e: print(f"Provider might already exist or creation failed: {e}") ``` -------------------------------- ### Set Access Token and Call Decorated Function Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/api_key_example.ipynb Inject the retrieved access token into the AgentArtsRuntimeContext and then call a function decorated with @require_api_key. The decorator will automatically use the token to fetch and pass the API key. ```python # 5. Set the retrieved token in the context AgentArtsRuntimeContext.set_workload_access_token(token) # 6. Call the decorated function print("Calling the decorated function...") call_llm() print("Execution complete!") ``` -------------------------------- ### Run All Tests Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/CONTRIBUTING.md Execute all tests in the project using pytest. This is a fundamental step to ensure code correctness and stability. ```bash pytest ``` -------------------------------- ### Create OAuth2 Credential Provider Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/oauth2_example.ipynb Registers an OAuth2 provider with the SDK. This action generates a callback URL that must be configured in your Identity Provider's dashboard. ```python # 3. Create OAuth2 Credential Provider print(f"Ensuring '{provider_name}' OAuth2 credential provider exists...") try: provider = client.create_oauth2_credential_provider( name=provider_name, vendor=OAuth2Vendor.GOOGLEOAUTH2, client_id="dummy-client-id", client_secret="dummy-client-secret", ) print(f"Created '{provider_name}' OAuth2 credential provider.") print("\n=== OAUTH2 CONFIGURATION REQUIRED ===") print(f"Callback URL: {provider.callback_url}") print( "ACTION: Please add this Callback URL to your Identity Provider (e.g., Google Cloud Console) as an Authorized Redirect URI." ) print("=======================================\n") except Exception as e: print(f"OAuth2 credential provider might already exist or creation failed: {e}") ``` -------------------------------- ### Create STS Credential Provider Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/sts_token_example.ipynb Creates an STS credential provider by referencing the previously created agency URN. This provider will be used to obtain STS tokens. ```python # 4. Create STS Credential Provider provider_name = f"sts-iam-provider-{random_suffix}" print(f"Ensuring STS Credential Provider '{provider_name}' exists...") try: provider = client.create_sts_credential_provider( name=provider_name, agency_urn=agency_urn ) print(f"Created Provider: {provider.name}") except Exception as e: print(f"Note: Provider might already exist or creation failed: {e}") ``` -------------------------------- ### Set Token and Call Decorated Function Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/sts_token_example.ipynb Sets the retrieved workload access token in the AgentArtsRuntimeContext and then calls the decorated function. The decorator uses the context token to assume the agency and inject temporary credentials. ```python # 7. Set the retrieved token in the context AgentArtsRuntimeContext.set_workload_access_token(token) # 7. Call the decorated function print("Calling the decorated function...") access_huawei_resource() print("Execution complete!") ``` -------------------------------- ### Create Workload Identity Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/sts_token_example.ipynb Creates a workload identity with the authorizer type set to NONE for simplicity. This is the initial step in setting up agent identity. ```python workload = client.create_workload_identity( name=workload_name, authorizer_type=AuthorizerType.NONE ) print(f"Created Workload: {workload.name}") ``` -------------------------------- ### Define Function with Automatic API Key Injection Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/api_key_example.ipynb Decorate a target function with `@require_api_key` to enable automatic API key injection. The SDK manages the API key retrieval and passing to the decorated function. ```python # Note: We use the dynamically generated provider name from the previous step @require_api_key(provider_name=api_key_provider_name, ignore_ssl_verification=True) def call_llm(api_key: str | None = None) -> None: """Calls an LLM service with an API key. Args: api_key: The API key injected automatically by the SDK. """ print(f"Using API Key: {api_key}") # Your actual LLM call logic would go here... print("Decorated function defined.") ``` -------------------------------- ### Demonstrate context isolation in asynchronous tasks Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/context_usage_example.ipynb Defines an asynchronous task that sets its own user ID, demonstrating that context variables are local to the task and do not affect the main context or other tasks. ```python async def isolated_task(task_name: str, new_user_id: str) -> None: print(f"[{task_name}] Started. Initial User ID inherited from parent: {AgentArtsRuntimeContext.get_user_id()}") # Set a new context specific to this task AgentArtsRuntimeContext.set_user_id(new_user_id) print(f"[{task_name}] Updated User ID: {AgentArtsRuntimeContext.get_user_id()}") # Simulate some work await asyncio.sleep(0.5) print(f"[{task_name}] Finished. Final User ID: {AgentArtsRuntimeContext.get_user_id()}") ``` -------------------------------- ### Define Cleanup Function for API Key Providers Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Defines a function to list and delete API Key credential providers, optionally filtering by a name prefix. It uses the raw client to interact with the ListApiKeyCredentialProviders and DeleteApiKeyCredentialProvider APIs. ```python def cleanup_api_key_providers(prefix: str | None = None): """List and delete API Key credential providers.""" print(f"Listing API Key providers (prefix='{prefix or ''}')...") response = raw_client.list_api_key_credential_providers(ListApiKeyCredentialProvidersRequest()) providers = response.credential_providers or [] deleted_count = 0 for p in providers: if not prefix or p.name.startswith(prefix): print(f" Deleting API Key Provider: {p.name}") raw_client.delete_api_key_credential_provider( DeleteApiKeyCredentialProviderRequest(credential_provider_name=p.name)) deleted_count += 1 print(f"Cleanup complete. Deleted {deleted_count} provider(s).") ``` -------------------------------- ### Configure Deployment Region Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Sets the deployment region for the agent using the agentarts CLI. ```bash # Configure region agentarts config set region cn-southwest-2 ``` -------------------------------- ### Configure Environment Variables for Agent Runtime Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Edits the .agentarts_config.yaml file to set environment variables for the agent's runtime, such as API keys and model names. ```yaml runtime: environment_variables: - key: OPENAI_API_KEY value: "your-openai-api-key" - key: OPENAI_MODEL_NAME value: "gpt-4o-mini" # Optional: gpt-4o, gpt-4-turbo, etc. - key: OPENAI_BASE_URL value: "" # Optional: custom API endpoint ``` -------------------------------- ### Retrieve Workload Access Token Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/client_manual_example.ipynb Obtain an access token for the created workload. This token will be used for manual authentication in subsequent API calls. ```python print(f"Getting workload access token for user {user_id}...") workload_access_token = client.create_workload_access_token( workload_name=workload.name, user_id=user_id ) print("Token successfully retrieved!") ``` -------------------------------- ### Run Specific Test File Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/CONTRIBUTING.md Execute tests only within a specified test file. Useful for focusing on a particular set of tests during development. ```bash pytest tests/unit/test_core.py ``` -------------------------------- ### Run Specific Test Function Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/CONTRIBUTING.md Execute a single, specific test function within a test file. Ideal for targeted debugging and verification. ```bash pytest tests/unit/test_core.py::test_import ``` -------------------------------- ### Fetch Workload Access Token Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/oauth2_example.ipynb Retrieves a workload access token using the created workload identity and user ID. This token is then set in the AgentArtsRuntimeContext. ```python # 5. Get and set workload access token print("Getting workload access token...") token = client.create_workload_access_token( workload_name=workload_name, user_id=user_id ) AgentArtsRuntimeContext.set_workload_access_token(token) print("Workload access token successfully retrieved and set in context.") ``` -------------------------------- ### Type Checking Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Performs static type checking on the agentarts package using mypy to catch type-related errors. ```bash mypy agentarts ``` -------------------------------- ### Define Update Workload Identity URLs Function Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Updates the allowed OAuth2 return URLs for a workload identity using raw SDK models. Requires an initialized 'raw_client'. ```python def update_workload_identity_urls(workload_name: str, allowed_urls: list[str]): """Update the allowed OAuth2 return URLs for a workload identity using raw SDK models.""" print(f"Updating workload identity '{workload_name}' with allowed URLs: {allowed_urls}...") # Construct the update request using the raw SDK models update_body = UpdateWorkloadIdentityReqBody( allowed_resource_oauth2_return_urls=allowed_urls ) request = UpdateWorkloadIdentityRequest( workload_identity_name=workload_name, body=update_body ) # Invoke the update via the raw AgentIdentityClient response = raw_client.update_workload_identity(request) print(f"Successfully updated workload identity: {response.workload_identity.name}") return response.workload_identity ``` -------------------------------- ### Define Python Code Execution Tool Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_tools/README.md Define the `execute_python_tool` function, which is decorated with `@tool` to be recognized by LangChain. This tool executes Python code within a sandbox environment using the `code_session` from AgentArts SDK. ```python @tool def execute_python_tool(code: str, description: str) -> str | None: """Execute Python Code in the sandbox""" if description: code = f"# {description}\n{code}" print(f"\n Generated Code: {code}") # 需配置环境 HUAWEICLOUD_SDK_CODE_INTERPRETER_API_KEY api_key = os.environ.get( "HUAWEICLOUD_SDK_CODE_INTERPRETER_API_KEY", "" ) # 配置环境变量后,api_key无需在代码中传递亦可正常工作 with code_session("your_region", "your_code_interpreter_name", api_key=api_key) as code_client: response = code_client.invoke( operate_type="execute_code", api_key=api_key, arguments={ "code": code, "language": "python", "clear_context": False, }, ) return json.dumps(response["result"]) ``` -------------------------------- ### Define Cleanup Function for Workload Identities Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Defines a function to list and delete workload identities, optionally filtering by a name prefix. It uses the raw client to interact with the ListWorkloadIdentities and DeleteWorkloadIdentity APIs. ```python def cleanup_workload_identities(prefix: str | None = None): """List and delete workload identities, optionally filtered by prefix.""" print(f"Listing workload identities (prefix='{prefix or ''}')...") response = raw_client.list_workload_identities(ListWorkloadIdentitiesRequest()) workloads = response.workload_identities or [] deleted_count = 0 for wl in workloads: if not prefix or wl.name.startswith(prefix): print(f" Deleting Workload Identity: {wl.name}") raw_client.delete_workload_identity(DeleteWorkloadIdentityRequest(workload_identity_name=wl.name)) deleted_count += 1 print(f"Cleanup complete. Deleted {deleted_count} workload(s).") ``` -------------------------------- ### Create a Workload Identity Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/sts_token_example.ipynb Registers a uniquely named workload identity with the Identity service. The 'authorizer_type' parameter is mandatory for this operation. ```python # 5. Create a workload identity print(f"Creating workload identity: {workload_name}...") # 'authorizer_type' is now a mandatory parameter in the underlying SDK. ``` -------------------------------- ### Fetch Workload Access Token Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/sts_token_example.ipynb Requests a workload access token using the registered workload and user ID. This token is required by the SDK to authorize fetching STS credentials. ```python # 6. Get workload access token print(f"Getting workload access token for {workload.name} and user {user_id}...") token = client.create_workload_access_token( workload_name=workload.name, user_id=user_id ) print("Workload access token successfully retrieved.") ``` -------------------------------- ### Define Cleanup Function for STS Providers Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Defines a function to list and delete STS credential providers, optionally filtering by a name prefix. It uses the raw client to interact with the ListStsCredentialProviders and DeleteStsCredentialProvider APIs. ```python def cleanup_sts_providers(prefix: str | None = None): """List and delete STS credential providers.""" print(f"Listing STS providers (prefix='{prefix or ''}')...") response = raw_client.list_sts_credential_providers(ListStsCredentialProvidersRequest()) providers = response.credential_providers or [] deleted_count = 0 for p in providers: if not prefix or p.name.startswith(prefix): print(f" Deleting STS Provider: {p.name}") raw_client.delete_sts_credential_provider( DeleteStsCredentialProviderRequest(credential_provider_name=p.name)) deleted_count += 1 print(f"Cleanup complete. Deleted {deleted_count} provider(s).") ``` -------------------------------- ### Lint Code Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/README.md Checks the codebase for style and potential errors using Ruff to enforce code quality standards. ```bash ruff check . ``` -------------------------------- ### Define Cleanup Function for OAuth2 Providers Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/utility_tools.ipynb Defines a function to list and delete OAuth2 credential providers, optionally filtering by a name prefix. It uses the raw client to interact with the ListOauth2CredentialProviders and DeleteOauth2CredentialProvider APIs. ```python def cleanup_oauth2_providers(prefix: str | None = None): """List and delete OAuth2 credential providers.""" print(f"Listing OAuth2 providers (prefix='{prefix or ''}')...") response = raw_client.list_oauth2_credential_providers(ListOauth2CredentialProvidersRequest()) providers = response.credential_providers or [] deleted_count = 0 for p in providers: if not prefix or p.name.startswith(prefix): print(f" Deleting OAuth2 Provider: {p.name}") raw_client.delete_oauth2_credential_provider( DeleteOauth2CredentialProviderRequest(credential_provider_name=p.name)) deleted_count += 1 print(f"Cleanup complete. Deleted {deleted_count} provider(s).") ``` -------------------------------- ### Create Workload Identity Source: https://github.com/huaweicloud/agentarts-sdk-python/blob/main/examples/agent_identity/oauth2_example.ipynb Creates a workload identity and specifies allowed callback URLs for the OAuth2 flow. This is a prerequisite for fetching workload access tokens. ```python # 4. Create a workload identity print(f"Creating workload identity: {workload_name}...") workload = client.create_workload_identity( name=workload_name, authorizer_type=AuthorizerType.NONE, allowed_resource_oauth2_return_urls=["http://localhost:8000/callback"], ) print(f"Created Workload: {workload.name}") ```