Code Examples
Complete working examples for all Selam API features in Python, JavaScript, and cURL. Copy and adapt these examples for your applications.
Quick Start
Get started with a simple chat completion request.
Basic Chat Completion
1from openai import OpenAI
2
3client = OpenAI(
4 api_key="your-api-key-here",
5 base_url="https://api.selamgpt.com/v1"
6)
7
8response = client.chat.completions.create(
9 model="selam-turbo",
10 messages=[
11 {"role": "user", "content": "Hello, how are you?"}
12 ]
13)
14
15print(response.choices[0].message.content)Streaming Responses
Stream responses in real-time for better user experience.
1from openai import OpenAI
2
3client = OpenAI(
4 api_key="your-api-key-here",
5 base_url="https://api.selamgpt.com/v1"
6)
7
8stream = client.chat.completions.create(
9 model="selam-turbo",
10 messages=[{"role": "user", "content": "Tell me a story"}],
11 stream=True
12)
13
14for chunk in stream:
15 if chunk.choices[0].delta.content:
16 print(chunk.choices[0].delta.content, end="", flush=True)Vision (Image Understanding)
Analyze images with vision-capable models.
Image Analysis
1from openai import OpenAI
2
3client = OpenAI(
4 api_key="your-api-key-here",
5 base_url="https://api.selamgpt.com/v1"
6)
7
8response = client.chat.completions.create(
9 model="selam-plus",
10 messages=[
11 {
12 "role": "user",
13 "content": [
14 {"type": "text", "text": "What's in this image?"},
15 {
16 "type": "image_url",
17 "image_url": {
18 "url": "https://example.com/image.jpg"
19 }
20 }
21 ]
22 }
23 ]
24)
25
26print(response.choices[0].message.content)Function Calling
Build tool-using agents with function calling.
Weather Function Example
1from openai import OpenAI
2import json
3
4client = OpenAI(
5 api_key="your-api-key-here",
6 base_url="https://api.selamgpt.com/v1"
7)
8
9tools = [
10 {
11 "type": "function",
12 "function": {
13 "name": "get_weather",
14 "description": "Get the current weather for a location",
15 "parameters": {
16 "type": "object",
17 "properties": {
18 "location": {
19 "type": "string",
20 "description": "City name"
21 },
22 "unit": {
23 "type": "string",
24 "enum": ["celsius", "fahrenheit"]
25 }
26 },
27 "required": ["location"]
28 }
29 }
30 }
31]
32
33response = client.chat.completions.create(
34 model="selam-plus",
35 messages=[{"role": "user", "content": "What's the weather in Addis Ababa?"}],
36 tools=tools
37)
38
39# Check if model wants to call a function
40if response.choices[0].message.tool_calls:
41 tool_call = response.choices[0].message.tool_calls[0]
42 function_name = tool_call.function.name
43 function_args = json.loads(tool_call.function.arguments)
44
45 print(f"Function: {function_name}")
46 print(f"Arguments: {function_args}")Image Generation
Generate images from text descriptions.
Generate Image
1from openai import OpenAI
2
3client = OpenAI(
4 api_key="your-api-key-here",
5 base_url="https://api.selamgpt.com/v1"
6)
7
8response = client.images.generate(
9 model="selam-image",
10 prompt="A beautiful Ethiopian coffee ceremony",
11 size="1024x1024",
12 n=1
13)
14
15image_url = response.data[0].url
16print(f"Image URL: {image_url}")Text-to-Speech
Convert text to natural-sounding speech in multiple languages.
Generate Speech
1from openai import OpenAI
2
3client = OpenAI(
4 api_key="your-api-key-here",
5 base_url="https://api.selamgpt.com/v1"
6)
7
8response = client.audio.speech.create(
9 model="tts-1",
10 voice="mekdes",
11 input="ሰላም! እንዴት ነህ?" # "Hello! How are you?" in Amharic
12)
13
14# Save to file
15response.stream_to_file("output.mp3")Translation
Translate conversations between English, Amharic, Somali, and Tigrinya.
Auto-Detect Translation
1from openai import OpenAI
2
3client = OpenAI(
4 api_key="your-api-key-here",
5 base_url="https://api.selamgpt.com/v1"
6)
7
8response = client.chat.completions.create(
9 model="selam-turbo",
10 messages=[
11 {"role": "user", "content": "ሰላም! እንዴት ነህ?"} # Amharic
12 ],
13 extra_headers={
14 "X-Target-Language": "en" # Translate to English
15 }
16)
17
18print(response.choices[0].message.content)
19# Output will be in EnglishFile Upload & OCR
Upload and analyze documents, PDFs, and code files.
Upload PDF
1from openai import OpenAI
2import base64
3
4client = OpenAI(
5 api_key="your-api-key-here",
6 base_url="https://api.selamgpt.com/v1"
7)
8
9# Read and encode file
10with open("document.pdf", "rb") as f:
11 file_data = base64.b64encode(f.read()).decode("utf-8")
12
13response = client.chat.completions.create(
14 model="selam-plus",
15 messages=[
16 {
17 "role": "user",
18 "content": [
19 {"type": "text", "text": "Summarize this document"},
20 {
21 "type": "image_url",
22 "image_url": {
23 "url": f"data:application/pdf;base64,{file_data}"
24 }
25 }
26 ]
27 }
28 ]
29)
30
31print(response.choices[0].message.content)Web Search
Access real-time information with web search integration.
Search-Enabled Chat
1from openai import OpenAI
2
3client = OpenAI(
4 api_key="your-api-key-here",
5 base_url="https://api.selamgpt.com/v1"
6)
7
8# Option 1: Use selam-search model (built-in search)
9response = client.chat.completions.create(
10 model="selam-search",
11 messages=[
12 {"role": "user", "content": "What's the latest news about AI?"}
13 ]
14)
15
16# Option 2: Use web_search tool with any model
17response = client.chat.completions.create(
18 model="selam-plus",
19 messages=[
20 {"role": "user", "content": "What's the latest news about AI?"}
21 ],
22 tools=[{"type": "web_search"}]
23)
24
25print(response.choices[0].message.content)Batch Processing
Process multiple requests efficiently with the batch endpoint.
Batch Requests
1import requests
2import json
3
4# Prepare batch requests in JSONL format
5batch_requests = [
6 {
7 "custom_id": "request-1",
8 "method": "POST",
9 "url": "/v1/chat/completions",
10 "body": {
11 "model": "selam-turbo",
12 "messages": [{"role": "user", "content": "What is AI?"}]
13 }
14 },
15 {
16 "custom_id": "request-2",
17 "method": "POST",
18 "url": "/v1/chat/completions",
19 "body": {
20 "model": "selam-turbo",
21 "messages": [{"role": "user", "content": "What is ML?"}]
22 }
23 }
24]
25
26# Convert to JSONL
27jsonl_data = "\n".join([json.dumps(req) for req in batch_requests])
28
29# Send batch request
30response = requests.post(
31 "https://api.selamgpt.com/v1/chat/completions/batch",
32 headers={
33 "Authorization": "Bearer your-api-key-here",
34 "Content-Type": "application/json"
35 },
36 data=jsonl_data
37)
38
39# Process responses
40for line in response.text.strip().split("\n"):
41 result = json.loads(line)
42 custom_id = result["custom_id"]
43 content = result["response"]["body"]["choices"][0]["message"]["content"]
44 print(f"{custom_id}: {content}")Error Handling
Handle errors gracefully with retry logic and proper exception handling.
Robust Error Handling
1from openai import OpenAI, APIError, RateLimitError, APIConnectionError
2import time
3
4client = OpenAI(
5 api_key="your-api-key-here",
6 base_url="https://api.selamgpt.com/v1"
7)
8
9def chat_with_retry(messages, max_retries=3):
10 for attempt in range(max_retries):
11 try:
12 response = client.chat.completions.create(
13 model="selam-turbo",
14 messages=messages
15 )
16 return response.choices[0].message.content
17
18 except RateLimitError as e:
19 if attempt < max_retries - 1:
20 wait_time = 2 ** attempt # Exponential backoff
21 print(f"Rate limit hit. Waiting {wait_time}s...")
22 time.sleep(wait_time)
23 else:
24 raise
25
26 except APIConnectionError as e:
27 if attempt < max_retries - 1:
28 print(f"Connection error. Retrying...")
29 time.sleep(1)
30 else:
31 raise
32
33 except APIError as e:
34 print(f"API error: {e}")
35 raise
36
37# Usage
38try:
39 result = chat_with_retry([
40 {"role": "user", "content": "Hello!"}
41 ])
42 print(result)
43except Exception as e:
44 print(f"Failed after retries: {e}")Complete Integration Example
A complete example showing multiple features working together.
Multi-Feature Chatbot
1from openai import OpenAI
2
3class SelamChatbot:
4 def __init__(self, api_key):
5 self.client = OpenAI(
6 api_key=api_key,
7 base_url="https://api.selamgpt.com/v1"
8 )
9 self.conversation_history = []
10
11 def chat(self, message, stream=False, translate_to=None):
12 """Send a message and get a response"""
13 self.conversation_history.append({
14 "role": "user",
15 "content": message
16 })
17
18 headers = {}
19 if translate_to:
20 headers["X-Target-Language"] = translate_to
21
22 response = self.client.chat.completions.create(
23 model="selam-plus",
24 messages=self.conversation_history,
25 stream=stream,
26 extra_headers=headers if headers else None
27 )
28
29 if stream:
30 full_response = ""
31 for chunk in response:
32 if chunk.choices[0].delta.content:
33 content = chunk.choices[0].delta.content
34 print(content, end="", flush=True)
35 full_response += content
36 print()
37 assistant_message = full_response
38 else:
39 assistant_message = response.choices[0].message.content
40 print(assistant_message)
41
42 self.conversation_history.append({
43 "role": "assistant",
44 "content": assistant_message
45 })
46
47 return assistant_message
48
49 def reset(self):
50 """Clear conversation history"""
51 self.conversation_history = []
52
53# Usage
54bot = SelamChatbot("your-api-key-here")
55
56# Regular chat
57bot.chat("Hello! Tell me about Ethiopia.")
58
59# Streaming response
60bot.chat("Tell me more about its history.", stream=True)
61
62# With translation
63bot.chat("ሰላም!", translate_to="en")
64
65# Reset conversation
66bot.reset()Common Patterns
Rate Limit Handling
Always implement exponential backoff when handling rate limits. Check theRetry-After header for the recommended wait time.
Context Management
For long conversations, trim older messages to stay within token limits. Keep system prompts and recent context, summarize or remove middle messages.
Streaming Best Practices
Use streaming for interactive applications. Buffer chunks and update UI incrementally. Handle connection errors gracefully with reconnection logic.
API Key Security
Never expose API keys in client-side code. Use environment variables and server-side proxies. Rotate keys regularly and monitor usage for anomalies.
Related Resources
Was this page helpful?