Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

multi-adapter-example.ts

93 lines2.4 KB

1import { AI } from "../packages/ai/src";
2import { OpenAIAdapter } from "../packages/ai-openai/src";
3import { AnthropicAdapter } from "../packages/ai-anthropic/src";
4
5// Create AI instance with multiple adapters
6const ai = new AI({
7 adapters: {
8 "open-ai": new OpenAIAdapter({
9 apiKey: process.env.OPENAI_API_KEY || "",
10 }),
11 anthropic: new AnthropicAdapter({
12 apiKey: process.env.ANTHROPIC_API_KEY || "",
13 }),
14 },
15});
17// Example 1: Chat with OpenAI (typesafe - autocomplete works!)
18async function chatWithOpenAI() {
19 const response = await ai.chat({
20 adapter: "open-ai", // TypeScript knows these are the available adapters
21 model: "gpt-4",
22 messages: [
23 {
24 role: "user",
25 content: "What is the capital of France?",
26 },
27 ],
28 });
30 console.log("OpenAI Response:", response.content);
31}
33// Example 2: Chat with Anthropic (typesafe - autocomplete works!)
34async function chatWithAnthropic() {
35 const response = await ai.chat({
36 adapter: "anthropic", // TypeScript knows these are the available adapters
37 model: "claude-3-5-sonnet-20241022",
38 messages: [
39 {
40 role: "user",
41 content: "What is the capital of Germany?",
42 },
43 ],
44 });
46 console.log("Anthropic Response:", response.content);
47}
49// Example 3: Stream chat
50async function streamChatExample() {
51 console.log("\nStreaming from OpenAI:");
52 for await (const chunk of ai.streamChat({
53 adapter: "open-ai",
54 model: "gpt-4",
55 messages: [
56 {
57 role: "user",
58 content: "Count from 1 to 5",
59 },
60 ],
61 })) {
62 if (chunk.type === "content") {
63 process.stdout.write(chunk.delta);
64 }
65 }
66 console.log("\n");
67}
69// Example 4: Get adapter names
70function showAdapters() {
71 console.log("Available adapters:", ai.adapterNames);
72}
74// Example 5: Add a new adapter dynamically (returns a new AI instance with updated types)
75function addNewAdapter() {
76 const aiWithGemini = ai.addAdapter(
77 "gemini",
78 new OpenAIAdapter({ apiKey: "fake-key" }) // Using OpenAI as placeholder
79 );
81 // Now "gemini" is available in the types!
82 // aiWithGemini.chat({ adapter: "gemini", ... })
83}
85// Run examples
86async function main() {
87 showAdapters();
88 await chatWithOpenAI();
89 await chatWithAnthropic();
90 await streamChatExample();
91}
93main().catch(console.error);