Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 14d473a

Browse files
Merge pull request avinashkranjan#2686 from Shivansh-Jain-github/cont1
Open AI chatbot using python
2 parents eec9f8b + 8a9853c commit 14d473a

File tree

5 files changed

+331
-0
lines changed

5 files changed

+331
-0
lines changed

‎ChatBot using OpenAI API/README.md‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
2+
```markdown
3+
# OpenAI Chatbot Example
4+
5+
This repository contains examples of using the OpenAI GPT-3 model to create a chatbot that can hold conversations with users.
6+
7+
## Prerequisites
8+
9+
- OpenAI Python Package (`openai`)
10+
- `requests` library (for Method 2)
11+
12+
You can install the required libraries using the following commands:
13+
14+
```bash
15+
pip install openai requests
16+
```
17+
18+
## Method 1 - Using OpenAI Python Package
19+
20+
This method demonstrates how to use the OpenAI Python package to create a chatbot using the `gpt-3.5-turbo` model.
21+
22+
The code provided in the repository (`method_1_openai_package.py`) includes:
23+
24+
- Setting up the OpenAI API key.
25+
- Initiating a conversation with a system message.
26+
- Taking user inputs and generating replies using the chatbot.
27+
- Displaying the chat history.
28+
29+
## Method 2 - Using API Endpoint
30+
31+
This method demonstrates how to interact with the OpenAI API directly using HTTP requests.
32+
33+
The code provided in the repository (`method_2_api_endpoint.py`) includes:
34+
35+
- Defining the API endpoint URL.
36+
- Creating a payload with user inputs and other parameters.
37+
- Sending a POST request to the API endpoint.
38+
- Extracting and displaying the generated response.
39+
40+
## Usage
41+
42+
1. Set up your OpenAI API key by replacing `'sk-'` in the code with your actual API key.
43+
44+
2. Choose the method you want to use (Method 1 or Method 2).
45+
46+
3. Run the selected script using a Python interpreter:
47+
48+
```bash
49+
python method_1_openai_package.py
50+
```
51+
or
52+
```bash
53+
python method_2_api_endpoint.py
54+
```
55+
56+
4. Observe the interaction with the chatbot and the generated responses.
57+
58+
## Notes
59+
60+
- Make sure to review the OpenAI API documentation for more information on available models, parameters, and best practices.
61+
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": 1,
6+
"metadata": {},
7+
"outputs": [],
8+
"source": [
9+
"\n",
10+
"!pip install -q openai"
11+
]
12+
},
13+
{
14+
"cell_type": "code",
15+
"execution_count": 2,
16+
"metadata": {},
17+
"outputs": [],
18+
"source": [
19+
"\n",
20+
"import openai"
21+
]
22+
},
23+
{
24+
"cell_type": "code",
25+
"execution_count": 3,
26+
"metadata": {},
27+
"outputs": [],
28+
"source": [
29+
"\n",
30+
"openai.api_key = 'sk-'"
31+
]
32+
},
33+
{
34+
"cell_type": "code",
35+
"execution_count": 4,
36+
"metadata": {},
37+
"outputs": [],
38+
"source": [
39+
"\n",
40+
"messages = [\n",
41+
" {\"role\": \"system\", \"content\": \"You are a kind helpful assistant.\"},\n",
42+
"]"
43+
]
44+
},
45+
{
46+
"cell_type": "code",
47+
"execution_count": null,
48+
"metadata": {},
49+
"outputs": [],
50+
"source": [
51+
"while True:\n",
52+
" message = input(\"User : \")\n",
53+
" if message:\n",
54+
" messages.append(\n",
55+
" {\"role\": \"user\", \"content\": message},\n",
56+
" )\n",
57+
" chat = openai.ChatCompletion.create(\n",
58+
" model=\"gpt-3.5-turbo\", messages=messages\n",
59+
" )\n",
60+
" \n",
61+
" reply = chat.choices[0].message.content\n",
62+
" print(f\"ChatGPT: {reply}\")\n",
63+
" messages.append({\"role\": \"assistant\", \"content\": reply})\n",
64+
" "
65+
]
66+
}
67+
],
68+
"metadata": {
69+
"kernelspec": {
70+
"display_name": "Python 3",
71+
"language": "python",
72+
"name": "python3"
73+
},
74+
"language_info": {
75+
"codemirror_mode": {
76+
"name": "ipython",
77+
"version": 3
78+
},
79+
"file_extension": ".py",
80+
"mimetype": "text/x-python",
81+
"name": "python",
82+
"nbconvert_exporter": "python",
83+
"pygments_lexer": "ipython3",
84+
"version": "3.11.4"
85+
},
86+
"orig_nbformat": 4
87+
},
88+
"nbformat": 4,
89+
"nbformat_minor": 2
90+
}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": 1,
6+
"metadata": {},
7+
"outputs": [
8+
{
9+
"ename": "NameError",
10+
"evalue": "name 'openai' is not defined",
11+
"output_type": "error",
12+
"traceback": [
13+
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
14+
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
15+
"Cell \u001b[1;32mIn[1], line 18\u001b[0m\n\u001b[0;32m 3\u001b[0m URL \u001b[39m=\u001b[39m \u001b[39m\"\u001b[39m\u001b[39mhttps://api.openai.com/v1/chat/completions\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[0;32m 5\u001b[0m payload \u001b[39m=\u001b[39m {\n\u001b[0;32m 6\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mmodel\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39m\"\u001b[39m\u001b[39mgpt-3.5-turbo\u001b[39m\u001b[39m\"\u001b[39m,\n\u001b[0;32m 7\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mmessages\u001b[39m\u001b[39m\"\u001b[39m: [{\u001b[39m\"\u001b[39m\u001b[39mrole\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39m\"\u001b[39m\u001b[39muser\u001b[39m\u001b[39m\"\u001b[39m, \u001b[39m\"\u001b[39m\u001b[39mcontent\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mWhat is the first computer in the world?\u001b[39m\u001b[39m\"\u001b[39m}],\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 13\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mfrequency_penalty\u001b[39m\u001b[39m\"\u001b[39m:\u001b[39m0\u001b[39m,\n\u001b[0;32m 14\u001b[0m }\n\u001b[0;32m 16\u001b[0m headers \u001b[39m=\u001b[39m {\n\u001b[0;32m 17\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mContent-Type\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39m\"\u001b[39m\u001b[39mapplication/json\u001b[39m\u001b[39m\"\u001b[39m,\n\u001b[1;32m---> 18\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mAuthorization\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mBearer \u001b[39m\u001b[39m{\u001b[39;00mopenai\u001b[39m.\u001b[39mapi_key\u001b[39m}\u001b[39;00m\u001b[39m\"\u001b[39m\n\u001b[0;32m 19\u001b[0m }\n\u001b[0;32m 21\u001b[0m response \u001b[39m=\u001b[39m requests\u001b[39m.\u001b[39mpost(URL, headers\u001b[39m=\u001b[39mheaders, json\u001b[39m=\u001b[39mpayload, stream\u001b[39m=\u001b[39m\u001b[39mFalse\u001b[39;00m)\n",
16+
"\u001b[1;31mNameError\u001b[0m: name 'openai' is not defined"
17+
]
18+
}
19+
],
20+
"source": [
21+
"import requests\n",
22+
"\n",
23+
"URL = \"https://api.openai.com/v1/chat/completions\"\n",
24+
"\n",
25+
"payload = {\n",
26+
"\"model\": \"gpt-3.5-turbo\",\n",
27+
"\"messages\": [{\"role\": \"user\", \"content\": f\"What is the first computer in the world?\"}],\n",
28+
"\"temperature\" : 1.0,\n",
29+
"\"top_p\":1.0,\n",
30+
"\"n\" : 1,\n",
31+
"\"stream\": False,\n",
32+
"\"presence_penalty\":0,\n",
33+
"\"frequency_penalty\":0,\n",
34+
"}\n",
35+
"\n",
36+
"headers = {\n",
37+
"\"Content-Type\": \"application/json\",\n",
38+
"\"Authorization\": f\"Bearer {openai.api_key}\"\n",
39+
"}\n",
40+
"\n",
41+
"response = requests.post(URL, headers=headers, json=payload, stream=False)"
42+
]
43+
},
44+
{
45+
"cell_type": "code",
46+
"execution_count": 2,
47+
"metadata": {},
48+
"outputs": [
49+
{
50+
"ename": "NameError",
51+
"evalue": "name 'response' is not defined",
52+
"output_type": "error",
53+
"traceback": [
54+
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
55+
"\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)",
56+
"Cell \u001b[1;32mIn[2], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m response\u001b[39m.\u001b[39mcontent\n",
57+
"\u001b[1;31mNameError\u001b[0m: name 'response' is not defined"
58+
]
59+
}
60+
],
61+
"source": [
62+
"\n",
63+
"response.content"
64+
]
65+
},
66+
{
67+
"cell_type": "code",
68+
"execution_count": null,
69+
"metadata": {},
70+
"outputs": [],
71+
"source": []
72+
}
73+
],
74+
"metadata": {
75+
"kernelspec": {
76+
"display_name": "Python 3",
77+
"language": "python",
78+
"name": "python3"
79+
},
80+
"language_info": {
81+
"codemirror_mode": {
82+
"name": "ipython",
83+
"version": 3
84+
},
85+
"file_extension": ".py",
86+
"mimetype": "text/x-python",
87+
"name": "python",
88+
"nbconvert_exporter": "python",
89+
"pygments_lexer": "ipython3",
90+
"version": "3.11.4"
91+
},
92+
"orig_nbformat": 4
93+
},
94+
"nbformat": 4,
95+
"nbformat_minor": 2
96+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Web Scraping with Beautiful Soup
2+
3+
This script performs web scraping on a CodeChef problem statement webpage using the Beautiful Soup library in Python.
4+
5+
## Description
6+
7+
The Python script utilizes the `requests` and `BeautifulSoup` libraries to extract information from a CodeChef problem statement webpage. It demonstrates the following actions:
8+
9+
- Printing the title of the webpage.
10+
- Finding and printing all links on the page.
11+
- Extracting text from paragraphs.
12+
- Extracting image URLs.
13+
- Counting and categorizing HTML tags.
14+
- Filtering and printing valid links.
15+
- Saving extracted data to a text file.
16+
17+
## Prerequisites
18+
19+
Ensure you have the following libraries installed:
20+
21+
- `requests`
22+
- `beautifulsoup4`
23+
24+
You can install them using the following commands:
25+
26+
```bash
27+
pip install requests beautifulsoup4
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import requests
2+
from bs4 import BeautifulSoup
3+
import re
4+
5+
url = 'https://www.codechef.com/problems/TWORANGES?tab=statement'
6+
response = requests.get(url)
7+
soup = BeautifulSoup(response.content, 'html.parser')
8+
9+
# Print the title of the webpage
10+
print(f"Title: {soup.title.text}\n")
11+
12+
# Find and print all links on the page
13+
print("Links on the page:")
14+
for link in soup.find_all('a'):
15+
print(link.get('href'))
16+
17+
# Extract text from paragraphs
18+
print("\nText from paragraphs:")
19+
for paragraph in soup.find_all('p'):
20+
print(paragraph.text)
21+
22+
# Extract image URLs
23+
print("\nImage URLs:")
24+
for img in soup.find_all('img'):
25+
img_url = img.get('src')
26+
if img_url:
27+
print(img_url)
28+
29+
# Count and categorize tags
30+
print("\nTag counts:")
31+
tag_counts = {}
32+
for tag in soup.find_all():
33+
tag_name = tag.name
34+
if tag_name:
35+
tag_counts[tag_name] = tag_counts.get(tag_name, 0) + 1
36+
37+
for tag, count in tag_counts.items():
38+
print(f"{tag}: {count}")
39+
40+
# Filter and print valid links
41+
print("\nValid links:")
42+
for link in soup.find_all('a'):
43+
href = link.get('href')
44+
if href and re.match(r'^https?://', href):
45+
print(href)
46+
47+
# Save data to a file
48+
with open('webpage_data.txt', 'w') as file:
49+
file.write(f"Title: {soup.title.text}\n\n")
50+
file.write("Links on the page:\n")
51+
for link in soup.find_all('a'):
52+
file.write(f"{link.get('href')}\n")
53+
file.write("\nText from paragraphs:\n")
54+
for paragraph in soup.find_all('p'):
55+
file.write(f"{paragraph.text}\n")
56+
57+
print("\nData saved to 'webpage_data.txt'")

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /