Skip to content

Commit 03b7d30

Browse files
committed
fix: AI example updates
1 parent d0de84e commit 03b7d30

File tree

22 files changed

+63
-52
lines changed

22 files changed

+63
-52
lines changed

frameworks/react-cra/examples/tanchat/assets/src/components/example-AIAssistant.tsx

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,14 @@ import { Store } from '@tanstack/store'
55
import { Send, X, ChevronRight } from 'lucide-react'
66
import { Streamdown } from 'streamdown'
77

8-
import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
9-
import { clientTools } from '@tanstack/ai-client'
10-
import type { UIMessage } from '@tanstack/ai-react'
8+
import { useGuitarRecommendationChat } from '@/lib/example.ai-hook'
9+
import type { ChatMessages } from '@/lib/example.ai-hook'
1110

1211
import GuitarRecommendation from './example-GuitarRecommendation'
13-
import { recommendGuitarToolDef } from '@/lib/example.guitar-tools'
14-
15-
const recommendGuitarToolClient = recommendGuitarToolDef.client(({ id }) => ({
16-
id: +id,
17-
}))
18-
19-
const tools = clientTools(recommendGuitarToolClient)
2012

2113
export const showAIAssistant = new Store(false)
2214

23-
function Messages({ messages }: { messages: Array<UIMessage> }) {
15+
function Messages({ messages }: { messages: ChatMessages }) {
2416
const messagesContainerRef = useRef<HTMLDivElement>(null)
2517

2618
useEffect(() => {
@@ -45,7 +37,7 @@ function Messages({ messages }: { messages: Array<UIMessage> }) {
4537
key={id}
4638
className={`py-3 ${
4739
role === 'assistant'
48-
? 'bg-gradient-to-r from-orange-500/5 to-red-600/5'
40+
? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
4941
: 'bg-transparent'
5042
}`}
5143
>
@@ -54,7 +46,7 @@ function Messages({ messages }: { messages: Array<UIMessage> }) {
5446
return (
5547
<div key={index} className="flex items-start gap-2 px-4">
5648
{role === 'assistant' ? (
57-
<div className="w-6 h-6 rounded-lg bg-gradient-to-r from-orange-500 to-red-600 flex items-center justify-center text-xs font-medium text-white flex-shrink-0">
49+
<div className="w-6 h-6 rounded-lg bg-linear-to-r from-orange-500 to-red-600 flex items-center justify-center text-xs font-medium text-white flex-shrink-0">
5850
AI
5951
</div>
6052
) : (
@@ -88,17 +80,14 @@ function Messages({ messages }: { messages: Array<UIMessage> }) {
8880

8981
export default function AIAssistant() {
9082
const isOpen = useStore(showAIAssistant)
91-
const { messages, sendMessage } = useChat({
92-
connection: fetchServerSentEvents('/demo/api/tanchat'),
93-
tools,
94-
})
83+
const { messages, sendMessage } = useGuitarRecommendationChat()
9584
const [input, setInput] = useState('')
9685

9786
return (
9887
<div className="relative z-50">
9988
<button
10089
onClick={() => showAIAssistant.setState((state) => !state)}
101-
className="w-full flex items-center justify-between px-4 py-2.5 rounded-lg bg-gradient-to-r from-orange-500 to-red-600 text-white hover:opacity-90 transition-opacity"
90+
className="w-full flex items-center justify-between px-4 py-2.5 rounded-lg bg-linear-to-r from-orange-500 to-red-600 text-white hover:opacity-90 transition-opacity"
10291
>
10392
<div className="flex items-center gap-2">
10493
<div className="w-5 h-5 rounded-lg bg-white/20 flex items-center justify-center text-xs font-medium">
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import { aiDevtoolsPlugin } from '@tanstack/react-ai-devtools'
2+
3+
export default aiDevtoolsPlugin()
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import {
2+
fetchServerSentEvents,
3+
useChat,
4+
createChatClientOptions,
5+
} from "@tanstack/ai-react";
6+
import type { InferChatMessages } from "@tanstack/ai-react";
7+
import { clientTools } from "@tanstack/ai-client";
8+
9+
import { recommendGuitarToolDef } from "@/lib/example.guitar-tools";
10+
11+
const recommendGuitarToolClient = recommendGuitarToolDef.client(({ id }) => ({
12+
id: +id,
13+
}));
14+
15+
const chatOptions = createChatClientOptions({
16+
connection: fetchServerSentEvents("/demo/api/tanchat"),
17+
tools: clientTools(recommendGuitarToolClient),
18+
});
19+
20+
export type ChatMessages = InferChatMessages<typeof chatOptions>;
21+
22+
export const useGuitarRecommendationChat = () => useChat(chatOptions);

frameworks/react-cra/examples/tanchat/assets/src/routes/demo/tanchat.tsx

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,19 @@ import { useEffect, useRef, useState } from 'react'
22
import { createFileRoute } from '@tanstack/react-router'
33
import { Send, Square } from 'lucide-react'
44
import { Streamdown } from 'streamdown'
5-
import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
6-
import { clientTools } from '@tanstack/ai-client'
7-
import type { UIMessage } from '@tanstack/ai-react'
5+
6+
import { useGuitarRecommendationChat } from '@/lib/example.ai-hook'
7+
import type { ChatMessages } from '@/lib/example.ai-hook'
88

99
import GuitarRecommendation from '@/components/example-GuitarRecommendation'
10-
import { recommendGuitarToolDef } from '@/lib/example.guitar-tools'
1110

1211
import './tanchat.css'
1312

14-
const recommendGuitarToolClient = recommendGuitarToolDef.client(({ id }) => ({
15-
id: +id,
16-
}))
17-
18-
const tools = clientTools(recommendGuitarToolClient)
19-
2013
function InitalLayout({ children }: { children: React.ReactNode }) {
2114
return (
2215
<div className="flex-1 flex items-center justify-center px-4">
2316
<div className="text-center max-w-3xl mx-auto w-full">
24-
<h1 className="text-6xl font-bold mb-4 bg-gradient-to-r from-orange-500 to-red-600 text-transparent bg-clip-text uppercase">
17+
<h1 className="text-6xl font-bold mb-4 bg-linear-to-r from-orange-500 to-red-600 text-transparent bg-clip-text uppercase">
2518
<span className="text-white">TanStack</span> Chat
2619
</h1>
2720
<p className="text-gray-400 mb-6 w-2/3 mx-auto text-lg">
@@ -42,7 +35,7 @@ function ChattingLayout({ children }: { children: React.ReactNode }) {
4235
)
4336
}
4437

45-
function Messages({ messages }: { messages: Array<UIMessage> }) {
38+
function Messages({ messages }: { messages: ChatMessages }) {
4639
const messagesContainerRef = useRef<HTMLDivElement>(null)
4740

4841
useEffect(() => {
@@ -67,13 +60,13 @@ function Messages({ messages }: { messages: Array<UIMessage> }) {
6760
key={message.id}
6861
className={`p-4 ${
6962
message.role === 'assistant'
70-
? 'bg-gradient-to-r from-orange-500/5 to-red-600/5'
63+
? 'bg-linear-to-r from-orange-500/5 to-red-600/5'
7164
: 'bg-transparent'
7265
}`}
7366
>
7467
<div className="flex items-start gap-4 max-w-3xl mx-auto w-full">
7568
{message.role === 'assistant' ? (
76-
<div className="w-8 h-8 rounded-lg bg-gradient-to-r from-orange-500 to-red-600 mt-2 flex items-center justify-center text-sm font-medium text-white flex-shrink-0">
69+
<div className="w-8 h-8 rounded-lg bg-linear-to-r from-orange-500 to-red-600 mt-2 flex items-center justify-center text-sm font-medium text-white flex-shrink-0">
7770
AI
7871
</div>
7972
) : (
@@ -117,10 +110,8 @@ function Messages({ messages }: { messages: Array<UIMessage> }) {
117110
}
118111

119112
function ChatPage() {
120-
const { messages, sendMessage, isLoading, stop } = useChat({
121-
connection: fetchServerSentEvents('/demo/api/tanchat'),
122-
tools,
123-
})
113+
const { messages, sendMessage, isLoading, stop } =
114+
useGuitarRecommendationChat()
124115
const [input, setInput] = useState('')
125116

126117
const Layout = messages.length ? ChattingLayout : InitalLayout

frameworks/react-cra/examples/tanchat/info.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@
3131
"type": "header-user",
3232
"path": "src/components/example-AIAssistant.tsx",
3333
"jsName": "TanChatAIAssistant"
34+
},
35+
{
36+
"type": "devtools",
37+
"path": "src/lib/ai-devtools.tsx",
38+
"jsName": "AiDevtools"
3439
}
3540
],
3641
"dependsOn": ["start", "store"],

frameworks/react-cra/examples/tanchat/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"@tanstack/ai-anthropic": "^0.0.1",
55
"@tanstack/ai-client": "^0.0.1",
66
"@tanstack/ai-react": "^0.0.1",
7+
"@tanstack/react-ai-devtools": "^0.0.1",
78
"highlight.js": "^11.11.1",
89
"streamdown": "^1.6.5",
910
"lucide-react": "^0.544.0",
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
// This file is auto-generated. Do not edit manually.
22
// Generated from add-ons, examples, hosts, project, and toolchains directories
3-
export const contentChecksum = 'd7d41081b1bcca2817f39f2d535d21ebd80c3dd2ec04560d0cd3a0663eb04058'
3+
export const contentChecksum = '0b4c2f7b4e91fb80d16db47f572d9547629aac841a00f154cb18869936013618'

frameworks/react-cra/tests/snapshots/react-cra/cr-js-form-npm.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
"/src/styles.css": "\nbody {\n margin: 0;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\",\n sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n font-family: source-code-pro, Menlo, Monaco, Consolas, \"Courier New\",\n monospace;\n}\n",
2020
"README.md": "Welcome to your new TanStack app! \n\n# Getting Started\n\nTo run this application:\n\n```bash\nnpm install\nnpm run start\n```\n\n# Building For Production\n\nTo build this application for production:\n\n```bash\nnpm run build\n```\n\n## Testing\n\nThis project uses [Vitest](https://vitest.dev/) for testing. You can run the tests with:\n\n```bash\nnpm run test\n```\n\n## Styling\n\nThis project uses CSS for styling.\n\n\n\n\n## Routing\nThis project uses [TanStack Router](https://tanstack.com/router). The initial setup is a file based router. Which means that the routes are managed as files in `src/routes`.\n\n### Adding A Route\n\nTo add a new route to your application just add another a new file in the `./src/routes` directory.\n\nTanStack will automatically generate the content of the route file for you.\n\nNow that you have two routes you can use a `Link` component to navigate between them.\n\n### Adding Links\n\nTo use SPA (Single Page Application) navigation you will need to import the `Link` component from `@tanstack/react-router`.\n\n```tsx\nimport { Link } from \"@tanstack/react-router\";\n```\n\nThen anywhere in your JSX you can use it like so:\n\n```tsx\n<Link to=\"/about\">About</Link>\n```\n\nThis will create a link that will navigate to the `/about` route.\n\nMore information on the `Link` component can be found in the [Link documentation](https://tanstack.com/router/v1/docs/framework/react/api/router/linkComponent).\n\n### Using A Layout\n\nIn the File Based Routing setup the layout is located in `src/routes/__root.tsx`. Anything you add to the root route will appear in all the routes. The route content will appear in the JSX where you use the `<Outlet />` component.\n\nHere is an example layout that includes a header:\n\n```tsx\nimport { Outlet, createRootRoute } from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nimport { Link } from \"@tanstack/react-router\";\n\nexport const Route = createRootRoute({\n component: () => (\n <>\n <header>\n <nav>\n <Link to=\"/\">Home</Link>\n <Link to=\"/about\">About</Link>\n </nav>\n </header>\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n```\n\nThe `<TanStackRouterDevtools />` component is not required so you can remove it if you don't want it in your layout.\n\nMore information on layouts can be found in the [Layouts documentation](https://tanstack.com/router/latest/docs/framework/react/guide/routing-concepts#layouts).\n\n\n## Data Fetching\n\nThere are multiple ways to fetch data in your application. You can use TanStack Query to fetch data from a server. But you can also use the `loader` functionality built into TanStack Router to load the data for a route before it's rendered.\n\nFor example:\n\n```tsx\nconst peopleRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: \"/people\",\n loader: async () => {\n const response = await fetch(\"https://swapi.dev/api/people\");\n return response.json();\n },\n component: () => {\n const data = peopleRoute.useLoaderData();\n return (\n <ul>\n {data.results.map((person) => (\n <li key={person.name}>{person.name}</li>\n ))}\n </ul>\n );\n },\n});\n```\n\nLoaders simplify your data fetching logic dramatically. Check out more information in the [Loader documentation](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#loader-parameters).\n\n### React-Query\n\nReact-Query is an excellent addition or alternative to route loading and integrating it into you application is a breeze.\n\nFirst add your dependencies:\n\n```bash\nnpm install @tanstack/react-query @tanstack/react-query-devtools\n```\n\nNext we'll need to create a query client and provider. We recommend putting those in `main.jsx`.\n\n```tsx\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\n\n// ...\n\nconst queryClient = new QueryClient();\n\n// ...\n\nif (!rootElement.innerHTML) {\n const root = ReactDOM.createRoot(rootElement);\n\n root.render(\n <QueryClientProvider client={queryClient}>\n <RouterProvider router={router} />\n </QueryClientProvider>\n );\n}\n```\n\nYou can also add TanStack Query Devtools to the root route (optional).\n\n```tsx\nimport { ReactQueryDevtools } from \"@tanstack/react-query-devtools\";\n\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <Outlet />\n <ReactQueryDevtools buttonPosition=\"top-right\" />\n <TanStackRouterDevtools />\n </>\n ),\n});\n```\n\nNow you can use `useQuery` to fetch your data.\n\n```tsx\nimport { useQuery } from \"@tanstack/react-query\";\n\nimport \"./App.css\";\n\nfunction App() {\n const { data } = useQuery({\n queryKey: [\"people\"],\n queryFn: () =>\n fetch(\"https://swapi.dev/api/people\")\n .then((res) => res.json())\n .then((data) => data.results),\n initialData: [],\n });\n\n return (\n <div>\n <ul>\n {data.map((person) => (\n <li key={person.name}>{person.name}</li>\n ))}\n </ul>\n </div>\n );\n}\n\nexport default App;\n```\n\nYou can find out everything you need to know on how to use React-Query in the [React-Query documentation](https://tanstack.com/query/latest/docs/framework/react/overview).\n\n## State Management\n\nAnother common requirement for React applications is state management. There are many options for state management in React. TanStack Store provides a great starting point for your project.\n\nFirst you need to add TanStack Store as a dependency:\n\n```bash\nnpm install @tanstack/store\n```\n\nNow let's create a simple counter in the `src/App.jsx` file as a demonstration.\n\n```tsx\nimport { useStore } from \"@tanstack/react-store\";\nimport { Store } from \"@tanstack/store\";\nimport \"./App.css\";\n\nconst countStore = new Store(0);\n\nfunction App() {\n const count = useStore(countStore);\n return (\n <div>\n <button onClick={() => countStore.setState((n) => n + 1)}>\n Increment - {count}\n </button>\n </div>\n );\n}\n\nexport default App;\n```\n\nOne of the many nice features of TanStack Store is the ability to derive state from other state. That derived state will update when the base state updates.\n\nLet's check this out by doubling the count using derived state.\n\n```tsx\nimport { useStore } from \"@tanstack/react-store\";\nimport { Store, Derived } from \"@tanstack/store\";\nimport \"./App.css\";\n\nconst countStore = new Store(0);\n\nconst doubledStore = new Derived({\n fn: () => countStore.state * 2,\n deps: [countStore],\n});\ndoubledStore.mount();\n\nfunction App() {\n const count = useStore(countStore);\n const doubledCount = useStore(doubledStore);\n\n return (\n <div>\n <button onClick={() => countStore.setState((n) => n + 1)}>\n Increment - {count}\n </button>\n <div>Doubled - {doubledCount}</div>\n </div>\n );\n}\n\nexport default App;\n```\n\nWe use the `Derived` class to create a new store that is derived from another store. The `Derived` class has a `mount` method that will start the derived store updating.\n\nOnce we've created the derived store we can use it in the `App` component just like we would any other store using the `useStore` hook.\n\nYou can find out everything you need to know on how to use TanStack Store in the [TanStack Store documentation](https://tanstack.com/store/latest).\n\n# Demo files\n\nFiles prefixed with `demo` can be safely deleted. They are there to provide a starting point for you to play around with the features you've installed.\n\n# Learn More\n\nYou can learn more about all of the offerings from TanStack in the [TanStack documentation](https://tanstack.com).\n",
2121
"index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <link rel=\"icon\" href=\"/favicon.ico\" />\n <meta name=\"theme-color\" content=\"#000000\" />\n <meta\n name=\"description\"\n content=\"Web site created using create-tsrouter-app\"\n />\n <link rel=\"apple-touch-icon\" href=\"/logo192.png\" />\n <link rel=\"manifest\" href=\"/manifest.json\" />\n <title>Create TanStack App - TEST</title>\n </head>\n <body>\n <div id=\"app\"></div>\n <script type=\"module\" src=\"/src/main.jsx\"></script>\n </body>\n</html>\n",
22-
"package.json": "{\n \"name\": \"TEST\",\n \"private\": true,\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite --port 3000\",\n \"build\": \"vite build && tsc\",\n \"serve\": \"vite preview\",\n \"test\": \"vitest run\"\n },\n \"dependencies\": {\n \"@tanstack/react-devtools\": \"^0.7.0\",\n \"@tanstack/react-form\": \"^1.0.0\",\n \"@tanstack/react-router\": \"^1.132.0\",\n \"@tanstack/react-router-devtools\": \"^1.132.0\",\n \"@tanstack/router-plugin\": \"^1.132.0\",\n \"react\": \"^19.2.0\",\n \"react-dom\": \"^19.2.0\",\n \"zod\": \"^4.1.11\"\n },\n \"devDependencies\": {\n \"@tanstack/devtools-vite\": \"^0.3.11\",\n \"@testing-library/dom\": \"^10.4.0\",\n \"@testing-library/react\": \"^16.2.0\",\n \"@types/react\": \"^19.2.0\",\n \"@types/react-dom\": \"^19.2.0\",\n \"@vitejs/plugin-react\": \"^5.0.4\",\n \"jsdom\": \"^27.0.0\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^7.1.7\",\n \"vitest\": \"^3.0.5\",\n \"web-vitals\": \"^5.1.0\"\n }\n}",
22+
"package.json": "{\n \"name\": \"TEST\",\n \"private\": true,\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"vite --port 3000\",\n \"build\": \"vite build && tsc\",\n \"preview\": \"vite preview\",\n \"test\": \"vitest run\"\n },\n \"dependencies\": {\n \"@tanstack/react-devtools\": \"^0.7.0\",\n \"@tanstack/react-form\": \"^1.0.0\",\n \"@tanstack/react-router\": \"^1.132.0\",\n \"@tanstack/react-router-devtools\": \"^1.132.0\",\n \"@tanstack/router-plugin\": \"^1.132.0\",\n \"react\": \"^19.2.0\",\n \"react-dom\": \"^19.2.0\",\n \"zod\": \"^4.1.11\"\n },\n \"devDependencies\": {\n \"@tanstack/devtools-vite\": \"^0.3.11\",\n \"@testing-library/dom\": \"^10.4.0\",\n \"@testing-library/react\": \"^16.2.0\",\n \"@types/react\": \"^19.2.0\",\n \"@types/react-dom\": \"^19.2.0\",\n \"@vitejs/plugin-react\": \"^5.0.4\",\n \"jsdom\": \"^27.0.0\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^7.1.7\",\n \"vitest\": \"^3.0.5\",\n \"web-vitals\": \"^5.1.0\"\n }\n}",
2323
"vite.config.js": "import { defineConfig } from 'vite'\nimport { devtools } from '@tanstack/devtools-vite'\nimport viteReact from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\nimport { fileURLToPath, URL } from 'node:url'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n devtools(),\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n viteReact(),\n ],\n resolve: {\n alias: {\n '@': fileURLToPath(new URL('./src', import.meta.url)),\n },\n },\n})\n"
2424
},
2525
"commands": [

0 commit comments

Comments
 (0)