api-example-stream.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import string
  2. import random
  3. import websockets
  4. import json
  5. import asyncio
  6. def random_hash():
  7. letters = string.ascii_lowercase + string.digits
  8. return ''.join(random.choice(letters) for i in range(9))
  9. async def run(context):
  10. server = "127.0.0.1"
  11. params = {
  12. 'max_new_tokens': 200,
  13. 'do_sample': True,
  14. 'temperature': 0.5,
  15. 'top_p': 0.9,
  16. 'typical_p': 1,
  17. 'repetition_penalty': 1.05,
  18. 'top_k': 0,
  19. 'min_length': 0,
  20. 'no_repeat_ngram_size': 0,
  21. 'num_beams': 1,
  22. 'penalty_alpha': 0,
  23. 'length_penalty': 1,
  24. 'early_stopping': False,
  25. }
  26. session = random_hash()
  27. async with websockets.connect(f"ws://{server}:7860/queue/join") as websocket:
  28. while content := json.loads(await websocket.recv()):
  29. #Python3.10 syntax, replace with if elif on older
  30. match content["msg"]:
  31. case "send_hash":
  32. await websocket.send(json.dumps({
  33. "session_hash": session,
  34. "fn_index": 7
  35. }))
  36. case "estimation":
  37. pass
  38. case "send_data":
  39. await websocket.send(json.dumps({
  40. "session_hash": session,
  41. "fn_index": 7,
  42. "data": [
  43. context,
  44. params['max_new_tokens'],
  45. params['do_sample'],
  46. params['temperature'],
  47. params['top_p'],
  48. params['typical_p'],
  49. params['repetition_penalty'],
  50. params['top_k'],
  51. params['min_length'],
  52. params['no_repeat_ngram_size'],
  53. params['num_beams'],
  54. params['penalty_alpha'],
  55. params['length_penalty'],
  56. params['early_stopping'],
  57. ]
  58. }))
  59. case "process_starts":
  60. pass
  61. case "process_generating" | "process_completed":
  62. yield content["output"]["data"][0]
  63. # You can search for your desired end indicator and
  64. # stop generation by closing the websocket here
  65. if (content["msg"] == "process_completed"):
  66. break
  67. prompt = "What I would like to say is the following: "
  68. async def get_result():
  69. async for response in run(prompt):
  70. # Print intermediate steps
  71. print(response)
  72. # Print final result
  73. print(response)
  74. asyncio.run(get_result())