借助ollama调用llama3本地大模型

模型拉取:

image-20251007101442971

1. 文章续写

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import ollama

# 1. 配置远程 Ollama 服务器地址
# 格式: http://<your_server_ip>:<port>
ollama_client = ollama.Client(host='http://192.168.100.135:11434')

# 2. 定义你的输入
input_text = "在一个阳光明媚的早晨,Alice决定去森林里探险。她走着走着,突然发现了一条小路。"

# 3. 调用 generate 方法与远程模型交互
# 'llama3.1:8b' 是你在远程服务器上已经 pull 下来的模型名称
try:
response = ollama_client.generate(
model="llama3.2:1b",
prompt=input_text,
# 你可以添加其他生成参数,如 temperature, max_tokens 等
options={
"temperature": 0.7,
"max_tokens": 256,
}
)

# 4. 提取并打印生成的文本
generated_text = response['response']
print("--- 生成的故事 ---")
print(generated_text)

except ollama.ResponseError as e:
print(f"API 调用失败: {e.error}")
print(f"状态码: {e.status_code}")
except Exception as e:
print(f"发生未知错误: {e}")

输出:

1
2
3
4
5
6
7
她一边走路,一边检查 surroundings,看看是否有任何危险或不寻常的物体。虽然空气是清新,但下雨从前几天来一直持续着,树叶都湿透了。她注意到道路上有几个散落在处方的木箱和包裹,似乎它们可能被忘记了去的地方。

Alice决定继续向前走,寻找一个可靠的目的地。她的步伐慢慢,心脏轻快地跳动,她不愿意让自己的注意力分开。有时她会停下来 admire一下树林的美丽,或者是看看下面的野生动物。

随着路线的逐渐变化,Alice发现森林变得越来越暗暗隐蔽。她感到一种感兴趣和紧张,因为她还没有找到目的地。偶尔,她会想起自己去哪儿了,为什么总是回家,但不确定理由。

下一道关头里,路面变成湿滑的石 pavement,她注意到有一些小草块被用来作为安全线。这让Alice感到一种安心感,知道她可以安全地走到目的地。

2. 创意文本生成

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import ollama

# 初始化 Ollama 客户端
ollama_client = ollama.Client(host='http://192.168.100.135:11434')

max_length = 100
input_text = "写一首关于爱情的诗"

try:
response = ollama_client.generate(
model="llama3.1:8b",
prompt=input_text,
options={
"temperature": 0.7,
"max_tokens": max_length,
}
)
generated_text = response['response']
print(generated_text)
except ollama.ResponseError as e:
print(f"API 调用失败: {e.error}")
except Exception as e:
print(f"发生未知错误: {e}")

输出:

1
2
3
4
5
6
7
8
9
10
爱如风起,轻松柔美
温暖心间,让人难以割舍
爱如雨落,细碎滴溜
浇灌希望,使生活变甜美

爱如花开,色彩绚丽
照亮整个世界,让每个人都有光明

爱如星辉,闪耀清冷
指引方向,让人走不迷路

3. 集成ai搜索

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import requests
import ollama
import json

# 初始化 Ollama 客户端
ollama_client = ollama.Client(host='http://192.168.100.135:11434')

# 秘塔搜索API配置
METASO_API_KEY = 'mk-xxx'
METASO_BASE_URL = 'https://metaso.cn/api/v1/search'

# 检索相关文档的函数
def retrieve_documents(query):
try:
headers = {
'Authorization': f'Bearer {METASO_API_KEY}',
'Accept': 'application/json',
'Content-Type': 'application/json'
}
payload = {
"q": query,
"scope": "webpage"
}

response = requests.post(METASO_BASE_URL, json=payload, headers=headers)
response.raise_for_status()
data = response.json()

# 提取搜索结果中的内容
documents = []
if 'webpages' in data:
for item in data['webpages'][:10]: # 限制前10个结果
if 'snippet' in item:
documents.append(item['snippet'])
elif 'title' in item:
documents.append(item['title'])

return documents
except Exception as e:
print(f"Error retrieving documents: {e}")
return []

# 生成答案的函数
def generate_answer(query, documents):
# 限制检索到的文档数量
documents = documents[:3]
context = "\n\n".join(documents) + "\n\nQuestion: " + query + "\nAnswer:"

# 使用远程 Ollama 模型生成答案
try:
response = ollama_client.generate(
model="llama3.1:8b",
prompt=context,
options={
"temperature": 0.7,
"max_tokens": 512,
}
)
answer = response['response']
return answer
except ollama.ResponseError as e:
return f"API 调用失败: {e.error}"
except Exception as e:
return f"发生未知错误: {e}"

# 主函数
def main():
query = "What is the capital of France?"
documents = retrieve_documents(query)
if documents:
answer = generate_answer(query, documents)
print("Question:", query)
print("Retrieved documents:", len(documents))
print("Answer:", answer)
else:
print("No documents retrieved.")

if __name__ == "__main__":
main()

输出:

1
2
3
Question: What is the capital of France?
Retrieved documents: 10
Answer: The capital of France is Paris.

本站由 卡卡龙 使用 Stellar 1.29.1主题创建

本站访问量 次. 本文阅读量 次.