Step‑by‑Step Guide to Building a Name‑Generator with LangChain and OpenAI

This tutorial walks through installing LangChain, creating an LLM with either self‑hosted or third‑party models, designing custom prompt templates, configuring output parsers for structured results, and running a complete Python example that generates culturally specific names using OpenAI's API.

JavaEdge
JavaEdge
JavaEdge
Step‑by‑Step Guide to Building a Name‑Generator with LangChain and OpenAI

1. Install LangChain

pip install --upgrade langchain==0.0.279 -i https://pypi.org/simple

LangChain provides a unified interface for large language models (LLMs) and supports prompt templating, output parsing, and chain composition.

2. Create an LLM

Self‑hosted platform + open‑source model (requires substantial GPU resources and your own training data).

Third‑party model APIs such as OpenAI, Baidu Wenxin, Alibaba Tongyi, etc. (no GPU needed).

Example goal: let the LLM generate Chinese‑style names. The basic LangChain call is llm.predict(prompt). The temperature parameter controls creativity.

3. Custom Prompt Templates

Template the context of a question.

Allow parameter injection.

Example: generate American‑style names.

Usage

Import the prompt utilities:

from langchain.prompts import PromptTemplate

4. Output Parser

Format LLM results into JSON or other structured data.

Useful for returning arrays instead of plain text.

Example: ask the model to return four Chinese names as an array.

from langchain.schema import BaseOutputParser

class CommaSeparatedListOutputParser(BaseOutputParser):
    """Parse the output of an LLM call to a comma‑separated list."""
    def parse(self, text: str):
        """Parse the output of an LLM call."""
        return text.strip().split(", ")

CommaSeparatedListOutputParser().parse("hi, bye")
['hi', 'bye']

5. Run the Full Example

pip install openai==v0.28.1 -i https://pypi.org/simple

Set OpenAI credentials

import os
os.environ["OPENAI_KEY"] = "sk-ss"
# For proxy access
os.environ["OPENAI_API_BASE"] = "https://ai-yyds.com/v1"

Verify installations

! pip show langchain
! pip show openai

Use OpenAI SDK directly

import openai, os
openai.api_base = os.getenv("OPENAI_API_BASE")
openai.api_key = os.getenv("OPENAI_KEY")
messages = [{"role": "user", "content": "介绍下你自己"}]
res = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=messages, stream=False)
print(res['choices'][0]['message']['content'])

Call the model through LangChain

from langchain.llms import OpenAI
import os
api_base = os.getenv("OPENAI_API_BASE")
api_key = os.getenv("OPENAI_KEY")
llm = OpenAI(model="gpt-3.5-turbo-instruct", temperature=0, openai_api_key=api_key, openai_api_base=api_base)
llm.predict("介绍下你自己")

Name‑generator with a custom prompt and parser

from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.schema import BaseOutputParser
import os

api_base = os.getenv("OPENAI_API_BASE")
api_key = os.getenv("OPENAI_KEY")
llm = OpenAI(model="gpt-3.5-turbo-instruct", temperature=0, openai_api_key=api_key, openai_api_base=api_base)

prompt = PromptTemplate.from_template(
    "你是一个起名大师,请模仿示例起3个{county}名字,示例:男孩常用名{boy},女孩常用名{girl}。请返回以逗号分隔的列表。"
)
message = prompt.format(county="美国男孩", boy="sam", girl="lucy")
print(message)
result = llm.predict(message)
class CommaSeparatedListOutputParser(BaseOutputParser):
    def parse(self, text: str):
        return text.strip().split(",")
print(CommaSeparatedListOutputParser().parse(result))

Typical output:

'

男孩: 龙飞、铁柱、小虎
女孩: 玉兰、梅香、小红梅'

Conclusion

The guide demonstrates how to set up LangChain, choose an LLM source, craft reusable prompt templates, and convert free‑form text into structured data with a custom output parser, enabling practical applications such as culturally aware name generation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonLLMPrompt EngineeringLangChainOpenAIoutput-parser
JavaEdge
Written by

JavaEdge

First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.