Интеграция Google Gemini python sdk в приложение Django возвращает html, а не ожидаемый ответ, как мне успешно интегрировать Gemini sdk? [дубликат]

#views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
import google.generativeai as genai
import logging

logger = logging.getLogger(__name__)


genai.configure(api_key='mykey')  

@csrf_exempt
@require_POST
def get_gemini_response(request):
    try:
        company_name = request.POST.get('company_Name')
        
        if not company_name:
            return JsonResponse({'error': 'Missing company name'}, status=400)

        # Formulate the prompt for Gemini AI
        prompt = f"Provide insights and analysis about the company '{company_name}', focusing on its financial health, market position, recent news, and potential future trends."

        # Use the Gemini Pro model
        model = genai.GenerativeModel(model="models/gemini-pro") 
        response = model.generate_text(
            prompt=prompt,
            temperature=0.7,
            max_output_tokens=512
        )

        # Extract the generated text from the response
        generated_text = response.result['candidates'][0]['content']['parts'][0]['text']

        # Return the generated text wrapped in HTML
        return JsonResponse({'response': generated_text})  

    except genai.GenerativeAIError as e:
        logger.error(f"Gemini API Error: {e}")
        return JsonResponse({'error': f"Gemini API Error: {e.message}"}, status=500)
    except Exception as e:
        logger.exception(f"Error processing request: {e}")
        return JsonResponse({'error': 'Internal server error'}, status=500)



#company_filing.html
   <div class="row justify-content-center">
                    <button class="btn btn-md col" data-toggle="modal" data-target="#aiInsights">AI Insights</button>
   </div>
<script>
    $(document).ready(function() {
        $('#aiInsights').on('show.bs.modal', function (event) {
            var companyName = "{{ company_name | safe }}";
            var csrftoken = $('input[name="csrfmiddlewaretoken"]').val();
    
            // Show loading spinner
            $('#geminiResponseContainer').html('<div class="text-center"><span class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></span></div>');
            
            // Logging the data sent in the AJAX request
            console.log('Preparing AJAX request with data:', {
                company_Name: companyName,
                csrfmiddlewaretoken: csrftoken
            });
    
            $.ajax({
                url: '/get_gemini_response/',
                type: 'POST',
                data: {
                    'company_Name': companyName,
                    'csrfmiddlewaretoken': csrftoken
                },
                success: function(data) {
                    console.log('AJAX request successful. Data received:', data);
                    if (data.error) {
                        $('#geminiResponseContainer').html(`<div class='alert alert-danger'>Error: ${data.error}</div>`);
                    } else {
                        $('#geminiResponseContainer').html(data.response);
                    }
                },
            
                error: function(xhr, status, error) {
                    console.error("AJAX Error:", error); // More detailed error logging
                    console.error("Detailed response:", xhr.responseText); // Log detailed response text for debugging
                    $('#geminiResponseContainer').html(`<div class='alert alert-danger'>AJAX Error: ${error}</div>`);
                }
            });
        });
    });
</script>
#modals.html (response is suppose to appear here after clicking 'Ai Insights button')

<!-- Modal Definition -->
<div aria-hidden="true" aria-labelledby="aiInsightsLabel" class="modal fade" id="aiInsights" role="dialog" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="aiInsightsModalTitle">
                    <!-- Dynamic title based on the context from AJAX or initial loading -->
                    <!-- This will be set dynamically by JavaScript if needed -->
                    AI Insights
                </h5>
                <button aria-label="Close" class="close" data-dismiss="modal" type="button">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Placeholder for AJAX content, initially empty -->
                <div id="geminiResponseContainer" class="text-center">
                    <!-- Content will be injected here by AJAX -->
                    <span class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></span>
                </div>
            </div>
        </div>
    </div>
</div>

Вместо этого мне возвращается файл base.html :


AJAX request successful. Data received: <!-- base.html -->


<head>
    <!-- Meta Pixel Code -->
    <script>
        !function(f,b,e,v,n,t,s)
        {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
        n.callMethod.apply(n,arguments):n.queue.push(arguments)};
        if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
        n.queue=[];t=b.createElement(e);t.async=!0;
        t.src=v;s=b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t,s)}(window,document,'script',
        'https://connect.facebook.net/en_US/fbevents.js');
         fbq('init', '837864435011709');
        fbq('track', 'PageView');
    </script>
    <noscript>
         <img height="1" width="1"
        src="https://www.facebook.com/tr?id=837864435011709&ev=PageView
        &noscript=1"/>
    </noscript>
    <!-- End Meta Pi

views.py обрабатывает запрос от js файла company_filings.html. js регистрирует правильный csrf, и мы получаем ответ 200 ok. Вот лог данных, используемых для запроса к views.py Preparing AJAX request with data: {company_Name: 'AbbVie Inc.', csrfmiddlewaretoken: 'G0oQmplzRNpWQJXgnANn3lSmJWgiSlQ9a18H7usDtb3mpXm7vhFIDHSvmhgV8JRr'}

Я пытался вернуть HttResponse в представлении django, что также не сработало. Я уверен, что правильно обрабатываю ответ, основываясь на документации gemini. Мне нужен правильный ответ от запроса.

Вернуться на верх