@Renat871

Как задать роль chatgpt langchain?

мне нужно подключить шаблон к chatgpt чтобы он соответствовал от имени прописанного в этом шаблоне и от его имени. но я никак не могу подключить его к langchain. к openai это делается вот так:
prefix_messages = {'role': 'system', 'content': template}

и подключается к openai.Competition.create, а через langchain я как только не пробовал – ничего не помогает.

вот мой код:
from langchain.agents import Tool, load_tools, initialize_agent, AgentType
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
from coinmarketcap_search import CryptocurrencySearchAPIWrapper

import config
llm = ChatOpenAI(
    temperature=1,
    streaming=False,
    max_tokens=900,
    openai_api_key = config.openai_api_key
)
tools = load_tools(["llm-math"], llm=llm)
crypto_search = CryptocurrencySearchAPIWrapper(coinmarketcap_api_key="65f06ec3-a650-4480-8c87-dce7396fb8db")
tools.append(Tool(
    name="Crypto Currency Search",
    func=crypto_search.run,
    description="Use this tool when you need to answer questions about Cryptocurrency prices or altcoins prices "
                "Input should be the Cryptocurrency coin name only or the ticker symbol"
))

memory = ConversationBufferMemory(memory_key="chat_history")
chain = initialize_agent(
    tools, llm,
    # agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
    verbose=False,
    memory=memory,
    agent_kwargs={
        'prefix': config.system,
    }
)

def search_by_prompt(prompt: str) -> str:
    try:
        response = chain.run(prompt)
    except Exception as e:
        response = str(e)
        suffix = "Could not parse LLM output: `"
        if response.startswith(suffix):
            response = response.removeprefix(suffix).removesuffix("`")

    return response

print(search_by_prompt('what is price of btc'))

когда спрашиваю "кто тьі?" - отвечает по шаблону, если о цене криптьі - то "Do I need to use a tool? No"
  • Вопрос задан
  • 120 просмотров
Пригласить эксперта
Ответы на вопрос 1
1) Для такого вида запросов верни agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION. в initialize_agent
2) Я так и не смог найти код CryptocurrencySearchAPIWrapper чтобы проверить работу и как там написан tool. Напиши где его взять - я может и помогу.
3) Обновись до последней версии Langhain - была там беда с интерпритацией (запуском задачи) из промпта.

Вот тебе рабочий пример, что тул заходит в функцию

from langchain.agents import Tool, load_tools, initialize_agent, AgentType
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
# from coinmarketcap_search import CryptocurrencySearchAPIWrapper


llm = ChatOpenAI(
    temperature=1,
    streaming=False,
    max_tokens=900,
)
tools = load_tools(["llm-math"], llm=llm)


def crypto_search(query):
  print('in tool')
  return 42


tools.append(Tool.from_function(
    name="Crypto Currency Search",
    func=crypto_search,
    description="Use this tool when you need to answer questions about Cryptocurrency prices or altcoins prices "
                "Input should be the Cryptocurrency coin name only or the ticker symbol"
))

memory = ConversationBufferMemory(memory_key="chat_history")
chain = initialize_agent(
    tools, llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    #agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,
    verbose=True,
    memory=memory
)

def search_by_prompt(prompt: str) -> str:
    try:
        response = chain.run(prompt)
    except Exception as e:
        response = str(e)
        suffix = "Could not parse LLM output: `"
        if response.startswith(suffix):
            response = response.removeprefix(suffix).removesuffix("`")

    return response

print(search_by_prompt('what is price of btc'))


Вывод будет таким:

> Entering new AgentExecutor chain...
I should use the Crypto Currency Search tool to find the price of BTC.
Action: Crypto Currency Search
Action Input: BTCin tool

Observation: 42
Thought:I now know the price of BTC.
Final Answer: The price of BTC is 42.

> Finished chain.
The price of BTC is 42.


Так как на руках у меня нет кода CryptocurrencySearchAPIWrapper - не подскажу что там.

Теперь просто нужно тебе разобраться с недрами CryptocurrencySearchAPIWrapper.run. внути по идее из запроса тебе нужно понять запрашиваемую монетку и зарядить запрос в Api. Далее вернуть в результат из тула. Дальше GPT сам красоту делает.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
SM Lab Москва
До 225 000 ₽
Real Deal Санкт-Петербург
от 300 000 ₽
Real Deal Санкт-Петербург
от 250 000 ₽
01 мая 2024, в 11:20
5000 руб./за проект
01 мая 2024, в 10:55
3000 руб./за проект