Haz tu propio ChatGPT

11 de febrero de 20235 lectura mínima

Recomendación: use NSDT Scene Designer para crear rápidamente escenas 3D.

Se sabe que ChatGPT es capaz de realizar hazañas impresionantes en este momento. Es probable que muchas personas tengan ideas para usar esta técnica en sus propios proyectos. Sin embargo, cabe señalar que ChatGPT actualmente no tiene una API oficial. El uso de API no oficiales puede causar dificultades.

Actualmente, el token de acceso y el token de cloudflare deben obtenerse manualmente para usar la API. Además, estos tokens deben cambiarse manualmente cada dos horas.

1, Chat GPT

ChatGPT utilizó el modelo GPT-3 en su diseño y desarrolló un nuevo modelo basado en él. Por lo tanto, la salida del nuevo modelo tiende a ser similar a GPT-3. Al momento de escribir este artículo, el modelo text-davinci-002-render se usa en ChatGPT para el nuevo modelo, pero actualmente no está disponible para el público.

Si bien ChatGPT puede no ser innovador, ofrece una nueva interfaz que aprovecha la tecnología existente. Utilizando sugerencias poderosas y ventanas de memoria eficientes. Por lo tanto, en lugar de piratear la API no oficial de ChatGPT, podemos replicar su funcionalidad utilizando el enfoque LLM Chain.

2, cadena de idioma

Langchain es un nuevo paquete de Python que proporciona una interfaz estándar para cadenas LLM, amplias integraciones con otras herramientas y cadenas de extremo a extremo para aplicaciones comunes.

LangChain está diseñado para ayudar en cuatro áreas principales, enumeradas aquí en orden de complejidad creciente:

  • LLM y consejos

  • cadena

  • interino

  • memoria

Obtenga más información sobre langchain en la documentación oficial aquí .

3. Instalación

Para usar el paquete langchain, puede instalarlo desde pypi.

pip install langchain

Para obtener las últimas actualizaciones de langchain, puede utilizar este método de instalación.

pip install "git+https://github.com/hwchase17/langchain.git"

Lea más sobre las opciones de instalación aquí .

4. Proyecto de ejemplo

Hay muchas cosas que puede hacer con ChatGPT, una de las cosas divertidas es crear preguntas y respuestas para las tareas de los estudiantes. Así que esta vez vamos a crear una versión AI de Brainly.

Esto es lo que obtendremos de ChatGPT.

Aquí están los consejos de langchain:

from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.chains import SimpleSequentialChain

llm = OpenAI(temperature=.7)
template = """You are a teacher in physics for High School student. Given the text of question, it is your job to write a answer that question with example.
Question: {text}
Answer:
"""
prompt_template = PromptTemplate(input_variables=["text"], template=template)
answer_chain = LLMChain(llm=llm, prompt=prompt_template)
answer = answer_chain.run("What is the formula for Gravitational Potential Energy (GPE)?")
print(answer)

Aquí están los resultados que obtenemos de GPT-3 usando langchain:

The formula for Gravitational Potential Energy (GPE) is GPE = mgh, where m is the mass of an object, g is the acceleration due to gravity, and h is the height of the object. For example, if an object with a mass of 10 kg is at a height of 5 meters, then the GPE would be GPE = 10 x 9.8 x 5 = 490 Joules.

5. Chatbots

Si necesita crear chatbots como AI, puede usar la memoria de langchain. Aquí hay un ejemplo de cómo hacerlo.

from langchain.chains.conversation.memory import ConversationBufferMemory
from langchain import OpenAI, LLMChain, PromptTemplate

template = """You are a teacher in physics for High School student. Given the text of question, it is your job to write a answer that question with example.
{chat_history}
Human: {question}
AI:
"""
prompt_template = PromptTemplate(input_variables=["chat_history","question"], template=template)
memory = ConversationBufferMemory(memory_key="chat_history")

llm_chain = LLMChain(
    llm=OpenAI(),
    prompt=prompt_template,
    verbose=True,
    memory=memory,
)

llm_chain.predict(question="What is the formula for Gravitational Potential Energy (GPE)?")

result = llm_chain.predict(question="What is Joules?")
print(result)

El resultado será algo como esto:

$ python3 memory.py

> Entering new LLMChain chain...
Prompt after formatting:
You are a teacher in physics for High School student. Given the text of question, it is your job to write a answer that question with example.

Human: What is the formula for Gravitational Potential Energy (GPE)?
AI:

> Finished LLMChain chain.

> Entering new LLMChain chain...
Prompt after formatting:
You are a teacher in physics for High School student. Given the text of question, it is your job to write a answer that question with example.

Human: What is the formula for Gravitational Potential Energy (GPE)?
AI: 
The formula for Gravitational Potential Energy (GPE) is GPE = mgh, where m is the mass of the object, g is the acceleration due to gravity, and h is the height of the object.

For example, if an object has a mass of 10 kg and is at a height of 5 meters, then the gravitational potential energy of the object is GPE = 10 kg x 9.8 m/s2 x 5 m = 490 Joules.
Human: What is Joules?
AI:

> Finished LLMChain chain.
Joules (J) is the SI unit of energy. It is defined as the amount of energy required to move an object of one kilogram at a speed of one meter per second. It is also equal to the work done when a force of one Newton is applied to an object and moved one meter in the direction of the force.

6. Conclusión

ChatGPT es un chatbot basado en GPT-3, actualmente no hay una API oficial. Con LangChain, los desarrolladores pueden replicar la funcionalidad de ChatGPT, como crear chatbots o sistemas de respuesta a preguntas, sin usar API no oficiales.

LangChain proporciona interfaces estándar, numerosas integraciones y cadenas de extremo a extremo para aplicaciones comunes. Se puede instalar desde pypi y se puede encontrar más información en la documentación oficial.

Supongo que te gusta

Origin blog.csdn.net/tianqiquan/article/details/129018505
Recomendado
Clasificación