我正在使用EventSource在浏览器中获取流式文本内容。问题是,当我想要一个链接出现,即使我有正确的文本,链接不呈现。
这是输出的文本(正确)
Here are a few options for single burner camping stoves that you might find suitable:1. The <a href='https://www.bcf.com.au/p/companion-lpg-portable-single-burner-gas-stove/292578.html?cgid=BCF08188'>Companion LPG Portable Single Burner Gas Stove</a> is a great option. It's portable and uses LPG, which is a common fuel type for camping stoves. This makes it a practical choice for camping trips.2. Another good choice is the <a href='https://www.tentworld.com.au/buy-sale/companion-1-burner-wok-cooker-stove'>Companion 1 Burner Wok Cooker Stove</a>. This stove is also portable and has a wok cooker, which adds versatility to your cooking options.For more options, you can check out the range of <a href='https://www.anacondastores.com/camping-hiking/camp-cooking/camping-stoves?q=:relevance:brand:coleman:dealType:OnSale:dealType:CLUB%20PRICE'>Camping Stoves</a> at Anaconda stores. They offer a variety of brands and styles, so you might find other single burner stoves that suit your needs.
下面是html/js:
<div id="response-display"></div>
<script>
const responseDisplay = document.getElementById('response-display');
const eventSource = new EventSource('http://127.0.0.1:8000/do-chat');
eventSource.onmessage = function(event) {
console.log('We have a message');
console.log(event.data);
// Append received data to the div
// responseDisplay.textContent += event.data + "\n";
responseDisplay.innerHTML += event.data;
};
eventSource.onerror = function(error) {
console.error('EventSource failed:', error);
eventSource.close();
};
</script>
这是Python/Django代码:
def get_gpt4_streaming_response(self, prompt):
model_engine = self.MODEL_NAME
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model_engine,
messages=messages,
temperature=0.5,
max_tokens=1000, # You can set this to be as long or short as you'd like
stream=True
)
for chunk in response:
print(chunk)
yield f"data: {chunk['choices'][0]['delta']['content']}\n\n"
if chunk['choices'][0]['finish_reason'] == 'stop':
break
2条答案
按热度按时间uyhoqukh1#
尝试以下修改:
r7s23pms2#
当您设置元素的innerHTML时,它默认将内容视为纯文本,而不是HTML。因此,接收到的数据中的HTML标记显示为文本,而链接不呈现为实际链接。
要正确呈现链接,您应该使用insertAdjacentHTML方法,而不是直接设置innerHTML。你能检查一下这是否对你有用吗?
编辑1:
清理HTML:使用像DOMPurify这样的库来清理接收到的HTML,以删除任何潜在的恶意或有害内容。*DOMPurify旨在清理不受信任的HTML,并使其在浏览器中安全呈现。
首先,在HTML中包含DOMPurify:
然后,修改您的JavaScript代码以清理和呈现HTML:
这种方法可以确保HTML内容在浏览器中呈现之前经过清理,以删除任何潜在的有害元素或脚本。
另外,检查您是否可以实现
Content Security Policy (CSP)
。它允许您定义允许在您的页面上执行哪些内容源,这可以帮助减轻XSS攻击的风险。