### Install Go OpenAI SDK Source: https://docs.laozhang.ai/api-capabilities/openai-sdk Install the go-openai SDK for Go applications using the go get command. This is necessary for integrating with the LaoZhang API. ```bash go get github.com/sashabaranov/go-openai ``` -------------------------------- ### Verify Configuration and Start Codex Source: https://docs.laozhang.ai/scenarios/programming/codex-cli Check if the environment variables are set correctly and then launch the Codex CLI. This confirms your setup is ready. ```bash # 验证环境变量 echo $OPENAI_API_KEY echo $OPENAI_BASE_URL # 启动 Codex codex ``` -------------------------------- ### Install Codex CLI via npm Source: https://docs.laozhang.ai/scenarios/programming/codex-cli Install the Codex CLI globally using npm. This is the recommended method for quick setup. ```bash npm install -g @openai/codex ``` -------------------------------- ### Example Prompt Construction Source: https://docs.laozhang.ai/api-reference/images An example demonstrating how to combine different elements into a detailed prompt for image generation. ```plaintext A majestic eagle (主体) in photorealistic style (风格) soaring above mountain peaks (环境) during golden hour (光照) highly detailed, 8K resolution (质量) ``` -------------------------------- ### Example-Driven Prompting Source: https://docs.laozhang.ai/api-reference/claude Providing concrete examples within the prompt guides Claude to understand and replicate desired output formats and styles. This technique is useful for ensuring consistency and clarity in responses. ```python prompt = """ 请按照以下示例的格式回答: 示例: 问题:[示例问题] 回答:[示例回答格式] 现在请回答:[实际问题] """ ``` -------------------------------- ### Install and Run Local Models with Ollama Source: https://docs.laozhang.ai/scenarios/programming/cline Install Ollama and run various local language models for development. Ensure Ollama is installed before running these commands. ```bash # Install Ollama and run local models ollama run deepseek-coder:6.7b ollama run qwen2.5-coder:7b ollama run codellama:13b ``` -------------------------------- ### Install Python OpenAI SDK Source: https://docs.laozhang.ai/api-capabilities/openai-sdk Install the official OpenAI Python library using pip. This is the first step to using the SDK. ```bash pip install openai ``` -------------------------------- ### Python Code Example Source: https://docs.laozhang.ai/faq/balance-query-api A Python script demonstrating how to call the Get Account Balance API using the `requests` library. ```APIDOC ## Python Example for Get Account Balance This Python script uses the `requests` library to fetch account balance information. The `requests` library automatically handles gzip decompression. ```python import requests # Configuration url = "https://api.laozhang.ai/api/user/self" access_token = "YOUR_ACCESS_TOKEN" # Replace with your token # Request Headers headers = { 'Accept': 'application/json', 'Authorization': access_token, 'Content-Type': 'application/json' } # Send Request try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # Raise an exception for bad status codes # Process Response data = response.json() user_data = data['data'] # Extract core information quota = user_data['quota'] used_quota = user_data['used_quota'] request_count = user_data['request_count'] # Calculate USD amounts (500,000 quota = $1.00 USD) remaining_usd = quota / 500000 used_usd = used_quota / 500000 # Print results print(f"Remaining Quota: ${remaining_usd:.2f} USD ({quota:,} quota)") print(f"Used Quota: ${used_usd:.2f} USD ({used_quota:,} quota)") print(f"Request Count: {request_count:,} requests") except requests.exceptions.RequestException as e: print(f"Request failed: {e}") except KeyError as e: print(f"Failed to parse response: Missing key {e}") except Exception as e: print(f"An unexpected error occurred: {e}") ``` ``` -------------------------------- ### Python: Quick Prototyping Examples Source: https://docs.laozhang.ai/api-capabilities/nano-banana-image Illustrates using the image generator for rapid prototyping of product concepts and UI designs. These examples show how to generate images for specific design ideas. ```python # 生成产品概念图 concept = generator.generate_image( "现代简约风格的智能手表设计,白色背景,专业产品摄影" ) # 生成UI界面 ui_design = generator.generate_image( "移动应用的登录界面设计,深色主题,现代扁平化风格" ) ``` -------------------------------- ### Batch Processing Configuration Example (Bash) Source: https://docs.laozhang.ai/api-capabilities/flux-image-generation Example configuration for the batch processing script, including defining the prompt and the array of image pairs to be processed. ```bash # 提示词配置 BATCH_PROMPT="Look at the left image and right image. Transfer the pattern/design from the left image to the clothes of the model in the right image, with the size being 2/3 of the width of the chest, located in the middle. Make it look natural and well-integrated." # 图片对数组 IMAGE_PAIRS=( "https://example.com/pattern1.jpg|https://example.com/model1.jpg" "https://example.com/design2.jpg|https://example.com/shirt2.jpg" ) ``` -------------------------------- ### Install Node.js OpenAI SDK Source: https://docs.laozhang.ai/api-capabilities/openai-sdk Install the official OpenAI Node.js library using npm. This is required before configuring and using the SDK. ```bash npm install openai ``` -------------------------------- ### Python Example (with polling logic) Source: https://docs.laozhang.ai/api-capabilities/veo/veo-31-async-api A complete Python code example demonstrating how to create a video task, poll for its status, and handle potential errors. ```Python import requests import time import os API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.laozhang.ai/v1" # Step 1: Create video task def create_video_task(prompt, model="veo-3.1", image_paths=None): """Creates a video generation task. Args: prompt: Video generation prompt. model: Model name. image_paths: Image paths, can be: - None: Text-to-video - str: Single image path - list: Multiple image paths (start/end frame mode, max 2) """ url = f"{BASE_URL}/videos" headers = {"Authorization": f"Bearer {API_KEY}"} if image_paths: # Unified list processing if isinstance(image_paths, str): image_paths = [image_paths] # Image-to-video: Upload images using multipart/form-data files = [] for path in image_paths: if not os.path.exists(path): raise FileNotFoundError(f"Image file not found: {path}") files.append(("input_reference", (os.path.basename(path), open(path, 'rb'), "image/jpeg"))) data = {"model": model, "prompt": prompt} response = requests.post(url, headers=headers, files=files, data=data) # Close file handles for _, (_, f, _) in files: f.close() else: # Text-to-video: Use JSON format headers["Content-Type"] = "application/json" data = {"model": model, "prompt": prompt} response = requests.post(url, headers=headers, json=data) response.raise_for_status() return response.json() # Step 2: Poll for status def wait_for_video(video_id, poll_interval=5, timeout=600): """Waits for video generation to complete.""" url = f"{BASE_URL}/videos/{video_id}" headers = {"Authorization": f"Bearer {API_KEY}"} start_time = time.time() while True: # Check for timeout if time.time() - start_time > timeout: raise TimeoutError(f"Video generation timed out ({timeout} seconds)") # Query status response = requests.get(url, headers=headers) response.raise_for_status() task = response.json() status = task["status"] print(f"Status: {status}") if status == "completed": return task elif status == "failed": raise Exception("Generation failed") # Wait and retry time.sleep(poll_interval) # Example Usage: # try: # # Create a text-to-video task # prompt = "A serene landscape with a flowing river." # task = create_video_task(prompt=prompt, model="veo-3.1") # video_id = task["id"] # print(f"Task created with ID: {video_id}") # # # Wait for completion # completed_task = wait_for_video(video_id) # print("Video generation completed!") # print(f"Video URL: {completed_task.get('url')}") # Note: URL is only available after fetching content separately or if the status response includes it. # # except FileNotFoundError as e: # print(e) # except TimeoutError as e: # print(e) # except Exception as e: # print(f"An error occurred: {e}") ``` -------------------------------- ### cURL Examples Source: https://docs.laozhang.ai/api-capabilities/veo/examples Examples of how to use cURL to interact with the Laozhang AI Video API. ```APIDOC ## cURL Commands ### Submit Task ```bash curl -X POST "https://api.laozhang.ai/veo/v1/api/video/submit" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your-api-key" \ -d '{ \ "prompt": "一只猫咪在雨夜散步", \ "model": "veo3" \ }' ``` ### Get Task Status ```bash curl -X GET "https://api.laozhang.ai/veo/v1/api/video/status/YOUR_TASK_ID" \ -H "Authorization: Bearer your-api-key" ``` ``` -------------------------------- ### Install Node.js Dependencies Source: https://docs.laozhang.ai/api-capabilities/veo/examples Install the axios library for making HTTP requests in Node.js. ```bash npm install axios ``` -------------------------------- ### Python: Prompt Optimization Example Source: https://docs.laozhang.ai/api-capabilities/nano-banana-image Contrasts a simple prompt with a detailed one for image generation. This example emphasizes the importance of descriptive prompts for achieving better results, showing how to provide more context and style guidance. ```python # ❌ 过于简单 prompt = "cat" # ✅ 详细描述 prompt = """ 一只橘色虎斑猫坐在窗边, 金色的夕阳洒在它身上, 背景是温馨的家居环境, 专业宠物摄影风格, 温暖柔和的氛围 """ ``` -------------------------------- ### Markdown Prompt Optimization Example Source: https://docs.laozhang.ai/scenarios/chat/chatgpt-next-web Example of structuring a prompt in Markdown format for role-setting, task description, and output requirements. ```markdown # 角色设定 你是一位经验丰富的[具体角色] # 任务说明 请帮我[具体任务] # 输出要求 - 要求1 - 要求2 ``` -------------------------------- ### Node.js Example for Chat Completions Source: https://docs.laozhang.ai/api-manual Provides a Node.js example for interacting with the chat completions API. ```javascript const OpenAI = require('openai'); const client = new OpenAI({ apiKey: 'YOUR_API_KEY', baseURL: 'https://api.laozhang.ai/v1' }); async function chatCompletion() { try { const response = await client.chat.completions.create({ model: 'gpt-4o-mini', messages: [ {"role": "system", "content": "你是一个有用的AI助手。"}, {"role": "user", "content": "你好!请介绍一下自己。"} ], temperature: 0.7, max_tokens: 1000 }); console.log(response.choices[0].message.content); } catch (error) { console.error('API调用错误:', error); } } chatCompletion(); ``` -------------------------------- ### Troubleshooting Guide Source: https://docs.laozhang.ai/api-capabilities/veo/troubleshooting Step-by-step guides for resolving common issues such as tasks remaining in a 'processing' state or generating unsatisfactory results. ```APIDOC ## Troubleshooting Guide ### Task Stuck in Processing State 1. **Check Task Duration:** Verify if the task duration exceeds the normal processing time (refer to model documentation). 2. **Validate Task ID:** Ensure you are using the correct task ID for queries. 3. **Check API Status:** Visit the status page or contact support to confirm service status. 4. **Retry Submission:** If the task exceeds 30 minutes, it may have timed out; please resubmit. ### Unsatisfactory Generation Quality * **Prompt Optimization:** ```python # Before optimization prompt = "cat" # After optimization prompt = """ An orange British Shorthair cat lying lazily on a soft sofa in a sunny living room, afternoon sunlight streaming through the window onto the cat, 4K resolution, warm tones """ ``` * **Use Reference Images:** ```python # Add high-quality reference images images = [ "https://example.com/cat-reference-1.jpg", "https://example.com/cat-reference-2.jpg" ] ``` * **Enable Enhancements:** ```python # Enable prompt enhancement enhance_prompt = True ``` * **Select Appropriate Model:** ```python # Choose the Pro version for high-quality requirements model = "veo3-pro" ``` ``` -------------------------------- ### Start Claude Code in Project Directory Source: https://docs.laozhang.ai/scenarios/programming/claude-code Navigate to your project directory and start the Claude Code assistant. The tool will display API configuration information upon first launch. ```bash # 进入项目目录 cd ~/Desktop/my-project # 启动 Claude Code claude ``` -------------------------------- ### Install Codex CLI from Source Source: https://docs.laozhang.ai/scenarios/programming/codex-cli Install the Codex CLI by cloning the repository and building from source. This method is useful for developers who want to contribute or modify the code. ```bash git clone https://github.com/openai/codex.git cd codex npm install npm link ``` -------------------------------- ### Verify Software Installation Source: https://docs.laozhang.ai/scenarios/programming/codex-cli Run these commands in your terminal to check if Git, Node.js, and npm are installed correctly. Ensure Node.js version is 22 or higher. ```bash git --version node --version npm --version ``` -------------------------------- ### Guide Image Transitions with Specific Prompts in Python Source: https://docs.laozhang.ai/api-capabilities/veo/veo-31-troubleshooting Improve the naturalness of image transitions by providing prompts that explicitly guide the transition style and ensure consistency between images. Demonstrates prompts that lack and include transition guidance. ```python # ❌ 没有过渡指导 prompt = "两张图片" # ✅ 明确过渡 prompt = "从第一张图平滑过渡到第二张图,采用淡入淡出效果,保持连贯性" ``` -------------------------------- ### Create Video Task (Image to Video - Start and End Frames) Source: https://docs.laozhang.ai/api-capabilities/veo/veo-31-async-api Generate a video with a smooth transition by providing two images as the start and end frames. Upload images using multipart/form-data. Replace YOUR_API_KEY with your actual API key. ```bash curl -X POST "https://api.laozhang.ai/v1/videos" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F "model=veo-3.1-landscape-fl" \ -F "prompt=让这个画面动起来,加点未来科技感" \ -F "input_reference=@start_frame.jpg" \ -F "input_reference=@end_frame.jpg" ``` ```json { "id": "video_xyz789", "object": "video", "created": 1762181833, "status": "queued", "model": "veo-3.1-landscape-fl" } ``` -------------------------------- ### Example Usage: Image-to-Video Source: https://docs.laozhang.ai/api-capabilities/sora2/async-api Demonstrates how to call the `generate_video_from_image_async` function with a local image path and a text prompt, specifying video size and duration. ```python # 图生视频 generate_video_from_image_async( image_path="/path/to/your/image.png", prompt="让这张图片中的场景动起来,增加自然的动态效果", size="1280x720", # 横屏 seconds="10" # 10秒 ) ``` -------------------------------- ### cURL Code Examples Source: https://docs.laozhang.ai/faq/balance-query-api Examples demonstrating how to call the Get Account Balance API using cURL, including handling compressed responses. ```APIDOC ## cURL Examples for Get Account Balance ### Basic Request This example shows a basic cURL request. Ensure you include the `--compressed` option as the API returns gzip compressed content. ```bash curl --compressed 'https://api.laozhang.ai/api/user/self' \ -H 'Accept: application/json' \ -H 'Authorization: YOUR_ACCESS_TOKEN' \ -H 'Content-Type: application/json' ``` ### Quick Test with jq This example uses environment variables and `jq` for a quick test, extracting core information. ```bash export LAOZHANG_TOKEN='YOUR_ACCESS_TOKEN' curl --compressed -s 'https://api.laozhang.ai/api/user/self' \ -H 'Accept: application/json' \ -H "Authorization: $LAOZHANG_TOKEN" \ -H 'Content-Type: application/json' | \ jq '.data | {quota, used_quota, request_count}' ``` **Note**: The `-s` option hides the progress meter, and `--compressed` automatically decompresses the gzip response. ``` -------------------------------- ### Python - Complete Workflow for Video and Character Management Source: https://docs.laozhang.ai/api-capabilities/sora2/character This comprehensive example demonstrates the full workflow: generating an initial video, creating a character from that video, and then reusing the character in a new video generation. It includes steps for checking video generation status. ```python import requests import openai import time API_KEY = "YOUR_API_KEY" BASE_URL = "https://api.laozhang.ai" # 步骤 1:生成初始视频(异步 API) print("步骤 1:生成初始视频...") video_response = requests.post( f"{BASE_URL}/v1/videos", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}" }, json={ "model": "sora-2", "prompt": "一个可爱的卡通角色在跳舞", "size": "1280x720", "seconds": "10" } ) task = video_response.json() task_id = task["id"] print(f"视频任务 ID: {task_id}") # 步骤 2:等待视频生成完成 print("步骤 2:等待视频生成...") while True: status_response = requests.get( f"{BASE_URL}/v1/videos/{task_id}", headers={"Authorization": f"Bearer {API_KEY}"} ) status = status_response.json() if status["status"] == "completed": print("视频生成完成!") break elif status["status"] == "failed": print("视频生成失败") exit(1) time.sleep(10) # 步骤 3:从视频创建角色 print("步骤 3:创建角色...") character_response = requests.post( f"{BASE_URL}/sora/v1/characters", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}" }, json={ "model": "sora-2-character", "from_task": task_id, "timestamps": "1,3" } ) character = character_response.json() username = character["username"] print(f"角色创建成功!Username: @{username}") # 步骤 4:使用角色生成新视频 print("步骤 4:使用角色生成新视频...") new_video_response = requests.post( f"{BASE_URL}/v1/videos", headers={ "Content-Type": "application/json", "Authorization": f"Bearer {API_KEY}" }, json={ "model": "sora-2", "prompt": f"@{username} 在舞台上表演,观众欢呼", "size": "1280x720", "seconds": "10" } ) new_task = new_video_response.json() print(f"新视频任务 ID: {new_task['id']}") ``` -------------------------------- ### Example Usage: Submit and Wait for Video Source: https://docs.laozhang.ai/api-capabilities/veo/examples Demonstrates submitting a video generation task and then waiting for its completion. Assumes `submit_video` and `wait_for_completion` functions are available. ```shell # 使用示例 echo "提交视频生成任务..." task_id=$(submit_video "一只猫咪在雨夜散步") echo "任务ID: $task_id" wait_for_completion "$task_id" ``` -------------------------------- ### Prompt Optimization Example Source: https://docs.laozhang.ai/api-capabilities/vision-understanding Demonstrates recommended practices for crafting specific and clear prompts, contrasting with vague or unhelpful ones. ```python # ❌ 不推荐:模糊的提示 prompt = "看看这是什么" ``` ```python # ✅ 推荐:具体明确的提示 prompt = """ 请从以下几个方面分析这张图片: 1. 主要对象:识别图片中的主要物体或人物 2. 场景环境:描述拍摄地点和环境特征 3. 色彩构图:分析配色方案和构图特点 4. 情感氛围:图片传达的情绪或氛围 5. 可能用途:这张图片适合用于什么场景 """ ``` -------------------------------- ### Get Account Balance Response Example Source: https://docs.laozhang.ai/faq/balance-query-api This is a successful response from the user self API, showing account balance and usage details. The response is gzipped. ```json { "success": true, "message": null, "data": { "username": "your_username", "display_name": "Your Name", "quota": 24997909, "used_quota": 10027091, "request_count": 339, "group": "svip" } } ``` -------------------------------- ### Text-to-Video Generation Source: https://docs.laozhang.ai/api-capabilities/sora2/api-reference Use this example to generate a video from a text prompt. Ensure you replace 'YOUR_API_KEY' with your actual API key. ```bash curl -X POST "https://api.laozhang.ai/v1/chat/completions" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "sora_video2", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "一只可爱的猫咪在阳光明媚的花园里玩球" } ] } ]' }' ``` ```python import openai client = openai.OpenAI( api_key="YOUR_API_KEY", base_url="https://api.laozhang.ai/v1" ) response = client.chat.completions.create( model="sora_video2", messages=[ { "role": "user", "content": [ { "type": "text", "text": "一只可爱的猫咪在阳光明媚的花园里玩球" } ] } ] ) print(response.choices[0].message.content) ``` ```javascript const OpenAI = require('openai'); const client = new OpenAI({ apiKey: 'YOUR_API_KEY', baseURL: 'https://api.laozhang.ai/v1' }); const response = await client.chat.completions.create({ model: 'sora_video2', messages: [ { role: 'user', content: [ { type: 'text', text: '一只可爱的猫咪在阳光明媚的花园里玩球' } ] } ] }); console.log(response.choices[0].message.content); ``` -------------------------------- ### Design Effective System Prompts Source: https://docs.laozhang.ai/api-reference/openai Craft detailed system prompts to guide the AI's behavior and expertise. This example defines a Python programming expert with specific coding standards and response requirements. ```python # 好的系统消息示例 system_prompt = "" 你是一个专业的Python编程专家,具有以下特点: 1. 代码风格遵循PEP8规范 2. 注重代码可读性和性能 3. 提供详细的注释和说明 4. 给出多种解决方案对比 请用简洁明了的语言回答,并提供可执行的代码示例。 "" ``` -------------------------------- ### Embeddings Request (Python SDK) Source: https://docs.laozhang.ai/api-manual Use the OpenAI Python SDK to generate embeddings. Ensure you have installed the library and configured your API key and base URL. This example shows how to retrieve the embedding vector and its dimension. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.laozhang.ai/v1" ) response = client.embeddings.create( model="text-embedding-ada-002", input="这是一段需要向量化的文本示例" ) # 获取向量 embedding = response.data[0].embedding print(f"向量维度: {len(embedding)}") print(f"前5个值: {embedding[:5]}") ``` -------------------------------- ### Example Usage: Text-to-Video Source: https://docs.laozhang.ai/api-capabilities/sora2/async-api Demonstrates how to call the `generate_video_async` function with a text prompt, specifying video size and duration. ```python if __name__ == "__main__": # 文生视频 generate_video_async( prompt="一只可爱的猫咪在阳光明媚的花园里玩球", size="1280x720", # 横屏 seconds="15" # 15秒 ) ``` -------------------------------- ### Basic Chat with Claude 3.5 Sonnet (Node.js) Source: https://docs.laozhang.ai/api-reference/claude Initiate a chat conversation with Claude 3.5 Sonnet using Node.js. Install the OpenAI Node.js library, provide your API key, and set the base URL to the LaoZhang API. This example demonstrates sending a system message and a user query. ```javascript import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: 'YOUR_API_KEY', baseURL: 'https://api.laozhang.ai/v1' }); const completion = await openai.chat.completions.create({ model: 'claude-3-5-sonnet-20241022', messages: [ { role: 'system', content: '你是一个专业的AI助手,擅长分析和解决复杂问题' }, { role: 'user', content: '请分析一下当前人工智能发展的主要趋势和挑战' } ], max_tokens: 1000, temperature: 0.7 }); console.log(completion.choices[0].message.content); ``` -------------------------------- ### Full Video Generation Workflow (Python) Source: https://docs.laozhang.ai/api-capabilities/sora2/official-forward This example demonstrates a complete video generation workflow in Python, including creating a video from a text prompt, polling for its status, and downloading the final video. It utilizes the previously defined functions. ```python # 完整流程示例 if __name__ == "__main__": # 文生视频 job = create_video( prompt="A golden retriever playing fetch on a sunny beach", model="sora-2", seconds="8", size="1280x720" ) print(f"任务已创建: {job['id']}") # 等待完成 result = poll_status(job["id"]) print("视频生成完成!") # 下载视频 download_video(job["id"], "my_video.mp4") # 图生视频示例 # job2 = create_video_from_image( # prompt="The scene comes alive with gentle movement", # image_path="reference.jpg", # model="sora-2", # seconds="4", # size="1280x720" # ) ``` -------------------------------- ### Python: Complete Video Generation Example Source: https://docs.laozhang.ai/api-capabilities/seedance2-video-generation This script demonstrates how to create a video generation task, poll its status, and download the video upon completion. Ensure your API_KEY is set as an environment variable. The script handles task creation, status checking with a loop and sleep, and saving the video file. ```python import os import time import requests API_KEY = os.environ["API_KEY"] BASE_URL = "https://api.laozhang.ai/v1" headers = { "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json", } payload = { "model": "doubao-seedance-2-0-fast-260128", "prompt": "第一人称视角果茶广告,8秒,快节奏剪辑,展示苹果果茶制作与成品,清爽风格", "ratio": "16:9", "duration": 8, "watermark": False, "generate_audio": True, } create_resp = requests.post(f"{BASE_URL}/videos", headers=headers, json=payload, timeout=60) create_resp.raise_for_status() task_id = create_resp.json()["id"] while True: query_resp = requests.get(f"{BASE_URL}/videos/{task_id}", headers=headers, timeout=60) query_resp.raise_for_status() task = query_resp.json() status = task.get("status") if status == "completed": video_url = task.get("video_url") or task.get("url") video_resp = requests.get(video_url, timeout=120) video_resp.raise_for_status() with open(f"{task_id}.mp4", "wb") as f: f.write(video_resp.content) break if status == "failed": raise RuntimeError(task.get("error") or task) time.sleep(20) ``` -------------------------------- ### Install Python Dependencies Source: https://docs.laozhang.ai/api-capabilities/veo/examples Install the requests library for making HTTP requests in Python. ```bash pip install requests ``` -------------------------------- ### Java Client Example Source: https://docs.laozhang.ai/api-capabilities/veo/examples A Java client demonstrating how to use the Laozhang AI Video API to submit tasks and poll for status. ```APIDOC ```java import com.google.gson.Gson; import okhttp3.*; import java.io.IOException; import java.util.concurrent.TimeUnit; public class VEOVideoClient { private final String baseUrl; private final String apiKey; private final OkHttpClient client; private final Gson gson; public VEOVideoClient(String baseUrl, String apiKey) { this.baseUrl = baseUrl; this.apiKey = apiKey; this.client = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); this.gson = new Gson(); } public static class SubmitRequest { String prompt; String model; boolean enhance_prompt; String[] images; public SubmitRequest(String prompt, String model, boolean enhancePrompt) { this.prompt = prompt; this.model = model; this.enhance_prompt = enhancePrompt; } } public static class ApiResponse { boolean success; Data data; public static class Data { String taskId; String status; Result result; public static class Result { String video_url; } } } public String submitTask(String prompt, String model, boolean enhancePrompt) throws IOException { SubmitRequest request = new SubmitRequest(prompt, model, enhancePrompt); String json = gson.toJson(request); RequestBody body = RequestBody.create( json, MediaType.parse("application/json")); Request httpRequest = new Request.Builder() .url(baseUrl + "/veo/v1/api/video/submit") .post(body) .addHeader("Authorization", "Bearer " + apiKey) .addHeader("Content-Type", "application/json") .build(); try (Response response = client.newCall(httpRequest).execute()) { if (!response.isSuccessful()) { throw new IOException("提交失败: " + response); } ApiResponse apiResponse = gson.fromJson( response.body().string(), ApiResponse.class); return apiResponse.data.taskId; } } public ApiResponse getStatus(String taskId) throws IOException { Request request = new Request.Builder() .url(baseUrl + "/veo/v1/api/video/status/" + taskId) .addHeader("Authorization", "Bearer " + apiKey) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { throw new IOException("查询失败: " + response); } return gson.fromJson( response.body().string(), ApiResponse.class); } } public static void main(String[] args) throws Exception { VEOVideoClient client = new VEOVideoClient( "https://api.laozhang.ai", "your-api-key"); // 提交任务 String taskId = client.submitTask( "一只猫咪在雨夜散步", "veo3", true); System.out.println("任务已提交,ID: " + taskId); // 轮询状态 while (true) { Thread.sleep(10000); // 等待10秒 ApiResponse status = client.getStatus(taskId); String currentStatus = status.data.status; if ("completed".equals(currentStatus)) { System.out.println("视频生成成功!"); System.out.println("视频URL: " + status.data.result.video_url); break; } else if ("failed".equals(currentStatus)) { System.out.println("生成失败"); break; } System.out.println("任务进行中... 状态: " + currentStatus); } } } ``` ``` -------------------------------- ### Basic Editing Example Source: https://docs.laozhang.ai/api-capabilities/image-edit Example of how to perform a basic image edit using the Image.create_edit method. ```python import openai # Edit image response = openai.Image.create_edit( image=open("original.png", "rb"), mask=open("mask.png", "rb"), prompt="A modern glass skyscraper with reflective windows", n=1, size="1024x1024" ) # Get the edited image URL edited_image_url = response['data'][0]['url'] print(f"Edited image URL: {edited_image_url}") ``` -------------------------------- ### Moderation API - Batch Moderation Example Source: https://docs.laozhang.ai/api-capabilities/moderation This example shows how to moderate multiple text inputs in a single API request. ```APIDOC ## POST /v1/moderations (Batch) ### Description Submit an array of texts to the Moderation API for efficient batch processing. ### Method POST ### Endpoint /v1/moderations ### Parameters #### Request Body - **input** (array of strings) - Required - An array of text strings to moderate. ### Request Example ```json { "input": [ "第一段文本", "第二段文本", "第三段文本" ] } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the moderation request. - **model** (string) - The model used for moderation. - **results** (array) - A list of moderation results, corresponding to each input text. - **flagged** (boolean) - Whether the content was flagged as inappropriate. - **categories** (object) - A map of category names to boolean flags. - **category_scores** (object) - A map of category names to their confidence scores. #### Response Example ```json { "id": "mod-xxxxxxxxxxxxxxxxxxxx", "model": "text-moderation-latest", "results": [ { "flagged": false, "categories": { ... }, "category_scores": { ... } }, { "flagged": true, "categories": { "hate": true, ... }, "category_scores": { "hate": 0.95, ... } } ] } ``` ``` -------------------------------- ### Prompt Optimization Examples in Python Source: https://docs.laozhang.ai/api-capabilities/gpt-image-1 These Python snippets illustrate how to improve image generation results by providing detailed descriptions, specifying styles, and defining composition and perspective. ```python # 基础提示词 prompt_basic = "a cat" # 优化后的提示词 prompt_detailed = "a fluffy white Persian cat sitting on a vintage velvet cushion, soft natural lighting, professional photography, shallow depth of field" ``` ```python styles = [ "in the style of Studio Ghibli anime", "photorealistic, professional photography", "digital art, concept art style", "oil painting, impressionist style", "minimalist, flat design illustration" ] ``` ```python compositions = [ "close-up portrait, centered composition", "wide angle landscape shot, rule of thirds", "aerial view, bird's eye perspective", "low angle shot, dramatic perspective" ] ``` -------------------------------- ### Prompt Optimization Examples Source: https://docs.laozhang.ai/api-capabilities/flux-image-generation Demonstrates effective prompt engineering for Flux image generation, including simple vs. detailed prompts, using prompt upsampling, and artistic style prompts. ```python # ❌ 过于简单 prompt = "cat" # ✅ 详细描述 prompt = """ A majestic orange tabby cat sitting by a window, golden hour lighting, soft focus background, professional pet photography style, warm and cozy atmosphere """ # ✅ 利用 prompt_upsampling 增强简单提示词 enhanced_result = generate_flux_image( prompt="cat by window", prompt_upsampling=True # AI 会自动扩展和优化提示词 ) # ✅ 艺术风格提示词 artistic_prompt = """ A surreal landscape painting in the style of Salvador Dali, melting clocks draped over twisted trees, vibrant sunset colors bleeding into a starry night sky, hyper-detailed, dreamlike atmosphere """ ``` -------------------------------- ### Moderation API - Basic Example Source: https://docs.laozhang.ai/api-capabilities/moderation This example demonstrates how to use the Moderation API to check a single piece of text for harmful content. ```APIDOC ## POST /v1/moderations ### Description Use AI to detect harmful content in text, supporting the identification of violence, hate speech, sexual content, and more. ### Method POST ### Endpoint /v1/moderations ### Parameters #### Request Body - **input** (string or array of strings) - Required - The text content to moderate. ### Request Example ```json { "input": "这是一段需要审核的文本内容" } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the moderation request. - **model** (string) - The model used for moderation. - **results** (array) - A list of moderation results, one for each input. - **flagged** (boolean) - Whether the content was flagged as inappropriate. - **categories** (object) - A map of category names to boolean flags indicating if the content belongs to that category. - **category_scores** (object) - A map of category names to their respective confidence scores (0-1). #### Response Example ```json { "id": "mod-xxxxxxxxxxxxxxxxxxxx", "model": "text-moderation-latest", "results": [ { "flagged": false, "categories": { "hate": false, "hate/threatening": false, "harassment": false, "harassment/threatening": false, "self-harm": false, "self-harm/intent": false, "self-harm/instructions": false, "sexual": false, "sexual/minors": false, "violence": false, "violence/graphic": false }, "category_scores": { "hate": 0.0001, "hate/threatening": 0.00001, "harassment": 0.002, "harassment/threatening": 0.00005, "self-harm": 0.00001, "self-harm/intent": 0.00001, "self-harm/instructions": 0.00001, "sexual": 0.00001, "sexual/minors": 0.00001, "violence": 0.00001, "violence/graphic": 0.00001 } } ] } ``` ``` -------------------------------- ### Install Claude Code CLI Source: https://docs.laozhang.ai/scenarios/programming/claude-code Install the Claude Code command-line interface globally using npm. Requires Node.js 18 or higher. ```bash npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Java Example for Chat Completions Source: https://docs.laozhang.ai/api-manual Demonstrates how to make a chat completion request using Java with OkHttp and Gson. ```java import okhttp3.*; import com.google.gson.Gson; import java.io.IOException; import java.util.*; public class LaoZhangExample { private static final String API_KEY = "YOUR_API_KEY"; private static final String BASE_URL = "https://api.laozhang.ai/v1"; public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient(); Gson gson = new Gson(); // 构建请求体 Map requestBody = new HashMap<>(); requestBody.put("model", "gpt-4o-mini"); requestBody.put("temperature", 0.7); requestBody.put("max_tokens", 1000); List> messages = Arrays.asList( Map.of("role", "system", "content", "你是一个有用的AI助手。"), Map.of("role", "user", "content", "你好!请介绍一下自己。") ); requestBody.put("messages", messages); RequestBody body = RequestBody.create( gson.toJson(requestBody), MediaType.parse("application/json") ); Request request = new Request.Builder() .url(BASE_URL + "/chat/completions") .addHeader("Authorization", "Bearer " + API_KEY) ``` -------------------------------- ### Python Image Generation Example Source: https://docs.laozhang.ai/api-capabilities/gpt-image-1 Example Python code demonstrating how to generate images using the GPT-Image-1 model and the OpenAI Python client. ```APIDOC ## Python Image Generation Example ### Description This example shows how to use the `openai.Image.create` method to generate images with various parameters and how to download the generated images. ### Method N/A ### Endpoint N/A ### Request Example ```python import openai import requests from PIL import Image from io import BytesIO # Configuration (ensure this is set before calling functions) openai.api_base = "https://api.laozhang.ai/v1" openai.api_key = "your-api-key" # Function to generate images def generate_image(prompt, size="auto", quality="auto", output_format="png", n=1): try: response = openai.Image.create( model="gpt-image-1", prompt=prompt, n=n, size=size, quality=quality, output_format=output_format ) return [item['url'] for item in response['data']] except Exception as e: print(f"Error generating image: {e}") return None # Function to generate advanced images with compression def generate_advanced_image(prompt, compression=None): params = { "model": "gpt-image-1", "prompt": prompt, "size": "1536x1024", "quality": "high", "output_format": "jpeg" if compression else "png", "background": "transparent" } if compression: params["output_compression"] = compression try: response = openai.Image.create(**params) return response['data'][0]['url'] except Exception as e: print(f"Error: {e}") return None # Function to download and save an image def save_image(url, filename): response = requests.get(url) img = Image.open(BytesIO(response.content)) img.save(filename) print(f"Image saved as {filename}") # Example usage prompts = [ "A futuristic city with flying cars and neon lights", "A cozy coffee shop in autumn with warm lighting", "An abstract art piece with vibrant colors and geometric shapes" ] for i, prompt in enumerate(prompts): print(f"Generating: {prompt}") urls = generate_image(prompt) if urls: save_image(urls[0], f"image_{i+1}.png") # Example with advanced settings (JPEG compression) advanced_prompt = "A minimalist logo design for a tech company" advanced_url = generate_advanced_image(advanced_prompt, compression=50) if advanced_url: save_image(advanced_url, "advanced_logo.jpg") ``` ```