Zero Labs
Industry News / AI

How to Create a Well-Structured Python SDK

Source · Towards AI By Asma Houimli

From the publisher’s feed, collected in the ZeroLabs newsroom.

Photo by Emile Perron on UnsplashDuring a previous summer internship, I worked on creating a comprehensive Python SDK. The SDK was designed to interact with various LLMs hosted on Ollama and to produce responses in PDF, TXT, or JSON formats. Additionally, I developed a command-line interface (CLI) to enhance usability.When I first started creating the SDK, I thought it would be easy since I believed there were enough resources available on the internet. However, I faced some difficulties along the way. That's why I've written a blog post about my experience. I want to help others facing similar challenges and remind myself of the tips and tricks I learned the hard way.So, let’s go through this detailed tutorial, in which I will share with you how to create a well-structured SDK and make it shareable with other developers.The code snippets provided in this tutorial are from the GitHub repository of my Python SDK.First things first ;1. What is an SDK?‘A software development kit (SDK) is a collection of software development tools in one installable package. They facilitate the creation of applications by having a compiler, debugger, and sometimes a software framework. They are normally specific to a hardware platform and operating system combination.’ -Wikipedia-In simple terms, an SDK, or Software Development Kit, is a toolbox filled with tools, resources, and code that assist developers in creating innovative applications using reusable functions. It often includes libraries and APIs, which let different programs and services communicate, code examples, and documentation. Having all these resources in one place saves time and encourages more developers to use the SDK. After all, no one will want to use an SDK if they’re unsure of what it can do, right?2. Organizing your SDK filesTo ensure your SDK is clear, understandable, and easy to maintain, it is essential to organize your files logically. Here is how I organized the files of my SDK:Files organisation in the SDKCore functional files: These are the files containing the classes and their associated methods that will be used to create reusable components.In these code files, it's important to group related files together in the same directories, especially those that address similar tasks or functions. This organization makes it easier to debug issues if something goes wrong and helps maintain a more orderly structure.Always organize your code in classes to ensure modularity and make it easier to add features, and don’t forget the rule: a class per file, and classes should be concise.In my SDK, the files are structured as follows:LL_model.py : This file contains a class that includes all the essential methods to create, generate, or chat with a large language model hosted in Ollama.Output_handler.py : This file manages the output format for interactions with the LLM. Users can specify whether they want the output to be in PDF, TXT, or JSON format. This structure keeps the logic separate from the large language model interactions.Currently, my SDK has only one directory for functional files. However, if I decide to add more complex features, such as text-to-speech, I would create a separate directory for them. This approach helps maintain an organized structure that can easily scale as the SDK expands.__init__.py files:Every directory in your SDK should include a __init__.pyfile. This file is used to turn the directory into a Python package. It can be empty or contain import statements for the files within that directory. This setup ensures that when the package is imported, all the modules in that directory are accessible and ready for use.For example, this is the content of __init__.py of the directory ll_model.py :from .LL_model import LL_modelfrom .OutputHandler import OutputHandler3. Other Specific Files in your SDKIn addition to the functionalities, there are more files that we need to include for the SDK to be installable, distributable, and usable.We will go over these files and how they contribute to a well-rounded SDK structure:requirements.txt : This file lists all dependencies needed to build and run the SDK. Each dependency should be written in this format lib_name==version to ensure consistent behavior across different environments. This file is essential for configuring the environment and enabling users to install necessary packages.Example:fpdf==1.7.2ollama==0.3.0_config.py : This file contains the configuration settings for the SDK. It may include variables such as API keys, default paths, and system parameters used across multiple modules. By centralizing these configurations in one file, we can maintain clearer code and make it easier to update and modify system-wide settings._version.py : This is a simple file that contains the version of the SDK. It usually includes a single line like this __version__='0.1.0' .cli.py : While not every SDK contains this file, it can be highly beneficial if you want to provide users with a Command Line Interface (CLI). This file allows users to interact with the SDK’s functionalities directly from the command line, making it easier to perform common tasks without writing additional code. For example, users could generate model outputs or configure settings using simple command-line commands. Creating a CLI can make your SDK more versatile and user-friendly.setup.py : This is probably the most critical file in the SDK, as it’s responsible for defining the installation process and metadata of the package. This file uses setuptools library to facilitate the distribution of the SDK. Here’s an example of how a setup.py file may look:from setuptools import setup, find_packagesdef parse_requirements(filename): with open(filename, 'r') as file: return file.read().splitlines()setup( name="llm_generate", version="0.1.0", author="Asma Houimli", author_email="asma.houimli@etudiant-fst.utm.tn", description="A package for interacting with LLama3 models.", long_description=open('README.md').read(), long_description_content_type="text/markdown", url="https://github.com/Asma1233670/llm_generate", packages=find_packages(), classifiers=[ 'Programming Language :: Python :: 3', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ], python_requires='>=3.8', install_requires=parse_requirements('requirements.txt'), entry_points={ 'console_scripts': [ 'll_model=ll_model.cli:main', ], })Explanation of key sections in setup.py :name : Name of the SDK.version : The current version of the SDK.author and author_email : The creator’s name and contact info.description is a brief description; however, long_description is a detailed explanation of the SDK, it often pulls the content of README.md .url : The repository or project homepage.packages : Uses find_packages() to automatically include all packages in the directory.install_requires : Here you can either parse the requirements.txt or just add the requirements here in a list, and you can in that case not include a requirements.txt file as you will be giving them directly in the setup.py .entry_points : Defines the command-line interface by linking a command (here : ll_model ), to a function (here: llm_model.cli:main ), which means the function main() of the file cli.py. That way, in the command line, when you write the command ll_model you can use its functions.In addition to the core files, there are additional components that you should add to your SDK to ensure that users and developers can understand, use, and extend your SDK.Test directory: Creating a dedicated testing directory is essential for verifying that the SDK functions as intended and for maintaining code reliability. You can use a testing framework like unittest or pytest which can help automate these tests.Code examples: Including a examples directory is important for other developers. This should contain examples of code implementing the main features of your SDK.Documentation: This is one of the most crucial parts of an SDK; it should be concise, comprehensive, and not complex or misleading. Documentation serves as a guide for understanding what each function, class, or module does and how it is used.4. Installing and setting up your SDKAlright, now that you have created your functions as well as the other files, guess it’s time to understand how to install it and set it up properly. This is crucial both for your testing and for sharing it with others who may use it or contribute to its development, at this point, what is the difference between this directory full of code and any other code you have on your computer?So to test it locally, you can install it with this command, which should be run from the root directory of the SDK:pip install .You can also install it in development mode, which installs the package in an ‘edible’ mode. This means that any changes you make to the code are immediately reflected without needing to reinstall it again. This is useful during the development or testing phases:pip install -e .What happens when you run this command?When you install the package, pip creates a directory ending in .egg-info (e.g. llm_generate.egg-info ). This directory contains metadata about the package, including information about the installed version, dependencies, and entry points. This metadata is essential for pip to manage the package and its dependencies correctly.These are generally the files you find inside .egg-info :PKG-INFO: Contains basic metadata (name, version, author, and description of the package…).requires.txt: Lists the package dependencies required to run the SDK.SOURCES.txt: A list of all files included in the package, useful for understanding the full structure of your project.dependency_links.txt: Points to any non-PyPI dependencies that may be required.entry_points.txt: Defines the entry points specified in the setup.py file. This file assists in managing command line script entry points, simplifying direct user access to certain functionalities via commands.top_level.txt: Lists the top-level packages included in your SDK.Cloning and Installing other repositoriesWhen you clone another developer’s repo, the process of installing the package and setting it up is pretty much the same:1. Cloning the repo:git clone https://github.com/Asma1233670/llm_generate.git2. Go inside the repo:cd llm_generate3. Installing the SDK (in editable mode):pip install -e .Bonus section: Diagnosing and Improving Code QualityWhen developing any software that you plan to publish for others to use either publicly or within an organization, or code that you plan on adding features to, one of the key practices that ensures the longevity and maintainability of your project is diagnosing and improving the quality of your code. It’s easy to get carried away writing new features, but code clarity, flexibility, and testability should always be your priority.Even for high-quality, widely used libraries, there’s always room for improvement.Why Diagnose Your Code?Before diving into improvements, we must understand the ‘why’ of things. Code diagnosis allows us:Improve code clarity: Code that is easy to understand is simpler to maintain, extend, and debug. When you or others struggle to comprehend your code, it becomes significantly more challenging to introduce new features, resolve issues, or even figure out how the code works.Enhance Code Flexibility: In a dynamic environment that requires frequent updates, flexible code enables you to implement changes with minimal disruption to the overall system. It is important to avoid tightly coupled code, as modifications in one part of the system can unnecessarily impact other areas.Ensure code testability: Code designed for testability tends to be more robust and reliable. It should be easy to write unit tests and run them efficiently. Good test coverage ensures that new features or changes do not disrupt existing functionality.Optimize performance: Although performance isn’t always the top priority during development, it should still be considered when refactoring.Common Issues In Production Code:Code clarity issues:Large files, large classes, and large functions: It’s difficult to navigate large files, classes, or functions.Too many variables in one class: If a class has many variables, it can become hard to follow.Inappropriate Naming: Choosing the right, expressive names for classes, functions, variables, and constants is crucial for clarity.Complicated logic: Overuse of deeply nested if statements and complex if-else chains often make code harder to understand.Code flexibility issues:Large number of imports: A file with hundreds of imports is a red flag. It means that there’s so much going on in the file, and maybe we need to split it into smaller modules.Tightly coupled classes and subclasses: When one class depends heavily on another, any change in the base class forces changes in all subclasses.Excessive Data Passing: Transferring excessive data between functions or classes can lead to unnecessary complexity. Aim to pass only the data essential for the task at hand, and think about restructuring your code to minimize excessive data dependencies.Repeated code segments: If you find yourself writing the same code or similar code in multiple places, it’s time to refactor.Code testability issues:Creating objects within classes: Sometimes, a class may create objects within itself, making it difficult to mock or test those objects independently.End-to-End vs. Unit Testing: In some cases, especially in complex user interfaces, unit tests may not be enough. In these scenarios, end-to-end testing, which tests the entire system’s functionality, might be necessary to ensure that the code behaves as expected in real-world scenarios.And again, tightly coupled code: Code that tightly couples classes and functions makes it difficult to unit test.Tips for writing better code:Break large files and functions into smaller, more manageable pieces.Choose meaningful names for variables, functions, and classes.Avoid deeply nested logic and try to simplify complex conditions.Keep your classes loosely coupled and aim for flexibility.Generalize repeated code into reusable functions.By diagnosing your code with these criteria in mind, you can identify areas that need improvement and refactor them before they become a problem. Remember, it’s not just about writing code that works; it’s about writing code that lasts and scales well over time.In conclusion, creating a well-structured Python SDK can be quite an adventure! But it’s worth the trouble, as it not only sharpens your coding skills but also allows you to contribute something valuable.Once we’re comfortable with our SDK, we can push it to a git repo where others can explore the code, contribute, and maybe even suggest improvements! Or we can go a little extra and actually distribute it through PyPI, which is Python open-source packages repository. Imagine the satisfaction of sharing your hard work with developers all over the world!I hope you found this article helpful! BYE!How to Create a Well-Structured Python SDK was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.