What's new

Access GPF from scripts and Update Designs

VECDESIGN

Senior Member
I am trying to access the actual part and the linked GPF to it from script as first steps as follows. I get the error
Error: No Global Parameter File (GPF) is linked to the current part.
Can you help about about finding the root? Is it better to specifically define hard coded the route to the files and files names?
Thanks.

import math # Import math module for mathematical operations
from AlibreScript import * # Import Alibre Script API
from datetime import datetime # Import for timestamps
import os # Import for file and folder operations


# Debug: Confirm the script starts execution
print("Script has started...") # Notify the user in the console

# Step 1: Access the current part in Alibre
try:
part = CurrentPart() # Attempt to get the currently active part
print("Part loaded: {}".format(part.Name)) # Debug: Part successfully accessed
except Exception as e:
# Handle the error if no part is loaded
print("Error: No part is currently loaded in Alibre.\n{}".format(str(e)))
raise SystemExit # Exit the script if no part is available

# Step 2: Access the Global Parameter File (GPF)
try:
GPF = CurrentGlobalParameters() # Access the GPF linked to the part
print("GPF loaded: {}".format(GPF.Name)) # Debug: GPF successfully accessed
except NameError:
# Handle the error if no GPF is linked
print("Error: No Global Parameter File (GPF) is linked to the current part.")
raise SystemExit # Exit the script if no GPF is available

# Step 3: Create the output folder
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") # Generate a timestamp for unique folder naming
output_folder = os.path.join("C:\\Users\\usuario\\Desktop\\DESIGNBATHS", "{}_{}_{}".format(part.Name, GPF.Name, timestamp))
os.makedirs(output_folder) # Create the output folder
print("Output folder created: {}".format(output_folder)) # Debug: Folder creation successful

# Step 4: Read favorite parameters from the GPF
parameter_names = [param.Name for param in GPF.Parameters if param.IsFavorite] # Retrieve favorite parameters
print("Debug: Favorite parameters found in GPF: {}".format(parameter_names)) # Debug: List of favorite parameters
 

stepalibre

Alibre Super User
Here’s my (and AI’s) interpretation of your post. GPF linking is a feature I’ve never used maybe someone can explain how to use it the help is not clear.
Python:
import math                             # For math operations
from datetime import datetime          # For timestamp
import os, sys                         # For path/file operations & sys.exit
print("Script has started...")

# Step 1: Access the current part
try:
    part = CurrentPart()
    print("Part loaded: {}".format(part.Name))
except Exception as e:
    print("Error: No part is currently loaded in Alibre.\n{}".format(str(e)))
    sys.exit()  # Exit if no part is available

# Step 2: Attempt to access an already-linked GPF
try:
    # Add GPF Link Code Here
    print("GPF loaded (linked to part): {}".format(GPF.Name))
except:
    # If there's no GPF linked, fallback to open a known GPF from disk
    print("No linked GPF found. Trying to open from path...")
    GPFpath = r"{path}"              # Adjust as needed
    GPFname = "New_Global_Parameters_Script"         # The GPF 'internal name'
    try:
        GPF = GlobalParameters(GPFpath, GPFname)
        print("Opened GPF from disk: '{}'".format(GPF.Name))
    except Exception as ex:
        print("Error: Could not open GPF from disk.\n{}".format(str(ex)))
        sys.exit()

# OPTIONAL: You can set units for your script if needed
Units.Current = UnitTypes.Inches

# Step 3: Create the output folder
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")  # For unique naming
output_folder = os.path.join(
    r"{path}",          # Base folder
    "{}_{}_{}".format(part.Name, GPF.Name, timestamp) # E.g. "PartName_GPFName_YYYYMMDD_HHMMSS"
)
os.makedirs(output_folder)
print("Output folder created: {}".format(output_folder))

# Step 4: Read *favorite* parameters from the GPF
Fake_Favorites = [param.Comment for param in GPF.Parameters if param.Comment]
print("Favorite parameters in GPF: {}".format(Fake_Favorites))

# (Optional) Debug or additional listing:
# Show all parameter names, values, and comments
all_names = [p.Name for p in GPF.Parameters]
all_values = [p.Value for p in GPF.Parameters]
all_comments = [p.Comment for p in GPF.Parameters]

print("All Param Names: ", all_names)
print("All Param Values:", all_values)
print("All Param Comments (Fake_Favorites):", all_comments)
print("Script completed successfully.")

1737916045998.png
Code:
Script has started...
Part loaded: SolidFeatureShowcase6
No linked GPF found. Trying to open from path...
Opened GPF from disk: 'New_Global_Parameters_Script'
Output folder created: A:\{folder}\SolidFeatureShowcase6_New_Global_Parameters_Script_20250126_121623
Favorite parameters in GPF: ['Test Comment a', 'Test Comment c', 'Test Comment b']
('All Param Names: ', ['a', 'c', 'b'])
('All Param Values:', [5.0, 10.0, 9.0])
('All Param Comments (Fake_Favorites):', ['Test Comment a', 'Test Comment c', 'Test Comment b'])
Script completed successfully.

I don't think the favorite property is exposed. You can fake a favorite by using the comment property:

Properties for Parameter:
Comment: Test Comment b
Equation:
ExcelCell:
ExcelSheet:
ExcelWorkbook:
Name: b
RawValue: 22.86
Type: Distance
Units: Inches
Value: 9.0

Alibre Design features and the API do not have a one-to-one relationship. This means it's worth searching the API documentation to ensure that what you want to do is possible with the API. A quick assessment is searching my GitHub projects, either online or locally. The chm files are the main source to search.

1737917828243.png
1737918229119.png

 
Last edited:

VECDESIGN

Senior Member
I tried both the CODE ASSISTANT and the API EXPERT and both are not searching in the available API features for some reason. GPT4o1 use to make same mistakes. I agree it must be in depth analyzed. Thanks Stephen.
 

NateLiquidGravity

Alibre Super User
Have you ever gotten CurrentGlobalParameters() to work because I don't remember seeing that before and these AI have a habit of making up things. Try asking the AI that gave you that where it exits. Sometimes they realize their mistake then.
 

stepalibre

Alibre Super User
I haven't updated/used those in months and have made many variations. My current AI setup is mostly local programs that use OpenAI, Gemini and Claude APIs directly with open source LLMs through LM studio. I have several check and validation steps that remove or replace generated code that are not found in AlibreX or Alibre Script. My plan is to release a dataset for Alibre Design that anyone can download as an addon and run locally. I didn't mention this in my other post, but the problem is Alibre Design and its API (and other CAD APIs) aren't designed to be AI assisted or automated to the degree I want. AlibreX and Alibre Script are two independent libraries. Alibre Script is built on top of AlibreX. AlibreX is not complete it has many placeholders throughout for stuff that is incomplete or not implemented. The interfaces for important features/functions are also missing methods and properties. To solve this I'm building a function library that is designed for automation and AI first. It is itself source generated and will only include functions. Every interface, method or property not fully implemented in AlibreX will be excluded from the library. This will improve reliability and consistency.
.
Those GPTs are useful if you know Alibre Script and is guiding it along the way. They are not meant to generate or synthesize scripts from scratch. My code databases are generated from scratch within my system, I act as a code reviewer.
 
Last edited:

VECDESIGN

Senior Member
Have you ever gotten CurrentGlobalParameters() to work because I don't remember seeing that before and these AI have a habit of making up things. Try asking the AI that gave you that where it exits. Sometimes they realize their mistake then.
I have not checked. My exercise to test these is just ask for something and also ask for improvements based on feedback with console output with multiple iterations to see how this tuned GPT work. Not far away, this iteration will be auto too. I will keep trying. To really solve some of the issues efficiency I finally had to guide GPT as you suggest, just questioning the proposal. The same we have to do with us, humans. :). Thanks so much for your help!
 

stepalibre

Alibre Super User
Generative AI is the greatest invention in my lifetime or as an adult! I can now give complex instructions, get the code, compile and run the program entirely headless. I run multiple programs in parallel, feed the results back into the LLM continuously until i am satisfied or my set output conditions are met. All within minutes!
 

stepalibre

Alibre Super User
@MDG ,
its old, must be updated, but you might give some inspiration...OLD THREAD
Regards
Stefan

one comment to AI: if you are not able to solve a problem by yourself, you might also be no able to find a fail made by AI...;)
Thanks for the link. I forget to search the forum. Yes Gen AI is very misunderstood and is used as a catch all while in reality a Gen AI session is closer to a real time natural language/code interpreter, programmable search engine and database. I learn more when mistakes are made over any output that is flawless. It's incredible. A lot of the failures are caused by poor API design and inconsistencies in how interfaces, classes, methods, fields and properties are named and how the code is structured. Many aspects of Alibre Script aren't well aligned with AlibreX this creates errors when trying to merge the two (in general and) in a AS Advanced API script (ironpython + C#). Naming conventions are the default for understanding which is often following industry standards or best practices. These conventions are for humans none of it matters to a Gen AI and it only adds more overhead to their task.

APIs were made for us, but this will change.
 

stepalibre

Alibre Super User
I should clarify I'm actually talking about two separate components that make up the system: the dataset is for training (for Alibre Script and AlibreX code generation) and the LLM (o1, Claude, Deepseek) with configuration, system prompts, instructions, external processes and other settings (for Alibre Script and AlibreX) that produce this output -> https://adai.donetoolkit.com/3D-Ske...libre-Design-1805708902a08039ad6de22774213b22.

Without the dataset the LLM cannot produce functioning Alibre code. Without any of the system prompts, instructions, external processes and other settings tailored for Alibre APIs and CAD, the output would be filled with wrong assumptions and API errors. The combined well thought out pairing of the two is what increases accuracy and reliability.
 
Last edited:

VECDESIGN

Senior Member
@MDG ,
its old, must be updated, but you might give some inspiration...OLD THREAD
Regards
Stefan

one comment to AI: if you are not able to solve a problem by yourself, you might also be no able to find a fail made by AI...;)
Thanks for the link and the reference scripts, very useful start point. I fully agree your comment to AI in most cases. In my conclusion another important capability for humans is to develop the ability to communicate and manage the AI so that the AI recognizes its fail. Something equivalent to human to human interaction. AI can be much more clever than humans then can be much more humble than humans. :)
 

VECDESIGN

Senior Member
Anyone knows how to expose if a global parameter is favorite or not? TRUE or FALSE what? I am searching where to find all available type of data exposed?
I found the next from helpful [B]idslk[/B] script in the link above.

.Name
.Comment
.Value
.Equation
.Units
.Type
 

NateLiquidGravity

Alibre Super User
If it isn't in the AlibreX API then it's not available. The AlibreX API help is linked at the bottom of the second tab of the Alibre home window. There's a 99.99% chance it's not available because favorites were added relatively recently and the API has barely gotten any updates over the years aside from materials.
 

stepalibre

Alibre Super User
I thought I answered that here.
Here’s my (and AI’s) interpretation of your post. GPF linking is a feature I’ve never used maybe someone can explain how to use it the help is not clear.
Python:
import math                             # For math operations
from datetime import datetime          # For timestamp
import os, sys                         # For path/file operations & sys.exit
print("Script has started...")

# Step 1: Access the current part
try:
    part = CurrentPart()
    print("Part loaded: {}".format(part.Name))
except Exception as e:
    print("Error: No part is currently loaded in Alibre.\n{}".format(str(e)))
    sys.exit()  # Exit if no part is available

# Step 2: Attempt to access an already-linked GPF
try:
    # Add GPF Link Code Here
    print("GPF loaded (linked to part): {}".format(GPF.Name))
except:
    # If there's no GPF linked, fallback to open a known GPF from disk
    print("No linked GPF found. Trying to open from path...")
    GPFpath = r"{path}"              # Adjust as needed
    GPFname = "New_Global_Parameters_Script"         # The GPF 'internal name'
    try:
        GPF = GlobalParameters(GPFpath, GPFname)
        print("Opened GPF from disk: '{}'".format(GPF.Name))
    except Exception as ex:
        print("Error: Could not open GPF from disk.\n{}".format(str(ex)))
        sys.exit()

# OPTIONAL: You can set units for your script if needed
Units.Current = UnitTypes.Inches

# Step 3: Create the output folder
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")  # For unique naming
output_folder = os.path.join(
    r"{path}",          # Base folder
    "{}_{}_{}".format(part.Name, GPF.Name, timestamp) # E.g. "PartName_GPFName_YYYYMMDD_HHMMSS"
)
os.makedirs(output_folder)
print("Output folder created: {}".format(output_folder))

# Step 4: Read *favorite* parameters from the GPF
Fake_Favorites = [param.Comment for param in GPF.Parameters if param.Comment]
print("Favorite parameters in GPF: {}".format(Fake_Favorites))

# (Optional) Debug or additional listing:
# Show all parameter names, values, and comments
all_names = [p.Name for p in GPF.Parameters]
all_values = [p.Value for p in GPF.Parameters]
all_comments = [p.Comment for p in GPF.Parameters]

print("All Param Names: ", all_names)
print("All Param Values:", all_values)
print("All Param Comments (Fake_Favorites):", all_comments)
print("Script completed successfully.")

View attachment 43831
Code:
Script has started...
Part loaded: SolidFeatureShowcase6
No linked GPF found. Trying to open from path...
Opened GPF from disk: 'New_Global_Parameters_Script'
Output folder created: A:\{folder}\SolidFeatureShowcase6_New_Global_Parameters_Script_20250126_121623
Favorite parameters in GPF: ['Test Comment a', 'Test Comment c', 'Test Comment b']
('All Param Names: ', ['a', 'c', 'b'])
('All Param Values:', [5.0, 10.0, 9.0])
('All Param Comments (Fake_Favorites):', ['Test Comment a', 'Test Comment c', 'Test Comment b'])
Script completed successfully.

I don't think the favorite property is exposed. You can fake a favorite by using the comment property:

Properties for Parameter:
Comment: Test Comment b
Equation:
ExcelCell:
ExcelSheet:
ExcelWorkbook:
Name: b
RawValue: 22.86
Type: Distance
Units: Inches
Value: 9.0

Alibre Design features and the API do not have a one-to-one relationship. This means it's worth searching the API documentation to ensure that what you want to do is possible with the API. A quick assessment is searching my GitHub projects, either online or locally. The chm files are the main source to search.

View attachment 43832
View attachment 43833
 

VECDESIGN

Senior Member
I was searching the API documentation and couldn't find the additional parameters mentioned in the script above. Thank you for confirming that they likely do not exist.
 

VECDESIGN

Senior Member
Thanks. I see now all this info is in API HELP button. I am sorry I am introducing to that to just know what can be done. I was searching only in the HELP WEB PAGE before. It is fully confirmed no favorite property exposed.
 

bolsover

Alibre Super User
I don't see any way to access Global Parameters from a Part..
Following screen grab is from my Property Viewer which recursively walks through properties exposed by an open part file..
The part has an associated global parameters file and in the screen grab, entry 9, parameter D11 takes its value from the Global Parameter PARAM2.
PARAM2 is NOT exposed in the enumeration of IADParameters and so far as I can tell, there is no way to access PARAM2 directly outside of the Global Parameter Editor.

If anyone is interested, the Property Viewer is part of the AlibreUtilities Add-on - latest version linked in resources.
Screenshot 2025-01-29 170641.png
 

stepalibre

Alibre Super User
I don't see any way to access Global Parameters from a Part..
Following screen grab is from my Property Viewer which recursively walks through properties exposed by an open part file..
The part has an associated global parameters file and in the screen grab, entry 9, parameter D11 takes its value from the Global Parameter PARAM2.
PARAM2 is NOT exposed in the enumeration of IADParameters and so far as I can tell, there is no way to access PARAM2 directly outside of the Global Parameter Editor.

If anyone is interested, the Property Viewer is part of the AlibreUtilities Add-on - latest version linked in resources.
View attachment 43851

Great! This is runtime COM populated properties. It is possible to access isFavorite and other properties not yet exposed to AlibreX COM API but is in C++. You can get the objects from reflection by tracing the calls or other techniques. We could say what's in AlibreX is the public API. This is COM so the private properties are available at runtime. You can simply dump this data to file or in memory to get isFavorite or anything. Everything is in this listtreeview! In an if statement if "Source" = IsFavrovite then Break...

Paramerters -> Enum -> Enum # -> Source -> IsFavrovite

Is IsFavorite value updated per instance would need to be answered. It could be updated somewhere else or the equation editor could use another method to store these properties.
 

bolsover

Alibre Super User
Code for the property viewer is open source. It has been a while since I wrote the tool. My motivation was just to gain a better understanding of what was going on inside a part file.
 
Top