api-example-stream.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. 'seed': -1,
  31. }
  32. session = random_hash()
  33. async with websockets.connect(f"ws://{server}:7860/queue/join") as websocket:
  34. while content := json.loads(await websocket.recv()):
  35. #Python3.10 syntax, replace with if elif on older
  36. match content["msg"]:
  37. case "send_hash":
  38. await websocket.send(json.dumps({
  39. "session_hash": session,
  40. "fn_index": 12
  41. }))
  42. case "estimation":
  43. pass
  44. case "send_data":
  45. await websocket.send(json.dumps({
  46. "session_hash": session,
  47. "fn_index": 12,
  48. "data": [
  49. context,
  50. params['max_new_tokens'],
  51. params['do_sample'],
  52. params['temperature'],
  53. params['top_p'],
  54. params['typical_p'],
  55. params['repetition_penalty'],
  56. params['encoder_repetition_penalty'],
  57. params['top_k'],
  58. params['min_length'],
  59. params['no_repeat_ngram_size'],
  60. params['num_beams'],
  61. params['penalty_alpha'],
  62. params['length_penalty'],
  63. params['early_stopping'],
  64. params['seed'],
  65. ]
  66. }))
  67. case "process_starts":
  68. pass
  69. case "process_generating" | "process_completed":
  70. yield content["output"]["data"][0]
  71. # You can search for your desired end indicator and
  72. # stop generation by closing the websocket here
  73. if (content["msg"] == "process_completed"):
  74. break
  75. prompt = "What I would like to say is the following: "
  76. async def get_result():
  77. async for response in run(prompt):
  78. # Print intermediate steps
  79. print(response)
  80. # Print final result
  81. print(response)
  82. asyncio.run(get_result())