api-example-stream.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. # Note, Gradio may pick a different fn value as the definition of the Gradio app changes.
  11. # You can always launch the web UI and inspect the websocket stream using your browser's dev tools
  12. # to determine what value Gradio expects here.
  13. GRADIO_FN = 29
  14. def random_hash():
  15. letters = string.ascii_lowercase + string.digits
  16. return ''.join(random.choice(letters) for i in range(9))
  17. async def run(context):
  18. server = "127.0.0.1"
  19. params = {
  20. 'max_new_tokens': 200,
  21. 'do_sample': True,
  22. 'temperature': 0.5,
  23. 'top_p': 0.9,
  24. 'typical_p': 1,
  25. 'repetition_penalty': 1.05,
  26. 'encoder_repetition_penalty': 1.0,
  27. 'top_k': 0,
  28. 'min_length': 0,
  29. 'no_repeat_ngram_size': 0,
  30. 'num_beams': 1,
  31. 'penalty_alpha': 0,
  32. 'length_penalty': 1,
  33. 'early_stopping': False,
  34. 'seed': -1,
  35. 'add_bos_token': True,
  36. 'truncation_length': 2048,
  37. 'custom_stopping_strings': [],
  38. 'ban_eos_token': False
  39. }
  40. payload = json.dumps([context, params])
  41. session = random_hash()
  42. async with websockets.connect(f"ws://{server}:7860/queue/join") as websocket:
  43. while content := json.loads(await websocket.recv()):
  44. # Python3.10 syntax, replace with if elif on older
  45. match content["msg"]:
  46. case "send_hash":
  47. await websocket.send(json.dumps({
  48. "session_hash": session,
  49. "fn_index": GRADIO_FN
  50. }))
  51. case "estimation":
  52. pass
  53. case "send_data":
  54. await websocket.send(json.dumps({
  55. "session_hash": session,
  56. "fn_index": GRADIO_FN,
  57. "data": [
  58. payload
  59. ]
  60. }))
  61. case "process_starts":
  62. pass
  63. case "process_generating" | "process_completed":
  64. yield content["output"]["data"][0]
  65. # You can search for your desired end indicator and
  66. # stop generation by closing the websocket here
  67. if (content["msg"] == "process_completed"):
  68. break
  69. prompt = "What I would like to say is the following: "
  70. async def get_result():
  71. async for response in run(prompt):
  72. # Print intermediate steps
  73. print(response)
  74. # Print final result
  75. print(response)
  76. asyncio.run(get_result())