Skip to content
TheChatArchiveThe Chat Archive
Mistralmistral-small-2506· Mistral AIHugging Face LMArena Human Preference 140K

Show me an example with express

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-4-maverick-17b-128e-instruct’s answer.
  1. User

    Show me an example with express

  2. Mistral Assistant

    Here's an example of using the ai-sdk package with Express to create a streaming text response using streamText.toDataStreamResponse() or a direct Response object:

    Example 1: Using streamText.toDataStreamResponse() with Express

    import express from 'express';
    import { streamText } from 'ai-sdk';
    
    const app = express();
    const port = 3000;
    
    app.get('/stream-text', async (req, res) => {
      try {
        // Generate streaming text
        const { readable, toDataStreamResponse } = await streamText({
          model: 'your-model-name', // Replace with your model
          prompt: 'Tell me a story about a brave knight.',
        });
    
        // Convert to a data stream response
        const response = toDataStreamResponse(readable);
    
        // Set headers and pipe the response
        res.setHeader('Content-Type', 'text/plain; charset=utf-8');
        response.pipe(res);
      } catch (error) {
        console.error('Error generating text:', error);
        res.status(500).send('Error generating text');
      }
    });
    
    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}`);
    });
    

    Example 2: Directly Using Response with Express

    import express from 'express';
    import { streamText } from 'ai-sdk';
    
    const app = express();
    const port = 3000;
    
    app.get('/stream-text', async (req, res) => {
      try {
        // Generate streaming text
        const { readable } = await streamText({
          model: 'your-model-name', // Replace with your model
          prompt: 'Tell me a story about a brave knight.',
        });
    
        // Create a Response object
        const response = new Response(readable, {
          headers: {
            'Content-Type': 'text/plain; charset=utf-8',
          },
        });
    
        // Pipe the response to the Express response
        response.body.pipe(res);
      } catch (error) {
        console.error('Error generating text:', error);
        res.status(500).send('Error generating text');
      }
    });
    
    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}`);
    });
    

    Example 3: Using streamText with Express and Node.js Streams

    If you want to handle the streaming more directly with Node.js streams:

    import express from 'express';
    import { streamText } from 'ai-sdk';
    
    const app = express();
    const port = 3000;
    
    app.get('/stream-text', async (req, res) => {
      try {
        // Generate streaming text
        const { readable } = await streamText({
          model: 'your-model-name', // Replace with your model
          prompt: 'Tell me a story about a brave knight.',
        });
    
        // Set headers
        res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    
        // Pipe the readable stream to the response
        readable.pipe(res);
      } catch (error) {
        console.error('Error generating text:', error);
        res.status(500).send('Error generating text');
      }
    });
    
    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}`);
    });
    

    Notes:

    1. Model Configuration: Replace 'your-model-name' with the actual model you want to use from the AI service you're connecting to.

    2. Error Handling: The examples include basic error handling. You might want to add more detailed error handling based on your application's needs.

    3. Express Version: These examples assume you're using Express 4.x or later. If you're using an older version, you might need to adjust the syntax slightly.

    4. Streaming: The examples demonstrate how to handle streaming responses. The client (e.g., a web browser or another service) will receive the text as it's generated, rather than waiting for the entire response.

    5. Dependencies: Make sure you have the required dependencies installed:

      npm install express ai-sdk
      # or
      yarn add express ai-sdk
      

    These examples should help you get started with streaming text responses using the ai-sdk package in an Express application.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.