Examples & Cookbook
This page provides practical examples and recipes for using OpenTyphoon.ai in various applications. Each example comes with complete, runnable code to help you get started quickly.
Basic Examples
from openai import OpenAI
client = OpenAI( api_key="<YOUR_API_KEY>", base_url="https://api.opentyphoon.ai/v1")
response = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=[ {"role": "user", "content": "กรุงเทพมหานครเป็นเมืองหลวงของประเทศอะไร?"} ])
print(response.choices[0].message.content)
from openai import OpenAI
client = OpenAI( api_key="<YOUR_API_KEY>", base_url="https://api.opentyphoon.ai/v1")
response = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=[ {"role": "system", "content": "You are a translation assistant that translates English to Thai."}, {"role": "user", "content": "Translate the following text to Thai: 'I would like to visit Thailand someday. What are the best places to visit?'"} ])
print(response.choices[0].message.content)
from openai import OpenAI
client = OpenAI( api_key="<YOUR_API_KEY>", base_url="https://api.opentyphoon.ai/v1")
review = "ร้านนี้อาหารอร่อยมาก บริการดีเยี่ยม แต่ราคาค่อนข้างสูง"
response = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=[ {"role": "system", "content": "You are a sentiment analysis assistant. Analyze the sentiment of the given text and respond with: POSITIVE, NEGATIVE, or NEUTRAL, followed by a brief explanation."}, {"role": "user", "content": f"Analyze the sentiment of this review: '{review}'"} ], temperature=0.1 # Lower temperature for more deterministic responses)
print(response.choices[0].message.content)
Advanced Use Cases
from openai import OpenAI
client = OpenAI( api_key="<YOUR_API_KEY>", base_url="https://api.opentyphoon.ai/v1")
# This example shows a multi-turn conversation with the modelconversation = [ {"role": "system", "content": "You are a helpful assistant specialized in Thai cuisine. Provide detailed and accurate information about Thai dishes, ingredients, and cooking methods."}, {"role": "user", "content": "วิธีทำต้มยำกุ้งมีอะไรบ้าง?"}]
# First turnresponse = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=conversation)
assistant_response = response.choices[0].message.contentprint(f"Assistant: {assistant_response}")
# Add the assistant's response to the conversationconversation.append({"role": "assistant", "content": assistant_response})
# Add user's follow-up questionconversation.append({"role": "user", "content": "แล้วถ้าไม่มีน้ำพริกเผาจะทำยังไง?"})
# Second turnresponse = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=conversation)
print(f"Assistant: {response.choices[0].message.content}")
from openai import OpenAIimport json
client = OpenAI( api_key="<YOUR_API_KEY>", base_url="https://api.opentyphoon.ai/v1")
prompt = """You are a helpful assistant that extracts information from text into structured JSON format.Extract the following information from the text below and return it as a valid JSON object with these fields:- name: the person's name- location: the location mentioned- date: any date mentioned- activities: an array of activities mentioned
Text: "สวัสดีครับ ผมชื่อสมชาย จะไปเที่ยวเชียงใหม่วันที่ 15 มกราคม 2567 ผมวางแผนจะไปเดินดอยสุเทพ ไปวัดพระธาตุดอยสุเทพ และไปกินข้าวซอย"
Important: Respond ONLY with the JSON object, with NO additional text."""
response = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=[{"role": "user", "content": prompt}], temperature=0.1, # Lower temperature for more deterministic and structured responses)
try: # Parse the response as JSON structured_data = json.loads(response.choices[0].message.content) print(json.dumps(structured_data, indent=2, ensure_ascii=False))except json.JSONDecodeError as e: print(f"Error parsing JSON: {e}") print("Raw response:", response.choices[0].message.content)
from openai import OpenAI
client = OpenAI( api_key="<YOUR_API_KEY>", base_url="https://api.opentyphoon.ai/v1")
long_text = """การท่องเที่ยวแห่งประเทศไทย (ททท.) รายงานสถานการณ์ท่องเที่ยวในช่วงครึ่งปีแรกของปี 2567 โดยพบว่ามีนักท่องเที่ยวต่างชาติเดินทางเข้ามาเที่ยวในประเทศไทยจำนวน 18.26 ล้านคน เพิ่มขึ้น 32.4% เมื่อเทียบกับช่วงเดียวกันของปีที่แล้ว สร้างรายได้กว่า 9.6 แสนล้านบาท โดยนักท่องเที่ยวจีนยังคงเป็นกลุ่มที่มีจำนวนมากที่สุด ตามมาด้วยนักท่องเที่ยวจากมาเลเซีย อินเดีย เกาหลีใต้ และรัสเซีย การท่องเที่ยวภายในประเทศก็มีแนวโน้มเติบโตเช่นกัน มีการเดินทางท่องเที่ยวภายในประเทศจำนวน 144.12 ล้านทริป สร้างรายได้ 6.8 แสนล้านบาท เพิ่มขึ้น 11% จากปีก่อน ททท. คาดการณ์ว่าตลอดทั้งปี 2567 จะมีนักท่องเที่ยวต่างชาติเดินทางมาไทยประมาณ 37.5 ล้านคน สร้างรายได้รวมทั้งสิ้นประมาณ 3.1 ล้านล้านบาท"""
response = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=[ {"role": "system", "content": "You are a summarization assistant. Provide concise summaries of the given text in Thai."}, {"role": "user", "content": f"โปรดสรุปข้อความต่อไปนี้ให้กระชับ (ไม่เกิน 3 ประโยค):\n\n{long_text}"} ], max_tokens=150, temperature=0.5)
print(response.choices[0].message.content)
from openai import OpenAI
client = OpenAI( api_key="<YOUR_API_KEY>", base_url="https://api.opentyphoon.ai/v1")
stream = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=[ {"role": "user", "content": "ให้คำแนะนำ 5 ข้อสำหรับการเรียนภาษาไทยให้มีประสิทธิภาพ"} ], stream=True, max_tokens=512)
# Process the streaming responsefor chunk in stream: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content, end="", flush=True)print() # Add a newline at the end
Integration Examples
from flask import Flask, request, jsonify, render_template_stringfrom openai import OpenAIimport os
app = Flask(__name__)
# Initialize OpenAI clientclient = OpenAI( api_key=os.environ.get("OPENTYPHOON_API_KEY"), base_url="https://api.opentyphoon.ai/v1")
# Simple HTML template for the chat interfaceHTML_TEMPLATE = '''<!DOCTYPE html><html><head> <title>Thai Chatbot</title> <style> body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; } #chat-container { height: 400px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; } .user-message { background-color: #e6f7ff; padding: 8px; border-radius: 10px; margin: 5px 0; text-align: right; } .assistant-message { background-color: #f0f0f0; padding: 8px; border-radius: 10px; margin: 5px 0; text-align: left; } #user-input { width: 85%; padding: 8px; } button { padding: 8px 15px; } </style></head><body> <h1>Thai Language Assistant</h1> <div id="chat-container"></div> <div> <input type="text" id="user-input" placeholder="Type your message..." /> <button onclick="sendMessage()">Send</button> </div> <script> function addMessageToChat(content, isUser) { const chatContainer = document.getElementById('chat-container'); const messageDiv = document.createElement('div'); messageDiv.className = isUser ? 'user-message' : 'assistant-message'; messageDiv.innerText = content; chatContainer.appendChild(messageDiv); chatContainer.scrollTop = chatContainer.scrollHeight; }
async function sendMessage() { const userInput = document.getElementById('user-input'); const userMessage = userInput.value.trim();
if (!userMessage) return;
addMessageToChat(userMessage, true); userInput.value = '';
// Show thinking indicator const thinkingDiv = document.createElement('div'); thinkingDiv.className = 'assistant-message'; thinkingDiv.id = 'thinking'; thinkingDiv.innerText = 'กำลังคิด...'; document.getElementById('chat-container').appendChild(thinkingDiv);
try { const response = await fetch('/chat', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({message: userMessage}) });
const data = await response.json();
// Remove thinking indicator document.getElementById('thinking').remove();
addMessageToChat(data.response, false); } catch (error) { document.getElementById('thinking').remove(); addMessageToChat('เกิดข้อผิดพลาด กรุณาลองใหม่อีกครั้ง', false); console.error('Error:', error); } }
// Press Enter to send document.getElementById('user-input').addEventListener('keyup', function(event) { if (event.key === 'Enter') { sendMessage(); } }); </script></body></html>'''
@app.route('/')def index(): return render_template_string(HTML_TEMPLATE)
@app.route('/chat', methods=['POST'])def chat(): user_message = request.json.get('message', '')
try: response = client.chat.completions.create( model="typhoon-v2-70b-instruct", messages=[ {"role": "system", "content": "คุณเป็นผู้ช่วยที่เป็นมิตรและให้ข้อมูลที่เป็นประโยชน์แก่ผู้ใช้ คุณจะตอบคำถามเป็นภาษาไทยที่สุภาพและเข้าใจง่าย"}, {"role": "user", "content": user_message} ], max_tokens=512, temperature=0.7 )
return jsonify({"response": response.choices[0].message.content}) except Exception as e: return jsonify({"error": str(e)}), 500
if __name__ == '__main__': app.run(debug=True, port=5000)
import type { NextApiRequest, NextApiResponse } from 'next';import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENTYPHOON_API_KEY as string, baseURL: 'https://api.opentyphoon.ai/v1',});
type ResponseData = { response?: string; error?: string;};
export default async function handler( req: NextApiRequest, res: NextApiResponse<ResponseData>) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); }
const { message } = req.body;
if (!message) { return res.status(400).json({ error: 'Message is required' }); }
try { const completion = await openai.chat.completions.create({ model: 'typhoon-v2-70b-instruct', messages: [ { role: 'system', content: 'คุณเป็นผู้ช่วยที่เป็นมิตรและให้ข้อมูลที่เป็นประโยชน์แก่ผู้ใช้ คุณจะตอบคำถามเป็นภาษาไทยที่สุภาพและเข้าใจง่าย', }, { role: 'user', content: message }, ], max_tokens: 512, temperature: 0.7, });
res.status(200).json({ response: completion.choices[0].message.content }); } catch (error) { console.error('Error calling OpenTyphoon API:', error); res.status(500).json({ error: 'Error processing your request' }); }}
import { useState, useRef, useEffect } from 'react';
type Message = { content: string; isUser: boolean;};
export default function Home() { const [input, setInput] = useState(''); const [messages, setMessages] = useState<Message[]>([]); const [isLoading, setIsLoading] = useState(false); const messagesEndRef = useRef<HTMLDivElement>(null);
const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); };
useEffect(scrollToBottom, [messages]);
const handleSubmit = async (e: React.FormEvent) => { e.preventDefault();
if (!input.trim()) return;
const userMessage = input; setInput('');
// Add user message to chat setMessages((prev) => [...prev, { content: userMessage, isUser: true }]); setIsLoading(true);
try { const response = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: userMessage }), });
const data = await response.json();
if (response.ok) { setMessages((prev) => [ ...prev, { content: data.response || 'ไม่มีข้อความตอบกลับ', isUser: false }, ]); } else { setMessages((prev) => [ ...prev, { content: data.error || 'เกิดข้อผิดพลาด', isUser: false }, ]); } } catch (error) { setMessages((prev) => [ ...prev, { content: 'เกิดข้อผิดพลาดในการเชื่อมต่อ', isUser: false }, ]); console.error('Error:', error); } finally { setIsLoading(false); } };
return ( <div className="max-w-2xl mx-auto p-4"> <h1 className="text-2xl font-bold mb-4">Thai Language Chat Assistant</h1>
<div className="bg-gray-100 rounded-lg p-4 h-96 overflow-y-auto mb-4"> {messages.map((msg, index) => ( <div key={index} className={`p-2 rounded-lg mb-2 ${ msg.isUser ? 'bg-blue-100 ml-auto text-right' : 'bg-white' } max-w-[80%] ${msg.isUser ? 'ml-auto' : 'mr-auto'}`} > {msg.content} </div> ))} {isLoading && ( <div className="bg-white p-2 rounded-lg mb-2 max-w-[80%]"> กำลังคิด... </div> )} <div ref={messagesEndRef} /> </div>
<form onSubmit={handleSubmit} className="flex"> <input type="text" value={input} onChange={(e) => setInput(e.target.value)} placeholder="พิมพ์ข้อความที่นี่..." className="flex-grow p-2 border rounded-l" disabled={isLoading} /> <button type="submit" className="bg-blue-500 text-white p-2 rounded-r" disabled={isLoading} > ส่ง </button> </form> </div> );}