53 lines
2.3 KiB
Python
53 lines
2.3 KiB
Python
|
from django.shortcuts import render
|
||
|
from django.http import JsonResponse
|
||
|
import requests
|
||
|
import json
|
||
|
|
||
|
def index(request):
|
||
|
return render(request, 'chat/index.html')
|
||
|
|
||
|
def send_message(request):
|
||
|
if request.method == 'POST':
|
||
|
user_message = request.POST.get('message')
|
||
|
|
||
|
api_url = 'http://192.168.1.36:11434/api/generate' # Updated URL with the correct port
|
||
|
headers = {
|
||
|
'Authorization': 'Bearer your_api_key_here', # Include your API key if needed
|
||
|
'Content-Type': 'application/json'
|
||
|
}
|
||
|
payload = {
|
||
|
'prompt': user_message,
|
||
|
'model': 'mistral:latest' # Include the model
|
||
|
}
|
||
|
|
||
|
try:
|
||
|
response = requests.post(api_url, json=payload, headers=headers)
|
||
|
response.raise_for_status() # This will raise an HTTPError for bad responses
|
||
|
print(f'Response Content: {response.content}')
|
||
|
|
||
|
# Handle the response correctly by splitting lines and parsing each JSON object
|
||
|
response_lines = response.content.decode('utf-8').splitlines()
|
||
|
combined_response = ""
|
||
|
for line in response_lines:
|
||
|
json_obj = json.loads(line)
|
||
|
if 'response' in json_obj:
|
||
|
combined_response += json_obj['response'] + " "
|
||
|
if json_obj.get('done', False):
|
||
|
break
|
||
|
|
||
|
return JsonResponse({'response': combined_response.strip()})
|
||
|
except requests.exceptions.HTTPError as errh:
|
||
|
print(f'HTTP Error: {errh}')
|
||
|
print(f'Response Content: {response.content}')
|
||
|
return JsonResponse({'error': f'HTTP Error: {errh}', 'details': response.content.decode('utf-8')}, status=400)
|
||
|
except requests.exceptions.ConnectionError as errc:
|
||
|
print(f'Error Connecting: {errc}')
|
||
|
return JsonResponse({'error': f'Error Connecting: {errc}'}, status=500)
|
||
|
except requests.exceptions.Timeout as errt:
|
||
|
print(f'Timeout Error: {errt}')
|
||
|
return JsonResponse({'error': f'Timeout Error: {errt}'}, status=500)
|
||
|
except requests.exceptions.RequestException as err:
|
||
|
print(f'Request Error: {err}')
|
||
|
print(f'Response Content: {response.content}')
|
||
|
return JsonResponse({'error': f'Request Error: {err}', 'details': response.content.decode('utf-8')}, status=500)
|