Skip to content

Commit

Permalink
📦 NEW: Next.js pipe.run() example
Browse files Browse the repository at this point in the history
  • Loading branch information
msaaddev committed Nov 16, 2024
1 parent ea34fed commit 682d4bb
Show file tree
Hide file tree
Showing 7 changed files with 232 additions and 12 deletions.
26 changes: 26 additions & 0 deletions examples/nextjs/app/langbase/pipe/run-stream/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {Pipe} from 'langbase';
import {NextRequest} from 'next/server';

export async function POST(req: NextRequest) {
const {prompt} = await req.json();

// 1. Initiate the Pipe.
const myPipe = new Pipe({
apiKey: process.env.LANGBASE_API_KEY!,
name: 'summary',
});

// 2. Generate a stream by asking a question
const {stream, threadId} = await myPipe.run({
messages: [{role: 'user', content: prompt}],
stream: true,
});

// 3. Done, return the stream in a readable stream format.
return new Response(stream, {
status: 200,
headers: {
'lb-thread-id': threadId ?? '',
},
});
}
21 changes: 21 additions & 0 deletions examples/nextjs/app/langbase/pipe/run/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {Pipe} from 'langbase';
import {NextRequest} from 'next/server';

export async function POST(req: NextRequest) {
const {prompt} = await req.json();

// 1. Initiate the Pipe.
const myPipe = new Pipe({
apiKey: process.env.LANGBASE_API_KEY!,
name: 'summary',
});

// 2. Generate a stream by asking a question
const result = await myPipe.run({
messages: [{role: 'user', content: prompt}],
stream: false,
});

// 3. Done, return the stream in a readable stream format.
return new Response(JSON.stringify(result));
}
4 changes: 4 additions & 0 deletions examples/nextjs/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import GenerateTextExample from '@/components/langbase/generate-text';
import RunNonStreamExample from '@/components/langbase/run';
import RunStreamExample from '@/components/langbase/run-stream';
import StreamTextExample from '@/components/langbase/stream-text';

export default function Home() {
Expand All @@ -13,6 +15,8 @@ export default function Home() {
An AI agent that responds to your prompts.
</p>
</div>
<RunStreamExample />
<RunNonStreamExample />
<GenerateTextExample />
<StreamTextExample />
</div>
Expand Down
10 changes: 5 additions & 5 deletions examples/nextjs/components/langbase/generate-text.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use client';

import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {useState} from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useState } from 'react';

export default function GenerateTextExample() {
const [prompt, setPrompt] = useState('');
Expand All @@ -20,7 +20,7 @@ export default function GenerateTextExample() {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({prompt}),
body: JSON.stringify({ prompt }),
});

if (!response.ok) {
Expand All @@ -41,7 +41,7 @@ export default function GenerateTextExample() {
<div className="bg-neutral-200 rounded-md p-2 flex flex-col gap-2 w-full">
<div className="flex flex-col gap-2 w-full">
<p className="text-lg font-semibold">
1. Generate Text{' '}
3. Generate Text{' '}
<a
className="text-indigo-500"
href="https://langbase.com/docs/langbase-sdk/generate-text"
Expand Down
88 changes: 88 additions & 0 deletions examples/nextjs/components/langbase/run-stream.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
'use client';

import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {getRunner} from 'langbase';
import {useState} from 'react';

export default function RunStreamExample() {
const [prompt, setPrompt] = useState('');
const [completion, setCompletion] = useState('');
const [loading, setLoading] = useState(false);

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!prompt.trim() || loading) return;

setLoading(true);
setCompletion('');

try {
const response = await fetch('/langbase/pipe/run-stream', {
method: 'POST',
body: JSON.stringify({prompt}),
headers: {'Content-Type': 'text/plain'},
});

if (response.body) {
const stream = getRunner(response.body);

// Method #1 to get all of the chunk.
for await (const chunk of stream) {
const content = chunk?.choices[0]?.delta?.content;
content && setCompletion(prev => prev + content);
}

// // Method #2 to get only the chunk's content as delta of the chunks
// stream.on('content', content => {
// setCompletion(prev => prev + content);
// });
}
} catch (error) {
setLoading(false);
console.error('Error:', error);
} finally {
setLoading(false);
}
};

return (
<div className="bg-neutral-200 rounded-md p-2 flex flex-col gap-2 w-full">
<div className="flex flex-col gap-2 w-full">
<p className="text-lg font-semibold">
1. Stream Text{' '}
<a
className="text-indigo-500"
href="https://langbase.com/docs/langbase-sdk/stream-text"
>
`pipe.run()`
</a>{' '}
with Route Handler
</p>
<p className="text-muted-foreground">
Ask a prompt to stream a text completion.
</p>
</div>
<form
onSubmit={handleSubmit}
className="flex flex-col w-full items-center gap-2"
>
<Input
type="text"
placeholder="Enter prompt message here"
onChange={e => setPrompt(e.target.value)}
value={prompt}
required
/>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'AI is thinking...' : 'Ask AI'}
</Button>
</form>
{completion && (
<p className="mt-4">
<strong>Stream:</strong> {completion}
</p>
)}
</div>
);
}
81 changes: 81 additions & 0 deletions examples/nextjs/components/langbase/run.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
'use client';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useState } from 'react';

export default function RunNonStreamExample() {
const [prompt, setPrompt] = useState('');
const [completion, setCompletion] = useState('');
const [loading, setLoading] = useState(false);

const handleSubmit = async (e: any) => {
e.preventDefault();
if (!prompt.trim()) return;

setLoading(true);
try {
const response = await fetch('/langbase/pipe/run', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ prompt }),
});

if (!response.ok) {
throw new Error('Network response was not ok');
}

const data = await response.json();
setCompletion(data.completion);
} catch (error) {
console.error('Error:', error);
setCompletion('An error occurred while generating the completion.');
} finally {
setLoading(false);
}
};

return (
<div className="bg-neutral-200 rounded-md p-2 flex flex-col gap-2 w-full">
<div className="flex flex-col gap-2 w-full">
<p className="text-lg font-semibold">
2. Generate Text{' '}
<a
className="text-indigo-500"
href="https://langbase.com/docs/langbase-sdk/generate-text"
>
`pipe.run()`
</a>{' '}
with Route Handler
</p>
<p className="text-muted-foreground">
Ask a prompt to generate a text completion.
</p>
</div>
<form
onSubmit={handleSubmit}
className="flex flex-col w-full items-center gap-2"
>
<Input
type="text"
placeholder="Enter prompt message here"
value={prompt}
onChange={e => setPrompt(e.target.value)}
required
/>

<Button type="submit" className="w-full" disabled={loading}>
{loading ? 'AI is thinking...' : 'Ask AI'}
</Button>
</form>

{!loading && completion && (
<p className="mt-4">
<strong>Generated completion:</strong> {completion}
</p>
)}
</div>
);
}
14 changes: 7 additions & 7 deletions examples/nextjs/components/langbase/stream-text.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use client';

import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {fromReadableStream} from 'langbase';
import {useState} from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { fromReadableStream } from 'langbase';
import { useState } from 'react';

export default function StreamTextExample() {
const [prompt, setPrompt] = useState('');
Expand All @@ -20,8 +20,8 @@ export default function StreamTextExample() {
try {
const response = await fetch('/langbase/pipe/stream-text', {
method: 'POST',
body: JSON.stringify({prompt}),
headers: {'Content-Type': 'text/plain'},
body: JSON.stringify({ prompt }),
headers: { 'Content-Type': 'text/plain' },
});

if (response.body) {
Expand Down Expand Up @@ -50,7 +50,7 @@ export default function StreamTextExample() {
<div className="bg-neutral-200 rounded-md p-2 flex flex-col gap-2 w-full">
<div className="flex flex-col gap-2 w-full">
<p className="text-lg font-semibold">
2. Stream Text{' '}
4. Stream Text{' '}
<a
className="text-indigo-500"
href="https://langbase.com/docs/langbase-sdk/stream-text"
Expand Down

0 comments on commit 682d4bb

Please sign in to comment.