api-example-stream.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 = 8
  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. }
  36. payload = json.dumps([context, params])
  37. session = random_hash()
  38. async with websockets.connect(f"ws://{server}:7860/queue/join") as websocket:
  39. while content := json.loads(await websocket.recv()):
  40. # Python3.10 syntax, replace with if elif on older
  41. match content["msg"]:
  42. case "send_hash":
  43. await websocket.send(json.dumps({
  44. "session_hash": session,
  45. "fn_index": GRADIO_FN
  46. }))
  47. case "estimation":
  48. pass
  49. case "send_data":
  50. await websocket.send(json.dumps({
  51. "session_hash": session,
  52. "fn_index": GRADIO_FN,
  53. "data": [
  54. payload
  55. ]
  56. }))
  57. case "process_starts":
  58. pass
  59. case "process_generating" | "process_completed":
  60. yield content["output"]["data"][0]
  61. # You can search for your desired end indicator and
  62. # stop generation by closing the websocket here
  63. if (content["msg"] == "process_completed"):
  64. break
  65. prompt = "What I would like to say is the following: "
  66. async def get_result():
  67. async for response in run(prompt):
  68. # Print intermediate steps
  69. print(response)
  70. # Print final result
  71. print(response)
  72. asyncio.run(get_result())