openai的API实现代码函数检索

  • 从代码库中先把所有的函数提取出来
import os
from glob import glob
import pandas as pd

def get_function_name(code):
    assert code.startswith("def ")
    return code[len("def "): code.index("(")]

def get_until_no_space(all_lines, i) -> str:
    ret = [all_lines[i]]
    for j in range(i + 1, i + 10000):
        if j < len(all_lines):
            if len(all_lines[j]) == 0 or all_lines[j][0] in [" ", "\t", ")"]:
                ret.append(all_lines[j])
            else:
                break
    return "\n".join(ret)

def get_functions(filepath):
    whole_code = open(filepath).read().replace("\r", "\n")
    all_lines = whole_code.split("\n")
    for i, l in enumerate(all_lines):
        if l.startswith("def "):
            code = get_until_no_space(all_lines, i)
            function_name = get_function_name(code)
            yield {"code": code, "function_name": function_name, "filepath": filepath}


root_dir = os.path.expanduser("~")

code_root = root_dir + "/python"

code_files = [y for x in os.walk(code_root) for y in glob(os.path.join(x[0], '*.py'))]
print("Total number of py files:", len(code_files))

if len(code_files) == 0:
    print("no code files")

all_funcs = []
for code_file in code_files:
    funcs = list(get_functions(code_file))
    for func in funcs:
        all_funcs.append(func)

print("Total number of functions extracted:", len(all_funcs))

OpenAI API中的get_embedding是用于获取给定文本的向量表示的方法。它使用OpenAI的预训练模型,将输入文本转换为一个向量,该向量可用于计算文本之间的相似性或进行其他自然语言处理任务。
get_embedding方法接受一个文本字符串作为输入,并返回一个表示该文本的向量。这个向量通常是一个具有固定维度的浮点数数组。该方法可以用于多种应用,例如文本分类、聚类、信息检索、自动摘要、机器翻译等。
需要注意的是,get_embedding方法返回的向量是基于OpenAI的预训练模型计算得出的,并且可能不适用于某些特定应用场景,因此需要根据具体应用情况选择合适的方法和模型。

from openai.embeddings_utils import get_embedding

df = pd.DataFrame(all_funcs)
df['code_embedding'] = df['code'].apply(lambda x: get_embedding(x, engine='text-embedding-ada-002'))
df['filepath'] = df['filepath'].apply(lambda x: x.replace(code_root, ""))
df.to_csv("data/code_search_python.csv", index=False)
df.head()

定义搜索函数

from openai.embeddings_utils import cosine_similarity

def search_functions(df, code_query, n=3, pprint=True, n_lines=7):
    embedding = get_embedding(code_query, engine='text-embedding-ada-002')
    df['similarities'] = df.code_embedding.apply(lambda x: cosine_similarity(x, embedding))

    res = df.sort_values('similarities', ascending=False).head(n)
    if pprint:
        for r in res.iterrows():
            print(r[1].filepath+":"+r[1].function_name + "  score=" + str(round(r[1].similarities, 3)))
            print("\n".join(r[1].code.split("\n")[:n_lines]))
            print('-'*70)
    return res
    
#调用搜索
res = search_functions(df, '想要搜索的函数内容', n=3)

深度学习模型列举
python的opencv库使用模板匹配
Python的opencv库进行物体跟踪
Python的opencv库使用行人检测
Python的使用opencv库人脸识别
Python的opencv库使用Haar 级联检测
Python的opencv库使用FAST 算法进行特征检测
Python的opencv库使用ORB算法 进行特征检测
Python的opencv库使用SURF 进行特征检测
Python的opencv库使用SIFT 进行特征检测
opencv库的功能
运动控制卡的运动控制介绍
介绍一下labview
运动控制卡
c# 如何调用Halcon 进行人脸识别
python如何使用halcon识别二维码
windows程序如何转linux开发
linux 的gdb软件如何使用
c#如何使用 USB(Universal Serial Bus)进行通信
数字化器Digitizer框架

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

openwin_top

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值