I asked ChatGPT to show me how could I use OpenAi's API to interact with it in my terminal window and it generated code which I modified a little bit in order to do what I wanted.
Here is the python code:
import requests
with open('../api-key.txt','r') as key:
data = key.read().strip()
api_key = data
model="text-danvinci-003"
def chat_with_chatgpt(prompt):
res = requests.post(f"https://api.openai.com/v1/engines/{model}/jobs", headers = {
"Content-Type":"application/json",
"Authorization":f"Bearer {api_key}"
},
json={
"prompt":prompt,
"max_tokens":100
}).json()
print(res)
return res.choices[0].text
while True:
prompt = input('Me: ')
response = chat_with_chatgpt(prompt)
print(f'ChatGPT: {response}')
But when I ran this code I got some messages that said:
Me: hello
{'error': {'message': 'That model does not exist', 'type': 'invalid_request_error', 'param': None, 'code': None}}
Traceback (most recent call last):
File "/data/data/com.termux/files/home/python/main.py", line 23, in <module>
response = chat_with_chatgpt(prompt) ^^^^^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/home/python/main.py", line 19, in chat_with_chatgpt
return res.choices[0].text
^^^^^^^^^^^ AttributeError: 'dict' object has no attribute 'choices'
The response I got is an error dict.
For some reason I am not able to install OpenAi via pip install openai on my system, so this is the only option I have.
I believe the engines API endpoints were deprecated in favour of models. For more info read here: https://help.openai.com/en/articles/6283125-what-happened-to-engines
You will want to look at the completions endpoint instead https://platform.openai.com/docs/api-reference/completions
Here's an example of the URL structure and headers required, using cURL.
curl https://api.openai.com/v1/completions \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{
"model": "text-davinci-003",
"prompt": "Say this is a test",
"max_tokens": 7,
"temperature": 0
}'
The general structure of the code should be fine, you'll just want to swap out the endpoint in use.
def chat_with_chatgpt(prompt):
res = requests.post(f"https://api.openai.com/v1/completions",
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
},
json={
"model": model
"prompt": prompt,
"max_tokens": 100
}).json()
return res.choices[0].text
This is what worked for me
import requests
import time
import sys
with open('../ap.txt','r') as key:
data = key.read().strip()
api_key = data
model="text-davinci-003"
def chat_with_chatgpt(prompt):
res = requests.post(f"https://api.openai.com/v1/completions",
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
},
json={
"model": model,
"prompt": prompt,
"max_tokens": 100
}).json()
return res['choices'][0]['text'][1:]#slice off the first newline line
while True:
prompt = input('\n\nJohn: ')
if prompt == "done":
break
response = chat_with_chatgpt(prompt)
print("Chatgpt:::>",end='\n')
for i in response:
sys.stdout.write(i)
sys.stdout.flush()
time.sleep(0.09)
I included sys to emulate typing of characters since it is easier to read some text as it is getting typed than reading all the text at once which is kinda boring
Related
I'm having troubles using Whatsapp Cloud API (which was released to the public on May 22). I did everything in the getting started in "Set up Developer Assets and Platform Access" section, that way I was able to send the template hello world in Ubuntu 20.04.4 LTS with:
curl -i -X POST \
https://graph.facebook.com/v14.0/my_number/messages \
-H 'Authorization: Bearer my_token' \
-H 'Content-Type: application/json' \
-d '{ "messaging_product": "whatsapp",
"to": "my_reciever",
"type": "template",
"template": { "name": "hello_world", "language": { "code": "en_US" } }
}'
or with Python 3.10 and requests 2.27.1 with:
from requests import Session
import json
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
BASE_URL = "https://graph.facebook.com/"
API_VERSION = "v13.0/"
SENDER = "my_number/"
ENDPOINT = "messages"
URL = BASE_URL + API_VERSION + SENDER + ENDPOINT
API_TOKEN = "my_token"
TO = "my_reciever"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
parameters = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": TO,
"type": "template",
"template": {"name": "hello_world", "language": {"code": "en_US"}}
}
session = Session()
session.headers.update(headers)
try:
response = session.post(URL, json=parameters)
data = json.loads(response.text)
print(f"data: {data}")
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
Then, I tried to send a text message with this:
from requests import Session
import json
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
BASE_URL = "https://graph.facebook.com/"
API_VERSION = "v13.0/"
SENDER = "my_number/"
ENDPOINT = "messages"
URL = BASE_URL + API_VERSION + SENDER + ENDPOINT
API_TOKEN = "my_token"
TO = "my_reciever"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
parameters = {
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": TO,
"type": "text",
"text": {
"preview_url": "false",
"body": "MESSAGE_CONTENT"
}
}
session = Session()
session.headers.update(headers)
try:
response = session.post(URL, json=parameters)
data = json.loads(response.text)
print(f"data: {data}")
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
And, even though the response is correct, something like this:
{'messaging_product': 'whatsapp', 'contacts': [{'input': 'my_reciever', 'wa_id': 'my_reciever'}], 'messages': [{'id': 'wamid.HBgMNTchangingMDYyM0I2AA=='}]}
I don't recieve any message in my_reciver. I don't know what I'm doing wrong, I might have to configure the webhook for this to work? Do I need to opt-in before recieve the message (this can be read in get-started page)?
I even tried using some unofficial wrappers in python like heyoo, but I got the same result.
Hope someone can help me with this, thanks.
Note: this is a similar post, but that one is with node, not Python or Curl, so I guess this does not count as repost.
I have written a brief article on WhatsApp Cloud API like how to send and receive WhatsApp messages and also set up a never expiry access token. Please have a look WhatsApp Cloud API
You need to send the WhatsApp message from your personal number to your WhatsApp business number after that you can send the message from your business number to your personal number. Basically, WhatsApp has a template message concept within 24h session and according to your question, I think you are trying to send a normal unsession message from a business number to your personal number. So, to avoid this case you need to first message from your personal to your business number then you can receive the message to your personal number. Full details in the article regarding template message.
Here is the CURL request for normal message
curl --location --request POST 'https://graph.facebook.com/v13.0/<Your Phone number ID>/messages' \
--header 'Authorization: Bearer <Your Temporary access token>' \
--header 'Content-Type: application/json' \
--data-raw '{"messaging_product":"whatsapp","recipient_type":"individual",
"to":"918587808915","type":"text","text": {"body":"Hello Rishabh!"}
}'
The official META-whatsapp documentation indicates that in order to send such messages, the conversation must be initiated by the user. https://developers.facebook.com/docs/whatsapp/conversation-types
i'm trying to interact with a website's APIs--specifically how to requests.put() a file (JPEG) to it. the Swagger API has a "try it out" function where I successfully can push a file from its "try it out" but when I try to run it in python it throws a 500 internal server error.
this is the successful curl put request from the Swagger "try it out":
curl -X PUT "https://some_website.com/api/v2/documents" -H "accept: /" -H "Content-Type: multipart/form-data" -H "Authorization: Bearer auth tokenp089u098u08j98jasdfsadgfasdg" -d {"file":{},"metadata":"{ "docType":"BILL_OF_LADING", "docTypeNamespace":"platform", "fileType":"IMAGE", "docReferences":{ "name":"bill o lading pal" }, "identifiers":{ "consignment":{ "carrierBookingNumber":"9876smg", "billOfLadingNumber":"1234smg" } } }"}
url = "https://some_website.com"
auth_token = "Bearer auth tokenp089u098u08j98jasdfsadgfasdg"
headers = {"Content-Type": "multipart/form-data",
"Accept": "*/*",
"Authorization": sa_token}
file_loc = "C:/location/of/file/I/want/to/put/Capture.JPG"
metadata = {
"docType":"doc_file",
"docTypeNamespace": "platform",
"fileType":"IMAGE",
"docReferences": {
"name": "this is the form to confirm receipt"
},
"identifiers": {
"consignment": {
"carrierBookingNumber":"9876smg",
"billOfLadingNumber":"1234smg"
}
}
}
body = {
"file": {},
"metadata": metadata
}
resp = requests.put(url=url, headers=headers, data=body)
You should probably send it via json as thats very easy...
import requets
file = "C:\somedir\somedir\somefile.somext"
with open(file, "rb") as f:
fileData = f.read()
putFile(fileD, site, port=3000):
requets.post(site, json='{"file": "' + str(fileD) + '"}'
But you'll need to convert it back to a file.
I am trying to create a very simple chatbot using dialogflow that I can ask a question and get a fulfillment message back. I was able to use python's dialogflow library to get this working, but when I tried to change it to a regular request it did not work. Here is the working code:
import os
import dialogflow
from google.api_core.exceptions import InvalidArgument
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = PATH_TO_JSON
DIALOGFLOW_PROJECT_ID = PROJECT_ID
DIALOGFLOW_LANGUAGE_CODE = 'en'
SESSION_ID = 'me'
text_to_be_analyzed = "How are my stocks"
session_client = dialogflow.SessionsClient()
session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
text_input = dialogflow.types.TextInput(text=text_to_be_analyzed, language_code=DIALOGFLOW_LANGUAGE_CODE)
query_input = dialogflow.types.QueryInput(text=text_input)
try:
response = session_client.detect_intent(session=session, query_input=query_input)
except InvalidArgument:
raise
#print(response)
print("Response:", response.query_result.fulfillment_text)
and it prints
your stocks are good
Using the request library I tried a similar setup and wrote this:
my_key = CLIENT_ACCESS_TOKEN
url = "https://api.dialogflow.com/v1/query?v=20170712"
headers = {
'Authorization': 'Bearer ' + my_key ,
'Content-Type' : 'application/json'
}
body = {
"lang": "en",
"query": "how are my stocks",
"sessionId": "me",
}
r.post(url,headers=headers,data=body).text
and I get an error:
{
"status": {
"code": 400,
"errorType": "bad_request",
"errorDetails": "Cannot parse json. Please validate your json. Code: 400"
}
}
I am getting my example from this url for the query post request. The reason I want this to work as an http request is because I would like to be able to use it in other applications and want to have a consistent way of accessing my intents. Thanks for the help!
Upon more research I found the error at this link. So the question was less about integration with dialogflow and more about making a request in python.
I've been trying to make a request to an API, I have to pass the following body:
{
"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"
}
Altough the code seems to be right and it finished with "Process finished with exit code 0", it's not working well. I have no idea of what I'm missing but this is my code:
http = urllib3.PoolManager()
http.urlopen('POST', 'http://localhost:8080/assets', headers={'Content-Type':'application/json'},
data={
"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"
})
By the way, this the first day working with Python so excuse me if I'm not specific enough.
Since you're trying to pass in a JSON request, you'll need to encode the body as JSON and pass it in with the body field.
For your example, you want to do something like:
import json
encoded_body = json.dumps({
"description": "Tenaris",
"ticker": "TS.BA",
"industry": "Metalúrgica",
"currency": "ARS",
})
http = urllib3.PoolManager()
r = http.request('POST', 'http://localhost:8080/assets',
headers={'Content-Type': 'application/json'},
body=encoded_body)
print r.read() # Do something with the response?
Edit: My original answer was wrong. Updated it to encode the JSON. Also, related question: How do I pass raw POST data into urllib3?
I ran into this issue when making a call to Gitlab CI. Since the above did not work for me (gave me some kind of error about not being able to concatenate bytes to a string), and because the arguments I was attempting to pass were nested, I thought I would post what ended up working for me:
API_ENDPOINT = "https://gitlab.com/api/v4/projects/{}/pipeline".format(GITLAB_PROJECT_ID)
API_TOKEN = "SomeToken"
data = {
"ref": ref,
"variables": [
{
"key": "ENVIRONMENT",
"value": some_env
},
{ "key": "S3BUCKET",
"value": some_bucket
},
]
}
req_headers = {
'Content-Type': 'application/json',
'PRIVATE-TOKEN': API_TOKEN,
}
http = urllib3.PoolManager()
encoded_data = json.dumps(data).encode('utf-8')
r = http.request('POST', API_ENDPOINT,
headers=req_headers,
body=encoded_data)
resp_body = r.data.decode('utf-8')
resp_dict = json.loads(r.data.decode('utf-8'))
logger.info('Response Code: {}'.format(r.status))
logger.info('Response Body: {}'.format(resp_body))
if 'message' in resp_body:
logfile_msg = 'Failed Gitlab Response-- {} {message}'.format(r.status, **resp_dict)
I recently became interested in using urllib3, and came across this problem. If you read the urllib3 "User Guide" page, you will see this:
For POST and PUT requests, you need to manually encode query parameters in the URL
Your code should be adjusted to look like this:
import urllib3
from urllib.parse import urlencode
data = {"description":"Tenaris",
"ticker":"TS.BA",
"industry":"Metalúrgica",
"currency":"ARS"}
http = urllib3.PoolManager()
encoded_data = urlencode(data)
http.request('POST',
'http://localhost:8080/assets?'+encoded_data,
headers={'Content-Type':'application/json'})
Im using python requests library to make google a drive api request to change permissions of a file, in this case the owner.
Here is what my code looks like
fileId = "123abcEfJl-mNooP45Kl6u" #fake file id
url = https://www.googleapis.com/drive/v2/files/%s/permissions' % fileId
payload = {"role":"owner", "type":"user", "value":"<some_user>#gmail.com"}
headers = {'Authorization': 'Bearer %s'%access_token, 'Content-Type':'application/json'}
permResponse = requests.post(url, data=payload, headers=headers)
print permResponse.text
When I run this, I get the following response:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
I've been following the google docs api for this and have not been able to figure out what im doing incorrectly.
https://developers.google.com/drive/v2/reference/permissions/insert
Even their Try It! section is broken because there isn't an option to add the required 'value' field.
What am I doing incorrectly? Is anyone else running into these issues?
Thanks
I'm using the urllib.request module, and It works fine. This is my code:
key = "?key=" + MY_API_KEY
url_destino = ("https://www.googleapis.com/drive/v2/files/%s/permissions" % source_id)+ key
values = "{"role":"owner", "type":"user", "value":"<some_user>#gmail.com"}"
data = values.encode('utf-8')
request = urllib.request.Request(url_destino, data, method='POST')
request.add_header("Authorization", "Bearer " + token)
request.add_header("Content-Length", len(data))
request.add_header("Content-Type", "application/json")
print(request.header_items()) # for debugging purpouse
f = urllib.request.urlopen(request)
print(f.read())
I've thought to replace the urllib.request by Requests module (it's more clean to work with) in my little library but, now works.
Because I use Python 3 I can't use the google-api-python-client.