|
| 1 | +--- |
| 2 | +title: LangChainAdapter |
| 3 | +description: API Reference for LangChainAdapter. |
| 4 | +--- |
| 5 | + |
| 6 | +# `LangChainAdapter` |
| 7 | + |
| 8 | +The `LangChainAdapter` module provides a way to transform LangChain output streams into AI streams. |
| 9 | +See the [LangChain Adapter documentation](/providers/adapters/langchain) for more information. |
| 10 | + |
| 11 | +## Import |
| 12 | + |
| 13 | +<Snippet text={`import { LangChainAdapter } from "ai"`} prompt={false} /> |
| 14 | + |
| 15 | +## API Signature |
| 16 | + |
| 17 | +### Methods |
| 18 | + |
| 19 | +<PropertiesTable |
| 20 | + content={[ |
| 21 | + { |
| 22 | + name: 'toAIStream', |
| 23 | + type: '(stream: ReadableStream<LangChainAIMessageChunk> | ReadableStream<string>, AIStreamCallbacksAndOptions) => AIStream', |
| 24 | + description: 'Converts LangChain output streams to AIStream.', |
| 25 | + }, |
| 26 | + ]} |
| 27 | +/> |
| 28 | + |
| 29 | +## Examples |
| 30 | + |
| 31 | +### Convert LangChain Expression Language Stream |
| 32 | + |
| 33 | +```tsx filename="app/api/completion/route.ts" highlight={"14"} |
| 34 | +import { ChatOpenAI } from '@langchain/openai'; |
| 35 | +import { LangChainAdapter, StreamingTextResponse } from 'ai'; |
| 36 | + |
| 37 | +export async function POST(req: Request) { |
| 38 | + const { prompt } = await req.json(); |
| 39 | + |
| 40 | + const model = new ChatOpenAI({ |
| 41 | + model: 'gpt-3.5-turbo-0125', |
| 42 | + temperature: 0, |
| 43 | + }); |
| 44 | + |
| 45 | + const stream = await model.stream(prompt); |
| 46 | + |
| 47 | + const aiStream = LangChainAdapter.toAIStream(stream); |
| 48 | + |
| 49 | + return new StreamingTextResponse(aiStream); |
| 50 | +} |
| 51 | +``` |
| 52 | + |
| 53 | +### Convert StringOutputParser Stream |
| 54 | + |
| 55 | +```tsx filename="app/api/completion/route.ts" highlight={"16"} |
| 56 | +import { ChatOpenAI } from '@langchain/openai'; |
| 57 | +import { LangChainAdapter, StreamingTextResponse } from 'ai'; |
| 58 | +import { StringOutputParser } from '@langchain/core/output_parsers'; |
| 59 | + |
| 60 | +export async function POST(req: Request) { |
| 61 | + const { prompt } = await req.json(); |
| 62 | + |
| 63 | + const model = new ChatOpenAI({ |
| 64 | + model: 'gpt-3.5-turbo-0125', |
| 65 | + temperature: 0, |
| 66 | + }); |
| 67 | + |
| 68 | + const parser = new StringOutputParser(); |
| 69 | + const stream = await model.pipe(parser).stream(prompt); |
| 70 | + |
| 71 | + const aiStream = LangChainAdapter.toAIStream(stream); |
| 72 | + |
| 73 | + return new StreamingTextResponse(aiStream); |
| 74 | +} |
| 75 | +``` |
0 commit comments