Generate Python Code Effortlessly with WizardCoder Cognitive Actions

25 Apr 2025
Generate Python Code Effortlessly with WizardCoder Cognitive Actions

In the rapidly evolving landscape of software development, automating code generation can significantly enhance productivity and streamline workflows. The WizardCoder Cognitive Actions, as defined in the andreasjansson/wizardcoder-python-34b-v1-gguf specification, empower developers to generate Python code with remarkable accuracy and structure compliance. Leveraging advanced capabilities such as grammar and JSON Schema integration, these actions simplify the code creation process, making it an ideal tool for various applications.

Prerequisites

Before diving into the integration of WizardCoder Cognitive Actions, ensure you have the following:

  • An API key for the Cognitive Actions platform.
  • Basic knowledge of JSON and Python.
  • Familiarity with making HTTP requests in your preferred programming language.

For authentication, you will typically pass your API key in the headers of your requests. This allows you to securely access the functionality provided by the Cognitive Actions.

Cognitive Actions Overview

Generate Python Code with WizardCoder

The Generate Python Code with WizardCoder action allows you to harness the power of the WizardCoder model to produce Python code snippets effectively. This action not only generates code based on a given prompt but also supports grammar and JSON Schema, ensuring that the output adheres to specified structures.

Input

To invoke this action, you need to construct a JSON payload that includes several fields:

  • prompt (required): The input text that guides the generated code output.
  • topK (optional): The number of top entries to consider during decoding. Default is 10.
  • topP (optional): The cumulative probability threshold for nucleus sampling. Default is 0.95.
  • maxTokens (optional): The maximum number of tokens to generate. Default is 500.
  • temperature (optional): Controls the randomness of the output. Default is 0.8.
  • grammar (optional): Defines the grammar in GBNF format. Use either grammar or JSON Schema, not both.
  • jsonschema (optional): Specifies the JSON Schema for the expected output structure.
  • mirostatMode (optional): Determines the mode of operation for Mirostat sampling. Default is Disabled.
  • repeatPenalty (optional): Penalty for word repetition. Default is 1.1.
  • presencePenalty (optional): Penalty for the presence of specific tokens. Default is 0.
  • frequencyPenalty (optional): Penalty based on the frequency of existing tokens. Default is 0.
  • mirostatEntropy (optional): Target entropy level for Mirostat sampling. Default is 5.
  • mirostatLearningRate (optional): Learning rate for Mirostat sampling when not disabled. Default is 0.1.

Example Input:

{
  "topK": 10,
  "topP": 0.95,
  "prompt": "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nWrite a short program that counts the number of occurrences of a character in a string.\n\n### Response:",
  "grammar": "root        ::= \"```python\\ndef num_occurrences(c: str, s: str) -> int:\\n    \" code \"```\"\ncode        ::= [^`()]+",
  "maxTokens": 500,
  "temperature": 0.8,
  "mirostatMode": "Disabled",
  "repeatPenalty": 1.1,
  "mirostatEntropy": 5,
  "presencePenalty": 0,
  "frequencyPenalty": 0,
  "mirostatLearningRate": 0.1
}

Output

The action typically returns a Python code snippet formatted as a string, with the generated code based on the provided prompt.

Example Output:

def num_occurrences(c: str, s: str) -> int:
    """Counts the number of occurrences of a character c in a string s.
    
    Args:
        c: A single character to count
        s: The string to search in
    
    Returns:
        The number of times c occurs in s
    """
    count = 0
    for char in s:
        if char == c:
            count += 1
    return count

Conceptual Usage Example (Python)

Here’s how you might call this action using Python:

import requests
import json

# Replace with your Cognitive Actions API key and endpoint
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"  # Hypothetical endpoint

action_id = "4420aad3-0bb3-4358-9027-587a09f2ca76"  # Action ID for Generate Python Code with WizardCoder

# Construct the input payload based on the action's requirements
payload = {
    "topK": 10,
    "topP": 0.95,
    "prompt": "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nWrite a short program that counts the number of occurrences of a character in a string.\n\n### Response:",
    "grammar": "root        ::= \"```python\\ndef num_occurrences(c: str, s: str) -> int:\\n    \" code \"```\"\ncode        ::= [^`()]+",
    "maxTokens": 500,
    "temperature": 0.8,
    "mirostatMode": "Disabled",
    "repeatPenalty": 1.1,
    "mirostatEntropy": 5,
    "presencePenalty": 0,
    "frequencyPenalty": 0,
    "mirostatLearningRate": 0.1
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json"
}

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json={"action_id": action_id, "inputs": payload}  # Hypothetical structure
    )
    response.raise_for_status()  # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body: {e.response.text}")

In this code snippet, replace the YOUR_COGNITIVE_ACTIONS_API_KEY and the hypothetical endpoint with your actual API key and endpoint. The action ID is set to the ID for generating Python code. The input payload is structured according to the requirements of the action.

Conclusion

The WizardCoder Cognitive Actions offer a powerful way to automate Python code generation, enhancing developer productivity and reducing manual coding errors. By integrating these pre-built actions into your applications, you can streamline workflows and focus on more complex aspects of development. Whether you're automating simple tasks or integrating sophisticated features, WizardCoder provides a robust solution to meet your needs. Explore the capabilities of this action and consider how it can fit into your development process!