Compare commits

..

9 Commits

Author SHA1 Message Date
rex
d86244b534 bump 2025-12-02 19:35:06 +08:00
rex
6bf1ac8c9d add tool call example 2025-12-02 17:05:37 +08:00
rex
ac2771d2dd vanilla api 2025-12-02 15:32:52 +08:00
rex
9701641f18 vanilla api 2025-12-02 15:21:53 +08:00
rex
44bc902d15 prompt 2025-11-27 19:23:32 +08:00
rex
cf81b21cbb prompt 2025-11-27 19:20:31 +08:00
rex
2a98b05972 doc 2025-11-26 19:21:34 +08:00
rex
2c543f689c doc 2025-11-26 18:01:01 +08:00
rex
f811bd6659 doc 2025-11-26 17:43:55 +08:00
13 changed files with 574 additions and 103 deletions

View File

@@ -1,8 +1,8 @@
{ {
"mcpServers": { "mcpServers": {
// "mujian": { "mujian-js-sdk": {
// "command": "npx", "command": "npx",
// "args": ["-y", "@mujian/mcp-docs-server"] "args": ["-y", "@mujian/mcp-docs-server"]
// } }
} }
} }

View File

@@ -3,24 +3,13 @@ description: 工程全局规则
alwaysApply: true alwaysApply: true
--- ---
你是一个游戏开发Agent需要在本工程中,协助我开发一个 HTML 游戏 # 你是一个游戏开发Agent在本工程中你需要协助我开发一个原生 HTML 游戏
## 本工程介绍 ## 本工程介绍
- 这是一个模版工程,开发者会基于这个工程进行拓展开发 - 这是一个模版工程,开发者会基于这个工程进行拓展开发
- 本工程采用 Vite + React 框架是一个React SPA架构的游戏/应用
- 本工程强烈建议使用如下前端NPM包
- react-router: 用于管理页面和路由
- zustand: 用于React状态管理
- TailwindCSS: 用于编写样式和管理主题
- axios用于发起http请求。包括上传和SSE场景。
- dayjs: 用于处理日期
- localforage: 用于管理Storage
- react-icons: 用于使用图标
- motion: 动效库
- loadsh-es: 用于提供一些常用的utils函数
## 你需要遵循的规则 ## 你需要遵循的规则
- 入口 HTML 文件必须是 `index.html`
- Always respond in 中文 - Always respond in 中文
- 只能新增、修改和删除 src 目录里的文件或者文件夹,严禁修改其他文件或者文件夹!

26
.gitignore vendored Normal file
View File

@@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.zip

View File

@@ -1,2 +0,0 @@
!src/**
!public/**

8
.trae/mcp.json Normal file
View File

@@ -0,0 +1,8 @@
{
"mcpServers": {
"mujian-js-sdk": {
"command": "npx",
"args": ["-y", "@mujian/mcp-docs-server"]
}
}
}

View File

@@ -0,0 +1,10 @@
# 你是一个游戏开发Agent在本工程中你需要协助我开发一个原生 HTML 游戏
## 本工程介绍
- 这是一个模版工程,开发者会基于这个工程进行拓展开发
## 你需要遵循的规则
- 入口 HTML 文件必须是 `index.html`
- Always respond in 中文

14
README.md Normal file
View File

@@ -0,0 +1,14 @@
# 幕间自定义界面-官方模版-H5 版
- [幕间官网](https://mujian.ai)
- [幕间文档站](https://docs.mujian.ai)
- [幕间SDK](https://docs.mujian.ai/creator/sdk/introduction.html)
- [教程地址](https://docs.mujian.ai/creator/game-dev/quick-start-h5.html)
- [仓库地址](https://git.mujian.me/mujian/h5-boilerplate)
本地调试
```sh
pnpm install -g http-server
http-server -p 5173 --cors -c-1
```

68
assets/css/chat.css Normal file
View File

@@ -0,0 +1,68 @@
/* 消息容器 */
#messages {
padding: 10px;
margin-bottom: 10px;
height: calc(100% - 140px);
overflow-y: auto;
}
/* 消息 */
#messages div {
border: 2px solid #000000;
font-size: 14px;
color: #000;
margin-bottom: 10px;
padding: 10px;
border-radius: 5px;
}
/* 消息加载中 */
#messages>.message.loading {
border-color: #003cff;
animation: pulse 1s infinite;
}
/* 消息加载中动画 */
@keyframes pulse {
0% {
border-color: #6e90ff;
}
50% {
border-color: #002ec5;
}
100% {
border-color: #6e90ff;
}
}
/* 用户消息 */
#messages>.message.user {
border-color: #c90000;
}
/* AI消息 */
#messages>.message.assistant {
border-color: #06af2d;
}
/* 输入容器 */
#input-container {
border-top: 2px solid #000000;
height: 100px;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
/* 输入框 */
#input {
margin-bottom: 10px;
height: 50px;
width: 90%;
border: 1px solid #ccc;
border-radius: 5px;
}

View File

@@ -1,5 +1,17 @@
html {
height: 100%;
width: 100%;
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#project-info-img { #project-info-img {
width: 64px; width: 64px;
height: 64px; height: 64px;
object-fit: cover; object-fit: cover;
} }

View File

@@ -1,59 +1,100 @@
const mujianSdk = new window.MujianUMD.MujianSdk(); const mujianSdk = new window.MujianUMD.MujianSdk();
const stopController = new AbortController();
async function chat( // 发送消息。入参是用户输入
query, async function send(query) {
cb, const id = Date.now();
) { addMessage("assistant", "等待回复中...", id); // 添加一个占位的AI消息。用于后续刷返回文字
let lastChunk = ''; startLoading(id); // 给消息添加loading状态
// 让缓冲区跨回调持久,防止分包导致的半行重复解析 await mujianSdk.ai.chat.complete( // 调用 mujian sdk 发送请求
let buffer = ''; query,
await mujianSdk.ai.chat.complete(query, (data) => { (res) => {
updateMessage(id, res.fullContent); // 流式实时更新消息
// data 可能是块状字符串;避免逐字符遍历 if (res.isFinished) { // 如果流式完成结束则停止loading状态
buffer += data; stopLoading(id); // 停止loading状态
const lines = buffer.split('\n'); }
buffer = lines.pop() || ''; },
stopController.signal,
for (const line of lines) { {
if (!line.startsWith('data: ')) continue; parseContent: true, // 让 sdk 只返回消息内容,不会返回其他字段
const payload = line.slice(6); },
try { );
const parsedData = JSON.parse(payload);
if (parsedData?.isFinished) {
// 结束标志,交给外层 await 完成
continue;
}
let content = parsedData?.choices?.[0]?.delta?.content;
// if (content && typeof window !== 'undefined') {
// const username = localStorage.getItem(USERNAME_KEY) || 'User';
// content = content?.replace(new RegExp(FAKE_USERNAME, 'g'), username);
// }
if (content !== undefined && content !== null) {
if (content.length > 0) {
lastChunk += content;
cb && cb(lastChunk);
}
} else {
console.error('data', payload);
}
} catch (error) {
console.log('error', error);
throw error;
}
}
});
// console.log('lastChunk', lastChunk);
return lastChunk;
} }
// 停止发送消息
function stop() {
stopController.abort();
}
mujianSdk.init().then(() => { // 渲染所有消息
chat('你好', (res) => { async function renderAllMessages() {
// console.log('res', res) const messages = await mujianSdk.ai.chat.message.getAll(); // 通过 sdk 获取所有消息
$('#message').text(res); renderMessages(messages); // 渲染所有消息
}) scrollToBottom(); // 滚动到底部
}); }
// 更新消息。入参是消息id和消息内容
function updateMessage(id, message) {
if ($(`#message-assistant-${id}`).length === 0) { // 如果消息不存在,则返回
return;
}
$(`#message-assistant-${id}`).text("assistant: " + message); // 更新消息内容
scrollToBottom(); // 滚动到底部
}
// 添加消息。入参是消息角色和消息内容
function addMessage(role, message, id = null) {
const _id = id || Date.now(); // 如果消息id不存在则生成一个唯一id
$("#messages").append(
`<div id="message-${role}-${_id}" class="message ${role === "user" ? "user" : "assistant"}">${role}: ${message}</div>`, // 添加消息
);
}
function startLoading(id) {
$(`#message-assistant-${id}`).addClass("loading");
}
function stopLoading(id) {
$(`#message-assistant-${id}`).removeClass("loading");
}
function clearMessages() {
$("#messages").empty();
}
function scrollToBottom() {
$("#messages").animate(
{ scrollTop: $("#messages").prop("scrollHeight") },
100,
);
}
// 渲染消息。入参是消息列表
function renderMessages(messages) {
// console.log("messages", messages);
messages.forEach((message) => {
// 添加消息
addMessage(message.role, message.content, message.id);
});
}
// 发送消息。点击发送按钮时,获取用户输入,并发送消息
$("#send").click(async () => {
const query = $("#input").val(); // 获取用户输入
if (!query) { // 如果用户输入为空,则返回
return;
}
$("#input").val(""); // 清空用户输入
addMessage("user", query, Date.now()); // 添加用户消息
await send(query); // 发送消息
});
$("#stop").click(stop); // 点击停止按钮时,停止发送消息
// 初始化。初始化幕间官方SDK
(async () => {
await mujianSdk.init().then(async () => {
await renderAllMessages(); // 渲染所有消息
});
})();

View File

@@ -1,16 +1,217 @@
const mujianSdk = new window.MujianUMD.MujianSdk(); const mujianSdk = new window.MujianUMD.MujianSdk();
mujianSdk.init().then(() => { mujianSdk.init().then(() => {
console.log('init success'); console.log("init success");
mujianSdk.ai.chat.project.getInfo().then((res) => { mujianSdk.ai.chat.project.getInfo().then((res) => {
console.log('getProjectInfo success', res); console.log("getProjectInfo success", res);
window.document.getElementById('project-info').innerHTML = `<pre>${JSON.stringify(res, null, 2)}</pre>`; window.document.getElementById("project-info").innerHTML =
window.document.getElementById('project-info-img').src = res.coverImageUrl; `<pre>${JSON.stringify(res, null, 2)}</pre>`;
}); window.document.getElementById("project-info-img").src = res.coverImageUrl;
});
mujianSdk.ai.chat.settings.persona.getActive().then((res) => { mujianSdk.ai.chat.settings.persona.getActive().then((res) => {
console.log('getPersonaInfo success', res); console.log("getPersonaInfo success", res);
// 支持 JQuery 操作页面元素 // 支持 JQuery 操作页面元素
$('#persona-info').html(JSON.stringify(res)); $("#persona-info").html(JSON.stringify(res));
}); });
$("#text-completion-button").click(async () => {
$("#text-completion-result").html("");
const res = await mujianSdk.ai.openai.completions.create({
prompt: "Hello, world!",
});
console.log("text completion success", res);
$("#text-completion-result").html(JSON.stringify(res));
});
$("#chat-completion-button").click(async () => {
$("#chat-completion-result").html("");
const res = await mujianSdk.ai.openai.chat.completions.create({
messages: [{ role: "user", content: "Hello, world!" }],
});
console.log("chat completion success", res);
$("#chat-completion-result").html(JSON.stringify(res));
});
// 文字补全流式
$("#text-completion-stream-button").click(async () => {
$("#text-completion-stream-result").html("");
const res = await mujianSdk.ai.openai.completions.create(
{
prompt: "给我讲个100字的故事",
stream: true,
},
{},
(data) => {
console.log("text completion stream data", data);
$("#text-completion-stream-result").append(data?.choices?.[0]?.text);
},
);
});
// 对话补全流式
$("#chat-completion-stream-button").click(async () => {
$("#chat-completion-stream-result").html("");
const res = await mujianSdk.ai.openai.chat.completions.create(
{
messages: [{ role: "user", content: "给我讲个100字的故事" }],
stream: true,
},
{},
(data) => {
console.log("chat completion stream data", data);
$("#chat-completion-stream-result").append(
data?.choices?.[0]?.delta?.content,
);
},
);
});
// Responses 非流式
$("#responses-button").click(async () => {
$("#responses-result").html("");
const res = await mujianSdk.ai.openai.responses.create({
input: [
{
type: "message",
role: "user",
content: [
{
type: "input_text",
text: "给我讲个100字的故事",
},
],
},
],
});
console.log("responses success", res);
$("#responses-result").html(res?.output?.[0]?.content?.[0]?.text);
});
// Responses 流式
$("#responses-stream-button").click(async () => {
$("#responses-stream-result").html("");
const res = await mujianSdk.ai.openai.responses.create(
{
input: [
{
type: "message",
role: "user",
content: [
{
type: "input_text",
text: "给我讲个100字的故事",
},
],
},
],
stream: true,
},
{},
(data) => {
// console.log("responses stream data", data);
$("#responses-stream-result").append(data?.delta);
},
);
});
$("#image-generation-button").click(async () => {
$("#image-generation-result").html("");
const res = await mujianSdk.ai.openai.images.generate({
prompt: "A beautiful sunset over a calm ocean",
});
console.log("image generation success", res?.choices?.[0]?.images);
for (const image of res?.choices?.[0]?.images || []) {
$("#image-generation-result").append(
`<img src="${image.image_url?.url}" alt="图像生成结果" style="max-width: 100%; height: auto; margin: 10px; border-radius: 8px;" />`,
);
}
});
$("#image-generation-stream-button").click(async () => {
$("#image-generation-stream-result").html("");
await mujianSdk.ai.openai.images.generate(
{
prompt:
"Create two images, one is a beautiful sunset over a calm ocean, the other is a beautiful sunrise over a calm ocean",
stream: true,
},
{},
(data) => {
console.log("image generation stream data", data);
if (data?.choices?.[0]?.images) {
$("#image-generation-stream-result").append(
`<img src="${data?.choices?.[0]?.images?.[0]?.image_url?.url}" alt="图像生成结果" style="max-width: 100%; height: auto; margin: 10px; border-radius: 8px;" />`,
);
}
},
);
});
$("#tool-call-button").click(async () => {
$("#tool-call-result").html("");
const weatherTool = {
type: "function",
function: {
name: "get_weather",
description: "Get the current weather in a location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city and state, e.g. San Francisco, CA",
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"],
description: "The unit of temperature, e.g. celsius, fahrenheit",
default: "celsius",
},
},
required: ["location"],
},
},
};
const get_weather = async (location, unit) => {
console.log("get_weather", location, unit);
return {
weather: "sunny",
temperature: 20,
unit: unit,
};
};
const TOOL_MAPPING = {
get_weather,
};
const res = await mujianSdk.ai.openai.chat.completions.create({
messages: [
{
role: "system",
content: "You are a helpful assistant.",
},
{
role: "user",
content: "What is the weather in San Francisco? in fahrenheit",
},
],
tools: [weatherTool],
tool_choice: "auto",
max_output_tokens: 9000,
});
console.log("tool call success", res);
$("#tool-call-result").html(JSON.stringify(res));
const msg = res.choices[0].message;
for (const toolCall of msg?.tool_calls || []) {
const toolName = toolCall.function.name;
const { location, unit } = JSON.parse(toolCall.function.arguments);
const toolResponse = await TOOL_MAPPING[toolName](location, unit);
console.log("tool response", toolResponse);
}
});
}); });

View File

@@ -12,16 +12,22 @@
<!-- 你的 CSS 样式代码,都放在这里 --> <!-- 你的 CSS 样式代码,都放在这里 -->
<link rel="stylesheet" href="assets/css/index.css" /> <link rel="stylesheet" href="assets/css/index.css" />
<link rel="stylesheet" href="assets/css/chat.css" />
</head> </head>
<body> <body>
<div id="messages" class="max-h-[200px] overflow-y-auto"></div>
<div id="message"></div>
<div id="input-container">
<textarea id="input" class="" ></textarea>
<div class="flex-1">
<button id="send" class="ui-button ui-widget ui-corner-all">发送</button>
<button id="stop" class="ui-button ui-widget ui-corner-all">停止</button>
</div>
</div>
<!-- 幕间官方SDK --> <!-- 幕间官方SDK -->
<script src="https://npm.onmicrosoft.cn/@mujian/js-sdk@0.0.6-beta.35/dist/umd/index.js"></script> <script src="https://npm.onmicrosoft.cn/@mujian/js-sdk@0.0.6-beta.41/dist/umd/index.js"></script>
<!-- 第三方库JQuery - 主要用于提供便利地操作页面元素的函数 --> <!-- 第三方库JQuery - 主要用于提供便利地操作页面元素的函数 -->
<script src="https://npm.onmicrosoft.cn/jquery@3.7.1/dist/jquery.min.js"></script> <script src="https://npm.onmicrosoft.cn/jquery@3.7.1/dist/jquery.min.js"></script>
<!-- 第三方库JQuery-UI - 主要用于提供基础的UI控件 --> <!-- 第三方库JQuery-UI - 主要用于提供基础的UI控件 -->
@@ -31,6 +37,5 @@
<!-- 你的 JS 代码,都放在这里 --> <!-- 你的 JS 代码,都放在这里 -->
<script src="assets/js/chat.js"></script> <script src="assets/js/chat.js"></script>
</body> </body>
</html> </html>

View File

@@ -15,38 +15,137 @@
</head> </head>
<body> <body>
<h2> <h3>
<img <img
id="logo" id="logo"
src="assets/img/logo.svg" src="assets/img/logo.svg"
alt="幕间UGC模版" alt="幕间UGC模版"
/>幕间UGC自定义界面项目模版 />幕间UGC自定义界面项目模版
</h2> </h3>
<h3>获取项目信息</h3> <h4>获取项目信息</h4>
<div id="project-info"></div> <div id="project-info" class="text-sm"></div>
<div> <div>
这是作品封面,你可以获取到 这是作品封面,你可以获取到
<img id="project-info-img" src="" alt="封面图" /> <img id="project-info-img" src="" alt="封面图" />
</div> </div>
<h3>Chat示例</h3> <h4>获取当前人设</h4>
<button class="ui-button ui-widget ui-corner-all" onclick="window.location.href = '/chat'">前往Chat示例</button> <div id="persona-info" class="text-sm"></div>
<h4>三方库示例</h4>
<h3>获取当前人设</h3>
<div id="persona-info"></div>
<h3>三方库示例</h3>
<i class="fa-solid fa-user"></i> <i class="fa-solid fa-user"></i>
<button class="ui-button ui-widget ui-corner-all">jquery-ui按钮</button> <button class="ui-button ui-widget ui-corner-all">jquery-ui按钮</button>
<div class="flex gap-2">
<h4>
Chat示例
<button
class="ui-button ui-widget ui-corner-all"
onclick="window.location.href = '/chat.html'"
>
前往Chat示例
</button>
</h4>
</div>
<h4>
文字补全 示例 (非流式)
<button
class="ui-button ui-widget ui-corner-all"
id="text-completion-button"
>
触发文字补全
</button>
</h4>
<div id="text-completion-result"></div>
<h4>
文字补全 示例 (流式)
<button
class="ui-button ui-widget ui-corner-all"
id="text-completion-stream-button"
>
触发文字补全
</button>
</h4>
<div id="text-completion-stream-result"></div>
<h4>
对话补全 示例 (非流式)
<button
class="ui-button ui-widget ui-corner-all"
id="chat-completion-button"
>
触发对话补全
</button>
</h4>
<div id="chat-completion-result"></div>
<h4>
对话补全 示例 (流式)
<button
class="ui-button ui-widget ui-corner-all"
id="chat-completion-stream-button"
>
触发对话补全
</button>
</h4>
<div id="chat-completion-stream-result"></div>
<h4>
Responses 示例 (非流式)
<button class="ui-button ui-widget ui-corner-all" id="responses-button">
触发Responses
</button>
</h4>
<div id="responses-result"></div>
<h4>
Responses 示例 (流式)
<button
class="ui-button ui-widget ui-corner-all"
id="responses-stream-button"
>
触发Responses
</button>
</h4>
<div id="responses-stream-result"></div>
<h4>
图像生成 示例(非流式)
<button
class="ui-button ui-widget ui-corner-all"
id="image-generation-button"
>
触发图像生成
</button>
</h4>
<div id="image-generation-result"></div>
<h4>
图像生成 示例(流式)
<button
class="ui-button ui-widget ui-corner-all"
id="image-generation-stream-button"
>
触发图像生成
</button>
</h4>
<div id="image-generation-stream-result"></div>
<h4>
Tool call 示例(非流式)
<button class="ui-button ui-widget ui-corner-all" id="tool-call-button">
触发Tool call
</button>
</h4>
<div id="tool-call-result"></div>
<!-- 幕间官方SDK --> <!-- 幕间官方SDK -->
<script src="https://npm.onmicrosoft.cn/@mujian/js-sdk@0.0.6-beta.35/dist/umd/index.js"></script> <script src="https://npm.onmicrosoft.cn/@mujian/js-sdk@0.0.6-beta.45/dist/umd/index.js"></script>
<!-- 第三方库JQuery - 主要用于提供便利地操作页面元素的函数 --> <!-- 第三方库JQuery - 主要用于提供便利地操作页面元素的函数 -->
<script src="https://npm.onmicrosoft.cn/jquery@3.7.1/dist/jquery.min.js"></script> <script src="https://npm.onmicrosoft.cn/jquery@3.7.1/dist/jquery.min.js"></script>
<!-- 第三方库JQuery-UI - 主要用于提供基础的UI控件 --> <!-- 第三方库JQuery-UI - 主要用于提供基础的UI控件 -->