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.
do a search to figure out the used price of <{message}> give back 5cheapest results you find
if {message} is audio related then you can also search on https://www.hifishark.com/ if not then ignore this step
I'm only intrested in used products so don't give me the retail price.
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
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)
code
# 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
Assistant
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';
The code snippet provided seems to incorporate both FastAPI and Next.js APIs. For streaming responses with Next.js, you would typically implement using Server-Sent Events (SSE). Here, I've adapted your existing handler function to include stream as part of the query parameters.
Below is an adapted version of the Next.js handler function for handling streaming responses. In this scenario, the client can request a streaming response by including stream=true in the request. When stream is true, the server will keep the connection open and write updates as Server-Sent Events (SSE).
javascript
// Import necessary modules from Next.js and other libraries
import { NextApiRequest, NextApiResponse } from 'next'
import assert from 'assert'
import NextCors from 'nextjs-cors';
// Additional imports and server setup omitted for brevity
// Your original API interfaces remain the same
export interface APIRequest {
// ... your existing code
}
export interface APIResponse {
// ... your existing code
}
// Utility functions and configurations omitted for brevity
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// Handle CORS and abort signal setup
// ... your existing code
// Extract 'stream' from query parameters (defaults to false if not provided)
const stream = req.query.stream === 'true';
const { prompt, model, context } = parseOpenAIMessage(req.body);
let lastLength = 0
let lastText = ''
try {
const chatbot = new BingWebBot({
// ... your existing code
});
if (stream) {
// Set headers for SSE
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
res.flushHeaders();
}
assert(prompt, 'messages can\'t be empty!')
const toneType = model as BingConversationStyle
await chatbot.sendMessage({
prompt,
context,
options: {
// ... your existing code
},
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.error('Catch Error:', error)
if (stream) {
res.write(`data: ${JSON.stringify(responseOpenAIMessage(`Error: ${error}`))}\n\n`)
} else {
res.status(500).json({ error: error.message });
}
} finally {
if (stream) {
res.end(`event: done\ndata: null\n\n`);
} else {
res.status(200).json(responseOpenAIMessage(lastText))
}
}
}
In this adaptation:
The stream variable is read from the query parameters to determine if a streaming response is required.
The respective headers are set up for SSE when streaming is true.
The res.write() is used to send data chunks to the client whenever there is an update from the chatbot.
The connection is kept open until the chatbot finished sending all responses or an error is encountered.
Upon completion, a done event is sent to indicate the end of the stream.
Remember to handle the client-side accordingly to establish an EventSource connection to this endpoint when you want to use the streaming functionality.