api-example-stream.py 2.3 KB

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