Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:25:37 +08:00
commit 13df4850f7
29 changed files with 6729 additions and 0 deletions

View File

@@ -0,0 +1,118 @@
/**
* Basic C1Chat Integration for Vite + React
*
* Minimal setup showing how to integrate TheSys Generative UI
* into a Vite + React application with custom backend.
*
* Features:
* - Simple form input
* - C1Component for custom UI control
* - Manual state management
* - Basic error handling
*
* Prerequisites:
* - Backend API endpoint at /api/chat
* - Environment variable: VITE_API_URL (optional, defaults to relative path)
*/
import "@crayonai/react-ui/styles/index.css";
import { ThemeProvider, C1Component } from "@thesysai/genui-sdk";
import { useState } from "react";
import "./App.css";
export default function App() {
const [isLoading, setIsLoading] = useState(false);
const [c1Response, setC1Response] = useState("");
const [question, setQuestion] = useState("");
const [error, setError] = useState<string | null>(null);
const apiUrl = import.meta.env.VITE_API_URL || "/api/chat";
const makeApiCall = async (query: string, previousResponse?: string) => {
if (!query.trim()) return;
setIsLoading(true);
setError(null);
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
prompt: query,
previousC1Response: previousResponse || c1Response,
}),
});
if (!response.ok) {
throw new Error(`API Error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
setC1Response(data.response || data.c1Response);
setQuestion(""); // Clear input after successful request
} catch (err) {
console.error("Error calling API:", err);
setError(err instanceof Error ? err.message : "Failed to get response");
} finally {
setIsLoading(false);
}
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
makeApiCall(question);
};
return (
<div className="app-container">
<header>
<h1>TheSys AI Assistant</h1>
<p>Ask me anything and I'll generate an interactive response</p>
</header>
<form onSubmit={handleSubmit} className="input-form">
<input
type="text"
value={question}
onChange={(e) => setQuestion(e.target.value)}
placeholder="Ask me anything..."
className="question-input"
disabled={isLoading}
autoFocus
/>
<button
type="submit"
className="submit-button"
disabled={isLoading || !question.trim()}
>
{isLoading ? "Processing..." : "Send"}
</button>
</form>
{error && (
<div className="error-message">
<strong>Error:</strong> {error}
</div>
)}
{c1Response && (
<div className="response-container">
<ThemeProvider>
<C1Component
c1Response={c1Response}
isStreaming={isLoading}
updateMessage={(message) => setC1Response(message)}
onAction={({ llmFriendlyMessage }) => {
// Handle interactive actions from generated UI
if (!isLoading) {
makeApiCall(llmFriendlyMessage, c1Response);
}
}}
/>
</ThemeProvider>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,208 @@
/**
* Custom C1Component Integration with Advanced State Management
*
* Shows how to use C1Component with full control over:
* - Message history
* - Conversation state
* - Custom UI layout
* - Error boundaries
*
* Use this when you need more control than C1Chat provides.
*/
import "@crayonai/react-ui/styles/index.css";
import { ThemeProvider, C1Component } from "@thesysai/genui-sdk";
import { useState, useRef, useEffect } from "react";
import { ErrorBoundary } from "react-error-boundary";
import "./App.css";
interface Message {
id: string;
role: "user" | "assistant";
content: string;
timestamp: Date;
}
function ErrorFallback({ error, resetErrorBoundary }: {
error: Error;
resetErrorBoundary: () => void;
}) {
return (
<div className="error-boundary">
<h2>Something went wrong</h2>
<pre className="error-details">{error.message}</pre>
<button onClick={resetErrorBoundary} className="retry-button">
Try again
</button>
</div>
);
}
export default function App() {
const [messages, setMessages] = useState<Message[]>([]);
const [currentResponse, setCurrentResponse] = useState("");
const [isStreaming, setIsStreaming] = useState(false);
const [inputValue, setInputValue] = useState("");
const messagesEndRef = useRef<HTMLDivElement>(null);
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages, currentResponse]);
const sendMessage = async (userMessage: string) => {
if (!userMessage.trim() || isStreaming) return;
// Add user message
const userMsg: Message = {
id: crypto.randomUUID(),
role: "user",
content: userMessage,
timestamp: new Date(),
};
setMessages((prev) => [...prev, userMsg]);
setInputValue("");
setIsStreaming(true);
setCurrentResponse("");
try {
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: [...messages, userMsg].map((m) => ({
role: m.role,
content: m.content,
})),
}),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
// Add assistant response
const assistantMsg: Message = {
id: crypto.randomUUID(),
role: "assistant",
content: data.response,
timestamp: new Date(),
};
setCurrentResponse(data.response);
setMessages((prev) => [...prev, assistantMsg]);
} catch (error) {
console.error("Error sending message:", error);
// Add error message
const errorMsg: Message = {
id: crypto.randomUUID(),
role: "assistant",
content: `Error: ${error instanceof Error ? error.message : "Failed to get response"}`,
timestamp: new Date(),
};
setMessages((prev) => [...prev, errorMsg]);
} finally {
setIsStreaming(false);
}
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
sendMessage(inputValue);
};
const clearConversation = () => {
setMessages([]);
setCurrentResponse("");
};
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<div className="chat-container">
<div className="chat-header">
<h1>AI Assistant</h1>
<button onClick={clearConversation} className="clear-button">
Clear
</button>
</div>
<div className="messages-container">
{messages.map((message, index) => (
<div
key={message.id}
className={`message message-${message.role}`}
>
<div className="message-header">
<span className="message-role">
{message.role === "user" ? "You" : "AI"}
</span>
<span className="message-time">
{message.timestamp.toLocaleTimeString()}
</span>
</div>
{message.role === "assistant" ? (
<ThemeProvider>
<C1Component
c1Response={message.content}
isStreaming={
index === messages.length - 1 && isStreaming
}
updateMessage={(updatedContent) => {
setCurrentResponse(updatedContent);
setMessages((prev) =>
prev.map((m) =>
m.id === message.id
? { ...m, content: updatedContent }
: m
)
);
}}
onAction={({ llmFriendlyMessage }) => {
sendMessage(llmFriendlyMessage);
}}
/>
</ThemeProvider>
) : (
<div className="message-content">{message.content}</div>
)}
</div>
))}
{isStreaming && !currentResponse && (
<div className="loading-indicator">
<div className="spinner" />
<span>AI is thinking...</span>
</div>
)}
<div ref={messagesEndRef} />
</div>
<form onSubmit={handleSubmit} className="input-container">
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Type your message..."
disabled={isStreaming}
className="message-input"
autoFocus
/>
<button
type="submit"
disabled={!inputValue.trim() || isStreaming}
className="send-button"
>
{isStreaming ? "..." : "Send"}
</button>
</form>
</div>
</ErrorBoundary>
);
}

View File

@@ -0,0 +1,40 @@
{
"name": "thesys-vite-react-example",
"private": true,
"version": "1.0.0",
"type": "module",
"description": "Vite + React integration with TheSys Generative UI",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0"
},
"dependencies": {
"@thesysai/genui-sdk": "^0.6.40",
"@crayonai/react-ui": "^0.8.42",
"@crayonai/react-core": "^0.7.6",
"@crayonai/stream": "^0.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-error-boundary": "^5.0.0",
"openai": "^4.73.0",
"zod": "^3.24.1",
"zod-to-json-schema": "^3.24.1"
},
"devDependencies": {
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.0.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.16",
"typescript": "^5.7.3",
"vite": "^6.0.5"
},
"optionalDependencies": {
"@tavily/core": "^1.0.0"
}
}

View File

@@ -0,0 +1,220 @@
/**
* TheSys C1 with Custom Theming and Dark Mode
*
* Demonstrates:
* - Custom theme configuration
* - Dark mode toggle
* - System theme detection
* - Theme presets
* - CSS variable overrides
*/
import "@crayonai/react-ui/styles/index.css";
import { C1Chat, ThemeProvider } from "@thesysai/genui-sdk";
import { themePresets } from "@crayonai/react-ui";
import { useState, useEffect } from "react";
import "./App.css";
type ThemeMode = "light" | "dark" | "system";
// Custom theme object
const customLightTheme = {
mode: "light" as const,
colors: {
primary: "#3b82f6",
secondary: "#8b5cf6",
background: "#ffffff",
foreground: "#1f2937",
border: "#e5e7eb",
muted: "#f3f4f6",
accent: "#10b981",
},
fonts: {
body: "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
heading: "'Poppins', sans-serif",
mono: "'Fira Code', 'Courier New', monospace",
},
borderRadius: "8px",
spacing: {
base: "16px",
},
};
const customDarkTheme = {
...customLightTheme,
mode: "dark" as const,
colors: {
primary: "#60a5fa",
secondary: "#a78bfa",
background: "#111827",
foreground: "#f9fafb",
border: "#374151",
muted: "#1f2937",
accent: "#34d399",
},
};
function useSystemTheme(): "light" | "dark" {
const [systemTheme, setSystemTheme] = useState<"light" | "dark">(
() =>
window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light"
);
useEffect(() => {
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
const handler = (e: MediaQueryListEvent) => {
setSystemTheme(e.matches ? "dark" : "light");
};
mediaQuery.addEventListener("change", handler);
return () => mediaQuery.removeEventListener("change", handler);
}, []);
return systemTheme;
}
export default function ThemedChat() {
const [themeMode, setThemeMode] = useState<ThemeMode>(
() => (localStorage.getItem("theme-mode") as ThemeMode) || "system"
);
const [usePreset, setUsePreset] = useState(false);
const systemTheme = useSystemTheme();
// Determine actual theme to use
const actualTheme =
themeMode === "system" ? systemTheme : themeMode;
// Choose theme object
const theme = usePreset
? themePresets.candy // Use built-in preset
: actualTheme === "dark"
? customDarkTheme
: customLightTheme;
// Persist theme preference
useEffect(() => {
localStorage.setItem("theme-mode", themeMode);
// Apply to document for app-wide styling
document.documentElement.setAttribute("data-theme", actualTheme);
}, [themeMode, actualTheme]);
return (
<div className="themed-app">
<div className="theme-controls">
<div className="theme-selector">
<h3>Theme Mode</h3>
<div className="button-group">
<button
className={themeMode === "light" ? "active" : ""}
onClick={() => setThemeMode("light")}
>
Light
</button>
<button
className={themeMode === "dark" ? "active" : ""}
onClick={() => setThemeMode("dark")}
>
🌙 Dark
</button>
<button
className={themeMode === "system" ? "active" : ""}
onClick={() => setThemeMode("system")}
>
💻 System
</button>
</div>
</div>
<div className="theme-type">
<h3>Theme Type</h3>
<div className="button-group">
<button
className={!usePreset ? "active" : ""}
onClick={() => setUsePreset(false)}
>
Custom
</button>
<button
className={usePreset ? "active" : ""}
onClick={() => setUsePreset(true)}
>
Preset (Candy)
</button>
</div>
</div>
</div>
<div className="chat-wrapper">
<ThemeProvider theme={{ ...theme, mode: actualTheme }}>
<C1Chat
apiUrl="/api/chat"
agentName="Themed AI Assistant"
logoUrl="https://placehold.co/100x100/3b82f6/ffffff?text=AI"
/>
</ThemeProvider>
</div>
<div className="theme-info">
<h3>Current Theme</h3>
<pre className="theme-preview">
{JSON.stringify(
{
mode: actualTheme,
usingPreset: usePreset,
preferredMode: themeMode,
systemPreference: systemTheme,
},
null,
2
)}
</pre>
</div>
</div>
);
}
/**
* CSS Example (App.css):
*
* [data-theme="light"] {
* --app-bg: #ffffff;
* --app-text: #1f2937;
* }
*
* [data-theme="dark"] {
* --app-bg: #111827;
* --app-text: #f9fafb;
* }
*
* .themed-app {
* background: var(--app-bg);
* color: var(--app-text);
* min-height: 100vh;
* transition: background-color 0.3s ease, color 0.3s ease;
* }
*
* .theme-controls {
* padding: 2rem;
* display: flex;
* gap: 2rem;
* border-bottom: 1px solid var(--app-text);
* }
*
* .button-group button {
* padding: 0.5rem 1rem;
* border: 1px solid var(--app-text);
* background: transparent;
* color: var(--app-text);
* cursor: pointer;
* transition: all 0.2s;
* }
*
* .button-group button.active {
* background: var(--app-text);
* color: var(--app-bg);
* }
*/

View File

@@ -0,0 +1,276 @@
/**
* Tool Calling Integration Example
*
* Demonstrates how to integrate tool calling (function calling) with TheSys C1.
* Shows:
* - Web search tool with Tavily API
* - Product inventory lookup
* - Order creation with Zod validation
* - Interactive UI for tool results
*
* Backend Requirements:
* - OpenAI SDK with runTools support
* - Zod for schema validation
* - Tool execution handlers
*/
import "@crayonai/react-ui/styles/index.css";
import { ThemeProvider, C1Component } from "@thesysai/genui-sdk";
import { useState } from "react";
import "./App.css";
// Example tool schemas (these match backend Zod schemas)
interface WebSearchTool {
name: "web_search";
args: {
query: string;
max_results: number;
};
}
interface ProductLookupTool {
name: "lookup_product";
args: {
product_type?: "gloves" | "hat" | "scarf";
};
}
interface CreateOrderTool {
name: "create_order";
args: {
customer_email: string;
items: Array<{
type: "gloves" | "hat" | "scarf";
quantity: number;
[key: string]: any;
}>;
};
}
type ToolCall = WebSearchTool | ProductLookupTool | CreateOrderTool;
export default function ToolCallingExample() {
const [isLoading, setIsLoading] = useState(false);
const [c1Response, setC1Response] = useState("");
const [question, setQuestion] = useState("");
const [activeTools, setActiveTools] = useState<string[]>([]);
const makeApiCall = async (query: string, previousResponse?: string) => {
if (!query.trim()) return;
setIsLoading(true);
setActiveTools([]);
try {
const response = await fetch("/api/chat-with-tools", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
prompt: query,
previousC1Response: previousResponse,
}),
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
// Handle streaming response
const reader = response.body?.getReader();
if (!reader) throw new Error("No response body");
const decoder = new TextDecoder();
let accumulatedResponse = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split("\n");
for (const line of lines) {
if (line.startsWith("data: ")) {
try {
const data = JSON.parse(line.slice(6));
if (data.type === "tool_call") {
// Track which tools are being called
setActiveTools((prev) => [...prev, data.tool_name]);
} else if (data.type === "content") {
accumulatedResponse += data.content;
setC1Response(accumulatedResponse);
}
} catch (e) {
// Skip invalid JSON
}
}
}
}
setQuestion("");
} catch (err) {
console.error("Error:", err);
setC1Response(
`Error: ${err instanceof Error ? err.message : "Failed to get response"}`
);
} finally {
setIsLoading(false);
}
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
makeApiCall(question);
};
// Example prompts to demonstrate tools
const examplePrompts = [
"Search the web for the latest AI news",
"Show me available products in the inventory",
"Create an order for 2 blue gloves size M and 1 red hat",
];
return (
<div className="tool-calling-container">
<header>
<h1>AI Assistant with Tools</h1>
<p>Ask me to search the web, check inventory, or create orders</p>
</header>
<div className="example-prompts">
<h3>Try these examples:</h3>
{examplePrompts.map((prompt, index) => (
<button
key={index}
onClick={() => {
setQuestion(prompt);
makeApiCall(prompt);
}}
className="example-button"
disabled={isLoading}
>
{prompt}
</button>
))}
</div>
<form onSubmit={handleSubmit} className="input-form">
<input
type="text"
value={question}
onChange={(e) => setQuestion(e.target.value)}
placeholder="Ask me to use a tool..."
className="question-input"
disabled={isLoading}
/>
<button
type="submit"
className="submit-button"
disabled={isLoading || !question.trim()}
>
{isLoading ? "Processing..." : "Send"}
</button>
</form>
{activeTools.length > 0 && (
<div className="active-tools">
<h4>Active Tools:</h4>
<div className="tool-badges">
{activeTools.map((tool, index) => (
<span key={index} className="tool-badge">
{tool}
</span>
))}
</div>
</div>
)}
{c1Response && (
<div className="response-container">
<ThemeProvider>
<C1Component
c1Response={c1Response}
isStreaming={isLoading}
updateMessage={(message) => setC1Response(message)}
onAction={({ llmFriendlyMessage, rawAction }) => {
console.log("Tool action:", rawAction);
if (!isLoading) {
makeApiCall(llmFriendlyMessage, c1Response);
}
}}
/>
</ThemeProvider>
</div>
)}
<div className="tool-info">
<h3>Available Tools</h3>
<ul>
<li>
<strong>web_search</strong> - Search the web for current information
</li>
<li>
<strong>lookup_product</strong> - Check product inventory
</li>
<li>
<strong>create_order</strong> - Create a new product order
</li>
</ul>
</div>
</div>
);
}
/**
* Backend API Example (route.ts or server.ts):
*
* import { z } from "zod";
* import zodToJsonSchema from "zod-to-json-schema";
* import OpenAI from "openai";
* import { TavilySearchAPIClient } from "@tavily/core";
*
* const webSearchSchema = z.object({
* query: z.string(),
* max_results: z.number().int().min(1).max(10).default(5),
* });
*
* const webSearchTool = {
* type: "function" as const,
* function: {
* name: "web_search",
* description: "Search the web for current information",
* parameters: zodToJsonSchema(webSearchSchema),
* },
* };
*
* const client = new OpenAI({
* baseURL: "https://api.thesys.dev/v1/embed",
* apiKey: process.env.THESYS_API_KEY,
* });
*
* const tavily = new TavilySearchAPIClient({
* apiKey: process.env.TAVILY_API_KEY,
* });
*
* export async function POST(req) {
* const { prompt } = await req.json();
*
* const stream = await client.beta.chat.completions.runTools({
* model: "c1/openai/gpt-5/v-20250930",
* messages: [
* {
* role: "system",
* content: "You are a helpful assistant with access to tools.",
* },
* { role: "user", content: prompt },
* ],
* stream: true,
* tools: [webSearchTool, productLookupTool, createOrderTool],
* toolChoice: "auto",
* });
*
* // Handle tool execution and streaming...
* }
*/