client.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import json
  2. import requests
  3. # NOTE: ollama must be running for this to work, start the ollama app or run `ollama serve`
  4. model = 'llama2' # TODO: update this for whatever model you wish to use
  5. context = [] # the context stores a conversation history, you can use this to make the model more context aware
  6. def generate(prompt):
  7. global context
  8. r = requests.post('http://localhost:11434/api/generate',
  9. json={
  10. 'model': model,
  11. 'prompt': prompt,
  12. 'context': context,
  13. },
  14. stream=True)
  15. r.raise_for_status()
  16. for line in r.iter_lines():
  17. body = json.loads(line)
  18. response_part = body.get('response', '')
  19. # the response streams one token at a time, print that as we recieve it
  20. print(response_part, end='', flush=True)
  21. if 'error' in body:
  22. raise Exception(body['error'])
  23. if body.get('done', False):
  24. context = body['context']
  25. return
  26. def main():
  27. while True:
  28. user_input = input("Enter a prompt: ")
  29. print()
  30. generate(user_input)
  31. print()
  32. if __name__ == "__main__":
  33. main()