Compare commits

...

10 Commits

Author SHA1 Message Date
2260306c87 update 2025-11-02 04:14:55 +08:00
47e3cbe0de update 2025-11-02 03:28:10 +08:00
27ca869b55 Create saying_messages.py 2025-11-01 23:43:00 +08:00
817cf9917b Create caring_messages.py 2025-10-31 20:04:49 +08:00
b93919f08c update 2025-10-13 19:39:24 +08:00
63cda21571 update 2025-10-11 14:05:37 +08:00
78f3828baf update 2025-10-10 20:12:02 +08:00
9cda0f9433 Update openblas_test_wtih_eigen.cpp 2025-09-30 00:18:51 +08:00
7f056c9cae Update cpp_with_eigen_package.cpp 2025-09-29 20:15:09 +08:00
f8577aa56d Create cpp_running_time.cpp 2025-09-29 17:30:51 +08:00
15 changed files with 551 additions and 2 deletions

View File

@@ -1,5 +1,5 @@
#include <iostream>
#include "Eigen/Dense" // #include <Eigen/Dense>
#include <Eigen/Dense>
int main() {
// 定义矩阵

View File

@@ -1,6 +1,6 @@
#define EIGEN_USE_BLAS
#include <iostream>
#include "Eigen/Dense" // #include <Eigen/Dense>
#include <Eigen/Dense>
int main() {
Eigen::MatrixXd A(4, 4);

View File

@@ -0,0 +1,15 @@
#include <iostream>
#include <chrono>
int main() {
double x = 0.0;
auto start = std::chrono::high_resolution_clock::now(); // 记录开始时间
for (long long i = 0; i < 1e10; ++i) {
x += 1e-10; // 模拟一些计算
}
auto end = std::chrono::high_resolution_clock::now(); // 记录结束时间
auto duration = std::chrono::duration_cast<std::chrono::seconds>(end - start); // 计算时间差
std::cout << "Running time: " << duration.count() << " s" << std::endl;
std::cout << "Result x = " << x << std::endl;
return 0;
}

View File

@@ -0,0 +1,3 @@
[build-system]
requires = ["setuptools", "wheel", "pybind11"]
build-backend = "setuptools.build_meta"

View File

@@ -0,0 +1,20 @@
from setuptools import setup, Extension
import pybind11
ext_modules = [
Extension(
"guan_cpp.guan_cpp_module", # 包名.模块名
["src/cpp/main.cpp"], # C++ 源文件列表
include_dirs=[pybind11.get_include()], # pybind11头文件
language="c++", # 指定语言为 C++
extra_link_args=["-static-libstdc++"], # 可选静态链接
),
]
setup(
name="guan_cpp", # 项目的名称(用于 pip install
version="0.0.1", # 版本号
package_dir={"": "src"}, # ​​指定 Python 包的根目录​​
packages=["guan_cpp"], # 包的名称(用于 import
ext_modules=ext_modules, # 指定 C++ 扩展模块
)

View File

@@ -0,0 +1,10 @@
#include <pybind11/pybind11.h>
int add(int a, int b) {
return a + b;
}
PYBIND11_MODULE(guan_cpp_module, m) {
m.doc() = "My C++ extension for Python";
m.def("add", &add, "A function that adds two numbers");
}

View File

@@ -0,0 +1 @@
from .guan_cpp_module import *

View File

@@ -0,0 +1,36 @@
#define EIGEN_USE_BLAS // 注释或取消注释来测试
// #define EIGEN_USE_MKL_ALL // 如果使用 MKL优先用 EIGEN_USE_MKL_ALL
#include <iostream>
#include <chrono>
#include <vector>
#include <iomanip>
#include <Eigen/Dense>
int main() {
std::vector<int> sizes = {100, 200, 300, 500, 1000, 2000, 3000, 5000}; // 要测试的不同矩阵大小
const int trials = 3; // 每个尺寸的测试次数
for (int size : sizes) {
std::cout << "Testing size: " << size << "x" << size << std::endl;
Eigen::MatrixXd A = Eigen::MatrixXd::Random(size, size);
A = A.transpose() * A + Eigen::MatrixXd::Identity(size, size); // 确保矩阵可逆
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < trials; ++i) {
Eigen::MatrixXd A_inv = A.inverse();
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Average time per inversion: "
<< std::fixed << std::setprecision(3)
<< (static_cast<double>(duration.count()) / 1000 / trials)
<< " s" << std::endl;
std::cout << "----------------------------------" << std::endl;
}
return 0;
}

View File

@@ -0,0 +1,22 @@
import numpy as np
import time
sizes = [100, 200, 300, 500, 1000, 2000, 3000, 5000]
trials = 3
for size in sizes:
print(f"Testing size: {size}x{size}")
A = np.random.rand(size, size)
A = A.T @ A + np.eye(size)
start = time.time()
for _ in range(trials):
A_inv = np.linalg.inv(A)
end = time.time()
duration = end - start
print(f"Average time per inversion: {duration/trials:.3f} s")
print("----------------------------------")

View File

@@ -0,0 +1,133 @@
"""
This code is supported by the website: https://www.guanjihuan.com
The newest version of this code is on the web page: https://www.guanjihuan.com/archives/47900
"""
import tkinter as tk
import random
import threading
import time
class WarmTipApp:
def __init__(self):
self.total_windows = 150
self.created_count = 0
self.windows = []
self.root = tk.Tk()
self.root.withdraw()
self.lock = threading.Lock()
def create_window(self, is_final=False):
def _create():
window = tk.Toplevel(self.root)
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
if is_final:
window_width, window_height = 300, 100
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
bg = 'lightpink'
frame = tk.Frame(window, bg=bg)
frame.pack(fill='both', expand=True)
tk.Label(frame, text='我想你了', bg=bg, font=('微软雅黑', 20, 'bold'),
fg='red').place(relx=0.5, rely=0.5, anchor='center')
window.protocol("WM_DELETE_WINDOW", lambda: self.quit_app(window))
window.title('特别提示')
else:
window_width, window_height = 300, 100
x = random.randint(0, max(0, screen_width - window_width))
y = random.randint(0, max(0, screen_height - window_height))
tips = [
# 健康相关
'多喝水哦,补充水分很重要',
'记得按时吃饭,别饿肚子啦',
'久坐了要起来活动活动哦',
'晚上别熬夜,早点休息呀',
'今天也要记得吃水果呀',
'天气变凉了,注意添衣服',
'保持良好作息,身体才会棒',
'累了就歇一歇,别硬撑呀',
# 情绪与心态
'保持微笑呀,你笑起来很好看',
'每天都要元气满满哦',
'保持好心情,好运会降临',
'不管怎样,好好爱自己最重要',
'别给自己太大压力,慢慢来',
'遇到不开心的事,记得跟我说',
'今天过得开心吗?要多笑笑呀',
'烦恼都会过去的,别太在意',
# 祝福与期待
'愿你每天都有小确幸',
'梦想一定会成真的',
'期待下一次见面呀',
'祝你事事顺顺利利',
'愿你被世界温柔以待',
'今天也要加油呀,你最棒',
'无论在哪,都有人惦记着你',
'愿所有美好都如期而至',
# 生活细节
'出门记得带钥匙和手机呀',
'雨天记得带伞,别淋湿了',
'开车要注意安全,慢慢来',
'记得给家里打个电话呀',
'有空多出去走走,晒晒太阳',
'今天也要认真生活呀',
'记得整理房间,心情会变好'
]
bg_colors = ['lightpink', 'skyblue', 'lightgreen', 'lavender', 'lightyellow', 'plum', 'coral', 'bisque', 'aquamarine', 'mistyrose']
tip = random.choice(tips)
bg = random.choice(bg_colors)
frame = tk.Frame(window, bg=bg)
frame.pack(fill='both', expand=True)
tk.Label(frame, text=tip, bg=bg, font=('微软雅黑', 16),
fg='black').place(relx=0.5, rely=0.5, anchor='center')
window.title('温馨提示')
self.windows.append(window)
window.geometry(f'{window_width}x{window_height}+{x}+{y}')
window.attributes('-topmost', True)
if not is_final:
with self.lock:
self.created_count += 1
if self.created_count == self.total_windows:
threading.Thread(target=self.close_all_windows, daemon=True).start()
self.root.after(0, _create)
def close_all_windows(self):
time.sleep(0.5)
for window in self.windows[:]:
self.root.after(0, window.destroy)
time.sleep(0.01)
self.windows.clear()
self.root.after(0, lambda: self.create_window(is_final=True))
def quit_app(self, window):
window.destroy()
self.root.quit()
def start(self):
def _create_all():
for _ in range(self.total_windows):
self.create_window()
time.sleep(0.1)
threading.Thread(target=_create_all, daemon=True).start()
self.root.mainloop()
if __name__ == "__main__":
app = WarmTipApp()
app.start()

View File

@@ -0,0 +1,155 @@
"""
This code is supported by the website: https://www.guanjihuan.com
The newest version of this code is on the web page: https://www.guanjihuan.com/archives/47900
"""
import tkinter as tk
import random
import threading
import time
class WarmTipApp:
def __init__(self):
self.total_windows = 150
self.created_count = 0
self.windows = []
self.root = tk.Tk()
self.root.withdraw()
self.lock = threading.Lock()
def create_window(self, is_final=False):
def _create():
window = tk.Toplevel(self.root)
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
if is_final:
window_width, window_height = 350, 150
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
bg = 'lightpink'
frame = tk.Frame(window, bg=bg)
frame.pack(fill='both', expand=True)
tk.Label(frame, text='人民万岁!', bg=bg, font=('微软雅黑', 28, 'bold'),
fg='red').place(relx=0.5, rely=0.5, anchor='center')
window.protocol("WM_DELETE_WINDOW", lambda: self.quit_app(window))
window.title('人民万岁')
else:
window_width, window_height = 350, 150
x = random.randint(0, max(0, screen_width - window_width))
y = random.randint(0, max(0, screen_height - window_height))
# 毛主席语录
quotes = [
# 革命与斗争
"枪杆子里面出政权。",
"星星之火,可以燎原。",
"下定决心,不怕牺牲,排除万难,去争取胜利。",
"人不犯我,我不犯人;人若犯我,我必犯人。",
"一切反动派都是纸老虎。",
"宜将剩勇追穷寇,不可沽名学霸王。",
# 政治与领导
"我们的原则是党指挥枪,而决不容许枪指挥党。",
"谁是我们的敌人?谁是我们的朋友?这个问题是革命的首要问题。",
"统一战线,武装斗争,党的建设,是中国共产党在中国革命中战胜敌人的三个法宝。",
"政策和策略是党的生命,各级领导同志务必充分注意,万万不可粗心大意。",
"我们应该谦虚、谨慎、戒骄、戒躁,全心全意地为中国人民服务。",
# 军事与战略
"敌进我退,敌驻我扰,敌疲我打,敌退我追。",
"打得赢就打,打不赢就走。",
"战争的伟力之最深厚的根源,存在于民众之中。",
"集中优势兵力,各个歼灭敌人。",
"伤其十指,不如断其一指。",
"兵民是胜利之本。",
"战略上藐视敌人,战术上重视敌人。",
# 思想与方法
"没有调查,就没有发言权。",
"实践、认识、再实践、再认识,这种形式,循环往复以至无穷,而实践和认识之每一循环的内容,都比较地进到了高一级的程度。",
"矛盾存在于一切事物的发展过程中;每一事物的发展过程中存在着自始至终的矛盾运动。",
"马克思主义的哲学认为十分重要的问题,不在于懂得了客观世界的规律性,因而能够解释世界,而在于拿了这种对于客观规律性的认识去能动地改造世界。",
"世上无难事,只要肯登攀。",
"人的正确思想,只能从社会实践中来,只能从社会的生产斗争、阶级斗争和科学实验这三项实践中来。",
"一切结论产生于调查情况的末尾,而不是在它的先头。",
"知识的问题是一个科学问题,来不得半点的虚伪和骄傲,决定地需要的倒是其反面——诚实和谦逊的态度。",
# 群众与服务
"为人民服务。",
"军民团结如一人,试看天下谁能敌。",
"我们共产党人好比种子,人民好比土地。我们到了一个地方,就要同那里的人民结合起来,在人民中间生根、开花。",
"人民,只有人民,才是创造世界历史的动力。",
# 文化与教育
"古为今用,洋为中用。",
"百花齐放,百家争鸣。",
"好好学习,天天向上。",
# 经济与建设
"自己动手,丰衣足食。",
"只有社会主义能够救中国。",
# 青年与未来
"世界是你们的,也是我们的,但是归根结底是你们的。你们青年人朝气蓬勃,正在兴旺时期,好像早晨八九点钟的太阳。希望寄托在你们身上。",
"自信人生二百年,会当水击三千里。",
# 哲理与励志
"不管风吹浪打,胜似闲庭信步。",
"要想不经过艰难曲折,不付出极大努力,总是一帆风顺,容易得到成功,这种想法,只是幻想。",
"读书是学习,使用也是学习,而且是更重要的学习。",
"我们的同志在困难的时候,要看到成绩,要看到光明,要提高我们的勇气。",
"错误和挫折教训了我们,使我们比较地聪明起来了,我们的事情就会办得好一些。"
]
bg_colors = ['lightyellow', 'lightblue', 'lightgreen', 'lavender', 'mistyrose', 'bisque', 'aquamarine']
tip = random.choice(quotes)
bg = random.choice(bg_colors)
frame = tk.Frame(window, bg=bg)
frame.pack(fill='both', expand=True)
tk.Label(frame, text=tip, bg=bg, font=('微软雅黑', 14),
fg='black', wraplength=320, justify='center').place(relx=0.5, rely=0.5, anchor='center')
window.title('毛主席语录')
self.windows.append(window)
window.geometry(f'{window_width}x{window_height}+{x}+{y}')
window.attributes('-topmost', True)
if not is_final:
with self.lock:
self.created_count += 1
if self.created_count == self.total_windows:
threading.Thread(target=self.close_all_windows, daemon=True).start()
self.root.after(0, _create)
def close_all_windows(self):
time.sleep(0.5)
for window in self.windows[:]:
self.root.after(0, window.destroy)
time.sleep(0.01)
self.windows.clear()
self.root.after(0, lambda: self.create_window(is_final=True))
def quit_app(self, window):
window.destroy()
self.root.quit()
def start(self):
def _create_all():
for _ in range(self.total_windows):
self.create_window()
time.sleep(0.1)
threading.Thread(target=_create_all, daemon=True).start()
self.root.mainloop()
if __name__ == "__main__":
app = WarmTipApp()
app.start()

View File

@@ -0,0 +1,2 @@
OPENAI_API_KEY=xxx
DASHSCOPE_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1

View File

@@ -0,0 +1,34 @@
import langchain_openai
from langchain_core.prompts import ChatPromptTemplate
import dotenv
import os
# 加载环境变量包含API密钥
dotenv.load_dotenv()
# 创建聊天模型
llm = langchain_openai.ChatOpenAI(
api_key=os.getenv("OPENAI_API_KEY"), # 从环境变量获取 API 密钥
base_url=os.getenv("DASHSCOPE_BASE_URL"), # 指定 API 端点
model="qwen-plus", # 使用通义千问 Plus 模型
temperature=0.7, # 控制回复的随机性0-1越高越有创意
streaming=True, # 启用流式模式
)
# 创建简单的提示词模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个友好的聊天助手。"), # 系统角色设定
("human", "{question}") # 用户输入占位符
])
# 创建处理链
chain = prompt | llm # 使用管道操作符连接组件
# 使用 stream() 实现流式输出
for chunk in chain.stream({"question": "你好"}):
print(chunk.content, end="", flush=True)
print() # 换行
# # 非流式输出
# response = chain.invoke({"question": "你好"})
# print(response.content)

View File

@@ -0,0 +1,61 @@
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory
# 加载 .env 中的 API 密钥等配置
load_dotenv()
# 初始化大模型
llm = ChatOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
model="qwen-plus",
temperature=0.7
)
# 定义带历史记录的提示模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个乐于助人的助手。"),
MessagesPlaceholder("history"), # 历史消息占位符
("human", "{input}") # 当前用户输入
])
# 创建基础链
chain = prompt | llm
# 内存存储:用字典模拟会话历史(仅用于演示)
store = {}
def get_session_history(session_id: str):
if session_id not in store:
store[session_id] = ChatMessageHistory()
return store[session_id]
# 包装成带记忆的链
chatbot = RunnableWithMessageHistory(
chain,
get_session_history,
input_messages_key="input",
history_messages_key="history",
)
def chat_with_agent(input_message, session_id):
print(f"用户: {input_message}")
print("助手: ", end="", flush=True)
for chunk in chatbot.stream(
{"input": input_message},
config={"configurable": {"session_id": session_id}} # 多轮对话(使用同一个 session_id
):
print(chunk.content, end="", flush=True)
print("\n\n---\n")
chat_with_agent(input_message='一句话解释下人工智能。', session_id="user_001")
chat_with_agent(input_message='我们都聊了什么?', session_id="user_001")
chat_with_agent(input_message='我们都聊了什么?', session_id="user_002")
chat_with_agent(input_message='我们都聊了什么?', session_id="user_001")

View File

@@ -0,0 +1,57 @@
import os
import dotenv
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
from langchain.agents import create_openai_tools_agent, AgentExecutor
# 加载环境变量
dotenv.load_dotenv()
# 定义工具Tool
@tool
def get_current_time() -> str:
"""获取当前日期和时间"""
from datetime import datetime
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@tool
def add_numbers(a: float, b: float) -> float:
"""将两个数字相加"""
return a + b
# 注意:你可以添加更多工具,比如天气查询、网络搜索等
tools = [get_current_time, add_numbers]
# 创建 LLM必须支持 function calling
llm = ChatOpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL"),
model="qwen-plus",
temperature=0.7,
streaming=True,
)
# 构建提示模板LangChain 会自动注入工具信息)
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个智能助手,可以使用工具来回答问题。"),
("human", "{input_message}"),
("placeholder", "{agent_scratchpad}"), # 必须包含这个占位符
])
# 创建 OpenAI 工具型智能体(兼容 function calling
agent = create_openai_tools_agent(llm, tools, prompt)
# 创建执行器
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True, # 打印中间步骤(可选)
handle_parsing_errors=True,
)
# 非流式调用AgentExecutor 目前对流式支持有限,尤其在工具调用场景)
response = agent_executor.invoke({"input_message": "现在几点了?然后把 123 和 456 加起来。"})
print('\n---\n')
print(response["output"])