Skip to main content

优雅的RCK (Relational Calculate Kernel) Python SDK

Project description

RCK Python SDK - Programming Guide

An elegant Python SDK that uses RCK (Relational Calculate Kernel) as an intelligent function kernel.

PyPI version Python Version

🚀 Quick Start

Installation

pip install rck-python-sdk

Basic Usage

from rck_sdk import RCKClient

# Initialize client
client = RCKClient(api_key="your-api-key")

# Use RCK as intelligent function kernel
result = client.compute.custom_compute(
    text="Spring has arrived, all things are reviving",
    task="Analyze sentiment and generate corresponding poetry"
)
print(result.data)

📋 Complete Example

Here's a comprehensive example demonstrating all major SDK features:

from rck_sdk import RCKClient

# Initialize client
client = RCKClient(api_key="your-api-key")

def run_complete_example():
    """Complete SDK feature demonstration"""
    
    print("=== RCK Python SDK Complete Example ===\n")
    
    # 1. Test connection
    print("1. Testing connection...")
    connection_test = client.test_connection()
    if connection_test["status"] == "success":
        print("✅ Connection successful")
    else:
        print(f"❌ Connection failed: {connection_test['message']}")
        return
    
    # 2. Text analysis
    print("\n2. Text Analysis Example:")
    poem_text = "Moonlight before my bed, looks like frost on the ground. I raise my head to see the moon, lower it to think of home."
    
    analysis_result = client.compute.analyze(
        text=poem_text,
        task="Analyze the emotion and theme of this poetry",
        output_format="basic_analysis"
    )
    
    print(f"Original text: {poem_text}")
    print(f"Analysis result:")
    for key, value in analysis_result.data.items():
        print(f"  {key}: {value}")
    
    # 3. Translation functionality
    print("\n3. Translation Example:")
    translation_result = client.compute.translate(
        text=poem_text,
        target_language="French",
        include_cultural_notes=True
    )
    
    print(f"French translation: {translation_result.data.get('translation', 'N/A')}")
    if 'cultural_notes' in translation_result.data:
        print(f"Cultural notes: {translation_result.data['cultural_notes'][:100]}...")
    
    # 4. Custom schema computation
    print("\n4. Custom Schema Example:")
    custom_schema = {
        "type": "object",
        "properties": {
            "poem": {"type": "string", "description": "Created poetry"},
            "creative_process": {"type": "string", "description": "Creative thinking process"},
            "style_notes": {"type": "string", "description": "Style explanation"}
        },
        "required": ["poem"]
    }
    
    poem_creation = client.compute.custom_compute(
        text="Spring flowers blooming in the garden",
        task="Create a poem based on this theme",
        output_schema=custom_schema,
        style="modern free verse",
        mood="joyful and peaceful"
    )
    
    print(f"Created poem: {poem_creation.data.get('poem', 'N/A')}")
    if 'creative_process' in poem_creation.data:
        print(f"Creative process: {poem_creation.data['creative_process'][:100]}...")
    
    # 5. Image generation
    print("\n5. Image Generation Example:")
    image_result = client.image.generate(
        prompt="A serene mountain lake reflecting the sky",
        composition="Wide panoramic view showcasing natural beauty",
        lighting="Soft morning sunlight creating peaceful atmosphere",
        style="Traditional Chinese landscape painting style with ink wash"
    )
    
    if image_result.success:
        print(f"✅ Image generation successful: {image_result.count} images created")
        
        # Save images (optional)
        try:
            saved_files = client.image.save_images(image_result, "example_landscape", ".")
            print(f"Images saved: {saved_files}")
        except Exception as e:
            print(f"Image saving failed: {e}")
    else:
        print("❌ Image generation failed")
    
    # 6. Multi-style batch generation
    print("\n6. Batch Style Generation Example:")
    styles = [
        "Traditional Chinese ink wash painting",
        "European classical oil painting style",
        "Modern abstract art style"
    ]
    
    batch_results = []
    for style in styles:
        try:
            result = client.image.generate(
                prompt="Peaceful lake reflecting distant mountains",
                composition="Classic composition with harmonious balance",
                lighting="Natural lighting, soft and bright",
                style=style
            )
            batch_results.append({
                "style": style,
                "success": result.success,
                "count": result.count if result.success else 0
            })
        except Exception as e:
            batch_results.append({
                "style": style,
                "success": False,
                "error": str(e)
            })
    
    print("Batch generation results:")
    for result in batch_results:
        status = "✅" if result["success"] else "❌"
        print(f"  {status} {result['style'][:30]}... - {result.get('count', 0)} images")
    
    # 7. Multimodal creation with resources
    print("\n7. Multimodal Creation Example:")
    multimodal_result = client.compute.create_poem(
        inspiration="Feel the artistic conception depicted in these images",
        style="five-character quatrain",
        resources=[
            {"nature_scene": "https://example.com/nature.jpg"},
            {"sunset_view": "https://example.com/sunset.jpg"}
        ]
    )
    
    if "poem" in multimodal_result.data:
        print(f"Multimodal creation result: {multimodal_result.data['poem']}")
    else:
        print("Multimodal creation completed (check full response for details)")
    
    # 8. Advanced workflow: Poem to Image
    print("\n8. Advanced Workflow - Poem to Scene to Image:")
    
    # Step 1: Convert poem to scene description
    scene_schema = {
        "type": "object",
        "properties": {
            "scene_description": {
                "type": "object",
                "properties": {
                    "main_subjects": {"type": "string"},
                    "lighting": {"type": "string"},
                    "composition": {"type": "string"},
                    "style": {"type": "string"}
                }
            }
        }
    }
    
    original_poem = "Empty mountains, no one in sight, but hearing human voices echo. Returning light enters deep forest, again illuminating green moss."
    
    scene_result = client.compute.custom_compute(
        text=original_poem,
        task="Analyze the poem content and create detailed visual scene description",
        output_schema=scene_schema,
        target_art_style="Traditional Chinese landscape painting"
    )
    
    if "scene_description" in scene_result.data:
        scene_desc = scene_result.data["scene_description"]
        print(f"Scene conversion successful:")
        print(f"  Main subjects: {scene_desc.get('main_subjects', 'N/A')}")
        
        # Step 2: Generate image from scene description
        workflow_image = client.image.generate(
            prompt=scene_desc.get("main_subjects", "Poetic landscape scene"),
            composition=scene_desc.get("composition", "Classic composition"),
            lighting=scene_desc.get("lighting", "Natural lighting"),
            style=scene_desc.get("style", "Traditional Chinese landscape painting")
        )
        
        if workflow_image.success:
            print(f"  ✅ Workflow completed: Poem → Scene → Image ({workflow_image.count} images)")
        else:
            print(f"  ❌ Image generation step failed")
    else:
        print("Scene description conversion failed")
    
    print("\n=== Example Complete ===")
    print("This example demonstrates:")
    print("• Basic text analysis and translation")
    print("• Custom schema and output formatting")
    print("• Single and batch image generation")
    print("• Multimodal resource processing")
    print("• Advanced multi-step workflows")

# Run the complete example
if __name__ == "__main__":
    # Replace with your actual API key
    client = RCKClient(api_key="your-api-key-here")
    run_complete_example()

Expected Output

When you run the complete example, you should see output similar to:

=== RCK Python SDK Complete Example ===

1. Testing connection...
✅ Connection successful

2. Text Analysis Example:
Original text: Moonlight before my bed, looks like frost on the ground. I raise my head to see the moon, lower it to think of home.
Analysis result:
  emotion: nostalgic and melancholic
  theme: homesickness and longing
  analysis: This classical Chinese poem expresses deep feelings of homesickness...

3. Translation Example:
French translation: Devant mon lit, la clarté de la lune, on dirait du givre sur le sol...
Cultural notes: This is one of the most famous poems by Li Bai, representing the classical Chinese literary tradition...

4. Custom Schema Example:
Created poem: Spring flowers dance in morning light, / Petals whisper secrets bright...
Creative process: I focused on capturing the joyful essence of spring blooms...

5. Image Generation Example:
✅ Image generation successful: 1 images created
Images saved: ['example_landscape_1.png']

6. Batch Style Generation Example:
Batch generation results:
  ✅ Traditional Chinese ink wash painting... - 1 images
  ✅ European classical oil painting style... - 1 images
  ✅ Modern abstract art style... - 1 images

7. Multimodal Creation Example:
Multimodal creation result: Mountain peaks touch azure sky, / River flows through valley green...

8. Advanced Workflow - Poem to Scene to Image:
Scene conversion successful:
  Main subjects: Empty mountain valley with ancient forest, moss-covered rocks, filtered sunlight
  ✅ Workflow completed: Poem → Scene → Image (1 images)

=== Example Complete ===

🧠 RCK Compute Engine Core Concepts

RCK compute engine is based on two core components: Start Point and Path, allowing you to encapsulate complex AI logic into simple Python functions.

Start Point: Define Initial State

start_point is the input for computation, containing two parts:

  • startPoint (string): Core text prompt
  • resource (array, optional): Additional non-text resources like images
# Pure text input
{
    "start_point": {
        "startPoint": "Moonlight before my bed, looks like frost on the ground"
    }
}

# Multimodal input (text + images)
{
    "start_point": {
        "startPoint": "Please combine the desolation of 'Image One' with the vastness of 'Image Two' to describe a scene.",
        "resource": [
            {"Image One": "https://url.to/image1.png"},
            {"Image Two": "https://url.to/image2.png"}
        ]
    }
}

Path: Apply Constraints and Define Goals

path is a declarative constraint on the transformation process:

  • expectPath (string): Core instruction telling AI "what to do"
  • Custom Fields (any): Any custom fields as auxiliary constraints
{
    "path": {
        "expectPath": "Analyze the emotional tone of the poetry and create a modern poem with corresponding mood",
        "style": "modern free verse",
        "mood": "tranquil and profound",
        "target_length": "4-6 lines"
    }
}

🎯 Recommended Usage Pattern: Functional Encapsulation

Use RCK as the intelligent kernel of functions, encapsulating complex AI logic into simple Python functions:

Example 1: Sentiment Analysis Function

def analyze_emotion(text, language="english"):
    """Analyze text sentiment using RCK engine"""
    
    result = client.compute.custom_compute(
        text=text,
        task="Analyze the emotional tendency and intensity of the text",
        output_schema={
            "type": "object",
            "properties": {
                "emotion": {"type": "string"},
                "intensity": {"type": "number"},
                "keywords": {"type": "array"}
            }
        },
        language=language,
        analysis_depth="detailed"
    )
    
    return result.data

# Use the function
emotion_result = analyze_emotion("Today is sunny and I feel particularly good")
print(f"Emotion: {emotion_result['emotion']}")
print(f"Intensity: {emotion_result['intensity']}")

Example 2: Intelligent Summary Generation Function

def intelligent_summary(content, max_length=100, style="professional"):
    """Generate intelligent summary using RCK engine"""
    
    result = client.compute.custom_compute(
        text=content,
        task=f"Generate a summary within {max_length} words",
        style=style,
        focus="core viewpoints",
        output_format="concise and clear"
    )
    
    return result.data.get('summary', '')

# Use the function
long_text = "This is a very long article content..."
summary = intelligent_summary(long_text, max_length=50, style="academic")
print(summary)

Example 3: Multimodal Creation Function

def create_poem_from_image(image_url, poem_style="five-character quatrain"):
    """Create poetry based on image"""
    
    result = client.compute.custom_compute(
        text="Please create poetry based on the artistic conception of the image",
        task="Observe image content, feel its artistic conception, and create poetry in corresponding style",
        resources=[{"inspiration_image": image_url}],
        output_schema={
            "type": "object",
            "properties": {
                "poem": {"type": "string"},
                "inspiration": {"type": "string"},
                "mood": {"type": "string"}
            }
        },
        style=poem_style,
        cultural_background="classical literature"
    )
    
    return result.data

# Use the function
poem_result = create_poem_from_image(
    "https://example.com/sunset.jpg", 
    "seven-character regulated verse"
)
print(f"Poem: {poem_result['poem']}")
print(f"Inspiration: {poem_result['inspiration']}")

Example 4: Complex Logic Workflow Function

def complex_analysis_workflow(data, analysis_type="comprehensive"):
    """Complex analysis workflow using Mermaid diagram to define logic"""
    
    mermaid_flow = """
    graph TD
        A[Input Analysis] --> B{Determine Type}
        B -->|Text| C[Text Sentiment Analysis]
        B -->|Data| D[Data Pattern Recognition]
        C --> E[Generate Suggestions]
        D --> E[Generate Suggestions]
        E --> F[Output Results]
    """
    
    result = client.compute.custom_compute(
        text=data,
        task=f"Analyze according to the following workflow: {mermaid_flow}",
        analysis_type=analysis_type,
        depth="deep analysis",
        output_schema={
            "type": "object",
            "properties": {
                "analysis_result": {"type": "string"},
                "suggestions": {"type": "array"},
                "confidence": {"type": "number"}
            }
        }
    )
    
    return result.data

# Use the function
analysis = complex_analysis_workflow(
    "User feedback data...", 
    "comprehensive"
)

🌟 Unlimited Flexibility in Language and Format

RCK supports extreme flexibility:

Any Language

# English processing
result = client.compute.custom_compute(
    text="To be or not to be, that is the question",
    task="Analyze the philosophical connotations of this Shakespeare quote"
)

# Chinese processing  
result = client.compute.custom_compute(
    text="春眠不觉晓,处处闻啼鸟",
    task="Translate to English while preserving poetic sentiment"
)

# Multi-language mixing
result = client.compute.custom_compute(
    text="Hello world, Bonjour le monde",
    task="Identify languages and translate uniformly to English"
)

Any Format

# Mathematical formulas
result = client.compute.custom_compute(
    text="f(x) = x^2 - 4x + 3",
    task="Find the minimum value of the function and describe the graph",
    custom_code="def calculate_min(x): return x**2 - 4*x + 3"
)

# Code analysis
result = client.compute.custom_compute(
    text="""
    def fibonacci(n):
        if n <= 1:
            return n
        return fibonacci(n-1) + fibonacci(n-2)
    """,
    task="Analyze code complexity and provide optimization suggestions",
    language="Python"
)

# JSON data processing
result = client.compute.custom_compute(
    text='{"users": [{"name": "Alice", "age": 30}]}',
    task="Analyze data structure and generate data report",
    format="JSON"
)

🎨 Image Generation Features

In addition to text computation, the SDK provides powerful image generation capabilities:

def generate_artwork(description, art_style="modern art"):
    """Generate artwork"""
    
    image = client.image.generate(
        prompt=description,
        composition="centered composition with strong visual impact",
        lighting="dramatic lighting effects",
        style=art_style
    )
    
    if image.success:
        # Save images
        saved_files = client.image.save_images(image, "artwork")
        return {
            "success": True,
            "image_count": image.count,
            "saved_files": saved_files
        }
    else:
        return {"success": False, "error": "Image generation failed"}

# Use the function
artwork = generate_artwork(
    "A lonely traveler walking under the starry sky", 
    "Van Gogh style oil painting"
)
print(f"Generation result: {artwork}")

🔧 Complete Example: Intelligent Assistant Function

class IntelligentAssistant:
    def __init__(self, api_key):
        self.client = RCKClient(api_key=api_key)
    
    def process_request(self, user_input, context="general"):
        """Intelligently process user requests"""
        
        # First analyze user intent
        intent_analysis = self.client.compute.custom_compute(
            text=user_input,
            task="Analyze user intent and categorize",
            output_schema={
                "type": "object",
                "properties": {
                    "intent": {"type": "string"},
                    "confidence": {"type": "number"},
                    "required_action": {"type": "string"}
                }
            },
            context=context
        )
        
        intent = intent_analysis.data.get('intent', 'unknown')
        
        # Execute different processing logic based on intent
        if intent == "creative_writing":
            return self._handle_creative_request(user_input)
        elif intent == "data_analysis":
            return self._handle_analysis_request(user_input)
        else:
            return self._handle_general_request(user_input)
    
    def _handle_creative_request(self, user_input):
        """Handle creative requests"""
        result = self.client.compute.custom_compute(
            text=user_input,
            task="Create content based on user needs",
            creativity_level="high",
            style="engaging",
            length="moderate"
        )
        return result.data
    
    def _handle_analysis_request(self, user_input):
        """Handle analysis requests"""
        result = self.client.compute.custom_compute(
            text=user_input,
            task="Conduct in-depth analysis and provide insights",
            analysis_depth="detailed",
            include_suggestions="yes",
            format="structured"
        )
        return result.data
    
    def _handle_general_request(self, user_input):
        """Handle general requests"""
        result = self.client.compute.custom_compute(
            text=user_input,
            task="Provide helpful answers and suggestions",
            tone="friendly",
            detail_level="moderate"
        )
        return result.data

# Use intelligent assistant
assistant = IntelligentAssistant(api_key="your-api-key")

# Process different types of requests
creative_result = assistant.process_request(
    "Help me write a poem about autumn", 
    context="creative"
)

analysis_result = assistant.process_request(
    "Analyze the trends in this sales data", 
    context="business"
)

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

📞 Contact Support

For questions or assistance, please contact:

📧 Email: omorsablin@gmail.com


💡 Core Philosophy: Use RCK as an intelligent function kernel, describing "what to do" declaratively rather than "how to do it". Let AI handle complex logic while you only need to define inputs, constraints, and expected outputs.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rck_python_sdk-1.0.1.tar.gz (22.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rck_python_sdk-1.0.1-py3-none-any.whl (22.5 kB view details)

Uploaded Python 3

File details

Details for the file rck_python_sdk-1.0.1.tar.gz.

File metadata

  • Download URL: rck_python_sdk-1.0.1.tar.gz
  • Upload date:
  • Size: 22.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.7

File hashes

Hashes for rck_python_sdk-1.0.1.tar.gz
Algorithm Hash digest
SHA256 9ef746818933bb61cdfdd8e1f2e5cbeb266d0ed075cc89b7a915593633ff23ea
MD5 0a4df29ccfd9456adb3102971319517e
BLAKE2b-256 56a72f8e5fed77f6b6fbb07db161b58ab8075ee6eb4324febdf705def6d90b82

See more details on using hashes here.

File details

Details for the file rck_python_sdk-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: rck_python_sdk-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 22.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.7

File hashes

Hashes for rck_python_sdk-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9156581a5aa57b782510b6c0809db3374f2989b907c0de7d0a29f805452ae3b1
MD5 a39d88b3f35919487cd6554919256b53
BLAKE2b-256 32c66fed8968fd6e8036d355a829fe1c65eaf41d12008f9769fb30ee7ade6966

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page