api-example-stream.py 2.9 KB

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