调用库(Libraries)
<p>[TOC]</p>
<h1>调用案例</h1>
<p>官方目前只提供两种语言的调用库,分别为:Node.js与Python,其它语言调用需要自己写代码,或者使用别人写好的,我们给大家整理了一些社区库供大家参考。</p>
<h2>Node.js 版本,基于官方提供的OpenAI库</h2>
<pre><code>const {OpenAI} = require('openai')
const openai = new OpenAI({
apiKey: '你的密钥',
baseURL: 'https://api.hellogptworld.com/v1'
})
async function main() {
const completion = await openai.chat.completions.create({
model: 'gpt-3.5-turbo-0125',
messages: [{ role: 'user', content: 'Hello, Nice to meet you' }],
});
console.log(completion);
}
main();</code></pre>
<h2>Python 版本,基于官方提供的OpenAI库</h2>
<h3>非流式输出</h3>
<pre><code>from openai import OpenAI
client = OpenAI(
api_key = '你的密钥',
base_url = 'https://api.hellogptworld.com/v1'
)
completion = client.chat.completions.create(
model = &quot;gpt-3.5-turbo-0125&quot;,
messages = [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello, Nice to meet you&quot;}],
)
print(completion)</code></pre>
<h3>流式输出</h3>
<pre><code>from openai import OpenAI
client = OpenAI(
api_key = '你的密钥',
base_url = 'https://api.hellogptworld.com/v1'
)
stream = client.chat.completions.create(
model=&quot;gpt-3.5-turbo&quot;,
messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello, Nice to meet you&quot;}],
stream=True,
)
for chunk in stream:
print(chunk)
</code></pre>
<h2>Python 版本,基于requests库</h2>
<h3>非流式输出</h3>
<p>文本模型</p>
<pre><code>import requests
data = {
&quot;model&quot;: &quot;gpt-3.5-turbo&quot;,
&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello, Nice to meet you&quot;}],
&quot;stream&quot;: False
}
url = &quot;https://api.hellogptworld.com/v1/chat/completions&quot;
headers = {
&quot;Content-Type&quot;: &quot;application/json&quot;,
&quot;Authorization&quot;: &quot;Bearer 你的密钥&quot;
}
response = requests.post(url, json=data, headers=headers)
print(response.text)</code></pre>
<p>视觉模型</p>
<pre><code>import base64
import requests
def image_to_base64(image_path):
with open(image_path, &quot;rb&quot;) as image_file:
encoded_string = base64.b64encode(image_file.read())
return encoded_string.decode('utf-8')
image = 'test.jpg';
base64 = image_to_base64(image)
data = {
&quot;model&quot;: &quot;gpt-4o&quot;,
&quot;max_tokens&quot;: 800,
&quot;temperature&quot;: 0.2,
&quot;top_p&quot;: 1,
&quot;n&quot;: 1,
&quot;presence_penalty&quot;: 0,
&quot;frequency_penalty&quot;: 0,
&quot;messages&quot;: [
{
&quot;role&quot;: &quot;user&quot;,
&quot;content&quot;:[
{
&quot;type&quot;:&quot;text&quot;,
&quot;text&quot;: &quot;图片描述了什么&quot;
},
{
&quot;type&quot;: &quot;image_url&quot;,
&quot;image_url&quot;: {
&quot;url&quot;: f&quot;data:image/jpeg;base64,{base64}&quot;
}
}
]
}
],
&quot;stream&quot;: True
}
url = &quot;https://api.hellogptworld.com/v1/chat/completions&quot;
headers = {
&quot;Content-Type&quot;: &quot;application/json&quot;,
&quot;Authorization&quot;: &quot;Bearer 你的密钥&quot;
}
response = requests.post(url, json=data, headers=headers, timeout=(200, 600))
for line in response.iter_lines():
if line:
print(line.decode('UTF-8'))</code></pre>
<h3>流式输出</h3>
<p>文本模型</p>
<pre><code>import requests
data = {
&quot;model&quot;: &quot;gpt-3.5-turbo&quot;,
&quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello, Nice to meet you&quot;}],
&quot;stream&quot;: True
}
url = &quot;https://api.hellogptworld.com/v1/chat/completions&quot;
headers = {
&quot;Content-Type&quot;: &quot;application/json&quot;,
&quot;Authorization&quot;: &quot;Bearer 你的密钥&quot;
}
response = requests.post(url, json=data, headers=headers)
for line in response.iter_lines():
if line:
print(line.decode('UTF-8'))</code></pre>
<p>视觉模型</p>
<pre><code>import base64
import requests
def image_to_base64(image_path):
with open(image_path, &quot;rb&quot;) as image_file:
encoded_string = base64.b64encode(image_file.read())
return encoded_string.decode('utf-8')
image = 'test.jpg';
base64 = image_to_base64(image)
data = {
&quot;model&quot;: &quot;gpt-4o&quot;,
&quot;max_tokens&quot;: 800,
&quot;temperature&quot;: 0.2,
&quot;top_p&quot;: 1,
&quot;n&quot;: 1,
&quot;presence_penalty&quot;: 0,
&quot;frequency_penalty&quot;: 0,
&quot;messages&quot;: [
{
&quot;role&quot;: &quot;user&quot;,
&quot;content&quot;:[
{
&quot;type&quot;:&quot;text&quot;,
&quot;text&quot;: &quot;图片描述了什么&quot;
},
{
&quot;type&quot;: &quot;image_url&quot;,
&quot;image_url&quot;: {
&quot;url&quot;: f&quot;data:image/jpeg;base64,{base64}&quot;
}
}
]
}
],
&quot;stream&quot;: True
}
url = &quot;https://api.hellogptworld.com/v1/chat/completions&quot;
headers = {
&quot;Content-Type&quot;: &quot;application/json&quot;,
&quot;Authorization&quot;: &quot;Bearer 你的密钥&quot;
}
response = requests.post(url, json=data, headers=headers, timeout=(200, 600))
print(response.text)</code></pre>
<h2>Java 版本</h2>
<h3>实体封装、依赖jar包引入</h3>
<pre><code>&lt;dependency&gt;
&lt;groupId&gt;cn.hutool&lt;/groupId&gt;
&lt;artifactId&gt;hutool-all&lt;/artifactId&gt;
&lt;version&gt;5.8.22&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
<pre><code>ChatCompletion chat = new ChatCompletion();
chat.setModel(&quot;gpt-3.5-turbo&quot;);
chat.setStream(false);
List&lt;Message&gt; messages = new ArrayList&lt;&gt;();
Message message = new Message();
message.setRole(&quot;user&quot;);
message.setContent(&quot;Hello, Nice to meet you&quot;);
messages.add(message);
chat.setMessages(messages);</code></pre>
<h3>Http 非流式输出</h3>
<pre><code>String requestBody = JSONUtil.toJsonStr(chat);
String body = HttpRequest.post(&quot;https://api.hellogptworld.com/v1/chat/completions&quot;)
.bearerAuth(&quot;你的密钥&quot;)
.contentType(ContentType.JSON.getValue())
.timeout(30000)
.body(requestBody)
.execute().body();
System.out.println(body);</code></pre>
<h3>Http 流式输出</h3>
<pre><code>String requestBody = JSONUtil.toJsonStr(chat);
InputStream inputStream = HttpRequest.post(&quot;https://api.hellogptworld.com/v1/chat/completions&quot;)
.bearerAuth(&quot;你的密钥&quot;)
.contentType(ContentType.JSON.getValue())
.timeout(30000)
.body(requestBody)
.execute().bodyStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}</code></pre>
<h3>SseEmitter 流式输出</h3>
<pre><code>&lt;dependency&gt;
&lt;groupId&gt;com.squareup.okhttp3&lt;/groupId&gt;
&lt;artifactId&gt;okhttp-sse&lt;/artifactId&gt;
&lt;version&gt;3.14.9&lt;/version&gt;
&lt;/dependency&gt;</code></pre>
<pre><code>@PostMapping(&quot;/stream&quot;)
public SseEmitter stream(@RequestBody ChatCompletion chat) {
SseEmitter sseEmitter = new SseEmitter(-1L);
SseStreamHandler streamHandler = new SseStreamHandler(sseEmitter);
EventSource.Factory factory = OpenAiUtils.init();
chat.setUser(NanoId.randomNanoId());
String requestBody = JSONUtil.toJsonStr(chat);
Request res = OpenAiUtils.requestChat(requestBody);
factory.newEventSource(res, streamHandler);
return sseEmitter;
}</code></pre>
<pre><code>public class OpenAiUtils {
public static EventSource.Factory init() {
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.connectTimeout(300000, TimeUnit.MILLISECONDS);
client.writeTimeout(300000, TimeUnit.MILLISECONDS);
client.readTimeout(300000, TimeUnit.MILLISECONDS);
return EventSources.createFactory(client.build());
}
public static Request requestChat(String requestBody) {
Request.Builder builder = new Request.Builder()
.url(&quot;https://api.hellogptworld.com/v1/chat/completions&quot;)
.post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody))
.header(Header.AUTHORIZATION.getValue(), &quot;Bearer 你的密钥&quot;);
return builder.build();
}
}</code></pre>
<pre><code>@RequiredArgsConstructor
public class SseStreamHandler extends EventSourceListener {
private final SseEmitter sseEmitter;
@Override
public void onOpen(EventSource eventSource, Response response) {
System.out.println(&quot;sseEmitter onOpen start&quot;);
}
@Override
public void onClosed(EventSource eventSource) {
eventSource.cancel();
}
public void onMsg(String message) {
sseEmitter.send(message);
}
public void onComplete() {
sseEmitter.complete();
}
@Override
public void onEvent(EventSource eventSource, String id, String type, String res) {
System.out.println(&quot;sseEmitter onEvent res:{}&quot;, res);
}
@Override
public void onFailure(EventSource eventSource, Throwable throwable, Response res) {
System.out.println(&quot;sseEmitter onFailure res:{}&quot;, res);
}</code></pre>
<h1>其它语言社区库</h1>
<p>下面这些库由更广泛的开发人员社区构建和维护,仅供参考。请注意,Talk-Bot不会验证这些项目的正确性或安全性。</p>
<h2>C# / .NET[](<a href="https://openai.xiniushu.com/docs/libraries#c--net">https://openai.xiniushu.com/docs/libraries#c--net</a> "C# / .NET的直接链接")</h2>
<ul>
<li><a href="https://github.com/betalgo/openai">Betalgo.OpenAI.GPT3</a> by <a href="https://github.com/betalgo">Betalgo</a></li>
</ul>
<h2>Crystal[](<a href="https://openai.xiniushu.com/docs/libraries#crystal">https://openai.xiniushu.com/docs/libraries#crystal</a> "Crystal的直接链接")</h2>
<ul>
<li><a href="https://github.com/sferik/openai-crystal">Openai-Crystal</a> by <a href="https://github.com/sferik">Sferik</a></li>
</ul>
<h2>Go[](<a href="https://openai.xiniushu.com/docs/libraries#go">https://openai.xiniushu.com/docs/libraries#go</a> "Go的直接链接")</h2>
<ul>
<li><a href="https://github.com/sashabaranov/go-gpt3">Go-GPT3</a> by <a href="https://github.com/sashabaranov">sashabaranov</a></li>
</ul>
<h2>Java[](<a href="https://openai.xiniushu.com/docs/libraries#java">https://openai.xiniushu.com/docs/libraries#java</a> "Java的直接链接")</h2>
<ul>
<li><a href="https://github.com/TheoKanning/openai-java">openai-java</a> by <a href="https://github.com/TheoKanning">Theo Kanning</a></li>
<li><a href="https://github.com/PlexPt/chatgpt-java">chatgpt-java</a> by <a href="https://github.com/PlexPt">PlexPt</a></li>
<li><a href="https://github.com/Grt1228/chatgpt-java">chatgpt-java</a> by <a href="https://github.com/Grt1228">Grt1228</a></li>
</ul>
<h2>Kotlin[](<a href="https://openai.xiniushu.com/docs/libraries#kotlin">https://openai.xiniushu.com/docs/libraries#kotlin</a> "Kotlin的直接链接")</h2>
<ul>
<li><a href="https://github.com/Aallam/openai-kotlin">openai-kotlin</a> by <a href="https://github.com/Aallam">Mouaad Aallam</a></li>
</ul>
<h2>Node.js[](<a href="https://openai.xiniushu.com/docs/libraries#nodejs">https://openai.xiniushu.com/docs/libraries#nodejs</a> "Node.js的直接链接")</h2>
<ul>
<li><a href="https://www.npmjs.com/package/openai-api">openai-api</a> by <a href="https://github.com/Njerschow">Njerschow</a></li>
<li><a href="https://www.npmjs.com/package/openai-api-node">OpenAI-API-Node</a> by <a href="https://github.com/erlapso">Erlapso</a></li>
<li><a href="https://www.npmjs.com/package/gpt-x">GPT-X</a> by <a href="https://github.com/ceifa">CEIFA</a></li>
<li><a href="https://www.npmjs.com/package/gpt3">GPT3</a> by <a href="https://github.com/poteat">Poteat</a></li>
<li><a href="https://www.npmjs.com/package/gpts">GPTS</a> by <a href="https://github.com/thencc">thencc</a></li>
<li><a href="https://www.npmjs.com/package/@dalenguyen/openai">@dalenguyen/OpenAI</a> by <a href="https://github.com/dalenguyen">Dalenguyen</a></li>
<li><a href="https://github.com/tectalichq/public-openai-client-js">Tectalic/OpenAI</a> by <a href="https://tectalic.com/">tectalic</a></li>
</ul>
<h2>PHP[](<a href="https://openai.xiniushu.com/docs/libraries#php">https://openai.xiniushu.com/docs/libraries#php</a> "PHP的直接链接")</h2>
<ul>
<li><a href="https://packagist.org/packages/orhanerday/open-ai">Orhanerday/Open-AI</a> by <a href="https://github.com/orhanerday">Orhanerday</a></li>
<li><a href="https://github.com/tectalichq/public-openai-client-php">Tectalic/OpenAI</a> by <a href="https://tectalic.com/">tectalic</a></li>
</ul>
<h2>Python[](<a href="https://openai.xiniushu.com/docs/libraries#python">https://openai.xiniushu.com/docs/libraries#python</a> "Python的直接链接")</h2>
<ul>
<li><a href="https://www.othersideai.com/">OthersideAI</a> by <a href="https://github.com/OthersideAI/chronology">OthersideAI</a></li>
</ul>
<h2>R[](<a href="https://openai.xiniushu.com/docs/libraries#r">https://openai.xiniushu.com/docs/libraries#r</a> "R的直接链接")</h2>
<ul>
<li><a href="https://github.com/ben-aaron188/rgpt3">RGPT3</a> by <a href="https://github.com/ben-aaron188">Ben-Aaron188</a></li>
</ul>
<h2>Ruby[](<a href="https://openai.xiniushu.com/docs/libraries#ruby">https://openai.xiniushu.com/docs/libraries#ruby</a> "Ruby的直接链接")</h2>
<ul>
<li><a href="https://github.com/nileshtrivedi">Nileshtrivedi</a> by <a href="https://github.com/nileshtrivedi/openai/">OpenAI</a></li>
<li><a href="https://github.com/alexrudall">Alexrudall</a> by <a href="https://github.com/alexrudall/ruby-openai">Ruby-Openai</a></li>
</ul>
<h2>Scala[](<a href="https://openai.xiniushu.com/docs/libraries#scala">https://openai.xiniushu.com/docs/libraries#scala</a> "Scala的直接链接")</h2>
<ul>
<li><a href="https://github.com/cequence-io/openai-scala-client">OpenAI-Scala-Client</a> by <a href="https://github.com/cequence-io">Cequence-IO</a></li>
</ul>
<h2>Swift[](<a href="https://openai.xiniushu.com/docs/libraries#swift">https://openai.xiniushu.com/docs/libraries#swift</a> "Swift的直接链接")</h2>
<ul>
<li><a href="https://github.com/dylanshine/openai-kit">OpenAIKit</a> by <a href="https://github.com/dylanshine">dylanshine</a></li>
</ul>
<h2>Unity[](<a href="https://openai.xiniushu.com/docs/libraries#unity">https://openai.xiniushu.com/docs/libraries#unity</a> "Unity的直接链接")</h2>
<ul>
<li><a href="https://github.com/hexthedev/OpenAi-Api-Unity">OpenAi-Api-Unity</a> by <a href="https://github.com/hexthedev">hexthedev</a></li>
</ul>
<h2>Unreal Engine[](<a href="https://openai.xiniushu.com/docs/libraries#unreal-engine">https://openai.xiniushu.com/docs/libraries#unreal-engine</a> "Unreal Engine的直接链接")</h2>
<ul>
<li><a href="https://github.com/KellanM/OpenAI-Api-Unreal">OpenAI-API-Unreal</a> by <a href="https://github.com/KellanM">KellanM</a></li>
</ul>