DevsDoCode commited on
Commit
59b8168
1 Parent(s): 5c5e16f

Upload 5 files

Browse files
Files changed (5) hide show
  1. DockerFile +11 -0
  2. api_info.py +75 -0
  3. app.py +40 -0
  4. bingChat.py +154 -0
  5. requirements.txt +4 -0
DockerFile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10
2
+
3
+ WORKDIR /code
4
+
5
+ COPY ./requirements.txt /code/requirements.txt
6
+
7
+ RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
8
+
9
+ COPY . .
10
+
11
+ CMD ["flask", "run", "--host", "0.0.0.0", "--port", "7860"]
api_info.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ developer_info = {
2
+ 'developer': 'Devs Do Code',
3
+ 'contact': {
4
+ 'Telegram': 'https://t.me/devsdocode',
5
+ 'YouTube Channel': 'https://www.youtube.com/@DevsDoCode',
6
+ 'LinkedIn': 'https://www.linkedin.com/in/developer-sreejan/',
7
+ 'Discord Server': 'https://discord.gg/ehwfVtsAts',
8
+ 'Instagram': {
9
+ 'Personal': 'https://www.instagram.com/sree.shades_/',
10
+ 'Channel': 'https://www.instagram.com/devsdocode_/'
11
+ }
12
+ }
13
+ }
14
+
15
+
16
+ endpoint = {
17
+ 'route': "/generate",
18
+ 'params': {
19
+ "query": "[SEARCH QUERY]"
20
+ },
21
+ 'optional_params': {
22
+ "max_tokens": "[]",
23
+ "model": "[]",
24
+ "temperature": "[]",
25
+ "system_prompt": "[]"
26
+ },
27
+ 'url_demo' : '/generate?query=Who is Devs Do Code&&max_tokens=500&&model=meta-llama/Meta-Llama-3-70B-Instruct&&temperature=0.7&&system_prompt=Your Owner is "Devs Do Code"'
28
+ }
29
+
30
+ available_models = {
31
+ "Bing": "Bing Chat Copilot"
32
+ }
33
+
34
+ error_message = {
35
+ 'developer_contact': {
36
+ 'Telegram': 'https://t.me/DevsDoCode',
37
+ 'Instagram': 'https://www.instagram.com/sree.shades_/',
38
+ 'Discord': 'https://discord.gg/ehwfVtsAts',
39
+ 'LinkedIn': 'https://www.linkedin.com/in/developer-sreejan/',
40
+ 'Twitter': 'https://twitter.com/Anand_Sreejan'
41
+ },
42
+ 'error': 'Oops! Something went wrong. Please contact the developer Devs Do Code.'
43
+ }
44
+
45
+
46
+ default_info = """This API is developed and being maintained by Devs Do Code (Sreejan).
47
+
48
+ **About the Developer**
49
+
50
+ Sreejan, a high school student from Patna, Bihar, India, has emerged as a notable figure in the technology sector.
51
+ His creation of an API is a testament to his dedication and expertise. Despite his youth, Sreejan's contributions
52
+ to artificial intelligence and machine learning are significant. As an AI & ML Engineer, he specializes in Deep Learning,
53
+ Natural Language Processing (NLP), and Robotics, with proficiency in Python, Java, and Mobile App Development.
54
+ Beyond his role as a technology consumer, Sreejan is an active open-source contributor, notably to projects like Hugging Face.
55
+
56
+ He is also recognized for his role in community development, particularly through "Devs Do Code," a platform he
57
+ founded to provide quality coding resources, tutorials, and projects. His mission is to equip developers with the
58
+ necessary skills to thrive in the ever-evolving tech landscape. Sreejan's commitment to sharing knowledge and
59
+ fostering collaboration is evident in his accessibility and engagement with the community across various platforms.
60
+
61
+ Connect with Sreejan and follow his journey in technology and innovation:
62
+
63
+ - Telegram: https://t.me/devsdocode
64
+ - YouTube Channel: https://www.youtube.com/@DevsDoCode
65
+ - LinkedIn: https://www.linkedin.com/in/developer-sreejan/
66
+ - Discord Server: https://discord.gg/ehwfVtsAts
67
+ - Instagram
68
+ - Personal: https://www.instagram.com/sree.shades_/
69
+ - Channel: https://www.instagram.com/devsdocode_/
70
+
71
+ Sreejan stands out not only as a developer but as a visionary and leader, driving change in the tech industry
72
+ with his passion, expertise, and unwavering commitment to community building. He continues to shape the
73
+ future of technology, one line of code at a time.
74
+ """
75
+
app.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ import bingChat
3
+ import api_info
4
+
5
+ app = Flask(__name__)
6
+
7
+ @app.route('/')
8
+ def initial():
9
+ return '<pre>' + api_info.default_info + '</pre>'
10
+
11
+ @app.route("/available_models", methods=['GET'])
12
+ def available_models():
13
+ return jsonify(api_info.available_models)
14
+
15
+ @app.route("/endpoints", methods=['GET'])
16
+ def endpoints():
17
+ return jsonify(api_info.endpoint)
18
+
19
+ @app.route("/developer_info", methods=['GET'])
20
+ def developer_info():
21
+ return jsonify(api_info.developer_info)
22
+
23
+ @app.route('/generate', methods=['GET'])
24
+ def generate():
25
+
26
+ conversation_history = request.args.get('conversation_history') # Assuming the query is sent in JSON format
27
+ realtime = request.args.get('realtime', False)
28
+ md_format=request.args.get('md_format', True)
29
+
30
+ if conversation_history:
31
+ response = bingChat.ddc_bing_converse(conv_history=conversation_history)
32
+ return jsonify([{'response': response}]), 200
33
+
34
+ else:
35
+ return jsonify(api_info.error_message), 400
36
+
37
+ if __name__ == '__main__':
38
+ app.run(debug=True)
39
+
40
+
bingChat.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ BingChat API Interaction Module
3
+
4
+ This module provides functionality to interact with the Bing Chat Copilot,
5
+ allowing for dynamic conversations and response streaming.
6
+
7
+ Created by: DevsDoCode
8
+ Last updated: 2024-09-21
9
+ """
10
+
11
+ import json
12
+ import requests
13
+ import os
14
+ from dotenv import load_dotenv; load_dotenv()
15
+
16
+ # Inspired by the DevsDoCode philosophy of clean, efficient code
17
+ ddc_api_endpoint = os.environ.get("api_url")
18
+
19
+
20
+ def ddc_bing_converse(conv_history=[], convo_tone="", md_format=False, realtime=True):
21
+ """
22
+ Initiates a conversation with the Bing Chat API and retrieves the response.
23
+
24
+ Args:
25
+ conv_history (list): A sequence of message objects forming the conversation.
26
+ convo_tone (str): The desired conversational style or tone.
27
+ md_format (bool): Flag to enable Markdown formatting in the response.
28
+ realtime (bool): Indicator for streaming the API response in real-time.
29
+
30
+ Returns:
31
+ dict: A response object containing API data or error information.
32
+ Structure mirrors the 'bing' class output from reference implementation.
33
+
34
+ Raises:
35
+ requests.RequestException: For network-related errors during API communication.
36
+ json.JSONDecodeError: If the API response cannot be parsed as JSON.
37
+ """
38
+ try:
39
+ headers = {
40
+ "Content-Type": "application/json"
41
+ }
42
+
43
+ # DDC: Innovative approach to boolean parsing
44
+ stream_mode = realtime if isinstance(realtime, bool) else False
45
+
46
+ try:
47
+ payload = json.dumps({
48
+ "messages": conv_history or [],
49
+ "conversation_style": convo_tone or "Balanced",
50
+ "markdown": md_format if md_format is not None else False,
51
+ "stream": stream_mode,
52
+ "model": "Bing"
53
+ })
54
+ except json.JSONDecodeError:
55
+ payload = json.dumps({
56
+ "messages": [],
57
+ "conversation_style": "Balanced",
58
+ "model": "Bing",
59
+ "markdown": False,
60
+ "stream": False
61
+ })
62
+
63
+ api_response = requests.post(url=ddc_api_endpoint,
64
+ headers=headers,
65
+ data=payload,
66
+ stream=stream_mode)
67
+
68
+ if api_response.status_code == 200:
69
+ if not stream_mode:
70
+ return ddc_process_non_stream_response(api_response)
71
+ else:
72
+ return {"api_error": None, "result": None, "bingdata": api_response}
73
+ else:
74
+ return ddc_handle_error_response(api_response)
75
+
76
+ except Exception as e:
77
+ return {
78
+ "api_error": {
79
+ "code": 500,
80
+ "status": False,
81
+ "api_error": "INTERNAL_SERVER_ERROR",
82
+ "message": f"Unexpected error: {str(e)}"
83
+ },
84
+ "bingdata": None,
85
+ "result": None
86
+ }
87
+
88
+
89
+ def ddc_process_non_stream_response(response):
90
+ """
91
+ Processes a non-streaming API response.
92
+
93
+ Args:
94
+ response (requests.Response): The API response object.
95
+
96
+ Returns:
97
+ dict: Processed response data or error information.
98
+ """
99
+ try:
100
+ json_start = response.text.index("{")
101
+ json_data = json.loads(response.text[json_start:])
102
+
103
+ if json_data.get("code") == 200 and json_data.get("status") == True:
104
+ return {"api_error": None, "result": json_data, "bingdata": None}
105
+ else:
106
+ return {"api_error": json_data, "result": None, "bingdata": None}
107
+ except (ValueError, json.JSONDecodeError):
108
+ return {
109
+ "api_error": {
110
+ "code": 500,
111
+ "status": False,
112
+ "api_error": "INTERNAL_SERVER_ERROR",
113
+ "message": "Failed to parse API response"
114
+ },
115
+ "result": None,
116
+ "bingdata": None
117
+ }
118
+
119
+
120
+ def ddc_handle_error_response(response):
121
+ """
122
+ Handles error responses from the API.
123
+
124
+ Args:
125
+ response (requests.Response): The error response from the API.
126
+
127
+ Returns:
128
+ dict: Formatted error information.
129
+ """
130
+ try:
131
+ error_data = response.json()
132
+ except json.JSONDecodeError:
133
+ error_data = {
134
+ "code": 500,
135
+ "status": False,
136
+ "api_error": "INTERNAL_SERVER_ERROR",
137
+ "message": "Unable to parse error response"
138
+ }
139
+ return {"api_error": error_data, "result": None, "bingdata": None}
140
+
141
+
142
+ if __name__ == "__main__":
143
+ # DevsDoCode: Example usage demonstration
144
+ sample_query = [{"role": "user", "content": "Describe India in 10 lines"}]
145
+ api_result = ddc_bing_converse(conv_history=sample_query, realtime=False, md_format=True)
146
+
147
+ if api_result["api_error"]:
148
+ print("API Error Encountered:", api_result["api_error"])
149
+ else:
150
+ if api_result["bingdata"]:
151
+ for data_chunk in api_result["bingdata"].iter_content(chunk_size=1024):
152
+ print(data_chunk.decode()) # Process streamed data
153
+ else:
154
+ print("API Response Content:", api_result['result'])
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastapi==0.110.2
2
+ Flask==3.0.3
3
+ Requests==2.31.0
4
+ uvicorn==0.29.0