Function Assistant: A Tool for NL Querying of APIs
FFunction Assistant : A Tool for NL Querying of APIs
Kyle Richardson and
Jonas Kuhn
Institute for Natural Language ProcessingUniversity of Stuttgart [email protected]
Abstract
In this paper, we describe
FunctionAssistant , a lightweight Python-basedtoolkit for querying and exploring sourcecode repositories using natural language.The toolkit is designed to help end-usersof a target API quickly find informationabout functions through high-level natu-ral language queries and descriptions. Fora given text query and background API,the tool finds candidate functions by per-forming a translation from the text toknown representations in the API usingthe semantic parsing approach of Richard-son and Kuhn (2017). Translations areautomatically learned from example text-code pairs in example APIs. The toolkitincludes features for building translationpipelines and query engines for arbitrarysource code projects. To explore this lastfeature, we perform new experiments on27 well-known Python projects hosted onGithub.
Software developers frequently shift between us-ing different third-party software libraries, orAPIs, when developing new applications. Much ofthe development time is dedicated to understand-ing the structure of these APIs, figuring out wherethe target functionality lies, and learning about thepeculiarities of how such software is structured orhow naming conventions work. When the targetAPI is large, finding the desired functionality canbe a formidable and time consuming task. Of-ten developers resort to resources like Google orStackOverflow to find (usually indirect) answersto questions.We illustrate these issues in Figure 1 using two c l a s s
DependencyGraph ( object ) : """A container ....for a dependency structure""" def remove by address ( s e l f , a d d r e s s ) : """Removes the node with the given address.""" def a d d a r c ( s e l f , head address , mod address ) : """Adds an arc from the node specified byhead_address to the node specified bythe mod address...."""
Figure 1: Example function documentation inPython NLTK about dependency graphs.example functions from the well-known NLTKtoolkit. Each function is paired with a short docstring , i.e., the quoted description under eachfunction, which provides a user of the softwarea description of what the function does. Whileunderstanding the documentation and code re-quires technical knowledge of dependency pars-ing and graphs, even with such knowledge, thefunction naming conventions are rather arbitrary.The function add arc could just as well becalled create arc . An end-user expecting an-other naming convention might be left astray whensearching for this functionality. Similarly, theavailable description might deviate from how anend-user would describe such functionality.Understanding the remove by address function, in contrast, requires knowing thedetails of the particular
DependencyGraph implementation being used. Nonetheless, thefunction corresponds to the standard operation of removing a node from a dependency graph. Here,the technical details about how this removal isspecific to a given address might obfuscate theoverall purpose of the function, making it hard tofind or understand. a r X i v : . [ c s . C L ] S e p t a first approximation, navigating a given APIrequires knowing correspondences between tex-tual descriptions and source code representations.For example, knowing that the English expression Adds an arc in Figure 1 translates (somewhat ar-bitrarily) to add arc , or that given address trans-lates to address . One must also know how todetect paraphrases of certain target entities or ac-tions, for example that adding an arc means thesame as creating an arc in this context. Othertechnical correspondences, such as the relation be-tween an address and the target dependencygraph implementation, must be learned.In our previous work (Richardson and Kuhn(2017), henceforth RK), we look at learning thesetypes of correspondences from example API col-lections in a variety of programming languagesand source natural languages. We treat eachgiven API, consisting of text and function rep-resentation pairs, as a parallel corpus for train-ing a simple semantic parsing model. In addi-tion to learning translational correspondences, ofthe type described above, we achieve improve-ments by adding document-level features that helpto learn other technical correspondences.In this paper, we focus on using our models asa tool for querying API collections. Given a tar-get API, our model learns an MT-based seman-tic parser that translates text to code representa-tions in the API. End-users can formulate naturallanguage queries to the background API, whichour model will translate into candidate functionrepresentations with the goal of finding the de-sired functionality. Our tool, called
FunctionAssistant can be used in two ways: as a black-box pipeline for building models directly from ar-bitrary API collections. As well, it can be cus-tomized and integrated with other outside compo-nents or models using the tool’s flexible internalPython API.In this paper, we focus on the first usage of ourtool. To explore building models for new API col-lections, we run our pipeline on 27 open sourcePython projects from the well-known
AwesomePython project list. As in previous work, weperform synthetic experiments on these datasets,which measure how well our models can generatefunction representations for unseen API descrip-tions, which mimic user queries. github.com/vinta/awesome-python Natural language querying of APIs has long beena goal in software engineering, related to the gen-eral problem of software reuse (Krueger, 1992).To date, a number of industrial scale productsare available in this area. To our knowledge,most implementations use shallow term match-ing and/or information-extraction techniques (Lvet al., 2015), differing from our methods that usemore conventional NLP components and tech-niques. As we show in this paper and in RK, termmatching and related techniques can sometimesserve as a competitive baseline, but are almost al-ways outperformed by our translation approach.More recently, there has been increased interestin machine learning on learning code representa-tions from APIs, especially using resources suchas GitHub or StackOverflow. However, this worktends to look at learning from many API collec-tions (Gu et al., 2016), making such systems hardto evaluate and to apply to querying specific APIs.Other work looks at learning to generate longercode from source code annotations for natural lan-guage programming (Allamanis et al., 2015), of-ten focusing narrowly on a specific programminglanguage (e.g., Java) or set of APIs. To our knowl-edge, none of these approaches include companionsoftware that facilitate building custom pipelinesfor specific APIs and querying.Technically, our approach is related to workon semantic parsing, which looks at generatingformal representations from text input for natu-ral language understanding applications, notablyquestion-answering. Many existing methods takedirect inspiration from work on MT (Wong andMooney, 2006) and parsing (Zettlemoyer andCollins, 2009). Please see RK for more discussionand pointers to related work.
In this paper, we focus on learning to generatefunction representations from textual descriptionsinside of source code collections, or APIs. Wewill refer to these target function representationsas
API components . Each component specifies afunction name, a list of arguments, and other op-tional information such as a namespace.Given a set of example text-component pairsfrom an example API, D = { ( x i , z i ) } ni =1 , the goal e.g., s to learn how to generate correct, well-formedcomponents z ∈ C for each text x . When viewedas a semantic parsing problem, we can view each z as analogous to a target logical form. In this paper,we focus narrowly on Python source code projects,and thus Python functions z , however our methodsare agnostic to the input natural language and out-put programming language as shown in RK.When used for querying, our model takes a textinput and attempts to generate the desired func-tion representation. Technically, our approach fol-lows our previous work and has two components:a simple and lightweight word-based translationmodel that generates candidate API components,and a discriminative model that reranks the trans-lation model output using additional phrase anddocument-level features. All of these models areimplemented natively in our tool, and we describeeach part in turn. Given an input text (or query) sequence x = w , .., w | x | , the goal is to generate an output APIcomponent z = u i , .., u | z | , which involves learn-ing a conditional distribution p ( z | x ) . We pursuea noisy-channel approach, where p ( z | x ) ∝ p ( x | z ) p ( z ) By assuming a uniform prior p ( z ) on outputcomponents, the model therefore involves com-puting p ( x | z ) , which under a word-based trans-lation model can be expressed as: p ( x | z ) = (cid:88) a p ( x, a | z ) where the summation ranges over the set of allmany-to-one (word) alignments a from x → z .While many different formulations of word-based models exist, we previously found that thesimplest lexical translation model, or IBM Model1 (Brown et al., 1993), outperforms even higher-order alignment models with location parameters.This model computes all alignments exactly usingthe following equation: p ( x | z ) ≈ | x | (cid:89) j =1 | z | (cid:88) i =0 p t ( w j | u i ) (1)where p t defines a multinomial distribution over agiven component term u j for all words w j . While many parameter estimation strategies ex-ist for training word-based models, we similarlyfound that the simplest EM procedure of Brownet al. (1993) works the best. In RK, we describe alinear-time decoding strategy (i.e., for generatingcomponents from input) over the number of com-ponents C , which we use in this paper. Our toolalso implements our types of conventional MT de-coding strategies that are better suited for largeAPIs and more complex semantic languages. Following most semantic parsing approaches(Zettlemoyer and Collins, 2009), we use a dis-criminative log-linear model to rerank the com-ponents generated from the underlying translationmodel. Such a model defines a conditional distri-bution: p ( z | x ; θ ) ∝ e θ · φ ( x,z ) , for a parameter vec-tor θ ∈ R b , and a set of feature functions φ ( x, z ) .Our tool implements several different trainingand optimization methods. For the purpose ofthis paper, we train our models using an online,stochastic gradient ascent algorithm under a max-imum conditional log-likelihood objective. For a given text input x and output component z , φ ( x, z ) defines a set of features between thesetwo items. By default, our pipeline implementa-tion uses three classes of features, identical to thefeature set used in RK. The first class includes ad-ditional word-level features, such as word/compo-nent match, overlap, component syntax informa-tion, and so on. The second includes phrase andhierarchical phrase features between text and com-ponent candidates, which are extracted standardlyfrom symmetric word-level alignment heuristics.The other category of features includesdocument-level features. This includes informa-tion about the underlying API class hierarchy,and relations between words/phrases and abstractclasses within this hierarchy. Also, we useadditional textual description of parameters in thedocstrings to indicate whether word-componentscandidate pairs overlap in these descriptions. All of the functionality above is implemented inthe
Function Assistant toolkit. The tool ispart of the companion software release for our pre-vious work called
Zubr . For efficiency, the core params = [( ” − b a s e l i n e ” , ” b a s e l i n e ” , False , ” bool ” , ”Use b a s e l i n e model [ d e f a u l t = False ] ” , ” GPipeline ” )] t a s k s = [ ”zubr . doc extractor . DocExtractor ” , ” process data ” , ”zubr . SymmetricAlignment” , ”zubr . Dataset ” , ”zubr . FeatureExtractor ” , ”zubr . Optimizer ” , ”zubr . QueryInterface ” , ”zubr . web . QueryServer” , ] def p r o c e s s d a t a ( c o n f i g ) : """Preprocess the extracted data using a customfunction or outside library (e.g., nltk):param config: The global configuration""" p r e p r o c e s s f u n c t i o n ( config , . . . ) Figure 2: An example pipeline script for buildinga translation model and query server.functionality is written in Cython , which is acompiled superset of the Python language that fa-cilitates native C/C++ integration.The tool is designed to be used in two ways:first, as a black-box pipeline to build custom trans-lation pipelines and API query engines. The toolcan also be integrated with other components us-ing our Cython and Python API. We focus on thefirst type of functionality. Our library uses dependency-injection OOP de-sign principles. All of the core components areimplemented as wholly independent classes, eachof which has a number of associated configura-tion values. These components interact via a classcalled
Pipeline , which glues together varioususer-specified components and dependencies, andbuilds a global configuration from these compo-nents. Subsequent instantiation and sharing of ob-jects is dictated, or injected , by these global con-figurations settings, which can change dynami-cally throughout a pipeline run.Pipelines are created by writing pipeline scripts,such as the one shown in Figure 2. This file isan ordinary Python file, with two mandatory vari-ables. The first params variable specifies vari-ous high-level configuration parameters associatedwith the pipeline. In this case, there is a set-ting --baseline , which can be evoked to run http://cython.org/ a baseline experiment, and will effect the subse-quent processing pipeline.The second, and most important, variable iscalled tasks , and this specifies an ordering ofsubprocesses that should be executed. The fieldsin this list are pointers to either core utilities inthe underlying Zubr toolkit (each with the pre-fix zubr. ), or user defined functions. This par-ticular pipeline starts by building a dataset froma user specified source code repository, using
DocExtractor , then builds a symmetric trans-lation model
SymmetricAlignment , a fea-ture extractor
FeatureExtractor , a discrim-inative reranker
Optimizer , all via various in-termediate steps. It finishes by building a queryinterface and query server,
QueryInterface and
QueryServer , which can then be used forquerying the input API.As noted already, each subprocesses has a num-ber of associated configuration settings, which arejoined into a global configuration object by the
Pipeline instance. For the translation model,settings include, for example, the type of trans-lation model to use, the number of iterations touse when training models, and so on. All ofthese settings can be specified on the terminal,or in a separate configuration file. As well, theuser is free to define custom functions, such as process data , or classes which can be used tomodify the default processing pipeline or imple-ment new ML features.
The last step in this pipeline builds an HTTP webserver that can be used to query the input API. In-ternally, the server makes calls to the trained trans-lation model and discriminative reranker, whichtakes user queries and attempts to translate theminto API function representations. These candi-date translations are then returned to the user aspotential answers to the query. Depending onthe outcome, the user can either rephrase his/herquestion if the target function is not found, orlook closer at the implementation by linking to thefunction’s source code.An example screen shot of the query server isshown in Figure 3. Here, the background API isthe NLTK toolkit, and the query is
Train a se-quence tagger model . While not mentioned ex-plicitly, the model returns training functions forthe
HiddenMarkovModelTagger . The rightigure 3: An example screen shot of the
Function Assistant web server.
Project scapy
757 1,029 7,839 1,576 zipline
753 1,122 8,184 1,517 biopython renpy
912 889 10,183 1,540 pyglet kivy
820 861 7,621 1,456 pip twisted vispy orange tensorflow pandas sqlalchemy pyspark nupic astropy sympy ipython orator
817 499 6,511 670 obspy rdkit django ansible statsmodels theano nltk sklearn
Table 1: New English Github datasets.side of the image shows the hyperlink path to theoriginal source in Github for the train function.
Our current
DocExtractor implementationsupports building parallel datasets from rawPython source code collections. Internally, thetool reads source code using the abstract syntaxtree utility, ast , in the Python standard library,and extracts sets of function and description pairs.In addition, the tool also extracts class descrip-tions, parameter and return value descriptions, and information about the API’s internal class hierar-chy. This last type of information is then used todefine document-level features.To experiment with this feature, we builtpipelines and ran experiments for 27 popularPython projects. The goal of these experiments isto test the robustness of our extractor, and see howwell our models answer unseen queries for theseresources using our previous experimental setup.
The example projects are shown in Table 1. Eachdataset is quantified in terms of , or thenumber of parallel function-component represen-tations, the in the component outputlanguage, the (NL)
Words and
Vocab size.
Each dataset is randomly split into train, test, anddev. sets using a 70%-30% (or 15%/15%) split.We can think of the held-out sets as mimickingqueries that users might ask the model. Stan-dardly, all models are trained on the training sets,and hyper-parameters are tuned to the dev. sets.For a unseen text input during testing, the modelgenerates a candidate list of component outputs.An output is considered correct if it matches ex-actly the gold function representation. As before,we measure the
Accuracy @1 , accuracy withintop ten (
Accuracy @10 ), and the
MRR .As in our previous work, three additional base-lines are used. The first is a simple bag-of-words ethod scapy zipline biopython renpy pyglet kivy pip twisted vispy
BoW
Term Match 21.2
Translation
Reranker 21.2 67.2 37.2 30.3 70.5 45.3 32.3 79.1 48.6 38.9 73.5 48.9 29.0 77.1 45.5 35.7 75.6 49.1 25.9 65.8 39.9 28.8 65.8 42.2 33.5 80.4 50.3Method orange tensorflow pandas sqlalchemy pyspark nupic astropy sympy ipython
BoW
Term Match
Translation
Reranker 45.1 84.1 59.9 38.4 77.7 51.8 31.1 66.1 43.1 35.0 76.1 49.7 41.5 81.5 55.3 orator obspy rdkit django ansible statsmodels theano nltk sklearn
BoW
Term Match
Translation 32.7
Reranker 32.7 82.7 49.7 37.7 80.0 52.3 25.3 63.3 39.6 25.8 64.5 39.4 40.5 77.0 53.1 28.8 69.1 41.7 27.3 66.1 39.9 31.6 72.5 45.7 29.2 75.5 44.5Accuracy @1 Accuracy @10 Mean Reciprocal Rank (MRR)
Table 2: Test results on our new Github datasets.(
BoW ) model, which uses word-component pairsas features. The second is a
Term Match baseline,which ranks candidates according to the numberof matches between input words and componentwords. We also compare the results of the
Trans-lation (model) without the reranker.
Test results are shown in Table 2, and largelyconform to our previous findings. The
BoW and
Term Match baselines are outperformed byall other models, which again shows that APIquerying is more complicated than simple word-component matching. The
Reranker model leadsto improvements on all datasets as compared withonly using the
Translation model, indicating thatdocument-level and phrase features can help.We note that these experiments are synthetic,in the sense that it’s unclear whether the held-out examples bear any resemblance to actual userqueries. Assuming, however, that each held-outset is a representative sample of the queries thatreal users would ask, we can then interpret the re-sults as indicating how well our models answerqueries. Whether or not these held-out examplesreflect real queries, we believe that they still pro-vide a good benchmark for model construction.All code and data will be released to facilitate fur-ther experimentation and application building. Fu-ture work will look at eliciting more naturalisticqueries (e.g., through StackOverflow), and doingusage studies via a permanent web demo . We introduce
Function Assistant , a lightweighttool for querying API collections using uncon- see demo here: http://zubr.ims.uni-stuttgart.de/ strained natural language. Users can supply ourtool with target source code projects and build cus-tom translation or processing pipelines and queryservers from scratch. In addition to the tool,we also created new resources for studying APIquerying, in the form of datasets built from 27popular Github projects. While our approach usessimple components, we hope will that our tooland resources will serve as a benchmark for fu-ture work in this area, and ultimately help to solveeveryday software search and reusability issues. References
Miltiadis Allamanis, Daniel Tarlow, Andrew D Gor-don, and Yi Wei. 2015. Bimodal modelling ofsource code and NL. In
Proceedings of ICML .Peter F Brown, Vincent J Della Pietra, Stephen A DellaPietra, and Robert L Mercer. 1993. The mathemat-ics of SMT.
Computational linguistics , 19(2).Xiaodong Gu, Hongyu Zhang, Dongmei Zhang, andSunghun Kim. 2016. Deep API Learning. arXivpreprint arXiv:1605.08535 .Charles W. Krueger. 1992. Software reuse.
ACM Com-puting Surveys (CSUR) , 24(2).Fei Lv, Hongyu Zhang, Jian-guang Lou, ShaoweiWang, Dongmei Zhang, and Jianjun Zhao. 2015.Codehow: Effective code search based on api under-standing and extended boolean model (e). In
Pro-ceedings of ASE .Kyle Richardson and Jonas Kuhn. 2017. Learning Se-mantic Correspondences in Technical Documenta-tion. In
Proceedings of ACL .Yuk Wah Wong and Raymond J. Mooney. 2006. Learn-ing for Semantic Parsing with Statistical MachineTranslation. In
Proceedings of HLT-NAACL .Luke S. Zettlemoyer and Michael Collins. 2009.Learning context-dependent mappings from sen-tences to logical form. In