Created
October 10, 2024 03:29
-
-
Save bsharper/c41ac3a0debec01b62ac7a1917de8838 to your computer and use it in GitHub Desktop.
Ollama API example using requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
def ollama_generate(host="localhost", model="phi3", prompt="Why is the sky blue?", verbose=False): | |
url = f"http://{host}:11434/api/generate" | |
data = {"model": model, "prompt": prompt} | |
headers = {'Content-Type': 'application/json'} | |
response = requests.post(url, json=data, headers=headers, stream=True) | |
if response.status_code == 200: | |
final_response = "" | |
for line in response.iter_lines(): | |
if line: | |
json_response = json.loads(line.decode('utf-8')) | |
final_response += json_response['response'] | |
if verbose: | |
print(json_response['response'], end='', flush=True) | |
if json_response['done']: | |
if verbose: | |
print("") | |
break | |
return final_response.strip() | |
else: | |
print(f"Failed to fetch data. Status code: {response.status_code}") | |
return "" | |
if __name__ == "__main__": | |
# Example usage | |
ollama_generate(host='localhost', model='phi3', prompt='Why is the sky blue?', verbose=True) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment