Wednesday 12 April 2023

Using chatGPT with Python

 



Now days ChatGPT is hot cake that everyone want to test it, Its rely a great to ask any type of question. Most of time it gives me better and faster answer than Google.  I tried using UI available in market but its not stable. Finally I have started using my favorite python code to call openai and ask questions.

I am calling chatGPT  in my python code, here is basic code snippet.

Lets create a function first, before that you might need to generate a key openai.api_key. 

# -*- coding: utf-8 -*-

"""

Created on Fri Mar 24 13:17:57 2023


@author: p.vikas

"""


import openai

# import speech_recognition as sr


def call_chatGPT(ask  =" "):

# Define OpenAI API key 

    openai.api_key = "<key>"

    

    # Set up the model and prompt

    model_engine = "text-davinci-003"

    prompt = ask


    completion = openai.Completion.create(

        engine=model_engine,

        prompt=prompt,

        max_tokens=1024,

        n=1,

        stop=None,

        temperature=0.5,

    )

  

    response = completion.choices[0].text

    return response

--------------------------

Now call that function

 # -*- coding: utf-8 -*-

"""

Created on Fri Feb 10 16:55:12 2023

@author: p.vikas

"""


from  functions import call_chatGPT,voice_to_text

import subprocess



voice_file_path="recording.wav" 

# Ask a question 

print("Please ask a question")

# subprocess.call(["C:\\Program Files\\MyApp\\MyApp.exe"])

# question = input("Please ask a question..")

question=f"""how to Develop Your Emotional Intelligence """


# question_text=voice_to_text(voice_file_path)

answer=call_chatGPT(question)

print(answer)

Now call this function in another program and you all set to asking question to chatGPT.

This code is much stable the UI available in the market. Even it give me more flexibility to pass question from various sources and write back answer and handle answer programmatically.

 

No comments:

Post a Comment

Data Mesh

  Data Mesh is a relatively new approach to managing and organizing data within organizations, especially large enterprises. It advocates fo...