[TOC]
# Langchain-初探01
提醒:使用OPENAI的ChatGPT需要課金
## Langchaine官網
https://python.langchain.com/docs/get_started/installation
## PIP安裝
以下程式範例皆使用Python完成
```python
pip install langchain
pip install langchain-cli
pip install langchain_community
pip install langchain-core
pip install langchain-experimental
pip install langchain-openai
```
## OPENAI-ChatGPT(online)
### 準備API KEY
https://platform.openai.com/account/api-keys
Before you create API KEY, would be asked to completed "you are human". A silly game
![creat new api key](https://hackmd.io/_uploads/BkQWJ59Rp.png)
### API價錢
https://openai.com/pricing
### 加值
https://platform.openai.com/account/billing/overview
![加值](https://hackmd.io/_uploads/r1qf9PlkR.png)
### 準備程式碼
* 基本問答
預設模型:gpt-3.5-turbo
```python=
from langchain_openai import ChatOpenAI
OPENAI_API_KEY="sk-YOUR API KEY"
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
print(llm.invoke("Can you read or write in Traditional Chinese characters?").content)
```
* 基本問答-指定模型和創意性
temperature(創意):0~1
model_name(模型):[連結](https://openai.com/pricing)
```python=
from langchain_openai import ChatOpenAI
OPENAI_API_KEY="sk-YOUR API KEY"
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, temperature=0, model_name="gpt-3.5-turbo-0301")
print(llm.invoke("Can you read or write in Traditional Chinese characters?").content)
```
* 給定回答範例的問答
```python=
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
OPENAI_API_KEY="sk-YOUR API KEY"
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
prompt = ChatPromptTemplate.from_messages([
("system", "You are world class technical documentation writer."),
("user", "{input}")
])
messages = prompt.format_messages(input="Provide an python example code that classic snake game.")
print(llm.invoke(messages).content)
```
### 知識資料庫
* 網頁資料庫
```pip install beautifulsoup4```
```python=
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.document_loaders import WebBaseLoader
OPENAI_API_KEY="sk-YOUR API KEY"
llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
# 使用 WebBaseLoader 從指定的 URL 加載文檔
loader = WebBaseLoader("https://python.langchain.com/docs/get_started/installation")
docs = loader.load()
# 假設您有一個特定的問題想要回答
question = "How can I install langchain?"
# 構造輸入提示,包含從網頁加載的文檔和用戶問題
# 這裡假設 docs 是一個文本字符串或可直接轉換為文本的格式
prompt_text = f"Below is the information extracted from the langchain documentation:\n{docs}\n\nBased on this, {question}"
# 調用 Ollama 模型來生成回答
response = llm.invoke(prompt_text)
# 輸出模型的回答
print(response.content)
```
* 文件資料庫
```
pip install pypdf
pip install faiss-cpu
```
```PYTHON=
import os
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
OPENAI_API_KEY="sk-YOUR API KEY"
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY
# 使用 WebBaseLoader 從指定的 URL 加載文檔
loader = PyPDFLoader("Filtering disaster responses using crowdsourcing.pdf")
pages = loader.load_and_split()
# 假設您有一個特定的問題想要回答
question = "這篇論文的重點整理"
faiss_index = FAISS.from_documents(pages, OpenAIEmbeddings())
docs = faiss_index.similarity_search(question, k=2)
for doc in docs:
print(str(doc.metadata["page"]) + ":", doc.page_content[:300])
```
## Ollama-Llama 2(local)
安裝Ollama:https://ollama.com/download
下載模型(cmd):`ollama pull llama2`
![ollama](https://hackmd.io/_uploads/SkbPCYq0a.png)
### 準備程式碼
* 基本詢問
```python=
from langchain_community.llms import Ollama
llm = Ollama(model="llama2")
print(llm.invoke("Can you read or write in Traditional Chinese characters?"))
```
* 給定回答範例
```python=
from langchain_community.llms import Ollama
from langchain_core.prompts import ChatPromptTemplate
llm = Ollama(model="llama2")
prompt = ChatPromptTemplate.from_messages([
("system", "You are world class technical documentation writer."),
("user", "{input}")
])
messages = prompt.format_messages(input="Provide an python example code that classic snake game.")
print(llm.invoke(messages))
```
### 知識資料庫
* 網頁資料庫
```pip install beautifulsoup4```
```python=
from langchain_community.llms import Ollama
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.document_loaders import WebBaseLoader
# 初始化 Ollama 模型
llm = Ollama(model="llama2")
# 使用 WebBaseLoader 從指定的 URL 加載文檔
loader = WebBaseLoader("https://python.langchain.com/docs/get_started/installation")
docs = loader.load()
# 假設您有一個特定的問題想要回答
question = "How can I install langchain?"
# 構造輸入提示,包含從網頁加載的文檔和用戶問題
# 這裡假設 docs 是一個文本字符串或可直接轉換為文本的格式
prompt_text = f"Below is the information extracted from the langchain documentation:\n{docs}\n\nBased on this, {question}"
# 調用 Ollama 模型來生成回答
response = llm.invoke(prompt_text)
# 輸出模型的回答
print(response)
```
## OPENAI-ChatGPT貪吃蛇
```python=
import pygame
import time
import random
pygame.init()
# Constants
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
GRID_SIZE = 20
FPS = 15
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Initialize the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake Game')
clock = pygame.time.Clock()
# Snake class
class Snake:
def __init__(self):
self.length = 1
self.positions = [((SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2))]
# Initialize self.direction with a direction vector, not a pygame key
self.direction = random.choice([(0, -1), (0, 1), (-1, 0), (1, 0)]) # UP, DOWN, LEFT, RIGHT as vectors
self.color = GREEN
def get_head_position(self):
return self.positions[0]
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = (((cur[0] + (x * GRID_SIZE)) % SCREEN_WIDTH), (cur[1] + (y * GRID_SIZE)) % SCREEN_HEIGHT)
if len(self.positions) > 2 and new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [((SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2))]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT])
def draw(self, surface):
for p in self.positions:
pygame.draw.rect(surface, self.color, (p[0], p[1], GRID_SIZE, GRID_SIZE))
def handle_keys(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and self.direction != (0, 1):
self.direction = (0, -1) # UP
elif event.key == pygame.K_DOWN and self.direction != (0, -1):
self.direction = (0, 1) # DOWN
elif event.key == pygame.K_LEFT and self.direction != (1, 0):
self.direction = (-1, 0) # LEFT
elif event.key == pygame.K_RIGHT and self.direction != (-1, 0):
self.direction = (1, 0) # RIGHT
# Food class
class Food:
def __init__(self):
self.position = (0, 0)
self.color = RED
self.randomize_position()
def randomize_position(self):
self.position = (random.randint(0, (SCREEN_WIDTH // GRID_SIZE) - 1) * GRID_SIZE, random.randint(0, (SCREEN_HEIGHT
// GRID_SIZE) - 1) * GRID_SIZE)
def draw(self, surface):
pygame.draw.rect(surface, self.color, (self.position[0], self.position[1], GRID_SIZE, GRID_SIZE))
# Main game loop
snake = Snake()
food = Food()
while True:
screen.fill(BLACK)
snake.handle_keys()
snake.move()
if snake.get_head_position() == food.position:
snake.length += 1
food.randomize_position()
snake.draw(screen)
food.draw(screen)
pygame.display.update()
clock.tick(FPS)
```