Skip to content

Create Optimization

This example demonstrates how to create and run an optimization on an existing G-Code in the Helio Additive platform. Optimizations adjust print speeds and other parameters to improve thermal quality and print outcomes.

Create the following GraphQL files, then run your language’s codegen tool to generate the types.

mutations/CreateOptimization.graphql
mutation CreateOptimization($input: CreateOptimizationInput!) {
createOptimization(input: $input) {
id
name
}
}

API Reference:

  1. Setup the client and configuration

    index.ts
    import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
    import { CreateOptimizationDocument } from "./mutations/__generated/CreateOptimization.generated";
    import { OptimizationDocument } from "./queries/__generated/Optimization.generated";
    // Load PAT from environment
    const PAT = process.env.PAT;
    if (!PAT) {
    throw new Error("PAT environment variable is required");
    }
    // Create Apollo Client
    const client = new ApolloClient({
    cache: new InMemoryCache(),
    link: new HttpLink({
    uri: "https://api.helioadditive.com/graphql",
    headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${PAT}`,
    },
    }),
    });
    // Replace with an actual G-Code ID from your account
    const GCODE_ID = process.env.GCODE_ID ?? "your-gcode-id";
  2. Create the optimization

    Create a new optimization for the specified G-Code. You can optionally specify optimization settings like layer ranges.

    async function createOptimizationEntry(gcodeId: string, name: string) {
    const { data, error } = await client.mutate({
    mutation: CreateOptimizationDocument,
    variables: {
    input: {
    gcodeId: gcodeId,
    name: name,
    // Optional: specify optimization settings
    optimizationSettings: {
    layersToOptimize: [{ fromLayer: 1, toLayer: 100 }],
    },
    },
    },
    errorPolicy: "all",
    });
    if (error) {
    throw new Error(`Failed to create optimization: ${error.message}`);
    }
    const optimizationId = data?.createOptimization?.id;
    if (!optimizationId) {
    throw new Error("Failed to create optimization");
    }
    return optimizationId;
    }
  3. Poll and wait for optimization to complete

    After creation, the optimization needs to run. Poll the status until it’s finished.

    async function waitForOptimizationComplete(optimizationId: string): Promise<void> {
    return new Promise((resolve, reject) => {
    const checkStatus = async () => {
    const { data } = await client.query({
    query: OptimizationDocument,
    variables: { id: optimizationId },
    fetchPolicy: "no-cache",
    });
    const status = data?.optimization?.status;
    const progress = data?.optimization?.progress;
    console.log(`Optimization status: ${status}, progress: ${progress}%`);
    if (status === "FINISHED") {
    console.log(`Optimized G-Code URL: ${data?.optimization?.optimizedGcodeUrl}`);
    console.log(`Quality Mean Improvement: ${data?.optimization?.qualityMeanImprovement}`);
    console.log(`Quality Std Improvement: ${data?.optimization?.qualityStdImprovement}`);
    resolve();
    } else if (status === "FAILED") {
    reject(new Error("Optimization failed"));
    } else {
    // Poll every 2 seconds
    setTimeout(checkStatus, 2000);
    }
    };
    checkStatus();
    });
    }
  4. Put it all together

    Combine all the steps into a single function and run it.

    async function createOptimization(gcodeId: string, name: string) {
    console.log(`Creating optimization for G-Code: ${gcodeId}`);
    // Create the optimization
    const optimizationId = await createOptimizationEntry(gcodeId, name);
    console.log(`Optimization created with ID: ${optimizationId}`);
    // Wait for optimization to complete
    console.log("Waiting for optimization to complete...");
    await waitForOptimizationComplete(optimizationId);
    console.log("Optimization finished!");
    return optimizationId;
    }
    // Example usage
    const optimizationName = `optimization-${Date.now()}`;
    createOptimization(GCODE_ID, optimizationName)
    .then((id) => console.log(`Successfully completed optimization: ${id}`))
    .catch(console.error);
  1. Create a .env.local file with your PAT and G-Code ID:

    Terminal window
    PAT="your-personal-access-token"
    GCODE_ID="your-gcode-id"
  2. Update the GCODE_ID with a valid G-Code ID from your account that is in READY status.

  3. Run the example:

    Terminal window
    bun run index.ts