页面简介
Powered by Ray, Anyscale empowers AI builders to run and scale all ML and AI workloads on any cloud and on-prem.
正文摘录
HomeBlogBlog DetailBuilding an LLM-powered GitHub bot to improve your pull requestsBy Max Pumperla | November 15, 2023Update June 2024: Anyscale Endpoints (Anyscale's LLM API Offering) and Private Endpoints (self-hosted LLMs) are now available as part of the Anyscale Platform. Click here to get started on the Anyscale platform. [ Code | Install the bot | Anyscale Endpoints | Ray Docs ] · 30 min readTechnical writing is hard. Developers want to focus on their core coding responsibilities, but it’s inevitable for technical experts to also participate in documentation efforts. Often, nobody else could even write the content in question. This means that many pull requests contain both code and plain English (or other natural languages). At Anyscale, we’ve embraced the Google developer doc style guide, and recommend using Vale to enforce it. But in practice it can happen that one slips up and introduces minor syntax or grammar errors. In fact, if you’re focusing mostly on code quality, writing quality might just not be top of mind. Ineffective or misleading formulations can be the result of that.By developing a bot that helps spot mistakes and inconsistencies in an automated fashion, developers get valuable feedback – directly in their PRs on GitHub. Let’s have a look at what Docu Mentor does for you in practice.In this guide you’ll learn to:💻 Build an LLM-powered bot, using Anyscale Endpoints and Anyscale Services, from scratch.🚀 Scale out the bot’s workload efficiently using Ray.✅ Evaluate the bot’s performance with the help of GPT-4 as evaluator by writing automated tests.🔀 Learn to leverage the GitHub API to hook into your pull requests and issues.📦 Deploy your bot and make it publicly available.💡 Create, deploy and share your own GitHub bots.LinkIntroducing Docu Mentordocumentor-imageTwo months ago we introduced Anyscale Endpoints as a cost-effective way to work with powerful open-source LLMs. We offer Endpoints to our customers, but we also use it internally to run experiments and constantly improve our own products. For instance, we concluded that you can run summarization tasks as well as GPT-4 with much cheaper Endpoints models, and we fine-tuned models available on Endpoints for domain-specific tasks.In this post we’re building a GitHub bot called “Docu Mentor” that you can mention in your pull requests to help you improve your writing. The bot is already up, and you can install it from GitHub in just a few clicks. The code for this whole app clocks in at just 250 lines of code and is freely available on GitHub. You can fork it, modify it, and build your own app in no time, and we’ll show you exactly how in this post.LinkDocu Mentor in actionAfter you install the bot in your repo, whenever you open a new pull request, the @docu-mentor bot will write a friendly helper message as a GitHub issue comment into your PR.documentor-pull-requestYou can trigger the bot by simply creating a comment of your own saying “@docu-mentor run”. This will analyze all the changes you’ve made in this PR, to give you suggestions on how to improve it. Often, most of the files in your PR will just be code changes, so if you’re seeking feedback on a single file or a specific folder, you can point Docu Mentor to those files. Here’s an example of me asking the bot to comment on the changes I’ve made in my README.md:documentor-botAfter a couple of seconds, Docu Mentor will get back to you with the results of its analysis. You can then incorporate that feedback into your PR to the extent you want.docu-mentor-bot2LinkHow Docu Mentor worksAt the core of our bot is a call to the codellama/CodeLlama-34b-Instruct-hf model, for which we’re using Anyscale Endpoints. Our Python API leverages the “openai” Python package from OpenAI. In fact, it’s a drop-in-replacement for it, given that you set the right API key and endpoint URL as follows:1import os 2import openai 3 4ANYSCALE_API_ENDPOINT = "https://api.endpoints.anyscale.com/v1" 5openai.api_base = ANYSCALE_API_ENDPOINT 6# Set this env variable to your Anyscale Endpoints API KEY 7openai.api_key = os.environ.get("ANYSCALE_API_KEY")To query any LLM, we have to craft a prompt and pass it to the LLM. This is the main instruction for the Docu Mentor bot:1SYSTEM_CONTENT = """You are a helpful assistant. 2Improve the following <content>. Criticise syntax, grammar, punctuation, style, etc. 3Recommend common technical writing knowledge, such as used in Vale 4and the Google developer documentation style guide. 5If the content is good, don't comment on it. 6You can use GitHub-flavored markdown syntax in your answer. 7""" 8 9PROMPT = """Improve this content. 10Don't comment on file names or other meta data, just the actual text. 11The <content> will be in JSON format and contains file name keys and text values. Make sure to give very concise feedback per file. 12"""We’ve set this instruction up for the system to take file-content input pairs, as this is the natural way to represent changes in pull requests. We’ll take care of dealing with the intricacies of the GitHub API much later. For now, consider the following “mentor” function as the central building block of our app:1def mentor( 2 content, 3 model="codellama/CodeLlama-34b-Instruct-hf", 4 system_content=SYSTEM_CONTENT, 5 prompt=PROMPT 6 ): 7 result = openai.ChatCompletion.create( 8 model=model, 9 messages=[ 10 {"role": "system", "content": system_content}, 11 {"role": "user", "content": f"This is the content: {content}. {prompt}"}, 12 ], 13 temperature=0, 14 ) 15 usage = result.get("usage") 16 prompt_tokens = usage.get("prompt_tokens") 17 completion_tokens = usage.get("completion_tokens") 18 content = result["choices"][0]["message"]["content"] 19 20 return content, model, prompt_tokens, completion_tokensAs you can see, this code snippet is leveraging the OpenAI API, but because we set an Anyscale Endpoints URL and API key, we can query faster and cheaper models such as CodeLlama here.LinkParallelizing LLM queries efficiently with RayWe have not explicitly discussed yet what the “content” is that we want to send to the “mentor” function. Our goal is to analyze pull requests. PRs are expressed as differences (“diffs”) between the branch in which you made changes and the base branch that you want to merge your changes to. Normally, a PR touches many files, so it’s natural to analyze diffs per file. Now, if your PR not only changes many files, but also touches many lines of code, naively passing the complete diff as “content” to Docu Mentor will not be a good idea.To address this issue, we can instead send one query per file-diff to “mentor” by leveraging Ray. This improves response quality and speed, as the number of input tokens is kept relatively small. We can do this quite easily by first creating a Ray task called “mentor_task” that simply passes through to our previous “mentor” function, by simply adding the “@ray.remote” decorator.1import ray 2 3@ray.remote 4def mentor_task(content, model, system_content, prompt): 5 return mentor(content, model, system_content, prompt)With that, we can define a distributed version of “mentor” by calling “mentor_task.remote(content,...)” for per-file content for a PR like this:1def ray_mentor( 2 content: dict, 3 model="codellama/CodeLlama-34b-Instruct-hf", 4 system_content=SYSTEM_CONTENT, 5 prompt="Improve this content." 6 ): 7 futures = [ 8 mentor_task.remote(v, model, system_content, prompt) 9 for v in content.values() 10 ] 11 suggestions = ray.get(futures) 12 content = {k: v[0] for k, v in zip(content.keys(), suggestions)} 13 prompt_tokens = sum(v[2] for v in suggestions) 14 completion_tokens = sum(v[3] for v in suggestions) 15 16 print_content = "" 17 for k, v in content.items(): 18 print_content += f"{k}:\n\t\{v}\n\n" 19 logger.info(print_content) 20 21 return print_content, model, prompt_tokens, completion_tokensNote how “ray_mentor” is just splitting up files and remotely executing “mentor_task” on individual file content. The results then need to be aggregated to fit into a single response that we can write to a GitHub comment. Here’s a visualization of this process:docu-mentor-processLinkEvaluating the approachBefore we throw any real user data against our “mentor” query, we have to investigate if using this model and prompt gives us the results we want. But what are realistic expectations for this system, and what makes the answer of our bot good or suitable? After all, we are not aware of any grammar- or style-correcting benchmarks we could test against our system. Human judgment, as is often the case with applications like this, is the ultimate litmus test, but extensive experimentation with human feedback is expensive and impossible to automate – by definition.An interesting approach that can be fully automated is the following:Pick the strongest available general-purpose LLM on the market, currently GPT-4.Use this model to generate a collection of sentences and paragraphs that have grammatical, syntactic, or stylistic deficiencies.Use this collection as test fixtures to define a set of tests for our bot:First, run our “mentor” function against this collection and return the results.Next, use GPT-4 as an evaluator of the results, by asking this stronger LLM if the proposed “mentor” results are considered good.Run the tests and generate a report that evaluates how much GPT-4 agrees with the results of our bot.If a certain threshold of agreement (X% of test sentences yield good results) is surpassed, consider the test as passing and the bot as strong enough.automated-processWe implemented this approach as unit tests in the docu-mentor GitHub repo. In our experience, GPT-4 can sometimes be overly critical in this scenario. This is why it’s not easy to set a good “agreement” threshold. Frankly speaking, it’s not trivial for two humans to agree on matters of style either. But judging from the results of evaluation, Docu Mentor passes GPT-4’s critical view at least 90% of the time when correcting flawed s