Skip to content

Commit 19b7377

Browse files
streaming-chatbot
- basic GenAI service setup - example of "streaming" feature
1 parent 24f71c4 commit 19b7377

File tree

3 files changed

+193
-0
lines changed

3 files changed

+193
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
Copyright (c) 2025 Oracle and/or its affiliates.
2+
3+
The Universal Permissive License (UPL), Version 1.0
4+
5+
Subject to the condition set forth below, permission is hereby granted to any
6+
person obtaining a copy of this software, associated documentation and/or data
7+
(collectively the "Software"), free of charge and under any and all copyright
8+
rights in the Software, and any and all patent rights owned or freely
9+
licensable by each licensor hereunder covering either (i) the unmodified
10+
Software as contributed to or provided by such licensor, or (ii) the Larger
11+
Works (as defined below), to deal in both
12+
13+
(a) the Software, and
14+
(b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
15+
one is included with the Software (each a "Larger Work" to which the Software
16+
is contributed by such licensors),
17+
18+
without restriction, including without limitation the rights to copy, create
19+
derivative works of, display, perform, and distribute the Software and make,
20+
use, sell, offer for sale, import, export, have made, and have sold the
21+
Software and the Larger Work(s), and to sublicense the foregoing rights on
22+
either these or other terms.
23+
24+
This license is subject to the following condition:
25+
The above copyright notice and either this complete permission notice or at
26+
a minimum a reference to the UPL must be included in all copies or
27+
substantial portions of the Software.
28+
29+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35+
SOFTWARE.
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Streaming Chatbot
2+
This asset is a Python-based chatbot that utilizes Oracle Cloud Infrastructure (OCI) Generative AI services to provide real-time, streaming responses. It is designed to interact with Cohere models available within OCI's Generative AI service. Users interested in leveraging other models, such as those from Meta or Google, can refer to the OCI Generative AI documentation for guidance on integrating these alternatives.
3+
4+
Reviewed: 22.10.2025
5+
6+
# When to use this asset?
7+
8+
This asset is suitable for developers and organizations aiming to integrate AI-driven conversational interfaces into their applications, particularly when:
9+
10+
- **Real-Time Interaction**: Immediate, dynamic responses are required in a chat interface.
11+
- **Stateless Processing**: Each user input is processed independently, without context from prior exchanges.
12+
- **Scalable AI Solutions**: Utilizing OCI's Generative AI services to handle varying loads and complex queries.
13+
14+
# How to use this asset?
15+
16+
To set up and run the `genai-streaming-chatbot`, follow these steps:
17+
18+
1. **Prerequisites**:
19+
20+
- **Python Environment**: Ensure Python 3.6 or later is installed.
21+
- **OCI Account**: An active Oracle Cloud Infrastructure account with necessary permissions.
22+
- **API Key**: Generate and configure an API key for authentication.
23+
24+
2. **Installation**:
25+
26+
- **Virtual Environment**: It's recommended to use a virtual environment to manage dependencies.
27+
28+
```bash
29+
pip install virtualenv
30+
virtualenv oci_env
31+
source oci_env/bin/activate
32+
```
33+
34+
- **Install OCI SDK**:
35+
36+
```bash
37+
pip install oci
38+
```
39+
40+
3. **Configuration**:
41+
42+
- **API Key Setup**: Generate an API key pair in the OCI Console and configure it in the `~/.oci/config` file. Ensure the private key has appropriate permissions.
43+
44+
- **Configuration File**: Create a `config` file in the `~/.oci` directory with the necessary details:
45+
46+
```ini
47+
[DEFAULT]
48+
user=ocid1.user.oc1..<unique_ID>
49+
fingerprint=<your_fingerprint>
50+
key_file=~/.oci/oci_api_key.pem
51+
tenancy=ocid1.tenancy.oc1..<unique_ID>
52+
region=us-ashburn-1
53+
```
54+
55+
4. **Running the Chatbot**:
56+
57+
- **Script Setup**: Save the chatbot script to a file, e.g., `genai_streaming_chatbot.py`.
58+
59+
- **Execute the Script**:
60+
61+
```bash
62+
python genai_streaming_chatbot.py
63+
```
64+
65+
- **Interaction**: Engage with the chatbot by typing messages. Type 'exit' to end the session.
66+
67+
**Note**: This chatbot processes each input independently and does not retain context from previous interactions. To implement a conversational chatbot that maintains context, you would need to manage the conversation history externally by storing previous user inputs and model responses, then appending this history to each new prompt.
68+
69+
# Useful Links
70+
71+
- [OCI Python SDK Documentation](https://docs.oracle.com/en-us/iaas/Content/API/SDKDocs/pythonsdk.htm)
72+
- Comprehensive guide on using the OCI Python SDK.
73+
- [OCI Generative AI Inference API Documentation](https://docs.oracle.com/en-us/iaas/tools/python/latest/api/generative_ai_inference.html)
74+
- Detailed information on the Generative AI Inference API.
75+
- [OCI Generative AI Service](https://docs.oracle.com/en-us/iaas/Content/generative-ai/home.htm)
76+
- Detailed information on OCI Generative AI Service
77+
78+
# License
79+
80+
Copyright (c) 2025 Oracle and/or its affiliates.
81+
82+
Licensed under the Universal Permissive License (UPL), Version 1.0.
83+
84+
See [LICENSE](https://github.com/oracle-devrel/technology-engineering/blob/main/LICENSE.txt) for more details.
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import json
2+
import oci
3+
from oci.generative_ai_inference import GenerativeAiInferenceClient
4+
from oci.generative_ai_inference.models import OnDemandServingMode, ChatDetails, CohereChatRequest
5+
6+
compartment_id = "ocid1.compartment.oc1..XXXXXXXXXXXXXXXXXXXXX"
7+
model_id = "ocid1.generativeaimodel.oc1.XXXXXXXXXXXXXXXXXXXXXX"
8+
endpoint = "https://inference.generativeai.XXXXXXXXXXXXXXXXXXX"
9+
10+
CONFIG_PROFILE = "DEFAULT"
11+
12+
config = oci.config.from_file('~/.oci/config', CONFIG_PROFILE)
13+
14+
def get_llm_response(prompt):
15+
client = GenerativeAiInferenceClient(
16+
config=config,
17+
service_endpoint=endpoint,
18+
retry_strategy=oci.retry.NoneRetryStrategy(),
19+
timeout=(10, 240)
20+
)
21+
22+
chat_request = CohereChatRequest(
23+
message=prompt,
24+
max_tokens=600,
25+
temperature=0.5,
26+
frequency_penalty=0,
27+
top_p=0.75,
28+
top_k=0,
29+
is_stream=True # Enable streaming
30+
)
31+
32+
chat_detail = ChatDetails(
33+
serving_mode=OnDemandServingMode(model_id=model_id),
34+
chat_request=chat_request,
35+
compartment_id=compartment_id
36+
)
37+
38+
try:
39+
response = client.chat(chat_detail)
40+
41+
buffer = ""
42+
for event in response.data.events():
43+
if not event.data:
44+
continue
45+
46+
buffer += event.data.strip()
47+
try:
48+
event_json = json.loads(buffer)
49+
buffer = "" # clear buffer if parse succeeded
50+
except json.JSONDecodeError:
51+
# wait for more chunks
52+
continue
53+
54+
text_chunk = event_json.get("text")
55+
if text_chunk:
56+
yield text_chunk
57+
58+
except Exception as e:
59+
yield f"\n[Error during streaming: {e}]\n"
60+
61+
def main():
62+
print("OCI GenAI chatbot. Type 'exit' to quit.")
63+
while True:
64+
user_input = input("You: ")
65+
if user_input.strip().lower() == 'exit':
66+
print("Goodbye!")
67+
break
68+
print("Assistant: ", end="", flush=True)
69+
for token in get_llm_response(user_input):
70+
print(token, end="", flush=True)
71+
print()
72+
73+
if __name__ == "__main__":
74+
main()

0 commit comments

Comments
 (0)