Created
February 2, 2025 21:54
-
-
Save yusukebe/ff02d993cc5ebcbc855f220ffbc61d34 to your computer and use it in GitHub Desktop.
streaming-deepseek.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Hono } from 'hono' | |
import { streamText } from 'hono/streaming' | |
type Env = { | |
Bindings: { | |
AI: Ai | |
} | |
} | |
const app = new Hono<Env>() | |
app.get('/', async (c) => { | |
const message = c.req.query('message') ?? 'Say hello!' | |
const messages = [ | |
{ role: 'system', content: 'You are a friendly assistant' }, | |
{ | |
role: 'user', | |
content: message | |
} | |
] | |
const result = (await c.env.AI.run('@cf/deepseek-ai/deepseek-r1-distill-qwen-32b', { | |
messages, | |
stream: true | |
})) as ReadableStream | |
return streamText(c, async (writer) => { | |
await writer.write('🤔') | |
let thinking = true | |
for await (const chunk of result.pipeThrough(new TextDecoderStream()).values()) { | |
for (const line of chunk.split('\n')) { | |
const jsonString = line.replace('data: ', '') | |
try { | |
const jsonData = JSON.parse(jsonString) | |
if (jsonData.response.trim() === '</think>') { | |
thinking = false | |
await writer.write('💡') | |
} else { | |
thinking ? await writer.write('.') : await writer.write(jsonData.response) | |
} | |
} catch {} | |
} | |
} | |
}) | |
}) | |
export default app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment