api-example-stream.py 3.0 KB

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