跳到主要内容 Python Tkinter 集成 DocsGPT 开发 AI 代码助手 | 极客日志
Python AI 算法
Python Tkinter 集成 DocsGPT 开发 AI 代码助手 开发背景 档记录基于 Python 和 Tkinter 构建集成 DocsGPT 与 OpenAI API 的本地 AI 代码助手开发过程。主要目标是通过本地 API 调用实现代码编辑、运行及智能问答功能。 功能需求 **界面布局**: 左侧:Python 代码编辑区(支持多行输入、语法高亮、Run 按钮)。 右侧:GPT 调用区(提问输入、答案显示、历史记录)。 **核心功能**: 支持本地…
魔法巫师 发布于 2026/4/6 更新于 2026/4/13 10K 浏览开发背景
本文档记录基于 Python 和 Tkinter 构建集成 DocsGPT 与 OpenAI API 的本地 AI 代码助手开发过程。主要目标是通过本地 API 调用实现代码编辑、运行及智能问答功能。
功能需求
界面布局 :
左侧:Python 代码编辑区(支持多行输入、语法高亮、Run 按钮)。
右侧:GPT 调用区(提问输入、答案显示、历史记录)。
核心功能 :
支持本地 DocsGPT API 及 OpenAI 官方 API。
代码上下文传递。
历史记录存储(SQLite)。
主题切换(浅色/深色)。
开发迭代
迭代 1:基础界面与 OpenAI 集成
实现 Tkinter 左右分栏布局。
集成 OpenAI API 客户端。
基础问答功能。
迭代 2:本地 DocsGPT 支持
更新 gpt_client.py 支持 DocsGPT 特定参数(项目 ID、会话 ID、流式响应)。
增加 API 类型选择(docsgpt / openai)。
优化错误处理与连接测试。
代码实现
项目结构
gpt_code_ide/
├── main.py
├── database.py
├── gpt_client.py
└── requirements.txt
依赖配置 (requirements.txt)
tkinter
sqlite3
requests
pygments
idlelib
数据库操作 (database.py)
"""数据库操作模块
创建和管理 SQLite 数据库,存储提问历史
"""
import sqlite3
import json
from datetime import datetime
from typing import List , Dict , Optional
class PyAIDatabase :
def __init__ (self, db_name: str = "pyai.db" ):
.db_name = db_name
.init_database()
( ):
sqlite3.connect( .db_name) conn:
cursor = conn.cursor()
cursor.execute( )
cursor.execute( )
cursor.execute( )
cursor.execute( )
conn.commit()
( ) -> :
sqlite3.connect( .db_name) conn:
cursor = conn.cursor()
cursor.execute( , (question, answer, code_context))
conn.commit()
cursor.lastrowid
( ) -> [ ]:
sqlite3.connect( .db_name) conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute( , (limit, offset))
rows = cursor.fetchall()
[ (row) row rows]
( ) -> :
sqlite3.connect( .db_name) conn:
cursor = conn.cursor()
cursor.execute( , (query_id,))
conn.commit()
cursor.rowcount >
( ) -> :
sqlite3.connect( .db_name) conn:
cursor = conn.cursor()
cursor.execute( )
conn.commit()
cursor.rowcount >
( ) -> :
sqlite3.connect( .db_name) conn:
cursor = conn.cursor()
cursor.execute( , (title, code, language))
conn.commit()
cursor.lastrowid
( ) -> [ ]:
sqlite3.connect( .db_name) conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute( )
[ (row) row cursor.fetchall()]
( ) -> [ ]:
sqlite3.connect( .db_name) conn:
cursor = conn.cursor()
cursor.execute( , (key,))
result = cursor.fetchone()
result[ ] result
( ):
sqlite3.connect( .db_name) conn:
cursor = conn.cursor()
cursor.execute( , (key, value))
conn.commit()
( ) -> [ ]:
sqlite3.connect( .db_name) conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute( , ( , ))
[ (row) row cursor.fetchall()]
db = PyAIDatabase()
微信扫一扫,关注极客日志 微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
self
self
def
init_database
self
"""初始化数据库表"""
with
self
as
"""
CREATE TABLE IF NOT EXISTS query_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
question TEXT NOT NULL,
answer TEXT NOT NULL,
code_context TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
"""
CREATE TABLE IF NOT EXISTS code_snippets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
code TEXT NOT NULL,
language TEXT DEFAULT 'python',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
"""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
"""
"""
INSERT OR IGNORE INTO settings (key, value) VALUES
('api_key', ''),
('api_url', 'https://api.openai.com/v1/chat/completions'),
('theme', 'light'),
('font_size', '12')
"""
def
save_query
self, question: str , answer: str , code_context: str = ""
int
"""保存查询记录"""
with
self
as
"""
INSERT INTO query_history (question, answer, code_context) VALUES (?, ?, ?)
"""
return
def
get_query_history
self, limit: int = 50 , offset: int = 0
List
Dict
"""获取查询历史"""
with
self
as
"""
SELECT id, question, answer, code_context, created_at, updated_at
FROM query_history
ORDER BY created_at DESC LIMIT ? OFFSET ?
"""
return
dict
for
in
def
delete_query
self, query_id: int
bool
"""删除查询记录"""
with
self
as
"DELETE FROM query_history WHERE id = ?"
return
0
def
clear_history
self
bool
"""清空历史记录"""
with
self
as
"DELETE FROM query_history"
return
0
def
save_code_snippet
self, title: str , code: str , language: str = "python"
int
"""保存代码片段"""
with
self
as
"""
INSERT INTO code_snippets (title, code, language) VALUES (?, ?, ?)
"""
return
def
get_code_snippets
self
List
Dict
"""获取所有代码片段"""
with
self
as
"""
SELECT id, title, code, language, created_at FROM code_snippets
ORDER BY created_at DESC
"""
return
dict
for
in
def
get_setting
self, key: str
Optional
str
"""获取配置"""
with
self
as
"SELECT value FROM settings WHERE key = ?"
return
0
if
else
None
def
update_setting
self, key: str , value: str
"""更新配置"""
with
self
as
"""
INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)
"""
def
search_history
self, keyword: str
List
Dict
"""搜索历史记录"""
with
self
as
"""
SELECT id, question, answer, created_at
FROM query_history
WHERE question LIKE ? OR answer LIKE ?
ORDER BY created_at DESC
"""
f"%{keyword} %"
f"%{keyword} %"
return
dict
for
in
GPT API 客户端 (gpt_client.py) """GPT API 客户端模块
处理与 GPT API 的通信
"""
import requests
import json
from typing import Optional , Dict , Any
import threading
from database import db
class GPTClient :
def __init__ (self, api_key: str = None , api_url: str = None ):
self .api_key = api_key or db.get_setting('api_key' ) or ""
self .api_url = api_url or db.get_setting('api_url' ) or "https://api.openai.com/v1/chat/completions"
self .session = requests.Session()
self .session.headers.update({
"Authorization" : f"Bearer {self.api_key} " ,
"Content-Type" : "application/json"
})
def set_api_key (self, api_key: str ):
"""设置 API 密钥"""
self .api_key = api_key
self .session.headers.update({"Authorization" : f"Bearer {api_key} " })
db.update_setting('api_key' , api_key)
def set_api_url (self, api_url: str ):
"""设置 API URL"""
self .api_url = api_url
db.update_setting('api_url' , api_url)
def ask_question (self, question: str , code_context: str = "" , model: str = "gpt-3.5-turbo" ,
max_tokens: int = 1000 , temperature: float = 0.7 , callback=None ) -> Optional [str ]:
"""
向 GPT 提问
Args:
question: 问题文本
code_context: 相关代码上下文
model: 使用的模型
max_tokens: 最大 token 数
temperature: 温度参数
callback: 回调函数,用于异步更新 UI
Returns:
GPT 的回答
"""
if not self .api_key:
return "错误:请先设置 API 密钥"
messages = []
if code_context:
messages.append({
"role" : "system" ,
"content" : f"以下是相关代码上下文:\n```python\n{code_context} \n```\n请基于此代码上下文回答问题。"
})
messages.append({
"role" : "user" ,
"content" : question
})
data = {
"model" : model,
"messages" : messages,
"max_tokens" : max_tokens,
"temperature" : temperature,
"stream" : False
}
try :
if callback:
thread = threading.Thread(target=self ._async_ask, args=(data, callback))
thread.daemon = True
thread.start()
return "正在处理..."
else :
return self ._sync_ask(data)
except Exception as e:
return f"请求错误:{str (e)} "
def _async_ask (self, data: Dict , callback ):
"""异步调用 GPT"""
try :
response = self .session.post(self .api_url, json=data, timeout=30 )
if response.status_code == 200 :
result = response.json()
answer = result['choices' ][0 ]['message' ]['content' ]
callback(answer)
else :
error_msg = f"API 错误:{response.status_code} \n{response.text} "
callback(error_msg)
except requests.exceptions.Timeout:
callback("错误:请求超时,请检查网络连接" )
except requests.exceptions.ConnectionError:
callback("错误:无法连接到 API 服务器" )
except Exception as e:
callback(f"未知错误:{str (e)} " )
def _sync_ask (self, data: Dict ) -> str :
"""同步调用 GPT"""
try :
response = self .session.post(self .api_url, json=data, timeout=30 )
if response.status_code == 200 :
result = response.json()
return result['choices' ][0 ]['message' ]['content' ]
else :
return f"API 错误:{response.status_code} \n{response.text} "
except requests.exceptions.Timeout:
return "错误:请求超时,请检查网络连接"
except requests.exceptions.ConnectionError:
return "错误:无法连接到 API 服务器"
except Exception as e:
return f"未知错误:{str (e)} "
def get_models (self ) -> list :
"""获取可用的模型列表(需要相应权限)"""
if not self .api_key:
return []
try :
response = self .session.get("https://api.openai.com/v1/models" , timeout=10 )
if response.status_code == 200 :
models = response.json()['data' ]
return [model['id' ] for model in models if 'gpt' in model['id' ].lower()]
return []
except :
return ["gpt-3.5-turbo" , "gpt-4" , "gpt-4-turbo" ]
gpt_client = GPTClient()
使用说明 步骤 操作 安装依赖 pip install requests autopep8运行程序 python main.py配置 API 密钥 在程序右侧的 API 密钥输入框中输入您的 OpenAI API 密钥,点击'保存'按钮 使用流程 1. 在左侧编写 Python 代码 2. 点击'运行代码'按钮执行 3. 在右侧输入问题,点击'获取答案'按钮向 GPT 提问 4. 查看历史记录中的问答历史
功能特点
代码编辑器 :支持语法高亮、文件操作(新建、打开、保存)、查找替换、撤销/重做。
GPT 助手 :集成 OpenAI GPT API,支持代码上下文、历史记录管理、搜索功能。
界面优化 :左右分栏设计、海蓝色主题按钮、深浅色主题切换、响应式布局。
数据库 :SQLite 存储历史记录、持久化设置、快速搜索查询。
该程序提供了一个完整的 Python 开发环境,集成了 GPT 智能助手,非常适合学习和开发使用。