import osfrom openai import OpenAIclient = OpenAI( api_key=os.environ.get("SAMURAI_API_KEY"), base_url="https://www.samuraiapi.in/v1" # Only change from OpenAI)response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is bushido?"} ])print(response.choices[0].message.content)# => "Bushido is the code of ethics followed by Japanese samurai warriors..."
You’ll get a response like:
{ "choices": [{ "message": { "role": "assistant", "content": "Bushido is the ethical code of conduct historically observed by the samurai of Japan..." }, "finish_reason": "stop" }], "usage": { "prompt_tokens": 24, "completion_tokens": 87, "total_tokens": 111 }}
stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Tell me a haiku about samurai."}], stream=True)for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True)
from openai import OpenAIclient = OpenAI( api_key="sk-samurai-YOUR_KEY", base_url="https://api.samuraiapi.in/v1")response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello! What can you do?"}])print(response.choices[0].message.content)