🔨
PythonでDeepSeekApiを叩いてみる
話題のDeepSeekを叩くまでの記事です。
venvで仮想環境を作成して叩くところまでやってみたいと思います。
仮想環境の作成
作りたいところのdirの直下で
python -m venv venv
有効化する
source venv/bin/activate
すると先頭にこんな感じでつく
(venv)
終了する時は
deactivate
公式を確認
# Please install OpenAI SDK first: `pip3 install openai`
from openai import OpenAI
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hello"},
],
stream=False
)
print(response.choices[0].message.content)
上記のような感じで叩けるみたい
venvを有効化してopenaiをまずはvenv環境にインストール
有効化したら
以下のコマンドを
pip install openai
あとはapi_keyを.env
ファイルを使用して、読み取っていきたいのでdotenv
というモジュールも入れたい
pip install dotenv
なんかエラーが出た。
pip install dotenv
Collecting dotenv
Using cached dotenv-0.0.5.tar.gz (2.4 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... done
Installing backend dependencies ... error
error: subprocess-exited-with-error
× pip subprocess to install backend dependencies did not run successfully.
│ exit code: 1
╰─> [32 lines of output]
Collecting distribute
Using cached distribute-0.7.3.zip (145 kB)
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'done'
Preparing metadata (pyproject.toml): started
Preparing metadata (pyproject.toml): finished with status 'error'
error: subprocess-exited-with-error
× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [6 lines of output]
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'dist_info'
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
調べてみると、今はdotenv
じゃなくてpython-dotenv
を入れるみたい
pip install python-dotenv
改良後
test.py
# Please install OpenAI SDK first: `pip3 install openai`
from dotenv import load_dotenv
import os
from openai import OpenAI
load_dotenv()
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
client = OpenAI(api_key=DEEPSEEK_API_KEY,
base_url="https://api.deepseek.com")
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hello"},
],
stream=False
)
print(response.choices[0].message.content)
.env
DEEPSEEK_API_KEY=自分の発行したAPI_KEY
実行してみる
% python test.py
Hello! How can I assist you today? 😊
レスポンスが返ってきた。
簡単にapiを叩くことは可能ですので、こんな感じ使用準備は完了です。
今後は別記事(もしくは追記)で、JSON OUTPUTにつて試してみたいと思っています。
Discussion