一、基于文心一言千帆【自动代码生成】
- 你是不是有很多大模型想法,但是由于技术原因无法实现?
- 你是不是有一些通过web页面实现的prompt,但是一直想要chatgpt模式的api构建自己应用,但苦于无接口可调用?
- 你想要集成文心一言到你的项目里,苦于没有代码参考?
- 你想要多伦对话跟文心一言一样的网页版?
- 你想要你的大模型智能?
大家期待文心一言API开放好几天了,那么项目来了,本项目是基于千帆API构建自己的代码生成器,非常方便。
1.效果图
1.1第一版
1.2第二版
2.前情提要
- 需要了解一点gradio知识 www.gradio.app/
- 需要了解一点python知识
二、开通千帆 & 学习帮助文档
1.申请 cloud.baidu.com/product/wen...
现在通过速度很快,基本上2小时就通过。
2.申请大模型权限
3.申请鉴权
url: cloud.baidu.com/doc/WENXINW...
python
# 填充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...
python
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替换成你自己的
python
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
python
# 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示例文件
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# 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"}