一、根据文心一言千帆【自动代码生成】

  • 你是不是有很多大模型想法,可是由于技术原因无法完结?
  • 你是不是有一些经过web页面完结的prompt,可是一直想要chatgpt模式的api构建自己运用,但苦于无接口可调用?
  • 你想要集成文心一言到你的项目里,苦于没有代码参考?
  • 你想要多伦对话跟文心一言一样的网页版?
  • 你想要你的大模型智能?

我们期待文心一言API敞开好几天了,那么项目来了,本项目是根据千帆API构建自己的代码生成器,十分便利。

1.效果图

1.1第一版

基于【文心一言】千帆API的自动代码生成助手

1.2第二版

基于【文心一言】千帆API的自动代码生成助手

2.前情提要

  • 需求了解一点gradio常识 www.gradio.app/
  • 需求了解一点python常识

二、开通千帆 & 学习帮助文档

1.请求 cloud.baidu.com/product/wen…

基于【文心一言】千帆API的自动代码生成助手

现在经过速度很快,基本上2小时就经过。

2.请求大模型权限

基于【文心一言】千帆API的自动代码生成助手

3.请求鉴权

url: cloud.baidu.com/doc/WENXINW…


# 填充API Key与Secret Key
import requests
import json
def main():
    url = "https://aip.baidubce.com/oauth/2.0/token?client_id=【API Key】&client_secret=【Secret Key】&grant_type=client_credentials"
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")
if __name__ == '__main__':
    access_token = main()
    print(access_token)

4.大模型运用文档

url:cloud.baidu.com/doc/WENXINW…


import requests
import json
def get_access_token():
    """
    运用 API Key,Secret Key 获取access_token,替换下列示例中的运用API Key、运用Secret Key
    """
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=[运用API Key]&client_secret=[运用Secret Key]"
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")
def main():
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + get_access_token()
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "请介绍一下你自己"
            },
            {
                "role": "assistant",
                "content": "我是百度公司开发的人工智能言语模型,我的中文名是文心一言,英文名是ERNIE-Bot,能够协助您完结范围广泛的任务并供给有关各种主题的信息,比如答复问题,供给界说和解说及主张。如果您有任何问题,请随时向我提问。"
            },
            {
                "role": "user",
                "content": "我在上海,周末能够去哪里玩?"
            },
            {
                "role": "assistant",
                "content": "上海是一个充满活力和文化氛围的城市,有很多适宜周末玩耍的当地。以下是几个值得推荐的当地:
1. 上海科技馆:上海科技馆是我国大陆最大的科技馆之一,有许多互动展览和科学实验室,能够让您了解科技的发展前史和最新成果。
2. 上海博物馆:上海博物馆是一座集艺术、前史和文化于一体的博物馆,有许多精美的艺术品和文物,能够让您深入了解我国和世界的文化前史。
3. 外滩:外滩是上海的标志性景点之一,有许多高楼大厦和繁华的商业街区,是赏识黄浦江美景和城市面貌的好去处。
4. 上海迪士尼乐土:上海迪士尼乐土是世界上最大的迪士尼主题公园之一,有许多精彩的游乐项目和表演,能够让您纵情享受娱乐和欢喜。
5. 上海野生动物园:上海野生动物园是一个以自然保护为主题的野生动物园,有许多珍稀动物和植物,能够让您近距离触摸大自然。
这些当地都是上海周末玩耍的好去处,能够根据自己的兴趣和需求挑选适宜的行程。"
            },
            {
                "role": "user",
                "content": "上海有哪些美食?"
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.text)
if __name__ == '__main__':
    main()

三、gradio脚本编写

1. 基本思路

  • 1.获取的token
  • 2.调用大模型接口
  • 3.绑定gradio展现

2.鉴权token获取

注意:client_id client_secret替换成你自己的

import requests
import json
def main():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=xxxxxxxxxxxxxxxxx&client_secret=yyyyyyyyyyyyyy"
    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.text)
if __name__ == '__main__':
    main()

3.gradio代码

注意:

  • mykey替换成你自己的
  • gradio文件名有必要以 gradio.py结尾,好多人没这么写布置不来。

3.1 code.gradio.py

# coding=utf-8
import json
import os
import gradio as gr
import requests
APIKEY = os.environ.get("APIKEY")
APISECRET = os.environ.get("APISECRET")
prompt = "我期望你充任算法专家,请你帮我给出算法解决我的问题,你应该运用你的计算机科学、网络基础设施和 IT 安全常识来解决我的问题。在您的答复中运用适宜所有级别的人的智能、简单和易于了解的言语将很有帮助,用关键逐步解说您的解决方案很有帮助,尽量避免过多的技术细节,但在必要时运用它们,我期望您回复解决方案,而不是写任何解说;以下是我的技术问题信息:"
def predict(prompt, lang):
    global APIKEY
    global APISECRET
    if prompt == '':
        return '输入不应该为空!'
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 替换你的token
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": prompt + f"运用{lang}编程言语描绘"
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request("POST", url, headers=headers, data=payload)
    except Exception as e:
        return '超时! 请稍候几分钟再试'
    answer = json.loads(response.text)['result']
    return prompt + answer
def main():
    gr.close_all()
    examples = []
    with open("./example_inputs.jsonl", "r") as f:
        for line in f:
            examples.append(list(json.loads(line).values()))
    with gr.Blocks() as demo:
        gr.Markdown("""<img src="https://paddlepaddle-org-cn.cdn.bcebos.com/paddle-site-front/static/media/banner.015c4d20.png"/>
            <h1><center>文心一言千帆自动代码生成</center></h1>
             <h2><center>本项目根据文心一言千帆API, 供给自动代码生成,欢迎品尝 !</center></font>""")
        with gr.Row():
            with gr.Column():
                prompt = gr.Textbox(lines=13, placeholder='请在下面输入描绘或挑选一个示例输入。', label='Input')
                with gr.Row():
                    gen = gr.Button("一键生成")
                    clr = gr.Button("✨一键清理✨")
            outputs = gr.Textbox(lines=15, label='Output')
        gr.Markdown(
            """
            生成参数
            """)
        with gr.Row():
            lang = gr.Radio(
                choices=["C++", "C", "C#", "Python", "Java", "HTML", "PHP", "JavaScript", "TypeScript", "Go",
                         "Rust",
                         "SQL", "Kotlin", "R", "Fortran"], value='lang', label='编程言语挑选',
                default="Python")
        inputs = [prompt, lang]
        gen.click(fn=predict, inputs=inputs, outputs=outputs)
        clr.click(fn=lambda value: gr.update(value=""), inputs=clr, outputs=prompt)
        gr_examples = gr.Examples(examples=examples, inputs=[prompt, lang],
                                  label="输入示例 (点击挑选比如)",
                                  examples_per_page=20)
    demo.launch()
if __name__ == '__main__':
    main()

3.2 example_inputs.jsonl示例文件

{"code": "# Write a function that returns the sum of the numbers from 1 to n.\n# For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\n\n# You may assume that n is a positive integer.\ndef sum_of_numbers(n):", "langauge": "Python"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n.\n// For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\n\n#include <iostream>\nusing namespace std;\nint sum_of_numbers(int n) {", "langauge": "C++"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n.\n// For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\n\n#include <stdio.h>\n#include <stdlib.h>\nint sum(int n)\n{", "langauge": "C"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n.\n// For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\nprivate int sum(int n) {", "langauge": "C#"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n.\n// For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\n\npublic class SumOfNumbers {", "langauge": "Java"}
{"code": "<!--Write a homepage of CodeGeeX.-->\n\n<div class=\"container\">", "langauge": "HTML"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n.\n// For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\n// If n is 0, then the function should return 0.\n// If n is less than 0, then the function should return -1.\n/**\n * @param {number} n\n * @return {number}\n */\nfunction sum ($n) {", "langauge": "PHP"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n.\n// For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\n\nfunction sum(n) {", "langauge": "JavaScript"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n,\n// but using a for loop instead of a while loop.\n\nfunction sumForLoop(n) {", "langauge": "TypeScript"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n,\n// but using a for loop instead of a while loop.\n\nfunc sumN(n int) int {", "langauge": "Go"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n,\n// but using a for loop instead of a while loop.\n\nfn sum_numbers(n: usize) -> usize {", "langauge": "Rust"}
{"code": "-- Search all the records from the table CodeGeeX\n-- Delete iterms with odd indices", "langauge": "SQL"}
{"code": "// Write a function that returns the sum of the numbers from 1 to n.\n// For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\n\nfun sum(n: Int): Int {", "langauge": "Kotlin"}
{"code": "! Write a function that returns the sum of the numbers from 1 to n.\n! For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\n\n! Use the following header:\n! module sum_numbers\n! end\nmodule sum_numbers", "langauge": "Fortran"}
{"code": "# Write a function that returns the sum of the numbers from 1 to n.\n# For example, if n is 5, then the function should return 1 + 2 + 3 + 4 + 5.\nsum_numbers <- function(n) {", "langauge": "R"}

3.3 项目地址: aistudio.baidu.com/aistudio/pr…