JeVoisBase  1.22
JeVois Smart Embedded Machine Vision Toolkit Base Modules
Share this page:
Loading...
Searching...
No Matches
test-ollama-works.py
Go to the documentation of this file.
1import asyncio
2import ollama
3from typing import *
4
5T = TypeVar('T')
6
7#https://stackoverflow.com/questions/50241696/how-to-iterate-over-an-asynchronous-iterator-with-a-timeout
8
9# async generator, needs python 3.6
10async def timeout(it: AsyncIterator[T], timeo: float, sentinel: T) -> AsyncGenerator[T, None]:
11 try:
12 nxt = asyncio.ensure_future(it.__anext__())
13 while True:
14 try:
15 yield await asyncio.wait_for(asyncio.shield(nxt), timeo)
16 nxt = asyncio.ensure_future(it.__anext__())
17 except asyncio.TimeoutError:
18 yield sentinel
19 except StopAsyncIteration:
20 pass
21 finally:
22 nxt.cancel() # in case we're getting cancelled our self
23
24async def something():
25 yield 1
26 await asyncio.sleep(1.1)
27 yield 2
28 await asyncio.sleep(2.1)
29 yield 3
30
31
32async def test():
33 expect = [1, None, 2, None, None, 3]
34 async for item in timeout(something(), 1, None):
35 print("Check", item)
36 assert item == expect.pop(0)
37
38async def main():
39 client = ollama.AsyncClient()
40 messages = []
41
42 while True:
43 if content_in := input('>>> '):
44 messages.append({'role': 'user', 'content': content_in})
45 content_out = ''
46 message = {'role': 'assistant', 'content': ''}
47 respaiter = await client.chat(model='tinydolphin', messages=messages, stream=True)
48 print("type is {}".format(type(respaiter)))
49 zob = timeout(respaiter, 0.01, None)
50 print("zob type is {}".format(type(zob)))
51
52 keepgoing = True
53 while keepgoing:
54 response = await anext(zob)
55 if response is not None:
56 if response['done']:
57 messages.append(message)
58 keepgoing = False
59 content = response['message']['content']
60 print(content, end='', flush=True)
61 message['content'] += content
62 else:
63 print("[timout]")
64 print()
65
66
67#asyncio.get_event_loop().run_until_complete(test())
68
69try:
70 asyncio.run(main())
71except (KeyboardInterrupt, EOFError):
72 ...
AsyncGenerator[T, None] timeout(AsyncIterator[T] it, float timeo, T sentinel)