腾讯云AI代码助手---用AI构造AI,打造属于个人的Copilot
随着AI的快速发展,使用AI构造AI也登录历史舞台。本日带各人使用腾讯云 AI 代码助手来创建基于AI大模子的AI呆板人对话网页,使用的开辟工具为Python的Flask作为后端,HTML5+js作为前端。文章末尾附完整源码。源码没有一个是本身手敲出来的 都是AI编写。看完你也会。一 环境和工具使用
PyCharm:适用于数据科学和 Web 开辟的 Python IDEhttps://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://www.jetbrains.com/zh-cn/pycharm/Miniconda — Conda documentationhttps://csdnimg.cn/release/blog_editor_html/release2.3.7/ckeditor/plugins/CsdnLink/icons/icon-default.png?t=O83Ahttps://docs.conda.io/en/latest/miniconda.html首先就是通过上面的链接分别下载pycharm社区版(免费的)和miniconda你本身电脑对应的版本
https://i-blog.csdnimg.cn/direct/6f9f3faeefd8458ca7c234139e5ace15.png
https://i-blog.csdnimg.cn/direct/74a72add27aa44a3b4eabaaf2ad2bf7b.png
下载过程中的选项除了安装路径不选择c盘换成其他盘,其他的都选择默认的就行。接下来找到这个打开
二 开辟前准备
https://i-blog.csdnimg.cn/direct/d405a1e9b03a4c73815ec153e1106580.png
创建conda虚拟环境 使用以下下令创建虚拟环境
https://i-blog.csdnimg.cn/direct/fea80e2c24c9481884b90b56938976d5.png
conda create -n your_env_name python=3.10
your_env_name:指的是你的虚拟环境的名字
python=3.10:指的是虚拟环境内置的python解释器版本
https://i-blog.csdnimg.cn/direct/00f4549598aa4e2891a68c712373e9a5.png
然后pycharm创建新项目 此处演示使用找到conda创建的解释器的位置选择就行
https://i-blog.csdnimg.cn/direct/65d45e8b8a084d46ae8096aeeeb28de4.png
右下角能看到当前解释器的名字和版本
https://i-blog.csdnimg.cn/direct/a169a15b5e554b21b627dda3c329a3ab.png
解释器设置完成后 点击文件下的设置找到里面的插件 在Marketplace界面中搜索腾讯 点击安装(我这里是安装好了的)
https://i-blog.csdnimg.cn/direct/920a66b5bb874a9391b541d88cd5478a.png
https://i-blog.csdnimg.cn/direct/b996e487e6d142ba8e6de362ee00d88b.png
https://i-blog.csdnimg.cn/direct/17781d5af3654616894aa9a457b0b07c.png
点击 然后扫码登录(微信扫码就行) 接下来与ai进行对话直接询问AI 我要使用什么去做什么,得到什么结果。例如我所询问的
https://i-blog.csdnimg.cn/direct/d919f1b69568461b8fede8029890e3de.png
那么我们按照它给出的第一步去细细盘问(这里之所以选择这个千帆大模子,这个里面有免费额度的)
https://i-blog.csdnimg.cn/direct/ae4a611e4ca14c5b909671d8645b2688.png
接下来根据引导注册,创建应用选择服务(选择我选择的两种模子,这两种模子是免费额度500千tokens的学习测试使用完全足够。)
https://i-blog.csdnimg.cn/direct/a248827758ab4845ad0593e8be1eb30d.png
https://i-blog.csdnimg.cn/direct/d4711bc04f584207b303c62c0a716070.png
接下来点击应用接入 就可以得到你的API Key 和Secret Key
https://i-blog.csdnimg.cn/direct/8c91e19d8ad9469fa562fb971314a184.png
https://i-blog.csdnimg.cn/direct/d4c03e154b2b442089f4f7e8b7b01342.png
三 操作AI来构造代码
根据得到的id API Key 和Secret Key 让其生成代码 然后插入到main.py文件内
https://i-blog.csdnimg.cn/direct/437305e299f849cca6f22c88b47cbad9.png
注意这里的插入代码是直接插入代码到你当前打开的文件里面去了 所以后端代码要放置在.py文件内 前端代码放置在当前目录下新建文件夹然后创建html后缀的文件
https://i-blog.csdnimg.cn/direct/435ffcba57c249a09980d7d568de8b08.png
https://i-blog.csdnimg.cn/direct/387077c5f9cc40ddae9683528ef093f0.png
这里进行新建html文件大概py文件
https://i-blog.csdnimg.cn/direct/41c0dc5e5ccf4841a07a97f2b36dbb46.png
这是插入后的结果 可以明显的看看到爆红了 这意味的没有安装库,根据ai之前的提示我们使用pip指令安装库
https://i-blog.csdnimg.cn/direct/febdad0eef484687bfd29f4d30cdb060.png
https://i-blog.csdnimg.cn/direct/fd245cd39ab648bbbc018cc86f369175.png
点击终端的图标复制给的指令 复制粘贴 敲回车安装库
https://i-blog.csdnimg.cn/direct/218fcbc7b41e4a15a4fae4c5257a30a7.png
https://i-blog.csdnimg.cn/direct/235f78aec0724cc4972ff02f2f7c7cf7.png
安装事子女码就不会爆红了
https://i-blog.csdnimg.cn/direct/32c85e72bca24763a24bb637138774d4.png
接下来运行代码 先运行main.py 此时出现报错将报错信息复制给ai 根据ai1给出的下令到终端去运行下载这个库。(这里会多次重复这个情况,ai也不是万能的,给他机会一次一次修改代码)这个过程就不一一展示了。
https://i-blog.csdnimg.cn/direct/5c75fedbd1ae4cf88e079e1f39a62813.png
https://i-blog.csdnimg.cn/direct/d6d7399a9cdd47ad97c3d6ab5642e798.png
https://i-blog.csdnimg.cn/direct/c8e6ffc6cb504b2a919df83577c3d7b1.png
知道运行不报错了 出现以下 这表明代码乐成了我们看看下结果
https://i-blog.csdnimg.cn/direct/93a2b2c2e5ac45048448b4792ddd99f8.png
https://i-blog.csdnimg.cn/direct/09f3dfeb46784c2c9a41ad5757b03627.png
四 反复鞭策AI让其给你生成你想要的结果
这个结果没题目,就是界面看起来不理想很不美观而且没有各种功能 我们将前端的代码再次发给ai让其对界面代码进行润色。 这里询问尽量全点,将你的逻辑梳理清晰,然后转换成笔墨来询问ai。 询问内容为(现在的前端代码展示的界面不理想 很不美观 请你进行优化 增长历史记载的功能 一旦用户发送题目后会等待结果,这个时间应该对话框内什么都没有没有任何的提示 应该显示ai正在思考中请等待)
https://i-blog.csdnimg.cn/direct/8b92e02e432a40008a527ee0e40493e7.png
接下来根据其给你的修改方案复制到代码相应的位置内 (小白的话,建议直接问ai这段代码应该插入到我的代码的哪里才对。大概直接一句给我修改后的完整的html的代码)得到最后的结果
https://i-blog.csdnimg.cn/direct/0a5ef9ef1f624f2282fc1352b0e61440.png
五 源码展示
后续可以不断的追问ai让其对界面不断的美满,好比加上聊天界面的两边头像大概加上两边每段对话的时间。以下是ai编写出来的源码
main.py
from flask import Flask, request, render_template, session, redirect, url_for
import requests
import json
import uuid
API_KEY = "输入你的钥匙"
SECRET_KEY = "输入你的密匙"
app = Flask(__name__)
app.secret_key = "your_secret_key_here"
def get_access_token():
url = "https://aip.baidubce.com/oauth/2.0/token"
params = {
"grant_type": "client_credentials",
"client_id": API_KEY,
"client_secret": SECRET_KEY
}
response = requests.post(url, params=params)
data = response.json()
return data.get("access_token")
def get_ai_response(user_messages):
access_token = get_access_token()
url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token={access_token}"
payload = {
"messages": user_messages,
"temperature": 0.95,
"top_p": 0.8,
"penalty_score": 1,
"enable_system_memory": False,
"disable_search": False,
"enable_citation": False
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
result = response.json()
ai_response = result.get("result", "抱歉,我未能理解您的请求。")
return ai_response
@app.route("/", methods=["GET"])
def home():
# 显示会话列表(如果没有则为空)
if "conversations" not in session:
session["conversations"] = {}
conversations = session["conversations"]
return render_template("index.html", chat_history=None, conversations=conversations, current_chat_id=None)
@app.route("/new_chat", methods=["GET"])
def new_chat():
# 创建新的会话ID
chat_id = str(uuid.uuid4())
if "conversations" not in session:
session["conversations"] = {}
session["conversations"] = []# 空会话
session.modified = True
return redirect(url_for("chat", chat_id=chat_id))
@app.route("/chat/<chat_id>", methods=["GET", "POST"])
def chat(chat_id):
if "conversations" not in session:
session["conversations"] = {}
if chat_id not in session["conversations"]:
# 如果传入的chat_id不存在,重定向回首页或新建
return redirect(url_for("home"))
chat_history = session["conversations"]
if request.method == "POST":
user_input = request.form.get("user_input", "").strip()
if user_input:
# 用户消息
chat_history.append({"role": "user", "content": user_input})
ai_response = get_ai_response([{"role": "user", "content": user_input}])
chat_history.append({"role": "assistant", "content": ai_response})
session["conversations"] = chat_history
session.modified = True
conversations = session["conversations"]
return render_template("index.html", chat_history=chat_history, conversations=conversations, current_chat_id=chat_id)
def get_ai_response(user_messages):
access_token = get_access_token()
url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token={access_token}"
payload = {
"messages": user_messages,
"temperature": 0.95,
"top_p": 0.8,
"penalty_score": 1,
"enable_system_memory": False,
"disable_search": False,
"enable_citation": False
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
result = response.json()
ai_response = result.get("result", "抱歉,我未能理解您的请求。")
return ai_response
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=True)
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>AI 对话页面</title>
<style>
body {
margin: 0;
padding: 0;
font-family: "Microsoft YaHei", sans-serif;
background: #f0f2f5;
height: 100vh;
display: flex;
color: #333;
}
.sidebar {
width: 260px;
background: #ffffff;
border-right: 1px solid #ddd;
display: flex;
flex-direction: column;
padding: 20px;
box-sizing: border-box;
}
.sidebar h2 {
font-size: 18px;
margin-bottom: 20px;
text-align: center;
color: #333;
}
.new-chat-btn {
display: block;
width: 100%;
text-align: center;
background: #409eff;
color: #fff;
border: none;
padding: 10px 0;
border-radius: 5px;
cursor: pointer;
margin-bottom: 20px;
font-size: 14px;
text-decoration: none;
line-height: 20px;
}
.new-chat-btn:hover {
background: #66b1ff;
}
.chat-list {
flex: 1;
overflow-y: auto;
}
.chat-item {
padding: 10px 0;
border-bottom: 1px solid #eee;
cursor: pointer;
font-size: 14px;
text-decoration: none;
color: #333;
display: block;
}
.chat-item:hover {
background: #f9f9f9;
}
.main {
flex: 1;
display: flex;
flex-direction: column;
background: #f0f2f5;
}
.header {
background: #409eff;
color: #fff;
padding: 15px;
text-align: center;
font-size: 18px;
}
.chat-window {
flex: 1;
padding: 20px;
box-sizing: border-box;
overflow-y: auto;
position: relative;
}
.message {
display: flex;
margin-bottom: 20px;
width: 100%;
}
.message.assistant .bubble {
margin-right: auto;
background: #ffffff;
border: 1px solid #eee;
color: #333;
}
.message.user .bubble {
margin-left: auto;
background: #409eff;
color: #fff;
}
.bubble {
max-width: 70%;
padding: 12px 15px;
border-radius: 8px;
line-height: 1.5;
word-wrap: break-word;
white-space: pre-wrap;
font-size: 14px;
}
.input-container {
border-top: 1px solid #ddd;
background: #ffffff;
padding: 10px;
display: flex;
align-items: center;
}
.input-box {
flex: 1;
display: flex;
align-items: center;
background: #f9f9f9;
border: 1px solid #ddd;
border-radius: 5px;
padding: 5px;
margin-right: 10px;
}
.input-box textarea {
flex: 1;
border: none;
background: transparent;
outline: none;
resize: none;
font-size: 14px;
padding: 5px;
line-height: 1.5;
}
.send-btn {
background: #409eff;
color: #fff;
border: none;
padding: 10px 20px;
font-size: 14px;
border-radius: 5px;
cursor: pointer;
}
.send-btn:hover {
background: #66b1ff;
}
.footer {
text-align: center;
color: #aaa;
font-size: 12px;
margin: 10px 0;
}
</style>
</head>
<body>
<div class="sidebar">
<h2>对话列表</h2>
<a href="{{ url_for('new_chat') }}" class="new-chat-btn">新建对话</a>
<div class="chat-list">
{% for cid, conv in conversations.items() %}
<a class="chat-item" href="{{ url_for('chat', chat_id=cid) }}">
对话: {{ cid|truncate(8,true,'...') }}
</a>
{% endfor %}
</div>
</div>
<div class="main">
<div class="header">与 AI 对话</div>
<div class="chat-window" id="chat-window">
{% if chat_history %}
{% for msg in chat_history %}
<div class="message {{ msg.role }}">
<div class="bubble">{{ msg.content }}</div>
</div>
{% endfor %}
{% endif %}
</div>
{% if current_chat_id %}
<form id="chat-form" method="post" action="{{ url_for('chat', chat_id=current_chat_id) }}" class="input-container">
<div class="input-box">
<textarea name="user_input" id="user_input" rows="1" placeholder="在此输入您的问题..."></textarea>
</div>
<button type="submit" class="send-btn">发送</button>
</form>
{% endif %}
<div class="footer">Powered by Wenxin & Flask</div>
</div>
<script>
const chatForm = document.getElementById('chat-form');
const chatWindow = document.getElementById('chat-window');
const userInput = document.getElementById('user_input');
if (chatForm) {
chatForm.addEventListener('submit', function(e) {
e.preventDefault(); // 阻止表单默认提交
const message = userInput.value.trim();
if (!message) return;
// 1. 先显示用户输入
appendMessage('user', message);
// 2. 显示AI正在思考中...
const thinkingMsg = appendMessage('assistant', 'AI正在思考中...');
// 3. 发送AJAX请求到后端
fetch(chatForm.action, {
method: 'POST',
body: new FormData(chatForm)
})
.then(response => response.text())
.then(html => {
// 用后端重新渲染的整页HTML进行局部更新
// 需要从返回的HTML中提取最新对话记录
// 简单的做法是后端返回JSON而非整页HTML
// 以下方法为简单演示,建议使用JSON接口!
// DEMO方式:使用JSON接口替代,下面的代码仅供参考:
// 实际中你应该在后端提供一个JSON返回的API,例如 /chat/<chat_id>/api
// 然后在这里解析JSON更新界面。
// 简单处理:重新从服务器获取新页面HTML片段(不建议生产用)
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const newChatWindow = doc.querySelector('#chat-window');
if (newChatWindow) {
chatWindow.innerHTML = newChatWindow.innerHTML;
}
})
.catch(err => {
console.error(err);
// 如果出错,则用一条消息表示出错信息
thinkingMsg.querySelector('.bubble').textContent = '出错了,请重试。';
})
.finally(() => {
userInput.value = '';
chatWindow.scrollTop = chatWindow.scrollHeight;
});
});
}
function appendMessage(role, content) {
const msgDiv = document.createElement('div');
msgDiv.className = 'message ' + role;
const bubble = document.createElement('div');
bubble.className = 'bubble';
bubble.textContent = content;
msgDiv.appendChild(bubble);
chatWindow.appendChild(msgDiv);
chatWindow.scrollTop = chatWindow.scrollHeight;
return msgDiv;
}
</script>
</body>
</html>
可以看到 ai修改生成的代码都非常的尺度,也很美观。节省了大量的开辟时间,有这时间摸鱼能不香嘛。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页:
[1]