Skip to content

Commit 3045264

Browse files
authored
Merge pull request #5 from IBM/pr5
Pull changes from main
2 parents 967f31a + 8268c54 commit 3045264

2 files changed

Lines changed: 3319 additions & 38 deletions

File tree

README.md

Lines changed: 240 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,68 +3,270 @@
33
![image](./docs/assets/cldk.png)
44
[![Python 3.11](https://img.shields.io/badge/python-3.11-blue.svg)](https://www.python.org/downloads/release/python-3110/)
55

6-
## Prerequisites
6+
Codellm-devkit (CLDK) is a multilingual program analysis framework that bridges the gap between traditional static analysis tools and Large Language Models (LLMs) specialized for code (CodeLLMs). Codellm-devkit allows developers to streamline the process of transforming raw code into actionable insights by providing a unified interface for integrating outputs from various analysis tools and preparing them for effective use by CodeLLMs.
77

8-
- Python 3.11+
9-
- Poetry (see [doc](https://python-poetry.org/docs/))
8+
Codellm-devkit simplifies the complex process of analyzing codebases that span multiple programming languages, making it easier to extract meaningful insights and drive LLM-based code analysis. `CLDK` achieves this through an open-source Python library that abstracts the intricacies of program analysis and LLM interactions. With this library, developer can streamline the process of transforming raw code into actionable insights by providing a unified interface for integrating outputs from various analysis tools and preparing them for effective use by CodeLLMs.
109

11-
## Installation
10+
**The purpose of Codellm-devkit is to enable the development and experimentation of robust analysis pipelines that harness the power of both traditional program analysis tools and CodeLLMs.**
11+
By providing a consistent and extensible framework, Codellm-devkit aims to reduce the friction associated with multi-language code analysis and ensure compatibility across different analysis tools and LLM platforms.
1212

13-
Obtain Codellm-DevKit from below:
13+
Codellm-devkit is designed to integrate seamlessly with a variety of popular analysis tools, such as WALA, Tree-sitter, LLVM, and CodeQL, each implemented in different languages. Codellm-devkit acts as a crucial intermediary layer, enabling efficient and consistent communication between these tools and the CodeLLMs.
1414

15-
```bash
16-
git clone git@github.com:IBM/codellm-devkit.git /path/to/cloned/repo
15+
Codellm-devkit is constantly evolving to include new tools and frameworks, ensuring it remains a versatile solution for code analysis and LLM integration.
16+
17+
Codellm-devkit is:
18+
19+
- **Unified**: Provides a single framework for integrating multiple analysis tools and CodeLLMs, regardless of the programming languages involved.
20+
- **Extensible**: Designed to support new analysis tools and LLM platforms, making it adaptable to the evolving landscape of code analysis.
21+
- **Streamlined**: Simplifies the process of transforming raw code into structured, LLM-ready inputs, reducing the overhead typically associated with multi-language analysis.
22+
23+
Codellm-devkit is an ongoing project, developed at IBM Research.
24+
25+
## Contact
26+
27+
For any questions, feedback, or suggestions, please contact the authors:
28+
29+
| Name | Email |
30+
| ---- | ----- |
31+
| Rahul Krishna | [i.m.ralk@gmail.com](mailto:i.m.ralk@gmail.com) |
32+
| Rangeet Pan | [rangeet.pan@ibm.com](mailto:rangeet.pan@gmail.com) |
33+
| Saurabh Sihna | [sinhas@us.ibm.com](mailto:sinhas@us.ibm.com) |
34+
## Table of Contents
35+
36+
- [CodeLLM-Devkit: A Python library for seamless interaction with CodeLLMs](#codellm-devkit-a-python-library-for-seamless-interaction-with-codellms)
37+
- [Contact](#contact)
38+
- [Table of Contents](#table-of-contents)
39+
- [Architectural and Design Overview](#architectural-and-design-overview)
40+
- [Quick Start: Example Walkthrough](#quick-start-example-walkthrough)
41+
- [Prerequisites](#prerequisites)
42+
- [Step 1: Set up an Ollama server](#step-1--set-up-an-ollama-server)
43+
- [Pull the latest version of Granite 8b instruct model from ollama](#pull-the-latest-version-of-granite-8b-instruct-model-from-ollama)
44+
- [Step 2: Install CLDK](#step-2--install-cldk)
45+
- [Step 3: Build a code summarization pipeline](#step-3--build-a-code-summarization-pipeline)
46+
47+
## Architectural and Design Overview
48+
49+
Below is a very high-level overview of the architectural of CLDK:
50+
51+
52+
```mermaid
53+
graph TD
54+
User <--> A[CLDK]
55+
A[CLDK] <--> B[Languages]
56+
B --> C[Java, Python, Go, C++, JavaScript, TypeScript, Rust]
57+
C --> D[Data Models]
58+
D --> 13{Pydantic}
59+
13 --> 7
60+
C --> 7{backends}
61+
7 <--> 8[CodeQL]
62+
8 <--> 14[Analysis]
63+
7 <--> 9[WALA]
64+
9 <--> 14[Analysis]
65+
7 <--> 10[Tree-sitter]
66+
10 <--> 14[Analysis]
67+
7 <--> 11[LLVM]
68+
11 <--> 14[Analysis]
69+
7 <--> 12[CodeQL]
70+
12 <--> 14[Analysis]
71+
72+
A --> 17[Retrieval ‡]
73+
A --> 16[Prompting ‡]
74+
75+
X[‡ Yet to be implemented]
1776
```
1877

19-
Install CodeLLM-Devkit
78+
The user interacts by invoking the CLDK API. The CLDK API is responsible for handling the user requests and delegating them to the appropriate language-specific modules.
79+
80+
Each language comprises of two key components: data models and backends.
81+
82+
1. **Data Models:** These are high level abstractions that represent the various language constructs and componentes in a structured format using pydantic. This confers a high degree of flexibility and extensibility to the models as well as allowing for easy accees of various data components via a simple dot notation. In addition, the data models are designed to be easily serializable and deserializable, making it easy to store and retrieve data from various sources.
83+
84+
85+
2. **Analysis Backends:** These are the components that are responsible for interfacing with the various program analysis tools. The core backends are Treesitter, Javaparse, WALA, LLVM, and CodeQL. The backends are responsible for handling the user requests and delegating them to the appropriate analysis tools. The analysis tools perfrom the requisite analysis and return the results to the user. The user merely calls one of several high-level API functions such as `get_method_body`, `get_method_signature`, `get_call_graph`, etc. and the backend takes care of the rest.
86+
87+
Some langugages may have multiple backends. For example, Java has WALA, Javaparser, Treesitter, and CodeQL backends. The user has freedom to choose the backend that best suits their needs.
88+
89+
We are currently working on implementing the retrieval and prompting components. The retrieval component will be responsible for retrieving the relevant code snippets from the codebase for RAG usecases. The prompting component will be responsible for generating the prompts for the CodeLLMs using popular prompting frameworks such as `PDL`, `Guidance`, or `LMQL`.
90+
91+
92+
## Quick Start: Example Walkthrough
93+
94+
In this section, we will walk through a simple example to demonstrate how to use CLDK. We will:
95+
96+
* Set up a local ollama server to interact with CodeLLMs
97+
* Build a simple code summarization pipeline for a Java and a Python application.
98+
99+
### Prerequisites
100+
101+
Before we begin, make sure you have the following prerequisites installed:
102+
103+
* Python 3.11 or later
104+
* Ollama v0.3.4 or later
105+
106+
107+
### Step 1: Set up an Ollama server
108+
109+
If don't already have ollama, please download and install it from here: [Ollama](https://ollama.com/download).
110+
111+
Once you have ollama, start the server and make sure it is running.
112+
113+
If you're on MacOS, Linux, or WSL, you can check to make sure the server is running by running the following command:
20114

21115
```bash
22-
pip install -U /path/to/cloned/repo
116+
sudo systemctl status ollama
23117
```
24118

25-
## Usage
119+
You should see an output similar to the following:
120+
121+
```bash
122+
➜ sudo systemctl status ollama
123+
● ollama.service - Ollama Service
124+
Loaded: loaded (/etc/systemd/system/ollama.service; enabled; preset: enabled)
125+
Active: active (running) since Sat 2024-08-10 20:39:56 EDT; 17s ago
126+
Main PID: 23069 (ollama)
127+
Tasks: 19 (limit: 76802)
128+
Memory: 1.2G (peak: 1.2G)
129+
CPU: 6.745s
130+
CGroup: /system.slice/ollama.service
131+
└─23069 /usr/local/bin/ollama serve
132+
```
26133

27-
### 1. Obtain sample application to experiment with (we'll use Daytrader 8 as an example)
134+
If not, you may have to start the server manually. You can do this by running the following command:
28135

29136
```bash
30-
wget https://github.com/OpenLiberty/sample.daytrader8/archive/refs/tags/v1.2.tar.gz
137+
sudo systemctl start ollama
31138
```
32139

33-
Extract the archive and navigate to the `daytrader8` directory:
140+
#### Pull the latest version of Granite 8b instruct model from ollama
141+
142+
To pull the latest version of the Granite 8b instruct model from ollama, run the following command:
34143

35144
```bash
36-
tar -xvf v1.2.tar.gz
37-
tar -xvf v1.2.tar.gz
145+
ollama pull granite-code:8b-instruct
38146
```
39147

40-
Save the location to where daytrader8 is extracted to, as we will need it later:
148+
Check to make sure the model was successfully pulled by running the following command:
41149

42150
```bash
43-
export DAYTRADER8_DIR=/path/to/sample.daytrader8-1.2
151+
ollama run granite-code:8b-instruct 'Write a function to print hello world in python'
44152
```
45153

46-
Then you can use the following command to run the codeanalyzer:
154+
The output should be similar to the following:
155+
156+
```
157+
➜ ollama run granite-code:8b-instruct 'Write a function to print hello world in python'
158+
159+
def say_hello():
160+
print("Hello World!")
161+
```
162+
163+
### Step 2: Install CLDK
164+
165+
You may install the latest version of CLDK from our GitHub repository:
166+
167+
```python
168+
pip install git+https://github.com/IBM/codellm-devkit.git
169+
```
170+
171+
Once CLDK is installed, you can import it into your Python code:
172+
173+
```python
174+
from cldk import CLDK
175+
```
176+
177+
### Step 3: Build a code summarization pipeline
178+
179+
Now that we have set up the ollama server and installed CLDK, we can build a simple code summarization pipeline for a Java application.
180+
181+
1. Let's download a sample Java (apache-commons-cli):
182+
183+
* Download and unzip the sample Java application:
184+
```bash
185+
wget https://github.com/apache/commons-cli/archive/refs/tags/rel/commons-cli-1.7.0.zip -O commons-cli-1.7.0.zip && unzip commons-cli-1.7.0.zip
186+
```
187+
* Record the path to the sample Java application:
188+
```bash
189+
export JAVA_APP_PATH=/path/to/commons-cli-1.7.0
190+
```
191+
192+
193+
Below is a simple code summarization pipeline for a Java application using CLDK. It does the following things:
194+
195+
* Creates a new instance of the CLDK class (see comment `# (1)`)
196+
* Creates an analysis object over the Java application (see comment `# (2)`)
197+
* Iterates over all the files in the project (see comment `# (3)`)
198+
* Iterates over all the classes in the file (see comment `# (4)`)
199+
* Iterates over all the methods in the class (see comment `# (5)`)
200+
* Gets the code body of the method (see comment `# (6)`)
201+
* Initializes the treesitter utils for the class file content (see comment `# (7)`)
202+
* Sanitizes the class for analysis (see comment `# (8)`)
203+
* Formats the instruction for the given focal method and class (see comment `# (9)`)
204+
* Prompts the local model on Ollama (see comment `# (10)`)
205+
* Prints the instruction and LLM output (see comment `# (11)`)
47206

48207
```python
49-
import os
50-
from rich import print # Optional, for pretty printing.
208+
# code_summarization_for_java.py
209+
51210
from cldk import CLDK
52-
from cldk.models.java.models import *
53-
54-
# Initialize the Codellm-DevKit object with the project directory, language, and backend.
55-
cldk = CLDK(language="java")
56-
57-
analysis = cldk.analysis(
58-
project_path=os.getenv("DAYTRADER8_DIR"),
59-
analysis_backend="codeanalyzer",
60-
analysis_json_path="/tmp",
61-
eager=True,
62-
analysis_level='call-graph'
63-
)
64-
# Get the java application view for the project. The application view is a representation of the project as a graph with all the classes, methods, and fields.
65-
app: JApplication = analysis.get_application_view()
66-
67-
# Get all the classes in the project.
68-
classes_dict = analysis.get_classes()
69-
print(classes_dict)
211+
212+
213+
def format_inst(code, focal_method, focal_class):
214+
"""
215+
Format the instruction for the given focal method and class.
216+
"""
217+
inst = f"Question: Can you write a brief summary for the method `{focal_method}` in the class `{focal_class}` below?\n"
218+
219+
inst += "\n"
220+
inst += f"```{language}\n"
221+
inst += code
222+
inst += "```" if code.endswith("\n") else "\n```"
223+
inst += "\n"
224+
return inst
225+
226+
def prompt_ollama(message: str, model_id: str = "granite-code:8b-instruct") -> str:
227+
"""Prompt local model on Ollama"""
228+
response_object = ollama.generate(model=model_id, prompt=message)
229+
return response_object["response"]
230+
231+
232+
if __name__ == "__main__":
233+
# (1) Create a new instance of the CLDK class
234+
cldk = CLDK(language="java")
235+
236+
# (2) Create an analysis object over the java application
237+
analysis = cldk.analysis(project_path=os.getenv("JAVA_APP_PATH"))
238+
239+
# (3) Iterate over all the files in the project
240+
for file_path, class_file in analysis.get_symbol_table().items():
241+
class_file_path = Path(file_path).absolute().resolve()
242+
# (4) Iterate over all the classes in the file
243+
for type_name, type_declaration in class_file.type_declarations.items():
244+
# (5) Iterate over all the methods in the class
245+
for method in type_declaration.callable_declarations.values():
246+
247+
# (6) Get code body of the method
248+
code_body = class_file_path.read_text()
249+
250+
# (7) Initialize the treesitter utils for the class file content
251+
tree_sitter_utils = cldk.tree_sitter_utils(source_code=code_body)
252+
253+
# (8) Sanitize the class for analysis
254+
sanitized_class = tree_sitter_utils.sanitize_focal_class(method.declaration)
255+
256+
# (9) Format the instruction for the given focal method and class
257+
instruction = format_inst(
258+
code=sanitized_class,
259+
focal_method=method.declaration,
260+
focal_class=type_name,
261+
)
262+
263+
# (10) Prompt the local model on Ollama
264+
llm_output = prompt_ollama(
265+
message=instruction,
266+
model_id="granite-code:20b-instruct",
267+
)
268+
269+
# (11) Print the instruction and LLM output
270+
print(f"Instruction:\n{instruction}")
271+
print(f"LLM Output:\n{llm_output}")
70272
```

0 commit comments

Comments
 (0)