openai-python本地使用
环境
旧版本转换
embeddings_utils
import openai
import numpy as np
my_client = openai.OpenAI(
base_url='http://localhost:11434/v1/',
api_key='ollama', # required but ignored
)
def get_embedding(text, engine="text-embedding-ada-002"):
text = text.replace("\n", " ")
return my_client.embeddings.create(input=[text], model=engine).data[0].embedding
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
基本使用
import openai
my_client = openai.OpenAI(
base_url='http://localhost:11434/v1/',
api_key='ollama', # required but ignored
)
token_len = 1024
temperature = 0
# 一问一答
response = my_client.chat.completions.create(
model='qwen2.5:0.5b',
messages=[
{
'role': 'user',
'content': "I have a question",
}
],
temperature=temperature,
max_tokens=token_len
)
ret = response.choices[0].message.content
print(ret)
# stream 适用于大数据
stream = client.chat.completions.create(
model='qwen2.5:7b',
messages=[
{
'role': 'user',
'content': "I have a question",
}
],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
if chunk.usage is not None:
print('prompt_tokens', chunk.usage.prompt_tokens)
print('completion_tokens', chunk.usage.completion_tokens)
print('total_tokens', chunk.usage.total_tokens)
本文来自博客园,作者:漫漫长夜何时休,转载请注明原文链接:https://www.cnblogs.com/ag-chen/p/18452141
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律