turn this into a streaming post instead of a post:

@app.post("/search1")
async def predict(request: Request, user: str = Depends(get_current_user)):
    body = await request.body()
    create = requests.post("https://bing.github1s.tk/api/create")
    data = json.loads(create.text)
    message = body.decode()  # convert bytes to string
    # logger.info(message)  # Add this line
    message = f"""I need you to find the used price of a {message}, you will respond with the most relateable item and the price and if you find different prices in Sweden and international price.

1. do a search to figure out the used price of <{message}> give back 5cheapest results you find
2. if {message} is audio related then you can also search on https://www.hifishark.com/ if not then ignore this step
3. I'm only intrested in used products so don't give me the retail price.
4. Always try to find the price relevated to the Swedish market (tradera/blocket/facebook) first hand and only go international if you can't find for swedish market
5. Describe what {message} to look for on this particular item to see if it's worth more or less.

answer in swedish"""
    header = {"Content-Type": "application/json"}
    request_message = {
        "conversationId": data["conversationId"],
        "encryptedconversationsignature": data["encryptedconversationsignature"],
        "clientId": data["clientId"],
        "invocationId": 0,
        "conversationStyle": "Balanced",
        "prompt": message,
        "allowSearch": True,
        "context": "",
    }
    # Serialize the dictionary to a JSON-formatted string
    request_message_json = json.dumps(request_message)

    # Print the serialized request message
    print(request_message_json)

    # Make the POST request to the specified URL
    responded = requests.post(
        "https://bing.github1s.tk/api/sydney", data=request_message_json, headers=header
    )

    # Check if the response has JSON content
    json_objects = responded.text.split("▲")
    json_objects = json_objects[0].split("\x1e")
    print(json_objects)
    texts = []
    for obj in json_objects:
        if obj:
            # Parse the JSON string
            json_data = json.loads(obj)
            print(json_data)
            if "arguments" in json_data and "messages" in json_data["arguments"][0]:
                for message in json_data["arguments"][0]["messages"]:
                    texts = message["text"]

    # texts should now contain all extracted text fields from each message
    print(texts)
    return texts




import { NextApiRequest, NextApiResponse } from 'next'
import assert from 'assert'
import NextCors from 'nextjs-cors';
import { BingWebBot } from '@/lib/bots/bing'
import { BingConversationStyle, APIMessage, Action } from '@/lib/bots/bing/types'
import { messageToContext } from '@/lib/utils';

export const config = {
  api: {
    responseLimit: false,
  },
}

export interface APIRequest {
  model: string
  action: Action
  messages: APIMessage[]
  stream?: boolean
}

export interface APIResponse {
  choices: {
    delta?: APIMessage
    message: APIMessage
  }[]
}

function parseOpenAIMessage(request: APIRequest) {
  const messages = request.messages.slice(0)
  const prompt = messages.pop()?.content
  const context = messageToContext(messages)
  return {
    prompt,
    context,
    stream: request.stream,
    allowSearch: /gpt-?4/i.test(request.model),
    model: /Creative|gpt-?4/i.test(request.model) ? 'Creative' : 'Balanced',
  };
}

function responseOpenAIMessage(content: string): APIResponse {
  const message: APIMessage = {
    role: 'assistant',
    content,
  };
  return {
    choices: [{
      delta: message,
      message,
    }],
  };
}

function getOriginFromHost(host: string) {
  const uri = new URL(`http://${host}`)
  if (uri.protocol === 'http:' && !/^[0-9.:]+$/.test(host)) {
    uri.protocol = 'https:';
  }
  return uri.toString().slice(0, -1)
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'GET') return res.status(200).end('ok')
  await NextCors(req, res, {
    // Options
    methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
    origin: '*',
    optionsSuccessStatus: 200,
  })
  const abortController = new AbortController()

  req.socket.once('close', () => {
    abortController.abort()
  })
  const { prompt, stream, model, context } = parseOpenAIMessage(req.body);
  let lastLength = 0
  let lastText = ''
  try {
    const chatbot = new BingWebBot({
      endpoint: getOriginFromHost(req.headers.host || '127.0.0.1:3000'),
    })

    if (stream) {
      res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
    }

    assert(prompt, 'messages can\'t be empty!')

    const toneType = model as BingConversationStyle

    await chatbot.sendMessage({
      prompt,
      context,
      options: {
        bingConversationStyle: Object.values(BingConversationStyle)
          .includes(toneType) ? toneType : BingConversationStyle.Creative,
      },
      signal: abortController.signal,
      onEvent(event) {
        if (event.type === 'UPDATE_ANSWER') {
          lastText = event.data.text
          if (stream && lastLength !== lastText.length) {
            res.write(`data: ${JSON.stringify(responseOpenAIMessage(lastText.slice(lastLength)))}\n\n`)
            lastLength = lastText.length
          }
        }
      },
    })
  } catch (error) {
    console.log('Catch Error:', error)
    res.write(`data: ${JSON.stringify(responseOpenAIMessage(`${error}`))}\n\n`)
  } finally {
    if (stream) {
      res.end(`data: [DONE]\n\n`);
    } else {
      res.end(JSON.stringify(responseOpenAIMessage(lastText)))
    }
  }
}